ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.
Python astracloudflarecontrol-panelcyberpaneldnsfablehosting-control-panelhosting-panelkimi-k3server-managementserverkitubuntu-web-panelwebserver
feat(palette): omnisearch core — providers, ranking, VS Code keys
Juan Denis3e0fbd2f81f7
diff --git a/frontend/src/components/CommandPalette.jsx b/frontend/src/components/CommandPalette.jsxindex 6695b8cf..5edf4217 100644--- a/frontend/src/components/CommandPalette.jsx+++ b/frontend/src/components/CommandPalette.jsx@@ -1,5 +1,9 @@import { useState, useEffect, useCallback, useMemo } from 'react';import { useNavigate } from 'react-router-dom';+import {+ History, SlidersHorizontal, LayoutGrid, Zap, Server, Globe,+ Database, Boxes, Puzzle, BookOpen, KeyRound, Clock, ExternalLink,+} from 'lucide-react';import api from '../services/api';import {CommandDialog,@@ -10,175 +14,322 @@ import {CommandItem,} from '@/components/ui/command';import { useContributions } from '../plugins/contributions';+import { useAuth } from '../contexts/AuthContext';+import { useTheme } from '../contexts/ThemeContext';+import usePaletteAuthz from '../hooks/usePaletteAuthz';+import { PALETTE_PAGES } from '../data/palettePages';+import { SETTINGS_INDEX } from '../data/settingsIndex';+import { COMMAND_ACTIONS } from '../data/commandActions';+import { DOCS_LINKS } from '../utils/docsLinks';+import { scoreItem } from '../utils/paletteScore';+import { frecencyScore, recordUse, recentIds } from '../utils/paletteFrecency';-const STATIC_PAGES = [- { label: 'Services', path: '/services', category: 'Pages', keywords: 'apps containers' },- { label: 'Docker', path: '/docker', category: 'Pages', keywords: 'containers images' },- { label: 'Databases', path: '/databases', category: 'Pages', keywords: 'mysql postgres sql' },- { label: 'Domains', path: '/domains', category: 'Pages', keywords: 'dns nginx records nameserver zones' },- { label: 'SSL Certificates', path: '/ssl', category: 'Pages', keywords: 'https tls' },- { label: 'Templates', path: '/templates', category: 'Pages', keywords: 'deploy one-click' },- { label: 'Deployments', path: '/deployments', category: 'Pages', keywords: 'deploy jobs status logs' },- // WordPress palette entries are contributed by the serverkit-wordpress extension.- { label: 'Files', path: '/files', category: 'Pages', keywords: 'file manager explorer' },- // The FTP Server palette entry is contributed by the serverkit-ftp extension.- { label: 'Observability', path: '/monitoring', category: 'Pages', keywords: 'metrics uptime monitoring alerts' },- { label: 'Backups', path: '/backups', category: 'Pages', keywords: 'snapshots restore' },- { label: 'Cron Jobs', path: '/cron', category: 'Pages', keywords: 'schedule tasks' },- { label: 'Security', path: '/security', category: 'Pages', keywords: 'firewall fail2ban' },- { label: 'Terminal', path: '/terminal', category: 'Pages', keywords: 'shell ssh console' },- { label: 'Servers', path: '/servers', category: 'Pages', keywords: 'fleet agents' },- { label: 'Fleet Monitor', path: '/fleet-monitor', category: 'Pages', keywords: 'agents status' },- // Status Pages / Cloud Provision / Remote Access palette entries are- // contributed by the serverkit-status / serverkit-cloud-provision /- // serverkit-remote-access extensions.- { label: 'Marketplace', path: '/marketplace', category: 'Pages', keywords: 'extensions plugins' },- { label: 'Import a Site', path: '/imports', category: 'Pages', keywords: 'import migrate cpanel directadmin hestia backup adoption move existing' },- { label: 'Downloads', path: '/downloads', category: 'Pages', keywords: 'agent installer' },- { label: 'Projects', path: '/projects', category: 'Pages', keywords: 'organization group' },- { label: 'Shared Variables', path: '/shared-variables', category: 'Pages', keywords: 'env secrets shared' },- { label: 'Workspaces', path: '/workspaces', category: 'Pages', keywords: 'organization team' },- // GPU Monitor + Workflow Builder command-palette entries are contributed by- // the serverkit-gpu / serverkit-workflows builtin extensions.- { label: 'Queue', path: '/queue', category: 'Pages', keywords: 'bus operations tasks' },- { label: 'Jobs', path: '/jobs', category: 'Pages', keywords: 'scheduler background work' },- { label: 'Events', path: '/telemetry', category: 'Pages', keywords: 'telemetry metrics observability system events' },- { label: 'Vaults', path: '/vaults', category: 'Pages', keywords: 'secrets tokens credentials vault' },- { label: 'Webhooks', path: '/webhooks', category: 'Pages', keywords: 'webhook receive forward delivery' },- { label: 'Settings', path: '/settings', category: 'Settings', keywords: 'profile preferences' },- { label: 'Settings: Users', path: '/settings/users', category: 'Settings', keywords: 'accounts team' },- { label: 'Settings: API Keys', path: '/settings/api', category: 'Settings', keywords: 'tokens access' },- { label: 'Settings: SSO', path: '/settings/sso', category: 'Settings', keywords: 'oauth saml login' },- { label: 'Settings: Appearance', path: '/settings/appearance', category: 'Settings', keywords: 'theme dark light' },- { label: 'Settings: Notifications', path: '/settings/notifications', category: 'Settings', keywords: 'alerts email slack' },- { label: 'Settings: System', path: '/settings/system', category: 'Settings', keywords: 'server config' },+// Group order in the list, plus a per-category icon and a scoring weight so the+// headline categories (Settings, Pages, Actions) outrank raw entity hits on ties.+const GROUP_ORDER = [+ 'Recently used', 'Settings', 'Pages', 'Actions', 'Services', 'Servers',+ 'Domains', 'Databases', 'Sites', 'Cron Jobs', 'Vaults', 'Extensions', 'Docs',];+const CATEGORY_ICONS = {+ 'Recently used': History,+ Settings: SlidersHorizontal,+ Pages: LayoutGrid,+ Actions: Zap,+ Services: Boxes,+ Servers: Server,+ Domains: Globe,+ Databases: Database,+ Sites: Globe,+ 'Cron Jobs': Clock,+ Vaults: KeyRound,+ Extensions: Puzzle,+ Docs: BookOpen,+};+const CATEGORY_WEIGHT = {+ Settings: 6, Pages: 4, Actions: 4, Services: 2, Servers: 2, Domains: 2,+ Databases: 2, Sites: 2, 'Cron Jobs': 1, Vaults: 1, Extensions: 1, Docs: 0,+};+// Backend /search row `type` -> palette category.+const ENTITY_CATEGORY = {+ service: 'Services', app: 'Services', server: 'Servers', domain: 'Domains',+ database: 'Databases', site: 'Sites', cron: 'Cron Jobs',+ extension: 'Extensions', plugin: 'Extensions', vault: 'Vaults',+};-function fuzzyMatch(text, query) {- const lower = text.toLowerCase();- const q = query.toLowerCase();- const idx = lower.indexOf(q);- if (idx === -1) return -1;- return idx === 0 ? 2 : 1;-}+// Docs entries derived from the single docsLinks map (plan 40). Hidden under+// White Label since they point at the public serverkit.ai docs.+const DOCS_ENTRIES = [+ { key: 'deploySources', label: 'Docs: Deploy sources', keywords: 'deploy source repo git' },+ { key: 'manifest', label: 'Docs: serverkit.yaml manifest', keywords: 'manifest yaml declarative' },+ { key: 'extensions', label: 'Docs: Extensions', keywords: 'extension plugin' },+ { key: 'extensionsInstalling', label: 'Docs: Installing extensions', keywords: 'install extension' },+ { key: 'extensionsBuilding', label: 'Docs: Building extensions', keywords: 'build extension develop sdk' },+ { key: 'extensionsPublishing', label: 'Docs: Publishing extensions', keywords: 'publish extension registry' },+ { key: 'extensionsSecurity', label: 'Docs: Extension security', keywords: 'extension security permissions' },+];++const PER_GROUP_CAP = 6;+const OVERALL_CAP = 30;-function scoreItem(item, query) {- const labelScore = fuzzyMatch(item.label, query);- if (labelScore > 0) return labelScore + 1;- const kwScore = fuzzyMatch(item.keywords || '', query);- if (kwScore > 0) return kwScore;- const pathScore = fuzzyMatch(item.path, query);- if (pathScore > 0) return pathScore;- return -1;+// Cap results per category and overall, preserving the incoming (sorted) order.+function capGroups(items, perGroup = PER_GROUP_CAP, overall = OVERALL_CAP) {+ const counts = {};+ const out = [];+ for (const it of items) {+ const c = counts[it.category] || 0;+ if (c >= perGroup) continue;+ counts[it.category] = c + 1;+ out.push(it);+ if (out.length >= overall) break;+ }+ return out;}const CommandPalette = ({ open, onClose }) => {const [query, setQuery] = useState('');- const [dynamicItems, setDynamicItems] = useState([]);+ const [entityItems, setEntityItems] = useState([]);const navigate = useNavigate();const { command_palette: pluginPaletteItems } = useContributions();+ const { logout } = useAuth();+ const { resolvedTheme, setTheme, whiteLabel } = useTheme();+ const { allowItem } = usePaletteAuthz();- // Fetch dynamic items (services/containers + servers) when opened- useEffect(() => {- if (!open) return;- setQuery('');+ // Prefix modes: `>` = actions only, `?` = docs only, bare = everything.+ const { mode, term } = useMemo(() => {+ if (query.startsWith('>')) return { mode: 'actions', term: query.slice(1).trimStart() };+ if (query.startsWith('?')) return { mode: 'docs', term: query.slice(1).trimStart() };+ return { mode: 'all', term: query };+ }, [query]);- let cancelled = false;- async function fetchDynamic() {- const items = [];- try {- const containers = await api.getContainers();- if (!cancelled && Array.isArray(containers)) {- containers.forEach(c => {- items.push({- label: c.name || c.Names?.[0]?.replace(/^\//, ''),- path: `/docker`,- category: 'Containers',- keywords: `${c.Image || ''} ${c.State || ''}`,- });- });- }- } catch (_e) {} // eslint-disable-line no-empty- try {- const serverData = await api.getServers();- const servers = serverData?.servers || serverData || [];- if (!cancelled && Array.isArray(servers)) {- servers.forEach(s => {- items.push({- label: s.name || s.hostname,- path: `/servers/${s.id}`,- category: 'Servers',- keywords: `${s.hostname || ''} ${s.ip_address || ''}`,- });- });- }- } catch (_e) {} // eslint-disable-line no-empty- if (!cancelled) setDynamicItems(items);- }- fetchDynamic();- return () => { cancelled = true; };+ // Reset transient state each time the palette opens/closes.+ useEffect(() => {+ if (open) setQuery('');+ else setEntityItems([]);}, [open]);- const allItems = useMemo(() => {- const fromPlugins = (pluginPaletteItems || [])+ // --- Sync providers ------------------------------------------------------+ const pageItems = useMemo(+ () => PALETTE_PAGES.filter(allowItem),+ [allowItem],+ );++ const settingsItems = useMemo(+ () => SETTINGS_INDEX+ .filter((s) => allowItem({ adminOnly: s.adminOnly }))+ .map((s) => ({+ id: `setting:${s.id}`,+ label: s.label,+ sublabel: s.description || '',+ keywords: `${s.keywords || ''} ${s.tab} settings`,+ path: `/settings/${s.tab}?focus=setting:${s.id}`,+ category: 'Settings',+ })),+ [allowItem],+ );++ const actionItems = useMemo(+ () => COMMAND_ACTIONS+ .filter((a) => allowItem({ adminOnly: a.adminOnly }))+ .map((a) => ({+ id: `action:${a.id}`,+ label: a.label,+ keywords: a.keywords || '',+ category: 'Actions',+ suggested: a.suggested,+ perform: a.perform,+ })),+ [allowItem],+ );++ const pluginItems = useMemo(+ () => (pluginPaletteItems || []).filter((it) => it && it.label && it.path).map((it) => ({+ id: `plugin:${it.path}:${it.label}`,label: it.label,+ keywords: it.keywords || '',path: it.path,category: it.category || 'Extensions',- keywords: it.keywords || '',+ })),+ [pluginPaletteItems],+ );++ const docItems = useMemo(() => {+ if (whiteLabel?.enabled) return [];+ return DOCS_ENTRIES+ .filter((d) => DOCS_LINKS[d.key])+ .map((d) => ({+ id: `docs:${d.key}`,+ label: d.label,+ keywords: d.keywords || '',+ path: DOCS_LINKS[d.key],+ category: 'Docs',+ external: true,}));- return [...STATIC_PAGES, ...fromPlugins, ...dynamicItems];- }, [dynamicItems, pluginPaletteItems]);+ }, [whiteLabel]);++ // --- Async entity provider (backend /search), debounced 200ms ------------+ useEffect(() => {+ if (!open) return undefined;+ const t = term.trim();+ if (mode !== 'all' || t.length < 2) {+ setEntityItems([]);+ return undefined;+ }+ let cancelled = false;+ const handle = setTimeout(async () => {+ try {+ const res = await api.search(t);+ if (cancelled) return;+ const rows = res?.results || [];+ setEntityItems(rows.map((r) => ({+ id: `entity:${r.type}:${r.path}`,+ label: r.label,+ sublabel: r.sublabel || '',+ path: r.path,+ category: ENTITY_CATEGORY[r.type] || 'Results',+ })));+ } catch {+ if (!cancelled) setEntityItems([]);+ }+ }, 200);+ return () => { cancelled = true; clearTimeout(handle); };+ }, [open, term, mode]);+ // --- Results -------------------------------------------------------------const results = useMemo(() => {- if (!query.trim()) return allItems.slice(0, 20);- return allItems- .map(item => ({ ...item, score: scoreItem(item, query.trim()) }))- .filter(item => item.score > 0)- .sort((a, b) => b.score - a.score)- .slice(0, 20);- }, [query, allItems]);+ const t = term.trim();++ // Empty query: recently used + suggestions (bare), or the full small set+ // for a prefix mode.+ if (!t) {+ if (mode === 'actions') return capGroups(actionItems);+ if (mode === 'docs') return capGroups(docItems);+ const pool = [...settingsItems, ...pageItems, ...actionItems, ...pluginItems, ...docItems];+ const byId = new Map(pool.map((i) => [i.id, i]));+ const recents = recentIds(8)+ .map((id) => byId.get(id))+ .filter(Boolean)+ .map((i) => ({ ...i, category: 'Recently used' }));+ const base = recents.length+ ? recents+ : pageItems.slice(0, 6).map((i) => ({ ...i, category: 'Recently used' }));+ const suggestions = actionItems.filter((a) => a.suggested).slice(0, 4);+ return capGroups([...base, ...suggestions], 8, OVERALL_CAP);+ }+ const syncPool = mode === 'actions'+ ? actionItems+ : mode === 'docs'+ ? docItems+ : [...settingsItems, ...pageItems, ...actionItems, ...pluginItems, ...docItems];++ const scored = [];+ for (const item of syncPool) {+ const s = scoreItem(item, t);+ if (s < 0) continue;+ const weight = CATEGORY_WEIGHT[item.category] ?? 1;+ const frec = Math.min(frecencyScore(item.id), 10);+ scored.push({ ...item, _score: s + weight + frec });+ }+ if (mode === 'all') {+ for (const item of entityItems) {+ // Entities already matched server-side; score locally only for+ // ordering, and never drop them.+ const s = scoreItem(item, t);+ const weight = CATEGORY_WEIGHT[item.category] ?? 1;+ scored.push({ ...item, _score: (s < 0 ? 0 : s) + weight });+ }+ }+ scored.sort((a, b) => b._score - a._score);+ return capGroups(scored);+ }, [term, mode, settingsItems, pageItems, actionItems, pluginItems, docItems, entityItems]);++ // --- Selection -----------------------------------------------------------const handleSelect = useCallback((item) => {- navigate(item.path);+ recordUse(item.id);onClose();- }, [navigate, onClose]);+ if (typeof item.perform === 'function') {+ item.perform({+ navigate,+ logout,+ api,+ toggleTheme: () => setTheme(resolvedTheme === 'dark' ? 'light' : 'dark'),+ });+ return;+ }+ if (item.external) {+ window.open(item.path, '_blank', 'noopener,noreferrer');+ return;+ }+ navigate(item.path);+ }, [navigate, onClose, logout, resolvedTheme, setTheme]);- // Group results by category+ // Group + order for rendering.const grouped = useMemo(() => {const groups = {};- results.forEach(item => {- if (!groups[item.category]) groups[item.category] = [];- groups[item.category].push(item);- });- return groups;+ for (const it of results) (groups[it.category] = groups[it.category] || []).push(it);+ return Object.keys(groups)+ .sort((a, b) => {+ const ia = GROUP_ORDER.indexOf(a);+ const ib = GROUP_ORDER.indexOf(b);+ return (ia === -1 ? 999 : ia) - (ib === -1 ? 999 : ib);+ })+ .map((k) => [k, groups[k]]);}, [results]);+ const placeholder = mode === 'actions'+ ? 'Run an action…'+ : mode === 'docs'+ ? 'Search docs…'+ : 'Search pages, settings, actions, services…';+return (- <CommandDialog open={open} onOpenChange={(isOpen) => { if (!isOpen) onClose(); }}>+ <CommandDialog+ open={open}+ shouldFilter={false}+ label="Command palette"+ onOpenChange={(isOpen) => { if (!isOpen) onClose(); }}+ ><CommandInput- placeholder="Search pages, services, servers..."+ placeholder={placeholder}value={query}onValueChange={setQuery}/><CommandList><CommandEmpty>No results found</CommandEmpty>- {Object.entries(grouped).map(([category, items]) => (- <CommandGroup key={category} heading={category}>- {items.map(item => (- <CommandItem- key={`${item.category}-${item.path}-${item.label}`}- value={`${item.label} ${item.path} ${item.keywords || ''}`}- onSelect={() => handleSelect(item)}- >- <span className="command-palette__item-label">{item.label}</span>- <span className="command-palette__item-path">{item.path}</span>- </CommandItem>- ))}- </CommandGroup>- ))}+ {grouped.map(([category, items]) => {+ const Icon = CATEGORY_ICONS[category] || LayoutGrid;+ return (+ <CommandGroup key={category} heading={category}>+ {items.map((item) => (+ <CommandItem+ key={item.id}+ value={item.id}+ onSelect={() => handleSelect(item)}+ >+ <Icon className="command-palette__item-icon" aria-hidden="true" />+ <span className="command-palette__item-body">+ <span className="command-palette__item-label">{item.label}</span>+ {item.sublabel && (+ <span className="command-palette__item-sublabel">{item.sublabel}</span>+ )}+ </span>+ {item.external && (+ <ExternalLink className="command-palette__item-ext" aria-hidden="true" />+ )}+ </CommandItem>+ ))}+ </CommandGroup>+ );+ })}</CommandList>+ <div className="command-palette__footer">+ <span className="command-palette__hint"><kbd>↵</kbd> open</span>+ <span className="command-palette__hint"><kbd>></kbd> actions</span>+ <span className="command-palette__hint"><kbd>?</kbd> docs</span>+ <span className="command-palette__hint"><kbd>esc</kbd> close</span>+ </div></CommandDialog>);};diff --git a/frontend/src/components/ui/command.jsx b/frontend/src/components/ui/command.jsxindex 8a2283f4..f724616e 100644--- a/frontend/src/components/ui/command.jsx+++ b/frontend/src/components/ui/command.jsx@@ -11,11 +11,11 @@ const Command = React.forwardRef(({ className, ...props }, ref) => ());Command.displayName = CommandPrimitive.displayName;-function CommandDialog({ children, ...props }) {+function CommandDialog({ children, shouldFilter, label, ...props }) {return (<Dialog {...props}><DialogContent className="ui-command-dialog">- <Command>{children}</Command>+ <Command shouldFilter={shouldFilter} label={label}>{children}</Command></DialogContent></Dialog>);diff --git a/frontend/src/data/commandActions.js b/frontend/src/data/commandActions.jsnew file mode 100644index 00000000..f8f7b6db--- /dev/null+++ b/frontend/src/data/commandActions.js@@ -0,0 +1,88 @@+// Runnable actions for the command palette (plan 41, Phase 3). Typing `>` filters+// results to this list. v1 ships only safe, non-destructive verbs — openers and+// navigation-with-intent — never blind destructive/exec commands (those belong to+// entity rows with confirm dialogs; see the plan's "Deliberately deferred").+//+// Each action: { id, label, keywords, adminOnly?, suggested?, perform(ctx) }.+// `ctx` = { navigate, toggleTheme, logout, api } is assembled by CommandPalette+// from the app's hooks. `suggested: true` surfaces the action on the empty-query+// screen. Every action still passes the Phase-1 authz filter (adminOnly + nav).++export const COMMAND_ACTIONS = [+ {+ id: 'new-service',+ label: 'New Service',+ keywords: 'create app deploy add service container',+ suggested: true,+ perform: ({ navigate }) => navigate('/services/new'),+ },+ {+ id: 'add-server',+ label: 'Add Server',+ keywords: 'connect agent fleet new server node',+ suggested: true,+ perform: ({ navigate }) => navigate('/servers'),+ },+ {+ id: 'add-domain',+ label: 'Add Domain',+ keywords: 'dns new create domain zone',+ perform: ({ navigate }) => navigate('/domains'),+ },+ {+ id: 'new-cron',+ label: 'New Cron Job',+ keywords: 'schedule task create cron job',+ perform: ({ navigate }) => navigate('/cron'),+ },+ {+ id: 'new-backup-policy',+ label: 'New Backup Policy',+ keywords: 'backup schedule protection create policy',+ perform: ({ navigate }) => navigate('/backups'),+ },+ {+ id: 'install-extension',+ label: 'Install Extension',+ keywords: 'marketplace plugin add manual install extension',+ perform: ({ navigate }) => navigate('/marketplace'),+ },+ {+ id: 'open-terminal',+ label: 'Open Terminal',+ keywords: 'shell ssh console terminal logs',+ perform: ({ navigate }) => navigate('/terminal'),+ },+ {+ id: 'toggle-theme',+ label: 'Toggle Theme',+ keywords: 'dark light mode appearance theme switch',+ perform: ({ toggleTheme }) => toggleTheme && toggleTheme(),+ },+ {+ id: 'copy-version',+ label: 'Copy Panel Version',+ keywords: 'about build version copy',+ perform: async ({ api }) => {+ try {+ const data = (await (api.getSystemInfo+ ? api.getSystemInfo()+ : api.getSystemSettings())) || {};+ const version = data.version || data.app_version || data.panel_version;+ if (version && navigator.clipboard) {+ await navigator.clipboard.writeText(String(version));+ }+ } catch {+ /* best-effort clipboard copy — never surface an error */+ }+ },+ },+ {+ id: 'sign-out',+ label: 'Sign Out',+ keywords: 'logout log out exit sign out',+ perform: ({ logout }) => logout && logout(),+ },+];++export default COMMAND_ACTIONS;diff --git a/frontend/src/data/palettePages.js b/frontend/src/data/palettePages.jsnew file mode 100644index 00000000..8db712f3--- /dev/null+++ b/frontend/src/data/palettePages.js@@ -0,0 +1,43 @@+// Static top-level pages for the command palette (plan 41). Extracted from the+// old inline STATIC_PAGES so the palette component stays about orchestration.+//+// `navId` ties a page to its sidebar item id, letting the palette apply the SAME+// workspace nav-permission gate the sidebar uses (a member whose workspace hides+// "servers" shouldn't find the Servers page here). Pages with no navId (e.g.+// Import a Site) have no sidebar item and are always reachable.+//+// The seven hand-typed `Settings: X` rows that used to live here retired in+// favor of data/settingsIndex.js, which indexes settings at the card level.+// WordPress / FTP / Status / GPU / Workflow / Remote-Access / Cloud-Provision+// palette entries are contributed by their extensions (command_palette).++export const PALETTE_PAGES = [+ { label: 'Services', path: '/services', navId: 'services', keywords: 'apps containers' },+ { label: 'Docker', path: '/docker', navId: 'docker', keywords: 'containers images' },+ { label: 'Databases', path: '/databases', navId: 'databases', keywords: 'mysql postgres sql mongo' },+ { label: 'Domains', path: '/domains', navId: 'domains', keywords: 'dns nginx records nameserver zones' },+ { label: 'SSL Certificates', path: '/ssl', navId: 'domains', keywords: 'https tls certificate' },+ { label: 'Templates', path: '/templates', navId: 'services', keywords: 'deploy one-click gallery' },+ { label: 'Deployments', path: '/deployments', navId: 'services', keywords: 'deploy jobs status logs' },+ { label: 'Files', path: '/files', navId: 'files', keywords: 'file manager explorer' },+ { label: 'Observability', path: '/monitoring', navId: 'monitoring', keywords: 'metrics uptime monitoring alerts' },+ { label: 'Events', path: '/telemetry', navId: 'monitoring', keywords: 'telemetry metrics observability system events' },+ { label: 'Backups', path: '/backups', navId: 'backups', keywords: 'snapshots restore protection' },+ { label: 'Cron Jobs', path: '/cron', navId: 'cron', keywords: 'schedule tasks' },+ { label: 'Security', path: '/security', navId: 'security', keywords: 'firewall fail2ban' },+ { label: 'Terminal', path: '/terminal', navId: 'terminal', keywords: 'shell ssh console logs' },+ { label: 'Servers', path: '/servers', navId: 'servers', keywords: 'fleet agents' },+ { label: 'Fleet Monitor', path: '/fleet-monitor', navId: 'servers', keywords: 'agents status' },+ { label: 'Marketplace', path: '/marketplace', navId: 'marketplace', keywords: 'extensions plugins' },+ { label: 'Downloads', path: '/downloads', navId: 'marketplace', keywords: 'agent installer' },+ { label: 'Import a Site', path: '/imports', keywords: 'import migrate cpanel directadmin hestia backup adoption move existing' },+ { label: 'Projects', path: '/projects', navId: 'organization', keywords: 'organization group' },+ { label: 'Shared Variables', path: '/shared-variables', navId: 'organization', keywords: 'env secrets shared' },+ { label: 'Workspaces', path: '/workspaces', navId: 'organization', keywords: 'organization team' },+ { label: 'Vaults', path: '/vaults', navId: 'organization', keywords: 'secrets tokens credentials vault' },+ { label: 'Queue Bus', path: '/queue', navId: 'queue', keywords: 'bus operations tasks' },+ { label: 'Jobs', path: '/jobs', navId: 'jobs', keywords: 'scheduler background work' },+ { label: 'Webhooks', path: '/webhooks', navId: 'webhooks', keywords: 'webhook receive forward delivery' },+].map((p) => ({ ...p, id: `page:${p.path}`, category: 'Pages' }));++export default PALETTE_PAGES;diff --git a/frontend/src/data/settingsIndex.js b/frontend/src/data/settingsIndex.jsnew file mode 100644index 00000000..8e5e5e1e--- /dev/null+++ b/frontend/src/data/settingsIndex.js@@ -0,0 +1,114 @@+// Searchable settings index (plan 41, Phase 2). Every meaningful settings card+// or field — not just the tab — becomes a palette result that lands you on the+// exact card via `/settings/<tab>?focus=setting:<id>` (see hooks/useSettingFocus).+//+// Shape: { id, label, description, keywords, tab, adminOnly }. `id` is unique+// across the whole index and is the value carried in the `?focus=setting:<id>`+// deep link. `adminOnly` mirrors the tab's gate in pages/Settings.jsx so a+// member never finds an admin-only card here.+//+// Completeness is enforced at lint time by scripts/check-settings-index.mjs:+// every settings tab must have at least one entry, so a new tab can't ship+// invisible to search.++export const SETTINGS_INDEX = [+ { id: 'profile-username', label: 'Update username', description: 'Change your account username', keywords: 'name account profile', tab: 'profile', adminOnly: false },+ { id: 'profile-email', label: 'Update email address', description: 'Change your account email', keywords: 'email contact', tab: 'profile', adminOnly: false },++ { id: 'security-password', label: 'Change password', description: 'Update your account password', keywords: 'password login authentication', tab: 'security', adminOnly: false },+ { id: 'security-2fa', label: 'Two-factor authentication', description: 'Enable or disable 2FA for your account with an authenticator app', keywords: '2fa mfa otp totp authenticator two factor', tab: 'security', adminOnly: false },+ { id: 'security-2fa-policy', label: 'Require two-factor for all members', description: 'Enforce 2FA across every account', keywords: '2fa mfa policy require enforce members', tab: 'security', adminOnly: true },+ { id: 'security-backup-codes', label: 'Backup codes', description: 'Regenerate or download backup codes for 2FA recovery', keywords: 'backup codes recovery 2fa', tab: 'security', adminOnly: false },+ { id: 'security-sessions', label: 'Active sessions', description: 'View and manage your active login sessions', keywords: 'sessions login devices', tab: 'security', adminOnly: false },+ { id: 'security-linked-accounts', label: 'Linked accounts', description: 'Connect or disconnect SSO identity providers to your account', keywords: 'sso oauth github google linked accounts', tab: 'security', adminOnly: false },++ { id: 'notifications-enable', label: 'Enable notifications', description: 'Turn notifications on or off', keywords: 'notifications enable disable', tab: 'notifications', adminOnly: false },+ { id: 'notifications-channels', label: 'Notification channels', description: 'Choose how to receive notifications (email, Discord, Slack, Telegram)', keywords: 'channels email discord slack telegram', tab: 'notifications', adminOnly: false },+ { id: 'notifications-email', label: 'Email notifications', description: 'Configure email settings for notifications', keywords: 'email smtp notifications', tab: 'notifications', adminOnly: false },+ { id: 'notifications-discord-webhook', label: 'Personal Discord webhook', description: 'Set up Discord direct message or channel notifications', keywords: 'discord webhook notifications', tab: 'notifications', adminOnly: false },+ { id: 'notifications-telegram', label: 'Personal Telegram', description: 'Configure Telegram chat for notifications', keywords: 'telegram bot notifications', tab: 'notifications', adminOnly: false },+ { id: 'notifications-severity', label: 'Alert severity levels', description: 'Choose which alert types to receive (critical, warning, info, success)', keywords: 'severity levels alerts critical warning', tab: 'notifications', adminOnly: false },+ { id: 'notifications-categories', label: 'Notification categories', description: 'Select event types that trigger notifications (system, security, backups, apps)', keywords: 'categories events system security backups', tab: 'notifications', adminOnly: false },+ { id: 'notifications-quiet-hours', label: 'Quiet hours', description: 'Pause non-critical notifications during specific hours', keywords: 'quiet hours silent do not disturb', tab: 'notifications', adminOnly: false },+ { id: 'notifications-email-smtp', label: 'Email SMTP configuration', description: 'Set up SMTP server for sending email notifications', keywords: 'smtp email server notifications', tab: 'notifications', adminOnly: true },+ { id: 'notifications-webhook', label: 'Generic notification webhook', description: 'Send notifications to a custom webhook endpoint', keywords: 'webhook generic json payload', tab: 'notifications', adminOnly: true },++ { id: 'appearance-theme', label: 'Theme mode', description: 'Choose between dark, light, or system default theme', keywords: 'theme dark light system mode', tab: 'appearance', adminOnly: false },+ { id: 'appearance-accent-color', label: 'Accent color', description: 'Select the primary accent color for the UI', keywords: 'color accent primary indigo ocean forest sunset rose', tab: 'appearance', adminOnly: false },+ { id: 'appearance-widgets', label: 'Dashboard widgets', description: 'Toggle visibility and reorder widgets on the dashboard', keywords: 'widgets dashboard visibility order', tab: 'appearance', adminOnly: false },++ { id: 'sidebar-view-profiles', label: 'Sidebar view profiles', description: 'Choose a preset layout or customize sidebar items individually', keywords: 'sidebar layout preset recommended custom', tab: 'sidebar', adminOnly: false },+ { id: 'sidebar-items', label: 'Sidebar items', description: 'Toggle individual sidebar items on or off', keywords: 'sidebar items menu visibility', tab: 'sidebar', adminOnly: false },++ { id: 'whitelabel-branding', label: 'Custom branding', description: 'Enable white label mode and replace ServerKit branding', keywords: 'white label branding custom logo', tab: 'whitelabel', adminOnly: false },+ { id: 'whitelabel-mode', label: 'Branding mode', description: 'Choose how to display custom branding (logo + text, full-width, or text only)', keywords: 'branding mode logo text', tab: 'whitelabel', adminOnly: false },+ { id: 'whitelabel-brand-name', label: 'Brand name', description: 'Set your custom brand name to replace ServerKit', keywords: 'brand name company', tab: 'whitelabel', adminOnly: false },+ { id: 'whitelabel-logo', label: 'Logo image', description: 'Upload a custom logo for the sidebar', keywords: 'logo image upload', tab: 'whitelabel', adminOnly: false },++ { id: 'about-version', label: 'Version information', description: 'View ServerKit version and check for updates', keywords: 'version updates check', tab: 'about', adminOnly: false },+ { id: 'about-links', label: 'Links and resources', description: 'Access documentation, GitHub, support, and bug reports', keywords: 'github documentation support issues', tab: 'about', adminOnly: false },++ { id: 'users-management', label: 'User management', description: 'Create, edit, and manage user accounts', keywords: 'users add create edit delete', tab: 'users', adminOnly: true },+ { id: 'users-role-permission', label: 'User roles and permissions', description: 'Assign roles (admin, developer, viewer) to users', keywords: 'role permission admin developer viewer', tab: 'users', adminOnly: true },+ { id: 'users-active-status', label: 'Activate or disable users', description: 'Enable or disable user account access', keywords: 'active disable deactivate status', tab: 'users', adminOnly: true },+ { id: 'users-login-links', label: 'One-time login links', description: 'Generate single-use sign-in URLs for users', keywords: 'login links one-time auth temporary', tab: 'users', adminOnly: true },+ { id: 'users-invitations', label: 'User invitations', description: 'Invite users to join via email', keywords: 'invitations email invite', tab: 'users', adminOnly: true },++ { id: 'activity-dashboard', label: 'Activity dashboard', description: 'Monitor team activity and view statistics', keywords: 'activity dashboard stats graphs', tab: 'activity', adminOnly: true },+ { id: 'activity-audit-log', label: 'Audit log', description: 'View a detailed audit trail of all system actions and user activities', keywords: 'audit log history actions', tab: 'activity', adminOnly: true },++ { id: 'site-registration', label: 'Public user registration', description: 'Allow or disable new user registration on the login page', keywords: 'registration public signup', tab: 'site', adminOnly: true },+ { id: 'site-app-ports', label: 'Managed app ports', description: 'Control the base port assigned to new applications', keywords: 'ports app wordpress container', tab: 'site', adminOnly: true },+ { id: 'site-base-domains', label: 'Base domains', description: 'Register and manage domains for publishing managed sites', keywords: 'base domain sites registry subdomain', tab: 'site', adminOnly: true },+ { id: 'site-server-ip', label: 'Server public IP', description: 'Configure the public IP address for DNS A records', keywords: 'server public ip dns', tab: 'site', adminOnly: true },+ { id: 'site-dns-mode', label: 'DNS mode', description: 'Choose between wildcard or per-site DNS records', keywords: 'dns mode wildcard per-site', tab: 'site', adminOnly: true },+ { id: 'site-https-setup', label: 'HTTPS certificate setup', description: 'Set up wildcard SSL certificates for base domains', keywords: 'https ssl certificate letsencrypt', tab: 'site', adminOnly: true },+ { id: 'site-dev-mode', label: 'Developer mode', description: 'Enable developer tools and diagnostics', keywords: 'dev mode developer tools debug', tab: 'site', adminOnly: true },+ { id: 'site-registry-url', label: 'Extension registry URL', description: 'Set the source URL for the extension marketplace index', keywords: 'registry url marketplace extensions index', tab: 'site', adminOnly: true },++ { id: 'connections-github', label: 'GitHub connection', description: 'Connect GitHub for source code repositories and deployments', keywords: 'github source control oauth', tab: 'connections', adminOnly: true },+ { id: 'connections-gitlab', label: 'GitLab connection', description: 'Connect GitLab for source code repositories', keywords: 'gitlab source control oauth', tab: 'connections', adminOnly: true },+ { id: 'connections-cloud-provider', label: 'Cloud providers', description: 'Connect cloud accounts for server provisioning', keywords: 'cloud provider digitalocean hetzner vultr linode', tab: 'connections', adminOnly: true },+ { id: 'connections-dns-provider', label: 'DNS providers', description: 'Connect DNS providers for domain and HTTPS management', keywords: 'dns provider cloudflare route53 godaddy', tab: 'connections', adminOnly: true },+ { id: 'connections-registrar', label: 'Domain registrar', description: 'Connect domain registrars to manage domain portfolio and expiry', keywords: 'registrar domains portfolio expiry', tab: 'connections', adminOnly: true },+ { id: 'connections-storage', label: 'Backup storage', description: 'Configure S3-compatible or B2 storage for offsite backups', keywords: 'storage backup s3 backblaze b2', tab: 'connections', adminOnly: true },+ { id: 'connections-email-relay', label: 'Email relay', description: 'Set up an email relay service for outgoing mail', keywords: 'email relay smtp outgoing', tab: 'connections', adminOnly: true },+ { id: 'connections-container-registry', label: 'Container registry', description: 'Connect container registries for Docker image pulls', keywords: 'container registry docker docker hub', tab: 'connections', adminOnly: true },++ { id: 'sso-general-settings', label: 'SSO general settings', description: 'Configure auto-provisioning, default roles, and allowed domains', keywords: 'sso auto provision default role', tab: 'sso', adminOnly: true },+ { id: 'sso-force-mode', label: 'SSO-only mode', description: 'Require all users to authenticate via SSO', keywords: 'sso only mode password disabled', tab: 'sso', adminOnly: true },+ { id: 'sso-google', label: 'Google OAuth', description: 'Configure Google as an SSO provider', keywords: 'google sso oauth', tab: 'sso', adminOnly: true },+ { id: 'sso-github', label: 'GitHub OAuth', description: 'Configure GitHub as an SSO provider', keywords: 'github sso oauth', tab: 'sso', adminOnly: true },+ { id: 'sso-oidc', label: 'OIDC provider', description: 'Configure a generic OpenID Connect provider', keywords: 'oidc openid connect', tab: 'sso', adminOnly: true },+ { id: 'sso-saml', label: 'SAML 2.0', description: 'Configure a SAML 2.0 identity provider', keywords: 'saml saml2 enterprise idp', tab: 'sso', adminOnly: true },++ { id: 'api-keys', label: 'API keys', description: 'Create, rotate, and revoke API keys for programmatic access', keywords: 'api key token authentication', tab: 'api', adminOnly: false },+ { id: 'api-key-scopes', label: 'API key scopes', description: 'Set permissions (scopes) for API keys', keywords: 'api scope permission', tab: 'api', adminOnly: false },+ { id: 'api-rate-limits', label: 'API rate limits', description: 'Configure API rate limits by tier', keywords: 'rate limit requests per minute', tab: 'api', adminOnly: true },+ { id: 'api-webhooks', label: 'Webhook subscriptions', description: 'Create and manage webhooks for event notifications', keywords: 'webhook events notifications', tab: 'api', adminOnly: false },+ { id: 'api-analytics', label: 'API usage analytics', description: 'Monitor API traffic, response times, and errors', keywords: 'api analytics traffic usage endpoints', tab: 'api', adminOnly: true },++ { id: 'ai-enable', label: 'Enable AI assistant', description: 'Toggle the in-panel AI assistant on or off', keywords: 'ai assistant enable disable', tab: 'ai', adminOnly: true },+ { id: 'ai-provider', label: 'AI provider', description: 'Select the AI service provider (OpenAI, Anthropic, Ollama, etc.)', keywords: 'ai provider openai anthropic ollama', tab: 'ai', adminOnly: true },+ { id: 'ai-model', label: 'AI model', description: 'Choose the language model to use', keywords: 'model gpt claude ollama', tab: 'ai', adminOnly: true },+ { id: 'ai-api-key', label: 'AI API key', description: 'Configure the API key for the selected AI provider', keywords: 'api key authentication', tab: 'ai', adminOnly: true },+ { id: 'ai-endpoint', label: 'AI endpoint', description: 'Set a custom endpoint for self-hosted AI models', keywords: 'endpoint url self-hosted ollama', tab: 'ai', adminOnly: true },+ { id: 'ai-cost-limit', label: 'AI cost ceiling', description: 'Set the maximum spending per conversation', keywords: 'cost limit spending budget', tab: 'ai', adminOnly: true },+ { id: 'ai-pii-redaction', label: 'PII redaction', description: 'Automatically redact personally identifiable information', keywords: 'pii redaction privacy sensitive', tab: 'ai', adminOnly: true },+ { id: 'ai-injection-detection', label: 'Prompt injection detection', description: 'Block prompt injection attack attempts', keywords: 'injection prompt attack security', tab: 'ai', adminOnly: true },++ { id: 'modules-toggle', label: 'Feature modules', description: 'Enable or disable optional feature areas (Email, WordPress, etc.)', keywords: 'modules features email wordpress toggle', tab: 'modules', adminOnly: true },++ { id: 'migrations-apply', label: 'Apply database migrations', description: 'Apply pending schema updates to the database', keywords: 'migration database schema update', tab: 'migrations', adminOnly: true },+ { id: 'migrations-history', label: 'Migration history', description: 'Review previously applied database migrations', keywords: 'migration history database schema', tab: 'migrations', adminOnly: true },++ { id: 'system-cpu', label: 'CPU metrics', description: 'View CPU usage, cores, and load average', keywords: 'cpu usage cores load', tab: 'system', adminOnly: true },+ { id: 'system-memory', label: 'Memory metrics', description: 'View memory usage and available RAM', keywords: 'memory ram usage', tab: 'system', adminOnly: true },+ { id: 'system-disk', label: 'Disk metrics', description: 'View disk usage and storage capacity', keywords: 'disk storage usage', tab: 'system', adminOnly: true },+ { id: 'system-network', label: 'Network metrics', description: 'View network traffic (bytes sent and received)', keywords: 'network bandwidth traffic', tab: 'system', adminOnly: true },+ { id: 'system-timezone', label: 'Server timezone', description: 'Change the server timezone', keywords: 'timezone time region', tab: 'system', adminOnly: true },+ { id: 'system-canonical-domain', label: 'Panel domain', description: 'Set the canonical domain for the ServerKit panel', keywords: 'canonical domain cors agents', tab: 'system', adminOnly: true },+ { id: 'system-encryption-key', label: 'Encryption key', description: 'Verify the encryption key is configured for credential security', keywords: 'encryption key credentials secret', tab: 'system', adminOnly: true },+];++export default SETTINGS_INDEX;diff --git a/frontend/src/hooks/usePaletteAuthz.js b/frontend/src/hooks/usePaletteAuthz.jsnew file mode 100644index 00000000..d7ac8e78--- /dev/null+++ b/frontend/src/hooks/usePaletteAuthz.js@@ -0,0 +1,56 @@+import { useMemo } from 'react';+import { useAuth } from '../contexts/AuthContext';+import { SIDEBAR_ITEMS } from '../components/sidebarItems';++// Sidebar items that can never be hidden (Dashboard, Marketplace) — the palette+// mirrors the sidebar's `alwaysVisible` so a workspace nav map can't hide them.+const ALWAYS_VISIBLE = new Set(+ SIDEBAR_ITEMS.filter((i) => i.alwaysVisible).map((i) => i.id),+);++/**+ * The palette's authz gate (plan 41, Phase 1 #3). Mirrors exactly what the+ * sidebar shows so a member's palette can't surface admin surface:+ * - `adminOnly` items require an admin.+ * - Items tied to a sidebar `navId` respect the active workspace's per-role+ * nav-permission map (same source as applyWorkspaceNavPermissions), which+ * only ever NARROWS a member's view.+ *+ * Note: this intentionally does NOT apply personal sidebar-preset hiding — a page+ * you hid from your sidebar for tidiness stays reachable via the palette.+ */+export default function usePaletteAuthz() {+ const { isAdmin } = useAuth();++ return useMemo(() => {+ let navMap = null;+ let role = 'member';+ try {+ const raw = localStorage.getItem('active_workspace');+ const ws = raw ? JSON.parse(raw) : null;+ navMap = ws?.settings?.nav || null;+ role = ws?.my_effective_role || ws?.my_role || 'member';+ } catch {+ navMap = null;+ }++ const allowNav = (navId) => {+ if (!navId) return true;+ if (isAdmin) return true;+ if (ALWAYS_VISIBLE.has(navId)) return true;+ if (!navMap) return true;+ const allowed = navMap[role];+ if (!Array.isArray(allowed) || allowed.length === 0) return true;+ return allowed.includes(navId);+ };++ const allowItem = (item) => {+ if (item.adminOnly && !isAdmin) return false;+ return allowNav(item.navId);+ };++ return { isAdmin, allowNav, allowItem };+ // Recomputes on login/role change (isAdmin flips); the workspace nav map+ // is read from localStorage at build time and isn't otherwise reactive.+ }, [isAdmin]);+}diff --git a/frontend/src/layouts/DashboardLayout.jsx b/frontend/src/layouts/DashboardLayout.jsxindex 96d17a8d..f7230fd0 100644--- a/frontend/src/layouts/DashboardLayout.jsx+++ b/frontend/src/layouts/DashboardLayout.jsx@@ -47,7 +47,13 @@ const DashboardLayout = () => {));const handleKeyDown = useCallback((e) => {- if ((e.metaKey || e.ctrlKey) && e.key === 'k') {+ // Open aliases: Ctrl/Cmd+K (original), plus VS Code muscle memory —+ // F1 and Ctrl/Cmd+Shift+P. preventDefault on F1 keeps the browser+ // help panel from stealing it.+ const cmdK = (e.metaKey || e.ctrlKey) && !e.shiftKey && e.key.toLowerCase() === 'k';+ const cmdShiftP = (e.metaKey || e.ctrlKey) && e.shiftKey && e.key.toLowerCase() === 'p';+ const f1 = e.key === 'F1';+ if (cmdK || cmdShiftP || f1) {e.preventDefault();setPaletteOpen(prev => !prev);}diff --git a/frontend/src/styles/components/_command-palette.scss b/frontend/src/styles/components/_command-palette.scssindex 37c226da..f11701d2 100644--- a/frontend/src/styles/components/_command-palette.scss+++ b/frontend/src/styles/components/_command-palette.scss@@ -137,3 +137,72 @@font-family: $font-mono;}}++// --------------------------------------------+// Palette v2 (plan 41): omnisearch item rows rendered inside the cmdk+// .ui-command-item. Icon + label/sublabel body + optional external marker.+// --------------------------------------------+.command-palette__item-icon {+ width: 16px;+ height: 16px;+ flex-shrink: 0;+ color: $text-tertiary;+}++.command-palette__item-body {+ display: flex;+ flex-direction: column;+ gap: 1px;+ min-width: 0;+ flex: 1;+}++.command-palette__item-sublabel {+ font-size: $font-size-xs;+ color: $text-tertiary;+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+}++.command-palette__item-ext {+ width: 13px;+ height: 13px;+ flex-shrink: 0;+ color: $text-tertiary;+ opacity: 0.7;+}++.command-palette__footer {+ display: flex;+ align-items: center;+ gap: $space-4;+ padding: $space-2 $space-3;+ border-top: 1px solid $border-subtle;+ background: $bg-secondary;+}++.command-palette__hint {+ display: inline-flex;+ align-items: center;+ gap: $space-1;+ font-size: $font-size-xs;+ color: $text-tertiary;++ kbd {+ min-width: 16px;+ padding: 1px 5px;+ text-align: center;+ font-size: $font-size-xs;+ font-family: $font-mono;+ color: $text-secondary;+ background: $bg-hover;+ border: 1px solid $border-subtle;+ border-radius: $radius-sm;+ }+}++// The selected item's icon should follow the highlighted text color.+.ui-command-item[data-selected='true'] .command-palette__item-icon {+ color: $text-primary;+}diff --git a/frontend/src/utils/paletteFrecency.js b/frontend/src/utils/paletteFrecency.jsnew file mode 100644index 00000000..f1e62454--- /dev/null+++ b/frontend/src/utils/paletteFrecency.js@@ -0,0 +1,57 @@+// Per-user "frecency" for the command palette (plan 41): frequency + recency of+// selections, kept in localStorage so an empty query can surface Recently used+// and a matched query can boost the things you actually pick. Client-only —+// server-side sync across devices is explicitly out of scope.++const STORE_KEY = 'serverkit:palette:frecency';+const HALF_LIFE_DAYS = 14; // a selection's weight halves every two weeks+const DAY_MS = 86400000;++function load() {+ try {+ const raw = localStorage.getItem(STORE_KEY);+ const parsed = raw ? JSON.parse(raw) : null;+ return parsed && typeof parsed === 'object' ? parsed : {};+ } catch {+ return {};+ }+}++function save(data) {+ try {+ localStorage.setItem(STORE_KEY, JSON.stringify(data));+ } catch {+ /* storage full / disabled — frecency is a nicety, never fatal */+ }+}++/** Exponentially time-decayed selection count for one item id. */+export function frecencyScore(id, now = Date.now()) {+ const rec = load()[id];+ if (!rec) return 0;+ const ageDays = Math.max(0, (now - (rec.lastUsed || 0)) / DAY_MS);+ const decay = Math.pow(0.5, ageDays / HALF_LIFE_DAYS);+ return (rec.count || 0) * decay;+}++/** Record that the user selected `id`. */+export function recordUse(id, now = Date.now()) {+ if (!id) return;+ const data = load();+ const rec = data[id] || { count: 0, lastUsed: 0 };+ rec.count += 1;+ rec.lastUsed = now;+ data[id] = rec;+ save(data);+}++/** Most-used-recently item ids, best first. */+export function recentIds(limit = 8, now = Date.now()) {+ const data = load();+ return Object.keys(data)+ .map((id) => ({ id, score: frecencyScore(id, now) }))+ .filter((r) => r.score > 0)+ .sort((a, b) => b.score - a.score)+ .slice(0, limit)+ .map((r) => r.id);+}diff --git a/frontend/src/utils/paletteScore.js b/frontend/src/utils/paletteScore.jsnew file mode 100644index 00000000..b7f07e5e--- /dev/null+++ b/frontend/src/utils/paletteScore.js@@ -0,0 +1,68 @@+// One scorer for the command palette (plan 41). A single subsequence fuzzy+// matcher with a word-start bonus, used across every provider so results from+// pages, settings, actions, and entities rank on the same scale. cmdk's own+// matcher is disabled (shouldFilter={false}) so this is the ONLY filter.++// Characters that begin a "word" — used to reward matches at the start of a+// token (e.g. "sm" hitting "SMTP" or "settings/security").+const WORD_BOUNDARY = /[\s\-_/:.]/;++/**+ * Subsequence fuzzy match of `query` against `text`.+ * @returns {number} score >= 0 on a match (higher is better), or -1 on no match.+ */+export function fuzzyScore(text, query) {+ if (!query) return 0;+ if (!text) return -1;+ const t = text.toLowerCase();+ const q = query.toLowerCase();++ // Fast path: a contiguous substring beats any scattered subsequence, and a+ // prefix / word-start hit beats a mid-word one.+ const idx = t.indexOf(q);+ if (idx !== -1) {+ let s = 100 - Math.min(idx, 40);+ if (idx === 0) s += 40;+ else if (WORD_BOUNDARY.test(t[idx - 1])) s += 20;+ return s;+ }++ // Subsequence: every char of q must appear in order within t.+ let ti = 0;+ let score = 0;+ let streak = 0;+ for (let qi = 0; qi < q.length; qi++) {+ const ch = q[qi];+ let found = -1;+ for (let k = ti; k < t.length; k++) {+ if (t[k] === ch) { found = k; break; }+ }+ if (found === -1) return -1;+ if (found === ti && qi > 0) { streak += 1; score += 2 + streak; }+ else { streak = 0; score += 1; }+ if (found === 0 || WORD_BOUNDARY.test(t[found - 1])) score += 3;+ ti = found + 1;+ }+ return score;+}++/**+ * Score a palette item against a query, weighting label matches highest, then+ * keywords, then sublabel, then path. Returns -1 when nothing matches.+ */+export function scoreItem(item, query) {+ const q = (query || '').trim();+ if (!q) return 0;++ const label = fuzzyScore(item.label || '', q);+ const kw = fuzzyScore(item.keywords || '', q);+ const sub = fuzzyScore(item.sublabel || '', q);+ const path = fuzzyScore(item.path || '', q);++ return Math.max(+ label >= 0 ? label + 25 : -1,+ kw >= 0 ? kw + 8 : -1,+ sub >= 0 ? sub + 4 : -1,+ path >= 0 ? path : -1,+ );+}