From 7b3486999e4b1e16cd052d69c289d36eb093648b Mon Sep 17 00:00:00 2001 From: kleinbem Date: Tue, 17 Nov 2026 02:50:27 +0000 Subject: [PATCH 1/2] feat: health detail, needs-attention panel and start-page polish Foyer showed one dot per service and nothing else from Gatus, so a page used as a start page could not answer what is wrong and since when. - Cards show response time, the last 20 checks and the failure reason; the host bar shows each host's health; the tab title counts what is down. - A 'Needs attention' panel lists services that are down plus the items of an optional JSON feed (attentionUrl). - The last config.json is kept in the browser: the page renders at once and survives a failed fetch instead of showing 'No services configured'. - typeToSearch opens the palette on any letter or digit, and results now rank name matches first, since Enter opens the first one. Co-Authored-By: Claude Fable 5.2 --- AGENTS.md | 5 +- README.md | 32 ++- src/lib/components/AttentionPanel.svelte | 77 +++++++ src/lib/components/CategorySection.svelte | 8 +- src/lib/components/CommandPalette.svelte | 47 ++-- src/lib/components/HostBar.svelte | 13 +- src/lib/components/ServiceCard.svelte | 45 +++- src/lib/config.ts | 24 +- src/lib/data/attention.ts | 101 +++++++++ src/lib/data/gatus.ts | 127 ++++++++--- src/lib/index.ts | 1 + src/lib/portal.ts | 79 ++++++- src/lib/types.ts | 35 +++ src/routes/+page.svelte | 101 +++++++-- test/attention.test.ts | 133 +++++++++++ test/gatus.test.ts | 124 ++++++++++- test/hub.test.ts | 259 ++++++++++++++++++++++ 17 files changed, 1131 insertions(+), 80 deletions(-) create mode 100644 src/lib/components/AttentionPanel.svelte create mode 100644 src/lib/data/attention.ts create mode 100644 test/attention.test.ts create mode 100644 test/hub.test.ts diff --git a/AGENTS.md b/AGENTS.md index 15f7005..0cef6f8 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -8,8 +8,9 @@ Foyer is a pure static SvelteKit 5 SPA (`ssr = false`, `prerender = true`, `200. - **`src/lib/config.ts`**: Runtime `/config.json` parser and loader (`parsePortalConfig`, `loadPortalConfig`, URL scheme sanitization, duplicate-ID filtering). Upstream ships a neutral default in `static/config.json`; fleet deployments inject site inventory via `/config.json`. - **`src/lib/portal.ts`**: Pure domain logic for bookmark validation/creation, multi-token `⌘K` palette search (`#host`, `@category`, `!network`, `>`), category grouping, health metrics, and Open-Meteo parsing. -- **`src/lib/data/gatus.ts`**: Optional client-side Gatus `/api/v1/endpoints/statuses` health polling and endpoint resolution. -- **`src/lib/components/`**: Svelte 5 runes UI components (`Header`, `WeatherWidget`, `HostBar`, `LayoutToggle`, `BookmarksSection`, `CategorySection`, `ServiceCard`, `CommandPalette`). Modals use native `` (`showModal()`). +- **`src/lib/data/gatus.ts`**: Optional client-side Gatus `/api/v1/endpoints/statuses` health polling and endpoint resolution (`fetchGatusSnapshot`: status plus response time, check history and failure reason per endpoint). +- **`src/lib/data/attention.ts`**: The "Needs attention" list: services that are down plus the optional `attentionUrl` JSON feed (`parseAttentionFeed` validates it). +- **`src/lib/components/`**: Svelte 5 runes UI components (`Header`, `WeatherWidget`, `HostBar`, `LayoutToggle`, `BookmarksSection`, `AttentionPanel`, `CategorySection`, `ServiceCard`, `CommandPalette`). Modals use native `` (`showModal()`). - **`test/`**: Hermetic Node `node:test` + Svelte 5 SSR test suite (`test/setup.ts` compiles `.svelte` and `.svelte.js`/`.svelte.ts` on the fly with zero extra npm dependencies). - **`nix/package.nix`**: `nixpkgs`-compliant `buildNpmPackage` derivation (`fetchNpmDeps`, `strictDeps = true`, `__structuredAttrs = true`, `checkPhase`, `installCheckPhase`, and offline Caddy `passthru.tests.smoke`). diff --git a/README.md b/README.md index a58973b..e7f21ff 100644 --- a/README.md +++ b/README.md @@ -7,10 +7,12 @@ Foyer compiles to a pure static SPA (`index.html`, `200.html`, `_app/`) with zer ## Features - **Runtime `/config.json` Catalogue**: Deploy one immutable static build anywhere and mount or serve `/config.json` per environment with strict runtime schema and URL validation. -- **Command Palette (`⌘K` / `/`)**: Multi-token keyboard search across services, pinned bookmarks, and host nodes with `#host`, `@category`, `!network`, and `>` web-search prefixes. +- **Command Palette (`⌘K` / `/`)**: Multi-token keyboard search across services, pinned bookmarks, and host nodes with `#host`, `@category`, `!network`, and `>` web-search prefixes. Matches in the name come first. With `typeToSearch`, typing a letter or digit anywhere on the page opens it. - **Network Reachability Badges**: Distinct indicators for `public`, `mesh`, and `lan` endpoints plus one-click filter chips. -- **Live Gatus Health**: Optional client-side polling against a [Gatus](https://gatus.io) `/api/v1/endpoints/statuses` endpoint with visibility-aware refresh and stale-data indication. -- **Host Node Bar**: Per-host service counts, one-click host filtering, and IP clipboard copy. +- **Live Gatus Health**: Optional client-side polling against a [Gatus](https://gatus.io) `/api/v1/endpoints/statuses` endpoint with visibility-aware refresh and stale-data indication. Each card shows the response time, the outcome of the last 20 checks, and why a failing check failed; the tab title counts the services that are down. +- **Needs Attention**: A panel that lists every service that is down, plus the items of an optional JSON feed (`attentionUrl`), most severe first. It is hidden when there is nothing to show. +- **Host Node Bar**: Per-host service counts and health, one-click host filtering, and IP clipboard copy. +- **Instant Start**: The last loaded `/config.json` is kept in the browser, so the page renders at once and stays usable when the file cannot be fetched. - **Shared Pinned Links**: Optional `links` in `/config.json` show the same pinned links to every visitor, ahead of their own bookmarks. - **Local Quick Bookmarks**: Browser-stored personal links (`localStorage`) in a dedicated native `` modal, immediately searchable from `⌘K`. - **Optional Weather & Clock**: Minute-aligned UTC/local header clock and optional [Open-Meteo](https://open-meteo.com) telemetry widget. @@ -25,6 +27,8 @@ Serve a `/config.json` file at the web root alongside Foyer's static assets (an "subtitle": "Homelab Launchpad", "gatusUrl": "https://status.example.com", "searchUrlTemplate": "https://duckduckgo.com/?q=%s", + "typeToSearch": true, + "attentionUrl": "/attention.json", "weather": { "latitude": 51.5072, "longitude": -0.1276, @@ -69,6 +73,28 @@ Serve a `/config.json` file at the web root alongside Foyer's static assets (an } ``` +### Attention feed + +`attentionUrl` points to a JSON file that anything can write: a cron job, a CI step, a script. Foyer fetches it every five minutes and never sends credentials of its own, so keep tokens in whatever generates the file. + +```json +{ + "items": [ + { + "id": "pr-42", + "title": "Review requested: fix the flux capacitor", + "url": "https://git.example.com/lab/core/pulls/42", + "detail": "Waiting for two days", + "source": "Forgejo", + "severity": "warning", + "updatedAt": "2026-01-15T09:30:00Z" + } + ] +} +``` + +Only `title` is required. `severity` is `critical`, `warning` or `info` (the default). A bare array of items works too; at most 50 items are shown. + ## Development ```bash diff --git a/src/lib/components/AttentionPanel.svelte b/src/lib/components/AttentionPanel.svelte new file mode 100644 index 0000000..6aef592 --- /dev/null +++ b/src/lib/components/AttentionPanel.svelte @@ -0,0 +1,77 @@ + + +{#if items.length > 0} +
+
+

Needs attention

+ {items.length} +
+ +
    + {#each visible as item (item.id)} + {@const sev = SEVERITY[item.severity]} + {@const when = formatRelativeTime(item.updatedAt)} +
  • + {sev.icon} +
    + {#if item.url} + + {item.title} + + {:else} + {item.title} + {/if} + {#if item.detail} +

    {item.detail}

    + {/if} +
    +
    + {#if item.source} + {item.source} + {/if} + {#if when} + + {/if} +
    +
  • + {/each} +
+ + {#if items.length > COLLAPSED_COUNT} + + {/if} +
+{/if} diff --git a/src/lib/components/CategorySection.svelte b/src/lib/components/CategorySection.svelte index 7e22596..2ee620d 100644 --- a/src/lib/components/CategorySection.svelte +++ b/src/lib/components/CategorySection.svelte @@ -1,19 +1,21 @@ { - if (!document.hidden && config.gatusUrl) { - refreshHealth(config.gatusUrl, AbortSignal.timeout(4000)); - } + if (document.hidden) return; + if (config.gatusUrl) refreshHealth(config.gatusUrl, AbortSignal.timeout(4000)); + if (config.attentionUrl) refreshFeed(config.attentionUrl, AbortSignal.timeout(5000)); }} /> @@ -167,7 +235,8 @@ {/if} - + + {#if config.services.length > 0} @@ -194,7 +263,9 @@ {/if}
- {#if config.services.length === 0} + {#if !configReady} +
Loading…
+ {:else if config.services.length === 0}

No services configured

@@ -209,6 +280,7 @@ category={group.category} services={group.services} {healthMap} + {healthDetails} {density} categoryIcons={config.categoryIcons} /> @@ -235,6 +307,7 @@ hosts={config.hosts} searchUrlTemplate={config.searchUrlTemplate} onSelectHost={(hostId) => (selectedHost = selectedHost === hostId ? null : hostId)} + typeToSearch={config.typeToSearch} bind:open={commandPaletteOpen} />

diff --git a/test/attention.test.ts b/test/attention.test.ts new file mode 100644 index 0000000..4224433 --- /dev/null +++ b/test/attention.test.ts @@ -0,0 +1,133 @@ +import * as assert from 'node:assert/strict'; +import { afterEach, describe, it } from 'node:test'; +import { + buildServiceAttention, + fetchAttentionFeed, + parseAttentionFeed, + sortAttention +} from '#lib/data/attention'; +import type { AttentionItem, EndpointDetail, ServiceItem } from '#lib/types'; + +const originalFetch = globalThis.fetch; + +afterEach(() => { + globalThis.fetch = originalFetch; +}); + +describe('parseAttentionFeed', () => { + it('accepts an items object or a bare array and fills defaults', () => { + const wrapped = parseAttentionFeed({ + items: [{ title: ' Review requested ', url: 'https://example.test/pr/1', source: 'GitHub', severity: 'warning' }] + }); + assert.deepEqual(wrapped, [ + { + id: 'feed:https://example.test/pr/1', + title: 'Review requested', + severity: 'warning', + url: 'https://example.test/pr/1', + detail: undefined, + source: 'GitHub', + updatedAt: undefined + } + ]); + assert.equal(parseAttentionFeed([{ title: 'Bare' }])[0].severity, 'info'); + }); + + it('drops entries without a title, unsafe URLs, invalid times and duplicate ids', () => { + const items = parseAttentionFeed([ + null, + 'text', + { url: 'https://example.test' }, + { title: 'Script', url: 'javascript:alert(1)', updatedAt: 'yesterday', severity: 'fatal' }, + { id: 'a', title: 'First', updatedAt: '2026-11-16T10:00:00Z' }, + { id: 'a', title: 'Second' } + ]); + assert.deepEqual( + items.map((i) => [i.id, i.title, i.url, i.updatedAt, i.severity]), + [ + ['feed:Script', 'Script', undefined, undefined, 'info'], + ['feed:a', 'First', undefined, '2026-11-16T10:00:00Z', 'info'] + ] + ); + }); + + it('returns nothing for a non-feed payload and caps the list at 50 items', () => { + for (const bad of [null, 42, 'x', {}, { items: 'none' }]) assert.deepEqual(parseAttentionFeed(bad), []); + const many = Array.from({ length: 80 }, (_, i) => ({ title: `Item ${i}` })); + assert.equal(parseAttentionFeed(many).length, 50); + }); + + it('shortens overlong text', () => { + const [item] = parseAttentionFeed([{ title: 't'.repeat(500), detail: 'd'.repeat(500) }]); + assert.equal(item.title.length, 200); + assert.equal(item.detail?.length, 300); + }); +}); + +describe('fetchAttentionFeed', () => { + it('returns parsed items, and null when the feed is unreachable or not JSON', async () => { + globalThis.fetch = (async () => new Response(JSON.stringify({ items: [{ title: 'One' }] }))) as typeof fetch; + assert.equal((await fetchAttentionFeed('/attention.json'))?.[0].title, 'One'); + + globalThis.fetch = (async () => new Response('', { status: 503 })) as typeof fetch; + assert.equal(await fetchAttentionFeed('/attention.json'), null); + + globalThis.fetch = (async () => new Response('login')) as typeof fetch; + assert.equal(await fetchAttentionFeed('/attention.json'), null); + + globalThis.fetch = (async () => { + throw new TypeError('network'); + }) as typeof fetch; + assert.equal(await fetchAttentionFeed('/attention.json'), null); + }); +}); + +describe('buildServiceAttention', () => { + const service = (id: string, name: string): ServiceItem => ({ + id, name, category: 'Apps', icon: '📦', description: '', url: `https://${id}.example.test`, host: 'core-pi', network: 'mesh' + }); + + it('lists only services whose latest probe failed', () => { + const details: Record = { + paperless: { + name: 'Paperless', status: 'down', history: [true, false], reason: 'connection refused', + checkedAt: '2026-11-16T10:06:00Z', downSince: '2026-11-16T10:03:00Z' + }, + grafana: { name: 'Grafana', status: 'healthy', history: [true] }, + old: { name: 'Old', status: 'down', history: [false], checkedAt: '2026-11-16T10:06:00Z' } + }; + const items = buildServiceAttention( + [service('paperless', 'Paperless'), service('grafana', 'Grafana'), service('old', 'Old'), service('unprobed', 'Unprobed')], + details + ); + assert.deepEqual(items, [ + { + id: 'svc:paperless', title: 'Paperless is down', severity: 'critical', + url: 'https://paperless.example.test', detail: 'connection refused', source: 'core-pi', + updatedAt: '2026-11-16T10:03:00Z' + }, + { + id: 'svc:old', title: 'Old is down', severity: 'critical', + url: 'https://old.example.test', detail: undefined, source: 'core-pi', + updatedAt: '2026-11-16T10:06:00Z' + } + ]); + }); +}); + +describe('sortAttention', () => { + it('orders by severity, then newest first, with undated items last', () => { + const item = (id: string, severity: AttentionItem['severity'], updatedAt?: string): AttentionItem => ({ + id, title: id, severity, updatedAt + }); + const input = [ + item('info-old', 'info', '2026-11-01T00:00:00Z'), + item('warn', 'warning'), + item('crit-undated', 'critical'), + item('info-new', 'info', '2026-11-16T00:00:00Z'), + item('crit-new', 'critical', '2026-11-16T00:00:00Z') + ]; + assert.deepEqual(sortAttention(input).map((i) => i.id), ['crit-new', 'crit-undated', 'warn', 'info-new', 'info-old']); + assert.equal(input[0].id, 'info-old'); + }); +}); diff --git a/test/gatus.test.ts b/test/gatus.test.ts index 2a84f01..aa34332 100644 --- a/test/gatus.test.ts +++ b/test/gatus.test.ts @@ -1,6 +1,6 @@ import * as assert from 'node:assert/strict'; import { afterEach, describe, it } from 'node:test'; -import { fetchGatusStatuses, resolveHealth } from '#lib/data/gatus'; +import { fetchGatusSnapshot, fetchGatusStatuses, resolveDetail, resolveHealth } from '#lib/data/gatus'; const originalFetch = globalThis.fetch; @@ -112,3 +112,125 @@ describe('resolveHealth', () => { assert.equal(resolveHealth({ id: 'unlisted' }, healthMap), 'unknown'); }); }); + +describe('fetchGatusSnapshot', () => { + const NS = 1e6; + function respondWith(endpoints: unknown) { + globalThis.fetch = (async () => new Response(JSON.stringify(endpoints), { status: 200 })) as typeof fetch; + } + + it('reports response time, check time and history of a healthy endpoint', async () => { + respondWith([ + { + name: 'Grafana', + key: 'infra_grafana', + results: [ + { success: false, duration: 5 * NS, timestamp: '2026-11-13T10:00:00Z' }, + { success: true, duration: 83.4 * NS, timestamp: '2026-11-13T10:03:00Z' } + ] + } + ]); + const snapshot = await fetchGatusSnapshot(); + assert.ok(snapshot); + assert.deepEqual(snapshot.details.grafana, { + name: 'Grafana', + status: 'healthy', + history: [false, true], + checkedAt: '2026-11-13T10:03:00Z', + responseMs: 83 + }); + assert.equal(snapshot.details.infra_grafana, snapshot.details.grafana); + assert.equal(snapshot.statuses.grafana, 'healthy'); + }); + + it('gives the reason and start of the current failing run', async () => { + respondWith([ + { + name: 'Paperless', + results: [ + { success: true, duration: NS, timestamp: '2026-11-13T10:00:00Z' }, + { + success: false, duration: NS, timestamp: '2026-11-13T10:03:00Z', + conditionResults: [{ condition: '[STATUS] (502) == 200', success: false }] + }, + { + success: false, duration: NS, timestamp: '2026-11-13T10:06:00Z', + errors: ['dial tcp: connection refused'], + conditionResults: [ + { condition: '[CONNECTED] == true', success: false }, + { condition: '[RESPONSE_TIME] < 3000', success: true } + ] + } + ] + }, + { + name: 'Conditions Only', + results: [ + { + success: false, duration: NS, timestamp: '2026-11-13T10:06:00Z', + conditionResults: [ + { condition: '[STATUS] (503) == 200', success: false }, + { condition: '[BODY].ok == true', success: false }, + { condition: '[RESPONSE_TIME] < 3000', success: true } + ] + } + ] + } + ]); + const snapshot = await fetchGatusSnapshot(); + assert.ok(snapshot); + const paperless = snapshot.details.paperless; + assert.equal(paperless.status, 'down'); + assert.equal(paperless.reason, 'dial tcp: connection refused'); + assert.equal(paperless.downSince, '2026-11-13T10:03:00Z'); + assert.deepEqual(paperless.history, [true, false, false]); + + // Every result in the window failed: the run started before it. + const conditionsOnly = snapshot.details.conditionsonly; + assert.equal(conditionsOnly.reason, '[STATUS] (503) == 200; [BODY].ok == true'); + assert.equal(conditionsOnly.downSince, undefined); + }); + + it('keeps the last 20 results, truncates long reasons and ignores malformed fields', async () => { + const results = Array.from({ length: 30 }, (_, i) => ({ + success: i % 2 === 0, duration: NS, timestamp: `2026-11-13T10:${String(i).padStart(2, '0')}:00Z` + })); + respondWith([ + { name: 'Long History', results }, + { + name: 'Odd Fields', + results: [ + null, + { success: 'yes' }, + { success: false, duration: 'slow', timestamp: 'not a date', errors: ['x'.repeat(500), 7] } + ] + } + ]); + const snapshot = await fetchGatusSnapshot(); + assert.ok(snapshot); + assert.equal(snapshot.details.longhistory.history.length, 20); + assert.equal(snapshot.details.longhistory.history.at(-1), false); + + const odd = snapshot.details.oddfields; + assert.equal(odd.status, 'down'); + assert.deepEqual(odd.history, [false]); + assert.equal(odd.responseMs, undefined); + assert.equal(odd.checkedAt, undefined); + assert.equal(odd.reason?.length, 160); + assert.ok(odd.reason?.endsWith('…')); + }); + + it('returns null when Gatus is unreachable', async () => { + globalThis.fetch = (async () => new Response('', { status: 502 })) as typeof fetch; + assert.equal(await fetchGatusSnapshot(), null); + }); +}); + +describe('resolveDetail', () => { + it('finds a service by its configured endpoint, then by id', () => { + const grafana = { name: 'Grafana', status: 'healthy' as const, history: [true] }; + assert.equal(resolveDetail({ id: 'monitoring', gatusEndpoint: 'Grafana' }, { grafana }), grafana); + assert.equal(resolveDetail({ id: 'grafana' }, { grafana }), grafana); + assert.equal(resolveDetail({ id: 'other' }, { grafana }), undefined); + }); +}); diff --git a/test/hub.test.ts b/test/hub.test.ts new file mode 100644 index 0000000..0b71f11 --- /dev/null +++ b/test/hub.test.ts @@ -0,0 +1,259 @@ +import * as assert from 'node:assert/strict'; +import { afterEach, describe, it } from 'node:test'; +import { render } from 'svelte/server'; +import AttentionPanel from '#lib/components/AttentionPanel.svelte'; +import CategorySection from '#lib/components/CategorySection.svelte'; +import HostBar from '#lib/components/HostBar.svelte'; +import ServiceCard from '#lib/components/ServiceCard.svelte'; +import { loadPortalConfig, parseCachedConfig, parsePortalConfig } from '#lib/config'; +import { + computeServiceMetrics, describeHealth, filterPaletteEntries, formatRelativeTime, formatResponseTime, isTypeToSearchKey +} from '#lib/portal'; +import type { PaletteEntry } from '#lib/portal'; +import type { AttentionItem, EndpointDetail, ServiceItem } from '#lib/types'; + +const originalFetch = globalThis.fetch; + +afterEach(() => { + globalThis.fetch = originalFetch; +}); + +const NOW = new Date('2026-11-16T12:00:00Z'); + +const service: ServiceItem = { + id: 'paperless', name: 'Paperless', category: 'Documents', icon: '📄', description: 'Document archive.', + url: 'https://paperless.example.test', host: 'nasbook', network: 'mesh' +}; + +const healthyDetail: EndpointDetail = { + name: 'Paperless', status: 'healthy', history: [true, false, true, true], responseMs: 83, + checkedAt: '2026-11-16T11:58:00Z' +}; + +const downDetail: EndpointDetail = { + name: 'Paperless', status: 'down', history: [true, false, false], responseMs: 12, + checkedAt: '2026-11-16T11:59:30Z', downSince: '2026-11-16T09:00:00Z', reason: 'connection refused' +}; + +describe('formatRelativeTime', () => { + it('uses minutes, hours and days, and is empty for missing, invalid or future times', () => { + assert.equal(formatRelativeTime('2026-11-16T11:59:30Z', NOW), 'just now'); + assert.equal(formatRelativeTime('2026-11-16T11:55:00Z', NOW), '5 min ago'); + assert.equal(formatRelativeTime('2026-11-16T09:00:00Z', NOW), '3 h ago'); + assert.equal(formatRelativeTime('2026-11-14T13:00:00Z', NOW), '47 h ago'); + assert.equal(formatRelativeTime('2026-11-13T12:00:00Z', NOW), '3 d ago'); + assert.equal(formatRelativeTime(undefined, NOW), ''); + assert.equal(formatRelativeTime('soon', NOW), ''); + assert.equal(formatRelativeTime('2026-11-16T12:05:00Z', NOW), ''); + }); +}); + +describe('filterPaletteEntries ranking', () => { + const entry = (name: string, description = ''): PaletteEntry => ({ + id: name, kind: 'service', name, description, icon: '📦', category: 'Apps' + }); + const entries = [ + entry('Buzz', 'Team chat with pairing relay'), + entry('Status', 'Fleet uptime page'), + entry('Nix Detour', 'Nixpkgs patch tracker'), + entry('Paperless-ngx', 'Document archive'), + entry('Grafana', 'Dashboards'), + entry('Spa Control', 'Pool') + ]; + const names = (query: string) => filterPaletteEntries(entries, query).map((e) => e.name); + + it('puts name matches before description matches, prefixes first', () => { + assert.deepEqual(names('pa'), ['Paperless-ngx', 'Spa Control', 'Buzz', 'Status', 'Nix Detour']); + assert.deepEqual(names('det'), ['Nix Detour']); + }); + + it('keeps the configured order without search words and among equal matches', () => { + assert.deepEqual(names(''), entries.map((e) => e.name)); + assert.deepEqual(names('@apps'), entries.map((e) => e.name)); + // All four match "t" in the name only as a later letter or word start: order as configured. + assert.deepEqual(names('tr'), ['Spa Control', 'Nix Detour']); + assert.deepEqual(names('s'), ['Status', 'Spa Control', 'Paperless-ngx', 'Buzz', 'Nix Detour', 'Grafana']); + }); +}); + +describe('formatResponseTime', () => { + it('never shows 0 ms and switches to seconds from one second on', () => { + assert.equal(formatResponseTime(0), '<1 ms'); + assert.equal(formatResponseTime(83), '83 ms'); + assert.equal(formatResponseTime(999), '999 ms'); + assert.equal(formatResponseTime(1240), '1.2 s'); + }); +}); + +describe('describeHealth', () => { + it('summarises a healthy, a failing and an unchecked service', () => { + assert.equal(describeHealth('healthy', healthyDetail, NOW), 'Operational · 83 ms · checked 2 min ago'); + assert.equal( + describeHealth('down', downDetail, NOW), + 'Offline · connection refused · since 3 h ago · checked just now' + ); + assert.equal(describeHealth('unknown', undefined, NOW), 'No health check'); + }); +}); + +describe('isTypeToSearchKey', () => { + const key = (k: string, mods: Partial = {}) => + ({ key: k, ctrlKey: false, metaKey: false, altKey: false, isComposing: false, ...mods }) as KeyboardEvent; + + it('accepts single letters and digits, also non-ASCII ones', () => { + for (const k of ['a', 'Z', '7', 'ä', 'é']) assert.equal(isTypeToSearchKey(key(k)), true, k); + }); + + it('rejects named keys, punctuation, space, shortcuts and IME composition', () => { + for (const k of ['Enter', 'Tab', 'F5', 'ArrowDown', ' ', '.', '?', 'Dead']) { + assert.equal(isTypeToSearchKey(key(k)), false, k); + } + assert.equal(isTypeToSearchKey(key('r', { ctrlKey: true })), false); + assert.equal(isTypeToSearchKey(key('l', { metaKey: true })), false); + assert.equal(isTypeToSearchKey(key('d', { altKey: true })), false); + assert.equal(isTypeToSearchKey(key('k', { isComposing: true })), false); + }); +}); + +describe('computeServiceMetrics host health', () => { + it('marks a host down when any of its services is, healthy when all checked ones are', () => { + const svc = (id: string, host: string): ServiceItem => ({ ...service, id, host }); + const metrics = computeServiceMetrics( + [svc('a', 'mixed'), svc('b', 'mixed'), svc('c', 'fine'), svc('d', 'fine'), svc('e', 'unchecked')], + { a: 'healthy', b: 'down', c: 'healthy' } + ); + assert.equal(metrics.hostHealth.mixed, 'down'); + assert.equal(metrics.hostHealth.fine, 'healthy'); + assert.equal(metrics.hostHealth.unchecked, undefined); + assert.equal(metrics.hostHealth.toString, undefined); + + const downFirst = computeServiceMetrics([svc('b', 'h'), svc('a', 'h')], { a: 'healthy', b: 'down' }); + assert.equal(downFirst.hostHealth.h, 'down'); + }); +}); + +describe('config: attention feed, type-to-search and the cached copy', () => { + it('accepts a safe attentionUrl and an explicit typeToSearch only', () => { + const on = parsePortalConfig({ attentionUrl: '/attention.json', typeToSearch: true }); + assert.equal(on.attentionUrl, '/attention.json'); + assert.equal(on.typeToSearch, true); + + const off = parsePortalConfig({ attentionUrl: 'javascript:alert(1)', typeToSearch: 'yes' }); + assert.equal(off.attentionUrl, undefined); + assert.equal(off.typeToSearch, false); + assert.equal(parsePortalConfig({ attentionUrl: '//evil.example.test/feed' }).attentionUrl, undefined); + }); + + it('returns the raw body with a loaded config, and none with the default', async () => { + const body = JSON.stringify({ title: 'Lab', links: [{ name: 'Docs', url: 'https://docs.example.test' }] }); + globalThis.fetch = (async () => new Response(body)) as typeof fetch; + const loaded = await loadPortalConfig(); + assert.equal(loaded.raw, body); + assert.equal(loaded.config.title, 'Lab'); + + // Parsing the cached body again gives the same config: link ids are not prefixed twice. + assert.deepEqual(parseCachedConfig(loaded.raw ?? null), loaded.config); + + globalThis.fetch = (async () => new Response('', { status: 404 })) as typeof fetch; + assert.equal((await loadPortalConfig()).raw, undefined); + globalThis.fetch = (async () => new Response('[1]')) as typeof fetch; + assert.equal((await loadPortalConfig()).raw, undefined); + }); + + it('ignores a missing or damaged cached copy', () => { + for (const bad of [null, '', '{broken', '[]', '"text"', 'null']) assert.equal(parseCachedConfig(bad), null); + }); +}); + +describe('ServiceCard health detail', () => { + it('shows response time, recent checks and a descriptive tooltip when healthy', () => { + const { body } = render(ServiceCard, { props: { service, health: 'healthy', detail: healthyDetail } }); + assert.match(body, /83 ms/); + assert.match(body, /3 of 4 recent checks passed/); + assert.match(body, /title="Operational · 83 ms · checked/); + }); + + it('shows why a service is down, without a response time', () => { + const { body } = render(ServiceCard, { props: { service, health: 'down', detail: downDetail } }); + assert.match(body, /connection refused/); + assert.match(body, /1 of 3 recent checks passed/); + assert.doesNotMatch(body, /12 ms/); + }); + + it('renders as before without detail, in every density', () => { + for (const density of ['comfortable', 'compact', 'list'] as const) { + const { body } = render(ServiceCard, { props: { service, density } }); + assert.match(body, /title="No health check"/); + assert.doesNotMatch(body, /recent checks passed/); + } + }); + + it('escapes a failure reason that contains markup', () => { + const detail: EndpointDetail = { ...downDetail, reason: '' }; + const { body } = render(ServiceCard, { props: { service, health: 'down', detail } }); + assert.doesNotMatch(body, / { + const { body } = render(CategorySection, { + props: { + category: 'Documents', services: [service], + healthMap: { paperless: 'down' }, healthDetails: { paperless: downDetail } + } + }); + assert.match(body, /connection refused/); + }); +}); + +describe('HostBar health', () => { + it('labels hosts with checked services and leaves the others unmarked', () => { + const { body } = render(HostBar, { + props: { + hosts: [ + { id: 'up', name: 'up-host', role: 'Node' }, + { id: 'bad', name: 'bad-host', role: 'Node' }, + { id: 'none', name: 'quiet-host', role: 'Node' } + ], + health: { up: 'healthy', bad: 'down' } + } + }); + assert.equal(body.match(/All checked services up/g)?.length, 3); + assert.equal(body.match(/Has services that are down/g)?.length, 3); + assert.equal(body.match(/role="status"/g)?.length, 2); + }); +}); + +describe('AttentionPanel', () => { + const item = (n: number, extra: Partial = {}): AttentionItem => ({ + id: `i${n}`, title: `Item ${n}`, severity: 'info', ...extra + }); + + it('renders nothing without items', () => { + assert.doesNotMatch(render(AttentionPanel, { props: { items: [] } }).body, /
{ + const items = [ + item(1, { + severity: 'critical', url: 'https://example.test/1', detail: 'connection refused', source: 'nasbook' + }), + ...[2, 3, 4, 5, 6, 7].map((n) => item(n)) + ]; + const { body } = render(AttentionPanel, { props: { items } }); + assert.match(body, /Needs attention/); + assert.match(body, /href="https:\/\/example\.test\/1"/); + assert.match(body, /rel="noopener noreferrer"/); + assert.match(body, /connection refused/); + assert.match(body, /nasbook/); + assert.match(body, /Item 5/); + assert.doesNotMatch(body, /Item 6/); + assert.match(body, /Show 2 more/); + assert.match(body, /border-status-danger-border/); + }); + + it('renders an item without a URL as plain text', () => { + const { body } = render(AttentionPanel, { props: { items: [item(1)] } }); + assert.doesNotMatch(body, / Date: Tue, 17 Nov 2026 03:05:31 +0000 Subject: [PATCH 2/2] fix: polling owned per configuration A config replaced while a health or feed request was pending aborted that request, and the shared in-flight flag then made the replacement skip its first fetch: with the cached config this delayed health by 30 s and the feed by 5 min on every load. Visibility refreshes also used their own signal, so a late answer for an old config could still be applied. startPolling gives each effect its own controller and in-flight state, and the effects now depend on the URLs only. Co-Authored-By: Claude Fable 5.2 --- AGENTS.md | 1 + src/lib/index.ts | 1 + src/lib/poll.ts | 47 ++++++++++++++ src/routes/+page.svelte | 89 ++++++++++---------------- test/poll.test.ts | 134 ++++++++++++++++++++++++++++++++++++++++ 5 files changed, 214 insertions(+), 58 deletions(-) create mode 100644 src/lib/poll.ts create mode 100644 test/poll.test.ts diff --git a/AGENTS.md b/AGENTS.md index 0cef6f8..271f152 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -9,6 +9,7 @@ Foyer is a pure static SvelteKit 5 SPA (`ssr = false`, `prerender = true`, `200. - **`src/lib/config.ts`**: Runtime `/config.json` parser and loader (`parsePortalConfig`, `loadPortalConfig`, URL scheme sanitization, duplicate-ID filtering). Upstream ships a neutral default in `static/config.json`; fleet deployments inject site inventory via `/config.json`. - **`src/lib/portal.ts`**: Pure domain logic for bookmark validation/creation, multi-token `⌘K` palette search (`#host`, `@category`, `!network`, `>`), category grouping, health metrics, and Open-Meteo parsing. - **`src/lib/data/gatus.ts`**: Optional client-side Gatus `/api/v1/endpoints/statuses` health polling and endpoint resolution (`fetchGatusSnapshot`: status plus response time, check history and failure reason per endpoint). +- **`src/lib/poll.ts`**: `startPolling`, the visibility-aware poller behind the Gatus and attention-feed refresh; each call owns and aborts its own requests. - **`src/lib/data/attention.ts`**: The "Needs attention" list: services that are down plus the optional `attentionUrl` JSON feed (`parseAttentionFeed` validates it). - **`src/lib/components/`**: Svelte 5 runes UI components (`Header`, `WeatherWidget`, `HostBar`, `LayoutToggle`, `BookmarksSection`, `AttentionPanel`, `CategorySection`, `ServiceCard`, `CommandPalette`). Modals use native `` (`showModal()`). - **`test/`**: Hermetic Node `node:test` + Svelte 5 SSR test suite (`test/setup.ts` compiles `.svelte` and `.svelte.js`/`.svelte.ts` on the fly with zero extra npm dependencies). diff --git a/src/lib/index.ts b/src/lib/index.ts index 854bc3f..caad92d 100644 --- a/src/lib/index.ts +++ b/src/lib/index.ts @@ -3,3 +3,4 @@ export * from './config'; export * from './portal'; export * from './data/gatus'; export * from './data/attention'; +export * from './poll'; diff --git a/src/lib/poll.ts b/src/lib/poll.ts new file mode 100644 index 0000000..3abedeb --- /dev/null +++ b/src/lib/poll.ts @@ -0,0 +1,47 @@ +/** The parts of `document` a poller needs; tests pass a stand-in. */ +export interface VisibilitySource { + readonly hidden: boolean; + addEventListener(type: 'visibilitychange', listener: () => void): void; + removeEventListener(type: 'visibilitychange', listener: () => void): void; +} + +/** + * Calls `load` now, every `intervalMs`, and when the page becomes visible again; never while it is + * hidden and never twice at once. Each poller owns its requests: the returned stop function aborts + * the one in flight and drops its result, and a new poller starts fetching at once. + */ +export function startPolling( + load: (signal: AbortSignal) => Promise, + onResult: (value: T) => void, + intervalMs: number, + doc: VisibilitySource = document +): () => void { + const controller = new AbortController(); + let inFlight = false; + + async function refresh() { + if (inFlight || doc.hidden || controller.signal.aborted) return; + inFlight = true; + try { + const value = await load(controller.signal); + if (!controller.signal.aborted) onResult(value); + } catch { + // The loaders report failure through their result; a throw only skips this round. + } finally { + inFlight = false; + } + } + + const onVisibilityChange = () => { + if (!doc.hidden) refresh(); + }; + + refresh(); + const interval = setInterval(refresh, intervalMs); + doc.addEventListener('visibilitychange', onVisibilityChange); + return () => { + controller.abort(); + clearInterval(interval); + doc.removeEventListener('visibilitychange', onVisibilityChange); + }; +} diff --git a/src/routes/+page.svelte b/src/routes/+page.svelte index 2666c50..368c271 100644 --- a/src/routes/+page.svelte +++ b/src/routes/+page.svelte @@ -10,6 +10,7 @@ import { DEFAULT_CONFIG, loadPortalConfig, parseCachedConfig } from '#lib/config'; import { buildServiceAttention, fetchAttentionFeed, sortAttention } from '#lib/data/attention'; import { fetchGatusSnapshot } from '#lib/data/gatus'; + import { startPolling } from '#lib/poll'; import { computeServiceMetrics, filterServices, groupServicesByCategory, type NetworkFilter } from '#lib/portal'; import type { AttentionItem, EndpointDetail, HealthStatus, LayoutDensity, PinnedBookmark, PortalConfig @@ -111,80 +112,52 @@ return () => controller.abort(); }); - let gatusInFlight = false; - async function refreshHealth(gatusUrl: string, signal: AbortSignal) { - if (gatusInFlight || document.hidden) return; - gatusInFlight = true; - try { - const next = await fetchGatusSnapshot(gatusUrl, signal); - if (signal.aborted) return; - if (next) { - healthMap = next.statuses; - healthDetails = next.details; - healthUpdatedAt = new Date(); - healthStale = false; - } else { - healthStale = true; - } - } finally { - gatusInFlight = false; - } - } + // Primitives, so replacing the config with one that has the same URLs restarts nothing. + let gatusUrl = $derived(config.gatusUrl); + let attentionUrl = $derived(config.attentionUrl); $effect(() => { - const gatusUrl = config.gatusUrl; - if (!gatusUrl) { + const url = gatusUrl; + if (!url) { healthMap = {}; healthDetails = {}; healthStale = false; return; } - const controller = new AbortController(); - refreshHealth(gatusUrl, controller.signal); - const interval = setInterval(() => refreshHealth(gatusUrl, controller.signal), 30_000); - return () => { - controller.abort(); - clearInterval(interval); - }; + return startPolling( + (signal) => fetchGatusSnapshot(url, signal), + (next) => { + // An unreachable Gatus keeps the last known health, marked stale. + if (next) { + healthMap = next.statuses; + healthDetails = next.details; + healthUpdatedAt = new Date(); + healthStale = false; + } else { + healthStale = true; + } + }, + 30_000 + ); }); - let feedInFlight = false; - async function refreshFeed(attentionUrl: string, signal: AbortSignal) { - if (feedInFlight || document.hidden) return; - feedInFlight = true; - try { - const next = await fetchAttentionFeed(attentionUrl, signal); - // An unreachable feed keeps the last items. - if (next && !signal.aborted) feedItems = next; - } finally { - feedInFlight = false; - } - } - $effect(() => { - const attentionUrl = config.attentionUrl; - if (!attentionUrl) { + const url = attentionUrl; + if (!url) { feedItems = []; return; } - const controller = new AbortController(); - refreshFeed(attentionUrl, controller.signal); - const interval = setInterval(() => refreshFeed(attentionUrl, controller.signal), 5 * 60_000); - return () => { - controller.abort(); - clearInterval(interval); - }; + return startPolling( + (signal) => fetchAttentionFeed(url, signal), + (next) => { + // An unreachable feed keeps the last items. + if (next) feedItems = next; + }, + 5 * 60_000 + ); }); - { - if (document.hidden) return; - if (config.gatusUrl) refreshHealth(config.gatusUrl, AbortSignal.timeout(4000)); - if (config.attentionUrl) refreshFeed(config.attentionUrl, AbortSignal.timeout(5000)); - }} -/> -
void>(); + const doc = { + hidden, + addEventListener: (_type: 'visibilitychange', l: () => void) => void listeners.add(l), + removeEventListener: (_type: 'visibilitychange', l: () => void) => void listeners.delete(l) + }; + return { + doc: doc as VisibilitySource, + listeners, + show() { + doc.hidden = false; + for (const l of listeners) l(); + }, + hide() { + doc.hidden = true; + for (const l of listeners) l(); + } + }; +} + +/** A loader whose requests stay pending until the test settles them. */ +function deferredLoader() { + const calls: Array<{ signal: AbortSignal; resolve: (value: string) => void }> = []; + const load = (signal: AbortSignal) => + new Promise((resolve) => { + calls.push({ signal, resolve }); + }); + return { calls, load }; +} + +const settle = () => new Promise((r) => setTimeout(r, 0)); +const wait = (ms: number) => new Promise((r) => setTimeout(r, ms)); + +describe('startPolling', () => { + it('loads at once, then on every interval, and stops when told', async () => { + const { doc } = fakeDocument(); + const results: number[] = []; + let n = 0; + const stop = startPolling(async () => ++n, (v) => results.push(v), 15, doc); + await settle(); + assert.deepEqual(results, [1]); + + await wait(80); + assert.ok(results.length >= 3, `expected repeated loads, got ${results.length}`); + + stop(); + const seen = results.length; + await wait(60); + assert.equal(results.length, seen); + }); + + it('does not start a second request while one is in flight', async () => { + const { doc, show } = fakeDocument(); + const { calls, load } = deferredLoader(); + const stop = startPolling(load, () => {}, 10, doc); + await wait(50); + show(); + assert.equal(calls.length, 1); + + calls[0].resolve('done'); + await wait(40); + assert.ok(calls.length >= 2); + stop(); + }); + + it('a stopped poller aborts its request, drops the late result, and does not block its successor', async () => { + const { doc } = fakeDocument(); + const first = deferredLoader(); + const second = deferredLoader(); + const results: string[] = []; + + const stopFirst = startPolling(first.load, (v) => results.push(v), 60_000, doc); + stopFirst(); + assert.equal(first.calls[0].signal.aborted, true); + + // The successor fetches immediately although the first request has not settled. + const stopSecond = startPolling(second.load, (v) => results.push(v), 60_000, doc); + assert.equal(second.calls.length, 1); + + first.calls[0].resolve('stale'); + second.calls[0].resolve('fresh'); + await settle(); + assert.deepEqual(results, ['fresh']); + stopSecond(); + }); + + it('waits while the page is hidden and refreshes when it is shown again', async () => { + const page = fakeDocument(true); + const results: string[] = []; + const stop = startPolling(async () => 'value', (v) => results.push(v), 60_000, page.doc); + await settle(); + assert.deepEqual(results, []); + + page.show(); + await settle(); + assert.deepEqual(results, ['value']); + + page.hide(); + await settle(); + assert.deepEqual(results, ['value']); + + stop(); + assert.equal(page.listeners.size, 0); + page.show(); + await settle(); + assert.deepEqual(results, ['value']); + }); + + it('survives a loader that throws', async () => { + const { doc } = fakeDocument(); + const results: string[] = []; + let fail = true; + const stop = startPolling( + async () => { + if (fail) throw new Error('boom'); + return 'ok'; + }, + (v) => results.push(v), + 10, + doc + ); + await settle(); + assert.deepEqual(results, []); + fail = false; + await wait(50); + assert.equal(results[0], 'ok'); + stop(); + }); +});