Hub stage 4: config history, rollback, drift check, baseline export and import

Every saved config, and every earlier baseline, is listed per app. You
can view it, diff it against a server's current config, and roll it back
through preview and apply. Earlier baselines can be restored.

A drift check (HUB_DRIFT_MINUTES, default 15) compares each server with
its effective config. Drift shows in the header and the matrix, with
Accept as baseline and Revert to baseline. All baselines export to one
file. Importing that file shows a dry run before it writes.

Rolling back preselects, and diffs against, the server the version came
from. The line-diff op "del" is renamed to "remove" for the language lint.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
DenozordecandClaude Opus 5.5 committed 2026-10-31 19:57:33 +07:00
1 parent 0e05039202
commit 57e492cceb
29 files changed
+2294 -125

No files matched your search

+94 -2
View File
@@ -1,4 +1,5 @@
import { apiRequest, type ApiOutcome } from './client'
import { urlApi } from '../app/base'
import { apiRequest, envelopeOutcome, type ApiOutcome } from './client'
/*
The nine endpoints of the `apps` family (upstream/master:www/js/apps.js).
@@ -276,7 +277,7 @@ export interface FieldChange {
}
export interface LineOp {
op: 'same' | 'add' | 'del'
op: 'same' | 'add' | 'remove'
text: string
}
@@ -358,3 +359,94 @@ export const previewConfig = (token: string | null, name: string, targets: strin
export const applyConfig = (token: string | null, name: string, targets: string[], expect: Record<string, string>): Promise<RunOutcome> =>
apiRequest('hub/apps/config/apply', { token, method: 'POST', body: { name, targets: targets.join(','), expect: JSON.stringify(expect) } })
/*
History, rollback, drift, and moving baselines between hubs (hub/apps-config.ts, hub/drift.ts).
*/
export interface HistoryEntry {
id: string
at: string
/** A server id, or `baseline` for an earlier text of the baseline. */
server: string
kind: string
size: number
hash: string
}
export interface HistoryDiff {
entry: HistoryEntry
server: string
writable: boolean
current: string
currentHash: string
version: string
changes: ConfigDiff
unchanged: boolean
}
export type DriftKind = 'differs' | 'unreadable' | 'not-installed'
export interface DriftEntry {
app: string
server: string
since: string
kind: DriftKind
}
export interface DriftState {
checkedAt: string | null
apps: DriftEntry[]
checking?: boolean
}
export interface ImportPlan {
apps: { app: string; status: 'new' | 'changed' | 'same'; ignoredServers: string[] }[]
applied: boolean
}
export const getHistory = (token: string | null, name: string): Promise<ApiOutcome<{ response: { entries: HistoryEntry[] } }>> =>
apiRequest('hub/apps/history/list', { token, body: { name } })
export const getHistoryEntry = (token: string | null, name: string, id: string): Promise<ApiOutcome<{ response: { entry: HistoryEntry; text: string } }>> =>
apiRequest('hub/apps/history/get', { token, body: { name, id } })
export const getHistoryDiff = (token: string | null, name: string, id: string, server: string): Promise<ApiOutcome<{ response: HistoryDiff }>> =>
apiRequest('hub/apps/history/diff', { token, body: { name, id, server } })
export const rollbackHistory = (token: string | null, name: string, id: string, targets: string[], expect: Record<string, string>): Promise<RunOutcome> =>
apiRequest('hub/apps/history/rollback', { token, method: 'POST', body: { name, id, targets: targets.join(','), expect: JSON.stringify(expect) } })
export const restoreBaseline = (token: string | null, name: string, id: string): Promise<ApiOutcome<{ response: { baseline: Baseline } }>> =>
apiRequest('hub/apps/baseline/restore', { token, method: 'POST', body: { name, id } })
export const getDrift = (token: string | null): Promise<ApiOutcome<{ response: DriftState }>> => apiRequest('hub/drift/get', { token })
export const checkDrift = (token: string | null): Promise<ApiOutcome<{ response: DriftState }>> => apiRequest('hub/drift/check', { token, method: 'POST', body: {} })
export const acceptDrift = (token: string | null, name: string, server: string): Promise<ApiOutcome<{ response: { baseline: Baseline } }>> =>
apiRequest('hub/apps/drift/accept', { token, method: 'POST', body: { name, server } })
export const importBaselines = (token: string | null, data: string, apply: boolean): Promise<ApiOutcome<{ response: ImportPlan }>> =>
apiRequest('hub/apps/import', { token, method: 'POST', body: { data, apply: apply ? 'true' : 'false' } })
/* The file of all baselines. A download is not the usual envelope, so it is read here (as the rule lists are). */
export async function exportBaselines(token: string | null): Promise<ApiOutcome<{ filename: string; text: string }>> {
const headers: Record<string, string> = {}
if (token) headers.Authorization = `Bearer ${token}`
let res: Response
let text: string
try {
res = await fetch(urlApi('api/hub/apps/export'), { headers })
text = await res.text()
} catch {
return { kind: 'error', message: 'Unable to connect to the server. Please try again.' }
}
try {
const env = JSON.parse(text) as { status?: string; hub?: string }
if (env.status !== undefined && env.status !== 'ok') return envelopeOutcome<{ filename: string; text: string }>(env, token)
} catch {
return { kind: 'error', message: 'The hub did not send a file.' }
}
const filename = /filename="([^"]+)"/.exec(res.headers.get('content-disposition') ?? '')?.[1] ?? 'hub-baselines.json'
return { kind: 'ok', data: { filename, text } }
}
+47
View File
@@ -0,0 +1,47 @@
import { useSyncExternalStore } from 'react'
import { getDrift, type DriftEntry } from './apps'
/*
Which servers no longer have the config the hub says they should. The session carries only a count
(`info.hubDrift`), cheap enough to read at sign-in; the list comes from `hub/drift/get`. The header
subscribes to this store, and the screens that fix a drift call `refreshHubDrift` afterwards.
*/
interface State {
count: number
entries: readonly DriftEntry[]
}
let current: State = { count: 0, entries: [] }
const listeners = new Set<() => void>()
function set(next: State): void {
if (next.count === current.count && next.entries.length === current.entries.length && next.entries.every((e, i) => e === current.entries[i])) return
current = next
for (const fn of listeners) fn()
}
/** The count from the session, before the list is read. */
export function setHubDriftCount(count: number): void {
if (current.entries.length === 0) set({ count, entries: [] })
}
export async function refreshHubDrift(token: string | null): Promise<void> {
const outcome = await getDrift(token)
if (outcome.kind !== 'ok') return
const entries = Array.isArray(outcome.data.response?.apps) ? outcome.data.response.apps : []
set({ count: entries.filter((e) => e.kind === 'differs').length, entries })
}
export function resetHubDrift(): void {
set({ count: 0, entries: [] })
}
const subscribe = (fn: () => void): (() => void) => {
listeners.add(fn)
return () => listeners.delete(fn)
}
const snapshot = (): State => current
export function useHubDrift(): State {
return useSyncExternalStore(subscribe, snapshot, snapshot)
}
+137
View File
@@ -0,0 +1,137 @@
import { useState } from 'react'
import { acceptDrift, checkDrift, type DriftEntry } from '../api/apps'
import { refreshHubDrift, useHubDrift } from '../api/hub-drift'
import { AppConfigSync } from '../screens/apps/AppConfigSync'
import { applyRequest } from '../screens/apps/applyRequest'
import { RunFlow, pickerServers, type RunRequest } from '../screens/apps/RunFlow'
import { Alert } from '../ui/Alert'
import { Button } from '../ui/Button'
import { Confirm } from '../ui/Confirm'
import { Dialog } from '../ui/Dialog'
import { Empty } from '../ui/Empty'
import { Tag } from '../ui/Tag'
import styles from './Shell.module.css'
/*
Behind a hub: a mark in the header when a server no longer has the config the hub says it should
(someone changed it in that server's own console), and the list of them. Each can be looked at in
the app's config view; a writer can accept the server's config as the new baseline, or revert the
server to the baseline after a preview.
*/
const KIND = { differs: 'Differs', unreadable: 'Cannot read', 'not-installed': 'Not installed' } as const
export function DriftStatus({ token, canWrite, writable }: { token: string | null; canWrite: boolean; writable: string[] }) {
const { count, entries } = useHubDrift()
const [open, setOpen] = useState(false)
const [configApp, setConfigApp] = useState<string | null>(null)
const [request, setRequest] = useState<RunRequest | null>(null)
const [accepting, setAccepting] = useState<DriftEntry | null>(null)
const [problem, setProblem] = useState<string | null>(null)
const [busy, setBusy] = useState(false)
if (count === 0 && !open) return null
async function accept(entry: DriftEntry) {
setBusy(true)
setProblem(null)
const outcome = await acceptDrift(token, entry.app, entry.server)
setBusy(false)
if (outcome.kind !== 'ok') setProblem(outcome.kind === 'error' ? outcome.message : 'The session ended.')
await refreshHubDrift(token)
}
async function checkNow() {
setBusy(true)
setProblem(null)
const outcome = await checkDrift(token)
setBusy(false)
if (outcome.kind !== 'ok') setProblem(outcome.kind === 'error' ? outcome.message : 'The session ended.')
await refreshHubDrift(token)
}
function revert(entry: DriftEntry) {
setRequest(
applyRequest(token, entry.app, pickerServers([{ id: entry.server, writable: writable.includes(entry.server) }]), [entry.server]),
)
}
return (
<>
<button type="button" className={styles.status} data-attention="true" aria-label="Config drift" onClick={() => setOpen(true)}>
<i className={styles.pdot} data-tone="warn" />
<span className={styles.lbl}>{`${count} config ${count === 1 ? 'drift' : 'drifts'}`}</span>
</button>
<Dialog
open={open}
onOpenChange={setOpen}
size="medium"
title="Config drift"
actions={
canWrite ? (
<Button disabled={busy} onClick={() => void checkNow()}>
Check now
</Button>
) : undefined
}
>
<p className="m-0 text-sm text-muted-foreground">
These servers no longer have the config the hub expects: the baseline plus the server's own local fields.
</p>
{problem !== null && <Alert type="danger" title="Error">{problem}</Alert>}
{entries.length === 0 ? (
<Empty title="No drift">Every server has the config the hub expects.</Empty>
) : (
<ul className="m-0 flex list-none flex-col gap-3 p-0" aria-label="Drifts">
{entries.map((e) => (
<li key={`${e.app}/${e.server}`} aria-label={`${e.app} on ${e.server}`} className="flex flex-wrap items-center gap-3 border-b border-border pb-3 text-sm last:border-b-0">
<span className="font-medium">{e.app}</span>
<span>{e.server}</span>
<Tag tone={e.kind === 'differs' ? 'warn' : 'neutral'}>{KIND[e.kind]}</Tag>
<span className="text-xs text-muted-foreground">since {new Date(e.since).toLocaleString()}</span>
<span className="ml-auto flex flex-wrap gap-2">
<Button size="sm" onClick={() => setConfigApp(e.app)}>
Open config
</Button>
{canWrite && e.kind === 'differs' && (
<>
<Button size="sm" disabled={busy} onClick={() => setAccepting(e)}>
Accept as baseline
</Button>
<Button size="sm" variant="primary" disabled={busy} onClick={() => revert(e)}>
Revert to baseline
</Button>
</>
)}
</span>
</li>
))}
</ul>
)}
</Dialog>
<Confirm
open={accepting !== null}
title="Accept as baseline"
text={`Make the config of ${accepting?.app ?? ''} on ${accepting?.server ?? ''} the baseline? The other servers will then differ from it. The old baseline is kept in the history.`}
label="Accept"
onClose={() => setAccepting(null)}
onConfirm={() => accepting && accept(accepting)}
/>
{configApp !== null && (
<AppConfigSync token={token} name={configApp} canWrite={canWrite} onClose={() => setConfigApp(null)} onChanged={() => void refreshHubDrift(token)} />
)}
{request !== null && (
<RunFlow
request={request}
onClose={(changed) => {
setRequest(null)
if (changed) void checkDrift(token).then(() => refreshHubDrift(token))
}}
/>
)}
</>
)
}
+20 -1
View File
@@ -1,5 +1,5 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { act, render, screen } from '@testing-library/react'
import { act, cleanup, render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { Shell, type ShellSession } from './Shell'
import { ThemeProvider } from '../theme/ThemeProvider'
@@ -103,6 +103,25 @@ describe('Shell on a hub', () => {
expect(status).not.toHaveTextContent('not answering')
})
it('marks the header with the config drift the session and the list report, on a hub only', async () => {
vi.restoreAllMocks()
vi.spyOn(client, 'apiRequest').mockImplementation((async (path: string) =>
path === 'hub/drift/get'
? { kind: 'ok', data: { status: 'ok', response: { checkedAt: 'x', apps: [{ app: 'Blocker', server: 'ndns', since: '2026-10-31T09:00:00Z', kind: 'differs' }] } } }
: { kind: 'ok', data: { status: 'ok', response: {} } }) as never)
const hubSession = session(true)
hubSession.info = { ...hubSession.info!, hubDrift: 1 }
render(
<ThemeProvider>
<Shell session={hubSession} onLogout={() => {}} />
</ThemeProvider>,
)
expect(await screen.findByRole('button', { name: 'Config drift' })).toHaveTextContent('1 config drift')
cleanup()
mount(false)
expect(screen.queryByRole('button', { name: 'Config drift' })).not.toBeInTheDocument()
})
/* Per-node calls (live metrics, settings) arrive right after an aggregate and say nothing. */
it('an ok response without the field leaves the warning, and an empty list clears it', async () => {
mount(true)
+17
View File
@@ -37,6 +37,8 @@ import { Versions } from './Versions'
import { BlockingMark } from './BlockingMark'
import { useBlockingMark } from '../screens/blocking/blocking-state'
import { useHubWarnings } from '../api/hub-warnings'
import { refreshHubDrift, resetHubDrift, setHubDriftCount } from '../api/hub-drift'
import { DriftStatus } from './DriftStatus'
import { Confirm } from '../ui/Confirm'
import { Notifier } from '../ui/Notifier'
import type { Notice } from '../lib/notice'
@@ -107,6 +109,8 @@ export interface ShellSession {
hub?: boolean
/** Only on the hub: the servers it holds an admin token for. */
hubWritable?: string[]
/** Only on the hub: how many servers differ from their baseline when the session was read. */
hubDrift?: number
/** Only on an initialised cluster (WebServiceAuthApi.cs:104-106). */
clusterDomain?: string
clusterNodes?: { name: string; type: string }[]
@@ -132,6 +136,18 @@ export function Shell({
const permissions = session.info?.permissions
const hub = session.info?.hub === true
const hubWarnings = useHubWarnings()
/* Behind a hub: the count comes with the session, the list is read now and then. */
const hubDriftAtStart = session.info?.hubDrift
useEffect(() => {
if (!hub) return
setHubDriftCount(hubDriftAtStart ?? 0)
void refreshHubDrift(session.token)
const timer = setInterval(() => void refreshHubDrift(session.token), 60_000)
return () => {
clearInterval(timer)
resetHubDrift()
}
}, [hub, session.token, hubDriftAtStart])
// Memoised: if it is recreated on every render, the `hashchange` resubscribes on each.
const sections = useMemo(() => visibleSections(permissions), [permissions])
/* The starting section comes from the address bar if it carries one, and only
@@ -586,6 +602,7 @@ export function Shell({
<span key={i} data-last={i === crumbs.length - 1}>{c}</span>
))}
</div>
{hub && <DriftStatus token={session.token} canWrite={permissions?.Apps?.canModify === true} writable={session.info?.hubWritable ?? []} />}
<Popover>
<PopoverTrigger className={styles.status} data-attention={blockingNow != null || hubWarnings.length > 0} aria-label="Server status">
<i className={styles.pdot} data-tone={hubWarnings.length > 0 ? 'warn' : (blockingNow?.tone ?? 'ok')} />
+2 -2
View File
@@ -84,13 +84,13 @@ describe('Compare', () => {
...WITH_BASELINE,
servers: [
view('mdns', { inSync: true, vsBaseline: { kind: 'text', lines: [], truncated: false, changed: 0 } }),
view('ndns', { inSync: false, vsBaseline: { kind: 'text', lines: [{ op: 'same', text: 'a = 1' }, { op: 'del', text: 'b = 2' }, { op: 'add', text: 'b = 3' }], truncated: false, changed: 2 } }),
view('ndns', { inSync: false, vsBaseline: { kind: 'text', lines: [{ op: 'same', text: 'a = 1' }, { op: 'remove', text: 'b = 2' }, { op: 'add', text: 'b = 3' }], truncated: false, changed: 2 } }),
],
})
mount(false)
const lines = await screen.findByLabelText('Line differences')
expect(within(lines).getByText(/b = 3/)).toHaveAttribute('data-op', 'add')
expect(within(lines).getByText(/b = 2/)).toHaveAttribute('data-op', 'del')
expect(within(lines).getByText(/b = 2/)).toHaveAttribute('data-op', 'remove')
})
it('shows an error with Retry', async () => {
+197 -44
View File
@@ -1,13 +1,17 @@
import { useCallback, useEffect, useState } from 'react'
import {
applyConfig,
getConfigCompare,
getCurrentLocalValues,
getHistory,
getHistoryDiff,
getHistoryEntry,
importBaseline,
previewConfig,
restoreBaseline,
saveBaseline,
saveOverrides,
type ConfigCompare,
type HistoryDiff,
type HistoryEntry,
type ServerConfigView,
} from '../../api/apps'
import { Alert } from '../../ui/Alert'
@@ -20,6 +24,8 @@ import { Skeleton } from '@/components/ui/skeleton'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { DiffView, FieldTable, fieldRows } from './ConfigDiffView'
import { RunFlow, pickerServers, type RunRequest } from './RunFlow'
import { applyRequest, rollbackRequest } from './applyRequest'
import { Select } from '../../ui/Field'
/*
One app's config across the servers, behind a hub: compare them, keep a baseline in the hub,
@@ -27,7 +33,7 @@ mark the fields that stay local to each server, then preview and apply. Everyone
sees the comparison; the editors and Apply are for roles that may change apps.
*/
type Tab = 'compare' | 'baseline' | 'local'
type Tab = 'compare' | 'baseline' | 'local' | 'history'
const when = (iso: string): string => (iso === '' ? '' : new Date(iso).toLocaleString())
@@ -63,6 +69,7 @@ export function AppConfigSync({
const [paths, setPaths] = useState<string[]>([])
const [values, setValues] = useState<Record<string, Record<string, string>>>({})
const [newPath, setNewPath] = useState('')
const [loads, setLoads] = useState(0)
const load = useCallback(async () => {
const outcome = await getConfigCompare(token, name)
@@ -72,6 +79,7 @@ export function AppConfigSync({
}
const d = outcome.data.response
setData(d)
setLoads((n) => n + 1)
setFailure(null)
setBaselineText(d.baseline?.text ?? '')
setPaths(d.overrides.paths)
@@ -130,49 +138,21 @@ export function AppConfigSync({
setValues(Object.fromEntries(Object.entries(outcome.data.response.values).map(([s, mine]) => [s, Object.fromEntries(Object.entries(mine).map(([p, v]) => [p, JSON.stringify(v)]))])))
}
function pickable(extra: Record<string, string> = {}) {
return pickerServers(
(data?.servers ?? []).map((s) => ({ id: s.id, writable: s.writable, ok: s.ok })),
{ ...Object.fromEntries((data?.servers ?? []).filter((s) => s.ok && !s.installed).map((s) => [s.id, 'Not installed'])), ...extra },
)
}
function startApply() {
if (data === null) return
const servers = data.servers
setRequest({
title: `Apply the baseline of ${name}`,
intro: 'Each server gets the baseline plus its own local values. You see what changes before anything is written.',
confirmLabel: 'Preview',
servers: pickerServers(
servers.map((s) => ({ id: s.id, writable: s.writable, ok: s.ok })),
Object.fromEntries(servers.filter((s) => s.ok && !s.installed).map((s) => [s.id, 'Not installed'])),
),
preselected: servers.filter((s) => s.installed && s.inSync === false).map((s) => s.id),
review: async (targets) => {
const outcome = await previewConfig(token, name, targets)
if (outcome.kind !== 'ok') return { kind: 'error', message: outcome.kind === 'error' ? outcome.message : 'The session ended.' }
const previews = outcome.data.response.targets
return {
kind: 'ok',
confirmLabel: 'Apply',
context: Object.fromEntries(previews.filter((p) => p.ok).map((p) => [p.server, p.currentHash])),
body: (
<div className="flex flex-col gap-6">
{previews.map((p) => (
<section key={p.server} aria-label={`Preview ${p.server}`} className="flex flex-col gap-3">
<h3 className="m-0 flex items-center gap-2 text-sm font-semibold">
{p.server}
{!p.ok ? <Tag tone="dan">Cannot apply</Tag> : p.unchanged ? <Tag tone="ok">Already in sync</Tag> : <Tag tone="warn">Will change</Tag>}
</h3>
{p.error !== undefined && <Alert type="danger" title="Error">{p.error}</Alert>}
{p.warnings.map((w) => (
<Alert key={w} type="warning" title="Warning">
{w}
</Alert>
))}
{p.ok && !p.unchanged && <DiffView diff={p.changes} from="Now" to="After apply" />}
</section>
))}
</div>
),
}
},
run: (targets, context) => applyConfig(token, name, targets, (context ?? {}) as Record<string, string>),
})
setRequest(applyRequest(token, name, pickable(), data.servers.filter((s) => s.installed && s.inSync === false).map((s) => s.id)))
}
function startRollback(entry: HistoryEntry) {
// Preselect the server the version came from: putting it on another server would also carry its local fields.
setRequest(rollbackRequest(token, name, entry, pickable(), entry.server === 'baseline' ? [] : [entry.server]))
}
const importButtons = (data?.servers ?? []).filter((s) => s.installed && s.ok)
@@ -220,6 +200,7 @@ export function AppConfigSync({
<TabsTrigger value="compare">Compare</TabsTrigger>
<TabsTrigger value="baseline">Baseline</TabsTrigger>
<TabsTrigger value="local">Local fields</TabsTrigger>
<TabsTrigger value="history">History</TabsTrigger>
</TabsList>
{problem !== null && <Alert type="danger" title="Error">{problem}</Alert>}
{saved !== null && <Alert type="success" title="Saved." onDismiss={() => setSaved(null)}>{saved}</Alert>}
@@ -352,6 +333,19 @@ export function AppConfigSync({
</>
)}
</TabsContent>
<TabsContent value="history" className="pt-3">
<HistoryTab
token={token}
name={name}
canWrite={canWrite}
servers={data.servers.filter((s) => s.installed && s.ok).map((s) => s.id)}
active={tab === 'history'}
onRollback={startRollback}
onRestore={(entry) => run(() => restoreBaseline(token, name, entry.id), 'Baseline restored.')}
version={String(loads)}
/>
</TabsContent>
</Tabs>
)}
</Dialog>
@@ -371,6 +365,165 @@ export function AppConfigSync({
)
}
const KIND: Record<string, string> = {
'before-apply': 'Before an apply',
'before-set': 'Before a save',
'before-uninstall': 'Before an uninstall',
'before-save': 'Old baseline',
}
/*
Every earlier config the hub kept: what a server had before the hub changed it, and what the
baseline was before it was replaced. Pick one to read it and to see how it differs from a server now.
*/
function HistoryTab({
token,
name,
canWrite,
servers,
active,
onRollback,
onRestore,
version,
}: {
token: string | null
name: string
canWrite: boolean
servers: string[]
active: boolean
onRollback: (entry: HistoryEntry) => void
onRestore: (entry: HistoryEntry) => void
/** Changes when the baseline does, so the list is read again. */
version: string
}) {
const [entries, setEntries] = useState<HistoryEntry[] | null>(null)
const [failure, setFailure] = useState<string | null>(null)
const [picked, setPicked] = useState<string | null>(null)
const [text, setText] = useState<string | null>(null)
const [server, setServer] = useState(servers[0] ?? '')
const [diff, setDiff] = useState<HistoryDiff | null>(null)
const [diffFailure, setDiffFailure] = useState<string | null>(null)
const load = useCallback(async () => {
const outcome = await getHistory(token, name)
if (outcome.kind === 'ok') {
setEntries(outcome.data.response.entries)
setFailure(null)
} else setFailure(outcome.kind === 'error' ? outcome.message : 'The session ended.')
}, [token, name])
useEffect(() => {
if (active) void load()
}, [active, load, version])
const entry = entries?.find((e) => e.id === picked) ?? null
useEffect(() => {
if (picked === null) return
void getHistoryEntry(token, name, picked).then((o) => setText(o.kind === 'ok' ? o.data.response.text : null))
}, [token, name, picked])
useEffect(() => {
if (entry === null || entry.kind === 'before-save' || server === '') return
void getHistoryDiff(token, name, entry.id, server).then((o) => {
setDiff(o.kind === 'ok' ? o.data.response : null)
setDiffFailure(o.kind === 'ok' ? null : o.kind === 'error' ? o.message : 'The session ended.')
})
}, [token, name, entry, server])
if (failure !== null && entries === null) {
return (
<Failure>
<span className="flex flex-col items-center gap-3">
<span>Could not read the history. {failure}</span>
<Button variant="primary" onClick={() => void load()}>
Retry
</Button>
</span>
</Failure>
)
}
if (entries === null) return <Skeleton className="h-24 w-full" />
if (entries.length === 0) {
return (
<Empty title="No history yet">
The hub keeps a copy of a server's config before it changes it, and of the baseline before it is replaced. They appear here.
</Empty>
)
}
return (
<div className="flex flex-col gap-4">
<ul className="m-0 flex max-h-56 list-none flex-col gap-1 overflow-auto p-0" aria-label="History">
{entries.map((e) => (
<li key={e.id}>
<button
type="button"
aria-pressed={e.id === picked}
aria-label={`${new Date(e.at).toLocaleString()} ${e.server === 'baseline' ? 'baseline' : e.server} ${KIND[e.kind] ?? e.kind}`}
className="flex w-full cursor-pointer flex-wrap items-center gap-3 rounded-md border border-border bg-transparent px-3 py-2 text-left text-sm transition-colors hover:bg-muted aria-pressed:bg-muted"
onClick={() => {
setPicked(e.id)
// A server's own version is compared with that server by default.
if (servers.includes(e.server)) setServer(e.server)
setText(null)
setDiff(null)
}}
>
<span className="tabular-nums">{new Date(e.at).toLocaleString()}</span>
<Tag tone={e.server === 'baseline' ? 'info' : 'neutral'}>{e.server === 'baseline' ? 'Baseline' : e.server}</Tag>
<span className="text-muted-foreground">{KIND[e.kind] ?? e.kind}</span>
<span className="text-xs text-muted-foreground">{e.size} bytes</span>
</button>
</li>
))}
</ul>
{entry !== null && (
<div className="flex flex-col gap-3">
<LabeledTextarea label="Version text" mono rows={10} readOnly spellCheck={false} value={text ?? ''} onChange={() => {}} />
{entry.kind !== 'before-save' && servers.length > 0 && (
<div className="flex flex-col gap-3">
<label className="flex max-w-60 flex-col gap-1 text-xs">
<span>Compare with the config now on</span>
<Select value={server} onChange={(e) => setServer(e.target.value)}>
{servers.map((id) => (
<option key={id} value={id}>
{id}
</option>
))}
</Select>
</label>
{diffFailure !== null ? (
<Alert type="danger" title="Error">{diffFailure}</Alert>
) : diff === null ? (
<Skeleton className="h-16 w-full" />
) : diff.unchanged ? (
<p className="m-0 text-sm text-muted-foreground">{server} already has this version.</p>
) : (
<DiffView diff={diff.changes} from={`${server} now`} to="This version" />
)}
</div>
)}
{canWrite && (
<div className="flex gap-2">
{entry.kind === 'before-save' ? (
<Button variant="primary" onClick={() => onRestore(entry)}>
Restore as baseline
</Button>
) : (
<Button variant="primary" onClick={() => onRollback(entry)}>
Roll back…
</Button>
)}
</div>
)}
</div>
)}
</div>
)
}
/* The differences, as a field table for JSON and as line diffs for text. */
function CompareBody({ data }: { data: ConfigCompare }) {
if (fieldRows(data) !== null) return <FieldTable data={data} />
+22
View File
@@ -2,6 +2,7 @@ import { KpiStrip } from '../../ui/KpiStrip'
import { useCallback, useContext, useEffect, useState } from 'react'
import {
downloadAndUpdate,
exportBaselines,
getAppConfig,
listApps,
uninstallApp,
@@ -30,6 +31,7 @@ import { AGGREGATE, ClusterNodeSelect, HubMode, type ClusterNode } from '../../u
import { AppsMatrix } from './AppsMatrix'
import { HubStore } from './HubStore'
import { HubInstallFile } from './HubInstallFile'
import { ImportBaselines } from './ImportBaselines'
import { RunFlow, type RunRequest } from './RunFlow'
/*
@@ -99,6 +101,7 @@ export function Apps({
const hubServers = nodes.map((n) => ({ id: n.name, writable: writable.includes(n.name) }))
const [hubView, setHubView] = useState<'matrix' | 'store'>('matrix')
const [fileDialog, setFileDialog] = useState(false)
const [importDialog, setImportDialog] = useState(false)
const [fileRequest, setFileRequest] = useState<RunRequest | null>(null)
const [refresh, setRefresh] = useState(0)
useEffect(() => {
@@ -222,6 +225,21 @@ export function Apps({
*/
const { rows: sortedApps, toggle } = useSort({ name: (a: InstalledApp) => a.name }, apps ?? [])
/* The file of every baseline, saved by the browser. */
async function exportFile() {
const outcome = await exportBaselines(token)
if (outcome.kind !== 'ok') {
setAlert(error(outcome))
return
}
const url = URL.createObjectURL(new Blob([outcome.data.text], { type: 'application/json' }))
const link = document.createElement('a')
link.href = url
link.download = outcome.data.filename
link.click()
URL.revokeObjectURL(url)
}
const selector = hub ? (
<InChrome>
<ClusterNodeSelect nodes={nodes} initialised={clusterInitialised} aggregate value={chosen} onChange={setNode} />
@@ -232,6 +250,7 @@ export function Apps({
return (
<>
{selector}
<Notifier notice={alert} onClose={() => setAlert(null)} />
<SectionHeader
title="Apps"
subtitle="DNS apps on every server"
@@ -242,6 +261,8 @@ export function Apps({
{hubView === 'store' ? 'Back to apps' : 'App Store'}
</Button>
<Button onClick={() => setFileDialog(true)}>Install from file</Button>
<Button onClick={() => void exportFile()}>Export baselines</Button>
<Button onClick={() => setImportDialog(true)}>Import baselines</Button>
</>
) : undefined
}
@@ -251,6 +272,7 @@ export function Apps({
) : (
<AppsMatrix token={token} canWrite={canWrite} refresh={refresh} />
)}
<ImportBaselines open={importDialog} onOpenChange={setImportDialog} token={token} onImported={() => setRefresh((n) => n + 1)} />
<HubInstallFile open={fileDialog} onOpenChange={setFileDialog} token={token} servers={hubServers} onRequest={setFileRequest} />
{fileRequest !== null && (
<RunFlow
+288
View File
@@ -0,0 +1,288 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { act, render, screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { AppConfigSync } from './AppConfigSync'
import { AppsMatrix } from './AppsMatrix'
import { Apps } from './Apps'
import { ImportBaselines } from './ImportBaselines'
import { DriftStatus } from '../../app/DriftStatus'
import { SlotProvider } from '../../app/ChromeSlot'
import { HubMode } from '../../ui/ClusterNodeSelect'
import { refreshHubDrift, resetHubDrift } from '../../api/hub-drift'
import * as api from '../../api/apps'
import type { ConfigCompare, DriftEntry, HistoryEntry, ServerConfigView } from '../../api/apps'
beforeEach(() => resetHubDrift())
afterEach(() => vi.restoreAllMocks())
const A = JSON.stringify({ ttl: 30 }, null, 2)
const B = JSON.stringify({ ttl: 60 }, null, 2)
const view = (id: string, over: Partial<ServerConfigView> = {}): ServerConfigView => ({
id, ok: true, installed: true, writable: true, version: '1.0', text: A, hash: 'h-' + id, warnings: [], inSync: true, vsOthers: {}, vsBaseline: { kind: 'json', changes: [] }, ...over,
})
const COMPARE: ConfigCompare = {
name: 'Blocker',
baseline: { app: 'Blocker', text: A, updatedAt: '2026-10-31T08:00:00Z', updatedBy: 'alice' },
overrides: { paths: [], values: {} },
servers: [view('mdns'), view('ndns', { text: B, inSync: false })],
}
const SERVER_ENTRY: HistoryEntry = { id: '2026-10-31T09-00-00.000Z__ndns__before-apply.txt', at: '2026-10-31T09:00:00.000Z', server: 'ndns', kind: 'before-apply', size: 20, hash: 'aaaa' }
const BASELINE_ENTRY: HistoryEntry = { id: '2026-10-31T08-00-00.000Z__baseline__before-save.txt', at: '2026-10-31T08:00:00.000Z', server: 'baseline', kind: 'before-save', size: 18, hash: 'bbbb' }
const ok = (results: api.TargetResult[]) => ({ kind: 'ok', data: { response: { results } } }) as never
function mockHistory(entries: HistoryEntry[]) {
vi.spyOn(api, 'getConfigCompare').mockResolvedValue({ kind: 'ok', data: { response: COMPARE } } as never)
vi.spyOn(api, 'getHistory').mockResolvedValue({ kind: 'ok', data: { response: { entries } } } as never)
vi.spyOn(api, 'getHistoryEntry').mockImplementation((async (_t: string | null, _n: string, id: string) => ({
kind: 'ok',
data: { response: { entry: entries.find((e) => e.id === id), text: id.includes('baseline') ? '{"old":true}' : '{"ttl":10}' } },
})) as never)
vi.spyOn(api, 'getHistoryDiff').mockImplementation((async (_t: string | null, _n: string, id: string, server: string) => ({
kind: 'ok',
data: {
response: {
entry: entries.find((e) => e.id === id), server, writable: true, current: B, currentHash: `hash-${server}`, version: '{"ttl":10}',
changes: { kind: 'json', changes: [{ path: 'ttl', type: 'changed', a: 60, b: 10 }] }, unchanged: false,
},
},
})) as never)
}
async function openHistory(canWrite: boolean) {
render(<AppConfigSync token="t" name="Blocker" canWrite={canWrite} onClose={() => {}} onChanged={() => {}} />)
await userEvent.click(await screen.findByRole('tab', { name: 'History' }))
}
describe('History tab', () => {
it('has an empty state', async () => {
mockHistory([])
await openHistory(false)
expect(await screen.findByText('No history yet')).toBeInTheDocument()
})
it('lists the saved versions and shows one with its difference from a server', async () => {
mockHistory([SERVER_ENTRY, BASELINE_ENTRY])
await openHistory(false)
const list = await screen.findByRole('list', { name: 'History' })
expect(within(list).getAllByRole('button')).toHaveLength(2)
expect(within(list).getByText('Before an apply')).toBeInTheDocument()
expect(within(list).getByText('Old baseline')).toBeInTheDocument()
await userEvent.click(within(list).getByRole('button', { name: /ndns Before an apply/ }))
expect(await screen.findByLabelText('Version text')).toHaveValue('{"ttl":10}')
expect(await screen.findByText('ttl')).toBeInTheDocument()
// Compared with the server the version came from.
expect(api.getHistoryDiff).toHaveBeenCalledWith('t', 'Blocker', SERVER_ENTRY.id, 'ndns')
// A reader may look, not act.
expect(screen.queryByRole('button', { name: 'Roll back…' })).not.toBeInTheDocument()
expect(screen.queryByRole('button', { name: 'Restore as baseline' })).not.toBeInTheDocument()
})
it('shows an error with Retry', async () => {
mockHistory([])
const spy = vi.spyOn(api, 'getHistory').mockResolvedValueOnce({ kind: 'error', message: 'No such app.' } as never)
await openHistory(false)
expect(await screen.findByText(/Could not read the history/)).toHaveTextContent('No such app.')
spy.mockResolvedValue({ kind: 'ok', data: { response: { entries: [] } } } as never)
await userEvent.click(screen.getByRole('button', { name: 'Retry' }))
expect(await screen.findByText('No history yet')).toBeInTheDocument()
})
it('rolls back after a preview, with the preview hash, and shows the results', async () => {
mockHistory([SERVER_ENTRY])
const rollback = vi.spyOn(api, 'rollbackHistory').mockResolvedValue(ok([{ server: 'ndns', ok: true, message: 'Applied and verified.' }]))
await openHistory(true)
await userEvent.click(await screen.findByRole('button', { name: /ndns Before an apply/ }))
await userEvent.click(await screen.findByRole('button', { name: 'Roll back…' }))
const picker = await screen.findByRole('dialog', { name: 'Roll back Blocker' })
// The version's own server is ticked already, and only it.
expect(within(picker).getByRole('checkbox', { name: 'ndns' })).toBeChecked()
expect(within(picker).getByRole('checkbox', { name: 'mdns' })).not.toBeChecked()
await userEvent.click(within(picker).getByRole('button', { name: 'Preview' }))
const review = await screen.findByRole('dialog', { name: 'Roll back Blocker: review' })
expect(within(review).getByText('Will change')).toBeInTheDocument()
expect(rollback).not.toHaveBeenCalled()
await userEvent.click(within(review).getByRole('button', { name: 'Roll back' }))
expect(rollback).toHaveBeenCalledWith('t', 'Blocker', SERVER_ENTRY.id, ['ndns'], { ndns: 'hash-ndns' })
const results = await screen.findByRole('dialog', { name: 'Roll back Blocker: results' })
expect(within(results).getByText('Applied and verified.')).toBeInTheDocument()
})
it('restores an old baseline as the baseline, for writers only', async () => {
mockHistory([BASELINE_ENTRY])
const restore = vi.spyOn(api, 'restoreBaseline').mockResolvedValue({ kind: 'ok', data: { response: { baseline: COMPARE.baseline } } } as never)
await openHistory(true)
await userEvent.click(await screen.findByRole('button', { name: /baseline Old baseline/ }))
expect(screen.queryByRole('button', { name: 'Roll back…' })).not.toBeInTheDocument()
await userEvent.click(await screen.findByRole('button', { name: 'Restore as baseline' }))
expect(restore).toHaveBeenCalledWith('t', 'Blocker', BASELINE_ENTRY.id)
expect(await screen.findByText('Baseline restored.')).toBeInTheDocument()
})
})
describe('DriftStatus in the header', () => {
const DRIFTS: DriftEntry[] = [
{ app: 'Blocker', server: 'ndns', since: '2026-10-31T09:00:00Z', kind: 'differs' },
{ app: 'Blocker', server: 'mdns', since: '2026-10-31T09:00:00Z', kind: 'unreadable' },
]
async function load(entries: DriftEntry[]) {
vi.spyOn(api, 'getDrift').mockResolvedValue({ kind: 'ok', data: { response: { checkedAt: 'x', apps: entries } } } as never)
await act(async () => refreshHubDrift('t'))
}
it('shows nothing without a drift and a count with one', async () => {
const { container } = render(<DriftStatus token="t" canWrite writable={['ndns']} />)
expect(container).toBeEmptyDOMElement()
await load(DRIFTS)
// Only a server that differs is counted; the unreadable one is listed in the dialog.
expect(await screen.findByRole('button', { name: 'Config drift' })).toHaveTextContent('1 config drift')
})
it('lists app, server, kind and since, and opens the config', async () => {
vi.spyOn(api, 'getConfigCompare').mockResolvedValue({ kind: 'ok', data: { response: COMPARE } } as never)
render(<DriftStatus token="t" canWrite={false} writable={[]} />)
await load(DRIFTS)
await userEvent.click(await screen.findByRole('button', { name: 'Config drift' }))
const row = await screen.findByRole('listitem', { name: 'Blocker on ndns' })
expect(within(row).getByText('Differs')).toBeInTheDocument()
expect(within(screen.getByRole('listitem', { name: 'Blocker on mdns' })).getByText('Cannot read')).toBeInTheDocument()
// A reader gets no actions.
expect(screen.queryByRole('button', { name: 'Accept as baseline' })).not.toBeInTheDocument()
expect(screen.queryByRole('button', { name: 'Revert to baseline' })).not.toBeInTheDocument()
await userEvent.click(within(row).getByRole('button', { name: 'Open config' }))
expect(await screen.findByRole('dialog', { name: 'App config: Blocker' })).toBeInTheDocument()
})
it('accepts a server config as the baseline after a confirmation and refreshes', async () => {
render(<DriftStatus token="t" canWrite writable={['ndns']} />)
await load(DRIFTS)
const accept = vi.spyOn(api, 'acceptDrift').mockResolvedValue({ kind: 'ok', data: { response: { baseline: COMPARE.baseline } } } as never)
await userEvent.click(await screen.findByRole('button', { name: 'Config drift' }))
await userEvent.click(await screen.findByRole('button', { name: 'Accept as baseline' }))
await userEvent.click(await screen.findByRole('button', { name: 'Accept' }))
expect(accept).toHaveBeenCalledWith('t', 'Blocker', 'ndns')
await waitFor(() => expect(api.getDrift).toHaveBeenCalledTimes(2))
})
it('reverts to the baseline through the preview', async () => {
render(<DriftStatus token="t" canWrite writable={['ndns']} />)
await load(DRIFTS)
const preview = vi.spyOn(api, 'previewConfig').mockResolvedValue({
kind: 'ok',
data: { response: { targets: [{ server: 'ndns', ok: true, writable: true, current: B, currentHash: 'hash-ndns', effective: A, unchanged: false, warnings: [], changes: { kind: 'json', changes: [{ path: 'ttl', type: 'changed', a: 60, b: 30 }] } }] } },
} as never)
const apply = vi.spyOn(api, 'applyConfig').mockResolvedValue(ok([{ server: 'ndns', ok: true, message: 'Applied and verified.' }]))
vi.spyOn(api, 'checkDrift').mockResolvedValue({ kind: 'ok', data: { response: { checkedAt: 'y', apps: [] } } } as never)
await userEvent.click(await screen.findByRole('button', { name: 'Config drift' }))
await userEvent.click(await screen.findByRole('button', { name: 'Revert to baseline' }))
const picker = await screen.findByRole('dialog', { name: 'Apply the baseline of Blocker' })
expect(within(picker).getByRole('checkbox', { name: 'ndns' })).toBeChecked()
await userEvent.click(within(picker).getByRole('button', { name: 'Preview' }))
expect(preview).toHaveBeenCalledWith('t', 'Blocker', ['ndns'])
await userEvent.click(within(await screen.findByRole('dialog', { name: 'Apply the baseline of Blocker: review' })).getByRole('button', { name: 'Apply' }))
expect(apply).toHaveBeenCalledWith('t', 'Blocker', ['ndns'], { ndns: 'hash-ndns' })
expect(await screen.findByText('Applied and verified.')).toBeInTheDocument()
})
})
describe('Drift badge in the matrix', () => {
it('marks the server cell whose config differs', async () => {
vi.spyOn(api, 'getAppsMatrix').mockResolvedValue({
kind: 'ok',
data: {
response: {
servers: [{ id: 'mdns', ok: true, writable: true }, { id: 'ndns', ok: true, writable: true }],
apps: [{ name: 'Blocker', description: '', configs: 'same', versions: 'same', servers: { mdns: { installed: true, version: '1.0', configStatus: 'read' }, ndns: { installed: true, version: '1.0', configStatus: 'read' } } }],
},
},
} as never)
vi.spyOn(api, 'getDrift').mockResolvedValue({ kind: 'ok', data: { response: { checkedAt: 'x', apps: [{ app: 'Blocker', server: 'ndns', since: 'z', kind: 'differs' }, { app: 'Blocker', server: 'mdns', since: 'z', kind: 'unreadable' }] } } } as never)
render(<AppsMatrix token="t" />)
await screen.findByText('Blocker')
await waitFor(() => expect(screen.getAllByText('Drift')).toHaveLength(1))
const row = screen.getByText('Blocker').closest('tr') as HTMLElement
expect(within(row).getByText('Drift')).toBeInTheDocument()
})
})
describe('Export and import of baselines', () => {
const NODES = [{ name: 'mdns', type: 'Primary' }]
function mountApps(canWrite: boolean) {
vi.spyOn(api, 'getAppsMatrix').mockResolvedValue({ kind: 'ok', data: { response: { servers: [], apps: [] } } } as never)
vi.spyOn(api, 'getDrift').mockResolvedValue({ kind: 'ok', data: { response: { checkedAt: null, apps: [] } } } as never)
return render(
<HubMode.Provider value>
<SlotProvider>
{(ref) => (
<>
<div ref={ref} />
<Apps token="t" nodes={NODES} clusterInitialised canWrite={canWrite} writable={['mdns']} />
</>
)}
</SlotProvider>
</HubMode.Provider>,
)
}
it('offers both to writers only', async () => {
const { unmount } = mountApps(false)
await screen.findByText('No apps installed')
expect(screen.queryByRole('button', { name: 'Export baselines' })).not.toBeInTheDocument()
expect(screen.queryByRole('button', { name: 'Import baselines' })).not.toBeInTheDocument()
unmount()
mountApps(true)
expect(await screen.findByRole('button', { name: 'Export baselines' })).toBeInTheDocument()
expect(screen.getByRole('button', { name: 'Import baselines' })).toBeInTheDocument()
})
it('downloads the file the hub sends', async () => {
mountApps(true)
const exported = vi.spyOn(api, 'exportBaselines').mockResolvedValue({ kind: 'ok', data: { filename: 'hub-baselines-2026-10-31.json', text: '{"hub":"technitium-hub"}' } } as never)
const create = vi.fn(() => 'blob:x')
Object.assign(URL, { createObjectURL: create, revokeObjectURL: vi.fn() })
const click = vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {})
await userEvent.click(await screen.findByRole('button', { name: 'Export baselines' }))
await waitFor(() => expect(click).toHaveBeenCalled())
expect(exported).toHaveBeenCalledWith('t')
expect(create).toHaveBeenCalled()
})
it('checks the file first, summarises it, and imports only on confirmation', async () => {
const spy = vi
.spyOn(api, 'importBaselines')
.mockResolvedValueOnce({ kind: 'ok', data: { response: { applied: false, apps: [{ app: 'Blocker', status: 'changed', ignoredServers: [] }, { app: 'Wild IP', status: 'new', ignoredServers: ['zzz'] }, { app: 'Split', status: 'same', ignoredServers: [] }] } } } as never)
.mockResolvedValueOnce({ kind: 'ok', data: { response: { applied: true, apps: [{ app: 'Blocker', status: 'changed', ignoredServers: [] }] } } } as never)
const onImported = vi.fn()
render(<ImportBaselines open onOpenChange={() => {}} token="t" onImported={onImported} />)
const file = new File(['{"hub":"technitium-hub"}'], 'b.json', { type: 'application/json' })
await userEvent.upload(screen.getByLabelText('Baselines file'), file)
await userEvent.click(screen.getByRole('button', { name: 'Check file' }))
const list = await screen.findByRole('list', { name: 'Apps in the file' })
expect(within(list).getByText('Changed')).toBeInTheDocument()
expect(within(list).getByText('New')).toBeInTheDocument()
expect(within(list).getByText('Same')).toBeInTheDocument()
expect(within(list).getByText(/zzz are ignored/)).toBeInTheDocument()
expect(spy).toHaveBeenCalledTimes(1)
expect(spy.mock.calls[0][2]).toBe(false)
await userEvent.click(screen.getByRole('button', { name: 'Import' }))
await waitFor(() => expect(spy).toHaveBeenCalledTimes(2))
expect(spy.mock.calls[1][2]).toBe(true)
expect(await screen.findByText('Imported.')).toBeInTheDocument()
expect(onImported).toHaveBeenCalled()
})
it('shows why a file was refused and imports nothing', async () => {
const spy = vi.spyOn(api, 'importBaselines').mockResolvedValue({ kind: 'error', message: 'This is not a baselines file of the hub.' } as never)
render(<ImportBaselines open onOpenChange={() => {}} token="t" onImported={() => {}} />)
await userEvent.upload(screen.getByLabelText('Baselines file'), new File(['{}'], 'x.json'))
await userEvent.click(screen.getByRole('button', { name: 'Check file' }))
expect(await screen.findByText('This is not a baselines file of the hub.')).toBeInTheDocument()
expect(spy).toHaveBeenCalledTimes(1)
expect(screen.queryByRole('button', { name: 'Import' })).not.toBeInTheDocument()
})
})
+14 -4
View File
@@ -1,5 +1,5 @@
import { useCallback, useEffect, useMemo, useState } from 'react'
import { getAppsMatrix, listStoreApps, runHubApps, type AppsMatrixData, type HubRunAction, type MatrixApp } from '../../api/apps'
import { getAppsMatrix, getDrift, listStoreApps, runHubApps, type AppsMatrixData, type HubRunAction, type MatrixApp } from '../../api/apps'
import { Badge } from '@/components/reui/badge'
import { Button } from '../../ui/Button'
import { DataTable, type Col } from '../../ui/DataTable'
@@ -73,13 +73,14 @@ function ConfigState({ app, data, onOpen }: { app: MatrixApp; data: AppsMatrixDa
}
}
function ServerCell({ app, id, data }: { app: MatrixApp; id: string; data: AppsMatrixData }) {
function ServerCell({ app, id, data, drifted }: { app: MatrixApp; id: string; data: AppsMatrixData; drifted: boolean }) {
const cell = app.servers[id]
if (data.servers.find((s) => s.id === id)?.ok === false) return <span className="text-sm text-muted-foreground">Unknown</span>
if (cell === undefined || !cell.installed) return <span className="text-sm text-muted-foreground">Not installed</span>
return (
<span className="flex flex-wrap items-center gap-2 text-sm">
<span>{cell.version === undefined ? 'Installed' : `v${cell.version}`}</span>
{drifted && <Tag tone="warn">Drift</Tag>}
{cell.updateAvailable === true && (
<Tag tone="warn">{cell.updateVersion === undefined ? 'Update' : `Update v${cell.updateVersion}`}</Tag>
)}
@@ -91,6 +92,8 @@ export function AppsMatrix({ token, canWrite = false, refresh = 0 }: { token: st
const [data, setData] = useState<AppsMatrixData | null>(null)
const [request, setRequest] = useState<RunRequest | null>(null)
const [configApp, setConfigApp] = useState<string | null>(null)
/** `app/server` pairs whose config differs from what the hub expects. */
const [drifted, setDrifted] = useState<Set<string>>(new Set())
/** What the store offers, by app: needed to know whether "Align versions" can be done. */
const [store, setStore] = useState<Record<string, string> | null>(null)
const [failure, setFailure] = useState<string | null>(null)
@@ -108,7 +111,14 @@ export function AppsMatrix({ token, canWrite = false, refresh = 0 }: { token: st
useEffect(() => {
void load()
}, [load, refresh])
void getDrift(token)
.then((o) => {
if (o.kind === 'ok' && Array.isArray(o.data.response?.apps)) {
setDrifted(new Set(o.data.response.apps.filter((e) => e.kind === 'differs').map((e) => `${e.app}\n${e.server}`)))
}
})
.catch(() => {})
}, [load, refresh, token])
useEffect(() => {
if (!canWrite) return
@@ -247,7 +257,7 @@ export function AppsMatrix({ token, canWrite = false, refresh = 0 }: { token: st
(s): Col<MatrixApp> => ({
id: `server-${s.id}`,
...head({ children: s.id }),
cell: (a) => <ServerCell app={a} id={s.id} data={data} />,
cell: (a) => <ServerCell app={a} id={s.id} data={data} drifted={drifted.has(`${a.name}\n${s.id}`)} />,
}),
),
{ id: 'config', ...head({ children: 'Config' }), cell: (a) => <ConfigState app={a} data={data} onOpen={() => setConfigApp(a.name)} /> },
+2 -2
View File
@@ -16,9 +16,9 @@ export const isLocal = (path: string, localPaths: string[]): boolean => localPat
const LINE_CLASS = {
same: 'text-muted-foreground',
add: 'bg-success/10 text-foreground',
del: 'bg-destructive/10 text-foreground',
remove: 'bg-destructive/10 text-foreground',
} as const
const MARK = { same: ' ', add: '+', del: '-' } as const
const MARK = { same: ' ', add: '+', remove: '-' } as const
/* The changes of one config to another: fields for JSON, lines for text. */
export function DiffView({ diff, localPaths = [], from = 'Now', to = 'Expected' }: { diff: ConfigDiff; localPaths?: string[]; from?: string; to?: string }) {
+126
View File
@@ -0,0 +1,126 @@
import { useEffect, useRef, useState } from 'react'
import { importBaselines, type ImportPlan } from '../../api/apps'
import { Alert } from '../../ui/Alert'
import { Button } from '../../ui/Button'
import { Dialog } from '../../ui/Dialog'
import { LabeledInput } from '../../ui/Field'
import { Loading } from '../../ui/Empty'
import { Tag } from '../../ui/Tag'
/*
Loads a file of baselines (made by "Export baselines") into this hub. The file is checked first and
the summary says, app by app, what is new, what changes and what is the same; nothing is written
until Import is pressed. It only touches the hub's own baselines: no server gets a config from it.
*/
const STATUS = { new: 'New', changed: 'Changed', same: 'Same' } as const
const TONE = { new: 'info', changed: 'warn', same: 'ok' } as const
export function ImportBaselines({
open,
onOpenChange,
token,
onImported,
}: {
open: boolean
onOpenChange: (o: boolean) => void
token: string | null
onImported: () => void
}) {
const [text, setText] = useState<string | null>(null)
const [plan, setPlan] = useState<ImportPlan | null>(null)
const [problem, setProblem] = useState<string | null>(null)
const [busy, setBusy] = useState(false)
const [done, setDone] = useState(false)
const fileRef = useRef<HTMLInputElement>(null)
useEffect(() => {
if (open) {
setText(null)
setPlan(null)
setProblem(null)
setBusy(false)
setDone(false)
}
}, [open])
async function check() {
const file = fileRef.current?.files?.[0]
if (!file) {
setProblem('Please select a baselines file.')
return
}
setBusy(true)
setProblem(null)
const content = await file.text()
const outcome = await importBaselines(token, content, false)
setBusy(false)
if (outcome.kind !== 'ok') {
setProblem(outcome.kind === 'error' ? outcome.message : 'The session ended.')
return
}
setText(content)
setPlan(outcome.data.response)
}
async function commit() {
if (text === null) return
setBusy(true)
const outcome = await importBaselines(token, text, true)
setBusy(false)
if (outcome.kind !== 'ok') {
setProblem(outcome.kind === 'error' ? outcome.message : 'The session ended.')
return
}
setPlan(outcome.data.response)
setDone(true)
onImported()
}
const changes = plan?.apps.filter((a) => a.status !== 'same').length ?? 0
return (
<Dialog
open={open}
onOpenChange={onOpenChange}
title="Import baselines"
actions={
plan === null ? (
<Button variant="primary" disabled={busy} onClick={() => void check()}>
Check file
</Button>
) : !done ? (
<Button variant="primary" disabled={busy || changes === 0} onClick={() => void commit()}>
Import
</Button>
) : undefined
}
>
{problem !== null && <Alert type="danger" title="Error">{problem}</Alert>}
{busy && <Loading>Working…</Loading>}
{plan === null ? (
<>
<p className="m-0 text-sm text-muted-foreground">
Choose a file made by Export baselines. It is checked first; nothing is changed until you press Import, and no server is touched.
</p>
<LabeledInput label="Baselines file" type="file" accept="application/json,.json" ref={fileRef} />
</>
) : (
<>
{done && <Alert type="success" title="Imported.">The baselines were saved. The replaced baselines are in each app's history.</Alert>}
<ul className="m-0 flex list-none flex-col gap-2 p-0" aria-label="Apps in the file">
{plan.apps.map((a) => (
<li key={a.app} className="flex flex-wrap items-center gap-2 text-sm">
<span className="font-medium">{a.app}</span>
<Tag tone={TONE[a.status]}>{STATUS[a.status]}</Tag>
{a.ignoredServers.length > 0 && (
<span className="text-xs text-muted-foreground">Local values of {a.ignoredServers.join(', ')} are ignored: this hub has no such server.</span>
)}
</li>
))}
</ul>
{!done && changes === 0 && <p className="m-0 text-sm text-muted-foreground">Everything in the file is already here.</p>}
</>
)}
</Dialog>
)
}
+90
View File
@@ -0,0 +1,90 @@
import { applyConfig, getHistoryDiff, previewConfig, rollbackHistory, type HistoryEntry } from '../../api/apps'
import { Alert } from '../../ui/Alert'
import { Tag } from '../../ui/Tag'
import { DiffView } from './ConfigDiffView'
import type { PickerServer, RunRequest } from './RunFlow'
/*
The two changes to a server's config that go through the picker, the review and the results: bring
it to the baseline (the sync), and put an earlier version back (a rollback). The Config dialog and
the drift list both start them.
*/
const sessionEnded = (kind: string, message?: string): string => (kind === 'error' ? (message ?? 'Failed.') : 'The session ended.')
/* The baseline plus each server's local values, to the chosen servers, after a preview. */
export function applyRequest(token: string | null, name: string, servers: PickerServer[], preselected: string[]): RunRequest {
return {
title: `Apply the baseline of ${name}`,
intro: 'Each server gets the baseline plus its own local values. You see what changes before anything is written.',
confirmLabel: 'Preview',
servers,
preselected,
review: async (targets) => {
const outcome = await previewConfig(token, name, targets)
if (outcome.kind !== 'ok') return { kind: 'error', message: sessionEnded(outcome.kind, outcome.kind === 'error' ? outcome.message : undefined) }
const previews = outcome.data.response.targets
return {
kind: 'ok',
confirmLabel: 'Apply',
context: Object.fromEntries(previews.filter((p) => p.ok).map((p) => [p.server, p.currentHash])),
body: (
<div className="flex flex-col gap-6">
{previews.map((p) => (
<section key={p.server} aria-label={`Preview ${p.server}`} className="flex flex-col gap-3">
<h3 className="m-0 flex items-center gap-2 text-sm font-semibold">
{p.server}
{!p.ok ? <Tag tone="dan">Cannot apply</Tag> : p.unchanged ? <Tag tone="ok">Already in sync</Tag> : <Tag tone="warn">Will change</Tag>}
</h3>
{p.error !== undefined && <Alert type="danger" title="Error">{p.error}</Alert>}
{p.warnings.map((w) => (
<Alert key={w} type="warning" title="Warning">
{w}
</Alert>
))}
{p.ok && !p.unchanged && <DiffView diff={p.changes} from="Now" to="After apply" />}
</section>
))}
</div>
),
}
},
run: (targets, context) => applyConfig(token, name, targets, (context ?? {}) as Record<string, string>),
}
}
/* One saved version of a server's config, put back on the chosen servers after seeing what changes. */
export function rollbackRequest(token: string | null, name: string, entry: HistoryEntry, servers: PickerServer[], preselected: string[]): RunRequest {
return {
title: `Roll back ${name}`,
intro: `Put the version saved at ${new Date(entry.at).toLocaleString()} back on the servers you choose. Their current configs are saved to the history first.`,
confirmLabel: 'Preview',
servers,
preselected,
review: async (targets) => {
const diffs = await Promise.all(targets.map((server) => getHistoryDiff(token, name, entry.id, server)))
const failed = diffs.find((d) => d.kind !== 'ok')
if (failed !== undefined) return { kind: 'error', message: sessionEnded(failed.kind, failed.kind === 'error' ? failed.message : undefined) }
const ok = diffs.flatMap((d) => (d.kind === 'ok' ? [d.data.response] : []))
return {
kind: 'ok',
confirmLabel: 'Roll back',
context: Object.fromEntries(ok.map((d) => [d.server, d.currentHash])),
body: (
<div className="flex flex-col gap-6">
{ok.map((d) => (
<section key={d.server} aria-label={`Preview ${d.server}`} className="flex flex-col gap-3">
<h3 className="m-0 flex items-center gap-2 text-sm font-semibold">
{d.server}
{d.unchanged ? <Tag tone="ok">Already this version</Tag> : <Tag tone="warn">Will change</Tag>}
</h3>
{!d.unchanged && <DiffView diff={d.changes} from="Now" to="After rollback" />}
</section>
))}
</div>
),
}
},
run: (targets, context) => rollbackHistory(token, name, entry.id, targets, (context ?? {}) as Record<string, string>),
}
}