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

test([client-tests-for-deep-routing-drag-smoke-tests-for]): smoke tests for goToWorld URL transitions and chip-reorder ordering

[._.]/ Adam Eivy3bff31041612
diff --git a/client/src/components/universeBuilder/InfluenceChipsInput.test.jsx b/client/src/components/universeBuilder/InfluenceChipsInput.test.jsx
new file mode 100644
index 0000000000..874040835b
--- /dev/null
+++ b/client/src/components/universeBuilder/InfluenceChipsInput.test.jsx
@@ -0,0 +1,133 @@
+import { describe, it, expect, vi } from 'vitest';
+import { render, screen, act } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+
+// `vi.hoisted` so the mock-state lives before the `vi.mock` factories below
+// (Vitest hoists `vi.mock` calls to the top of the file). NOTE: this is
+// module-scoped — if a single test ever renders two `<InfluenceChipsInput>`
+// instances, the last-rendered DndContext wins (later renders overwrite
+// `onDragEnd`). Add a per-render scope if that ever bites.
+const dndState = vi.hoisted(() => ({ onDragEnd: null }));
+
+// Stub @dnd-kit/core's DndContext so we can fire drag-end events imperatively
+// from the test. The real implementation needs DOM measurement + pointer
+// sensors, which jsdom doesn't provide reliably — but the only behavior we
+// care about here is "what does the component do when onDragEnd fires with
+// these ids," and that's all driven through the `onDragEnd` callback we
+// capture below.
+vi.mock('@dnd-kit/core', () => ({
+ DndContext: ({ children, onDragEnd }) => {
+ dndState.onDragEnd = onDragEnd;
+ return <>{children}</>;
+ },
+ KeyboardSensor: function KeyboardSensorStub() {},
+ PointerSensor: function PointerSensorStub() {},
+ closestCenter: () => null,
+ useSensor: () => null,
+ useSensors: () => [],
+}));
+
+// Keep `arrayMove` real (we want the live ordering invariant) but stub
+// `useSortable` so each chip renders without DnD lifecycle wiring.
+vi.mock('@dnd-kit/sortable', async () => {
+ const actual = await vi.importActual('@dnd-kit/sortable');
+ return {
+ ...actual,
+ SortableContext: ({ children }) => <>{children}</>,
+ useSortable: () => ({
+ attributes: {},
+ listeners: {},
+ setNodeRef: () => {},
+ transform: null,
+ transition: null,
+ isDragging: false,
+ }),
+ rectSortingStrategy: 'rect',
+ sortableKeyboardCoordinates: () => null,
+ };
+});
+
+// Imported after the mocks so the component picks them up.
+import InfluenceChipsInput from './InfluenceChipsInput';
+
+const fireDragEnd = (activeId, overId) => act(() => {
+ dndState.onDragEnd({ active: { id: activeId }, over: overId == null ? null : { id: overId } });
+});
+
+describe('InfluenceChipsInput — chip-reorder smoke tests', () => {
+ it('renders the token chips in order', () => {
+ render(<InfluenceChipsInput tokens={['alpha', 'bravo', 'charlie']} onChange={() => {}} />);
+ expect(screen.getByText('alpha')).toBeInTheDocument();
+ expect(screen.getByText('bravo')).toBeInTheDocument();
+ expect(screen.getByText('charlie')).toBeInTheDocument();
+ });
+
+ it('calls onChange with the reordered tokens when a chip moves forward', () => {
+ const onChange = vi.fn();
+ render(<InfluenceChipsInput tokens={['alpha', 'bravo', 'charlie']} onChange={onChange} />);
+
+ // Drag `charlie` over `alpha` → ['charlie', 'alpha', 'bravo']
+ fireDragEnd('charlie', 'alpha');
+
+ expect(onChange).toHaveBeenCalledTimes(1);
+ expect(onChange).toHaveBeenCalledWith(['charlie', 'alpha', 'bravo']);
+ });
+
+ it('calls onChange with the reordered tokens when a chip moves backward', () => {
+ const onChange = vi.fn();
+ render(<InfluenceChipsInput tokens={['alpha', 'bravo', 'charlie']} onChange={onChange} />);
+
+ // Drag `alpha` over `charlie` → ['bravo', 'charlie', 'alpha']
+ fireDragEnd('alpha', 'charlie');
+
+ expect(onChange).toHaveBeenCalledWith(['bravo', 'charlie', 'alpha']);
+ });
+
+ it('does not call onChange when dropped on the same chip (no-op drag)', () => {
+ const onChange = vi.fn();
+ render(<InfluenceChipsInput tokens={['alpha', 'bravo', 'charlie']} onChange={onChange} />);
+
+ fireDragEnd('bravo', 'bravo');
+
+ expect(onChange).not.toHaveBeenCalled();
+ });
+
+ it('does not call onChange when dropped outside any chip (over is null)', () => {
+ const onChange = vi.fn();
+ render(<InfluenceChipsInput tokens={['alpha', 'bravo', 'charlie']} onChange={onChange} />);
+
+ fireDragEnd('alpha', null);
+
+ expect(onChange).not.toHaveBeenCalled();
+ });
+
+ it('does not call onChange when active id is not in the list (stale drag)', () => {
+ const onChange = vi.fn();
+ render(<InfluenceChipsInput tokens={['alpha', 'bravo', 'charlie']} onChange={onChange} />);
+
+ fireDragEnd('ghost', 'bravo');
+
+ expect(onChange).not.toHaveBeenCalled();
+ });
+
+ it('removes a chip via the X button', async () => {
+ const onChange = vi.fn();
+ const user = userEvent.setup();
+ render(<InfluenceChipsInput tokens={['alpha', 'bravo', 'charlie']} onChange={onChange} />);
+
+ await user.click(screen.getByLabelText('Remove bravo'));
+
+ expect(onChange).toHaveBeenCalledWith(['alpha', 'charlie']);
+ });
+
+ it('readOnly mode renders chips without DnD wiring', () => {
+ const onChange = vi.fn();
+ render(<InfluenceChipsInput tokens={['alpha', 'bravo']} onChange={onChange} readOnly />);
+
+ expect(screen.getByText('alpha')).toBeInTheDocument();
+ expect(screen.getByText('bravo')).toBeInTheDocument();
+ // No drag handles, no remove buttons, no input in readOnly mode.
+ expect(screen.queryByLabelText(/Drag alpha to reorder/)).toBeNull();
+ expect(screen.queryByLabelText(/Remove alpha/)).toBeNull();
+ });
+});
diff --git a/client/src/hooks/README.md b/client/src/hooks/README.md
index da5d67ef75..440ccd5192 100644
--- a/client/src/hooks/README.md
+++ b/client/src/hooks/README.md
@@ -95,5 +95,6 @@ grep -i "what you want to do" client/src/hooks/README.md
| `useProviderModels` | AI providers + two-step provider→model selection. | Any UI that picks a provider + model. |
| `useTheme` | Dark/light theme + paired-theme switching. | Theme picker. |
| `useUniverseAction` | LLM-driven universe mutation scaffolding. | Universe Builder action UIs. |
+| `useUniverseNav` | `goToWorld(id)` → navigate to `/universe-builder/:id`, preserve `location.search`. | Any Universe Builder caller that needs to switch worlds via URL. |
| `useVoiceUiSync` | Keeps voice server's UI index in sync with current page. | Wire once at root for voice agent support. |
| `useMoltworldWs` | Moltworld WebSocket feed. | Moltworld surfaces only. |
diff --git a/client/src/hooks/index.js b/client/src/hooks/index.js
index a616399cbb..3e1e309088 100644
--- a/client/src/hooks/index.js
+++ b/client/src/hooks/index.js
@@ -73,4 +73,5 @@ export * from './useAppOperation.js';
export * from './useCityData.js';
export * from './useDeathClock.js';
export * from './usePostSession.js';
+export * from './useUniverseNav.js';
export * from './useVoiceUiSync.js';
diff --git a/client/src/hooks/useUniverseNav.js b/client/src/hooks/useUniverseNav.js
new file mode 100644
index 0000000000..01f0aea9aa
--- /dev/null
+++ b/client/src/hooks/useUniverseNav.js
@@ -0,0 +1,24 @@
+import { useLocation, useNavigate } from 'react-router-dom';
+
+// Strips any trailing `/:universeId` (or deeper path) so the result is always
+// the "/universe-builder" root for the current route prefix. Mirrors the regex
+// previously inlined in UniverseBuilder.jsx so consumers don't have to re-think
+// the basePath derivation.
+export function universeBuilderBasePath(pathname) {
+ return (pathname || '').replace(/\/universe-builder(?:\/.*)?$/, '/universe-builder');
+}
+
+// Returns `goToWorld(id)`. Calling it navigates to the Universe Builder route
+// for `id` (or back to the index when id is null/undefined), preserving the
+// current `location.search` so query state like `?tab=&bucket=` survives the
+// create-from-idea round-trip. The id is `encodeURIComponent`-wrapped so
+// universe ids with slashes / spaces / `#` don't smear into the path.
+export function useUniverseNav() {
+ const navigate = useNavigate();
+ const location = useLocation();
+ const basePath = universeBuilderBasePath(location.pathname);
+ return (id) => navigate({
+ pathname: id ? `${basePath}/${encodeURIComponent(id)}` : basePath,
+ search: location.search,
+ });
+}
diff --git a/client/src/hooks/useUniverseNav.test.jsx b/client/src/hooks/useUniverseNav.test.jsx
new file mode 100644
index 0000000000..d607991e73
--- /dev/null
+++ b/client/src/hooks/useUniverseNav.test.jsx
@@ -0,0 +1,110 @@
+import { describe, it, expect } from 'vitest';
+import { renderHook, act } from '@testing-library/react';
+import { MemoryRouter, useLocation } from 'react-router-dom';
+import { useUniverseNav, universeBuilderBasePath } from './useUniverseNav';
+
+// Pair the hook with `useLocation` so each test can read back the URL the
+// `goToWorld(id)` call produced — the contract here is URL transitions, so
+// that's what we assert on. Mirrors the `usePreviewRoute.test.jsx` pattern.
+const renderUniverseNav = (initial = '/universe-builder') => {
+ const wrapper = ({ children }) => (
+ <MemoryRouter initialEntries={[initial]}>{children}</MemoryRouter>
+ );
+ return renderHook(() => ({
+ goToWorld: useUniverseNav(),
+ location: useLocation(),
+ }), { wrapper });
+};
+
+describe('universeBuilderBasePath', () => {
+ it('strips a trailing /:universeId from the root mount', () => {
+ expect(universeBuilderBasePath('/universe-builder/u-123')).toBe('/universe-builder');
+ });
+
+ it('strips deeper trailing paths', () => {
+ expect(universeBuilderBasePath('/universe-builder/u-123/extra/path')).toBe('/universe-builder');
+ });
+
+ it('preserves a prefixed mount (e.g. /media/universe-builder)', () => {
+ expect(universeBuilderBasePath('/media/universe-builder/u-123')).toBe('/media/universe-builder');
+ });
+
+ it('returns the input unchanged when /universe-builder is the leaf with no id', () => {
+ expect(universeBuilderBasePath('/universe-builder')).toBe('/universe-builder');
+ });
+
+ it('tolerates null / empty input without throwing', () => {
+ expect(universeBuilderBasePath(null)).toBe('');
+ expect(universeBuilderBasePath('')).toBe('');
+ });
+});
+
+describe('useUniverseNav', () => {
+ it('navigates to /universe-builder/:id when called with an id', () => {
+ const { result } = renderUniverseNav();
+
+ act(() => result.current.goToWorld('u-42'));
+
+ expect(result.current.location.pathname).toBe('/universe-builder/u-42');
+ });
+
+ it('navigates back to the basePath when called with null', () => {
+ const { result } = renderUniverseNav('/universe-builder/u-42');
+
+ act(() => result.current.goToWorld(null));
+
+ expect(result.current.location.pathname).toBe('/universe-builder');
+ });
+
+ it('preserves location.search across the transition', () => {
+ const { result } = renderUniverseNav('/universe-builder?tab=cast&bucket=heroes');
+
+ act(() => result.current.goToWorld('u-42'));
+
+ expect(result.current.location.pathname).toBe('/universe-builder/u-42');
+ expect(result.current.location.search).toBe('?tab=cast&bucket=heroes');
+ });
+
+ it('preserves location.search when clearing back to the index', () => {
+ const { result } = renderUniverseNav('/universe-builder/u-42?series=s1');
+
+ act(() => result.current.goToWorld(null));
+
+ expect(result.current.location.pathname).toBe('/universe-builder');
+ expect(result.current.location.search).toBe('?series=s1');
+ });
+
+ it('URI-encodes ids containing reserved characters', () => {
+ const { result } = renderUniverseNav();
+
+ act(() => result.current.goToWorld('id with spaces & ?#'));
+
+ // Spaces / `&` / `?` / `#` would otherwise smear into the path or split
+ // off as query / hash — verify they all land inside the encoded segment.
+ expect(result.current.location.pathname).toBe('/universe-builder/id%20with%20spaces%20%26%20%3F%23');
+ });
+
+ it('URI-encodes ids containing forward slashes (path-segment smear guard)', () => {
+ const { result } = renderUniverseNav();
+
+ act(() => result.current.goToWorld('a/b'));
+
+ expect(result.current.location.pathname).toBe('/universe-builder/a%2Fb');
+ });
+
+ it('honors a prefixed mount when computing basePath', () => {
+ const { result } = renderUniverseNav('/media/universe-builder/u-old');
+
+ act(() => result.current.goToWorld('u-new'));
+
+ expect(result.current.location.pathname).toBe('/media/universe-builder/u-new');
+ });
+
+ it('swaps id-for-id when already on a world', () => {
+ const { result } = renderUniverseNav('/universe-builder/u-old');
+
+ act(() => result.current.goToWorld('u-new'));
+
+ expect(result.current.location.pathname).toBe('/universe-builder/u-new');
+ });
+});
diff --git a/client/src/pages/UniverseBuilder.jsx b/client/src/pages/UniverseBuilder.jsx
index 09ae088da7..b53e041364 100644
--- a/client/src/pages/UniverseBuilder.jsx
+++ b/client/src/pages/UniverseBuilder.jsx
@@ -8,7 +8,7 @@
*/
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
-import { Link, useLocation, useNavigate, useParams, useSearchParams } from 'react-router-dom';
+import { Link, useLocation, useParams, useSearchParams } from 'react-router-dom';
import {
Plus, Trash2, Sparkles, Wand2, Loader2, Save, FolderOpen,
Edit3, X, MessageSquarePlus, Play, Lock, Unlock,
@@ -28,6 +28,7 @@ import {
import useClickOutside from '../hooks/useClickOutside';
import { useLocalStoragePersisted } from '../hooks/useLocalStorageBool';
import useUniverseAction from '../hooks/useUniverseAction';
+import { useUniverseNav } from '../hooks/useUniverseNav';
import InfluenceChipsInput from '../components/universeBuilder/InfluenceChipsInput';
import ImageGenSettingsForm from '../components/imageGen/ImageGenSettingsForm';
import { RUNNER_FAMILIES } from '../lib/runnerFamilies';
@@ -468,19 +469,14 @@ export default function UniverseBuilder() {
// and /media/universe-builder(/:universeId) — strip any trailing /<id> off the
// current pathname to derive the base for navigation back to the list.
const params = useParams();
- const navigate = useNavigate();
const location = useLocation();
const selectedId = params.universeId || null;
- const basePath = location.pathname.replace(/\/universe-builder(?:\/.*)?$/, '/universe-builder');
- // Preserve the `?tab=&bucket=` (and `?series=`) query string so the
- // auto-save → create path doesn't snap the user back to the Bible tab
+ // `goToWorld` preserves `location.search` (e.g. `?tab=&bucket=&series=`) so
+ // the auto-save → create path doesn't snap the user back to the Bible tab
// after they triggered Generate From Idea from inside Cast/Places/Objects.
// The stale-bucket effect already strips any bucket that no longer exists
// under the new universe's categories.
- const goToWorld = (id) => navigate({
- pathname: id ? `${basePath}/${encodeURIComponent(id)}` : basePath,
- search: location.search,
- });
+ const goToWorld = useUniverseNav();
const [universes, setWorlds] = useState([]);
const [loading, setLoading] = useState(true);