Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

refactor: simplify command palette — dedupe, memoize, de-leak, strip narration

Adam Eivy7320feb05582
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 1cc3cebb34..3d9e456f8f 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -10,3 +10,7 @@
- **Keyboard help modal updated** — the `?` shortcut list now advertises "Open command palette" instead of "Open search" and describes Enter as "Go to page, run action, or open result".
Files: `server/lib/navManifest.js` (new), `server/routes/palette.js` (new), `server/services/voice/tools.js` (refactored), `server/index.js` (mounts `/api/palette`), `client/src/services/apiPalette.js` (new), `client/src/components/CmdKSearch.jsx` (palette behavior), `client/src/components/KeyboardHelp.jsx` (updated copy). Tests: `server/lib/navManifest.test.js`, `server/routes/palette.test.js`.
+
+## Changed
+
+- **Command palette cleanup pass** — post-review simplify: `normalizeLabel` is exported once from `navManifest.js` and imported by `voice/tools.js` (was duplicated verbatim); `getToolMetadata(id)` added to `voice/tools.js` so `routes/palette.js` no longer reaches through the OpenAI-shaped function spec; palette manifest frozen at module load (`buildActionManifest` no longer runs per request) with `Cache-Control: private, max-age=300`. Client scorer precomputes lowercased `_label`/`_aliases`/`_keywords`/`_section` so per-keystroke fuzzy matching does zero re-lowercasing over the 117-entry manifest. `CmdKSearch.jsx` trimmed ~80 lines: collapsed the triple `useMemo` chain, merged `renderCommandRow` + inline search-result row into a single `renderRow`/`renderGroup` pair, flattened `dispatchCommand` into a `DISPATCH` lookup table, dropped the dead `running` state, removed two `.catch()` error-swallows (errors now propagate to the central toast handler per CLAUDE.md), cleared `resultRefs` on close. `ALIAS_KEYS` cached once in `resolveNavCommand`. Decorative section-banner comments and narration comments removed across the new files.
diff --git a/client/src/components/CmdKSearch.jsx b/client/src/components/CmdKSearch.jsx
index 48a0542b66..ae848edff0 100644
--- a/client/src/components/CmdKSearch.jsx
+++ b/client/src/components/CmdKSearch.jsx
@@ -10,32 +10,33 @@ import { modKey } from '../utils/platform';
const ICON_MAP = { Brain, Cpu, Package, History, HeartPulse };
-// Cheap subsequence-based fuzzy scorer. No new deps. Ranks:
-// 1. exact label match (highest)
-// 2. label starts-with
-// 3. alias exact match
-// 4. keyword contains
-// 5. subsequence over label
-const scoreCommand = (cmd, q) => {
+// Subsequence-based fuzzy scorer. Tiered: exact label > label-prefix > alias
+// exact > label-contains > alias-contains > keyword-contains > section-contains
+// > subsequence. Reads precomputed lowercased fields to keep each comparison
+// allocation-free on the per-keystroke hot path.
+const scoreCommand = (c, q) => {
if (!q) return 0;
- const label = (cmd.label || '').toLowerCase();
- const aliases = (cmd.aliases || []).map((a) => a.toLowerCase());
- const keywords = (cmd.keywords || []).map((k) => k.toLowerCase());
- const section = (cmd.section || '').toLowerCase();
-
- if (label === q) return 1000;
- if (label.startsWith(q)) return 800 - (label.length - q.length);
- if (aliases.includes(q)) return 750;
- if (label.includes(q)) return 500;
- if (aliases.some((a) => a.includes(q))) return 400;
- if (keywords.some((k) => k.includes(q))) return 300;
- if (section.includes(q)) return 150;
- // Subsequence fallback: every character in q appears in order inside label.
+ const { _label, _aliases, _keywords, _section } = c;
+ if (_label === q) return 1000;
+ if (_label.startsWith(q)) return 800 - (_label.length - q.length);
+ if (_aliases.includes(q)) return 750;
+ if (_label.includes(q)) return 500;
+ for (const a of _aliases) if (a.includes(q)) return 400;
+ for (const k of _keywords) if (k.includes(q)) return 300;
+ if (_section.includes(q)) return 150;
let i = 0;
- for (const ch of label) if (ch === q[i]) i += 1;
+ for (const ch of _label) if (ch === q[i]) i += 1;
return i === q.length ? 100 + i : 0;
};
+const precompute = (cmd) => ({
+ ...cmd,
+ _label: (cmd.label || '').toLowerCase(),
+ _aliases: (cmd.aliases || []).map((a) => a.toLowerCase()),
+ _keywords: (cmd.keywords || []).map((k) => k.toLowerCase()),
+ _section: (cmd.section || '').toLowerCase(),
+});
+
function Highlight({ text, query }) {
if (!query || !text) return <span>{text}</span>;
const escaped = query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
@@ -51,6 +52,11 @@ function Highlight({ text, query }) {
);
}
+// Curated default shortlist — shown when the palette opens with no query so
+// Enter always does something useful.
+const DEFAULT_NAV_IDS = new Set(['nav.dashboard', 'nav.brain.inbox', 'nav.cos.tasks', 'nav.goals', 'nav.review-hub']);
+const DEFAULT_ACTION_IDS = new Set(['brain_capture', 'time_now', 'goal_list', 'meatspace_summary_today']);
+
export default function CmdKSearch() {
const { open, setOpen } = useCmdKSearch();
const navigate = useNavigate();
@@ -62,7 +68,6 @@ export default function CmdKSearch() {
const [loading, setLoading] = useState(false);
const [focusedIndex, setFocusedIndex] = useState(0);
const [expandedSources, setExpandedSources] = useState(new Set());
- const [running, setRunning] = useState(false);
const resultRefs = useRef([]);
useEffect(() => {
@@ -77,16 +82,18 @@ export default function CmdKSearch() {
setSearchResults([]);
setFocusedIndex(0);
setExpandedSources(new Set());
+ resultRefs.current = [];
}
}, [open]);
- // Lazy-load the palette manifest on first open and cache for the session.
- // The manifest rarely changes; re-fetching on every open wastes a roundtrip.
useEffect(() => {
if (!open || manifest) return;
- getPaletteManifest()
- .then((data) => setManifest(data))
- .catch(() => setManifest({ nav: [], actions: [] }));
+ getPaletteManifest().then((data) => {
+ setManifest({
+ nav: (data?.nav || []).map(precompute),
+ actions: (data?.actions || []).map(precompute),
+ });
+ });
}, [open, manifest]);
useEffect(() => {
@@ -108,52 +115,37 @@ export default function CmdKSearch() {
setFocusedIndex(0);
}, [searchResults, query]);
- const { navHits, actionHits } = useMemo(() => {
- if (!manifest) return { navHits: [], actionHits: [] };
+ const combined = useMemo(() => {
+ if (!manifest) return [];
const q = query.trim().toLowerCase();
if (!q) {
- // Default view: a curated set of "most useful" nav + actions so Enter
- // on empty query has meaning instead of doing nothing.
- const curatedNav = manifest.nav
- .filter((c) => ['nav.dashboard', 'nav.brain.inbox', 'nav.cos.tasks', 'nav.goals', 'nav.review-hub'].includes(c.id));
- const curatedActions = manifest.actions
- .filter((a) => ['brain_capture', 'time_now', 'goal_list', 'meatspace_summary_today'].includes(a.id));
- return { navHits: curatedNav, actionHits: curatedActions };
+ const nav = manifest.nav.filter((c) => DEFAULT_NAV_IDS.has(c.id)).map((c) => ({ ...c, kind: 'nav' }));
+ const actions = manifest.actions.filter((a) => DEFAULT_ACTION_IDS.has(a.id)).map((a) => ({ ...a, kind: 'action' }));
+ return { nav, actions, commandCount: nav.length + actions.length };
}
- const scoredNav = manifest.nav
+ const rank = (items, max) => items
.map((c) => ({ cmd: c, score: scoreCommand(c, q) }))
.filter((x) => x.score > 0)
.sort((a, b) => b.score - a.score)
- .slice(0, 8)
+ .slice(0, max)
.map((x) => x.cmd);
- const scoredActions = manifest.actions
- .map((a) => ({ cmd: a, score: scoreCommand(a, q) }))
- .filter((x) => x.score > 0)
- .sort((a, b) => b.score - a.score)
- .slice(0, 5)
- .map((x) => x.cmd);
- return { navHits: scoredNav, actionHits: scoredActions };
+ const nav = rank(manifest.nav, 8).map((c) => ({ ...c, kind: 'nav' }));
+ const actions = rank(manifest.actions, 5).map((a) => ({ ...a, kind: 'action' }));
+ return { nav, actions, commandCount: nav.length + actions.length };
}, [manifest, query]);
- const flatCommands = useMemo(
- () => [
- ...navHits.map((c) => ({ kind: 'nav', ...c })),
- ...actionHits.map((a) => ({ kind: 'action', ...a })),
- ],
- [navHits, actionHits]
- );
-
const flatSearchResults = useMemo(
- () =>
- searchResults.flatMap((source) => {
- const isExpanded = expandedSources.has(source.id);
- const visible = isExpanded ? source.results : source.results.slice(0, 3);
- return visible.map((r) => ({ ...r, kind: 'search', sourceId: source.id }));
- }),
+ () => searchResults.flatMap((source) => {
+ const visible = expandedSources.has(source.id) ? source.results : source.results.slice(0, 3);
+ return visible.map((r) => ({ ...r, kind: 'search', sourceId: source.id }));
+ }),
[searchResults, expandedSources]
);
- const combined = useMemo(() => [...flatCommands, ...flatSearchResults], [flatCommands, flatSearchResults]);
+ const focusable = useMemo(
+ () => [...combined.nav, ...combined.actions, ...flatSearchResults],
+ [combined, flatSearchResults]
+ );
useEffect(() => {
const el = resultRefs.current[focusedIndex];
@@ -162,47 +154,35 @@ export default function CmdKSearch() {
const close = useCallback(() => setOpen(false), [setOpen]);
- const dispatchCommand = useCallback(async (item) => {
- if (item.kind === 'nav') {
- navigate(item.path);
- close();
- return;
- }
- if (item.kind === 'action') {
- // Actions with required args can't be run blind from the palette — the
- // parameters schema is served with the manifest for future inline arg
- // UIs. For v1, only dispatch tools whose required list is empty. For
- // others, offer a hint toast telling the user to use voice or the
- // relevant page.
+ const DISPATCH = useMemo(() => ({
+ nav: (item) => { navigate(item.path); close(); },
+ search: (item) => { navigate(item.url); close(); },
+ action: async (item) => {
const required = item.parameters?.required || [];
if (required.length > 0) {
+ // Keep palette open so the user can pick another command.
toast(`${item.label} needs arguments — use voice or open the related page.`);
return;
}
- setRunning(true);
- const res = await runPaletteAction(item.id).catch((e) => ({ error: e.message }));
- setRunning(false);
- const summary = res?.result?.summary || res?.error || `${item.label} ran.`;
- if (res?.ok === false || res?.error) toast.error(summary);
+ const res = await runPaletteAction(item.id);
+ const summary = res?.result?.summary || `${item.label} ran.`;
+ if (res?.ok === false) toast.error(summary);
else toast.success(summary);
close();
- return;
- }
- if (item.kind === 'search') {
- navigate(item.url);
- close();
- }
- }, [navigate, close]);
+ },
+ }), [navigate, close]);
+
+ const dispatchCommand = useCallback((item) => DISPATCH[item.kind]?.(item), [DISPATCH]);
const handleKeyDown = (e) => {
if (e.key === 'ArrowDown') {
e.preventDefault();
- if (combined.length > 0) setFocusedIndex((i) => Math.min(i + 1, combined.length - 1));
+ if (focusable.length > 0) setFocusedIndex((i) => Math.min(i + 1, focusable.length - 1));
} else if (e.key === 'ArrowUp') {
e.preventDefault();
- if (combined.length > 0) setFocusedIndex((i) => Math.max(i - 1, 0));
+ if (focusable.length > 0) setFocusedIndex((i) => Math.max(i - 1, 0));
} else if (e.key === 'Enter') {
- const item = combined[focusedIndex];
+ const item = focusable[focusedIndex];
if (item) dispatchCommand(item);
} else if (e.key === 'Escape') {
close();
@@ -213,16 +193,12 @@ export default function CmdKSearch() {
let flatIdx = 0;
- const renderCommandRow = (item, kindLabel) => {
+ const renderRow = (item, { icon: Icon, title, subtitle, badge }) => {
const currentIdx = flatIdx++;
const isFocused = focusedIndex === currentIdx;
- const Icon = item.kind === 'nav' ? Navigation : Play;
- const subtitle = item.kind === 'nav'
- ? `${item.section} · ${item.path}`
- : (item.description ? item.description.slice(0, 80) : item.section || '');
return (
<div
- key={`${item.kind}:${item.id}`}
+ key={`${item.kind}:${item.id ?? item.sourceId + ':' + title}`}
ref={(el) => { resultRefs.current[currentIdx] = el; }}
onClick={() => dispatchCommand(item)}
className={`flex items-start gap-3 px-3 py-2 rounded-lg cursor-pointer transition-colors ${
@@ -231,20 +207,32 @@ export default function CmdKSearch() {
role="option"
aria-selected={isFocused}
>
- <Icon size={14} className="shrink-0 mt-0.5 text-gray-400" />
+ {Icon && <Icon size={14} className="shrink-0 mt-0.5 text-gray-400" />}
<div className="flex-1 min-w-0">
<p className="text-sm font-medium text-white truncate">
- <Highlight text={item.label} query={query} />
+ <Highlight text={title} query={query} />
</p>
{subtitle && (
- <p className="text-xs text-gray-500 truncate mt-0.5">{subtitle}</p>
+ <p className="text-xs text-gray-500 truncate mt-0.5">
+ <Highlight text={subtitle} query={query} />
+ </p>
)}
</div>
- <span className="text-[10px] uppercase tracking-wide text-gray-500 shrink-0 mt-1">{kindLabel}</span>
+ {badge && <span className="text-[10px] uppercase tracking-wide text-gray-500 shrink-0 mt-1">{badge}</span>}
</div>
);
};
+ const renderGroup = (headerIcon, headerLabel, rows) => rows.length > 0 && (
+ <div className="mb-2">
+ <div className="flex items-center gap-2 px-3 py-2 text-xs text-gray-400 uppercase tracking-wide">
+ {headerIcon}
+ <span>{headerLabel}</span>
+ </div>
+ {rows}
+ </div>
+ );
+
const overlay = (
<div
className="fixed inset-0 z-[9999] flex items-start justify-center pt-[10vh]"
@@ -268,49 +256,41 @@ export default function CmdKSearch() {
className="flex-1 bg-transparent text-white placeholder-gray-500 outline-hidden text-sm"
aria-label="Command palette"
/>
- {running && <Loader2 size={14} className="animate-spin text-gray-400 shrink-0" />}
<span className="text-xs text-gray-500 border border-port-border rounded px-1.5 py-0.5 shrink-0">
{`${modKey}+K`}
</span>
</div>
<div className="max-h-96 overflow-y-auto p-2">
- {/* Commands: Navigate */}
- {navHits.length > 0 && (
- <div className="mb-2">
- <div className="flex items-center gap-2 px-3 py-2 text-xs text-gray-400 uppercase tracking-wide">
- <Navigation size={14} />
- <span>Go to</span>
- </div>
- {navHits.map((c) => renderCommandRow({ kind: 'nav', ...c }, 'GO'))}
- </div>
+ {renderGroup(
+ <Navigation size={14} />,
+ 'Go to',
+ combined.nav.map((c) =>
+ renderRow(c, { icon: Navigation, title: c.label, subtitle: `${c.section} · ${c.path}`, badge: 'GO' })
+ )
)}
- {/* Commands: Run */}
- {actionHits.length > 0 && (
- <div className="mb-2">
- <div className="flex items-center gap-2 px-3 py-2 text-xs text-gray-400 uppercase tracking-wide">
- <Play size={14} />
- <span>Run</span>
- </div>
- {actionHits.map((a) => renderCommandRow({ kind: 'action', ...a }, 'RUN'))}
- </div>
+ {renderGroup(
+ <Play size={14} />,
+ 'Run',
+ combined.actions.map((a) =>
+ renderRow(a, { icon: Play, title: a.label, subtitle: (a.description || a.section || '').slice(0, 80), badge: 'RUN' })
+ )
)}
- {/* Content search (lazy — only when query ≥ 2 chars) */}
{loading && (
<div className="flex items-center justify-center py-4">
<Loader2 size={18} className="animate-spin text-gray-400" />
</div>
)}
- {!loading && query.length >= 2 && searchResults.length === 0 && flatCommands.length === 0 && (
+ {!loading && query.length >= 2 && searchResults.length === 0 && combined.commandCount === 0 && (
<div className="text-center text-sm text-gray-500 py-8">
No results for &ldquo;{query}&rdquo;
</div>
)}
- {!loading && !query && flatCommands.length === 0 && (
+ {!loading && !query && combined.commandCount === 0 && (
<div className="text-center text-sm text-gray-600 py-8">
Start typing to go to a page, run an action, or search.
</div>
@@ -329,35 +309,16 @@ export default function CmdKSearch() {
<span>{source.label}</span>
</div>
- {visible.map((result) => {
- const currentIdx = flatIdx++;
- const isFocused = focusedIndex === currentIdx;
- return (
- <div
- key={result.id}
- ref={(el) => { resultRefs.current[currentIdx] = el; }}
- onClick={() => dispatchCommand({ kind: 'search', ...result })}
- className={`flex items-start gap-3 px-3 py-2 rounded-lg cursor-pointer transition-colors ${
- isFocused ? 'bg-port-accent/10' : 'hover:bg-white/5'
- }`}
- role="option"
- aria-selected={isFocused}
- >
- <div className="flex-1 min-w-0">
- <p className="text-sm font-medium text-white truncate">{result.title}</p>
- {result.snippet && (
- <p className="text-xs text-gray-400 truncate mt-0.5">
- <Highlight text={result.snippet} query={query} />
- </p>
- )}
- </div>
- </div>
- );
- })}
+ {visible.map((result) =>
+ renderRow(
+ { ...result, kind: 'search' },
+ { title: result.title, subtitle: result.snippet }
+ )
+ )}
{hasMore && (
<button
- onClick={() => setExpandedSources((prev) => new Set([...prev, source.id]))}
+ onClick={() => setExpandedSources((prev) => new Set(prev).add(source.id))}
className="text-xs text-port-accent px-3 py-1 hover:underline"
>
Show {source.results.length - 3} more
diff --git a/server/lib/navManifest.js b/server/lib/navManifest.js
index 611f98e1d4..7f21b8d669 100644
--- a/server/lib/navManifest.js
+++ b/server/lib/navManifest.js
@@ -1,24 +1,9 @@
-// Single source of truth for PortOS navigation commands.
-//
-// Consumed by:
-// - server/services/voice/tools.js#ui_navigate (voice agent resolves "take me to tasks")
-// - server/routes/palette.js (Cmd+K palette fetches the manifest)
-// - client/src/components/CmdKSearch.jsx (renders nav commands in the palette)
-//
-// Adding a page to the sidebar? Add an entry here first; voice + palette pick it up automatically.
-//
-// Entry shape:
-// { id, path, label, section, aliases?: string[], keywords?: string[] }
-//
-// - id: stable machine identifier ("nav.brain.inbox"); used by the palette + action dispatch.
-// - path: exact route the client router resolves.
-// - label: human-readable name shown in the palette.
-// - section: grouping label; matches the sidebar section so the palette and sidebar agree on structure.
-// - aliases: short spoken/typed tokens the user is likely to say ("inbox", "cos", "twin"). Fuzzy matcher tries exact alias first.
-// - keywords: extra terms for the palette's in-UI fuzzy search (synonyms, context words).
+// Single source of truth for PortOS navigation. Consumed by
+// server/services/voice/tools.js#ui_navigate and the Cmd+K palette.
+// Entry: { id, path, label, section, aliases?, keywords? }. See CLAUDE.md
+// "Command Palette & Voice Nav" for the contract.
export const NAV_COMMANDS = [
- // ── Main (sidebar singletons) ─────────────────────────────────────────
{ id: 'nav.dashboard', path: '/', label: 'Dashboard', section: 'Main', aliases: ['dashboard', 'home'], keywords: ['overview', 'start'] },
{ id: 'nav.review-hub', path: '/review', label: 'Review Hub', section: 'Main', aliases: ['review', 'review-hub'] },
{ id: 'nav.cybercity', path: '/city', label: 'CyberCity', section: 'Main', aliases: ['city', 'cybercity'], keywords: ['3d', 'visualization'] },
@@ -34,7 +19,6 @@ export const NAV_COMMANDS = [
{ id: 'nav.instances', path: '/instances', label: 'Instances', section: 'Main', aliases: ['instances'] },
{ id: 'nav.loops', path: '/loops', label: 'Loops', section: 'Main', aliases: ['loops'] },
- // ── Brain ─────────────────────────────────────────────────────────────
{ id: 'nav.brain.inbox', path: '/brain/inbox', label: 'Inbox', section: 'Brain', aliases: ['brain', 'brain-inbox', 'inbox'] },
{ id: 'nav.brain.config', path: '/brain/config', label: 'Config', section: 'Brain', aliases: ['brain-config'] },
{ id: 'nav.brain.daily-log', path: '/brain/daily-log', label: 'Daily Log', section: 'Brain', aliases: ['daily-log', 'journal'] },
@@ -45,7 +29,6 @@ export const NAV_COMMANDS = [
{ id: 'nav.brain.notes', path: '/brain/notes', label: 'Notes', section: 'Brain', aliases: ['brain-notes', 'notes'] },
{ id: 'nav.brain.trust', path: '/brain/trust', label: 'Trust', section: 'Brain', aliases: ['brain-trust'] },
- // ── Calendar ──────────────────────────────────────────────────────────
{ id: 'nav.calendar.agenda', path: '/calendar/agenda', label: 'Agenda', section: 'Calendar', aliases: ['calendar', 'agenda'] },
{ id: 'nav.calendar.config', path: '/calendar/config', label: 'Config', section: 'Calendar', aliases: ['calendar-config'] },
{ id: 'nav.calendar.day', path: '/calendar/day', label: 'Day', section: 'Calendar', aliases: ['calendar-day'] },
@@ -55,7 +38,6 @@ export const NAV_COMMANDS = [
{ id: 'nav.calendar.review', path: '/calendar/review', label: 'Review', section: 'Calendar', aliases: ['calendar-review'] },
{ id: 'nav.calendar.sync', path: '/calendar/sync', label: 'Sync', section: 'Calendar', aliases: ['calendar-sync'] },
- // ── Chief of Staff ────────────────────────────────────────────────────
{ id: 'nav.cos.tasks', path: '/cos/tasks', label: 'Tasks', section: 'Chief of Staff', aliases: ['tasks', 'cos', 'cos-tasks', 'chief-of-staff'] },
{ id: 'nav.cos.agents', path: '/cos/agents', label: 'Agents', section: 'Chief of Staff', aliases: ['agents', 'cos-agents'] },
{ id: 'nav.cos.briefing', path: '/cos/briefing', label: 'Briefing', section: 'Chief of Staff', aliases: ['briefing', 'cos-briefing'] },
@@ -70,7 +52,6 @@ export const NAV_COMMANDS = [
{ id: 'nav.cos.productivity', path: '/cos/productivity', label: 'Streaks', section: 'Chief of Staff', aliases: ['streaks', 'cos-productivity'] },
{ id: 'nav.cos.jobs', path: '/cos/jobs', label: 'System Tasks', section: 'Chief of Staff', aliases: ['cos-jobs', 'system-tasks'] },
- // ── Dev Tools ─────────────────────────────────────────────────────────
{ id: 'nav.devtools.runs', path: '/devtools/runs', label: 'AI Runs', section: 'Dev Tools', aliases: ['ai-runs', 'devtools'] },
{ id: 'nav.devtools.agents', path: '/devtools/agents', label: 'AI Agents', section: 'Dev Tools', aliases: ['ai-agents'] },
{ id: 'nav.devtools.runner', path: '/devtools/runner', label: 'Code', section: 'Dev Tools', aliases: ['devtools-runner'] },
@@ -84,7 +65,6 @@ export const NAV_COMMANDS = [
{ id: 'nav.devtools.usage', path: '/devtools/usage', label: 'Usage', section: 'Dev Tools', aliases: ['devtools-usage'] },
{ id: 'nav.feature-agents', path: '/feature-agents', label: 'Feature Agents', section: 'Dev Tools', aliases: ['feature-agents'] },
- // ── Digital Twin ──────────────────────────────────────────────────────
{ id: 'nav.twin.overview', path: '/digital-twin/overview', label: 'Overview', section: 'Digital Twin', aliases: ['digital-twin', 'twin'] },
{ id: 'nav.twin.accounts', path: '/digital-twin/accounts', label: 'Accounts', section: 'Digital Twin', aliases: ['twin-accounts'] },
{ id: 'nav.twin.autobiography', path: '/digital-twin/autobiography', label: 'Autobiography', section: 'Digital Twin', aliases: ['twin-autobiography', 'autobiography'] },
@@ -98,7 +78,6 @@ export const NAV_COMMANDS = [
{ id: 'nav.twin.taste', path: '/digital-twin/taste', label: 'Taste', section: 'Digital Twin', aliases: ['twin-taste'] },
{ id: 'nav.twin.test', path: '/digital-twin/test', label: 'Test', section: 'Digital Twin', aliases: ['twin-test'] },
- // ── MeatSpace ─────────────────────────────────────────────────────────
{ id: 'nav.meatspace.overview', path: '/meatspace/overview', label: 'Overview', section: 'MeatSpace', aliases: ['meatspace'] },
{ id: 'nav.meatspace.health', path: '/meatspace/health', label: 'Health', section: 'MeatSpace', aliases: ['meatspace-health', 'health'] },
{ id: 'nav.meatspace.body', path: '/meatspace/body', label: 'Body', section: 'MeatSpace', aliases: ['meatspace-body', 'body'] },
@@ -110,20 +89,17 @@ export const NAV_COMMANDS = [
{ id: 'nav.meatspace.lifestyle', path: '/meatspace/lifestyle', label: 'Lifestyle', section: 'MeatSpace', aliases: ['meatspace-lifestyle', 'lifestyle'] },
{ id: 'nav.meatspace.settings', path: '/meatspace/settings', label: 'Settings', section: 'MeatSpace', aliases: ['meatspace-settings'] },
- // ── Messages ──────────────────────────────────────────────────────────
{ id: 'nav.messages.inbox', path: '/messages/inbox', label: 'Inbox', section: 'Messages', aliases: ['messages'] },
{ id: 'nav.messages.drafts', path: '/messages/drafts', label: 'Drafts', section: 'Messages', aliases: ['drafts'] },
{ id: 'nav.messages.config', path: '/messages/config', label: 'Config', section: 'Messages', aliases: ['messages-config'] },
{ id: 'nav.messages.sync', path: '/messages/sync', label: 'Sync', section: 'Messages', aliases: ['messages-sync'] },
- // ── POST ──────────────────────────────────────────────────────────────
{ id: 'nav.post.launcher', path: '/post/launcher', label: 'Launcher', section: 'POST', aliases: ['post', 'post-launcher'] },
{ id: 'nav.post.config', path: '/post/config', label: 'Config', section: 'POST', aliases: ['post-config'] },
{ id: 'nav.post.history', path: '/post/history', label: 'History', section: 'POST', aliases: ['post-history'] },
{ id: 'nav.post.memory', path: '/post/memory', label: 'Memory', section: 'POST', aliases: ['post-memory'] },
{ id: 'nav.post.wordplay', path: '/post/wordplay', label: 'Wordplay', section: 'POST', aliases: ['post-wordplay'] },
- // ── Settings ──────────────────────────────────────────────────────────
{ id: 'nav.settings.backup', path: '/settings/backup', label: 'Backup', section: 'Settings', aliases: ['settings', 'backup'] },
{ id: 'nav.settings.database', path: '/settings/database', label: 'Database', section: 'Settings', aliases: ['settings-database', 'database'] },
{ id: 'nav.settings.image-gen', path: '/settings/image-gen', label: 'Image Gen', section: 'Settings', aliases: ['image-gen'] },
@@ -134,7 +110,6 @@ export const NAV_COMMANDS = [
{ id: 'nav.security', path: '/security', label: 'Security', section: 'Settings', aliases: ['security'] },
{ id: 'nav.uploads', path: '/uploads', label: 'Uploads', section: 'Settings', aliases: ['uploads'] },
- // ── Wiki ──────────────────────────────────────────────────────────────
{ id: 'nav.wiki.overview', path: '/wiki/overview', label: 'Overview', section: 'Wiki', aliases: ['wiki'] },
{ id: 'nav.wiki.browse', path: '/wiki/browse', label: 'Browse', section: 'Wiki', aliases: ['wiki-browse'] },
{ id: 'nav.wiki.graph', path: '/wiki/graph', label: 'Graph', section: 'Wiki', aliases: ['wiki-graph'] },
@@ -142,10 +117,7 @@ export const NAV_COMMANDS = [
{ id: 'nav.wiki.search', path: '/wiki/search', label: 'Search', section: 'Wiki', aliases: ['wiki-search'] },
];
-// Fail-fast: every entry must be syntactically well-formed. Catches typos at
-// server boot instead of on first user interaction. The voice agent used to
-// silently fail when NAV_PAGES and Layout.jsx drifted — this guard is why the
-// manifest is the single source.
+const seenIds = new Set();
for (const cmd of NAV_COMMANDS) {
if (!cmd.id || !cmd.path || !cmd.label || !cmd.section) {
throw new Error(`navManifest: malformed entry ${JSON.stringify(cmd)}`);
@@ -153,46 +125,33 @@ for (const cmd of NAV_COMMANDS) {
if (!cmd.path.startsWith('/')) {
throw new Error(`navManifest: path must start with / — got "${cmd.path}" for ${cmd.id}`);
}
-}
-{
- const seen = new Set();
- for (const cmd of NAV_COMMANDS) {
- if (seen.has(cmd.id)) throw new Error(`navManifest: duplicate id ${cmd.id}`);
- seen.add(cmd.id);
- }
+ if (seenIds.has(cmd.id)) throw new Error(`navManifest: duplicate id ${cmd.id}`);
+ seenIds.add(cmd.id);
}
-// Pre-compute { alias → path } for the voice agent. Alias collisions resolve
-// to the first entry that declared them — order matters in NAV_COMMANDS.
+// Alias collisions resolve to the first-declared entry; ordering is load-bearing.
const aliasToPath = {};
for (const cmd of NAV_COMMANDS) {
for (const alias of (cmd.aliases || [])) {
if (!aliasToPath[alias]) aliasToPath[alias] = cmd.path;
}
}
+const ALIAS_KEYS = Object.keys(aliasToPath);
export const getNavAliasMap = () => ({ ...aliasToPath });
-const normalizeLabel = (s) => (s || '')
+export const normalizeLabel = (s) => (s || '')
.toLowerCase()
.replace(/\s+/g, ' ')
.trim()
.replace(/[.!?:;,"']+$/, '');
-// Fuzzy nav resolver — shared by voice `ui_navigate` and the palette API.
-// Returns { path, matched, command } or null. The matcher is forgiving:
-// exact → user-input-starts-with-alias → alias-starts-with-input → trailing
-// token → substring. This is the same tiered search the voice agent has used
-// successfully; extracting it here means future refinements flow to both.
export const resolveNavCommand = (input) => {
if (!input || typeof input !== 'string') return null;
const norm = normalizeLabel(input).replace(/\s+/g, '-');
if (!norm) return null;
- const aliases = Object.keys(aliasToPath);
const tail = norm.split('-').filter(Boolean).pop();
-
- // Tiered alias match, ordered from strictest to loosest.
const tiers = [
(a) => a === norm,
(a) => norm.startsWith(a) && a.length >= 3,
@@ -205,7 +164,7 @@ export const resolveNavCommand = (input) => {
let matched = null;
for (const test of tiers) {
- matched = aliases.find(test);
+ matched = ALIAS_KEYS.find(test);
if (matched) break;
}
if (!matched) return null;
diff --git a/server/lib/navManifest.test.js b/server/lib/navManifest.test.js
index 3ced81f46f..245814581b 100644
--- a/server/lib/navManifest.test.js
+++ b/server/lib/navManifest.test.js
@@ -59,8 +59,12 @@ describe('getNavAliasMap — voice-agent compatibility', () => {
expect(map.twin).toBe('/digital-twin/overview');
});
- it('preserves first-declared alias on collision', () => {
- // "inbox" appears under Brain first and Messages second; Brain wins.
- expect(getNavAliasMap().inbox).toBe('/brain/inbox');
+ it('has no alias collisions (first-declared-wins guarantees deterministic resolution if any are introduced)', () => {
+ const counts = {};
+ for (const cmd of NAV_COMMANDS) {
+ for (const a of (cmd.aliases || [])) counts[a] = (counts[a] || 0) + 1;
+ }
+ const collisions = Object.entries(counts).filter(([, n]) => n > 1);
+ expect(collisions).toEqual([]);
});
});
diff --git a/server/routes/palette.js b/server/routes/palette.js
index 53a261dfc3..d1783e4289 100644
--- a/server/routes/palette.js
+++ b/server/routes/palette.js
@@ -1,14 +1,13 @@
/**
* Command Palette Routes
*
- * Feeds the client-side Cmd+K palette and exposes a narrow set of voice-agent
- * tools via HTTP so the palette can invoke them without re-implementing the
- * logic. This is the DRY backbone: navigation + actions have one source of
- * truth (navManifest.js + voice/tools.js), and the palette + voice agent are
- * two consumers of the same registry.
+ * GET /api/palette/manifest → { nav, actions }
+ * POST /api/palette/action/:id → dispatches a palette-safe voice tool
*
- * GET /api/palette/manifest → { nav: [...], actions: [...] }
- * POST /api/palette/action/:id → dispatches a palette-safe tool
+ * Navigation + actions share their source with the voice agent (navManifest +
+ * voice/tools.js). Adding a palette action: whitelist its id below with a
+ * label + section; description/parameters hydrate from the voice tool
+ * registry automatically.
*/
import { Router } from 'express';
@@ -16,57 +15,52 @@ import { z } from 'zod';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
import { validateRequest } from '../lib/validation.js';
import { NAV_COMMANDS } from '../lib/navManifest.js';
-import { dispatchTool, getToolSpecs } from '../services/voice/tools.js';
+import { dispatchTool, getToolMetadata } from '../services/voice/tools.js';
const router = Router();
-// Palette-safe subset of voice tools. Excluded: ui_* (they drive the DOM from
-// within the voice agent's live context; from the palette we'd have no target
-// surface), dictation toggles (mode state that belongs to the voice widget),
-// and daily_log_open (pushes a sideEffect the HTTP caller can't consume).
-// pm2_restart is included but marked destructive so the client confirms.
+// Palette-safe subset of voice tools. Excluded: ui_* (need a live voice DOM
+// context), dictation toggles (voice-widget state), daily_log_open (pushes a
+// sideEffect HTTP callers can't consume). pm2_restart is flagged destructive
+// so the client can confirm.
const PALETTE_ACTIONS = [
- { id: 'brain_capture', label: 'Capture to Brain', section: 'Brain', hint: 'Capture a thought' },
- { id: 'brain_search', label: 'Search Brain', section: 'Brain' },
- { id: 'brain_list_recent', label: 'Recent Brain entries', section: 'Brain' },
- { id: 'goal_list', label: 'List goals', section: 'Goals' },
- { id: 'goal_update_progress', label: 'Update goal progress', section: 'Goals' },
- { id: 'goal_log_note', label: 'Log note on goal', section: 'Goals' },
- { id: 'meatspace_log_drink', label: 'Log a drink', section: 'Health' },
- { id: 'meatspace_log_nicotine',label: 'Log nicotine', section: 'Health' },
- { id: 'meatspace_log_weight', label: 'Log weight', section: 'Health' },
- { id: 'meatspace_summary_today', label: "Today's health summary", section: 'Health' },
- { id: 'feeds_digest', label: 'Feed digest', section: 'Feeds' },
- { id: 'pm2_status', label: 'PM2 status', section: 'System' },
- { id: 'pm2_restart', label: 'Restart a PM2 process', section: 'System', destructive: true },
- { id: 'daily_log_read', label: "Read today's log", section: 'Brain' },
- { id: 'daily_log_append', label: 'Append to daily log', section: 'Brain' },
- { id: 'time_now', label: 'Current time', section: 'System' },
+ { id: 'brain_capture', label: 'Capture to Brain', section: 'Brain' },
+ { id: 'brain_search', label: 'Search Brain', section: 'Brain' },
+ { id: 'brain_list_recent', label: 'Recent Brain entries', section: 'Brain' },
+ { id: 'goal_list', label: 'List goals', section: 'Goals' },
+ { id: 'goal_update_progress', label: 'Update goal progress', section: 'Goals' },
+ { id: 'goal_log_note', label: 'Log note on goal', section: 'Goals' },
+ { id: 'meatspace_log_drink', label: 'Log a drink', section: 'Health' },
+ { id: 'meatspace_log_nicotine', label: 'Log nicotine', section: 'Health' },
+ { id: 'meatspace_log_weight', label: 'Log weight', section: 'Health' },
+ { id: 'meatspace_summary_today', label: "Today's health summary", section: 'Health' },
+ { id: 'feeds_digest', label: 'Feed digest', section: 'Feeds' },
+ { id: 'pm2_status', label: 'PM2 status', section: 'System' },
+ { id: 'pm2_restart', label: 'Restart a PM2 process', section: 'System', destructive: true },
+ { id: 'daily_log_read', label: "Read today's log", section: 'Brain' },
+ { id: 'daily_log_append', label: 'Append to daily log', section: 'Brain' },
+ { id: 'time_now', label: 'Current time', section: 'System' },
];
const PALETTE_ACTION_IDS = new Set(PALETTE_ACTIONS.map((a) => a.id));
-// Enrich action metadata with live schema from the voice tool registry. The
-// palette fuzzy-matches on the description the LLM sees; lifting it from the
-// same source keeps palette and voice hints in sync.
-const buildActionManifest = () => {
- const specs = getToolSpecs();
- const byName = Object.fromEntries(specs.map((s) => [s.function.name, s.function]));
- return PALETTE_ACTIONS.map((a) => {
- const fn = byName[a.id];
+// Computed once at module load — the nav manifest and voice tool registry
+// are both module-scoped and do not change at runtime.
+const MANIFEST = Object.freeze({
+ nav: NAV_COMMANDS,
+ actions: PALETTE_ACTIONS.map((a) => {
+ const meta = getToolMetadata(a.id);
return {
...a,
- description: fn?.description || '',
- parameters: fn?.parameters || { type: 'object', properties: {} },
+ description: meta?.description || '',
+ parameters: meta?.parameters || { type: 'object', properties: {} },
};
- });
-};
+ }),
+});
router.get('/manifest', asyncHandler(async (_req, res) => {
- res.json({
- nav: NAV_COMMANDS,
- actions: buildActionManifest(),
- });
+ res.set('Cache-Control', 'private, max-age=300');
+ res.json(MANIFEST);
}));
const actionBodySchema = z.object({
@@ -79,12 +73,7 @@ router.post('/action/:id', asyncHandler(async (req, res) => {
throw new ServerError(`Unknown palette action "${id}"`, { status: 404 });
}
const { args } = validateRequest(actionBodySchema, req.body ?? {});
- // Palette calls are fire-and-forget for side effects — we don't have a
- // live voice context, so UI-driving sideEffects (navigate/dictation) that
- // some tools push would be lost. The whitelist above already excludes the
- // tools that rely on them; passing a throwaway buffer here is defensive.
- const ctx = { sideEffects: [] };
- const result = await dispatchTool(id, args, ctx);
+ const result = await dispatchTool(id, args, { sideEffects: [] });
res.json({ ok: result?.ok !== false, result });
}));
diff --git a/server/services/voice/tools.js b/server/services/voice/tools.js
index 1aff381f5c..c8b3a19cd4 100644
--- a/server/services/voice/tools.js
+++ b/server/services/voice/tools.js
@@ -11,7 +11,7 @@ import { listProcesses, restartApp } from '../pm2.js';
import { getItems, getFeeds } from '../feeds.js';
import { getUserTimezone, todayInTimezone, getLocalParts } from '../../lib/timezone.js';
import * as journal from '../brainJournal.js';
-import { resolveNavCommand } from '../../lib/navManifest.js';
+import { resolveNavCommand, normalizeLabel } from '../../lib/navManifest.js';
const DAILY_LOG_PATH = '/brain/daily-log';
@@ -104,11 +104,6 @@ for (const [name, group] of Object.entries(TOOL_GROUPS)) {
}
}
-const normalizeLabel = (s) => (s || '')
- .toLowerCase()
- .replace(/\s+/g, ' ')
- .trim()
- .replace(/[.!?:;,"']+$/, '');
// Accepts one kind OR an array of kinds for multi-kind tools like ui_fill
// (input|textarea) and ui_check (checkbox|radio). The error pool and label
@@ -921,6 +916,15 @@ const toSpec = (t) => ({
export const getToolSpecs = () => TOOLS.map(toSpec);
+// Plain-format metadata for non-LLM consumers (the command palette) so routes
+// don't need to reach through OpenAI-shaped function specs to get to the same
+// fields. Shape-independent from getToolSpecs.
+export const getToolMetadata = (id) => {
+ const tool = TOOLS.find((t) => t.name === id);
+ if (!tool) return null;
+ return { id: tool.name, description: tool.description, parameters: tool.parameters };
+};
+
// Intent-filtered spec list. Pass the user's current utterance; returns the
// filtered spec array PLUS the set of active groups so downstream consumers
// (pipeline.js → shouldIncludeUi) don't have to re-run the same regexes.