Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

Show truthful Docs load failures and preserve same-guide retry

pulse-triage[bot]b5a27bbbced9
diff --git a/frontend-modern/src/pages/Docs.tsx b/frontend-modern/src/pages/Docs.tsx
index 387acdb139..863ae7d7dc 100644
--- a/frontend-modern/src/pages/Docs.tsx
+++ b/frontend-modern/src/pages/Docs.tsx
@@ -1,5 +1,6 @@
import { useLocation, useNavigate, useParams } from '@solidjs/router';
import { Show, createEffect, createMemo, createResource, onCleanup } from 'solid-js';
+import { Button } from '@/components/shared/Button';
import { PageHeader } from '@/components/shared/PageHeader';
import {
docAssetUrlForPath,
@@ -13,21 +14,49 @@ import {
const DOCS_INDEX_PATH = 'README';
-async function fetchDoc(docPath: string): Promise<string> {
- const response = await fetch(docAssetUrlForPath(docPath), {
- headers: { Accept: 'text/markdown, text/plain' },
- });
- if (!response.ok) {
- throw new Error(String(response.status));
+const LOAD_FAILURE_MESSAGES = {
+ missing: "That document is not part of this installation's shipped documentation set.",
+ access:
+ 'Access to this guide was refused. Check that you are still signed in and have access, then try again.',
+ unavailable:
+ 'This guide could not be loaded. There may be a temporary connection or server problem. Try again.',
+};
+
+class DocLoadError extends Error {
+ constructor(
+ readonly kind: keyof typeof LOAD_FAILURE_MESSAGES,
+ readonly docPath: string,
+ ) {
+ // Keep response bodies and transport details out of the reading surface.
+ super(LOAD_FAILURE_MESSAGES[kind]);
}
- // A document that is not shipped does not 404. Both the Go static handler
- // and the dev server fall back to index.html for any unmatched non-API
- // path, including one ending in .md, so the only reliable signal that the
- // asset is missing is getting HTML back instead of markdown.
- if (isHtmlResponse(response)) {
- throw new Error('not-shipped');
+}
+
+async function fetchDoc(docPath: string): Promise<string> {
+ try {
+ const response = await fetch(docAssetUrlForPath(docPath), {
+ headers: { Accept: 'text/markdown, text/plain' },
+ });
+ if (!response.ok) {
+ const kind =
+ response.status === 404 || response.status === 410
+ ? 'missing'
+ : response.status === 401 || response.status === 403
+ ? 'access'
+ : 'unavailable';
+ throw new DocLoadError(kind, docPath);
+ }
+ // Both static handlers can return the SPA's HTML for a missing .md asset.
+ // Check status first: an HTML access/error page is not evidence of absence.
+ if (isHtmlResponse(response)) {
+ throw new DocLoadError('missing', docPath);
+ }
+ return await response.text();
+ } catch (error) {
+ if (error instanceof DocLoadError) throw error;
+ // A connection failure or interrupted response body can both be retried.
+ throw new DocLoadError('unavailable', docPath);
}
- return response.text();
}
export function isHtmlResponse(response: Pick<Response, 'headers'>): boolean {
@@ -42,7 +71,14 @@ export default function Docs() {
let article: HTMLElement | undefined;
const docPath = createMemo(() => normalizeDocPath(params.docPath ?? '') || DOCS_INDEX_PATH);
- const [document] = createResource(docPath, fetchDoc);
+ const [document, { refetch }] = createResource(docPath, fetchDoc);
+
+ // Keep a failed guide's retry control mounted while that same read is in
+ // flight, but never present its error as a different guide loads.
+ const loadError = createMemo(() => {
+ const error: unknown = document.error;
+ return error instanceof DocLoadError && error.docPath === docPath() ? error : undefined;
+ });
// Reading a resource that rejected re-throws, so the error has to be checked
// before the accessor is touched or the failure escapes the memo instead of
@@ -116,21 +152,42 @@ export default function Docs() {
</Show>
<Show
- when={!document.loading}
- fallback={<p class="text-sm text-muted">Loading documentation&hellip;</p>}
+ when={!document.loading || loadError()}
+ fallback={
+ <p role="status" class="text-sm text-muted">
+ Loading documentation&hellip;
+ </p>
+ }
>
<Show
- when={!document.error}
+ when={!loadError()}
fallback={
<div class="space-y-2">
- <p class="text-sm text-muted">
- That document is not part of this installation's shipped documentation set.
+ <p role="alert" class="text-sm text-muted">
+ {loadError()?.message}
</p>
+ <Button
+ size="sm"
+ // Native disabled blurs the keyboard reader's control. Keep it
+ // focusable, announce its state and reject duplicate reads here.
+ aria-disabled={document.loading}
+ class="aria-disabled:cursor-wait aria-disabled:opacity-50"
+ onClick={() => {
+ if (!document.loading) void refetch();
+ }}
+ >
+ Try again
+ </Button>
+ <Show when={document.loading}>
+ <p role="status" class="text-sm text-muted">
+ Loading documentation&hellip;
+ </p>
+ </Show>
<a
href={docRouteForPath(DOCS_INDEX_PATH)}
data-doc-link=""
onClick={handleClick}
- class="text-sm text-blue-600 hover:underline dark:text-blue-400"
+ class="block text-sm text-blue-600 hover:underline dark:text-blue-400"
>
Back to the documentation index
</a>
diff --git a/frontend-modern/src/pages/__tests__/Docs.loading.test.tsx b/frontend-modern/src/pages/__tests__/Docs.loading.test.tsx
new file mode 100644
index 0000000000..37b51302e4
--- /dev/null
+++ b/frontend-modern/src/pages/__tests__/Docs.loading.test.tsx
@@ -0,0 +1,190 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { cleanup, fireEvent, render, screen, waitFor } from '@solidjs/testing-library';
+import { Route, Router } from '@solidjs/router';
+import Docs from '../Docs';
+
+const missing = "That document is not part of this installation's shipped documentation set.";
+const access = 'Access to this guide was refused.';
+const temporary = 'This guide could not be loaded.';
+const privateBody = '<h1>private-upstream-detail</h1><script>window.leaked = true</script>';
+const faq = '# FAQ\n\n## Answer\n\nA shipped answer.';
+const markdown = (body: string) =>
+ new Response(body, { headers: { 'Content-Type': 'text/plain' } });
+const deferred = <T,>() => {
+ let resolve!: (value: T) => void;
+ const promise = new Promise<T>((done) => {
+ resolve = done;
+ });
+ return { promise, resolve };
+};
+
+function mount() {
+ render(() => (
+ <Router>
+ <Route path="/docs/*docPath" component={Docs} />
+ </Router>
+ ));
+}
+
+describe('Docs load failures and explicit same-guide retry', () => {
+ const fetchMock = vi.fn<typeof fetch>();
+ const scroll = vi.fn();
+
+ beforeEach(() => {
+ window.history.replaceState(null, '', '/docs/FAQ?reader=fixture#answer');
+ fetchMock.mockReset();
+ vi.stubGlobal('fetch', fetchMock);
+ vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) =>
+ setTimeout(() => callback(0), 0),
+ );
+ vi.stubGlobal('cancelAnimationFrame', (id: number) => clearTimeout(id));
+ vi.stubGlobal('scrollTo', vi.fn());
+ Object.defineProperty(HTMLElement.prototype, 'scrollIntoView', {
+ configurable: true,
+ value: scroll,
+ });
+ scroll.mockClear();
+ });
+
+ afterEach(() => {
+ cleanup();
+ vi.unstubAllGlobals();
+ Reflect.deleteProperty(HTMLElement.prototype, 'scrollIntoView');
+ window.history.replaceState(null, '', '/');
+ });
+
+ it.each([
+ [404, 'text/plain', missing],
+ [410, 'text/plain', missing],
+ [200, 'text/html; charset=utf-8', missing],
+ [401, 'text/html', access],
+ [403, 'text/html', access],
+ [408, 'text/plain', temporary],
+ [429, 'text/plain', temporary],
+ [500, 'text/html', temporary],
+ [503, 'text/html', temporary],
+ ])(
+ 'classifies HTTP %s / %s without exposing its response',
+ async (status, contentType, message) => {
+ fetchMock.mockResolvedValueOnce(
+ new Response(privateBody, {
+ status,
+ headers: { 'Content-Type': contentType },
+ }),
+ );
+ mount();
+ const alert = await screen.findByRole('alert');
+ expect(alert.textContent).toContain(message);
+ expect(alert.textContent?.includes(missing)).toBe(message === missing);
+ expect(document.body).not.toHaveTextContent('private-upstream-detail');
+ expect(document.querySelector('article')).toBeNull();
+ expect(screen.getByRole('button', { name: 'Try again' })).toBeEnabled();
+ expect(fetchMock).toHaveBeenCalledExactlyOnceWith('/docs/FAQ.md', {
+ headers: { Accept: 'text/markdown, text/plain' },
+ });
+ },
+ );
+
+ it.each(['connection', 'body'])(
+ 'handles an interrupted %s as retryable, not missing',
+ async (phase) => {
+ if (phase === 'connection') fetchMock.mockRejectedValueOnce(new Error(privateBody));
+ else
+ fetchMock.mockResolvedValueOnce({
+ ok: true,
+ headers: new Headers({ 'Content-Type': 'text/markdown' }),
+ text: () => Promise.reject(new Error(privateBody)),
+ } as Response);
+ mount();
+ expect(await screen.findByRole('alert')).toHaveTextContent(temporary);
+ expect(document.body).not.toHaveTextContent('private-upstream-detail');
+ expect(document.body).not.toHaveTextContent(missing);
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ },
+ );
+
+ it('announces initial loading, then renders ordinary shipped markdown', async () => {
+ const pending = deferred<Response>();
+ fetchMock.mockReturnValueOnce(pending.promise);
+ mount();
+ expect(screen.getByRole('status')).toHaveTextContent('Loading documentation');
+ expect(screen.queryByRole('button', { name: 'Try again' })).toBeNull();
+ pending.resolve(markdown(faq));
+ // FAQ is also the loading title fallback; wait for the fetched section.
+ const heading = await screen.findByRole('heading', { name: 'Answer' });
+ expect(screen.getByRole('heading', { name: 'FAQ' })).toBeInTheDocument();
+ expect(screen.queryByRole('alert')).toBeNull();
+ await waitFor(() => expect(document.activeElement).toBe(heading));
+ });
+
+ it('retries only on request, blocks duplicate activation and restores the exact guide/section', async () => {
+ const pending = deferred<Response>();
+ fetchMock.mockRejectedValueOnce(new Error(privateBody)).mockReturnValueOnce(pending.promise);
+ mount();
+ const button = await screen.findByRole('button', { name: 'Try again' });
+ const location = window.location.href;
+ const historyLength = window.history.length;
+ button.focus();
+ fireEvent.click(button);
+ expect(button).toHaveAttribute('aria-disabled', 'true');
+ expect(button).not.toBeDisabled();
+ expect(document.activeElement).toBe(button);
+ expect(screen.getByRole('status')).toHaveTextContent('Loading documentation');
+ button.click();
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ expect(fetchMock.mock.calls[1]).toEqual(fetchMock.mock.calls[0]);
+ pending.resolve(markdown(faq));
+ const heading = await screen.findByRole('heading', { name: 'Answer' });
+ await waitFor(() => expect(document.activeElement).toBe(heading));
+ expect(scroll).toHaveBeenCalledWith({ block: 'start' });
+ expect(window.location.href).toBe(location);
+ expect(window.history.length).toBe(historyLength);
+ expect(screen.queryByRole('alert')).toBeNull();
+ expect(screen.queryByRole('status')).toBeNull();
+ });
+
+ it('keeps the focused retry control usable after another failed read', async () => {
+ const pending = deferred<Response>();
+ fetchMock
+ .mockResolvedValueOnce(new Response('', { status: 403 }))
+ .mockReturnValueOnce(pending.promise);
+ mount();
+ const button = await screen.findByRole('button', { name: 'Try again' });
+ button.focus();
+ fireEvent.click(button);
+ pending.resolve(new Response(privateBody, { status: 503 }));
+ await waitFor(() => expect(screen.getByRole('alert')).toHaveTextContent(temporary));
+ expect(button).toHaveAttribute('aria-disabled', 'false');
+ expect(document.activeElement).toBe(button);
+ expect(screen.queryByRole('status')).toBeNull();
+ expect(document.body).not.toHaveTextContent('private-upstream-detail');
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ });
+
+ it('allows index navigation during retry and ignores the obsolete response', async () => {
+ const oldRead = deferred<Response>();
+ const indexRead = deferred<Response>();
+ fetchMock
+ .mockRejectedValueOnce(new Error(privateBody))
+ .mockReturnValueOnce(oldRead.promise)
+ .mockReturnValueOnce(indexRead.promise);
+ mount();
+ fireEvent.click(await screen.findByRole('button', { name: 'Try again' }));
+ fireEvent.click(screen.getByRole('link', { name: 'Back to the documentation index' }));
+ await waitFor(() => expect(window.location.pathname).toBe('/docs/README'));
+ expect(screen.queryByRole('alert')).toBeNull();
+ expect(screen.getByRole('status')).toHaveTextContent('Loading documentation');
+ indexRead.resolve(markdown('# Documentation\n\nExisting index.'));
+ expect(await screen.findByRole('heading', { name: 'Documentation' })).toBeInTheDocument();
+ oldRead.resolve(markdown(faq));
+ await oldRead.promise;
+ expect(screen.queryByRole('heading', { name: 'FAQ' })).toBeNull();
+ expect(screen.queryByRole('button', { name: 'Try again' })).toBeNull();
+ expect(document.body).toHaveTextContent('Existing index.');
+ expect(fetchMock.mock.calls.map(([url]) => url)).toEqual([
+ '/docs/FAQ.md',
+ '/docs/FAQ.md',
+ '/docs/README.md',
+ ]);
+ });
+});