SPB Git

Repository Public

CommandCenterIndex.swift 13.2 KB 216 lines swift

1//2//  SP Chat iOS3//  File: SPChat-iOS/Features/CommandCenter/CommandCenterIndex.swift4//  Description: Pure index of the AI Command Center — builds the commands from the account's data (conversations,5//               models, projects, prompts, tools) and ranks them against what the owner types.6//7//  Author: Simon-Pierre Boucher8//  Contact: contact@spboucher.ai9//1011import Foundation1213enum CommandSection: Int, CaseIterable, Sendable, Identifiable {14    case actions, conversations, models, projects, prompts, settings15    var id: Int { rawValue }16    var title: String {17        switch self {18        case .actions: String(localized: "Actions"); case .conversations: String(localized: "Conversations"); case .models: String(localized: "Modèles")19        case .projects: String(localized: "Projets"); case .prompts: String(localized: "Prompts"); case .settings: String(localized: "Réglages")20        }21    }22}2324/// What a command does. Executed by `CommandCenterView` against the real stores; nothing here has side effects.25enum CommandAction: Equatable, Sendable {26    case newConversation27    case searchMessages28    case openConversation(String)29    case selectModel(String)30    case routing(String)31    case toggleWebSearch32    case toggleTools33    case toggleTool(String)34    case arena35    /// A space presented as a sheet: explorer · constellation · prompts · projects · research · images · settings.36    case space(String)37    /// A contextual panel of the conversation on screen: timeline · branches · context · lens · models.38    case panel(String)39    case newProject40    case newConversationInProject(String)41    case insertPrompt(String)42    case theme(String)43    case toggleFollowUps44}4546struct CommandItem: Identifiable, Equatable, Sendable {47    var id: String48    var section: CommandSection49    var title: String50    var subtitle: String?51    var symbol: String52    /// Model commands show the maker's mark instead of a symbol.53    var logo: String?54    var creatorName: String?55    var route: String?56    /// A switch: true / false = its current state (shown as a trailing check), nil = not a switch.57    var isOn: Bool?58    /// Extra words the command answers to (never shown).59    var keywords: String = ""60    var action: CommandAction61}6263/// Everything the index reads, as plain values (the view fills it from the environment; tests fill it by hand).64struct CommandCenterInput: Sendable {65    var conversations: [Conversation] = []66    var models: [AIModel] = []67    /// Ids shown first when nothing is typed (dock, favourites, recents), in order.68    var preferredModelIds: [String] = []69    var currentModelId: String?70    var projects: [Project] = []71    var prompts: [SavedPrompt] = []72    var tools: [ServerTool] = []73    var webSearch = false74    var toolsEnabled = true75    var disabledTools: Set<String> = []76    var followUps = true77    var theme = "system"78    /// A conversation with messages is on screen: its panels can be opened.79    var hasOpenConversation = false80    var currentConversationId: String?81}8283struct CommandCenterIndex: Sendable {84    let items: [CommandItem]85    private let haystacks: [String]8687    init(_ input: CommandCenterInput) {88        var out: [CommandItem] = []89        func add(_ id: String, _ section: CommandSection, _ title: String, _ symbol: String, _ action: CommandAction, subtitle: String? = nil, isOn: Bool? = nil, keywords: String = "") {90            out.append(CommandItem(id: id, section: section, title: title, subtitle: subtitle, symbol: symbol, isOn: isOn, keywords: keywords, action: action))91        }9293        // actions94        add("a.new", .actions, String(localized: "Nouvelle conversation"), "square.and.pencil", .newConversation, keywords: "new chat nouveau")95        add("a.search", .actions, String(localized: "Rechercher dans les messages"), "magnifyingglass", .searchMessages, keywords: "search find trouver")96        add("a.arena", .actions, String(localized: "Démarrer une Arène"), "square.split.2x1", .arena, subtitle: String(localized: "Le même prompt à plusieurs modèles"), keywords: "comparer compare arena")97        add("a.web", .actions, String(localized: "Recherche web"), "globe", .toggleWebSearch, subtitle: String(localized: "Le modèle cherche avant de répondre"), isOn: input.webSearch, keywords: "web search tavily internet")98        add("a.tools", .actions, String(localized: "Outils"), "wrench.and.screwdriver", .toggleTools, subtitle: String(localized: "Tous les outils du serveur"), isOn: input.toolsEnabled, keywords: "tools outils")99        if input.toolsEnabled {100            for t in input.tools {101                add("a.tool.\(t.name)", .actions, String(localized: "Outil · \(t.label)"), t.symbol, .toggleTool(t.name), isOn: !input.disabledTools.contains(t.name), keywords: "\(t.name) tool outil")102            }103        }104        add("a.models", .actions, String(localized: "Changer de modèle…"), "square.stack.3d.up", .panel("models"), keywords: "model modèle switch")105        if input.hasOpenConversation {106            add("a.timeline", .actions, String(localized: "Chronologie et relecture"), "clock.arrow.circlepath", .panel("timeline"), subtitle: String(localized: "Conversation en cours"), keywords: "timeline replay historique")107            add("a.branches", .actions, String(localized: "Branches"), "arrow.triangle.branch", .panel("branches"), subtitle: String(localized: "Conversation en cours"), keywords: "tree arbre fork bifurquer")108            add("a.context", .actions, String(localized: "Inspecteur de contexte"), "gauge.with.dots.needle.33percent", .panel("context"), subtitle: String(localized: "Conversation en cours"), keywords: "context tokens jetons")109            add("a.lens", .actions, String(localized: "Lentilles de la dernière réponse"), "camera.filters", .panel("lens"), subtitle: String(localized: "Conversation en cours"), keywords: "lens résumé vérifier summary verify")110        }111        add("a.explorer", .actions, String(localized: "Explorateur de modèles"), "square.grid.2x2", .space("explorer"), keywords: "openrouter catalogue explorer")112        add("a.constellation", .actions, String(localized: "Constellation"), "point.3.connected.trianglepath.dotted", .space("constellation"), keywords: "graphe graph carte")113        add("a.research", .actions, String(localized: "Recherche approfondie"), "doc.text.magnifyingglass", .space("research"), keywords: "deep research rapport")114        add("a.images", .actions, String(localized: "Studio d’images"), "photo.on.rectangle.angled", .space("images"), keywords: "image studio générer")115        add("a.prompts", .actions, String(localized: "Bibliothèque de prompts"), "text.book.closed", .space("prompts"), keywords: "prompts library")116117        // conversations (the list is already ordered: pinned, then most recent)118        for c in input.conversations where c.id != input.currentConversationId {119            add("c.\(c.id)", .conversations, c.title, c.pinned ? "pin" : "bubble.left", .openConversation(c.id), subtitle: c.projectName, keywords: c.branchLabel ?? "")120        }121122        // models: the owner's dock / favourites / recents first, then the rest of the catalogue123        let byId = Dictionary(input.models.map { ($0.id, $0) }, uniquingKeysWith: { a, _ in a })124        var seen = Set<String>()125        let ordered = input.preferredModelIds.compactMap { byId[$0] }.filter { seen.insert($0.id).inserted } + input.models.filter { !seen.contains($0.id) }126        for m in ordered {127            var item = CommandItem(id: "m.\(m.id)", section: .models, title: m.displayName, subtitle: m.isCatalogOnly ? String(localized: "catalogue · non testé") : nil, symbol: "cpu",128                                   isOn: m.id == input.currentModelId ? true : nil, keywords: "\(m.id) \(m.creatorName) \(m.creator) \(m.route)", action: .selectModel(m.id))129            item.logo = m.logo; item.creatorName = m.creatorName; item.route = m.route130            out.append(item)131        }132        for (mode, title) in [("auto", String(localized: "Routage automatique")), ("fast", String(localized: "Routage rapide")), ("quality", String(localized: "Routage qualité")), ("economy", String(localized: "Routage économie"))] {133            add("m.route.\(mode)", .models, title, "sparkles", .routing(mode), subtitle: String(localized: "Le serveur choisit un modèle vérifié"), keywords: "router routing \(mode)")134        }135136        // projects137        add("p.new", .projects, String(localized: "Nouveau projet…"), "folder.badge.plus", .newProject, keywords: "project créer create")138        add("p.all", .projects, String(localized: "Tous les projets"), "folder", .space("projects"), keywords: "projects gérer instructions")139        for p in input.projects {140            add("p.\(p.id)", .projects, p.name, "folder", .newConversationInProject(p.id), subtitle: String(localized: "Nouvelle conversation dans ce projet"), keywords: p.description ?? "")141        }142143        // prompts (favourites first)144        for p in input.prompts.filter(\.favorite) + input.prompts.filter({ !$0.favorite }) {145            add("pr.\(p.id)", .prompts, p.title, p.favorite ? "star" : "text.quote", .insertPrompt(p.id), subtitle: String(p.body.prefix(80)), keywords: p.tags.joined(separator: " "))146        }147148        // settings149        add("s.settings", .settings, String(localized: "Réglages"), "gearshape", .space("settings"), keywords: "settings préférences fournisseurs clés sécurité")150        add("s.followups", .settings, String(localized: "Suggestions de suite"), "arrow.turn.down.right", .toggleFollowUps, subtitle: String(localized: "Réglage du compte, partagé avec le web et le Mac"), isOn: input.followUps, keywords: "follow-ups followups")151        for (t, title, symbol) in [("system", String(localized: "Thème : système"), "circle.lefthalf.filled"), ("light", String(localized: "Thème : clair"), "sun.max"), ("dark", String(localized: "Thème : sombre"), "moon")] {152            add("s.theme.\(t)", .settings, title, symbol, .theme(t), isOn: input.theme == t ? true : nil, keywords: "theme apparence appearance \(t)")153        }154155        items = out156        haystacks = out.map { Self.fold("\($0.title) \($0.subtitle ?? "") \($0.keywords)") }157    }158159    /// Lowercased, accents removed: « modele » finds « Modèle ».160    static func fold(_ s: String) -> String { s.folding(options: [.diacriticInsensitive, .caseInsensitive], locale: nil).lowercased() }161162    struct Group: Identifiable, Equatable, Sendable { var section: CommandSection; var items: [CommandItem]; var id: Int { section.rawValue } }163164    /// How many rows a section shows when nothing is typed / while searching.165    static func limit(_ s: CommandSection, searching: Bool) -> Int {166        if searching { return s == .conversations || s == .models ? 8 : 6 }167        switch s { case .actions: return 7; case .conversations: return 5; case .models: return 5; case .projects: return 4; case .prompts: return 4; case .settings: return 2 }168    }169170    /// Score of an item for the folded query tokens, nil when a token is missing. Title matches outrank keyword171    /// matches; a prefix outranks a word start, which outranks a match inside a word.172    private func score(_ index: Int, tokens: [Substring], whole: String) -> Int? {173        let hay = haystacks[index]174        let title = Self.fold(items[index].title)175        var total = 0176        for t in tokens {177            guard hay.contains(t) else { return nil }178            if title.hasPrefix(t) { total += 60 }179            else if title.split(whereSeparator: { !$0.isLetter && !$0.isNumber }).contains(where: { $0.hasPrefix(t) }) { total += 40 }180            else if title.contains(t) { total += 20 }181            else { total += 5 }182        }183        if title == whole { total += 200 } else if title.hasPrefix(whole) { total += 80 }184        return total185    }186187    /// Sections in their fixed order, each with its best matches (original order kept between equal scores, so the188    /// most recent conversation and the preferred models stay first). When the query matches, the section that holds189    /// the best item overall comes first: Return runs what the owner most likely meant.190    func results(for query: String) -> [Group] {191        let whole = Self.fold(query.trimmingCharacters(in: .whitespacesAndNewlines))192        let tokens = whole.split(separator: " ")193        var groups: [Group] = []194        var best: [CommandSection: Int] = [:]195        for section in CommandSection.allCases {196            let indices = items.indices.filter { items[$0].section == section }197            if tokens.isEmpty {198                let list = indices.prefix(Self.limit(section, searching: false)).map { items[$0] }199                if !list.isEmpty { groups.append(Group(section: section, items: Array(list))) }200            } else {201                let scored = indices.compactMap { i in score(i, tokens: tokens, whole: whole).map { (i, $0) } }202                    .sorted { $0.1 != $1.1 ? $0.1 > $1.1 : $0.0 < $1.0 }203                    .prefix(Self.limit(section, searching: true))204                if let top = scored.first { best[section] = top.1; groups.append(Group(section: section, items: scored.map { items[$0.0] })) }205            }206        }207        if !tokens.isEmpty {208            groups.sort { a, b in209                let x = best[a.section] ?? 0, y = best[b.section] ?? 0210                return x != y ? x > y : a.section.rawValue < b.section.rawValue211            }212        }213        return groups214    }215}216
Files main
Menu

Theme