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

feat: show recent destinations in command palette

[._.]/ Adam Eivy416df4620c3b
diff --git a/client/src/components/CmdKSearch.jsx b/client/src/components/CmdKSearch.jsx
index 0d52c05ed9..8f408b1627 100644
--- a/client/src/components/CmdKSearch.jsx
+++ b/client/src/components/CmdKSearch.jsx
@@ -1,6 +1,6 @@
import { useState, useEffect, useRef, useCallback, useMemo } from 'react';
import { createPortal } from 'react-dom';
-import { useNavigate } from 'react-router-dom';
+import { useLocation, useNavigate } from 'react-router-dom';
import { Brain, Cpu, Package, History, HeartPulse, Search, Loader2, Navigation, Play, LayoutGrid, BookMarked } from 'lucide-react';
import { useCmdKSearch } from '../hooks/useCmdKSearch';
import { useScrollLock } from '../hooks/useScrollLock';
@@ -9,6 +9,8 @@ import toast from './ui/Toast';
import { modKey } from '../utils/platform';
import { DASHBOARD_LAYOUT_CHANGED } from '../constants/events.js';
import { recordManualLayoutPick } from '../utils/timeWindow.js';
+import { RECENT_KEY, RECENT_CAP, resolveRecentNavEntries } from '../utils/navWorkingSet.js';
+import { safeReadJsonStorage } from '../lib/safeStorage.js';
const ICON_MAP = { Brain, Cpu, Package, History, HeartPulse };
@@ -62,6 +64,7 @@ const DEFAULT_ACTION_IDS = new Set(['brain_capture', 'time_now', 'goal_list', 'm
export default function CmdKSearch() {
const { open, setOpen } = useCmdKSearch();
const navigate = useNavigate();
+ const location = useLocation();
const inputRef = useRef(null);
const [query, setQuery] = useState('');
@@ -71,6 +74,7 @@ export default function CmdKSearch() {
const [loading, setLoading] = useState(false);
const [focusedIndex, setFocusedIndex] = useState(0);
const [expandedSources, setExpandedSources] = useState(new Set());
+ const [recentPaths, setRecentPaths] = useState([]);
const resultRefs = useRef([]);
useEffect(() => {
@@ -79,6 +83,13 @@ export default function CmdKSearch() {
useScrollLock(open);
+ // Layout records every route visit in the shared sidebar working set. Refresh
+ // from storage on each open so the palette reflects navigation that happened
+ // since its previous use without owning a second history store.
+ useEffect(() => {
+ if (open) setRecentPaths(safeReadJsonStorage(RECENT_KEY, []));
+ }, [open]);
+
useEffect(() => {
if (!open) {
setQuery('');
@@ -186,12 +197,21 @@ export default function CmdKSearch() {
}, [searchResults, catalogResults, query]);
const combined = useMemo(() => {
- if (!manifest) return { nav: [], actions: [], layouts: [], commandCount: 0 };
+ if (!manifest) return { recentNav: [], nav: [], actions: [], layouts: [], commandCount: 0 };
const q = query.trim().toLowerCase();
if (!q) {
- const nav = manifest.nav.filter((c) => DEFAULT_NAV_IDS.has(c.id)).map((c) => ({ ...c, kind: 'nav' }));
+ const recentNav = resolveRecentNavEntries(recentPaths, manifest.nav, {
+ currentPath: location.pathname,
+ limit: RECENT_CAP,
+ }).map((c) => ({ ...c, kind: 'nav' }));
+ const recentIds = new Set(recentNav.map((c) => c.id));
+ const fallbackLimit = Math.max(0, RECENT_CAP - recentNav.length);
+ const nav = manifest.nav
+ .filter((c) => DEFAULT_NAV_IDS.has(c.id) && !recentIds.has(c.id) && c.path !== location.pathname)
+ .slice(0, fallbackLimit)
+ .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, layouts: [], commandCount: nav.length + actions.length };
+ return { recentNav, nav, actions, layouts: [], commandCount: recentNav.length + nav.length + actions.length };
}
const rank = (items, max) => items
.map((c) => ({ cmd: c, score: scoreCommand(c, q) }))
@@ -202,8 +222,8 @@ export default function CmdKSearch() {
const nav = rank(manifest.nav, 8).map((c) => ({ ...c, kind: 'nav' }));
const actions = rank(manifest.actions, 5).map((a) => ({ ...a, kind: 'action' }));
const layouts = rank(manifest.layouts || [], 5).map((l) => ({ ...l, kind: 'layout' }));
- return { nav, actions, layouts, commandCount: nav.length + actions.length + layouts.length };
- }, [manifest, query]);
+ return { recentNav: [], nav, actions, layouts, commandCount: nav.length + actions.length + layouts.length };
+ }, [manifest, query, recentPaths, location.pathname]);
const flatSearchResults = useMemo(
() => searchResults.flatMap((source) => {
@@ -225,7 +245,7 @@ export default function CmdKSearch() {
);
const focusable = useMemo(
- () => [...combined.nav, ...combined.actions, ...combined.layouts, ...catalogHits, ...flatSearchResults],
+ () => [...combined.recentNav, ...combined.nav, ...combined.actions, ...combined.layouts, ...catalogHits, ...flatSearchResults],
[combined, catalogHits, flatSearchResults]
);
@@ -296,7 +316,7 @@ export default function CmdKSearch() {
const isFocused = focusedIndex === currentIdx;
return (
<div
- key={`${item.kind}:${item.id ?? item.sourceId + ':' + title}`}
+ key={`${item.kind}:${item.path ?? 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 ${
@@ -360,6 +380,14 @@ export default function CmdKSearch() {
</div>
<div className="max-h-96 overflow-y-auto p-2">
+ {renderGroup(
+ <History size={14} />,
+ 'Recent destinations',
+ combined.recentNav.map((c) =>
+ renderRow(c, { icon: History, title: c.label, subtitle: `${c.section} · ${c.path}`, badge: 'RECENT' })
+ )
+ )}
+
{renderGroup(
<Navigation size={14} />,
'Go to',
diff --git a/client/src/components/CmdKSearch.test.jsx b/client/src/components/CmdKSearch.test.jsx
new file mode 100644
index 0000000000..1ff7bf7b22
--- /dev/null
+++ b/client/src/components/CmdKSearch.test.jsx
@@ -0,0 +1,70 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { act, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
+import { MemoryRouter, useLocation } from 'react-router-dom';
+import { RECENT_KEY } from '../utils/navWorkingSet.js';
+
+const getPaletteManifest = vi.fn();
+const getDashboardLayouts = vi.fn();
+
+vi.mock('../services/api', () => ({
+ search: vi.fn(() => Promise.resolve({ sources: [] })),
+ getPaletteManifest: (...args) => getPaletteManifest(...args),
+ runPaletteAction: vi.fn(() => Promise.resolve({ ok: true })),
+ getDashboardLayouts: (...args) => getDashboardLayouts(...args),
+ setActiveDashboardLayout: vi.fn(() => Promise.resolve()),
+ listCatalogIngredients: vi.fn(() => Promise.resolve({ items: [] })),
+}));
+
+import CmdKSearch from './CmdKSearch.jsx';
+
+const NAV = [
+ { id: 'nav.dashboard', path: '/', label: 'Dashboard', section: 'Home', aliases: [], keywords: [] },
+ { id: 'nav.apps', path: '/apps', label: 'Apps', section: 'System', aliases: [], keywords: [] },
+ { id: 'nav.brain.inbox', path: '/brain/inbox', label: 'Brain Inbox', section: 'Brain', aliases: [], keywords: [] },
+ { id: 'nav.goals', path: '/goals', label: 'Goals', section: 'Life', aliases: [], keywords: [] },
+ { id: 'nav.current', path: '/current', label: 'Current Page', section: 'Test', aliases: [], keywords: [] },
+];
+
+function LocationProbe() {
+ const location = useLocation();
+ return <output data-testid="location">{location.pathname}</output>;
+}
+
+beforeEach(() => {
+ getPaletteManifest.mockResolvedValue({ nav: NAV, actions: [] });
+ getDashboardLayouts.mockResolvedValue({ layouts: [] });
+ HTMLElement.prototype.scrollIntoView = vi.fn();
+});
+
+describe('CmdKSearch recent destinations', () => {
+ it('leads with shared nav history, resolves deep links, and fills with non-duplicate defaults', async () => {
+ localStorage.setItem(RECENT_KEY, JSON.stringify([
+ '/current',
+ '/apps/example-app',
+ '/brain/inbox',
+ '/stale-route',
+ ]));
+
+ render(
+ <MemoryRouter initialEntries={['/current']}>
+ <CmdKSearch />
+ <LocationProbe />
+ </MemoryRouter>,
+ );
+
+ fireEvent.keyDown(document, { key: 'k', metaKey: true });
+ await screen.findByText('Recent destinations');
+ await act(async () => {});
+
+ const options = screen.getAllByRole('option');
+ expect(within(options[0]).getByText('Apps')).toBeInTheDocument();
+ expect(within(options[0]).getByText(/\/apps\/example-app/)).toBeInTheDocument();
+ expect(within(options[1]).getByText('Brain Inbox')).toBeInTheDocument();
+ expect(screen.getAllByText('Brain Inbox')).toHaveLength(1);
+ expect(screen.queryByText('Current Page')).not.toBeInTheDocument();
+ expect(screen.getByText('Dashboard')).toBeInTheDocument();
+
+ fireEvent.click(options[0]);
+ await waitFor(() => expect(screen.getByTestId('location')).toHaveTextContent('/apps/example-app'));
+ });
+});
diff --git a/client/src/hooks/useCitySettings.test.jsx b/client/src/hooks/useCitySettings.test.jsx
index 0c7837139f..c828736e78 100644
--- a/client/src/hooks/useCitySettings.test.jsx
+++ b/client/src/hooks/useCitySettings.test.jsx
@@ -11,7 +11,7 @@ afterEach(() => {
describe('useCitySettings localStorage resilience', () => {
it('initializes to defaults when reads throw (blocked storage)', () => {
- vi.spyOn(window.localStorage.__proto__, 'getItem').mockImplementation(() => {
+ vi.spyOn(window.localStorage, 'getItem').mockImplementation(() => {
throw new DOMException('The operation is insecure.', 'SecurityError');
});
@@ -33,7 +33,7 @@ describe('useCitySettings localStorage resilience', () => {
});
it('keeps in-memory setting updates working when writes throw', () => {
- vi.spyOn(window.localStorage.__proto__, 'setItem').mockImplementation(() => {
+ vi.spyOn(window.localStorage, 'setItem').mockImplementation(() => {
throw new DOMException('QuotaExceededError', 'QuotaExceededError');
});
@@ -54,7 +54,7 @@ describe('useCitySettings localStorage resilience', () => {
// This is the listener fired by useTheme.setTheme; with storage blocked its
// write must not surface an unhandled error on the theme-switch path.
window.localStorage.setItem(STORAGE_KEY, JSON.stringify({ timeOfDay: 'night' }));
- vi.spyOn(window.localStorage.__proto__, 'setItem').mockImplementation(() => {
+ vi.spyOn(window.localStorage, 'setItem').mockImplementation(() => {
throw new DOMException('QuotaExceededError', 'QuotaExceededError');
});
diff --git a/client/src/hooks/useNavWorkingSet.js b/client/src/hooks/useNavWorkingSet.js
index 816e5ac0f1..a622cc40c8 100644
--- a/client/src/hooks/useNavWorkingSet.js
+++ b/client/src/hooks/useNavWorkingSet.js
@@ -4,28 +4,17 @@ import {
RECENT_KEY, PINNED_KEY,
recordVisit, togglePin as togglePinPure, isPinned as isPinnedPure,
} from '../utils/navWorkingSet.js';
+import { safeReadJsonStorage, safeWriteStorage } from '../lib/safeStorage.js';
// Read a JSON string[] from localStorage, tolerating absent/corrupt/throwing storage.
const readList = (key) => {
- try {
- const raw = localStorage.getItem(key);
- if (!raw) return [];
- const parsed = JSON.parse(raw);
- return Array.isArray(parsed) ? parsed.filter((p) => typeof p === 'string') : [];
- } catch {
- return [];
- }
+ const parsed = safeReadJsonStorage(key, []);
+ return Array.isArray(parsed) ? parsed.filter((p) => typeof p === 'string') : [];
};
// Persist a JSON string[]; ignore storage failures (private mode / quota) so the
// in-memory React state still updates and the app never crashes on a write.
-const writeList = (key, list) => {
- try {
- localStorage.setItem(key, JSON.stringify(list));
- } catch {
- /* storage unavailable (private mode / quota) — keep in-memory state only */
- }
-};
+const writeList = (key, list) => safeWriteStorage(key, JSON.stringify(list));
/**
* Sidebar working-set state (Pinned + Recent), persisted to localStorage.
diff --git a/client/src/hooks/useTheme.test.jsx b/client/src/hooks/useTheme.test.jsx
index b62dc16f06..8ce5be85a0 100644
--- a/client/src/hooks/useTheme.test.jsx
+++ b/client/src/hooks/useTheme.test.jsx
@@ -20,7 +20,7 @@ afterEach(() => {
describe('useTheme localStorage resilience', () => {
it('initializes to the default theme when reads throw (blocked storage)', () => {
- vi.spyOn(window.localStorage.__proto__, 'getItem').mockImplementation(() => {
+ vi.spyOn(window.localStorage, 'getItem').mockImplementation(() => {
throw new DOMException('The operation is insecure.', 'SecurityError');
});
@@ -40,7 +40,7 @@ describe('useTheme localStorage resilience', () => {
});
it('keeps in-memory theme switching functional when writes throw', () => {
- vi.spyOn(window.localStorage.__proto__, 'setItem').mockImplementation(() => {
+ vi.spyOn(window.localStorage, 'setItem').mockImplementation(() => {
throw new DOMException('QuotaExceededError', 'QuotaExceededError');
});
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index 76a125a044..2c938b37d0 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -95,7 +95,7 @@ grep -i "what you want to do" client/src/lib/README.md
| `mediaSearch.js` | `buildMediaHaystack`, `tokenizeQuery`, `matchHaystack`, `filterByQuery` — client-side AND-token search over normalized media items (prompt/model/seed/LoRA/universe tags). Shared by MediaHistory + the Image Gen gallery picker. |
| `moodBoardItemSrc.js` | `moodBoardItemSrc(item)` resolves a mood-board item to a display image src (`imageUrl` → served `image:<file>` bytes → null). Shared by MoodBoardDetail + MoodBoardReferenceStrip. |
| `registerServiceWorker.js` | `registerServiceWorker()` / `unregisterServiceWorkers()` — wires up the offline app-shell + low-bandwidth asset-caching service worker (`public/sw.js`). Registers only in a production secure context (HTTPS or localhost); no-ops over plain-HTTP Tailnet and tears down any stale SW in dev. Called once from `main.jsx`. |
-| `safeStorage.js` | `safeReadStorage` / `safeWriteStorage` / `safeRemoveStorage` — guarded `localStorage` access that swallows throws (Safari private mode, blocked storage) and treats missing storage as absent (`null`). Use instead of touching `localStorage` inline so a storage failure never crashes init or a write path (#2387). Consumed by `useTheme` / `useCitySettings`. |
+| `safeStorage.js` | `safeReadStorage` / `safeReadJsonStorage` / `safeWriteStorage` / `safeRemoveStorage` — guarded `localStorage` access that swallows throws (Safari private mode, blocked storage), with fallback-safe JSON parsing for structured entries. Use instead of touching `localStorage` inline so a storage failure never crashes init or a write path (#2387). Consumed by `useTheme`, `useCitySettings`, `useNavWorkingSet`, and the command palette. |
| `sameJsonShape.js` | `sameJsonShape(prev, next)` — JSON.stringify-based equality for `useAutoRefetch`'s `compare` option on small, deterministically-shaped poll payloads. |
| `sketchCanvas.js` | Pure stroke model + 2D-context renderer for the media annotation canvas (`createStroke`, `appendPoint`, `undoStrokes`, `drawStrokes`, `clampSize`). Points stored in natural-pixel space; erase strokes use `destination-out`. Used by `AnnotationCanvas.jsx` / `MediaAnnotate.jsx` (#2036). |
| `unsorted.js` | Synthetic "Unsorted" collection from media not filed in any real collection. |
diff --git a/client/src/lib/safeStorage.js b/client/src/lib/safeStorage.js
index 5125d67bda..24036a673a 100644
--- a/client/src/lib/safeStorage.js
+++ b/client/src/lib/safeStorage.js
@@ -15,6 +15,19 @@ export const safeReadStorage = (key) => {
}
};
+// Parse a JSON value from storage, returning the caller's fallback for a missing,
+// inaccessible, or corrupt entry. Keeps JSON.parse's exception boundary beside
+// the storage boundary so feature code never needs its own try/catch.
+export const safeReadJsonStorage = (key, fallback = null) => {
+ const raw = safeReadStorage(key);
+ if (raw === null) return fallback;
+ try {
+ return JSON.parse(raw);
+ } catch {
+ return fallback;
+ }
+};
+
// Best-effort write; silently no-ops when storage is unavailable.
export const safeWriteStorage = (key, value) => {
try {
diff --git a/client/src/lib/safeStorage.test.js b/client/src/lib/safeStorage.test.js
index d5e78880be..8356e5c24e 100644
--- a/client/src/lib/safeStorage.test.js
+++ b/client/src/lib/safeStorage.test.js
@@ -1,5 +1,5 @@
import { describe, it, expect, afterEach, vi } from 'vitest';
-import { safeReadStorage, safeWriteStorage, safeRemoveStorage } from './safeStorage.js';
+import { safeReadStorage, safeReadJsonStorage, safeWriteStorage, safeRemoveStorage } from './safeStorage.js';
afterEach(() => {
vi.restoreAllMocks();
@@ -21,17 +21,26 @@ describe('safeStorage', () => {
});
it('returns null instead of throwing when getItem throws', () => {
- vi.spyOn(window.localStorage.__proto__, 'getItem').mockImplementation(() => {
+ vi.spyOn(window.localStorage, 'getItem').mockImplementation(() => {
throw new DOMException('The operation is insecure.', 'SecurityError');
});
expect(safeReadStorage('k')).toBeNull();
});
+ it('reads JSON and returns the supplied fallback for missing or corrupt values', () => {
+ window.localStorage.setItem('valid', JSON.stringify(['/brain/inbox']));
+ window.localStorage.setItem('corrupt', '{not-json');
+
+ expect(safeReadJsonStorage('valid', [])).toEqual(['/brain/inbox']);
+ expect(safeReadJsonStorage('missing', [])).toEqual([]);
+ expect(safeReadJsonStorage('corrupt', [])).toEqual([]);
+ });
+
it('swallows setItem / removeItem throws', () => {
- vi.spyOn(window.localStorage.__proto__, 'setItem').mockImplementation(() => {
+ vi.spyOn(window.localStorage, 'setItem').mockImplementation(() => {
throw new DOMException('QuotaExceededError', 'QuotaExceededError');
});
- vi.spyOn(window.localStorage.__proto__, 'removeItem').mockImplementation(() => {
+ vi.spyOn(window.localStorage, 'removeItem').mockImplementation(() => {
throw new DOMException('QuotaExceededError', 'QuotaExceededError');
});
expect(() => safeWriteStorage('k', 'v')).not.toThrow();
diff --git a/client/src/utils/README.md b/client/src/utils/README.md
index 95be1edfac..d1e686f56a 100644
--- a/client/src/utils/README.md
+++ b/client/src/utils/README.md
@@ -35,7 +35,7 @@ grep -i "what you want to do" client/src/utils/README.md
| `hashString` | Deterministic string → 32-bit hash (stable colors, keys, seeds). |
| `urlNormalize` | `isUrl` detection and `normalizeUrl` (optional git/`requireDot` modes). |
| `platform` | `isMac` detection and `modKey` (⌘/Ctrl) for keyboard-shortcut display. |
-| `navWorkingSet` | Recent/pinned nav persistence in localStorage (`recordVisit`, `togglePin`, `isPinned`). |
+| `navWorkingSet` | Recent/pinned nav persistence (`recordVisit`, `togglePin`, `isPinned`) plus `resolveRecentNavEntries` for mapping stored deep links back to their longest matching nav-manifest entry. |
| `providers` | AI-provider type predicates and helpers (`isCliProvider`, `isApiProvider`, `isCodexProvider`, `filterSelectableModels`, `getProviderTimeout`, configured-default sentinels, and the claude/codex thinking-effort levels — `effortLevelsForProvider`, mirror of server `providerModels.js`). |
| `layeredIntelligenceReasons` | Canonical gloss for the Layered Intelligence loop's run-outcome reason tokens, shared by the on-demand toast and the durable "Last run" line (`formatLiReason`, `liReasonTone`, `LI_NEUTRAL_REASONS`). |
diff --git a/client/src/utils/navWorkingSet.js b/client/src/utils/navWorkingSet.js
index 79ba7071bf..ecb6d38933 100644
--- a/client/src/utils/navWorkingSet.js
+++ b/client/src/utils/navWorkingSet.js
@@ -8,7 +8,7 @@ export const PINNED_KEY = 'portos-nav-pinned';
export const RECENT_CAP = 5;
const asList = (list) => (Array.isArray(list) ? list : []);
-const isPath = (p) => typeof p === 'string' && p.length > 0;
+const isPath = (p) => typeof p === 'string' && /^\/(?!\/)/.test(p);
// Move/insert `path` to the front of the MRU list, dedup, cap at RECENT_CAP.
export const recordVisit = (path, list) => {
@@ -27,3 +27,34 @@ export const togglePin = (path, list) => {
};
export const isPinned = (path, list) => asList(list).includes(path);
+
+// Resolve stored recent paths against the server-backed nav manifest. Exact
+// routes win; deep-link selections fall back to the longest matching base route
+// while preserving the stored destination path for navigation.
+export const resolveRecentNavEntries = (paths, commands, {
+ currentPath = null,
+ limit = RECENT_CAP,
+} = {}) => {
+ const commandList = asList(commands).filter((command) => isPath(command?.path));
+ const seenPaths = new Set();
+ const resolved = [];
+
+ for (const path of asList(paths)) {
+ if (!isPath(path) || path === currentPath || seenPaths.has(path)) continue;
+ seenPaths.add(path);
+
+ let match = null;
+ for (const command of commandList) {
+ const exact = command.path === path;
+ const containsDeepLink = command.path !== '/' && path.startsWith(`${command.path}/`);
+ if ((exact || containsDeepLink) && (!match || command.path.length > match.path.length)) {
+ match = command;
+ }
+ }
+
+ if (match) resolved.push({ ...match, path });
+ if (resolved.length >= limit) break;
+ }
+
+ return resolved;
+};
diff --git a/client/src/utils/navWorkingSet.test.js b/client/src/utils/navWorkingSet.test.js
index b53ddd0d9c..d08dcbd589 100644
--- a/client/src/utils/navWorkingSet.test.js
+++ b/client/src/utils/navWorkingSet.test.js
@@ -1,7 +1,7 @@
import { describe, it, expect } from 'vitest';
import {
RECENT_KEY, PINNED_KEY, RECENT_CAP,
- recordVisit, togglePin, isPinned,
+ recordVisit, togglePin, isPinned, resolveRecentNavEntries,
} from './navWorkingSet.js';
describe('navWorkingSet — constants', () => {
@@ -33,6 +33,8 @@ describe('recordVisit', () => {
expect(recordVisit(null, ['/a'])).toEqual(['/a']);
expect(recordVisit(undefined, ['/a'])).toEqual(['/a']);
expect(recordVisit(42, ['/a'])).toEqual(['/a']);
+ expect(recordVisit('javascript:alert(1)', ['/a'])).toEqual(['/a']);
+ expect(recordVisit('//example.com', ['/a'])).toEqual(['/a']);
});
it('tolerates a non-array current list', () => {
@@ -41,6 +43,32 @@ describe('recordVisit', () => {
});
});
+describe('resolveRecentNavEntries', () => {
+ const commands = [
+ { id: 'nav.dashboard', path: '/', label: 'Dashboard' },
+ { id: 'nav.apps', path: '/apps', label: 'Apps' },
+ { id: 'nav.pipeline', path: '/pipeline', label: 'Pipeline' },
+ { id: 'nav.pipeline.series', path: '/pipeline/series', label: 'Series' },
+ ];
+
+ it('resolves exact paths and preserves deep-link destinations via the longest base route', () => {
+ expect(resolveRecentNavEntries(['/apps/example', '/pipeline/series/series-1', '/'], commands))
+ .toEqual([
+ { ...commands[1], path: '/apps/example' },
+ { ...commands[3], path: '/pipeline/series/series-1' },
+ commands[0],
+ ]);
+ });
+
+ it('skips the current, stale, duplicate, and unsafe paths while honoring the limit', () => {
+ expect(resolveRecentNavEntries(
+ ['/apps', '/missing', '/apps/example', '/apps/example', '//example.com'],
+ commands,
+ { currentPath: '/apps', limit: 1 },
+ )).toEqual([{ ...commands[1], path: '/apps/example' }]);
+ });
+});
+
describe('togglePin / isPinned', () => {
it('adds a path when absent', () => {
expect(togglePin('/a', [])).toEqual(['/a']);