feat(client): admin storage panel — backends list, category map, health strip, one-PUT save

This commit is contained in:
jubnl
2026-08-20 14:14:02 +02:00
parent f1be56cede
commit 462c5973ef
3 changed files with 610 additions and 0 deletions
@@ -0,0 +1,210 @@
import { http, HttpResponse } from 'msw';
import { beforeEach, describe, expect, it } from 'vitest';
import { MASKED_SETTING_VALUE, type StorageAdminState, type StorageConfig } from '@trek/shared';
import { server } from '../../../../tests/helpers/msw/server';
import { fireEvent, render, screen, waitFor, within } from '../../../../tests/helpers/render';
import { ToastContainer } from '../../shared/Toast';
import AdminStoragePanel from './AdminStoragePanel';
const S3_MASKED = {
endpoint: 'http://127.0.0.1:9000', bucket: 'trek', accessKeyId: 'ak',
secretAccessKey: MASKED_SETTING_VALUE, region: 'us-east-1', keyPrefix: '', retries: 1, timeoutMs: 30000,
};
function baseState(overrides: Partial<StorageAdminState> = {}): StorageAdminState {
return {
backends: [
{ name: 'uploads-local', type: 'local', source: 'built-in', options: { root: '/data/uploads' }, categories: ['files', 'journey', 'covers', 'avatars', 'photos', 'photos-google', 'photos-trek'] },
{ name: 'backups-local', type: 'local', source: 'built-in', options: { root: '/data/backups' }, categories: ['backups'] },
{ name: 'place-photos-local', type: 'local', source: 'env', options: { root: '/photos' }, categories: ['places'] },
{ name: 'off-box', type: 's3', source: 'settings', options: S3_MASKED, categories: ['covers'] },
],
categories: {
files: { backend: 'uploads-local', source: 'default' },
journey: { backend: 'uploads-local', source: 'default' },
covers: { backend: 'off-box', source: 'settings' },
avatars: { backend: 'uploads-local', source: 'default' },
places: { backend: 'place-photos-local', source: 'default' },
photos: { backend: 'uploads-local', source: 'default' },
'photos-google': { backend: 'uploads-local', source: 'default' },
'photos-trek': { backend: 'uploads-local', source: 'default' },
backups: { backend: 'backups-local', source: 'default' },
},
health: { replicaFailures: [] },
encryptionReady: true,
seedFilePresent: false,
...overrides,
};
}
function stubGet(state: StorageAdminState) {
server.use(http.get('/api/admin/storage', () => HttpResponse.json(state)));
}
async function renderPanel(state: StorageAdminState = baseState()) {
stubGet(state);
render(
<>
<ToastContainer />
<AdminStoragePanel />
</>,
);
await waitFor(() => expect(screen.getByText('Backends')).toBeInTheDocument());
}
const backendRow = (name: string) => screen.getByTestId(`storage-backend-${name}`);
const categoryRow = (category: string) => screen.getByTestId(`storage-category-${category}`);
describe('AdminStoragePanel', () => {
beforeEach(() => {
// Each test re-stubs GET; PUT/POST are stubbed where used.
});
it('FE-ADMIN-STOR-001: renders every backend with type badge, source tag and its categories', async () => {
await renderPanel();
const uploads = backendRow('uploads-local');
expect(within(uploads).getByText('Local')).toBeInTheDocument();
expect(within(uploads).getByText('Built-in')).toBeInTheDocument();
expect(within(uploads).getByText(/Used by: files/)).toBeInTheDocument();
const env = backendRow('place-photos-local');
expect(within(env).getByText('Environment')).toBeInTheDocument();
expect(within(env).getByText(/read-only/)).toBeInTheDocument();
expect(within(env).queryByRole('button', { name: 'Edit' })).not.toBeInTheDocument();
expect(within(env).queryByRole('button', { name: 'Remove' })).not.toBeInTheDocument();
const offBox = backendRow('off-box');
expect(within(offBox).getByText('S3')).toBeInTheDocument();
expect(within(offBox).getByText('Settings')).toBeInTheDocument();
});
it('FE-ADMIN-STOR-002: the mask echoes through edit → save untouched (no-op by contract)', async () => {
let putBody: unknown;
await renderPanel();
server.use(
http.put('/api/admin/storage', async ({ request }) => {
putBody = await request.json();
return HttpResponse.json(baseState());
}),
);
fireEvent.click(within(backendRow('off-box')).getByRole('button', { name: 'Edit' }));
expect(screen.getByLabelText(/Secret access key/)).toHaveValue(MASKED_SETTING_VALUE);
fireEvent.click(screen.getByRole('button', { name: 'Apply' }));
fireEvent.click(screen.getByRole('button', { name: 'Save changes' }));
await screen.findByText('Storage configuration saved');
const body = putBody as StorageConfig;
const offBox = body.backends.find((b) => b.name === 'off-box')!;
expect((offBox.options as Record<string, unknown>).secretAccessKey).toBe(MASKED_SETTING_VALUE);
});
it('FE-ADMIN-STOR-003: the PUT carries only the settings-owned document', async () => {
let putBody: unknown;
await renderPanel();
server.use(
http.put('/api/admin/storage', async ({ request }) => {
putBody = await request.json();
return HttpResponse.json(baseState());
}),
);
// Touch something to enable Save: reassign the files category.
fireEvent.click(within(categoryRow('files')).getByText('uploads-local (default)'));
const choices = screen.getAllByText('off-box');
fireEvent.click(choices[choices.length - 1]!);
fireEvent.click(screen.getByRole('button', { name: 'Save changes' }));
await screen.findByText('Storage configuration saved');
const body = putBody as StorageConfig;
expect(body.backends.map((b) => b.name)).toEqual(['off-box']); // built-ins/env never in the body
expect(body.categories).toEqual({ covers: 'off-box', files: 'off-box' });
});
it('FE-ADMIN-STOR-004: reassigning a category shows the objects-do-not-move warning inline', async () => {
await renderPanel();
expect(screen.queryByText(/Existing objects do not move/)).not.toBeInTheDocument();
fireEvent.click(within(categoryRow('files')).getByText('uploads-local (default)'));
const choices = screen.getAllByText('off-box');
fireEvent.click(choices[choices.length - 1]!);
expect(within(categoryRow('files')).getByText(/Existing objects do not move/)).toBeInTheDocument();
});
it('FE-ADMIN-STOR-005: a 400 renders the server message verbatim next to Save', async () => {
await renderPanel();
const registryError =
"backend 'off-box' has a plaintext secret 'secretAccessKey' but ENCRYPTION_KEY is not set — set ENCRYPTION_KEY explicitly to save credentialed storage backends (the implicit key persisted in the data directory is not accepted: it rides inside backups)";
server.use(http.put('/api/admin/storage', () => HttpResponse.json({ error: registryError }, { status: 400 })));
fireEvent.click(within(categoryRow('files')).getByText('uploads-local (default)'));
const choices = screen.getAllByText('off-box');
fireEvent.click(choices[choices.length - 1]!);
fireEvent.click(screen.getByRole('button', { name: 'Save changes' }));
expect(await screen.findByText(registryError)).toBeInTheDocument();
});
it('FE-ADMIN-STOR-006: Remove pre-checks assignments in the confirm dialog, then omits the backend from the PUT', async () => {
let putBody: unknown;
await renderPanel();
server.use(
http.put('/api/admin/storage', async ({ request }) => {
putBody = await request.json();
return HttpResponse.json(baseState());
}),
);
fireEvent.click(within(backendRow('off-box')).getByRole('button', { name: 'Remove' }));
expect(screen.getByText(/Still assigned to: covers/)).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: 'Remove backend' }));
fireEvent.click(screen.getByRole('button', { name: 'Save changes' }));
await screen.findByText('Storage configuration saved');
expect((putBody as StorageConfig).backends).toEqual([]);
});
it('FE-ADMIN-STOR-007: Test shows per-target results for a mirror', async () => {
const state = baseState();
state.backends.push({
name: 'backup-mirror', type: 'mirror', source: 'settings',
options: { primary: 'backups-local', replicas: ['off-box'] }, categories: [],
});
await renderPanel(state);
server.use(
http.post('/api/admin/storage/test', () =>
HttpResponse.json({
ok: false,
targets: [
{ name: 'backups-local', ok: true },
{ name: 'off-box', ok: false, error: 'connect ECONNREFUSED' },
],
}),
),
);
fireEvent.click(within(backendRow('backup-mirror')).getByRole('button', { name: 'Test' }));
await within(backendRow('backup-mirror')).findByText('Test failed');
expect(within(backendRow('backup-mirror')).getByText(/backups-local/)).toBeInTheDocument();
expect(within(backendRow('backup-mirror')).getByText(/connect ECONNREFUSED/)).toBeInTheDocument();
});
it('FE-ADMIN-STOR-008: the health strip lists replica failures with a relative age; all-clear otherwise', async () => {
const now = Date.now();
await renderPanel(
baseState({
health: { replicaFailures: [{ backend: 'off-box', key: 'backups/db.sqlite3', op: 'put', error: 'timeout', at: now - 120_000 }] },
}),
);
expect(screen.getByText(/put of backups\/db\.sqlite3 on off-box failed: timeout/)).toBeInTheDocument();
expect(screen.getByText(/2 minutes ago/)).toBeInTheDocument();
expect(screen.queryByText('No replica failures recorded.')).not.toBeInTheDocument();
});
it('FE-ADMIN-STOR-009: all-clear health and the seed-file note', async () => {
await renderPanel(baseState({ seedFilePresent: true }));
expect(screen.getByText('No replica failures recorded.')).toBeInTheDocument();
expect(screen.getByText(/seed file is present but ignored/)).toBeInTheDocument();
});
it('FE-ADMIN-STOR-010: a managed-mode 403 on GET renders its body message gracefully', async () => {
server.use(
http.get('/api/admin/storage', () =>
HttpResponse.json(
{ error: 'This is configured by the operator of this instance.', code: 'MANAGED_FORBIDDEN' },
{ status: 403 },
),
),
);
render(<AdminStoragePanel />);
expect(await screen.findByText('This is configured by the operator of this instance.')).toBeInTheDocument();
});
});
@@ -0,0 +1,296 @@
import React, { useState } from 'react'
import { Activity, FolderTree, HardDrive } from 'lucide-react'
import { STORAGE_CATEGORIES, type StorageBackend, type StorageCategory, type StorageTestResponse } from '@trek/shared'
import { useTranslation } from '../../../i18n'
import { relativeTime } from '../../../utils/relativeTime'
import ConfirmDialog from '../../shared/ConfirmDialog'
import CustomSelect from '../../shared/CustomSelect'
import { useToast } from '../../shared/Toast'
import Section from '../../Settings/Section'
import BackendForm from './BackendForm'
import {
asWireBackend,
categoriesPointingAt,
mirrorsReferencing,
removeBackend,
upsertBackend,
type StateBackend,
} from './storageModel'
import { useStorageAdmin } from './useStorageAdmin'
interface Row {
name: string
type: StorageBackend['type']
source: 'built-in' | 'env' | 'settings'
backend: StorageBackend
categories: readonly string[]
}
function TestResult({ result, failedLabel, okLabel }: {
result: StorageTestResponse | undefined
failedLabel: string
okLabel: string
}): React.ReactElement | null {
if (result === undefined) return null
return (
<div className="mt-2 space-y-0.5">
<p className="text-xs font-semibold text-content">{result.ok ? okLabel : failedLabel}</p>
{result.targets.map((target) => (
<p key={target.name} className="text-xs text-content-faint">
{target.ok ? '✓' : '✗'} {target.name}
{target.error ? ` — ${target.error}` : ''}
</p>
))}
</div>
)
}
export default function AdminStoragePanel(): React.ReactElement {
const { t, locale } = useTranslation()
const toast = useToast()
const admin = useStorageAdmin(t('common.error'))
const [editing, setEditing] = useState<{ initial: StorageBackend | null; originalName: string | null } | null>(null)
const [confirmRemove, setConfirmRemove] = useState<string | null>(null)
if (admin.loading) {
return <p className="text-sm italic p-4 text-content-faint">{t('storage.loading')}</p>
}
if (!admin.state || !admin.draft) {
return (
<div role="alert" className="rounded-xl border p-4 text-sm border-edge bg-surface-card text-content">
{admin.loadError || t('common.error')}
</div>
)
}
const { state, draft } = admin
const draftNames = draft.backends.map((b) => b.name)
const backendNames = [...new Set([...state.backends.map((b) => b.name), ...draftNames])]
// The list shows the DRAFT world: built-ins/env from the state (unless a
// draft row overrides the name), settings rows from the draft (unsaved
// edits, additions and removals included).
const stateByName = new Map(state.backends.map((b) => [b.name, b]))
const rows: Row[] = []
for (const b of state.backends) {
if (draftNames.includes(b.name)) continue // the draft copy renders below
if (b.source === 'settings') continue // removed from the draft, pending save
rows.push({ name: b.name, type: b.type, source: b.source, backend: asWireBackend(b), categories: b.categories })
}
for (const b of draft.backends) {
const inState = stateByName.get(b.name) as StateBackend | undefined
rows.push({
name: b.name,
type: b.type,
source: 'settings',
backend: b,
categories: inState?.categories ?? categoriesPointingAt(draft, b.name),
})
}
const startEdit = (row: Row) => {
// Editing a built-in creates a settings override row bearing its name —
// the first-class relocation path (merge-by-name).
setEditing({ initial: row.backend, originalName: row.name })
}
const commitBackend = (backend: StorageBackend) => {
const renamedFrom =
editing?.originalName && editing.originalName !== backend.name ? editing.originalName : null
const base = renamedFrom ? removeBackend(draft, renamedFrom) : draft
admin.setDraft(upsertBackend(base, backend))
setEditing(null)
}
const removeMessage = (name: string): string => {
const assigned = categoriesPointingAt(draft, name)
const mirrors = mirrorsReferencing(draft, name)
return [
t('storage.remove.body', { name }),
assigned.length > 0 ? t('storage.remove.stillAssigned', { categories: assigned.join(', ') }) : '',
mirrors.length > 0 ? t('storage.remove.referencedBy', { backends: mirrors.join(', ') }) : '',
]
.filter(Boolean)
.join(' ')
}
const setCategory = (category: StorageCategory, backendName: string) => {
const effective = state.categories[category]!
// Exhaustive record: storageAdminStateSchema's `categories` maps all nine
// STORAGE_CATEGORIES entries (server-enforced), so this index is total.
const categories = { ...draft.categories }
if (effective.source === 'default' && backendName === effective.backend) {
delete categories[category] // back to the default → no longer settings-owned
} else {
categories[category] = backendName
}
admin.setDraft({ ...draft, categories })
}
const save = async () => {
if (await admin.save()) toast.success(t('storage.saved'))
}
return (
<div>
<Section title={t('storage.health.title')} icon={Activity}>
{state.health.replicaFailures.length === 0 ? (
<p className="text-sm text-content-faint">{t('storage.health.allClear')}</p>
) : (
<ul className="space-y-1">
{state.health.replicaFailures.map((failure) => (
<li key={`${failure.backend}-${failure.key}-${failure.at}`} className="text-sm text-content">
{t('storage.health.failureLine', {
op: failure.op,
key: failure.key,
backend: failure.backend,
error: failure.error,
})}
<span className="text-content-faint"> · {relativeTime(failure.at, locale)}</span>
</li>
))}
</ul>
)}
{state.seedFilePresent && <p className="text-xs mt-2 text-content-faint">{t('storage.health.seedFile')}</p>}
</Section>
<Section title={t('storage.backends.title')} icon={HardDrive}>
<p className="text-sm text-content-faint" style={{ marginTop: -8 }}>{t('storage.description')}</p>
<div className="space-y-3">
{rows.map((row) => (
<div key={row.name} data-testid={`storage-backend-${row.name}`} className="rounded-xl border p-4 border-edge-secondary">
<div className="flex items-center gap-2 flex-wrap">
<span className="text-sm font-semibold text-content">{row.name}</span>
<span className="text-xs px-2 py-0.5 rounded-full border border-edge text-content-secondary">
{t(`storage.type.${row.type}`)}
</span>
<span className="text-xs px-2 py-0.5 rounded-full border border-edge text-content-faint">
{t(`storage.source.${row.source}`)}
</span>
<span className="flex-1" />
<button className="text-xs underline text-content-secondary" style={{ background: 'none', border: 'none', cursor: 'pointer' }} onClick={() => admin.test(row.backend)}>
{t('storage.actions.test')}
</button>
{row.source !== 'env' && (
<button className="text-xs underline text-content-secondary" style={{ background: 'none', border: 'none', cursor: 'pointer' }} onClick={() => startEdit(row)}>
{t('storage.actions.edit')}
</button>
)}
{row.source === 'settings' && (
<button className="text-xs underline text-content-secondary" style={{ background: 'none', border: 'none', cursor: 'pointer' }} onClick={() => setConfirmRemove(row.name)}>
{t('storage.actions.remove')}
</button>
)}
</div>
<p className="text-xs mt-1 text-content-faint">
{row.categories.length > 0
? t('storage.backends.usedBy', { categories: row.categories.join(', ') })
: t('storage.backends.unused')}
</p>
{row.source === 'env' && <p className="text-xs mt-1 text-content-faint">{t('storage.backends.envReadOnly')}</p>}
{admin.testResults[row.name] === 'running' ? (
<p className="text-xs mt-2 text-content-faint">{t('storage.test.running')}</p>
) : (
<TestResult
result={admin.testResults[row.name] as StorageTestResponse | undefined}
okLabel={t('storage.test.ok')}
failedLabel={t('storage.test.failed')}
/>
)}
</div>
))}
</div>
{editing ? (
<BackendForm
initial={editing.initial}
backendNames={backendNames}
encryptionReady={state.encryptionReady}
onCommit={commitBackend}
onCancel={() => setEditing(null)}
/>
) : (
<button
onClick={() => setEditing({ initial: null, originalName: null })}
style={{
padding: '8px 20px', borderRadius: 10, cursor: 'pointer', fontFamily: 'inherit',
fontSize: 'calc(14px * var(--fs-scale-body, 1))', fontWeight: 500,
border: '2px solid var(--border-primary)', background: 'var(--bg-card)', color: 'var(--text-primary)',
}}
>
{t('storage.backends.add')}
</button>
)}
</Section>
<Section title={t('storage.categories.title')} icon={FolderTree}>
<div className="space-y-4">
{STORAGE_CATEGORIES.map((category) => {
const effective = state.categories[category]!
// Exhaustive record — see the setCategory comment above.
const selected = draft.categories[category] ?? effective.backend
const changed = selected !== effective.backend
return (
<div key={category} data-testid={`storage-category-${category}`}>
<label className="block text-sm font-medium mb-1.5 text-content-secondary">
{t(`storage.category.${category}`)}
</label>
<CustomSelect
value={selected}
onChange={(value) => setCategory(category, String(value))}
options={backendNames.map((name) => ({
value: name,
label:
effective.source === 'default' && name === effective.backend
? `${name} (${t('storage.categories.default')})`
: name,
}))}
size="sm"
style={{ maxWidth: 320 }}
/>
{changed && (
<p role="alert" className="text-xs mt-1 text-content-faint">
{t('storage.categories.reassignWarning')}
</p>
)}
</div>
)
})}
</div>
</Section>
<div className="flex items-center gap-3">
<button
onClick={save}
disabled={!admin.dirty || admin.saving}
style={{
padding: '10px 20px', borderRadius: 10, cursor: admin.dirty && !admin.saving ? 'pointer' : 'default',
fontFamily: 'inherit', fontSize: 'calc(14px * var(--fs-scale-body, 1))', fontWeight: 600,
border: '2px solid var(--text-primary)', background: 'var(--bg-hover)', color: 'var(--text-primary)',
opacity: admin.dirty && !admin.saving ? 1 : 0.5,
}}
>
{t('storage.save')}
</button>
{admin.dirty && <span className="text-xs text-content-faint">{t('storage.unsaved')}</span>}
</div>
{admin.saveError && (
<p role="alert" className="text-sm mt-2 text-content">
{admin.saveError}
</p>
)}
<ConfirmDialog
isOpen={confirmRemove !== null}
onClose={() => setConfirmRemove(null)}
onConfirm={() => {
if (confirmRemove) admin.setDraft(removeBackend(draft, confirmRemove))
setConfirmRemove(null)
}}
title={t('storage.remove.title')}
message={confirmRemove ? removeMessage(confirmRemove) : ''}
confirmLabel={t('storage.remove.title')}
/>
</div>
)
}
@@ -0,0 +1,104 @@
import { useCallback, useEffect, useState } from 'react'
import type { StorageAdminState, StorageBackend, StorageConfig, StorageTestResponse } from '@trek/shared'
import { adminApi } from '../../../api/client'
import { getApiErrorMessage } from '../../../types'
import { settingsDocumentOf } from './storageModel'
export type StorageTestResults = Record<string, StorageTestResponse | 'running'>
export interface StorageAdmin {
state: StorageAdminState | null
/** The settings-owned document (the PUT body), with local edits layered in. */
draft: StorageConfig | null
dirty: boolean
loading: boolean
loadError: string | null
/** Server 400s land here VERBATIM — long registry messages outlive a toast. */
saveError: string | null
saving: boolean
testResults: StorageTestResults
setDraft: (next: StorageConfig) => void
save: () => Promise<boolean>
test: (backend: StorageBackend) => Promise<void>
}
/**
* Shared by the desktop and phone storage panels (DefaultUserSettingsTab
* model: self-contained, adminApi directly, deliberately no offline core —
* hoster-level config is online-only).
*/
export function useStorageAdmin(genericError: string): StorageAdmin {
const [state, setState] = useState<StorageAdminState | null>(null)
const [draft, setDraftState] = useState<StorageConfig | null>(null)
const [dirty, setDirty] = useState(false)
const [loading, setLoading] = useState(true)
const [loadError, setLoadError] = useState<string | null>(null)
const [saveError, setSaveError] = useState<string | null>(null)
const [saving, setSaving] = useState(false)
const [testResults, setTestResults] = useState<StorageTestResults>({})
const applyState = useCallback((next: StorageAdminState) => {
setState(next)
setDraftState(settingsDocumentOf(next))
setDirty(false)
setSaveError(null)
}, [])
useEffect(() => {
let cancelled = false
adminApi
.getStorage()
.then((data) => {
if (!cancelled) applyState(data)
})
.catch((err: unknown) => {
if (!cancelled) setLoadError(getApiErrorMessage(err, genericError))
})
.finally(() => {
if (!cancelled) setLoading(false)
})
return () => {
cancelled = true
}
}, [applyState, genericError])
const setDraft = useCallback((next: StorageConfig) => {
setDraftState(next)
setDirty(true)
}, [])
const save = useCallback(async (): Promise<boolean> => {
if (!draft) return false
setSaving(true)
setSaveError(null)
try {
// The response is the fresh effective world, never the request echo.
applyState(await adminApi.updateStorage(draft))
return true
} catch (err: unknown) {
setSaveError(getApiErrorMessage(err, genericError))
return false
} finally {
setSaving(false)
}
}, [draft, applyState, genericError])
const test = useCallback(
async (backend: StorageBackend): Promise<void> => {
setTestResults((prev) => ({ ...prev, [backend.name]: 'running' }))
try {
const result = await adminApi.testStorageBackend(backend)
setTestResults((prev) => ({ ...prev, [backend.name]: result }))
} catch (err: unknown) {
const error = getApiErrorMessage(err, genericError)
setTestResults((prev) => ({
...prev,
[backend.name]: { ok: false, targets: [{ name: backend.name, ok: false, error }] },
}))
}
},
[genericError],
)
return { state, draft, dirty, loading, loadError, saveError, saving, testResults, setDraft, save, test }
}