mirror of
https://github.com/lukaszraczylo/gohoarder.git
synced 2026-11-26 06:37:07 +00:00
fix(frontend): show load failures as errors and add a not-found route
A failed request left the store error set while the view kept its own empty-list branch, so the page said nothing was cached. Every view now checks loading, then error, then content, and the retry button refetches. Unknown paths render a NotFound page with a link to the dashboard. The brand shares the sidebar left edge, and a stopped socket reads Live updates paused in a neutral tone; the client already retries with backoff.
This commit is contained in:
@@ -21,8 +21,9 @@ onMounted(() => {
|
||||
class="sr-only focus:not-sr-only focus:absolute focus:start-2 focus:top-2 focus:z-(--z-toast) focus:rounded-md focus:bg-primary focus:px-3 focus:py-2 focus:text-sm focus:text-primary-foreground"
|
||||
>Skip to main content</a
|
||||
>
|
||||
<!-- px-6 on the bar equals the sidebar nav's p-3 plus the link's px-3, so the brand icon sits over the nav icons. -->
|
||||
<!-- AppShell wraps its #header slot in its own <header> and AppHeader renders one too; outside the shell there is one banner. -->
|
||||
<AppHeader sticky mobile-variant="sheet" class="[&>div]:h-(--header-h)">
|
||||
<AppHeader sticky mobile-variant="sheet" class="[&>div]:h-(--header-h) [&>div]:px-6">
|
||||
<template #brand>
|
||||
<Icon :icon="faBoxOpen" size="lg" class="text-primary" />
|
||||
<p class="m-0 text-lg font-semibold">GoHoarder</p>
|
||||
|
||||
@@ -17,16 +17,16 @@
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<LoadingState v-if="loading" variant="table" label="Loading bypasses..." />
|
||||
|
||||
<ErrorState
|
||||
v-if="error"
|
||||
v-else-if="error"
|
||||
variant="card"
|
||||
title="Could not load bypasses"
|
||||
:message="error"
|
||||
@retry="fetchBypasses"
|
||||
/>
|
||||
|
||||
<LoadingState v-if="loading" variant="table" label="Loading bypasses..." />
|
||||
|
||||
<Card v-else>
|
||||
<CardContent>
|
||||
<EmptyState
|
||||
|
||||
@@ -244,4 +244,21 @@ describe('Dashboard.vue', () => {
|
||||
expect(wrapper.text()).toContain('999')
|
||||
expect(wrapper.text()).toContain('777')
|
||||
})
|
||||
|
||||
it('shows a neutral "Live updates paused" badge while the socket is down', async () => {
|
||||
const wrapper = mount(Dashboard)
|
||||
const badge = wrapper.find('[data-testid="ws-live-indicator"]')
|
||||
expect(badge.text()).toBe('Live updates paused')
|
||||
expect(badge.text()).not.toMatch(/offline/i)
|
||||
expect(badge.attributes('data-tone')).toBe('neutral')
|
||||
})
|
||||
|
||||
it('shows a "Live" badge once the socket is connected', async () => {
|
||||
const wrapper = mount(Dashboard)
|
||||
useRealtimeStore().connected = true
|
||||
await wrapper.vm.$nextTick()
|
||||
const badge = wrapper.find('[data-testid="ws-live-indicator"]')
|
||||
expect(badge.text()).toBe('Live')
|
||||
expect(badge.attributes('data-tone')).toBe('success')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -3,26 +3,27 @@
|
||||
<PageHeader title="Dashboard" description="What the cache holds and what is moving through it.">
|
||||
<template #actions>
|
||||
<StatusBadge
|
||||
:status="rt.connected ? 'live' : 'offline'"
|
||||
:label="rt.connected ? 'Live' : 'Offline'"
|
||||
:tones="{ live: 'success', offline: 'neutral' }"
|
||||
:status="rt.connected ? 'live' : 'paused'"
|
||||
:label="rt.connected ? 'Live' : 'Live updates paused'"
|
||||
:tones="{ live: 'success', paused: 'neutral' }"
|
||||
:pulse="rt.connected"
|
||||
data-testid="ws-live-indicator"
|
||||
/>
|
||||
</template>
|
||||
</PageHeader>
|
||||
|
||||
<LoadingState v-if="loading" variant="kpi-grid" :columns="4" label="Loading statistics..." />
|
||||
|
||||
<ErrorState
|
||||
v-if="error"
|
||||
v-else-if="error"
|
||||
variant="card"
|
||||
title="Could not load statistics"
|
||||
:message="error"
|
||||
@retry="refresh"
|
||||
/>
|
||||
|
||||
<LoadingState v-if="loading" variant="kpi-grid" :columns="4" label="Loading statistics..." />
|
||||
|
||||
<StatGroup v-else :columns="4" aria-label="Cache totals">
|
||||
<template v-else>
|
||||
<StatGroup :columns="4" aria-label="Cache totals">
|
||||
<KpiTile label="Total packages" :value="displayStats?.total_packages || 0" :icon="faBoxesStacked" />
|
||||
<KpiTile label="Total size" :value="formatBytes(displayStats?.total_size || 0)" :icon="faHardDrive" />
|
||||
<KpiTile label="Total downloads" :value="displayStats?.total_downloads || 0" :icon="faDownload" />
|
||||
@@ -51,6 +52,13 @@
|
||||
layout="inline"
|
||||
label="Loading chart data..."
|
||||
/>
|
||||
<ErrorState
|
||||
v-else-if="chartError"
|
||||
variant="inline"
|
||||
title="Could not load download activity"
|
||||
:message="chartError"
|
||||
@retry="fetchTimeSeriesData"
|
||||
/>
|
||||
<BarChart
|
||||
v-else
|
||||
:labels="chartLabels"
|
||||
@@ -86,6 +94,7 @@
|
||||
</DataTable>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</template>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -211,16 +220,19 @@ interface TimeSeriesStats {
|
||||
|
||||
const timeSeriesData = ref<TimeSeriesStats | null>(null)
|
||||
const chartLoading = ref(false)
|
||||
const chartError = ref<string | null>(null)
|
||||
|
||||
// Fetch time-series data from API
|
||||
async function fetchTimeSeriesData() {
|
||||
chartLoading.value = true
|
||||
chartError.value = null
|
||||
try {
|
||||
const response = await axios.get(`/api/stats/timeseries?period=${selectedPeriod.value}`)
|
||||
timeSeriesData.value = response.data
|
||||
} catch (err) {
|
||||
console.error('Failed to fetch time-series data:', err)
|
||||
timeSeriesData.value = null
|
||||
chartError.value = err instanceof Error ? err.message : 'Failed to load download activity'
|
||||
} finally {
|
||||
chartLoading.value = false
|
||||
}
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
<template>
|
||||
<div class="flex flex-col gap-6">
|
||||
<PageHeader title="Page not found" />
|
||||
<EmptyState
|
||||
title-as="h2"
|
||||
size="lg"
|
||||
:icon="faMagnifyingGlass"
|
||||
title="No page at this address"
|
||||
:description="`Nothing lives at ${route.path}.`"
|
||||
>
|
||||
<template #action>
|
||||
<Button as-child>
|
||||
<RouterLink to="/">Back to the dashboard</RouterLink>
|
||||
</Button>
|
||||
</template>
|
||||
</EmptyState>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { RouterLink, useRoute } from 'vue-router'
|
||||
import { Button, EmptyState, PageHeader } from '@perfect-design/ui'
|
||||
import { faMagnifyingGlass } from '@/lib/icons'
|
||||
|
||||
const route = useRoute()
|
||||
</script>
|
||||
@@ -16,16 +16,16 @@
|
||||
<SearchInput v-model="searchTerm" aria-label="Search packages" placeholder="Search packages..." class="w-full sm:ms-auto sm:w-64" />
|
||||
</div>
|
||||
|
||||
<LoadingState v-if="loading" variant="table" label="Loading packages..." />
|
||||
|
||||
<ErrorState
|
||||
v-if="error"
|
||||
v-else-if="error"
|
||||
variant="card"
|
||||
title="Could not load packages"
|
||||
:message="error"
|
||||
@retry="store.fetchPackages()"
|
||||
/>
|
||||
|
||||
<LoadingState v-if="loading" variant="table" label="Loading packages..." />
|
||||
|
||||
<Card v-else>
|
||||
<CardContent>
|
||||
<EmptyState
|
||||
@@ -282,8 +282,11 @@ async function deletePackage() {
|
||||
showDeleteModal.value = false
|
||||
packageToDelete.value = null
|
||||
const label = `${target.name}@${target.version}`
|
||||
if (store.error) toasts.error('Could not delete package', `${label}: ${store.error}`)
|
||||
else toasts.success('Package deleted', label)
|
||||
if (store.error) {
|
||||
toasts.error('Could not delete package', `${label}: ${store.error}`)
|
||||
// The toast reports it; the list loaded fine, so it must not be replaced by a load error.
|
||||
store.error = null
|
||||
} else toasts.success('Package deleted', label)
|
||||
}
|
||||
|
||||
function showVulnerabilityDetails(registry: string, name: string, version: string) {
|
||||
|
||||
@@ -30,9 +30,11 @@ describe('Stats.vue', () => {
|
||||
})
|
||||
|
||||
it('displays error message when error occurs', async () => {
|
||||
const wrapper = mount(Stats)
|
||||
const store = usePackageStore()
|
||||
vi.spyOn(store, 'fetchStats').mockResolvedValue()
|
||||
const wrapper = mount(Stats)
|
||||
|
||||
store.loading = false
|
||||
store.error = 'Failed to fetch statistics'
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
|
||||
@@ -2,16 +2,16 @@
|
||||
<div class="flex flex-col gap-6">
|
||||
<PageHeader title="Statistics" description="Storage, traffic and scan results across every registry." />
|
||||
|
||||
<LoadingState v-if="loading" variant="kpi-grid" :columns="3" label="Loading statistics..." />
|
||||
|
||||
<ErrorState
|
||||
v-if="error"
|
||||
v-else-if="error"
|
||||
variant="card"
|
||||
title="Could not load statistics"
|
||||
:message="error"
|
||||
@retry="refresh"
|
||||
/>
|
||||
|
||||
<LoadingState v-if="loading" variant="kpi-grid" :columns="3" label="Loading statistics..." />
|
||||
|
||||
<template v-else>
|
||||
<Card>
|
||||
<CardHeader>
|
||||
|
||||
@@ -151,6 +151,11 @@ async function fetchVulnerablePackages() {
|
||||
|
||||
try {
|
||||
await store.fetchPackages()
|
||||
// The store records a failed request in store.error and resolves; surface it instead of an empty list.
|
||||
if (store.error) {
|
||||
error.value = store.error
|
||||
return
|
||||
}
|
||||
vulnerablePackages.value = store.packages.filter(pkg => {
|
||||
const isVulnerable = pkg.vulnerabilities?.status === 'vulnerable'
|
||||
if (showOnlyBlocked.value) {
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { createPinia, setActivePinia } from 'pinia'
|
||||
import axios from 'axios'
|
||||
import { flushPromises } from '@vue/test-utils'
|
||||
import App from '@/App.vue'
|
||||
import Dashboard from './Dashboard.vue'
|
||||
import PackageList from './PackageList.vue'
|
||||
import PackageDetails from './PackageDetails.vue'
|
||||
import VulnerablePackages from './VulnerablePackages.vue'
|
||||
import BypassManagementPanel from './BypassManagementPanel.vue'
|
||||
import Stats from './Stats.vue'
|
||||
import { __resetRealtimeSingleton, useRealtimeStore } from '@/stores/realtime'
|
||||
import { mountStrict } from '@/test/mountStrict'
|
||||
import { createTestRouter } from '@/test/router'
|
||||
|
||||
vi.mock('axios')
|
||||
|
||||
const FAILURE = Object.assign(new Error('Request failed with status code 502'), {
|
||||
response: { status: 502, data: {} },
|
||||
})
|
||||
|
||||
// What each view must not say when the request failed: an empty state would tell the operator there is nothing to see.
|
||||
const EMPTY_TEXT: Record<string, string> = {
|
||||
Dashboard: 'No packages cached yet',
|
||||
PackageList: 'No packages cached yet',
|
||||
VulnerablePackages: 'No vulnerable packages',
|
||||
Stats: 'No registries reported',
|
||||
BypassManagementPanel: 'No bypasses found',
|
||||
}
|
||||
|
||||
const CASES: Array<[string, Parameters<typeof mountStrict>[0], string]> = [
|
||||
['Dashboard', Dashboard, '/'],
|
||||
['PackageList', PackageList, '/packages'],
|
||||
['PackageDetails', PackageDetails, '/package/npm/left-pad/1.3.0'],
|
||||
['VulnerablePackages', VulnerablePackages, '/vulnerable-packages'],
|
||||
['BypassManagementPanel', BypassManagementPanel, '/admin/bypasses'],
|
||||
['Stats', Stats, '/stats'],
|
||||
]
|
||||
|
||||
let restore: (() => void) | undefined
|
||||
|
||||
beforeEach(() => {
|
||||
setActivePinia(createPinia())
|
||||
__resetRealtimeSingleton()
|
||||
vi.mocked(axios.get).mockRejectedValue(FAILURE)
|
||||
localStorage.setItem('admin_api_key', 'test-key')
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
restore?.()
|
||||
restore = undefined
|
||||
localStorage.clear()
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
describe('an API failure renders ErrorState, never an empty state', () => {
|
||||
it.each(CASES)('%s', async (name, component, path) => {
|
||||
const router = await createTestRouter(path)
|
||||
const pinia = createPinia()
|
||||
setActivePinia(pinia)
|
||||
vi.spyOn(useRealtimeStore(), 'connect').mockImplementation(() => {})
|
||||
vi.spyOn(console, 'error').mockImplementation(() => {})
|
||||
const mounted = await mountStrict(component, { global: { plugins: [pinia, router] } })
|
||||
restore = mounted.restore
|
||||
await flushPromises()
|
||||
|
||||
const state = mounted.wrapper.find('[data-slot="error-state"]')
|
||||
expect(state.exists()).toBe(true)
|
||||
expect(state.text()).toContain('502')
|
||||
expect(state.find('button').text()).toMatch(/try again/i)
|
||||
expect(mounted.wrapper.find('[data-slot="empty-state"]').exists()).toBe(false)
|
||||
if (EMPTY_TEXT[name]) expect(mounted.wrapper.text()).not.toContain(EMPTY_TEXT[name])
|
||||
})
|
||||
|
||||
it('retry fetches again and clears the error when the backend is back', async () => {
|
||||
const router = await createTestRouter('/vulnerable-packages')
|
||||
const pinia = createPinia()
|
||||
setActivePinia(pinia)
|
||||
const mounted = await mountStrict(VulnerablePackages, { global: { plugins: [pinia, router] } })
|
||||
restore = mounted.restore
|
||||
vi.mocked(axios.get).mockResolvedValue({ data: { packages: [] } })
|
||||
await mounted.wrapper.find('[data-slot="error-state"] button').trigger('click')
|
||||
await flushPromises()
|
||||
expect(mounted.wrapper.find('[data-slot="error-state"]').exists()).toBe(false)
|
||||
expect(mounted.wrapper.text()).toContain('No vulnerable packages')
|
||||
})
|
||||
})
|
||||
|
||||
describe('unknown routes', () => {
|
||||
it('render NotFound with a link to the dashboard', async () => {
|
||||
vi.mocked(axios.get).mockResolvedValue({ data: {} })
|
||||
const router = await createTestRouter('/vulnerable')
|
||||
const pinia = createPinia()
|
||||
setActivePinia(pinia)
|
||||
vi.spyOn(useRealtimeStore(), 'connect').mockImplementation(() => {})
|
||||
const mounted = await mountStrict(App, { global: { plugins: [pinia, router] } })
|
||||
restore = mounted.restore
|
||||
await flushPromises()
|
||||
|
||||
expect(mounted.problems).toEqual([])
|
||||
const main = mounted.wrapper.find('main')
|
||||
expect(main.find('h1').text()).toBe('Page not found')
|
||||
expect(main.find('[data-slot="empty-state"]').text()).toContain('/vulnerable')
|
||||
const link = main.find('a[href="/"]')
|
||||
expect(link.text()).toMatch(/dashboard/i)
|
||||
})
|
||||
})
|
||||
@@ -168,13 +168,17 @@ describe('view smoke tests (strict mode throw, fixture data)', () => {
|
||||
it('App renders one banner, one main, a skip link first and the five sections', async () => {
|
||||
const { wrapper, problems } = await smoke(App, '/')
|
||||
expect(problems).toEqual([])
|
||||
expect(document.body.querySelectorAll('header').length).toBe(1)
|
||||
// A page's own <header> inside <main> is not a banner landmark.
|
||||
expect(document.body.querySelectorAll('header:not(main header)').length).toBe(1)
|
||||
expect(document.body.querySelectorAll('main').length).toBe(1)
|
||||
const first = document.body.querySelector<HTMLElement>('a[href], button')
|
||||
expect(first?.getAttribute('href')).toBe('#main-content')
|
||||
const nav = wrapper.find('nav[aria-label="Sections"]')
|
||||
expect(nav.findAll('a').map((a) => a.text())).toEqual(['Dashboard', 'Packages', 'Vulnerable', 'Bypasses', 'Stats'])
|
||||
expect(document.documentElement.getAttribute('data-style')).toBe('workbench')
|
||||
// Brand column and sidebar items share one left edge: 6 spacing units each.
|
||||
expect(document.body.querySelector('header')?.className).toContain('[&>div]:px-6')
|
||||
expect(nav.classes()).toContain('p-3')
|
||||
})
|
||||
|
||||
it('PackageList still fetches through the store on mount', async () => {
|
||||
|
||||
@@ -1,47 +1,53 @@
|
||||
import { createRouter, createWebHistory } from 'vue-router'
|
||||
import { createRouter, createWebHistory, type RouteRecordRaw, type RouterHistory } from 'vue-router'
|
||||
|
||||
const router = createRouter({
|
||||
history: createWebHistory(),
|
||||
routes: [
|
||||
{
|
||||
path: '/',
|
||||
name: 'dashboard',
|
||||
component: () => import('../components/Dashboard.vue'),
|
||||
},
|
||||
{
|
||||
path: '/packages/:registry?',
|
||||
name: 'packages',
|
||||
component: () => import('../components/PackageList.vue'),
|
||||
props: true,
|
||||
},
|
||||
{
|
||||
// Separate route for package details - supports names with slashes (Go packages)
|
||||
path: '/package/:registry/:name+/:version',
|
||||
name: 'package-details',
|
||||
component: () => import('../components/PackageDetails.vue'),
|
||||
props: true,
|
||||
},
|
||||
{
|
||||
path: '/stats',
|
||||
name: 'stats',
|
||||
component: () => import('../components/Stats.vue'),
|
||||
},
|
||||
{
|
||||
path: '/vulnerable-packages',
|
||||
name: 'vulnerable-packages',
|
||||
component: () => import('../components/VulnerablePackages.vue'),
|
||||
},
|
||||
{
|
||||
path: '/blocked-packages',
|
||||
name: 'blocked-packages',
|
||||
component: () => import('../components/VulnerablePackages.vue'),
|
||||
},
|
||||
{
|
||||
path: '/admin/bypasses',
|
||||
name: 'bypasses',
|
||||
component: () => import('../components/BypassManagementPanel.vue'),
|
||||
},
|
||||
],
|
||||
})
|
||||
export const routes: RouteRecordRaw[] = [
|
||||
{
|
||||
path: '/',
|
||||
name: 'dashboard',
|
||||
component: () => import('../components/Dashboard.vue'),
|
||||
},
|
||||
{
|
||||
path: '/packages/:registry?',
|
||||
name: 'packages',
|
||||
component: () => import('../components/PackageList.vue'),
|
||||
props: true,
|
||||
},
|
||||
{
|
||||
// Separate route for package details - supports names with slashes (Go packages)
|
||||
path: '/package/:registry/:name+/:version',
|
||||
name: 'package-details',
|
||||
component: () => import('../components/PackageDetails.vue'),
|
||||
props: true,
|
||||
},
|
||||
{
|
||||
path: '/stats',
|
||||
name: 'stats',
|
||||
component: () => import('../components/Stats.vue'),
|
||||
},
|
||||
{
|
||||
path: '/vulnerable-packages',
|
||||
name: 'vulnerable-packages',
|
||||
component: () => import('../components/VulnerablePackages.vue'),
|
||||
},
|
||||
{
|
||||
path: '/blocked-packages',
|
||||
name: 'blocked-packages',
|
||||
component: () => import('../components/VulnerablePackages.vue'),
|
||||
},
|
||||
{
|
||||
path: '/admin/bypasses',
|
||||
name: 'bypasses',
|
||||
component: () => import('../components/BypassManagementPanel.vue'),
|
||||
},
|
||||
{
|
||||
path: '/:pathMatch(.*)*',
|
||||
name: 'not-found',
|
||||
component: () => import('../components/NotFound.vue'),
|
||||
},
|
||||
]
|
||||
|
||||
export default router
|
||||
export function createAppRouter(history: RouterHistory = createWebHistory()) {
|
||||
return createRouter({ history, routes })
|
||||
}
|
||||
|
||||
export default createAppRouter()
|
||||
|
||||
@@ -1,23 +1,8 @@
|
||||
import { createMemoryHistory, createRouter, type Router } from 'vue-router'
|
||||
import { defineComponent, h } from 'vue'
|
||||
import { createMemoryHistory } from 'vue-router'
|
||||
import { createAppRouter } from '@/router'
|
||||
|
||||
const Stub = defineComponent({ render: () => h('div') })
|
||||
|
||||
export const ROUTE_PATHS = [
|
||||
'/',
|
||||
'/packages/:registry?',
|
||||
'/package/:registry/:name+/:version',
|
||||
'/stats',
|
||||
'/vulnerable-packages',
|
||||
'/blocked-packages',
|
||||
'/admin/bypasses',
|
||||
]
|
||||
|
||||
export async function createTestRouter(initial = '/'): Promise<Router> {
|
||||
const router = createRouter({
|
||||
history: createMemoryHistory(),
|
||||
routes: ROUTE_PATHS.map((path) => ({ path, component: Stub })),
|
||||
})
|
||||
export async function createTestRouter(initial = '/') {
|
||||
const router = createAppRouter(createMemoryHistory())
|
||||
await router.push(initial)
|
||||
await router.isReady()
|
||||
return router
|
||||
|
||||
Reference in New Issue
Block a user