feat: add routable browser URLs for stacks and shell views (#1586)

* feat: add routable browser URLs for stacks and shell views

Sync in-memory navigation to the address bar via a History API hook so
deep links, refresh, Back/Forward, and bookmarks work across nodes,
views, stack editor tabs, and mobile surfaces. Gate role/tier URL
normalization on permissions and license readiness, preserve URLs on
metadata fetch failure, and surface retryable stack-list errors without
rewriting pending stack paths.

* fix: preserve deep-link views on cold load and refresh

Stop the node-switch effect from resetting to dashboard on initial mount.

Defer URL writer settlement until hydrated activeView matches the route.

Adds E2E coverage for shell cold loads, stack refresh, and compose env tab.

* fix: keep mobile dashboard on list surface so sidebar renders

On mobile, the URL sync hook was routing /nodes/<slug>/dashboard to the
content surface, hiding the stack list sidebar. This prevented the
data-stacks-loaded sentinel from appearing, causing sidebar truncation
E2E tests to time out after reload on a mobile viewport.

Mobile dashboard now stays on the list surface; other non-editor views
still render on the content surface.

* fix: complete mobile URL routing follow-ups for stack deep links

Restore mobile /dashboard vs /stacks, list surface always writes /stacks.

Hydrate pendingDetailStack, freeze compose failures with routeDetailError,

and add unit plus E2E coverage.

* fix: hydrate shell views from URL and sync in-app navigation

Bootstrap activeView and tab state from the pathname on cold load.

Settle route phase when state already matches, normalize unknown segments,

and open Monaco editor tabs from stack deep links via applyEditorRouteState.

* fix: prevent mobile stack deep links from hanging on cold load

The resolvePendingStack effect did not re-fire when the pending stack ref
was populated during URL hydration, because the urlHydratingStack state
set in the same callback was not listed in the effect's dependency array.
Adding it causes the effect to retry once hydration has committed.

A resolvingRef mutex prevents concurrent invocations. When the target file
is already loaded, route state is applied directly without calling
loadFileForRoute, which avoids unmounting the editor (and hiding the
recovery chip) if a background refresh triggers route resolution during
a deploy operation.

* test: adapt stack, deploy, and sidebar e2e specs to routable stack URLs

* ci: raise E2E Playwright job timeout to 20 minutes
This commit is contained in:
Anso
2026-07-08 13:07:16 -04:00
committed by GitHub
parent 0c37d18586
commit 5fe0843eb2
35 changed files with 2263 additions and 199 deletions
@@ -94,8 +94,8 @@ export interface ViewRouterProps {
onSecurityTabChange: (tab: SecurityTab) => void;
fleetUpdatesIntent?: { tab: 'nodes' | 'changelog' } | null;
onFleetUpdatesIntentConsumed?: () => void;
fleetTab?: FleetTab | null;
onFleetTabConsumed?: () => void;
fleetActiveTab?: FleetTab;
onFleetActiveTabChange?: (tab: FleetTab) => void;
// Render slot for the inline editor view. Kept as a callback so the
// (large) editor JSX is only allocated when activeView === 'editor',
// not on every parent render that lands on a different view.
@@ -127,8 +127,8 @@ export function ViewRouter({
onSecurityTabChange,
fleetUpdatesIntent,
onFleetUpdatesIntentConsumed,
fleetTab,
onFleetTabConsumed,
fleetActiveTab,
onFleetActiveTabChange,
renderEditor,
stackUpdates,
}: ViewRouterProps): ReactNode {
@@ -202,8 +202,8 @@ export function ViewRouter({
onOpenMuteRulesWithPrefill={onOpenMuteRulesWithPrefill}
fleetUpdatesIntent={fleetUpdatesIntent}
onFleetUpdatesIntentConsumed={onFleetUpdatesIntentConsumed}
fleetTab={fleetTab}
onFleetTabConsumed={onFleetTabConsumed}
fleetActiveTab={fleetActiveTab}
onFleetActiveTabChange={onFleetActiveTabChange}
/>
</LazyView>
</CapabilityGate>
@@ -22,9 +22,11 @@ function mockCommunityUser() {
vi.mocked(AuthContext.useAuth).mockReturnValue({
isAdmin: false,
can: (p: string) => p === 'node:read',
permissionsStatus: 'ready',
} as unknown as ReturnType<typeof AuthContext.useAuth>);
vi.mocked(LicenseContext.useLicense).mockReturnValue({
isPaid: false,
licenseStatus: 'ready',
} as unknown as ReturnType<typeof LicenseContext.useLicense>);
}
@@ -33,9 +35,11 @@ function mockDeployer() {
vi.mocked(AuthContext.useAuth).mockReturnValue({
isAdmin: false,
can: (p: string) => p === 'stack:read' || p === 'stack:deploy',
permissionsStatus: 'ready',
} as unknown as ReturnType<typeof AuthContext.useAuth>);
vi.mocked(LicenseContext.useLicense).mockReturnValue({
isPaid: false,
licenseStatus: 'ready',
} as unknown as ReturnType<typeof LicenseContext.useLicense>);
}
@@ -43,9 +47,11 @@ function mockPaidAdmin() {
vi.mocked(AuthContext.useAuth).mockReturnValue({
isAdmin: true,
can: (p: string) => p === 'system:audit' || p === 'node:read',
permissionsStatus: 'ready',
} as unknown as ReturnType<typeof AuthContext.useAuth>);
vi.mocked(LicenseContext.useLicense).mockReturnValue({
isPaid: true,
licenseStatus: 'ready',
} as unknown as ReturnType<typeof LicenseContext.useLicense>);
}
@@ -53,9 +59,11 @@ function mockCommunityAdmin() {
vi.mocked(AuthContext.useAuth).mockReturnValue({
isAdmin: true,
can: (p: string) => p === 'node:read',
permissionsStatus: 'ready',
} as unknown as ReturnType<typeof AuthContext.useAuth>);
vi.mocked(LicenseContext.useLicense).mockReturnValue({
isPaid: false,
licenseStatus: 'ready',
} as unknown as ReturnType<typeof LicenseContext.useLicense>);
}
@@ -176,7 +184,7 @@ describe('useViewNavigationState', () => {
);
});
expect(result.current.activeView).toBe('fleet');
expect(result.current.fleetTab).toBe('snapshots');
expect(result.current.fleetActiveTab).toBe('snapshots');
});
it('SENCHO_NAVIGATE_EVENT with no nodeId sets filterNodeId to null', () => {
@@ -45,7 +45,10 @@ export function useOverlayState() {
// bottom-tab / hamburger destination). Wrapped in an object so the state
// setter is not mistaken for a functional update. Runs after the user
// confirms the unsaved-changes dialog. See useStackActions.attemptLeaveEditor.
const [pendingLeaveAction, setPendingLeaveAction] = useState<{ run: () => void } | null>(null);
const [pendingLeaveAction, setPendingLeaveAction] = useState<{
run: () => void;
onCancel?: () => void;
} | null>(null);
const [bashModalOpen, setBashModalOpen] = useState(false);
const [selectedContainer, setSelectedContainer] = useState<Container | null>(null);
@@ -8,6 +8,8 @@ import type { useViewNavigationState } from './useViewNavigationState';
import type { OverlayState } from './useOverlayState';
import type { Node } from '@/context/NodeContext';
import type { RunWithLogParams } from '@/context/DeployFeedbackContext';
import { parsePath } from '@/lib/router/senchoRoute';
import type { EditorTab } from '@/lib/router/routeTypes';
import type { StackAction, RecoverableAction, FailureClassification } from '../EditorView';
import type { NotificationItem } from '../../dashboard/types';
import type { PolicyBlockPayload, PolicyBlockableAction } from '../../stack/PolicyBlockDialog';
@@ -272,6 +274,9 @@ export function useStackActions(options: UseStackActionsOptions) {
editorState.content !== editorState.originalContent ||
editorState.envContent !== editorState.originalEnvContent;
const isComposeDirty = () => editorState.content !== editorState.originalContent;
const isEnvDirty = () => editorState.envContent !== editorState.originalEnvContent;
const getStackMenuVisibility = (file: string) => {
// A partial stack has running containers, so it shows the running-stack
// lifecycle actions (stop/restart/update) rather than deploy.
@@ -481,18 +486,22 @@ export function useStackActions(options: UseStackActionsOptions) {
}
};
const loadFile = async (filename: string) => {
if (!filename) return;
const applyEditorRouteState = (tab: EditorTab) => {
editorState.setActiveTab(tab);
editorState.setEditingCompose(true);
editorState.setIsEditing(false);
};
const loadFileCore = async (filename: string): Promise<boolean> => {
if (!filename) return false;
if (
stackListState.selectedFile &&
filename !== stackListState.selectedFile &&
hasUnsavedChanges()
) {
overlayState.setPendingUnsavedLoad(filename);
return;
return false;
}
// Cancel any in-flight load before starting a new one. A late response
// from the previous stack must not overwrite the freshly-loaded one.
loadFileAbortRef.current?.abort();
const controller = new AbortController();
loadFileAbortRef.current = controller;
@@ -504,9 +513,12 @@ export function useStackActions(options: UseStackActionsOptions) {
editorState.setActiveTab('compose');
try {
const res = await apiFetch(`/stacks/${filename}`, { signal });
if (signal.aborted) return;
if (signal.aborted) return false;
const text = await res.text();
if (signal.aborted) return;
if (signal.aborted) return false;
if (!res.ok) {
throw new Error(`Failed to load stack: ${res.status}`);
}
stackListState.setSelectedFile(filename);
navState.setActiveView('editor');
editorState.setContent(text || '');
@@ -515,12 +527,10 @@ export function useStackActions(options: UseStackActionsOptions) {
await loadEnvState(filename, signal);
await loadContainerState(filename, signal);
await loadBackupState(filename, signal);
return true;
} catch (error) {
if (isAbortError(error) || signal.aborted) return;
if (isAbortError(error) || signal.aborted) return false;
console.error('Failed to load file:', error);
// Surface the failure so a tap that cannot load (offline, dead remote
// node, 5xx) is not a silent no-op, especially on mobile where the row
// tap optimistically opens the detail surface.
toast.error(`Could not open "${filename.replace(/\.(ya?ml)$/, '')}". Check your connection and try again.`);
stackListState.setSelectedFile(null);
editorState.setContent('');
@@ -530,6 +540,7 @@ export function useStackActions(options: UseStackActionsOptions) {
editorState.setOriginalEnvContent('');
editorState.setEnvEtag(null);
editorState.setContainers([]);
return false;
} finally {
if (!signal.aborted) {
editorState.setIsFileLoading(false);
@@ -537,6 +548,14 @@ export function useStackActions(options: UseStackActionsOptions) {
}
};
const loadFile = async (filename: string) => {
await loadFileCore(filename);
};
const loadFileForRoute = async (filename: string): Promise<boolean> => {
return loadFileCore(filename);
};
// Keep ref in sync so loadFileOnNode always calls the latest loadFile closure
loadFileRef.current = loadFile;
@@ -1209,18 +1228,48 @@ export function useStackActions(options: UseStackActionsOptions) {
// destination. When the editor is dirty the navigation is stashed and the
// unsaved-changes dialog opens; discardAndLoadPending runs it on confirm.
// When clean it runs immediately.
const attemptLeaveEditor = (perform: () => void) => {
const attemptLeaveEditor = (perform: () => void, onCancel?: () => void) => {
if (stackListState.selectedFile && hasUnsavedChanges()) {
overlayState.setPendingLeaveAction({ run: perform });
overlayState.setPendingLeaveAction({ run: perform, onCancel });
return;
}
perform();
};
const wouldDiscardOnPopstate = (): boolean => {
if (!stackListState.selectedFile) return false;
const parsed = parsePath(window.location.pathname, window.location.search);
const targetStack = parsed.stackName;
const targetView = parsed.view;
if (targetView !== 'editor' || !targetStack || targetStack !== stackListState.selectedFile) {
return isComposeDirty() || isEnvDirty();
}
if (
parsed.editorTab === 'env'
&& editorState.activeTab === 'env'
&& parsed.envFile
&& parsed.envFile !== editorState.selectedEnvFile
) {
return isEnvDirty();
}
return false;
};
const attemptPopstateNavigation = (apply: () => void, onCancel: () => void) => {
if (wouldDiscardOnPopstate()) {
overlayState.setPendingLeaveAction({ run: apply, onCancel });
return;
}
apply();
};
const cancelPendingUnsavedLoad = () => {
const cancel = overlayState.pendingLeaveAction?.onCancel;
overlayState.setPendingUnsavedLoad(null);
overlayState.setPendingUnsavedNode(null);
overlayState.setPendingLeaveAction(null);
cancel?.();
};
const discardAndLoadPending = () => {
@@ -1398,7 +1447,9 @@ export function useStackActions(options: UseStackActionsOptions) {
refreshSelectedContainers,
refreshGitSourcePending,
loadFile,
loadFileForRoute,
loadFileOnNode,
applyEditorRouteState,
navigateToNotification,
changeEnvFile,
saveFile,
@@ -1419,6 +1470,7 @@ export function useStackActions(options: UseStackActionsOptions) {
requestStackUpdate,
deleteStack,
attemptLeaveEditor,
attemptPopstateNavigation,
cancelPendingUnsavedLoad,
discardAndLoadPending,
requestDeleteStack,
@@ -64,6 +64,8 @@ export interface RemoteResult {
const EMPTY_UPDATES: Record<string, StackUpdateInfo> = {};
export type StacksLoadStatus = 'idle' | 'loading' | 'success' | 'error';
export function useStackListState() {
const { nodes, activeNode } = useNodes();
@@ -100,6 +102,10 @@ export function useStackListState() {
const [filterChip, setFilterChip] = useState<FilterChip>('all');
const [bulkMode, setBulkMode] = useState(false);
const [selectedFiles, setSelectedFiles] = useState<Set<string>>(new Set());
const [stacksLoadStatus, setStacksLoadStatus] = useState<StacksLoadStatus>('idle');
const [stacksLoadError, setStacksLoadError] = useState<string | null>(null);
const [stacksLoadNodeId, setStacksLoadNodeId] = useState<number | null>(null);
const hadSuccessfulListRef = useRef(false);
const { stackUpdates, refresh: fetchImageUpdates, sidebarIndicators } = useImageUpdates(activeNode?.id);
const sidebarStackUpdates = sidebarIndicators ? stackUpdates : EMPTY_UPDATES;
@@ -117,6 +123,12 @@ export function useStackListState() {
if (evictedOldest) toast.info('Pinned. Unpinned oldest (max 10).');
}, [evictedOldest]);
useEffect(() => {
hadSuccessfulListRef.current = false;
setStacksLoadStatus('idle');
setStacksLoadError(null);
}, [activeNode?.id]);
// Ref is updated synchronously alongside the state setter so any code that
// runs right after (e.g. `refreshStacks(true)` in an action's finally block)
// observes the cleared map before React commits the next render. Without
@@ -180,25 +192,39 @@ export function useStackListState() {
}, [refreshLabels]);
const refreshStacks = async (background = false): Promise<string[]> => {
if (!background) setIsLoading(true);
// Snapshot the node this fetch targets and a sequence token so a superseded
// or out-of-order resolution (from a rapid node switch) cannot overwrite a
// newer node's list, keeping `files` and `filesNodeId` consistent.
const fetchNodeId = activeNode?.id ?? null;
const mySeq = ++fetchSeqRef.current;
const stale = () => fetchSeqRef.current !== mySeq;
if (!background) setIsLoading(true);
setStacksLoadNodeId(fetchNodeId);
if (!background || !hadSuccessfulListRef.current) {
setStacksLoadStatus('loading');
setStacksLoadError(null);
}
try {
const res = await apiFetch('/stacks');
if (stale()) return [];
if (!res.ok) {
const message = `Could not load stacks (${res.status})`;
if (background && hadSuccessfulListRef.current) {
setStacksLoadError(message);
return files;
}
setFiles([]);
setFilesNodeId(fetchNodeId);
setStacksLoadStatus('error');
setStacksLoadError(message);
return [];
}
const data = await res.json();
const fileList: string[] = Array.isArray(data) ? data : [];
setFiles(fileList);
setFilesNodeId(fetchNodeId);
hadSuccessfulListRef.current = true;
setStacksLoadStatus('success');
setStacksLoadError(null);
// Fetch all stack statuses in a single bulk call. Only the current object
// format can express `partial`; a node lacking the endpoint or returning
@@ -244,8 +270,15 @@ export function useStackListState() {
} catch (error) {
if (stale()) return [];
console.error('Failed to refresh stacks:', error);
const message = error instanceof Error ? error.message : 'Failed to load stacks';
if (background && hadSuccessfulListRef.current) {
setStacksLoadError(message);
return files;
}
setFiles([]);
setFilesNodeId(fetchNodeId);
setStacksLoadStatus('error');
setStacksLoadError(message);
return [];
} finally {
setIsLoading(false);
@@ -434,5 +467,8 @@ export function useStackListState() {
isCollapsed, toggleCollapse,
remoteSearchLoading,
remoteSearchFailedNodes,
stacksLoadStatus,
stacksLoadError,
stacksLoadNodeId,
} as const;
}
@@ -0,0 +1,340 @@
import { describe, it, expect, beforeEach, vi } from 'vitest';
import { renderHook, act } from '@testing-library/react';
import type { Node } from '@/context/NodeContext';
import type { ReachabilityContext } from '@/lib/routing/reachability';
import { useUrlSync, type UseUrlSyncOptions } from './useUrlSync';
function makeNode(over: Partial<Node> = {}): Node {
return {
id: 1,
name: 'local',
type: 'local',
is_default: true,
url: 'http://127.0.0.1:1852',
compose_dir: '/compose',
...over,
} as Node;
}
function makeReachCtx(over: Partial<ReachabilityContext> = {}): ReachabilityContext {
return {
isAdmin: true,
isPaid: true,
can: () => true,
isRemote: false,
hasFleetCapability: true,
containerLabelsEnabled: true,
permissionsStatus: 'ready',
licenseStatus: 'ready',
...over,
};
}
function makeOpts(over: Partial<UseUrlSyncOptions> = {}): UseUrlSyncOptions {
const node = makeNode();
return {
nodes: [node],
nodesLoaded: true,
activeNode: node,
setActiveNode: vi.fn(),
activeView: 'dashboard',
setActiveView: vi.fn(),
settingsSection: 'appearance',
setSettingsSection: vi.fn(),
securityTab: 'overview',
setSecurityTab: vi.fn(),
fleetActiveTab: 'overview',
setFleetActiveTab: vi.fn(),
filterNodeId: null,
setFilterNodeId: vi.fn(),
selectedFile: null,
files: ['radarr'],
filesNodeId: 1,
stacksLoadStatus: 'success',
stacksLoadNodeId: 1,
isFileLoading: false,
activeTab: 'compose',
setActiveTab: vi.fn(),
selectedEnvFile: '',
envFiles: [],
loadFileForRoute: vi.fn().mockResolvedValue(true),
changeEnvFile: vi.fn().mockResolvedValue(undefined),
applyEditorRouteState: vi.fn(),
refreshStacks: vi.fn().mockResolvedValue(['radarr']),
reachCtx: makeReachCtx(),
isMobile: false,
mobileSurface: null,
setMobileSurface: vi.fn(),
mobileSettingsSection: null,
setMobileSettingsSection: vi.fn(),
setPendingDetailStack: vi.fn(),
attemptPopstateNavigation: (apply) => { apply(); },
...over,
};
}
describe('useUrlSync', () => {
beforeEach(() => {
window.history.replaceState({ senchoIdx: 0 }, '', '/nodes/local/dashboard');
});
it('mounts and hydrates when history state lacks senchoIdx', () => {
window.history.replaceState({}, '', '/nodes/local/security');
const setSecurityTab = vi.fn();
act(() => {
renderHook(
(props) => useUrlSync(props),
{
initialProps: makeOpts({
activeView: 'security',
setSecurityTab,
}),
},
);
});
expect(window.location.pathname).toBe('/nodes/local/security');
});
it('pushState increments senchoIdx on user navigation', () => {
const pushSpy = vi.spyOn(window.history, 'pushState');
const { rerender } = renderHook(
(props) => useUrlSync(props),
{ initialProps: makeOpts({ activeView: 'dashboard' }) },
);
act(() => {
rerender(makeOpts({ activeView: 'resources' }));
});
const pushed = pushSpy.mock.calls.find(call => String(call[2]).includes('/resources'));
expect(pushed).toBeDefined();
expect((pushed?.[0] as { senchoIdx?: number }).senchoIdx).toBe(1);
pushSpy.mockRestore();
});
it('keeps a pending stack deep link when stack list load fails', () => {
window.history.replaceState({ senchoIdx: 0 }, '', '/nodes/local/stacks/radarr/compose');
const setActiveView = vi.fn();
act(() => {
renderHook(
(props) => useUrlSync(props),
{
initialProps: makeOpts({
activeView: 'editor',
setActiveView,
files: [],
stacksLoadStatus: 'error',
stacksLoadNodeId: 1,
}),
},
);
});
expect(setActiveView).not.toHaveBeenCalledWith('dashboard');
expect(window.location.pathname).toBe('/nodes/local/stacks/radarr/compose');
});
it('routes popstate through attemptPopstateNavigation', () => {
const attempt = vi.fn();
renderHook(
(props) => useUrlSync(props),
{
initialProps: makeOpts({
attemptPopstateNavigation: attempt,
}),
},
);
act(() => {
window.history.pushState({ senchoIdx: 1 }, '', '/nodes/local/resources');
window.dispatchEvent(new PopStateEvent('popstate', { state: { senchoIdx: 0 } }));
});
expect(attempt).toHaveBeenCalledTimes(1);
expect(attempt.mock.calls[0]).toHaveLength(2);
});
it('does not normalize a paid URL while permissions metadata is still loading', () => {
window.history.replaceState({ senchoIdx: 0 }, '', '/nodes/local/audit');
const setActiveView = vi.fn();
act(() => {
renderHook(
(props) => useUrlSync(props),
{
initialProps: makeOpts({
activeView: 'audit-log',
setActiveView,
reachCtx: makeReachCtx({ permissionsStatus: 'loading' }),
}),
},
);
});
expect(setActiveView).not.toHaveBeenCalledWith('dashboard');
expect(window.location.pathname).toBe('/nodes/local/audit');
});
it('retryFrozenRoute triggers a foreground stack refresh', async () => {
const refreshStacks = vi.fn().mockResolvedValue(['radarr']);
const { result } = renderHook(
(props) => useUrlSync(props),
{
initialProps: makeOpts({
refreshStacks,
stacksLoadStatus: 'error',
files: [],
}),
},
);
await act(async () => {
await result.current.retryFrozenRoute();
});
expect(refreshStacks).toHaveBeenCalledWith(false);
});
it('hydrates fleet view from URL', () => {
window.history.replaceState({ senchoIdx: 0 }, '', '/nodes/local/fleet');
const setActiveView = vi.fn();
act(() => {
renderHook(
(props) => useUrlSync(props),
{
initialProps: makeOpts({
activeView: 'fleet',
setActiveView,
}),
},
);
});
expect(setActiveView).toHaveBeenCalledWith('fleet');
});
it('normalizes unknown view segments to dashboard', () => {
window.history.replaceState({ senchoIdx: 0 }, '', '/nodes/local/not-a-view');
const setActiveView = vi.fn();
act(() => {
renderHook(
(props) => useUrlSync(props),
{
initialProps: makeOpts({
activeView: 'dashboard',
setActiveView,
}),
},
);
});
expect(window.location.pathname).toBe('/nodes/local/dashboard');
});
it('hydrates mobile dashboard to the content surface', () => {
window.history.replaceState({ senchoIdx: 0 }, '', '/nodes/local/dashboard');
const setMobileSurface = vi.fn();
act(() => {
renderHook(
(props) => useUrlSync(props),
{
initialProps: makeOpts({
isMobile: true,
mobileSurface: null,
setMobileSurface,
}),
},
);
});
expect(setMobileSurface).toHaveBeenCalledWith('content');
});
it('sets pending detail stack on mobile stack URL hydrate', () => {
window.history.replaceState({ senchoIdx: 0 }, '', '/nodes/local/stacks/radarr/compose');
const setPendingDetailStack = vi.fn();
act(() => {
renderHook(
(props) => useUrlSync(props),
{
initialProps: makeOpts({
isMobile: true,
setPendingDetailStack,
}),
},
);
});
expect(setPendingDetailStack).toHaveBeenCalledWith('radarr');
});
it('freezes route and sets routeDetailError when compose load fails', async () => {
window.history.replaceState({ senchoIdx: 0 }, '', '/nodes/local/stacks/radarr/compose');
const loadFileForRoute = vi.fn().mockResolvedValue(false);
const setPendingDetailStack = vi.fn();
const { result } = renderHook(
(props) => useUrlSync(props),
{
initialProps: makeOpts({
isMobile: true,
setPendingDetailStack,
loadFileForRoute,
activeView: 'editor',
}),
},
);
await act(async () => {
await Promise.resolve();
});
expect(loadFileForRoute).toHaveBeenCalledWith('radarr');
expect(result.current.routeDetailError).toContain('Could not open');
expect(window.location.pathname).toBe('/nodes/local/stacks/radarr/compose');
});
it('clears routeDetailError after a successful retry', async () => {
window.history.replaceState({ senchoIdx: 0 }, '', '/nodes/local/stacks/radarr/compose');
const loadFileForRoute = vi.fn().mockResolvedValue(false);
const { result, rerender } = renderHook(
(props) => useUrlSync(props),
{
initialProps: makeOpts({
isMobile: true,
loadFileForRoute,
activeView: 'editor',
}),
},
);
await act(async () => {
await Promise.resolve();
});
expect(result.current.routeDetailError).not.toBeNull();
loadFileForRoute.mockResolvedValue(true);
rerender(makeOpts({
isMobile: true,
loadFileForRoute,
activeView: 'editor',
selectedFile: 'radarr',
}));
await act(async () => {
await result.current.retryFrozenRoute();
});
expect(result.current.routeDetailError).toBeNull();
});
});
@@ -0,0 +1,478 @@
import { useEffect, useRef, useCallback, useState } from 'react';
import type { Node } from '@/context/NodeContext';
import type { FleetTab, SecurityTab } from '@/lib/events';
import type { SectionId } from '@/components/settings/types';
import type { ActiveView, EditorTab, MobileRouteSurface } from '@/lib/router/routeTypes';
import { buildPath, parsePath } from '@/lib/router/senchoRoute';
import { nodeIdToSlug, slugToNodeId } from '@/lib/nodeSlug';
import {
authzReady,
isFleetTabHidden,
isSettingsSectionHidden,
isViewHidden,
normalizeHiddenView,
type ReachabilityContext,
} from '@/lib/routing/reachability';
import type { StacksLoadStatus } from './useStackListState';
type RoutePhase = 'initial' | 'applying' | 'settled' | 'frozen';
type RouteIntent = 'push' | 'replace' | 'none';
interface HistoryState {
senchoIdx?: number;
}
interface PendingRoute {
view: ActiveView;
stackName: string | null;
editorTab: EditorTab;
envFile: string | null;
securityTab: SecurityTab;
fleetTab: FleetTab;
settingsSection: SectionId | null;
filterNodeId: number | null;
isStackList: boolean;
}
export interface UseUrlSyncOptions {
nodes: Node[];
nodesLoaded: boolean;
activeNode: Node | null;
setActiveNode: (node: Node) => void;
activeView: ActiveView;
setActiveView: (view: ActiveView) => void;
settingsSection: SectionId;
setSettingsSection: (section: SectionId) => void;
securityTab: SecurityTab;
setSecurityTab: (tab: SecurityTab) => void;
fleetActiveTab: FleetTab;
setFleetActiveTab: (tab: FleetTab) => void;
filterNodeId: number | null;
setFilterNodeId: (id: number | null) => void;
selectedFile: string | null;
files: string[];
filesNodeId: number | null;
stacksLoadStatus: StacksLoadStatus;
stacksLoadNodeId: number | null;
isFileLoading: boolean;
activeTab: EditorTab;
setActiveTab: (tab: EditorTab) => void;
selectedEnvFile: string;
envFiles: string[];
loadFileForRoute: (filename: string) => Promise<boolean>;
changeEnvFile: (file: string) => Promise<void>;
applyEditorRouteState: (tab: EditorTab) => void;
refreshStacks: (background?: boolean) => Promise<string[]>;
reachCtx: ReachabilityContext;
isMobile: boolean;
mobileSurface: MobileRouteSurface | null;
setMobileSurface: (surface: MobileRouteSurface) => void;
mobileSettingsSection: SectionId | null;
setMobileSettingsSection: (section: SectionId | null) => void;
setPendingDetailStack: (stack: string | null) => void;
attemptPopstateNavigation: (apply: () => void, onCancel: () => void) => void;
}
function currentPath(): string {
return window.location.pathname + window.location.search;
}
function readIdx(state: unknown): number | null {
if (state && typeof state === 'object' && 'senchoIdx' in state) {
const v = (state as HistoryState).senchoIdx;
return typeof v === 'number' ? v : null;
}
return null;
}
export function useUrlSync(options: UseUrlSyncOptions) {
const optsRef = useRef(options);
optsRef.current = options;
const [routeDetailError, setRouteDetailError] = useState<string | null>(null);
const [urlHydratingStack, setUrlHydratingStack] = useState<string | null>(null);
const phaseRef = useRef<RoutePhase>('initial');
const historyIdxRef = useRef(0);
const suppressNextPopstateRef = useRef(false);
const pendingRouteRef = useRef<PendingRoute | null>(null);
const pendingStackRef = useRef<string | null>(null);
const pendingEnvRef = useRef<string | null>(null);
const pendingTabRef = useRef<EditorTab | null>(null);
const initialHydratedRef = useRef(false);
const routeReplaceRef = useRef(false);
const appliedViewRef = useRef<ActiveView | null>(null);
const resolvingRef = useRef(false);
const writeHistory = useCallback((path: string, intent: RouteIntent) => {
const prev = window.history.state as HistoryState | null;
const base: HistoryState = prev && typeof prev === 'object' ? { ...prev } : {};
if (intent === 'push') {
historyIdxRef.current += 1;
base.senchoIdx = historyIdxRef.current;
window.history.pushState(base, '', path);
} else {
base.senchoIdx = historyIdxRef.current;
window.history.replaceState(base, '', path);
}
}, []);
const buildCurrentPath = useCallback(() => {
const o = optsRef.current;
const slug = o.activeNode ? nodeIdToSlug(o.activeNode.id, o.nodes) : null;
if (!slug) return null;
const view = authzReady(o.reachCtx) ? normalizeHiddenView(o.activeView, o.reachCtx) : o.activeView;
let mobileSurface: MobileRouteSurface | null = o.mobileSurface;
if (!o.isMobile) mobileSurface = null;
return buildPath({
nodeSlug: slug,
activeView: view,
stackName: o.selectedFile,
editorTab: o.activeTab,
envFile: o.selectedEnvFile || null,
securityTab: o.securityTab,
fleetActiveTab: o.fleetActiveTab,
settingsSection: o.isMobile ? o.mobileSettingsSection : o.settingsSection,
filterNodeId: o.filterNodeId,
mobileSurface,
isMobile: o.isMobile,
});
}, []);
const applyPendingRoute = useCallback(async () => {
const o = optsRef.current;
const pending = pendingRouteRef.current;
if (!pending) return;
let view = pending.view;
if (authzReady(o.reachCtx)) {
view = normalizeHiddenView(view, o.reachCtx);
}
if (pending.isStackList && o.isMobile) {
o.setMobileSurface('list');
o.setActiveView('dashboard');
} else {
o.setActiveView(view);
if (o.isMobile && view !== 'editor') {
o.setMobileSurface('content');
}
}
if (pending.securityTab) o.setSecurityTab(pending.securityTab);
if (pending.fleetTab) o.setFleetActiveTab(pending.fleetTab);
if (pending.settingsSection) {
if (o.isMobile) o.setMobileSettingsSection(pending.settingsSection);
else o.setSettingsSection(pending.settingsSection);
}
if (pending.filterNodeId != null) o.setFilterNodeId(pending.filterNodeId);
if (pending.stackName) {
pendingStackRef.current = pending.stackName;
pendingEnvRef.current = pending.envFile;
pendingTabRef.current = pending.editorTab;
setUrlHydratingStack(pending.stackName);
if (o.isMobile) {
o.setPendingDetailStack(pending.stackName);
}
} else {
setUrlHydratingStack(null);
setRouteDetailError(null);
pendingRouteRef.current = null;
if (o.activeView === view) {
appliedViewRef.current = null;
phaseRef.current = 'settled';
} else {
appliedViewRef.current = view;
phaseRef.current = 'applying';
}
}
}, []);
const resolvePendingStack = useCallback(async () => {
if (resolvingRef.current) return;
const o = optsRef.current;
const stack = pendingStackRef.current;
if (!stack || !o.activeNode) return;
if (o.filesNodeId !== o.activeNode.id) return;
if (o.stacksLoadStatus === 'loading' || o.stacksLoadStatus === 'idle') return;
if (o.stacksLoadStatus === 'error' && o.stacksLoadNodeId === o.activeNode.id) {
phaseRef.current = 'frozen';
pendingRouteRef.current = null;
return;
}
const match = o.files.find(f => f === stack)
?? o.files.find(f => f.toLowerCase() === stack.toLowerCase());
if (!match) {
routeReplaceRef.current = true;
pendingStackRef.current = null;
pendingRouteRef.current = null;
setUrlHydratingStack(null);
setRouteDetailError(null);
if (o.isMobile) o.setPendingDetailStack(null);
o.setActiveView('dashboard');
phaseRef.current = 'settled';
return;
}
// If the file is already loaded, apply route state without reloading
// to avoid unmounting the editor (loadFileCore clears selectedFile on
// failure, which would hide the recovery chip during a deploy).
if (o.selectedFile === match) {
const env = pendingEnvRef.current;
const tab = pendingTabRef.current ?? 'compose';
if (env && o.envFiles.includes(env) && env !== o.envFiles[0]) {
await o.changeEnvFile(env);
}
o.setActiveTab(tab);
o.applyEditorRouteState(tab);
pendingStackRef.current = null;
pendingEnvRef.current = null;
pendingTabRef.current = null;
pendingRouteRef.current = null;
setUrlHydratingStack(null);
setRouteDetailError(null);
phaseRef.current = 'settled';
return;
}
resolvingRef.current = true;
const attempted = match;
const loaded = await o.loadFileForRoute(match);
if (pendingStackRef.current !== attempted) { resolvingRef.current = false; return; }
if (!loaded) {
phaseRef.current = 'frozen';
pendingRouteRef.current = null;
setRouteDetailError(`Could not open "${attempted.replace(/\.(ya?ml)$/, '')}". Check your connection and try again.`);
resolvingRef.current = false;
return;
}
const env = pendingEnvRef.current;
const tab = pendingTabRef.current ?? 'compose';
if (env && o.envFiles.includes(env) && env !== o.envFiles[0]) {
await o.changeEnvFile(env);
}
o.setActiveTab(tab);
o.applyEditorRouteState(tab);
pendingStackRef.current = null;
pendingEnvRef.current = null;
pendingTabRef.current = null;
pendingRouteRef.current = null;
setUrlHydratingStack(null);
setRouteDetailError(null);
phaseRef.current = 'settled';
resolvingRef.current = false;
}, []);
const hydrateFromUrl = useCallback((pathname: string, search: string) => {
const o = optsRef.current;
if (!o.nodesLoaded || o.nodes.length === 0) return;
const parsed = parsePath(pathname, search);
if (!parsed.nodeSlug) {
const slug = o.activeNode ? nodeIdToSlug(o.activeNode.id, o.nodes) : null;
if (slug) {
routeReplaceRef.current = true;
writeHistory(`/nodes/${slug}/dashboard`, 'replace');
}
phaseRef.current = 'settled';
return;
}
const nodeId = slugToNodeId(parsed.nodeSlug, o.nodes);
if (nodeId == null) {
const fallback = o.activeNode ?? o.nodes[0];
if (fallback) {
routeReplaceRef.current = true;
const slug = nodeIdToSlug(fallback.id, o.nodes);
if (slug) writeHistory(`/nodes/${slug}/dashboard`, 'replace');
}
phaseRef.current = 'settled';
return;
}
const node = o.nodes.find(n => n.id === nodeId);
if (!node) return;
if (parsed.nodeSlug && parsed.view == null && !parsed.isStackList) {
routeReplaceRef.current = true;
const slug = nodeIdToSlug(node.id, o.nodes);
if (slug) writeHistory(`/nodes/${slug}/dashboard`, 'replace');
phaseRef.current = 'settled';
if (o.activeView !== 'dashboard') o.setActiveView('dashboard');
return;
}
let view = parsed.view ?? 'dashboard';
let fleetTab = parsed.fleetTab ?? 'overview';
if (parsed.fleetTab && isFleetTabHidden(parsed.fleetTab, o.reachCtx)) {
fleetTab = 'overview';
routeReplaceRef.current = true;
}
let settingsSection = parsed.settingsSection as SectionId | null;
if (settingsSection && isSettingsSectionHidden(settingsSection, o.reachCtx)) {
settingsSection = null;
routeReplaceRef.current = true;
}
if (view && isViewHidden(view, o.reachCtx)) {
view = 'dashboard';
routeReplaceRef.current = true;
}
if (o.isMobile && view === 'fleet' && parsed.fleetTab && parsed.fleetTab !== 'overview') {
fleetTab = 'overview';
routeReplaceRef.current = true;
}
pendingRouteRef.current = {
view,
stackName: parsed.stackName,
editorTab: parsed.editorTab ?? 'compose',
envFile: parsed.envFile,
securityTab: parsed.securityTab ?? 'overview',
fleetTab,
settingsSection,
filterNodeId: parsed.filterNodeId,
isStackList: parsed.isStackList,
};
phaseRef.current = 'applying';
if (o.activeNode?.id !== node.id) {
o.setActiveNode(node);
} else {
void applyPendingRoute();
}
}, [applyPendingRoute, writeHistory]);
useEffect(() => {
const base: HistoryState = readIdx(window.history.state) != null
? (window.history.state as HistoryState)
: { senchoIdx: 0 };
if (readIdx(base) == null) {
base.senchoIdx = 0;
window.history.replaceState(base, '', window.location.pathname + window.location.search);
}
historyIdxRef.current = base.senchoIdx ?? 0;
}, []);
useEffect(() => {
if (!options.nodesLoaded || options.nodes.length === 0) return;
if (initialHydratedRef.current) return;
initialHydratedRef.current = true;
hydrateFromUrl(window.location.pathname, window.location.search);
}, [hydrateFromUrl, options.nodesLoaded, options.nodes.length]);
useEffect(() => {
if (pendingRouteRef.current && optsRef.current.activeNode) {
void applyPendingRoute();
}
}, [applyPendingRoute, options.activeNode?.id]);
useEffect(() => {
void resolvePendingStack();
}, [
resolvePendingStack,
options.files,
options.filesNodeId,
options.stacksLoadStatus,
options.stacksLoadNodeId,
options.selectedFile,
options.isFileLoading,
options.envFiles,
urlHydratingStack,
]);
useEffect(() => {
if (phaseRef.current !== 'applying') return;
if (pendingStackRef.current) return;
const applied = appliedViewRef.current;
if (applied == null) return;
if (options.activeView !== applied) return;
appliedViewRef.current = null;
phaseRef.current = 'settled';
}, [options.activeView]);
useEffect(() => {
if (phaseRef.current !== 'settled') return;
if (options.isFileLoading) return;
if (pendingStackRef.current) return;
if (options.activeView === 'editor' && !options.selectedFile) return;
const target = buildCurrentPath();
if (!target || target === currentPath()) return;
const intent: RouteIntent = routeReplaceRef.current ? 'replace' : 'push';
routeReplaceRef.current = false;
writeHistory(target, intent);
}, [
buildCurrentPath,
writeHistory,
options.activeView,
options.selectedFile,
options.activeTab,
options.selectedEnvFile,
options.securityTab,
options.fleetActiveTab,
options.settingsSection,
options.filterNodeId,
options.activeNode?.id,
options.isMobile,
options.mobileSurface,
options.mobileSettingsSection,
options.isFileLoading,
options.reachCtx,
]);
useEffect(() => {
const onPopstate = (event: PopStateEvent) => {
if (suppressNextPopstateRef.current) {
suppressNextPopstateRef.current = false;
return;
}
const newIdx = readIdx(event.state) ?? readIdx(window.history.state);
const oldIdx = historyIdxRef.current;
const delta = newIdx != null ? newIdx - oldIdx : -1;
if (newIdx != null) historyIdxRef.current = newIdx;
const apply = () => {
phaseRef.current = 'applying';
hydrateFromUrl(window.location.pathname, window.location.search);
};
const cancel = () => {
if (delta === 0) return;
suppressNextPopstateRef.current = true;
window.history.go(-delta);
};
optsRef.current.attemptPopstateNavigation(apply, cancel);
};
window.addEventListener('popstate', onPopstate);
return () => window.removeEventListener('popstate', onPopstate);
}, [hydrateFromUrl]);
const prevIsMobileRef = useRef(options.isMobile);
useEffect(() => {
if (prevIsMobileRef.current !== options.isMobile) {
prevIsMobileRef.current = options.isMobile;
routeReplaceRef.current = true;
}
}, [options.isMobile]);
const retryFrozenRoute = useCallback(() => {
setRouteDetailError(null);
phaseRef.current = 'applying';
void optsRef.current.refreshStacks(false).then(() => {
void resolvePendingStack();
});
}, [resolvePendingStack]);
return { retryFrozenRoute, urlHydratingStack, routeDetailError };
}
@@ -13,34 +13,18 @@ import type { SecurityTab, FleetTab } from '@/lib/events';
import type { SectionId } from '@/components/settings/types';
import type { ScheduleTaskPrefill } from '@/components/ScheduledOperationsView';
import type { MuteRuleDraft } from '@/lib/muteRules';
import type { ActiveView } from '@/lib/router/routeTypes';
import { HUB_ONLY_VIEWS } from '@/lib/router/routeTypes';
import { readUrlRouteState } from '@/lib/router/readUrlRouteState';
import {
authzReady,
isViewHidden,
normalizeHiddenView,
type ReachabilityContext,
} from '@/lib/routing/reachability';
export type ActiveView =
| 'dashboard'
| 'editor'
| 'host-console'
| 'resources'
| 'templates'
| 'global-observability'
| 'fleet'
| 'security'
| 'audit-log'
| 'scheduled-ops'
| 'auto-updates'
| 'settings';
// Views that operate on hub-owned state (node registry, fleet schedules,
// centralized audit, fleet-wide log aggregation, fleet-wide update preview).
// Hidden from the nav strip and force-redirect to dashboard when the active
// node is remote, since proxying them would surface that remote's own
// disconnected state instead of the hub's. Settings sub-sections use the
// parallel `hiddenOnRemote` registry (see settings/registry.ts).
export const HUB_ONLY_VIEWS: ReadonlySet<ActiveView> = new Set([
'fleet',
'scheduled-ops',
'audit-log',
'global-observability',
'auto-updates',
]);
export type { ActiveView };
export { HUB_ONLY_VIEWS };
export interface NavItem {
value: ActiveView;
@@ -50,24 +34,39 @@ export interface NavItem {
interface UseViewNavigationStateOptions {
onNavigateToDashboard?: () => void;
hasFleetCapability?: boolean;
containerLabelsEnabled?: boolean;
}
export function useViewNavigationState(options?: UseViewNavigationStateOptions) {
const { onNavigateToDashboard } = options ?? {};
const { isAdmin, can } = useAuth();
const { isPaid } = useLicense();
const { onNavigateToDashboard, hasFleetCapability = false, containerLabelsEnabled = false } = options ?? {};
const { isAdmin, can, permissionsStatus } = useAuth();
const { isPaid, licenseStatus } = useLicense();
const { activeNode } = useNodes();
const isRemote = activeNode?.type === 'remote';
const [activeView, setActiveView] = useState<ActiveView>('dashboard');
const [settingsSection, setSettingsSection] = useState<SectionId>('appearance');
const [securityTab, setSecurityTab] = useState<SecurityTab>('overview');
const [fleetTab, setFleetTab] = useState<FleetTab | null>(null);
const [filterNodeId, setFilterNodeId] = useState<number | null>(null);
const initialRoute = readUrlRouteState();
const [activeView, setActiveView] = useState<ActiveView>(initialRoute.activeView);
const [settingsSection, setSettingsSection] = useState<SectionId>(initialRoute.settingsSection);
const [securityTab, setSecurityTab] = useState<SecurityTab>(initialRoute.securityTab);
const [fleetActiveTab, setFleetActiveTab] = useState<FleetTab>(initialRoute.fleetActiveTab);
const [filterNodeId, setFilterNodeId] = useState<number | null>(initialRoute.filterNodeId);
const [schedulePrefill, setSchedulePrefill] = useState<ScheduleTaskPrefill | null>(null);
const [muteRulePrefill, setMuteRulePrefill] = useState<MuteRuleDraft | null>(null);
const [mobileNavOpen, setMobileNavOpen] = useState(false);
const reachCtx: ReachabilityContext = useMemo(() => ({
isAdmin,
isPaid,
can: (action: string) => can(action as Parameters<typeof can>[0]),
isRemote,
hasFleetCapability,
containerLabelsEnabled,
permissionsStatus,
licenseStatus,
}), [isAdmin, isPaid, can, isRemote, hasFleetCapability, containerLabelsEnabled, permissionsStatus, licenseStatus]);
const handleOpenSettings = useCallback((section?: SectionId) => {
if (section) setSettingsSection(section);
setActiveView('settings');
@@ -86,6 +85,9 @@ export function useViewNavigationState(options?: UseViewNavigationStateOptions)
const handleNavigate = useCallback((value: string) => {
if (value === activeView) return;
if (value === 'fleet') {
setFleetActiveTab('overview');
}
if (value === 'dashboard') {
onNavigateToDashboard?.();
setActiveView('dashboard');
@@ -100,17 +102,13 @@ export function useViewNavigationState(options?: UseViewNavigationStateOptions)
const detail = (e as CustomEvent<SenchoNavigateDetail & { view: string }>).detail;
if (!detail?.view) return;
if (detail.view === 'security') {
// Set the target tab before switching the view so the controlled
// SecurityView lands on it deterministically (no mount race).
setSecurityTab(detail.tab ?? 'overview');
setActiveView('security');
setFilterNodeId(detail.nodeId ?? null);
return;
}
if (detail.view === 'fleet') {
// Set the target sub-tab before switching so the controlled FleetView
// lands on it (e.g. Snapshots from the stack storage warning).
if (detail.fleetTab) setFleetTab(detail.fleetTab);
if (detail.fleetTab) setFleetActiveTab(detail.fleetTab);
setActiveView('fleet');
setFilterNodeId(detail.nodeId ?? null);
return;
@@ -126,54 +124,47 @@ export function useViewNavigationState(options?: UseViewNavigationStateOptions)
const items: NavItem[] = [
{ value: 'dashboard', label: 'Home', icon: Home },
];
// Fleet surfaces node topology and host stats, so it is gated on node:read
// (held by every role except deployer), matching the backend guard on the
// fleet overview / configuration / dependency / networking reads.
if (can('node:read')) items.push({ value: 'fleet', label: 'Fleet', icon: Radar });
if (!isViewHidden('fleet', reachCtx)) {
items.push({ value: 'fleet', label: 'Fleet', icon: Radar });
}
items.push(
{ value: 'resources', label: 'Resources', icon: HardDrive },
// Security is a Community, node-scoped review surface (not hub-only), so
// it shows for every authenticated user and on remote nodes too.
{ value: 'security', label: 'Security', icon: ShieldCheck },
{ value: 'templates', label: 'App Store', icon: CloudDownload },
);
// The aggregated Logs feed crosses every managed stack, so it is an
// admin-only operator view (the backend gates the same routes on admin).
if (isAdmin) items.push({ value: 'global-observability', label: 'Logs', icon: Activity });
if (isAdmin) {
if (!isViewHidden('global-observability', reachCtx)) {
items.push({ value: 'global-observability', label: 'Logs', icon: Activity });
}
if (!isViewHidden('auto-updates', reachCtx)) {
items.push({ value: 'auto-updates', label: 'Update', icon: RefreshCw });
}
if (!isViewHidden('scheduled-ops', reachCtx)) {
items.push({ value: 'scheduled-ops', label: 'Schedules', icon: Clock });
}
if (isPaid) {
if (isAdmin) items.push({ value: 'host-console', label: 'Console', icon: Terminal });
if (can('system:audit')) items.push({ value: 'audit-log', label: 'Audit', icon: ScrollText });
if (!isViewHidden('host-console', reachCtx)) {
items.push({ value: 'host-console', label: 'Console', icon: Terminal });
}
return isRemote
? items.filter(i => !HUB_ONLY_VIEWS.has(i.value))
: items;
}, [isAdmin, isPaid, can, isRemote]);
if (!isViewHidden('audit-log', reachCtx)) {
items.push({ value: 'audit-log', label: 'Audit', icon: ScrollText });
}
return items;
}, [reachCtx]);
useEffect(() => {
// Redirect off a view the active context can't reach: a hub-only view while
// a remote node is active, the admin-only Logs view as a non-admin, or the
// Fleet view without node:read (e.g. arrived via a deep-link event rather
// than the now-hidden nav item).
const blockedByRemote = isRemote && HUB_ONLY_VIEWS.has(activeView);
const blockedByRole =
(!isAdmin && activeView === 'global-observability')
|| (!can('node:read') && activeView === 'fleet');
if (blockedByRemote || blockedByRole) {
if (!authzReady(reachCtx)) return;
const normalized = normalizeHiddenView(activeView, reachCtx);
if (normalized !== activeView) {
onNavigateToDashboard?.();
setActiveView('dashboard');
setActiveView(normalized);
setFilterNodeId(null);
}
}, [isRemote, isAdmin, can, activeView, onNavigateToDashboard]);
}, [reachCtx, activeView, onNavigateToDashboard]);
return {
activeView, setActiveView,
settingsSection, setSettingsSection,
securityTab, setSecurityTab,
fleetTab, setFleetTab,
fleetActiveTab, setFleetActiveTab,
filterNodeId, setFilterNodeId,
schedulePrefill, setSchedulePrefill,
muteRulePrefill, setMuteRulePrefill,
@@ -184,5 +175,6 @@ export function useViewNavigationState(options?: UseViewNavigationStateOptions)
openMuteRulesWithPrefill,
handleNavigate,
navItems,
reachCtx,
} as const;
}
@@ -0,0 +1,40 @@
import { describe, it, expect } from 'vitest';
import { shouldClearPendingDetailStack } from './mobile-pending-detail';
describe('shouldClearPendingDetailStack', () => {
const base = {
pendingDetailStack: 'radarr',
detailReady: false,
isFileLoading: false,
stacksLoadStatus: 'success' as const,
urlHydratingStack: null,
routeDetailError: null,
};
it('returns false when there is no pending stack', () => {
expect(shouldClearPendingDetailStack({ ...base, pendingDetailStack: null })).toBe(false);
});
it('does not clear while stacks are loading during URL hydration', () => {
expect(shouldClearPendingDetailStack({
...base,
stacksLoadStatus: 'loading',
urlHydratingStack: 'radarr',
})).toBe(false);
});
it('does not clear while a route detail error is shown', () => {
expect(shouldClearPendingDetailStack({
...base,
routeDetailError: 'Could not open stack',
})).toBe(false);
});
it('clears when the detail surface is ready', () => {
expect(shouldClearPendingDetailStack({ ...base, detailReady: true })).toBe(true);
});
it('does not clear while compose is still loading', () => {
expect(shouldClearPendingDetailStack({ ...base, isFileLoading: true })).toBe(false);
});
});
@@ -0,0 +1,21 @@
import type { StacksLoadStatus } from './hooks/useStackListState';
export interface PendingDetailClearInput {
pendingDetailStack: string | null;
detailReady: boolean;
isFileLoading: boolean;
stacksLoadStatus: StacksLoadStatus;
urlHydratingStack: string | null;
routeDetailError: string | null;
}
/** Whether the optimistic mobile detail placeholder can be cleared. */
export function shouldClearPendingDetailStack(input: PendingDetailClearInput): boolean {
if (!input.pendingDetailStack) return false;
if (input.routeDetailError) return false;
if (input.urlHydratingStack) return false;
if (input.detailReady) return true;
if (input.isFileLoading) return false;
if (input.stacksLoadStatus === 'loading' || input.stacksLoadStatus === 'idle') return false;
return false;
}