chore(openspec): archive completed changes
Move finished change directories to openspec/changes/archive/: - configurable-dashboard-widgets - decommission-monitoring-poller - service-registry - unify-tasks-on-services All associated implementation has been merged to main.
This commit is contained in:
@@ -0,0 +1,198 @@
|
||||
# Apply Progress: Configurable Dashboard Widgets
|
||||
|
||||
**Change:** `configurable-dashboard-widgets`
|
||||
**Apply run:** PR 1 / Slice 1 — Backend CRUD and default seeding
|
||||
**Date:** 2026-06-19
|
||||
|
||||
## Completed tasks (Slice 1)
|
||||
|
||||
All Slice 1 tasks are marked `- [x]` in `tasks.md`:
|
||||
|
||||
- [x] 1.1 Create widget Pydantic models
|
||||
- [x] 1.2 Create backend widget registry
|
||||
- [x] 1.3 Implement widgets router (CRUD + metadata)
|
||||
- [x] 1.4 Extend `SettingsStore` for `dashboard_widgets`
|
||||
- [x] 1.5 Register widgets router in `main.py`
|
||||
- [x] 1.6 Add backend tests for registry, CRUD, and seeding
|
||||
- [x] 1.7 Verify backend slice
|
||||
|
||||
## Files changed
|
||||
|
||||
### New files
|
||||
|
||||
- `backend/src/media_library_viewer_api/models/widgets.py` — Pydantic models: `WidgetInstance`, `WidgetInstanceInput`, `WidgetTypeInfo`, `WidgetDataResponse`, plus credential-key/secret-value validators.
|
||||
- `backend/src/media_library_viewer_api/widgets/__init__.py` — Package marker.
|
||||
- `backend/src/media_library_viewer_api/widgets/registry.py` — Closed `WIDGET_REGISTRY` for six Phase 1 widget types, source-type listing, type metadata, and lightweight config-schema validation.
|
||||
- `backend/src/media_library_viewer_api/routers/widgets.py` — REST endpoints for `/api/widgets/sources`, `/types`, `/instances`, and instance CRUD.
|
||||
- `backend/tests/test_widgets.py` — 12 tests covering registry, CRUD, validation, and seeding.
|
||||
|
||||
### Modified files
|
||||
|
||||
- `backend/src/media_library_viewer_api/services/settings_store.py` — Added `dashboard_widgets` table, index, CRUD helpers, default seeding, and refactored `ensure_defaults()` to seed widgets independently of machine seeding.
|
||||
- `backend/src/media_library_viewer_api/main.py` — Registered `widgets_router`.
|
||||
|
||||
## Verification
|
||||
|
||||
Commands run:
|
||||
|
||||
```bash
|
||||
cd backend
|
||||
.venv/bin/python -m ruff check . # All checks passed
|
||||
PYTHONPATH=src .venv/bin/python -m pytest # 185 passed, 2 warnings
|
||||
cd ../frontend
|
||||
npm run lint # 2 pre-existing warnings, 0 errors
|
||||
npm run build # Built successfully
|
||||
```
|
||||
|
||||
Focused widget test output: `12 passed`.
|
||||
|
||||
## Deviations from design
|
||||
|
||||
- None significant for Slice 1. The implementation follows the design's backend CRUD layout.
|
||||
- Used `HTTP_422_UNPROCESSABLE_CONTENT` instead of the deprecated `HTTP_422_UNPROCESSABLE_ENTITY`.
|
||||
|
||||
## Completed tasks (Slice 2)
|
||||
|
||||
All Slice 2 tasks are marked `- [x]` in `tasks.md`:
|
||||
|
||||
- [x] 2.1 Add observability URL settings (`grafana_url`, `prometheus_url`)
|
||||
- [x] 2.2 Create source adapters (`jellyfin`, `backups`, `grafana`, `prometheus`, `ssh_task`, `static`)
|
||||
- [x] 2.3 Add per-widget data endpoint (`GET /api/widgets/instances/{id}/data`)
|
||||
- [x] 2.4 Extract shared backup/Jellyfin dashboard helpers into `domain/dashboard.py`
|
||||
- [x] 2.5 Add adapter + data endpoint tests
|
||||
|
||||
## Files changed (Slice 2)
|
||||
|
||||
### New files
|
||||
|
||||
- `backend/src/media_library_viewer_api/widgets/sources.py` — `WidgetSource` protocol and six source adapters.
|
||||
- `backend/src/media_library_viewer_api/domain/dashboard.py` — Shared dashboard helpers (`_map_sessions_to_activity_rows`, `build_backup_dashboard_summary`).
|
||||
|
||||
### Modified files
|
||||
|
||||
- `backend/src/media_library_viewer_api/config.py` — Added `grafana_url` and `prometheus_url` settings.
|
||||
- `backend/src/media_library_viewer_api/routers/widgets.py` — Added `GET /api/widgets/instances/{id}/data`.
|
||||
- `backend/src/media_library_viewer_api/routers/dashboard.py` — Delegated to shared `domain/dashboard.py` helpers.
|
||||
- `backend/tests/test_widgets.py` — Added adapter and data endpoint tests.
|
||||
- `docker-compose.yml`, `docker-compose.dev.yml`, `.env.example` — Wired `GRAFANA_URL` and `PROMETHEUS_URL` for the new adapters.
|
||||
|
||||
## Verification (Slice 2)
|
||||
|
||||
```bash
|
||||
cd backend
|
||||
.venv/bin/python -m ruff check . # All checks passed
|
||||
PYTHONPATH=src .venv/bin/python -m pytest # 200 passed, 2 warnings
|
||||
cd ../frontend
|
||||
npm run lint # 2 pre-existing warnings, 0 errors
|
||||
npm run build # Built successfully
|
||||
```
|
||||
|
||||
Focused widget test output: `27 passed`.
|
||||
|
||||
## Deviations from design (Slice 2)
|
||||
|
||||
- Adapters currently call `get_settings_store()` internally for `backups`/`ssh_task` sources. The router-level endpoint uses FastAPI DI, but adapter unit tests patch `get_settings_store` to inject a test store. A future refactor can pass `store` and `settings` explicitly into `adapter.fetch()` for cleaner testability.
|
||||
|
||||
## Completed tasks (Slice 3)
|
||||
|
||||
All Slice 3 tasks are marked `- [x]` in `tasks.md`:
|
||||
|
||||
- [x] 3.1 Add TypeScript widget interfaces (`WidgetInstance`, `WidgetInstanceInput`, `WidgetTypeInfo`, `WidgetDataResponse`)
|
||||
- [x] 3.2 Create widget API client (`frontend/src/api/widgets.ts`)
|
||||
- [x] 3.3 Create widget TanStack Query hooks (`frontend/src/hooks/useWidgets.ts`)
|
||||
- [x] 3.4 Create frontend widget registry (`frontend/src/widgets/registry.ts`)
|
||||
- [x] 3.5 Implement six widget presentational components (`frontend/src/widgets/*.tsx`)
|
||||
- [x] 3.6 Add frontend registry unit test (`frontend/src/widgets/registry.test.ts`)
|
||||
|
||||
## Files changed (Slice 3)
|
||||
|
||||
### New files
|
||||
|
||||
- `frontend/src/api/widgets.ts` — API functions for widget CRUD, registry metadata, and per-widget data.
|
||||
- `frontend/src/hooks/useWidgets.ts` — TanStack Query hooks for instances, data, sources, types, and mutations.
|
||||
- `frontend/src/widgets/registry.ts` — Closed frontend registry with metadata, refresh intervals, and config fields.
|
||||
- `frontend/src/widgets/JellyfinWidget.tsx` — Renders Jellyfin session activity.
|
||||
- `frontend/src/widgets/BackupsWidget.tsx` — Renders backup dashboard summary.
|
||||
- `frontend/src/widgets/GrafanaLinkWidget.tsx` — Renders a deep-link to Grafana (no iframe).
|
||||
- `frontend/src/widgets/PrometheusMetricWidget.tsx` — Renders PromQL instant query result.
|
||||
- `frontend/src/widgets/SshTaskWidget.tsx` — Renders saved SSH task output.
|
||||
- `frontend/src/widgets/StaticWidget.tsx` — Renders static text.
|
||||
- `frontend/src/widgets/index.ts` — Barrel exports.
|
||||
- `frontend/src/widgets/registry.test.ts` — Vitest unit tests for registry metadata.
|
||||
|
||||
### Modified files
|
||||
|
||||
- `frontend/src/types/index.ts` — Added widget TypeScript interfaces.
|
||||
|
||||
## Verification (Slice 3)
|
||||
|
||||
```bash
|
||||
cd backend
|
||||
.venv/bin/python -m ruff check . # All checks passed
|
||||
PYTHONPATH=src .venv/bin/python -m pytest # 200 passed, 2 warnings
|
||||
cd ../frontend
|
||||
npm run lint # 2 pre-existing warnings, 0 errors
|
||||
npm run build # Built successfully
|
||||
npm run test -- src/widgets/registry.test.ts # 3 passed
|
||||
```
|
||||
|
||||
## Deviations from design (Slice 3)
|
||||
|
||||
- Registry unit test is colocated at `frontend/src/widgets/registry.test.ts` and runs with Vitest, matching the project's existing `npm run test` setup, instead of `frontend/tests/widgets.test.mjs`.
|
||||
- `JellyfinWidget` uses `SessionActivityPanel` directly because `NowPlaying` does not expose an `emptyMessage` prop.
|
||||
|
||||
## Completed tasks (Slice 4)
|
||||
|
||||
All Slice 4 tasks are marked `- [x]` in `tasks.md`:
|
||||
|
||||
- [x] 4.1 Refactor `Dashboard.tsx` to render enabled widget instances in sort order
|
||||
- [x] 4.2 Create `WidgetInstance` renderer component
|
||||
- [x] 4.3 Create `WidgetConfigDialog` for add/edit/reorder/delete widgets
|
||||
- [x] 4.4 Create addon pages (`AddonPage`, `GrafanaAddonPage`, `PrometheusAddonPage`, `SshTasksAddonPage`)
|
||||
- [x] 4.5 Register `/addons/:addonId` route in `App.tsx`
|
||||
- [x] 4.6 Update `docs/REQUIREMENTS.md` with widget system documentation
|
||||
|
||||
## Files changed (Slice 4)
|
||||
|
||||
### New files
|
||||
|
||||
- `frontend/src/components/WidgetInstance.tsx` — Renders a widget instance by looking up its definition and dispatching to the registered component.
|
||||
- `frontend/src/components/WidgetConfigDialog.tsx` — Dashboard widget configuration UI: list, add, edit, delete, reorder, enable/disable.
|
||||
- `frontend/src/pages/AddonPage.tsx` — Route mapper for `/addons/:addonId`.
|
||||
- `frontend/src/addons/GrafanaAddonPage.tsx` — Grafana addon landing page (deep-link only).
|
||||
- `frontend/src/addons/PrometheusAddonPage.tsx` — Prometheus addon landing page.
|
||||
- `frontend/src/addons/SshTasksAddonPage.tsx` — SSH tasks addon landing page.
|
||||
- `frontend/src/addons/index.ts` — Barrel exports.
|
||||
|
||||
### Modified files
|
||||
|
||||
- `frontend/src/pages/Dashboard.tsx` — Replaced hard-coded Jellyfin/Backups sections with widget instance loop; kept Shortcuts section; added "Edit dashboard" button.
|
||||
- `frontend/src/App.tsx` — Registered `/addons/:addonId` route in both OIDC and non-OIDC route trees.
|
||||
- `docs/REQUIREMENTS.md` — Added Configurable Dashboard Widgets section.
|
||||
|
||||
## Verification (Slice 4)
|
||||
|
||||
```bash
|
||||
cd backend
|
||||
.venv/bin/python -m ruff check . # All checks passed
|
||||
PYTHONPATH=src .venv/bin/python -m pytest # 200 passed, 2 warnings
|
||||
cd ../frontend
|
||||
npm run lint # 2 pre-existing warnings, 0 errors
|
||||
npm run build # Built successfully
|
||||
npm run test -- src/widgets/registry.test.ts # 3 passed
|
||||
```
|
||||
|
||||
## Deviations from design (Slice 4)
|
||||
|
||||
- The "Edit dashboard" button lives in the Shortcuts section action area for now. A future UI pass can move it to a dedicated dashboard header.
|
||||
- Machine/task selectors in the config dialog filter to enabled Jellyfin machines / enabled tasks, which is slightly stricter than the design's generic string field.
|
||||
|
||||
## Remaining work
|
||||
|
||||
- Phase 1 widget system is complete. Future work could include widget grid layout, drag-and-drop reorder, richer Prometheus visualizations, or migrating shortcuts into the widget system.
|
||||
|
||||
## PR boundary
|
||||
|
||||
This slice is **PR 1 of 4** in the approved stacked-to-main chain. It is backend-only and leaves the frontend build/lint green.
|
||||
|
||||
**Actual changed-line count:** ~780 added lines across production code and tests (new files: ~597 lines; modified files: ~181 insertions). This is above the nominal ~400-line review budget, but Slice 1 is the smallest coherent backend unit: removing the CRUD router, store helpers, or tests would leave the slice non-functional or unverifiable. If the reviewer prefers a smaller blast radius, the store helpers (~90 lines) could be split into a preceding PR, though that PR would not be independently user-visible.
|
||||
@@ -0,0 +1,749 @@
|
||||
# SDD Design: Configurable Dashboard Widgets
|
||||
|
||||
**Change:** `configurable-dashboard-widgets`
|
||||
**Phase:** design
|
||||
**Date:** 2026-06-19
|
||||
|
||||
## 1. Architecture overview
|
||||
|
||||
The widget system introduces a thin, closed registry layer between the existing FastAPI backend and the React dashboard. It reuses the existing `SettingsStore` SQLite database, dependency-injection helpers (`get_jellyfin_client`, `get_ssh_client`, saved-task registry), and shadcn/ui component patterns.
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────────────────┐
|
||||
│ Browser │
|
||||
│ Dashboard.tsx ──► WidgetInstance renderer ──► widget registry │
|
||||
│ │ │ │ │
|
||||
│ │ useWidgetData() addon pages │
|
||||
│ │ │ │ │
|
||||
│ └──────────────► /api/widgets/instances/{id}/data ◄────────┘
|
||||
└─────────────────────────────────────────────────────────────────────┘
|
||||
│
|
||||
▼
|
||||
┌────────────────────────────────────────┐
|
||||
│ FastAPI /api/widgets router │
|
||||
│ - CRUD instances │
|
||||
│ - registry metadata │
|
||||
│ - data fetch via source adapters │
|
||||
└────────────────────────────────────────┘
|
||||
│
|
||||
┌─────────────────────────┼─────────────────────────┐
|
||||
▼ ▼ ▼
|
||||
SettingsStore source adapters existing routers
|
||||
(SQLite) (stateless) /api/dashboard
|
||||
dashboard_widgets jellyfin /api/tasks
|
||||
backups /api/settings
|
||||
grafana
|
||||
prometheus
|
||||
ssh_task
|
||||
static
|
||||
```
|
||||
|
||||
**Key constraints carried from the spec:**
|
||||
|
||||
- Closed, compile-time registries in both backend and frontend. No runtime plugin loading.
|
||||
- No secrets in `config_json`; credentials come from the machine/SSH-key store or environment settings.
|
||||
- Stacked `SectionCard` layout; no grid/drag/resize.
|
||||
- Each widget fetches its own data independently with per-type polling intervals and timeouts.
|
||||
|
||||
---
|
||||
|
||||
## 2. Backend design
|
||||
|
||||
### 2.1 `dashboard_widgets` table schema
|
||||
|
||||
Extend `SettingsStore.init_schema()` in `backend/src/media_library_viewer_api/services/settings_store.py`:
|
||||
|
||||
```sql
|
||||
CREATE TABLE IF NOT EXISTS dashboard_widgets (
|
||||
id TEXT PRIMARY KEY,
|
||||
addon_id TEXT NOT NULL,
|
||||
widget_type TEXT NOT NULL,
|
||||
title TEXT NOT NULL,
|
||||
config_json TEXT NOT NULL DEFAULT '{}',
|
||||
enabled INTEGER NOT NULL DEFAULT 1,
|
||||
sort_order INTEGER NOT NULL DEFAULT 0,
|
||||
created_at INTEGER NOT NULL,
|
||||
updated_at INTEGER NOT NULL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_dashboard_widgets_sort ON dashboard_widgets(sort_order);
|
||||
```
|
||||
|
||||
Store helper additions:
|
||||
|
||||
- `_row_to_widget(row)` — parse `config_json` into a `config` dict.
|
||||
- `_normalize_widget_payload(payload, widget_id=None)` — validate/assign defaults, generate `id` if missing.
|
||||
- `list_widgets()` — return all rows ordered by `sort_order ASC, created_at ASC`.
|
||||
- `get_widget(widget_id)` — single row.
|
||||
- `upsert_widget(payload, widget_id=None)` — insert or replace; preserve `created_at`.
|
||||
- `delete_widget(widget_id)` — delete by id.
|
||||
- `seed_default_widgets()` — called from `ensure_defaults()`; inserts the two defaults only when the table is empty.
|
||||
|
||||
`ensure_defaults()` already runs on startup (called via `get_settings_store()`). Seeding logic:
|
||||
|
||||
```python
|
||||
def ensure_defaults(self) -> None:
|
||||
self.init_schema()
|
||||
# existing local-machine seeding ...
|
||||
self._seed_dashboard_widgets()
|
||||
|
||||
def _seed_dashboard_widgets(self) -> None:
|
||||
with self.connect() as conn:
|
||||
row = conn.execute("SELECT COUNT(*) FROM dashboard_widgets").fetchone()
|
||||
if row and int(row[0]) > 0:
|
||||
return
|
||||
now = int(time.time())
|
||||
defaults = [
|
||||
{
|
||||
"id": "jellyfin-activity-default",
|
||||
"addon_id": "core",
|
||||
"widget_type": "jellyfin",
|
||||
"title": "Jellyfin activity",
|
||||
"config": {"machine_id": ""},
|
||||
"enabled": True,
|
||||
"sort_order": 0,
|
||||
},
|
||||
{
|
||||
"id": "backups-summary-default",
|
||||
"addon_id": "backups",
|
||||
"widget_type": "backups",
|
||||
"title": "Backups",
|
||||
"config": {},
|
||||
"enabled": True,
|
||||
"sort_order": 1,
|
||||
},
|
||||
]
|
||||
for w in defaults:
|
||||
self.upsert_widget(w)
|
||||
```
|
||||
|
||||
IDs are hard-coded so repeated startups are idempotent. Empty `config` for `jellyfin` resolves to the first enabled Jellyfin machine via existing DI.
|
||||
|
||||
### 2.2 Widget source adapter protocol
|
||||
|
||||
Adapters live in `backend/src/media_library_viewer_api/widgets/sources.py` (single file is sufficient for Phase 1).
|
||||
|
||||
```python
|
||||
from typing import Any, Protocol
|
||||
|
||||
class WidgetSource(Protocol):
|
||||
source_type: str
|
||||
async def fetch(self, config: dict[str, Any]) -> dict[str, Any]: ...
|
||||
```
|
||||
|
||||
Concrete adapters:
|
||||
|
||||
| source_type | class | implementation notes |
|
||||
|-------------|-------|----------------------|
|
||||
| `jellyfin` | `JellyfinWidgetSource` | Build a Starlette `Request` with `machine_id` query param, call `get_jellyfin_client(req)` and `get_user_id(req)`, then `client.sessions()`; reuse `_map_sessions_to_activity_rows` from `routers/dashboard.py` or move the helper to a shared `domain/dashboard.py`. |
|
||||
| `backups` | `BackupsWidgetSource` | Call `SettingsStore.list_backup_jobs`, `list_backup_runs`, `list_backup_alerts` and compute the same summary as `GET /api/dashboard/backups`; reuse `BackupDashboardSummary`. |
|
||||
| `grafana` | `GrafanaWidgetSource` | Read `grafana_url` from `get_settings()` (new setting, default `http://grafana:3000`) and `config.dashboard_uid`/`panel_id`; return `{url: "{grafana_url}/d/{dashboard_uid}?..."}`. No embedding. |
|
||||
| `prometheus` | `PrometheusWidgetSource` | Read `prometheus_url` from settings (env or default `http://prometheus:9090`), run instant query `config.promql`, return scalar/vector result. Apply 10 s timeout. |
|
||||
| `ssh_task` | `SshTaskWidgetSource` | Look up saved task by `config.task_id` in `SettingsStore`, resolve machine via existing `_resolve_machine_for_task` logic or a shared helper, run via `LocalCommandClient`/`RemoteSSHClient`, return trimmed stdout/stderr/exit_status. |
|
||||
| `static` | `StaticWidgetSource` | Return `{"text": config.get("text", "")}`; no network call. |
|
||||
|
||||
Adapter registry:
|
||||
|
||||
```python
|
||||
SOURCE_REGISTRY: dict[str, WidgetSource] = {
|
||||
"jellyfin": JellyfinWidgetSource(),
|
||||
"backups": BackupsWidgetSource(),
|
||||
"grafana": GrafanaWidgetSource(),
|
||||
"prometheus": PrometheusWidgetSource(),
|
||||
"ssh_task": SshTaskWidgetSource(),
|
||||
"static": StaticWidgetSource(),
|
||||
}
|
||||
```
|
||||
|
||||
Adapters must catch all exceptions and return `{"error": "human-readable message"}`. The only 500 case is an unhandled exception in the adapter, which the endpoint catches and logs.
|
||||
|
||||
Timeouts (adapter-level, not HTTP client-level where possible):
|
||||
|
||||
- `jellyfin`: 10 s
|
||||
- `backups`: 10 s
|
||||
- `prometheus`: 10 s
|
||||
- `ssh_task`: 30 s
|
||||
- `grafana`: 5 s
|
||||
- `static`: no fetch
|
||||
|
||||
### 2.3 Router layout
|
||||
|
||||
New file: `backend/src/media_library_viewer_api/routers/widgets.py`
|
||||
|
||||
```python
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from pydantic import BaseModel
|
||||
|
||||
from media_library_viewer_api.dependencies import get_settings_store
|
||||
from media_library_viewer_api.models.widgets import (
|
||||
WidgetInstance,
|
||||
WidgetInstanceInput,
|
||||
WidgetTypeInfo,
|
||||
WidgetDataResponse,
|
||||
)
|
||||
from media_library_viewer_api.services.settings_store import SettingsStore
|
||||
from media_library_viewer_api.widgets.registry import WIDGET_REGISTRY
|
||||
from media_library_viewer_api.widgets.sources import SOURCE_REGISTRY
|
||||
|
||||
router = APIRouter(prefix="/api/widgets", tags=["widgets"])
|
||||
```
|
||||
|
||||
Endpoints:
|
||||
|
||||
| Method | Path | Handler |
|
||||
|--------|------|---------|
|
||||
| GET | `/sources` | `list_sources()` — returns `["jellyfin", "backups", "grafana", "prometheus", "ssh_task", "static"]` |
|
||||
| GET | `/types` | `list_types()` — returns `list[WidgetTypeInfo]` built from `WIDGET_REGISTRY` |
|
||||
| GET | `/instances` | `list_instances(store)` — `store.list_widgets()` mapped to `WidgetInstance` |
|
||||
| POST | `/instances` | `create_instance(body, store)` — status 201 |
|
||||
| PUT | `/instances/{widget_id}` | `update_instance(widget_id, body, store)` — 404 if missing, 400 if `body.id != widget_id` |
|
||||
| DELETE | `/instances/{widget_id}` | `delete_instance(widget_id, store)` — 404 if missing |
|
||||
| GET | `/instances/{widget_id}/data` | `fetch_data(widget_id, store)` — look up widget, resolve source adapter, return `WidgetDataResponse` |
|
||||
|
||||
Validation flow in create/update:
|
||||
|
||||
1. Validate `WidgetInstanceInput` Pydantic model.
|
||||
2. Reject forbidden credential keys anywhere in `config`.
|
||||
3. Verify `widget_type` is in `WIDGET_REGISTRY`.
|
||||
4. Verify `addon_id` matches the registry entry for that type.
|
||||
5. Validate `config` against the widget type's JSON schema.
|
||||
6. Persist via `store.upsert_widget()`.
|
||||
|
||||
### 2.4 Pydantic models
|
||||
|
||||
New file: `backend/src/media_library_viewer_api/models/widgets.py`
|
||||
|
||||
```python
|
||||
from typing import Any
|
||||
from pydantic import BaseModel, Field, field_validator, model_validator
|
||||
|
||||
FORBIDDEN_CONFIG_KEYS = {
|
||||
"password", "token", "secret", "api_key", "apikey",
|
||||
"private_key", "passphrase", "credential",
|
||||
}
|
||||
|
||||
def _looks_secret(value: Any) -> bool:
|
||||
if not isinstance(value, str) or not value.strip():
|
||||
return False
|
||||
lowered = value.lower()
|
||||
if value.startswith("sk-") or value.startswith("eyJ"):
|
||||
return True
|
||||
if len(value) > 64 and lowered.isalnum():
|
||||
return True
|
||||
return False
|
||||
|
||||
def _validate_config_keys(config: dict[str, Any]) -> dict[str, Any]:
|
||||
for key, value in config.items():
|
||||
if key.lower() in FORBIDDEN_CONFIG_KEYS:
|
||||
raise ValueError(f"Credential key '{key}' is not allowed in widget config")
|
||||
if _looks_secret(value):
|
||||
raise ValueError(f"Value for '{key}' looks like a secret")
|
||||
if isinstance(value, dict):
|
||||
_validate_config_keys(value)
|
||||
return config
|
||||
|
||||
class WidgetInstanceInput(BaseModel):
|
||||
id: str | None = None
|
||||
addon_id: str
|
||||
widget_type: str
|
||||
title: str = Field(..., min_length=1)
|
||||
config: dict[str, Any] = Field(default_factory=dict)
|
||||
enabled: bool = True
|
||||
sort_order: int = Field(default=0, ge=0)
|
||||
|
||||
@field_validator("config")
|
||||
@classmethod
|
||||
def reject_credential_keys(cls, v):
|
||||
return _validate_config_keys(v or {})
|
||||
|
||||
class WidgetInstance(WidgetInstanceInput):
|
||||
id: str
|
||||
created_at: int
|
||||
updated_at: int
|
||||
|
||||
class WidgetTypeInfo(BaseModel):
|
||||
addon_id: str
|
||||
widget_type: str
|
||||
name: str
|
||||
description: str
|
||||
source_type: str
|
||||
config_schema: dict[str, Any]
|
||||
|
||||
class WidgetDataResponse(BaseModel):
|
||||
widget_id: str
|
||||
widget_type: str
|
||||
data: dict[str, Any] | None
|
||||
error: str | None
|
||||
fetched_at: int
|
||||
```
|
||||
|
||||
Widget registry file: `backend/src/media_library_viewer_api/widgets/registry.py`
|
||||
|
||||
```python
|
||||
WIDGET_REGISTRY: dict[str, dict[str, Any]] = {
|
||||
"jellyfin": {
|
||||
"addon_id": "core",
|
||||
"name": "Jellyfin activity",
|
||||
"description": "Live sessions and idle users from a Jellyfin server.",
|
||||
"source_type": "jellyfin",
|
||||
"config_schema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"machine_id": {"type": "string", "description": "Jellyfin machine id (empty = default)"},
|
||||
},
|
||||
"required": [],
|
||||
},
|
||||
},
|
||||
"backups": { "addon_id": "backups", ... },
|
||||
"grafana-link": { "addon_id": "grafana", ... },
|
||||
"prometheus-metric": { "addon_id": "prometheus", ... },
|
||||
"ssh-task": { "addon_id": "ssh-tasks", ... },
|
||||
"static": { "addon_id": "core", ... },
|
||||
}
|
||||
```
|
||||
|
||||
The registry explicitly maps `widget_type -> addon_id` so the backend can enforce invariant #2.
|
||||
|
||||
### 2.5 Main.py registration
|
||||
|
||||
Add to `backend/src/media_library_viewer_api/main.py`:
|
||||
|
||||
```python
|
||||
from media_library_viewer_api.routers import widgets as widgets_router
|
||||
...
|
||||
app.include_router(widgets_router.router)
|
||||
```
|
||||
|
||||
Because all `/api/widgets` endpoints are under the existing JWT/API-key middleware (`enforce_jwt_auth`), no additional auth decorator is needed.
|
||||
|
||||
---
|
||||
|
||||
## 3. Frontend design
|
||||
|
||||
### 3.1 Widget registry
|
||||
|
||||
New file: `frontend/src/widgets/registry.ts`
|
||||
|
||||
```typescript
|
||||
import type { WidgetInstance, WidgetInstanceInput } from "../types";
|
||||
|
||||
export interface WidgetConfigField {
|
||||
key: string;
|
||||
label: string;
|
||||
type: "string" | "select" | "boolean" | "number";
|
||||
options?: { label: string; value: string }[];
|
||||
helper?: string;
|
||||
}
|
||||
|
||||
export interface WidgetDefinition {
|
||||
widgetType: string;
|
||||
addonId: string;
|
||||
name: string;
|
||||
description: string;
|
||||
sourceType: string;
|
||||
refreshInterval: number; // ms, 0 = no polling
|
||||
defaultConfig: Record<string, unknown>;
|
||||
configFields: WidgetConfigField[];
|
||||
component: React.ComponentType<{ widget: WidgetInstance }>;
|
||||
}
|
||||
|
||||
export const WIDGET_REGISTRY: Record<string, WidgetDefinition> = {
|
||||
jellyfin: { ... },
|
||||
backups: { ... },
|
||||
"grafana-link": { ... },
|
||||
"prometheus-metric": { ... },
|
||||
"ssh-task": { ... },
|
||||
static: { ... },
|
||||
};
|
||||
|
||||
export function getWidgetDefinition(widgetType: string): WidgetDefinition | undefined {
|
||||
return WIDGET_REGISTRY[widgetType];
|
||||
}
|
||||
```
|
||||
|
||||
Refresh intervals (ms):
|
||||
|
||||
- `jellyfin`: 30_000
|
||||
- `backups`: 60_000
|
||||
- `grafana-link`: 0
|
||||
- `prometheus-metric`: 30_000
|
||||
- `ssh-task`: 0
|
||||
- `static`: 0
|
||||
|
||||
Widget components live in `frontend/src/widgets/*.tsx`:
|
||||
|
||||
- `JellyfinWidget.tsx` — wraps `NowPlaying` / activity data.
|
||||
- `BackupsWidget.tsx` — reuses `BackupDashboardWidget` internals or extracts a shared presentational component.
|
||||
- `GrafanaLinkWidget.tsx` — renders a deep-link card.
|
||||
- `PrometheusMetricWidget.tsx` — metric value/sparkline card.
|
||||
- `SshTaskWidget.tsx` — preformatted output panel.
|
||||
- `StaticWidget.tsx` — markdown/text block.
|
||||
|
||||
### 3.2 Dashboard rendering loop
|
||||
|
||||
Modify `frontend/src/pages/Dashboard.tsx`:
|
||||
|
||||
```tsx
|
||||
import { useWidgetInstances } from "../hooks/useWidgets";
|
||||
import { WidgetInstance } from "../components/WidgetInstance";
|
||||
|
||||
export function Dashboard() {
|
||||
const { data: instances = [] } = useWidgetInstances();
|
||||
const visible = useMemo(
|
||||
() => instances.filter((w) => w.enabled).sort((a, b) => a.sort_order - b.sort_order),
|
||||
[instances],
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
{/* Shortcuts remain a first-class section to avoid data migration */}
|
||||
<ShortcutsSection />
|
||||
|
||||
{visible.map((widget) => (
|
||||
<WidgetInstance key={widget.id} widget={widget} />
|
||||
))}
|
||||
|
||||
<WidgetConfigDialog />
|
||||
<ConfirmDialog ... />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
`WidgetInstance` renderer (`frontend/src/components/WidgetInstance.tsx`):
|
||||
|
||||
```tsx
|
||||
import { SectionCard } from "./SectionCard";
|
||||
import { useWidgetData } from "../hooks/useWidgets";
|
||||
import { getWidgetDefinition } from "../widgets/registry";
|
||||
|
||||
export function WidgetInstance({ widget }: { widget: WidgetInstance }) {
|
||||
const def = getWidgetDefinition(widget.widget_type);
|
||||
const { data, isLoading } = useWidgetData(widget.id, def?.refreshInterval ?? 0);
|
||||
|
||||
if (!def) {
|
||||
return (
|
||||
<SectionCard title={widget.title}>
|
||||
<Alert><AlertDescription>Unknown widget type: {widget.widget_type}</AlertDescription></Alert>
|
||||
</SectionCard>
|
||||
);
|
||||
}
|
||||
|
||||
const Component = def.component;
|
||||
return (
|
||||
<SectionCard title={widget.title}>
|
||||
{isLoading && !data ? <SkeletonWidget /> : <Component widget={widget} />}
|
||||
</SectionCard>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
Each widget component receives the `widget` instance and reads `data?.data` / `data?.error` from its own `useWidgetData` query (or the parent can pass it; both work, but passing avoids a second hook call). Prefer passing `data` and `isLoading` from `WidgetInstance` to the component to keep components pure.
|
||||
|
||||
### 3.3 TanStack Query hooks
|
||||
|
||||
New file: `frontend/src/hooks/useWidgets.ts`:
|
||||
|
||||
```typescript
|
||||
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import {
|
||||
fetchWidgetSources,
|
||||
fetchWidgetTypes,
|
||||
fetchWidgetInstances,
|
||||
createWidgetInstance,
|
||||
updateWidgetInstance,
|
||||
deleteWidgetInstance,
|
||||
fetchWidgetData,
|
||||
} from "../api/widgets";
|
||||
import type { WidgetInstanceInput } from "../types";
|
||||
|
||||
export function useWidgetInstances() {
|
||||
return useQuery({
|
||||
queryKey: ["widgets", "instances"],
|
||||
queryFn: fetchWidgetInstances,
|
||||
refetchInterval: 60_000,
|
||||
});
|
||||
}
|
||||
|
||||
export function useWidgetData(widgetId: string, refreshInterval: number) {
|
||||
return useQuery({
|
||||
queryKey: ["widgets", "data", widgetId],
|
||||
queryFn: () => fetchWidgetData(widgetId),
|
||||
refetchInterval: refreshInterval || false,
|
||||
retry: 1,
|
||||
});
|
||||
}
|
||||
|
||||
export function useSaveWidgetInstance() {
|
||||
const queryClient = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: (input: WidgetInstanceInput) =>
|
||||
input.id ? updateWidgetInstance(input) : createWidgetInstance(input),
|
||||
onSuccess: () => queryClient.invalidateQueries({ queryKey: ["widgets", "instances"] }),
|
||||
});
|
||||
}
|
||||
|
||||
export function useDeleteWidgetInstance() {
|
||||
const queryClient = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: (widgetId: string) => deleteWidgetInstance(widgetId),
|
||||
onSuccess: () => queryClient.invalidateQueries({ queryKey: ["widgets", "instances"] }),
|
||||
});
|
||||
}
|
||||
|
||||
export function useWidgetSources() {
|
||||
return useQuery({ queryKey: ["widgets", "sources"], queryFn: fetchWidgetSources });
|
||||
}
|
||||
|
||||
export function useWidgetTypes() {
|
||||
return useQuery({ queryKey: ["widgets", "types"], queryFn: fetchWidgetTypes });
|
||||
}
|
||||
```
|
||||
|
||||
### 3.4 Configuration UI
|
||||
|
||||
Add a new `WidgetConfigDialog` component (can live in `frontend/src/components/WidgetConfigDialog.tsx` or inline in `Dashboard.tsx`).
|
||||
|
||||
Behavior:
|
||||
|
||||
- "Edit dashboard" button in the Dashboard header opens the dialog.
|
||||
- Dialog lists all instances (enabled and disabled) with sort-order inputs, enabled toggle, edit/delete actions, and up/down reorder buttons.
|
||||
- "Add widget" sub-flow: select widget type from registry, then render source-specific config fields.
|
||||
- Form fields reuse `Dialog`, `Input`, `Label`, `Switch`, `Select`, `Button`, `Alert`.
|
||||
|
||||
Source-specific config rendering:
|
||||
|
||||
```tsx
|
||||
function WidgetConfigFields({
|
||||
definition,
|
||||
config,
|
||||
onChange,
|
||||
}: {
|
||||
definition: WidgetDefinition;
|
||||
config: Record<string, unknown>;
|
||||
onChange: (config: Record<string, unknown>) => void;
|
||||
}) {
|
||||
return (
|
||||
<div className="flex flex-col gap-3">
|
||||
{definition.configFields.map((field) => (
|
||||
<Field key={field.key} label={field.label} htmlFor={field.key}>
|
||||
{field.type === "select" ? (
|
||||
<Select
|
||||
value={String(config[field.key] ?? "")}
|
||||
onValueChange={(v) => onChange({ ...config, [field.key]: v })}
|
||||
>
|
||||
{/* ... */}
|
||||
</Select>
|
||||
) : (
|
||||
<Input
|
||||
id={field.key}
|
||||
value={String(config[field.key] ?? "")}
|
||||
onChange={(e) => onChange({ ...config, [field.key]: e.target.value })}
|
||||
/>
|
||||
)}
|
||||
</Field>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
For fields that need dynamic options (e.g., machine selection for `jellyfin`, saved task selection for `ssh-task`), the dialog can use `useMonitoringSettings()` and `useTasks()` to populate select options and map them to `machine_id`/`task_id` config values.
|
||||
|
||||
### 3.5 Addon pages
|
||||
|
||||
New file: `frontend/src/pages/AddonPage.tsx`:
|
||||
|
||||
```tsx
|
||||
import { useParams } from "react-router-dom";
|
||||
import { Alert, AlertDescription } from "@/components/ui/alert";
|
||||
import { GrafanaAddonPage } from "../addons/GrafanaAddonPage";
|
||||
import { PrometheusAddonPage } from "../addons/PrometheusAddonPage";
|
||||
import { SshTasksAddonPage } from "../addons/SshTasksAddonPage";
|
||||
|
||||
const ADDON_PAGES: Record<string, React.ComponentType> = {
|
||||
grafana: GrafanaAddonPage,
|
||||
prometheus: PrometheusAddonPage,
|
||||
"ssh-tasks": SshTasksAddonPage,
|
||||
};
|
||||
|
||||
export function AddonPage() {
|
||||
const { addonId } = useParams<{ addonId: string }>();
|
||||
const Page = addonId ? ADDON_PAGES[addonId] : undefined;
|
||||
if (!Page) {
|
||||
return (
|
||||
<Alert>
|
||||
<AlertDescription>Addon "{addonId}" is not installed.</AlertDescription>
|
||||
</Alert>
|
||||
);
|
||||
}
|
||||
return <Page />;
|
||||
}
|
||||
```
|
||||
|
||||
Register in `frontend/src/App.tsx` inside both route trees:
|
||||
|
||||
```tsx
|
||||
<Route path="/addons/:addonId" element={<AddonPage />} />
|
||||
```
|
||||
|
||||
Grafana widgets render a link to `/addons/grafana` or directly to the external Grafana URL; either is acceptable. The spec requires the addon page route exists and Grafana widgets deep-link rather than embed.
|
||||
|
||||
---
|
||||
|
||||
## 4. Data flow
|
||||
|
||||
1. **Config CRUD**
|
||||
- User opens config dialog → `useWidgetInstances()` and `useWidgetTypes()` load.
|
||||
- Add/edit form → `useSaveWidgetInstance().mutate(input)` → `POST/PUT /api/widgets/instances` → backend validates, persists, returns `WidgetInstance` → query cache invalidated → dashboard re-renders.
|
||||
|
||||
2. **Per-widget data fetch**
|
||||
- `Dashboard.tsx` maps enabled instances to `<WidgetInstance />`.
|
||||
- Each `WidgetInstance` calls `useWidgetData(widget.id, refreshInterval)`.
|
||||
- Hook calls `GET /api/widgets/instances/{id}/data`.
|
||||
- Endpoint loads the instance, picks the adapter by `source_type`, calls `adapter.fetch(config)`, wraps in `WidgetDataResponse`.
|
||||
- Adapter resolves credentials from machine store / env / SSH-key store and returns data or error payload.
|
||||
|
||||
3. **Error boundaries and loading states**
|
||||
- Adapter exceptions are caught by the endpoint and returned as `error` with HTTP 200; unhandled exceptions return 500.
|
||||
- `WidgetInstance` shows a skeleton on initial load.
|
||||
- If `data.error` is set, render an inline `Alert` inside the widget's `SectionCard`.
|
||||
- A failing widget does not block sibling widgets because each has its own query.
|
||||
|
||||
---
|
||||
|
||||
## 5. Security design
|
||||
|
||||
- **No secrets in `config_json`**: forbidden key list enforced by Pydantic validator and store write path. Values starting with `sk-`/`eyJ` or long alphanumeric strings are rejected.
|
||||
- **Credential resolution**: adapters use `get_settings_store().get_machine_config()`, `get_ssh_key()`, and `get_settings()` for Grafana/Prometheus URLs. No widget config stores URLs with embedded credentials.
|
||||
- **Saved-task registry reuse**: `ssh_task` adapter only runs tasks from the existing saved-task registry; no arbitrary command execution.
|
||||
- **Auth**: all `/api/widgets` endpoints inherit existing JWT/API-key middleware.
|
||||
- **No iframes**: addon pages and Grafana widgets render links only.
|
||||
- **Validation at two layers**: Pydantic model rejects malformed/credential-laden configs; store-level normalization also rejects forbidden keys as defense-in-depth.
|
||||
|
||||
---
|
||||
|
||||
## 6. Testing approach
|
||||
|
||||
### Backend
|
||||
|
||||
New test file: `backend/tests/test_widgets.py`
|
||||
|
||||
- `TestWidgetRegistry`: `GET /api/widgets/sources` and `/api/widgets/types` return expected closed lists.
|
||||
- `TestWidgetCrud`:
|
||||
- create static widget → 201, config round-trips.
|
||||
- update nonexistent → 404.
|
||||
- delete → 404 after delete.
|
||||
- unknown widget type → 422.
|
||||
- credential key in config → 422.
|
||||
- `TestWidgetData`:
|
||||
- static widget data returns text unchanged.
|
||||
- misconfigured jellyfin widget returns `error` in payload with HTTP 200.
|
||||
- `TestWidgetSeeding`:
|
||||
- fresh store seeds Jellyfin + Backups widgets.
|
||||
- existing widget rows prevent re-seeding.
|
||||
|
||||
Use existing `test_client` fixture pattern from `test_api.py` with mocked Jellyfin/SSH clients where needed.
|
||||
|
||||
### Frontend
|
||||
|
||||
- `npm run build` (via `tsc -b`) validates new TypeScript types and component imports.
|
||||
- Add `frontend/tests/widgets.test.mjs` using the existing `node:test` + `node:assert/strict` setup to test:
|
||||
- `getWidgetDefinition` returns correct refresh intervals.
|
||||
- registry contains exactly the six Phase 1 widget types.
|
||||
- If/when the project adopts Vitest, add hook tests with MSW; for Phase 1, rely on build + manual component tests.
|
||||
|
||||
### Integration / manual
|
||||
|
||||
- Fresh Docker dev stack shows Jellyfin activity + Backups widgets by default.
|
||||
- Add each widget type via config UI and verify render + polling behavior.
|
||||
- Verify disabled widget is hidden and reorder changes dashboard order.
|
||||
|
||||
---
|
||||
|
||||
## 7. File-level plan
|
||||
|
||||
### Create
|
||||
|
||||
| File | Rationale |
|
||||
|------|-----------|
|
||||
| `backend/src/media_library_viewer_api/models/widgets.py` | Pydantic models: `WidgetInstance`, `WidgetInstanceInput`, `WidgetTypeInfo`, `WidgetDataResponse` plus credential validators. |
|
||||
| `backend/src/media_library_viewer_api/widgets/__init__.py` | Package marker for widget subsystem. |
|
||||
| `backend/src/media_library_viewer_api/widgets/registry.py` | Closed widget-type registry mapping widget_type → addon_id, source_type, JSON schema. |
|
||||
| `backend/src/media_library_viewer_api/widgets/sources.py` | Stateless source adapters for all six source types. |
|
||||
| `backend/src/media_library_viewer_api/routers/widgets.py` | REST endpoints for CRUD, registry metadata, and data fetch. |
|
||||
| `frontend/src/types/index.ts` additions | TypeScript interfaces matching backend models. |
|
||||
| `frontend/src/api/widgets.ts` | API functions for widget endpoints. |
|
||||
| `frontend/src/hooks/useWidgets.ts` | TanStack Query hooks for instances, data, mutations. |
|
||||
| `frontend/src/widgets/registry.ts` | Frontend closed widget registry. |
|
||||
| `frontend/src/widgets/*.tsx` | Six widget presentational components. |
|
||||
| `frontend/src/components/WidgetInstance.tsx` | Renderer that loads data and dispatches to widget component. |
|
||||
| `frontend/src/components/WidgetConfigDialog.tsx` | Add/edit/reorder/remove configuration UI. |
|
||||
| `frontend/src/pages/AddonPage.tsx` | Route target for `/addons/:addonId`. |
|
||||
| `frontend/src/addons/GrafanaAddonPage.tsx` | Grafana addon page (links only, no iframe). |
|
||||
| `frontend/src/addons/PrometheusAddonPage.tsx` | Prometheus addon page. |
|
||||
| `frontend/src/addons/SshTasksAddonPage.tsx` | SSH tasks addon page. |
|
||||
| `backend/tests/test_widgets.py` | Backend API and store tests. |
|
||||
| `frontend/tests/widgets.test.mjs` | Frontend registry unit tests. |
|
||||
|
||||
### Modify
|
||||
|
||||
| File | Rationale |
|
||||
|------|-----------|
|
||||
| `backend/src/media_library_viewer_api/services/settings_store.py` | Add `dashboard_widgets` schema, CRUD helpers, default seeding in `ensure_defaults()`. |
|
||||
| `backend/src/media_library_viewer_api/config.py` | Add `grafana_url: str` setting (default `http://grafana:3000`) so adapters can build deep-links. Optional if Grafana URL is already derivable from env; for Phase 1 add it explicitly. |
|
||||
| `backend/src/media_library_viewer_api/main.py` | Register `widgets_router`. |
|
||||
| `frontend/src/pages/Dashboard.tsx` | Replace hard-coded Jellyfin/Backups sections with widget instance loop; keep Shortcuts section intact; add "Edit dashboard" action. |
|
||||
| `frontend/src/App.tsx` | Add `/addons/:addonId` route in both OIDC and non-OIDC route trees. |
|
||||
| `docs/REQUIREMENTS.md` | Document new widget system behavior and security rule. |
|
||||
|
||||
---
|
||||
|
||||
## 8. Slice boundaries
|
||||
|
||||
A full Phase 1 implementation is expected to touch ~1,000–1,200 lines across backend and frontend, exceeding the ~400-line review budget. Recommended reviewable slices:
|
||||
|
||||
### Slice 1: Backend CRUD and default seeding
|
||||
|
||||
- Create `models/widgets.py`.
|
||||
- Create `widgets/registry.py`.
|
||||
- Create `routers/widgets.py` for CRUD + metadata endpoints.
|
||||
- Extend `settings_store.py` with table schema, helpers, and `_seed_dashboard_widgets()`.
|
||||
- Register router in `main.py`.
|
||||
- Add `backend/tests/test_widgets.py` for CRUD/registry tests.
|
||||
- **Estimated:** ~350–400 changed lines.
|
||||
|
||||
### Slice 2: Backend source adapters and data endpoint
|
||||
|
||||
- Create `widgets/sources.py` with all six adapters.
|
||||
- Add `GET /api/widgets/instances/{id}/data` endpoint.
|
||||
- Add `grafana_url` to `config.py`.
|
||||
- Extract/share `dashboard.py` activity mapping if needed.
|
||||
- Extend tests with data-fetch scenarios.
|
||||
- **Estimated:** ~300–350 changed lines.
|
||||
|
||||
### Slice 3: Frontend types, API, hooks, and widget registry
|
||||
|
||||
- Add TypeScript interfaces to `types/index.ts`.
|
||||
- Create `api/widgets.ts` and `hooks/useWidgets.ts`.
|
||||
- Create `widgets/registry.ts` and the six widget components.
|
||||
- Add `frontend/tests/widgets.test.mjs`.
|
||||
- **Estimated:** ~350–400 changed lines.
|
||||
|
||||
### Slice 4: Dashboard rendering loop, config UI, and addon pages
|
||||
|
||||
- Modify `Dashboard.tsx` to render widget instances.
|
||||
- Create `WidgetInstance.tsx` and `WidgetConfigDialog.tsx`.
|
||||
- Create `AddonPage.tsx` and addon pages.
|
||||
- Register addon route in `App.tsx`.
|
||||
- Update `docs/REQUIREMENTS.md`.
|
||||
- **Estimated:** ~350–400 changed lines.
|
||||
|
||||
**Recommended order:** Slice 1 → Slice 2 → Slice 3 → Slice 4. Each slice is independently testable and leaves the app in a working state. Slices 1 and 2 can be merged into one PR if the backend-only change stays under the budget; otherwise keep them separate.
|
||||
|
||||
---
|
||||
|
||||
## 9. Open questions / decisions
|
||||
|
||||
1. **Grafana URL source**: Add `grafana_url` to `Settings` in `config.py` (default `http://grafana:3000`). This is the minimal change; alternatively derive from `ALERTMANAGER_URL` or an env var, but explicit is clearer.
|
||||
2. **Shortcuts migration**: Keep Shortcuts as a hard-coded section above widgets for Phase 1. This avoids a data migration and satisfies "no data is lost". A future phase can migrate shortcuts into the widget system.
|
||||
3. **Prometheus URL**: Reuse existing `prometheus_file_sd_dir` / convention or add `prometheus_url` setting. For instant queries the adapter needs a query URL; add `prometheus_url: str = "http://prometheus:9090"` to `Settings`.
|
||||
@@ -0,0 +1,210 @@
|
||||
# SDD Explore: Configurable Dashboard Widgets
|
||||
|
||||
**Change:** `configurable-dashboard-widgets`
|
||||
**Phase:** explore
|
||||
**Date:** 2026-06-19
|
||||
|
||||
## 1. Existing Frontend Architecture
|
||||
|
||||
### Routing & navigation
|
||||
|
||||
- `frontend/src/App.tsx` defines a static `navItems` array and registers routes inside `<Routes>`.
|
||||
- Current top-level pages: `/` Dashboard, `/observability`, `/media`, `/files`, `/backups`, `/users`, `/actions`, `/settings`.
|
||||
- Sidebar and mobile drawer both consume `navItems`; adding a new addon page requires editing this file today.
|
||||
|
||||
### Page structure
|
||||
|
||||
- Pages live in `frontend/src/pages/`.
|
||||
- Some pages are re-exported through thin entrypoints (`FileBrowser.tsx`, `Users.tsx`) while implementations live in `*.impl.tsx` files.
|
||||
- `BackupsPage` and `ObservabilityPage` live under `frontend/src/components/` but are routed as pages.
|
||||
|
||||
### Dashboard composition today
|
||||
|
||||
- `frontend/src/pages/Dashboard.tsx` renders three hard-coded sections:
|
||||
1. **Shortcuts** — `SectionCard` + `ShortcutCard` grid.
|
||||
2. **Jellyfin activity** — `SectionCard` + `NowPlaying`.
|
||||
3. **Backups** — `BackupDashboardWidget`.
|
||||
- Machine selection (e.g., active Jellyfin machine) is local component state.
|
||||
|
||||
## 2. Existing Backend Architecture
|
||||
|
||||
### Router registration
|
||||
|
||||
- `backend/src/media_library_viewer_api/main.py` statically imports routers and calls `app.include_router(...)`.
|
||||
- Existing routers: `dashboard`, `monitoring`, `media`, `files`, `jobs`, `users`, `tasks`, `settings`, `backups`.
|
||||
|
||||
### Settings persistence
|
||||
|
||||
- `backend/src/media_library_viewer_api/services/settings_store.py` is the single SQLite-backed store.
|
||||
- Pattern: `init_schema()` creates tables, JSON columns store flexible config, CRUD helpers return plain dicts.
|
||||
- Already stores: monitoring machines, SSH keys, saved tasks, dashboard shortcuts, backup jobs/runs/alerts.
|
||||
|
||||
### Client resolution
|
||||
|
||||
- `backend/src/media_library_viewer_api/dependencies.py` resolves machines by `machine_id` query param and service tag.
|
||||
- Jellyfin/SSH/local clients are built from machine config + SSH key store.
|
||||
|
||||
## 3. Widget / Addon Extension Points
|
||||
|
||||
### Frontend
|
||||
|
||||
| Extension point | Current state | How to reuse/extend |
|
||||
|---|---|---|
|
||||
| Sidebar nav | Static `navItems` | Derive from an addon registry; add dynamic `Route` entries |
|
||||
| Dashboard surface | Hard-coded sections | Render widget instances from persisted config |
|
||||
| Widget chrome | `SectionCard`, `MetricCard` | Reuse as container tiles |
|
||||
| Page chrome | `ObservabilityPage` pattern | Model addon pages on shadcn Card + lucide icons + TanStack Query |
|
||||
| Data fetching | `useDashboard`, `useBackups`, `useObservability` | Add `useWidgets` hooks per source |
|
||||
|
||||
### Backend
|
||||
|
||||
| Extension point | Current state | How to reuse/extend |
|
||||
|---|---|---|
|
||||
| Router registration | Static imports | Add a `widgets` dispatcher router or explicitly register addon routers |
|
||||
| Persistence | `SettingsStore` JSON columns | Add `dashboard_widgets` / `addon_configs` tables |
|
||||
| Client/credential access | `dependencies.py` machine resolution | Widget adapters reuse existing clients |
|
||||
| Source adapters | None | New abstraction: `WidgetSource` per source type |
|
||||
|
||||
## 4. What a Widget Needs to Consume Data
|
||||
|
||||
### Source adapters (backend)
|
||||
|
||||
A widget source adapter should implement a small interface, e.g.:
|
||||
|
||||
```python
|
||||
class WidgetSource(Protocol):
|
||||
source_type: str
|
||||
|
||||
async def fetch(self, config: dict[str, Any]) -> dict[str, Any]:
|
||||
...
|
||||
```
|
||||
|
||||
Candidate source types:
|
||||
|
||||
- `jellyfin` — reuse `JellyfinClient` for counts/sessions.
|
||||
- `backups` — reuse backup summary logic already in `dashboard.py`.
|
||||
- `grafana` — link/iframe metadata or query a Grafana datasource (env URL/auth already configured).
|
||||
- `prometheus` — instant query via env Prometheus URL.
|
||||
- `alertmanager` — summary already exists in `monitoring.py`.
|
||||
- `ssh_task` / `script` — run a saved task or whitelisted script through the existing machine/task registry.
|
||||
- `static` — simple text/markdown/no-data widget.
|
||||
|
||||
### Config schema
|
||||
|
||||
Each widget instance needs:
|
||||
|
||||
- `id`, `addon_id`, `widget_type`, `title`, `icon`, `enabled`
|
||||
- `source_type` + `source_config` (JSON)
|
||||
- `refresh_interval_seconds`
|
||||
- `layout` (position, size) or `sort_order`
|
||||
- `display_options` (e.g., show header, variant)
|
||||
|
||||
### Refresh / polling
|
||||
|
||||
- Frontend: TanStack Query `refetchInterval` per widget type.
|
||||
- Backend: short-lived proxy/adapters; avoid heavy polling for slow sources (SSH scripts).
|
||||
|
||||
### Credential handling
|
||||
|
||||
- **Never store secrets in widget config.**
|
||||
- Jellyfin/SSH: use machine registry + SSH key store.
|
||||
- Grafana/Prometheus/Alertmanager: use backend env settings (`get_settings()`).
|
||||
|
||||
## 5. Key Architectural Decisions
|
||||
|
||||
### Widget registry: compile-time vs runtime
|
||||
|
||||
- **Compile-time** (simpler): a static map of `widget_type -> component` in the frontend and source adapters in the backend.
|
||||
- **Runtime** (more “addon”): backend serves an addon manifest, frontend lazily loads component modules.
|
||||
- **Recommendation**: start compile-time for Phase 1; keep the data model flexible for runtime manifests later.
|
||||
|
||||
### Addon manifest format
|
||||
|
||||
A minimal manifest could be:
|
||||
|
||||
```yaml
|
||||
id: grafana-addon
|
||||
name: Grafana
|
||||
icon: Activity
|
||||
page:
|
||||
route: /addons/grafana
|
||||
component: ./addons/grafana/GrafanaPage
|
||||
widgets:
|
||||
- type: grafana-link
|
||||
name: Grafana Link
|
||||
component: ./addons/grafana/GrafanaLinkWidget
|
||||
source_type: grafana
|
||||
config_schema:
|
||||
- name: dashboardUid
|
||||
type: string
|
||||
```
|
||||
|
||||
### Dashboard persistence model
|
||||
|
||||
- Store widget instances globally (like current shortcuts) in a new `dashboard_widgets` table:
|
||||
- `id TEXT PRIMARY KEY`
|
||||
- `addon_id TEXT`
|
||||
- `widget_type TEXT`
|
||||
- `title TEXT`
|
||||
- `config_json TEXT`
|
||||
- `enabled INTEGER`
|
||||
- `sort_order INTEGER`
|
||||
- `created_at`, `updated_at`
|
||||
- Consider a `user_id` column later if multi-user config is needed.
|
||||
|
||||
### Layout
|
||||
|
||||
- **Option A**: keep the existing stacked `SectionCard` list (simple, mobile-safe, no new dependencies).
|
||||
- **Option B**: adopt a grid library (e.g., `react-grid-layout`) for drag/resize.
|
||||
- **Recommendation**: Option A for Phase 1 to respect the thin-dashboard aesthetic and review budget.
|
||||
|
||||
### Routing
|
||||
|
||||
- Addon pages under `/addons/{addon_id}` avoids collisions and keeps the namespace clean.
|
||||
- Alternatively top-level routes if the UX demands it.
|
||||
|
||||
### Backend API surface
|
||||
|
||||
Proposed endpoints:
|
||||
|
||||
- `GET /api/widgets/sources` — list available source types.
|
||||
- `GET /api/widgets/types` — list widget types per addon.
|
||||
- `GET /api/widgets/instances` — persisted dashboard widget instances.
|
||||
- `POST /api/widgets/instances` — create instance.
|
||||
- `PUT /api/widgets/instances/{id}` — update instance.
|
||||
- `DELETE /api/widgets/instances/{id}` — delete instance.
|
||||
- `GET /api/widgets/instances/{id}/data` — fetch widget data via source adapter.
|
||||
|
||||
### Admin vs user configuration
|
||||
|
||||
- Today there is no RBAC; Settings is implicitly admin.
|
||||
- Widget configuration can live in Settings or a new “Dashboard settings” mode.
|
||||
- Keep it simple: global config, editable by any authenticated user.
|
||||
|
||||
### Default widgets
|
||||
|
||||
- Seed new installs with the existing defaults: Jellyfin activity, Backup summary.
|
||||
- This preserves today’s out-of-box dashboard while making it configurable.
|
||||
|
||||
### Error / loading states
|
||||
|
||||
- Reuse `Skeleton`, `Alert`, `EmptyState` patterns from `ObservabilityPage`.
|
||||
- Each widget fails independently; the dashboard continues to render.
|
||||
|
||||
## 6. Patterns to Reuse
|
||||
|
||||
- **UI containers**: `SectionCard`, `MetricCard`, `Card`, `Badge`.
|
||||
- **Data fetching**: TanStack Query hooks with `refetchInterval`.
|
||||
- **Local state**: `usePersistentState`.
|
||||
- **Backend persistence**: `SettingsStore` JSON-column CRUD.
|
||||
- **Dependency injection**: FastAPI `Depends` + machine/client resolution.
|
||||
- **Type contracts**: Pydantic models in `backend/src/media_library_viewer_api/models/`.
|
||||
- **Lazy loading**: `React.lazy` for optional addon frontends.
|
||||
|
||||
## 7. Open Questions for Proposal
|
||||
|
||||
1. Should Phase 1 support runtime addon discovery, or a closed built-in widget set?
|
||||
2. Do we need a grid layout with drag/resize, or is the existing stacked SectionCard list sufficient?
|
||||
3. Should widget configuration be global or per-user?
|
||||
4. Which sources are in Phase 1? (Recommended: Jellyfin, Backups, Grafana link, Prometheus instant query, SSH saved task.)
|
||||
5. Do we want addon pages to be iframes (e.g., Grafana) or custom React pages?
|
||||
@@ -0,0 +1,155 @@
|
||||
# SDD Proposal: Configurable Dashboard Widgets
|
||||
|
||||
**Change:** `configurable-dashboard-widgets`
|
||||
**Phase:** proposal
|
||||
**Date:** 2026-06-19
|
||||
|
||||
## 1. Problem / Why Now
|
||||
|
||||
The Manage dashboard (`frontend/src/pages/Dashboard.tsx`) currently renders three hard-coded sections: Shortcuts, Jellyfin activity, and Backups. Each new source of at-a-glance information requires editing the dashboard component and adding ad hoc backend endpoints. The user wants to surface information from many sources—Grafana, Jellyfin, SSH scripts, Prometheus, and more—without rebuilding the dashboard every time. We need a small, extensible widget system that makes the dashboard configurable while keeping the implementation within the existing FastAPI/React stack and the current thin-dashboard aesthetic.
|
||||
|
||||
## 2. Target Users and Situations
|
||||
|
||||
- **Primary users:** Homelab operators and small-team admins who open Manage to check overall system health.
|
||||
- **Workflow moments:**
|
||||
- First login of the day: scan backup status, Jellyfin activity, and key Prometheus metrics.
|
||||
- Troubleshooting: jump from a widget into a dedicated addon page (e.g., Grafana dashboard, saved SSH task output).
|
||||
- Onboarding a new machine: add a widget that exposes a saved SSH task or Prometheus query without a code change.
|
||||
- **Urgency:** Medium. The existing dashboard already works; the pain is maintainability and visibility into an expanding set of sources.
|
||||
|
||||
## 3. Product Outcome
|
||||
|
||||
After Phase 1, an authenticated user can:
|
||||
|
||||
- See the existing dashboard sections rendered as configurable widgets.
|
||||
- Add, edit, remove, enable/disable, and reorder widgets from a single global dashboard configuration.
|
||||
- Choose from a built-in set of widget types backed by Jellyfin, backup summaries, Grafana deep-links, Prometheus instant queries, and SSH saved-task output.
|
||||
- Open dedicated addon pages under `/addons/{addon_id}` for widgets that need more space (e.g., Grafana details).
|
||||
- Continue using the familiar stacked `SectionCard` layout on desktop and mobile.
|
||||
|
||||
## 4. Scope Boundaries (Phase 1) and Non-Goals
|
||||
|
||||
### In scope for Phase 1
|
||||
|
||||
- A closed, compile-time widget registry in both frontend and backend.
|
||||
- Five source types:
|
||||
1. `jellyfin` — activity/counts (reuses existing `useActivity` / counts data).
|
||||
2. `backups` — backup summary (reuses `BackupDashboardWidget` logic).
|
||||
3. `grafana` — deep-link to a Grafana dashboard or panel.
|
||||
4. `prometheus` — instant query result rendered as a metric or spark value.
|
||||
5. `ssh_task` — output of a saved task (reuses saved task registry and `run_task`).
|
||||
- Optional `static` text/markdown widget to dog-food the configuration UI.
|
||||
- Global dashboard widget config persisted in SQLite and editable by any authenticated user.
|
||||
- Addon pages rendered as custom React pages under `/addons/{addon_id}`; Grafana widgets deep-link to Grafana instead of embedding.
|
||||
- Stacked `SectionCard` layout; no grid, drag, or resize.
|
||||
|
||||
### Non-goals (explicitly out of scope)
|
||||
|
||||
- Runtime addon discovery or dynamic component loading.
|
||||
- Per-user widget configuration.
|
||||
- Grid/drag/resize layout engine.
|
||||
- Iframe embedding of Grafana or any other external UI.
|
||||
- Public/unauthenticated widget access.
|
||||
- Generic "run any script" widget; only saved tasks from the existing registry are allowed.
|
||||
- Real-time WebSocket updates; polling via TanStack Query refetch intervals is sufficient.
|
||||
|
||||
## 5. High-Level Approach
|
||||
|
||||
### 5.1 Backend
|
||||
|
||||
1. **Data model**
|
||||
- Add a `dashboard_widgets` table in `SettingsStore`:
|
||||
|
||||
```sql
|
||||
CREATE TABLE dashboard_widgets (
|
||||
id TEXT PRIMARY KEY,
|
||||
addon_id TEXT NOT NULL,
|
||||
widget_type TEXT NOT NULL,
|
||||
title TEXT NOT NULL,
|
||||
config_json TEXT NOT NULL,
|
||||
enabled INTEGER NOT NULL DEFAULT 1,
|
||||
sort_order INTEGER NOT NULL DEFAULT 0,
|
||||
created_at INTEGER NOT NULL,
|
||||
updated_at INTEGER NOT NULL
|
||||
);
|
||||
CREATE INDEX idx_dashboard_widgets_sort ON dashboard_widgets(sort_order);
|
||||
```
|
||||
|
||||
- `config_json` stores source-specific settings (e.g., `machine_id`, `dashboard_uid`, `promql`, `task_id`). No secrets are stored here.
|
||||
|
||||
2. **Widget source adapters**
|
||||
- Introduce a small protocol/interface, e.g. `WidgetSource`:
|
||||
|
||||
```python
|
||||
class WidgetSource(Protocol):
|
||||
source_type: str
|
||||
async def fetch(self, config: dict[str, Any]) -> dict[str, Any]: ...
|
||||
```
|
||||
|
||||
- Implement one adapter per source type. Adapters reuse existing dependency-injection helpers (`get_jellyfin_client`, `get_ssh_client`, saved task registry, Grafana/Prometheus URLs from `get_settings()`).
|
||||
|
||||
3. **API surface**
|
||||
- `GET /api/widgets/sources` — list available source types.
|
||||
- `GET /api/widgets/types` — list built-in widget types per addon.
|
||||
- `GET /api/widgets/instances` — persisted widget instances.
|
||||
- `POST /api/widgets/instances` — create instance.
|
||||
- `PUT /api/widgets/instances/{id}` — update instance.
|
||||
- `DELETE /api/widgets/instances/{id}` — delete instance.
|
||||
- `GET /api/widgets/instances/{id}/data` — fetch data via the source adapter.
|
||||
|
||||
4. **Default data**
|
||||
- On first install, seed `dashboard_widgets` with the existing defaults: Jellyfin activity and Backup summary. Existing dashboards keep their current behavior after upgrade.
|
||||
|
||||
### 5.2 Frontend
|
||||
|
||||
1. **Widget registry**
|
||||
- A static TypeScript map: `widget_type -> { component, defaultConfig, configSchema }`.
|
||||
- Components render inside the existing `SectionCard` container and use `MetricCard`, `Skeleton`, `Alert`, and `Badge` patterns already present in `ObservabilityPage`.
|
||||
|
||||
2. **Dashboard rendering**
|
||||
- `Dashboard.tsx` replaces its three hard-coded sections with a loop over widget instances returned by `useWidgetsInstances()`.
|
||||
- Each widget fetches its own data through `useWidgetData(widgetId, refreshInterval)` with TanStack Query `refetchInterval`.
|
||||
|
||||
3. **Configuration UI**
|
||||
- Add an "Edit dashboard" action that opens a dialog/panel listing widget instances.
|
||||
- Reuse the form patterns from `ShortcutDialog` and `Settings.tsx` for add/edit widget forms.
|
||||
- Source-specific fields are rendered by small config sub-forms registered next to each widget type.
|
||||
|
||||
4. **Addon pages**
|
||||
- Register a wildcard-ish route `/addons/:addonId` in `App.tsx` that renders an `AddonPage` component.
|
||||
- `AddonPage` looks up the addon in a static map and renders its dedicated page component (e.g., `GrafanaAddonPage`).
|
||||
- Sidebar/nav items for addons are added to the existing `navItems` array in Phase 1; dynamic nav is deferred to a future phase.
|
||||
|
||||
### 5.3 Type contracts
|
||||
|
||||
- Add Pydantic models in `backend/src/media_library_viewer_api/models/` for `WidgetInstance`, `WidgetInstanceInput`, `WidgetTypeInfo`, `WidgetDataResponse`.
|
||||
- Add matching TypeScript interfaces in `frontend/src/types/index.ts`.
|
||||
|
||||
## 6. Success Criteria / Acceptance Criteria
|
||||
|
||||
1. A fresh install shows the Jellyfin activity and Backup summary widgets by default.
|
||||
2. An authenticated user can add, edit, enable/disable, delete, and reorder widgets; changes persist across reloads.
|
||||
3. All five Phase 1 source types can be selected and rendered without errors when configured correctly.
|
||||
4. A misconfigured widget fails gracefully: the rest of the dashboard renders, and the widget shows an error state.
|
||||
5. Addon page route `/addons/{addon_id}` renders a custom React page for the selected addon.
|
||||
6. Existing backend tests and frontend typecheck (`npm run build`) continue to pass.
|
||||
7. No secrets are stored in `config_json`.
|
||||
|
||||
## 7. Risks and Mitigations
|
||||
|
||||
| Risk | Mitigation |
|
||||
|------|------------|
|
||||
| Scope creep toward a full grid/layout engine | Document and enforce Phase 1 non-goals; keep stacked `SectionCard` layout. |
|
||||
| Widget source adapters duplicating backend logic | Reuse existing routers/clients via dependency injection rather than reimplementing endpoints. |
|
||||
| Slow SSH-task widgets blocking dashboard renders | Fetch each widget independently; short timeouts; display loading/error states per widget. |
|
||||
| Secrets leaking into widget config | Validate config schema server-side; reject credential fields; rely on machine/SSH key store and env settings. |
|
||||
| Upgrade path breaks existing dashboards | Seed default widget rows on first install only; leave existing shortcuts/sections untouched. |
|
||||
| Review budget overrun (~400 changed lines) | Keep the registry closed and compile-time; avoid generic schema editors; defer dynamic routing. |
|
||||
|
||||
## 8. Future Phases
|
||||
|
||||
1. **Per-user dashboards** — add `user_id` column and UI toggle between global and personal layouts.
|
||||
2. **Runtime addon discovery** — backend serves an addon manifest; frontend lazily loads addon page modules.
|
||||
3. **Grid layout** — optional `react-grid-layout` integration with drag/resize behind a feature flag.
|
||||
4. **Additional sources** — Alertmanager summary, Loki log snippets, custom HTTP endpoints, Jellyseerr requests.
|
||||
5. **Widget templates/export** — import/export widget layouts and shareable presets.
|
||||
+576
@@ -0,0 +1,576 @@
|
||||
# Dashboard Widgets Specification
|
||||
|
||||
> Domain: `dashboard-widgets` · Change: `configurable-dashboard-widgets`
|
||||
> Full spec (no prior canonical spec exists for this domain).
|
||||
|
||||
## Purpose
|
||||
|
||||
Define WHAT must be true after Phase 1 of the configurable dashboard widgets change: the Manage dashboard becomes a persisted, configurable stack of widget instances backed by a closed, compile-time registry. Authenticated users can add, edit, enable/disable, reorder, and remove widgets; widget data is fetched independently; misconfigured widgets fail gracefully; and addon pages render under `/addons/{addon_id}`.
|
||||
|
||||
## Scope Summary
|
||||
|
||||
### In scope
|
||||
|
||||
- Closed compile-time widget/source registries in the backend and frontend.
|
||||
- SQLite persistence of widget instances (`dashboard_widgets` table).
|
||||
- Source adapters for `jellyfin`, `backups`, `grafana`, `prometheus`, and `ssh_task`, plus a `static` text/markdown widget.
|
||||
- REST API for widget instance CRUD and per-instance data fetch.
|
||||
- Dashboard rendering loop in `Dashboard.tsx` using widget instances.
|
||||
- Configuration UI for add/edit/reorder/remove widgets.
|
||||
- Addon page route `/addons/:addonId` with a static addon page registry.
|
||||
- Default widget seeding on first install.
|
||||
|
||||
### Out of scope (reminders)
|
||||
|
||||
- Runtime addon discovery or dynamic component loading.
|
||||
- Per-user widget configuration.
|
||||
- Grid, drag, or resize layout engine.
|
||||
- Iframe embedding of Grafana or any external UI.
|
||||
- Public/unauthenticated widget access.
|
||||
- Generic "run any script" widget; only saved tasks from the existing registry are allowed.
|
||||
- Real-time WebSocket updates.
|
||||
|
||||
## Requirements
|
||||
|
||||
### Requirement: Widget instance persistence
|
||||
|
||||
The backend MUST persist widget instances in a `dashboard_widgets` table with the following columns and invariants:
|
||||
|
||||
- `id` TEXT PRIMARY KEY
|
||||
- `addon_id` TEXT NOT NULL
|
||||
- `widget_type` TEXT NOT NULL
|
||||
- `title` TEXT NOT NULL
|
||||
- `config_json` TEXT NOT NULL (source-specific JSON config)
|
||||
- `enabled` INTEGER NOT NULL DEFAULT 1
|
||||
- `sort_order` INTEGER NOT NULL DEFAULT 0
|
||||
- `created_at` INTEGER NOT NULL
|
||||
- `updated_at` INTEGER NOT NULL
|
||||
|
||||
The table MUST have an index on `sort_order` named `idx_dashboard_widgets_sort`.
|
||||
|
||||
The `SettingsStore` MUST provide CRUD helpers that return plain Python dicts matching the API response shape. `config_json` MUST be stored as JSON text and validated on write.
|
||||
|
||||
#### Scenario: Create and read a widget instance
|
||||
|
||||
- GIVEN an empty `dashboard_widgets` table
|
||||
- WHEN the store creates a widget instance with `addon_id="core"`, `widget_type="static"`, `title="Notes"`, `config_json={"text":"hello"}`, `enabled=true`, `sort_order=1`
|
||||
- THEN `list_widgets()` returns a list containing one item with the same field values
|
||||
- AND `created_at` and `updated_at` are Unix epoch seconds
|
||||
|
||||
#### Scenario: Update enabled and sort_order
|
||||
|
||||
- GIVEN an existing widget instance
|
||||
- WHEN the store updates `enabled` to `false` and `sort_order` to `5`
|
||||
- THEN subsequent reads reflect the new values
|
||||
- AND `updated_at` is greater than or equal to the write time
|
||||
|
||||
#### Scenario: Delete a widget instance
|
||||
|
||||
- GIVEN an existing widget instance
|
||||
- WHEN the store deletes it by `id`
|
||||
- THEN `list_widgets()` no longer returns that instance
|
||||
|
||||
---
|
||||
|
||||
### Requirement: Default widget seeding on first install
|
||||
|
||||
On first install (when `dashboard_widgets` is empty during startup or `ensure_defaults`), the system MUST seed exactly two default widget instances:
|
||||
|
||||
1. `addon_id="core"`, `widget_type="jellyfin"`, `title="Jellyfin activity"`, enabled, sort_order before backups.
|
||||
2. `addon_id="backups"`, `widget_type="backups"`, `title="Backups"`, enabled, sort_order after Jellyfin.
|
||||
|
||||
Existing installations with one or more widget rows MUST NOT be modified by the seeding logic.
|
||||
|
||||
#### Scenario: Fresh install shows default widgets
|
||||
|
||||
- GIVEN a fresh settings database with no `dashboard_widgets` rows
|
||||
- WHEN the backend starts or `ensure_defaults()` runs
|
||||
- THEN `GET /api/widgets/instances` returns exactly the Jellyfin activity and Backups widgets in that order
|
||||
- AND both are enabled
|
||||
|
||||
#### Scenario: Existing install is not re-seeded
|
||||
|
||||
- GIVEN a settings database with at least one `dashboard_widgets` row
|
||||
- WHEN the backend starts
|
||||
- THEN the existing widget rows remain unchanged
|
||||
- AND no new default rows are inserted
|
||||
|
||||
---
|
||||
|
||||
### Requirement: Closed widget and source registries
|
||||
|
||||
The widget system MUST use a closed, compile-time registry. The backend MUST reject any `widget_type` not in the registry and any `source_type` without a registered adapter.
|
||||
|
||||
Phase 1 built-in widget types:
|
||||
|
||||
| `widget_type` | `addon_id` | Source adapter | Purpose |
|
||||
|---|---|---|---|
|
||||
| `jellyfin` | `core` | `jellyfin` | Activity/counts from a Jellyfin machine |
|
||||
| `backups` | `backups` | `backups` | Backup summary stats |
|
||||
| `grafana-link` | `grafana` | `grafana` | Deep-link to a Grafana dashboard or panel |
|
||||
| `prometheus-metric` | `prometheus` | `prometheus` | Instant query rendered as a metric |
|
||||
| `ssh-task` | `ssh-tasks` | `ssh_task` | Output of a saved task |
|
||||
| `static` | `core` | `static` | Plain text/markdown widget |
|
||||
|
||||
#### Scenario: Unknown widget type is rejected
|
||||
|
||||
- GIVEN a `POST /api/widgets/instances` request with `widget_type="unknown"`
|
||||
- WHEN the request is processed
|
||||
- THEN the response status is `422 Unprocessable Entity`
|
||||
- AND the response body contains a validation error naming the unsupported widget type
|
||||
|
||||
#### Scenario: Source registry is fixed
|
||||
|
||||
- GIVEN `GET /api/widgets/sources`
|
||||
- WHEN the endpoint responds
|
||||
- THEN the list contains exactly `jellyfin`, `backups`, `grafana`, `prometheus`, `ssh_task`, and `static`
|
||||
|
||||
---
|
||||
|
||||
### Requirement: Widget config validation
|
||||
|
||||
Each widget type MUST have a JSON config schema. The backend MUST validate `config_json` against the schema on create and update and reject credential fields.
|
||||
|
||||
The following keys are forbidden anywhere in `config_json` (case-insensitive):
|
||||
|
||||
- `password`, `token`, `secret`, `api_key`, `apikey`, `private_key`, `passphrase`, `credential`
|
||||
|
||||
Any value that is a non-empty string and looks like a secret (e.g., starts with `sk-`, `eyJ`, or is longer than 64 random-looking characters) SHOULD be rejected as a defense-in-depth measure.
|
||||
|
||||
#### Scenario: Valid static widget config passes
|
||||
|
||||
- GIVEN a `POST /api/widgets/instances` request with `widget_type="static"` and `config_json={"text":"Hello"}`
|
||||
- WHEN the request is processed
|
||||
- THEN the response status is `200 OK` or `201 Created`
|
||||
- AND the stored `config_json` equals the submitted value
|
||||
|
||||
#### Scenario: Credential field in config is rejected
|
||||
|
||||
- GIVEN a `POST /api/widgets/instances` request with `config_json={"api_key":"abc123"}`
|
||||
- WHEN the request is processed
|
||||
- THEN the response status is `422 Unprocessable Entity`
|
||||
- AND the error message indicates that credential fields are not allowed
|
||||
|
||||
#### Scenario: Jellyfin config requires machine_id
|
||||
|
||||
- GIVEN a `POST` for `widget_type="jellyfin"` with `config_json={}`
|
||||
- WHEN the request is processed
|
||||
- THEN the response status is `422 Unprocessable Entity`
|
||||
- AND the error indicates that `machine_id` is required
|
||||
|
||||
---
|
||||
|
||||
### Requirement: Widget source adapters
|
||||
|
||||
Each source adapter MUST implement a uniform async interface:
|
||||
|
||||
```python
|
||||
class WidgetSource(Protocol):
|
||||
source_type: str
|
||||
async def fetch(self, config: dict[str, Any]) -> dict[str, Any]: ...
|
||||
```
|
||||
|
||||
Adapters MUST reuse existing dependency-injection helpers and MUST NOT reimplement client logic:
|
||||
|
||||
- `jellyfin`: `get_jellyfin_client` + existing `client.sessions()` / counts.
|
||||
- `backups`: `BackupDashboardSummary` building logic from `dashboard.py`.
|
||||
- `grafana`: `get_settings()` Grafana URL; only returns deep-link metadata, never embeds.
|
||||
- `prometheus`: `get_settings()` Prometheus URL; performs an instant query via HTTP.
|
||||
- `ssh_task`: existing saved task registry + `run_task` helper.
|
||||
- `static`: returns the text/markdown from `config_json` unchanged.
|
||||
|
||||
Adapters MUST catch their own exceptions and return an error payload; they MUST NOT raise unhandled exceptions into the endpoint.
|
||||
|
||||
#### Scenario: Jellyfin adapter returns sessions
|
||||
|
||||
- GIVEN a Jellyfin widget configured with a valid `machine_id`
|
||||
- WHEN `GET /api/widgets/instances/{id}/data` is called
|
||||
- THEN the response contains a `data` field with activity rows
|
||||
- AND `error` is null
|
||||
|
||||
#### Scenario: SSH task adapter times out gracefully
|
||||
|
||||
- GIVEN an `ssh-task` widget configured with a slow task
|
||||
- WHEN the adapter exceeds its timeout
|
||||
- THEN it returns `{ "error": "Widget data fetch timed out" }`
|
||||
- AND the HTTP endpoint still responds with `200 OK` carrying the error payload
|
||||
|
||||
---
|
||||
|
||||
### Requirement: API contract
|
||||
|
||||
The backend MUST expose the following endpoints under `/api/widgets`, protected by the existing JWT/API-key auth:
|
||||
|
||||
| Method | Path | Purpose | Success | Error |
|
||||
|---|---|---|---|---|
|
||||
| GET | `/api/widgets/sources` | List source types | `200 OK` + list of strings | 401/403 |
|
||||
| GET | `/api/widgets/types` | List widget types per addon | `200 OK` + `WidgetTypeInfo[]` | 401/403 |
|
||||
| GET | `/api/widgets/instances` | List persisted instances | `200 OK` + `WidgetInstance[]` | 401/403 |
|
||||
| POST | `/api/widgets/instances` | Create instance | `201 Created` + `WidgetInstance` | 400/401/403/422 |
|
||||
| PUT | `/api/widgets/instances/{id}` | Update instance | `200 OK` + `WidgetInstance` | 400/401/403/404/422 |
|
||||
| DELETE | `/api/widgets/instances/{id}` | Delete instance | `200 OK` + `{status:"deleted"}` | 401/403/404 |
|
||||
| GET | `/api/widgets/instances/{id}/data` | Fetch widget data | `200 OK` + `WidgetDataResponse` | 401/403/404/500 |
|
||||
|
||||
`WidgetInstance` response fields (exact names):
|
||||
|
||||
- `id`: string
|
||||
- `addon_id`: string
|
||||
- `widget_type`: string
|
||||
- `title`: string
|
||||
- `config`: object (parsed JSON)
|
||||
- `enabled`: boolean
|
||||
- `sort_order`: number
|
||||
- `created_at`: number
|
||||
- `updated_at`: number
|
||||
|
||||
`WidgetInstanceInput` request fields:
|
||||
|
||||
- `id`: string | null (optional on create)
|
||||
- `addon_id`: string
|
||||
- `widget_type`: string
|
||||
- `title`: string
|
||||
- `config`: object
|
||||
- `enabled`: boolean
|
||||
- `sort_order`: number
|
||||
|
||||
`WidgetTypeInfo` fields:
|
||||
|
||||
- `addon_id`: string
|
||||
- `widget_type`: string
|
||||
- `name`: string
|
||||
- `description`: string
|
||||
- `source_type`: string
|
||||
- `config_schema`: JSON Schema object
|
||||
|
||||
`WidgetDataResponse` fields:
|
||||
|
||||
- `widget_id`: string
|
||||
- `widget_type`: string
|
||||
- `data`: object | null
|
||||
- `error`: string | null
|
||||
- `fetched_at`: number (Unix epoch seconds)
|
||||
|
||||
#### Scenario: Create widget instance via API
|
||||
|
||||
- GIVEN an authenticated `POST /api/widgets/instances` with a valid `WidgetInstanceInput`
|
||||
- WHEN the request is processed
|
||||
- THEN the response status is `201 Created`
|
||||
- AND the response body contains the created `WidgetInstance` with a generated `id`
|
||||
|
||||
#### Scenario: Update nonexistent widget returns 404
|
||||
|
||||
- GIVEN an authenticated `PUT /api/widgets/instances/does-not-exist`
|
||||
- WHEN the request is processed
|
||||
- THEN the response status is `404 Not Found`
|
||||
|
||||
#### Scenario: Data endpoint returns error for misconfigured widget
|
||||
|
||||
- GIVEN a widget whose adapter returns an error payload
|
||||
- WHEN `GET /api/widgets/instances/{id}/data` is called
|
||||
- THEN the response status is `200 OK`
|
||||
- AND `error` is a non-empty string
|
||||
- AND `data` is null
|
||||
|
||||
---
|
||||
|
||||
### Requirement: Type contracts
|
||||
|
||||
The Pydantic models in the backend and the TypeScript interfaces in the frontend MUST use the exact field names listed above.
|
||||
|
||||
Backend Pydantic models MUST live in `backend/src/media_library_viewer_api/models/widgets.py` and MUST include:
|
||||
|
||||
- `WidgetInstance`
|
||||
- `WidgetInstanceInput`
|
||||
- `WidgetTypeInfo`
|
||||
- `WidgetDataResponse`
|
||||
|
||||
Frontend TypeScript interfaces MUST be added to `frontend/src/types/index.ts`:
|
||||
|
||||
- `WidgetInstance`
|
||||
- `WidgetInstanceInput`
|
||||
- `WidgetTypeInfo`
|
||||
- `WidgetDataResponse`
|
||||
- `WidgetSource` (string union of source types)
|
||||
|
||||
#### Scenario: Backend model serializes config as object
|
||||
|
||||
- GIVEN a `WidgetInstance` model initialized from a database row with `config_json='{"text":"x"}'`
|
||||
- WHEN it is serialized with `model_dump()`
|
||||
- THEN `config` is the parsed object `{"text":"x"}`
|
||||
|
||||
#### Scenario: Frontend type matches API response
|
||||
|
||||
- GIVEN the `WidgetInstance` TypeScript interface
|
||||
- WHEN a widget instance payload from `GET /api/widgets/instances` is typed with it
|
||||
- THEN `npm run build` succeeds without type errors
|
||||
|
||||
---
|
||||
|
||||
### Requirement: Dashboard rendering loop
|
||||
|
||||
`frontend/src/pages/Dashboard.tsx` MUST render widget instances returned by `useWidgetInstances()` instead of the three hard-coded sections.
|
||||
|
||||
The dashboard MUST:
|
||||
|
||||
- Query widget instances on mount.
|
||||
- Render only instances with `enabled === true`.
|
||||
- Sort enabled instances by `sort_order` ascending.
|
||||
- Render each widget inside the existing `SectionCard` container.
|
||||
- Pass the widget instance to a registered widget component.
|
||||
- Preserve the existing stacked layout (`flex flex-col gap-4`).
|
||||
- Keep the existing Shortcuts functionality as a widget type or continue to support it as a first-class widget instance (`widget_type="shortcuts"` or equivalent) so that no data is lost.
|
||||
|
||||
#### Scenario: Fresh install rendering
|
||||
|
||||
- GIVEN a fresh install with default widgets
|
||||
- WHEN the Dashboard page loads
|
||||
- THEN it renders the Jellyfin activity widget followed by the Backups widget
|
||||
- AND both fetch their own data independently
|
||||
|
||||
#### Scenario: Disabled widget is hidden
|
||||
|
||||
- GIVEN a widget instance with `enabled=false`
|
||||
- WHEN the Dashboard renders
|
||||
- THEN that widget is not rendered
|
||||
- AND the remaining widgets maintain their sort order
|
||||
|
||||
#### Scenario: Misconfigured widget fails gracefully
|
||||
|
||||
- GIVEN a dashboard with one valid widget and one widget whose data endpoint returns an error
|
||||
- WHEN the Dashboard renders
|
||||
- THEN the valid widget displays normally
|
||||
- AND the failing widget renders an inline `Alert` with the error message
|
||||
- AND the rest of the dashboard is not blocked
|
||||
|
||||
---
|
||||
|
||||
### Requirement: Independent widget data fetching
|
||||
|
||||
Each widget MUST fetch its own data independently via `useWidgetData(widgetId, refreshInterval)`. The hook MUST use TanStack Query with a per-widget `refetchInterval`.
|
||||
|
||||
Default refresh intervals:
|
||||
|
||||
- `jellyfin`: 30 seconds
|
||||
- `backups`: 60 seconds
|
||||
- `grafana`: 0 (no polling; static link)
|
||||
- `prometheus`: 30 seconds
|
||||
- `ssh_task`: 0 (fetch on mount only; heavy)
|
||||
- `static`: 0
|
||||
|
||||
A widget component MUST show a loading state while data is being fetched for the first time and MUST show an error state if `error` is non-null.
|
||||
|
||||
#### Scenario: Jellyfin widget auto-refreshes
|
||||
|
||||
- GIVEN a rendered Jellyfin widget
|
||||
- WHEN 30 seconds elapse
|
||||
- THEN `useWidgetData` refetches the data automatically
|
||||
|
||||
#### Scenario: Grafana widget does not poll
|
||||
|
||||
- GIVEN a rendered Grafana-link widget
|
||||
- WHEN it mounts
|
||||
- THEN it fetches data once to build the deep-link
|
||||
- AND it does not refetch automatically
|
||||
|
||||
---
|
||||
|
||||
### Requirement: Configuration UI
|
||||
|
||||
The Dashboard MUST provide an "Edit dashboard" action that opens a configuration panel or dialog. The panel MUST allow the user to:
|
||||
|
||||
- See all widget instances (enabled and disabled).
|
||||
- Add a new widget by choosing a widget type from the closed registry.
|
||||
- Edit a widget's `title`, `enabled` flag, `sort_order`, and source-specific `config`.
|
||||
- Remove a widget with a confirmation step.
|
||||
- Reorder widgets by changing `sort_order` (simple numeric input or up/down buttons).
|
||||
|
||||
Source-specific config fields MUST be rendered by small sub-forms registered next to each widget type in the frontend registry.
|
||||
|
||||
The UI MUST reuse existing shadcn/ui form patterns (`Dialog`, `Input`, `Label`, `Switch`, `Select`, `Button`, `Alert`).
|
||||
|
||||
#### Scenario: User adds a Grafana-link widget
|
||||
|
||||
- GIVEN the dashboard configuration panel is open
|
||||
- WHEN the user selects widget type `grafana-link`, enters `title="Grafana Overview"`, `config.dashboard_uid="overview"`, and saves
|
||||
- THEN a new widget instance is persisted
|
||||
- AND it appears on the dashboard with a deep-link to Grafana
|
||||
|
||||
#### Scenario: User disables a widget
|
||||
|
||||
- GIVEN the dashboard configuration panel is open and a widget is enabled
|
||||
- WHEN the user toggles its `enabled` switch off and saves
|
||||
- THEN the widget disappears from the dashboard
|
||||
- AND it remains in the instances list with `enabled=false`
|
||||
|
||||
#### Scenario: Reorder widgets
|
||||
|
||||
- GIVEN two widgets with sort_order 0 and 1
|
||||
- WHEN the user swaps their sort_order values and saves
|
||||
- THEN the dashboard re-renders them in the new order
|
||||
|
||||
---
|
||||
|
||||
### Requirement: Addon pages
|
||||
|
||||
The frontend MUST register a route `/addons/:addonId` in `App.tsx`. The `AddonPage` component MUST look up `addonId` in a static addon registry and render the matching page component.
|
||||
|
||||
Phase 1 addon registry MUST include at least:
|
||||
|
||||
- `grafana` — `GrafanaAddonPage`
|
||||
- `prometheus` — `PrometheusAddonPage`
|
||||
- `ssh-tasks` — `SshTasksAddonPage`
|
||||
|
||||
Navigating to an unknown `addonId` MUST render a 404-style message inside the page shell.
|
||||
|
||||
Grafana widgets MUST deep-link to Grafana (using env-configured URL) instead of embedding.
|
||||
|
||||
#### Scenario: Addon page navigation
|
||||
|
||||
- GIVEN the user clicks "Open Grafana addon" from a Grafana widget
|
||||
- WHEN the browser navigates to `/addons/grafana`
|
||||
- THEN the `GrafanaAddonPage` component renders
|
||||
- AND the page shows Grafana deep-links and no iframe
|
||||
|
||||
#### Scenario: Unknown addon page
|
||||
|
||||
- GIVEN a navigation to `/addons/unknown`
|
||||
- WHEN the route resolves
|
||||
- THEN the page renders an `Alert` stating the addon is not found
|
||||
- AND the sidebar and shell remain intact
|
||||
|
||||
---
|
||||
|
||||
## Non-Functional Requirements
|
||||
|
||||
### Requirement: Security — no secrets in widget config
|
||||
|
||||
The system MUST ensure that widget `config_json` never stores secrets. Credential detection MUST be applied both at the Pydantic model level and at the store write level. Backend adapters MUST resolve credentials from the existing machine/SSH-key store or environment settings.
|
||||
|
||||
#### Scenario: Secret-looking value rejected
|
||||
|
||||
- GIVEN a widget config containing `"token": "super-secret-api-token-value"`
|
||||
- WHEN the create/update endpoint processes it
|
||||
- THEN the request is rejected with `422 Unprocessable Entity`
|
||||
|
||||
---
|
||||
|
||||
### Requirement: Performance — independent fetches and timeouts
|
||||
|
||||
Each widget data fetch MUST be independent. A slow or failing adapter MUST NOT block other widgets or the dashboard render. Adapters MUST apply a short timeout:
|
||||
|
||||
- `jellyfin`: 10 seconds
|
||||
- `backups`: 10 seconds
|
||||
- `prometheus`: 10 seconds
|
||||
- `ssh_task`: 30 seconds
|
||||
- `grafana`: 5 seconds
|
||||
- `static`: no fetch
|
||||
|
||||
The dashboard MUST render the widget chrome immediately and show loading skeletons while data loads.
|
||||
|
||||
#### Scenario: Slow widget does not block dashboard
|
||||
|
||||
- GIVEN a dashboard with three widgets, one of which takes 25 seconds
|
||||
- WHEN the dashboard loads
|
||||
- THEN the other two widgets render their data immediately
|
||||
- AND the slow widget shows a loading skeleton until it completes or times out
|
||||
|
||||
---
|
||||
|
||||
### Requirement: Maintainability — closed registry
|
||||
|
||||
The widget and source registries MUST be closed and compile-time. Adding a new widget type or source adapter MUST require a code change in both backend and frontend registries. There MUST be no plugin loading, dynamic imports, or runtime manifests in Phase 1.
|
||||
|
||||
#### Scenario: Registry is discoverable in source
|
||||
|
||||
- GIVEN the source code
|
||||
- WHEN searching for the list of supported widget types
|
||||
- THEN it is found as an explicit map/list in the backend and frontend source files
|
||||
|
||||
---
|
||||
|
||||
## Invariants and Validation Rules
|
||||
|
||||
1. `widget_type` MUST be in the closed registry.
|
||||
2. `addon_id` MUST match the addon registered for the widget type.
|
||||
3. `config_json` MUST be valid JSON and MUST validate against the widget type's JSON schema.
|
||||
4. `config_json` MUST NOT contain keys matching the forbidden credential list.
|
||||
5. `sort_order` MUST be a non-negative integer.
|
||||
6. `enabled` MUST be a boolean.
|
||||
7. The data endpoint for a disabled widget MUST still function if called directly, but the dashboard MUST NOT render it.
|
||||
8. A widget instance's `id` MUST be immutable after creation.
|
||||
9. Source adapters MUST be stateless and MUST NOT persist widget-specific secrets.
|
||||
10. Addon page components MUST NOT embed external iframes.
|
||||
|
||||
## Error Handling Requirements
|
||||
|
||||
| Flow / Endpoint | Expected Error Condition | Response |
|
||||
|---|---|---|
|
||||
| `GET /api/widgets/instances` | Unauthenticated | `401 Unauthorized` |
|
||||
| `POST /api/widgets/instances` | Invalid JSON | `400 Bad Request` |
|
||||
| `POST /api/widgets/instances` | Unknown `widget_type` | `422 Unprocessable Entity` |
|
||||
| `POST /api/widgets/instances` | Config fails schema validation | `422 Unprocessable Entity` |
|
||||
| `POST /api/widgets/instances` | Config contains credential key | `422 Unprocessable Entity` |
|
||||
| `PUT /api/widgets/instances/{id}` | Widget not found | `404 Not Found` |
|
||||
| `PUT /api/widgets/instances/{id}` | ID in path mismatches body | `400 Bad Request` |
|
||||
| `DELETE /api/widgets/instances/{id}` | Widget not found | `404 Not Found` |
|
||||
| `GET /api/widgets/instances/{id}/data` | Widget not found | `404 Not Found` |
|
||||
| `GET /api/widgets/instances/{id}/data` | Adapter raises unhandled exception | `500 Internal Server Error` with a safe message |
|
||||
| `GET /api/widgets/instances/{id}/data` | Adapter returns error payload | `200 OK` with `error` set |
|
||||
| Dashboard render | Widget data hook errors | Inline error state; dashboard continues |
|
||||
| Configuration UI | Network error on save | Inline `Alert`; form remains open |
|
||||
|
||||
## Scenario Catalog
|
||||
|
||||
### Scenario: Fresh install shows default widgets
|
||||
|
||||
- GIVEN a fresh settings database
|
||||
- WHEN the backend starts and the Dashboard page loads
|
||||
- THEN `GET /api/widgets/instances` returns two enabled widgets: Jellyfin activity and Backups
|
||||
- AND the Dashboard renders them in order
|
||||
|
||||
### Scenario: User adds a Grafana-link widget
|
||||
|
||||
- GIVEN the Dashboard configuration panel is open
|
||||
- WHEN the user chooses `grafana-link`, sets `title="Grafana Overview"`, `config.dashboard_uid="overview"`, and saves
|
||||
- THEN `POST /api/widgets/instances` succeeds
|
||||
- AND the new widget appears on the dashboard
|
||||
- AND clicking the widget opens the Grafana dashboard in a new tab
|
||||
|
||||
### Scenario: User disables a widget
|
||||
|
||||
- GIVEN a widget is enabled and visible on the dashboard
|
||||
- WHEN the user opens the configuration panel, toggles the widget off, and saves
|
||||
- THEN `PUT /api/widgets/instances/{id}` returns `enabled=false`
|
||||
- AND the widget is no longer rendered on the dashboard
|
||||
|
||||
### Scenario: Misconfigured widget fails gracefully
|
||||
|
||||
- GIVEN a `prometheus-metric` widget with an invalid `promql` query
|
||||
- WHEN the dashboard renders
|
||||
- THEN the widget shows an error Alert with a message from the adapter
|
||||
- AND all other widgets render normally
|
||||
- AND the dashboard remains scrollable and interactive
|
||||
|
||||
### Scenario: Addon page navigation
|
||||
|
||||
- GIVEN a Grafana widget with a configured dashboard
|
||||
- WHEN the user clicks the addon deep-link
|
||||
- THEN the browser navigates to `/addons/grafana`
|
||||
- AND the `GrafanaAddonPage` renders with relevant deep-links
|
||||
- AND no iframe is present
|
||||
|
||||
## File Targets (Informative)
|
||||
|
||||
- Backend models: `backend/src/media_library_viewer_api/models/widgets.py`
|
||||
- Backend router: `backend/src/media_library_viewer_api/routers/widgets.py`
|
||||
- Backend source adapters: `backend/src/media_library_viewer_api/widgets/*.py`
|
||||
- Backend store: extend `backend/src/media_library_viewer_api/services/settings_store.py`
|
||||
- Backend main: register router in `backend/src/media_library_viewer_api/main.py`
|
||||
- Frontend types: `frontend/src/types/index.ts`
|
||||
- Frontend API client: `frontend/src/api/widgets.ts`
|
||||
- Frontend hooks: `frontend/src/hooks/useWidgets.ts`
|
||||
- Frontend widget registry: `frontend/src/widgets/registry.ts`
|
||||
- Frontend widget components: `frontend/src/widgets/*.tsx`
|
||||
- Frontend dashboard: `frontend/src/pages/Dashboard.tsx`
|
||||
- Frontend addon page: `frontend/src/pages/AddonPage.tsx`
|
||||
- Frontend app routes: `frontend/src/App.tsx`
|
||||
@@ -0,0 +1,270 @@
|
||||
# SDD Tasks: Configurable Dashboard Widgets
|
||||
|
||||
**Change:** `configurable-dashboard-widgets`
|
||||
**Phase:** tasks
|
||||
**Date:** 2026-06-19
|
||||
|
||||
## Review Workload Forecast
|
||||
|
||||
| Field | Value |
|
||||
|-------|-------|
|
||||
| Estimated changed lines | ~1,550–1,650 (sum of four implementation slices) |
|
||||
| 400-line budget risk | High |
|
||||
| Chained PRs recommended | Yes |
|
||||
| Suggested split | PR 1: Backend CRUD + default seeding → PR 2: Backend source adapters + data endpoint → PR 3: Frontend types/API/hooks/registry/components → PR 4: Dashboard loop + config UI + addon pages |
|
||||
| Delivery strategy | ask-on-risk |
|
||||
| Chain strategy | stacked-to-main |
|
||||
|
||||
```text
|
||||
Decision needed before apply: Yes
|
||||
Chained PRs recommended: Yes
|
||||
Chain strategy: stacked-to-main
|
||||
400-line budget risk: High
|
||||
```
|
||||
|
||||
> **Note:** The preflight preference is `single-PR-default`, but the Phase 1 implementation clearly exceeds the ~400 changed-line review budget. The recommended split above keeps every slice independently testable and green. Confirm the chained-PR strategy before moving to `sdd-apply`.
|
||||
|
||||
---
|
||||
|
||||
## Phase 1 Goal
|
||||
|
||||
Replace the hard-coded dashboard sections in `frontend/src/pages/Dashboard.tsx` with a persisted, closed-registry widget system. Backend stores widget instances in SQLite, exposes CRUD + per-widget data endpoints, and provides source adapters for Jellyfin, backups, Grafana links, Prometheus instant queries, saved SSH tasks, and static text. Frontend renders enabled widgets in sort order, fetches data independently, and provides a configuration UI plus `/addons/:addonId` pages.
|
||||
|
||||
---
|
||||
|
||||
## Slice 1: Backend CRUD and default seeding
|
||||
|
||||
**Goal:** Persist widget instances and expose registry metadata + CRUD endpoints. Leave all source adapters and data fetch for Slice 2.
|
||||
|
||||
- [x] **1.1 Create widget Pydantic models**
|
||||
- Files: `backend/src/media_library_viewer_api/models/widgets.py` (new)
|
||||
- Lines: ~70
|
||||
- Dependencies: none
|
||||
- Details: Add `WidgetInstance`, `WidgetInstanceInput`, `WidgetTypeInfo`, `WidgetDataResponse`. Include credential-key validator (`password`, `token`, `secret`, `api_key`, etc.) and secret-looking-value heuristic.
|
||||
|
||||
- [x] **1.2 Create backend widget registry**
|
||||
- Files: `backend/src/media_library_viewer_api/widgets/__init__.py` (new), `backend/src/media_library_viewer_api/widgets/registry.py` (new)
|
||||
- Lines: ~50
|
||||
- Dependencies: 1.1
|
||||
- Details: Define `WIDGET_REGISTRY` mapping `widget_type` → `addon_id`, `name`, `description`, `source_type`, JSON Schema `config_schema` for all six Phase 1 types.
|
||||
|
||||
- [x] **1.3 Implement widgets router (CRUD + metadata)**
|
||||
- Files: `backend/src/media_library_viewer_api/routers/widgets.py` (new)
|
||||
- Lines: ~110
|
||||
- Dependencies: 1.1, 1.2
|
||||
- Details: Implement `GET /api/widgets/sources`, `GET /api/widgets/types`, `GET /api/widgets/instances`, `POST /api/widgets/instances` (201), `PUT /api/widgets/instances/{id}`, `DELETE /api/widgets/instances/{id}`. Validate `widget_type` and `addon_id` against registry; validate config schema; reject credential keys.
|
||||
|
||||
- [x] **1.4 Extend `SettingsStore` for `dashboard_widgets`**
|
||||
- Files: `backend/src/media_library_viewer_api/services/settings_store.py`
|
||||
- Lines: ~90
|
||||
- Dependencies: none
|
||||
- Details: Add table + index `idx_dashboard_widgets_sort`, `_row_to_widget`, `_normalize_widget_payload`, `list_widgets`, `get_widget`, `upsert_widget`, `delete_widget`, and `_seed_dashboard_widgets` (Jellyfin + Backups defaults only when table is empty).
|
||||
|
||||
- [x] **1.5 Register widgets router in `main.py`**
|
||||
- Files: `backend/src/media_library_viewer_api/main.py`
|
||||
- Lines: ~5
|
||||
- Dependencies: 1.3
|
||||
- Details: `app.include_router(widgets_router.router)`; endpoints inherit existing JWT/API-key middleware.
|
||||
|
||||
- [x] **1.6 Add backend tests for registry, CRUD, and seeding**
|
||||
- Files: `backend/tests/test_widgets.py` (new)
|
||||
- Lines: ~75
|
||||
- Dependencies: 1.3, 1.4
|
||||
- Details: Test sources/types lists, create/read/update/delete, unknown widget type → 422, credential key → 422, fresh-store seeding, existing store not re-seeded.
|
||||
|
||||
- [x] **1.7 Verify backend slice**
|
||||
- Run: `cd backend && ruff check . && PYTHONPATH=src pytest tests/test_widgets.py`
|
||||
|
||||
**Slice 1 total:** ~400 changed lines.
|
||||
|
||||
---
|
||||
|
||||
## Slice 2: Backend source adapters and data endpoint
|
||||
|
||||
**Goal:** Fetch widget data through stateless adapters reusing existing DI and clients.
|
||||
|
||||
- [ ] **2.1 Add observability URL settings**
|
||||
- Files: `backend/src/media_library_viewer_api/config.py`
|
||||
- Lines: ~15
|
||||
- Dependencies: none
|
||||
- Details: Add `grafana_url: str = "http://grafana:3000"` and `prometheus_url: str = "http://prometheus:9090"`.
|
||||
|
||||
- [ ] **2.2 Create source adapters**
|
||||
- Files: `backend/src/media_library_viewer_api/widgets/sources.py` (new)
|
||||
- Lines: ~200
|
||||
- Dependencies: 1.2, 2.1
|
||||
- Details: Implement `WidgetSource` protocol + adapters for `jellyfin`, `backups`, `grafana`, `prometheus`, `ssh_task`, `static`. Catch exceptions and return `{"error": "..."}`. Apply per-type timeouts (10 s / 10 s / 5 s / 10 s / 30 s / none).
|
||||
|
||||
- [ ] **2.3 Add per-widget data endpoint**
|
||||
- Files: `backend/src/media_library_viewer_api/routers/widgets.py`
|
||||
- Lines: ~35
|
||||
- Dependencies: 1.3, 2.2
|
||||
- Details: Implement `GET /api/widgets/instances/{id}/data`, returning `WidgetDataResponse` with `widget_id`, `widget_type`, `data`, `error`, `fetched_at`. Unhandled adapter exceptions → 500.
|
||||
|
||||
- [ ] **2.4 Share Jellyfin activity mapping helper**
|
||||
- Files: `backend/src/media_library_viewer_api/routers/dashboard.py`, `backend/src/media_library_viewer_api/domain/dashboard.py` (new)
|
||||
- Lines: ~25
|
||||
- Dependencies: 2.2
|
||||
- Details: Move `_map_sessions_to_activity_rows` to `domain/dashboard.py`; import it from both `routers/dashboard.py` and the Jellyfin adapter.
|
||||
|
||||
- [ ] **2.5 Add backend tests for adapters and data endpoint**
|
||||
- Files: `backend/tests/test_widgets.py`
|
||||
- Lines: ~85
|
||||
- Dependencies: 2.2, 2.3
|
||||
- Details: Test static widget data round-trip, misconfigured jellyfin returns `error` with HTTP 200, SSH task adapter timeout returns error payload, unhandled exception path returns 500.
|
||||
|
||||
- [ ] **2.6 Verify backend slice**
|
||||
- Run: `cd backend && ruff check . && PYTHONPATH=src pytest tests/test_widgets.py`
|
||||
|
||||
**Slice 2 total:** ~360 changed lines.
|
||||
|
||||
---
|
||||
|
||||
## Slice 3: Frontend types, API, hooks, registry, and widget components
|
||||
|
||||
**Goal:** Build the frontend widget runtime: types, API client, hooks, closed registry, and presentational components. No dashboard integration yet.
|
||||
|
||||
- [ ] **3.1 Add TypeScript widget interfaces**
|
||||
- Files: `frontend/src/types/index.ts`
|
||||
- Lines: ~45
|
||||
- Dependencies: none
|
||||
- Details: Add `WidgetInstance`, `WidgetInstanceInput`, `WidgetTypeInfo`, `WidgetDataResponse`, and `WidgetSource` union type with exact field names from the spec.
|
||||
|
||||
- [ ] **3.2 Create widget API client**
|
||||
- Files: `frontend/src/api/widgets.ts` (new)
|
||||
- Lines: ~60
|
||||
- Dependencies: 3.1
|
||||
- Details: Functions for `fetchWidgetSources`, `fetchWidgetTypes`, `fetchWidgetInstances`, `createWidgetInstance`, `updateWidgetInstance`, `deleteWidgetInstance`, `fetchWidgetData`.
|
||||
|
||||
- [ ] **3.3 Create widget TanStack Query hooks**
|
||||
- Files: `frontend/src/hooks/useWidgets.ts` (new)
|
||||
- Lines: ~70
|
||||
- Dependencies: 3.2
|
||||
- Details: `useWidgetInstances`, `useWidgetData(widgetId, refreshInterval)`, `useSaveWidgetInstance`, `useDeleteWidgetInstance`, `useWidgetSources`, `useWidgetTypes`. Use correct per-type `refetchInterval`.
|
||||
|
||||
- [ ] **3.4 Create frontend widget registry**
|
||||
- Files: `frontend/src/widgets/registry.ts` (new)
|
||||
- Lines: ~70
|
||||
- Dependencies: 3.1
|
||||
- Details: Define `WidgetConfigField`, `WidgetDefinition`, `WIDGET_REGISTRY` for all six types, `getWidgetDefinition`, plus `refreshInterval` defaults.
|
||||
|
||||
- [ ] **3.5 Implement widget presentational components**
|
||||
- Files: `frontend/src/widgets/JellyfinWidget.tsx`, `BackupsWidget.tsx`, `GrafanaLinkWidget.tsx`, `PrometheusMetricWidget.tsx`, `SshTaskWidget.tsx`, `StaticWidget.tsx`
|
||||
- Lines: ~150
|
||||
- Dependencies: 3.1, 3.3, 3.4
|
||||
- Details: Each component receives `widget: WidgetInstance` and renders inside the existing card patterns. Grafana widget renders an external deep-link only (no iframe).
|
||||
|
||||
- [ ] **3.6 Add frontend registry unit tests**
|
||||
- Files: `frontend/tests/widgets.test.mjs` (new)
|
||||
- Lines: ~40
|
||||
- Dependencies: 3.4
|
||||
- Details: Assert registry contains exactly six widget types and refresh intervals match spec.
|
||||
|
||||
- [ ] **3.7 Verify frontend slice**
|
||||
- Run: `cd frontend && npm run lint && npm run build`
|
||||
|
||||
**Slice 3 total:** ~435 changed lines.
|
||||
|
||||
---
|
||||
|
||||
## Slice 4: Dashboard loop, configuration UI, and addon pages
|
||||
|
||||
**Goal:** Wire widgets into the dashboard, add configuration UI, and add addon page routes.
|
||||
|
||||
- [ ] **4.1 Refactor `Dashboard.tsx` to render widget instances**
|
||||
- Files: `frontend/src/pages/Dashboard.tsx`
|
||||
- Lines: ~60
|
||||
- Dependencies: Slice 3
|
||||
- Details: Keep the existing Shortcuts section as a hard-coded first-class section (no migration). Add an "Edit dashboard" button. Render enabled widgets sorted by `sort_order` via `<WidgetInstance />`.
|
||||
|
||||
- [ ] **4.2 Create widget instance renderer**
|
||||
- Files: `frontend/src/components/WidgetInstance.tsx` (new)
|
||||
- Lines: ~40
|
||||
- Dependencies: 3.3, 3.4, 3.5
|
||||
- Details: Lookup definition, call `useWidgetData`, show skeleton on first load, render inline `Alert` for `error`, dispatch to registered component.
|
||||
|
||||
- [ ] **4.3 Create widget configuration dialog**
|
||||
- Files: `frontend/src/components/WidgetConfigDialog.tsx` (new)
|
||||
- Lines: ~160
|
||||
- Dependencies: 3.3, 3.4
|
||||
- Details: List all instances with enabled toggle, sort-order input, up/down reorder, edit/delete. Add widget flow selects type then renders source-specific config fields. Use existing shadcn `Dialog`, `Input`, `Label`, `Switch`, `Select`, `Button`, `Alert`.
|
||||
|
||||
- [ ] **4.4 Create addon pages**
|
||||
- Files: `frontend/src/pages/AddonPage.tsx` (new), `frontend/src/addons/GrafanaAddonPage.tsx` (new), `frontend/src/addons/PrometheusAddonPage.tsx` (new), `frontend/src/addons/SshTasksAddonPage.tsx` (new)
|
||||
- Lines: ~130
|
||||
- Dependencies: none
|
||||
- Details: `AddonPage` maps `addonId` to static page components; unknown addon shows an `Alert`. Pages render links/metadata only (no iframes).
|
||||
|
||||
- [ ] **4.5 Register addon route in `App.tsx`**
|
||||
- Files: `frontend/src/App.tsx`
|
||||
- Lines: ~5
|
||||
- Dependencies: 4.4
|
||||
- Details: Add `<Route path="/addons/:addonId" element={<AddonPage />} />` in both the OIDC and non-OIDC route trees.
|
||||
|
||||
- [ ] **4.6 Update `docs/REQUIREMENTS.md`**
|
||||
- Files: `docs/REQUIREMENTS.md`
|
||||
- Lines: ~25
|
||||
- Dependencies: none
|
||||
- Details: Document configurable dashboard widgets, supported source types, security rule (no secrets in config), and addon pages.
|
||||
|
||||
- [ ] **4.7 Verify frontend slice and full build**
|
||||
- Run: `cd frontend && npm run lint && npm run build`
|
||||
|
||||
**Slice 4 total:** ~420 changed lines.
|
||||
|
||||
---
|
||||
|
||||
## Integration and acceptance verification
|
||||
|
||||
- [ ] **5.1 Backend full test run**
|
||||
- Run: `cd backend && PYTHONPATH=src pytest`
|
||||
- Verify existing tests still pass and `test_widgets.py` covers registry, CRUD, seeding, and data fetch.
|
||||
|
||||
- [ ] **5.2 Frontend full build + lint**
|
||||
- Run: `cd frontend && npm run lint && npm run build`
|
||||
- Verify no TypeScript errors and no new lint failures.
|
||||
|
||||
- [ ] **5.3 Manual dev-stack verification**
|
||||
- Run: `docker compose -f docker-compose.dev.yml up --build`
|
||||
- Verify:
|
||||
- Fresh install shows Jellyfin activity + Backups widgets.
|
||||
- Disabled widget is hidden.
|
||||
- Reorder changes dashboard order.
|
||||
- Misconfigured widget shows inline error without blocking dashboard.
|
||||
- `/addons/grafana`, `/addons/prometheus`, `/addons/ssh-tasks` render; unknown addon shows not-found alert.
|
||||
- No widget config can contain `api_key`, `token`, `secret`, etc.
|
||||
|
||||
---
|
||||
|
||||
## Total Phase 1 estimate
|
||||
|
||||
| Slice | Changed lines |
|
||||
|-------|---------------|
|
||||
| Slice 1: Backend CRUD + seeding | ~400 |
|
||||
| Slice 2: Backend adapters + data endpoint | ~360 |
|
||||
| Slice 3: Frontend runtime (types/API/hooks/registry/components) | ~435 |
|
||||
| Slice 4: Dashboard loop + config UI + addon pages | ~420 |
|
||||
| Integration tests/docs | ~25 |
|
||||
| **Total** | **~1,640** |
|
||||
|
||||
This exceeds the ~400-line review budget. Use the four chained PRs above; each slice is independently buildable/testable and leaves the app functional.
|
||||
|
||||
---
|
||||
|
||||
## Tests and docs summary
|
||||
|
||||
- **Backend tests:** New `backend/tests/test_widgets.py` covering registry, CRUD, validation, default seeding, and adapter data fetch. Run with `pytest`.
|
||||
- **Frontend tests:** New `frontend/tests/widgets.test.mjs` covering registry contents and refresh intervals. Run implicitly via `npm run build`/`lint`; add Vitest/MSW tests only if the project adopts Vitest before this change.
|
||||
- **Typecheck/build:** `npm run build` (runs `tsc -b`) must pass for every slice.
|
||||
- **Docs:** Update `docs/REQUIREMENTS.md` to describe the widget system, security rule, and addon pages.
|
||||
|
||||
---
|
||||
|
||||
## Guard lines
|
||||
|
||||
```text
|
||||
Decision needed before apply: Yes
|
||||
Chained PRs recommended: Yes
|
||||
Chain strategy: stacked-to-main
|
||||
400-line budget risk: High
|
||||
```
|
||||
@@ -0,0 +1,101 @@
|
||||
# Plan — decommission-monitoring-poller
|
||||
|
||||
> Status: **DRAFT — awaiting user approval before implementation.**
|
||||
> Scope: a focused backend+frontend decommission, not a full SDD change. Plan-then-implement (user-approved 2026-06-17).
|
||||
> Root cause this addresses: the 2026-06-16/17 observability update externalised metrics to Prometheus+Grafana+Loki+Alertmanager, but the *legacy Manage-side SSH-scraping monitor* (the `MonitoringPoller`, `/monitoring/disk`, `/monitoring/machines/{id}/actions`, and the `monitoring_machine_actions` SQLite table) was never removed. It duplicates the new stack, drains SSH budget every 300s, and feeds nothing (its UI was deleted in `e2ad731`).
|
||||
|
||||
## 1. Problem
|
||||
|
||||
Manage runs a background thread (`MonitoringPoller`) that, every 300s, SSHes into every configured machine, runs `df`, and stores the result in its own SQLite table (`monitoring_machine_actions`, 30-day retention). After the observability update, **Prometheus already scrapes node_exporter on these machines and Grafana already owns the dashboards**. The poller is pure duplication: more SSH sessions, more stale state, a second source of truth for "disk usage," and a SQLite table that nothing reads.
|
||||
|
||||
The alerting side (Alertmanager proxy + `/alerts` + `/alertmanager-status` + `/alertmanager-webhook` + `/prometheus-targets` + `/machines`) already fits the new model and is untouched by this change.
|
||||
|
||||
## 2. Goals / non-goals
|
||||
|
||||
**Goals**
|
||||
|
||||
- Stop the duplicated SSH-scraping of system metrics.
|
||||
- Remove the dead `/disk`, `/poller`, `/machines/{id}/actions` surface and the SQLite history that fed it.
|
||||
- Remove the now-orphaned frontend `DiskSpaceCard` + `DiskSpace` type.
|
||||
- Leave Manage a clean thin-dashboard: Alertmanager alerts + Prometheus target health + Grafana deep-links.
|
||||
|
||||
**Non-goals**
|
||||
|
||||
- Do NOT touch the Alertmanager proxy, `/prometheus-targets`, `/machines`, or `/alertmanager-webhook` — they fit the model.
|
||||
- Do NOT remove the `disk_usage` **job template** in `jobs.py` (user-approved: it is a manual on-demand Actions job, not monitoring).
|
||||
- Do NOT remove `node_exporter_*` fields on `MonitoringMachine` — they configure where Prometheus scrapes; that is correct and stays.
|
||||
- Do NOT introduce a Prometheus query proxy / PromQL reader in this change (that was the alternative the user did not pick).
|
||||
- Do NOT add new features. This is a removal.
|
||||
|
||||
## 3. Exact removal map (verified against source)
|
||||
|
||||
### Backend — delete entirely
|
||||
|
||||
- `backend/src/media_library_viewer_api/services/monitoring_poller.py` (the `MonitoringPoller` class, `PollerConfig`, `_MONITORING_POLLER`, `get_monitoring_poller`).
|
||||
- **Verified sole callers:** `main.py` lifespan, `dependencies.py` wrapper, `routers/monitoring.py:/poller`, `routers/settings.py` (machine save → `poller.start()/kick()`).
|
||||
- `backend/src/media_library_viewer_api/services/monitoring_actions.py` (the whole file: `build_machine_client`, `disk_space`, `summarize_operation_result`, `json_compact`, `run_machine_operation`, `poll_machine_snapshot`).
|
||||
- **Verified:** `run_machine_operation` has exactly 2 callers (`poll_machine_snapshot` here, and `/monitoring/disk`) — both going. `tasks.py` does NOT use it. Nothing else imports the module.
|
||||
- `backend/tests/test_monitoring_actions.py` (36 lines, tests `poll_machine_snapshot`).
|
||||
|
||||
### Backend — edit in place
|
||||
|
||||
- `backend/src/media_library_viewer_api/main.py` lifespan (lines ~48–56): remove `monitoring_poller = get_monitoring_poller()`, `monitoring_poller.start()`, `monitoring_poller.stop()`, and the `get_monitoring_poller` import on line 16. Keep `backup_poller` and `mail_queue` intact.
|
||||
- `backend/src/media_library_viewer_api/dependencies.py`: remove the `MonitoringPoller` import block (lines 24–29) and the `get_monitoring_poller` wrapper (lines 254–256).
|
||||
- `backend/src/media_library_viewer_api/routers/monitoring.py`: remove imports of `disk_space`, `run_machine_operation`, `poll_machine_snapshot`; remove the three endpoints `/poller` (99), `/machines/{machine_id}/actions` (113), `/disk` (127). Keep `/machines`, `/prometheus-targets`, `/alerts`, `/alertmanager-status`, `/alertmanager-webhook`. Also drop the now-unused `_resolve_machine` helper if it becomes unreferenced after `/disk` and `/actions` removal (verify during impl — `/machines` does not use it).
|
||||
- `backend/src/media_library_viewer_api/routers/settings.py` (lines 198–204 and 218–224): remove the `get_monitoring_poller()` + `poller.start()` + `poller.kick()` calls from `post_machine` and `put_machine`. Keep `write_prometheus_targets(store)` (that is the new-model target generation).
|
||||
- `backend/src/media_library_viewer_api/services/settings_store.py`:
|
||||
- Remove `CREATE TABLE IF NOT EXISTS monitoring_machine_actions` (lines ~90) and its two indexes (`idx_monitoring_machine_actions_machine_time`, `idx_monitoring_machine_actions_action_status`, lines ~183–190) from `init_schema`.
|
||||
- Remove methods `record_machine_action` (566), `list_machine_actions` (610), `prune_machine_actions` (638).
|
||||
- Note: existing databases will keep the orphaned `monitoring_machine_actions` table harmlessly (no migration framework here — `init_schema` is `CREATE TABLE IF NOT EXISTS` + ad-hoc `ALTER`). A one-line `DROP TABLE IF EXISTS` can be added to `init_schema` for cleanliness; decide at impl time.
|
||||
- `backend/src/media_library_viewer_api/config.py`: remove `monitoring_poll_interval_seconds` (56), `monitoring_poll_initial_delay_seconds` (57), `monitoring_action_retention_days` (58).
|
||||
|
||||
### Backend — tests to fix
|
||||
|
||||
- `backend/tests/test_api.py`:
|
||||
- `TestMonitoring.test_disk` (line 615) — **remove** (tests `/api/monitoring/disk`).
|
||||
- `TestMonitoring.test_prometheus_targets_empty` and `..._returns_enabled_ssh_node_exporter` — **keep** (test the surviving `/prometheus-targets`).
|
||||
- `TestSettingsMachines` — **keep** but verify they still pass after the `poller` calls are removed from `post/put_machine`.
|
||||
- `TestAlertmanager` — **keep** (untouched).
|
||||
- The `disk_usage` reference at line 576/586 is the **Jobs** test (`/api/jobs/run`), NOT the monitoring poller — **keep** (the job template stays).
|
||||
|
||||
### Frontend — delete
|
||||
|
||||
- `frontend/src/components/DiskSpaceCard.tsx` — **verified orphaned** (only `__tests__/DiskSpaceCard.test.tsx` imports it; no page uses it).
|
||||
- `frontend/src/components/__tests__/DiskSpaceCard.test.tsx`.
|
||||
- `frontend/src/types/index.ts` `DiskSpace` interface (line 279) — remove after confirming no importer (grep shows none outside the type file).
|
||||
|
||||
### Docs
|
||||
|
||||
- `AGENTS.md` line 25 ("starts the mail queue and monitoring poller") → "...starts the mail queue and backup alert poller."
|
||||
- `docs/monitoring-logging-design.md` line 65 (describes the poller) → update or strike the poller paragraph.
|
||||
- `docs/MIGRATION_PLAN.md` line 110 (`/api/monitoring/disk` row) → remove the row.
|
||||
- `docs/REQUIREMENTS.md` → add a note that Manage-side system-metric scraping is retired in favour of the external observability stack.
|
||||
- `docs/superpowers/specs/2026-05-11-backup-monitoring-design.md` is a historical spec; leave as-is (it is an archived design doc).
|
||||
|
||||
## 4. Slice plan (≤400 lines each, build+pytest green per slice)
|
||||
|
||||
1. **Slice 1 — Backend removal (endpoints + poller + actions + store + config).** Delete `monitoring_poller.py`, `monitoring_actions.py`, `test_monitoring_actions.py`; edit `main.py`, `dependencies.py`, `routers/monitoring.py`, `routers/settings.py`, `settings_store.py`, `config.py`; fix `test_api.py` (`test_disk` removed, `TestSettingsMachines` re-checked). Gate: `cd backend && PYTHONPATH=src pytest`.
|
||||
2. **Slice 2 — Frontend orphan removal.** Delete `DiskSpaceCard.tsx` + its test + `DiskSpace` type. Gate: `cd frontend && npm run build && npm run lint && npm test`.
|
||||
3. **Slice 3 — Docs.** `AGENTS.md`, `docs/monitoring-logging-design.md`, `docs/MIGRATION_PLAN.md`, `docs/REQUIREMENTS.md`. Gate: none (docs); commit standalone.
|
||||
|
||||
Estimated total: ~500–700 lines deleted, ~50–100 added (edits). Each slice well under 400.
|
||||
|
||||
## 5. Risks & verification
|
||||
|
||||
- **Hidden caller of `run_machine_operation` / `poll_machine_snapshot`**: mitigated — grep shows exactly the callers listed; re-grep at slice-1 start.
|
||||
- **`TestSettingsMachines` breakage** once `poller.start()/kick()` is removed from `post/put_machine`: those tests mock `write_prometheus_targets` and don't assert on the poller; should pass. If they reference `get_monitoring_poller`, fix by dropping the assertion.
|
||||
- **Orphaned SQLite table on existing DBs**: harmless (empty, unused). Optional `DROP TABLE IF EXISTS monitoring_machine_actions` in `init_schema` for cleanliness.
|
||||
- **No browser smoke**: same caveat as the UI rework; backend covered by pytest.
|
||||
- **`_resolve_machine` in monitoring.py** may become unused after `/disk` + `/actions` removal; remove if so.
|
||||
|
||||
## 6. Acceptance
|
||||
|
||||
- `cd backend && PYTHONPATH=src pytest` green (with `test_disk` + `test_monitoring_actions.py` removed).
|
||||
- `grep -rnE 'MonitoringPoller|poll_machine_snapshot|/monitoring/disk|monitoring_machine_actions|monitoring_poll_interval_seconds|DiskSpaceCard' backend/ frontend/src/` → only historical/docs hits (spec.md archive is fine).
|
||||
- `cd frontend && npm run build && npm run lint && npm test` green.
|
||||
- Docs updated to reflect Manage no longer scrapes its own metrics.
|
||||
|
||||
## 7. Open questions for the user (none blocking, defaults shown)
|
||||
|
||||
- Q1. Existing DBs' orphaned `monitoring_machine_actions` table — (a) add `DROP TABLE IF EXISTS` to `init_schema` for a clean slate [default], or (b) leave it harmless?
|
||||
- Q2. Commit/PR mechanics — same as the UI rework (commit per slice, no push until you say)?
|
||||
@@ -0,0 +1,119 @@
|
||||
# Apply Progress: Runtime Service Registry
|
||||
|
||||
**Change:** `service-registry`
|
||||
**Apply run:** PRs #7–#10 (Slices 1–4a)
|
||||
**Date:** 2026-06-19
|
||||
|
||||
## Slices 1–3 (MERGED)
|
||||
|
||||
- Slice 1 (#7): backend service foundation — encryption, integrations registry,
|
||||
services + service_task_runs tables, `/api/services*` CRUD.
|
||||
- Slice 2 (#8): backend widget rebind — service_id + widget_kind, ServiceRecord
|
||||
adapters, built-ins, SSH run logging, retired old widget registry.
|
||||
- Slice 3 (#9): frontend services runtime — types/API/hooks, frontend registry,
|
||||
ServicePage, route swap, reconciled widget components + config dialog.
|
||||
|
||||
## Slice 4a — Cleanup + services admin UI + docs (this PR)
|
||||
|
||||
### Completed tasks
|
||||
|
||||
- [x] Removed addon pages (`/addons/:addonId`, `AddonPage.tsx`, `addons/*`) —
|
||||
superseded by service pages.
|
||||
- [x] Removed `grafana_url` / `prometheus_url` from `config.py`, both compose
|
||||
files, `.env.example`, and README. (Frontend `VITE_GRAFANA_URL` /
|
||||
`VITE_PROMETHEUS_URL` deep-link vars retained.)
|
||||
- [x] Added a **Services page** (`/services`) with create/list/delete and a nav
|
||||
entry, so service pages are reachable and services are configurable in the
|
||||
tool itself.
|
||||
- [x] Registered `/services` route in both route trees + sidebar nav.
|
||||
- [x] Updated `docs/REQUIREMENTS.md` (service registry section) and added
|
||||
`CHANGELOG.md` with the breaking-upgrade note.
|
||||
|
||||
### Decision resolved mid-slice
|
||||
|
||||
"Full machine migration" was scoped into **4a (cleanup) + 4b (Jellyfin/Jellyseerr
|
||||
migration)** because removing machine-level Jellyfin/Jellyseerr fields is deeply
|
||||
coupled to the Media/Users/Files pages (load-bearing) and there is no
|
||||
`jellyseerr` service definition yet. 4a ships the safe cleanup + the services
|
||||
admin UI; 4b does the machine-app-field migration as its own reviewable change.
|
||||
|
||||
### Files changed (Slice 4a)
|
||||
|
||||
- Backend: `config.py` (removed grafana_url/prometheus_url).
|
||||
- Compose/env/docs: `docker-compose.yml`, `docker-compose.dev.yml`,
|
||||
`.env.example`, `README.md`, `docs/REQUIREMENTS.md`, `CHANGELOG.md` (new).
|
||||
- Frontend: new `pages/ServicesPage.tsx`; `App.tsx` (routes + nav); removed
|
||||
`pages/AddonPage.tsx`, `addons/*`.
|
||||
|
||||
### Verification (Slice 4a)
|
||||
|
||||
```bash
|
||||
cd backend
|
||||
.venv/bin/ruff check . # clean
|
||||
PYTHONPATH=src .venv/bin/python -m pytest # 222 passed
|
||||
cd ../frontend
|
||||
npm run lint # 0 errors
|
||||
npm run build # success
|
||||
npm run test # 70 passed
|
||||
```
|
||||
|
||||
## Slice 4b — Jellyfin/Jellyseerr → services migration (in progress)
|
||||
|
||||
### Completed (backend, this PR)
|
||||
|
||||
- [x] Added `jellyseerr` service definition (`integrations/jellyseerr.py`) and
|
||||
registered it (6 service types total).
|
||||
- [x] Added `user_id` to the Jellyfin service config.
|
||||
- [x] `dependencies.py`: new `_request_jellyfin_service_id` + `_service_record`
|
||||
(decrypt-on-read). Rewrote `get_jellyfin_client`, `get_jellyseerr_client`,
|
||||
and `get_user_id` to resolve against the service registry via the
|
||||
`jellyfin_service_id` query param (first enabled instance as fallback).
|
||||
- [x] SSH/Files transport (`get_ssh_client`) unchanged — still uses
|
||||
`machine_id`.
|
||||
- [x] Updated service-registry tests for 6 types.
|
||||
|
||||
### Selection model (decided)
|
||||
|
||||
Split query params: `?jellyfin_service_id=` selects the Jellyfin/Jellyseerr
|
||||
instance; `?machine_id=` selects SSH/Files transport. Pages that need both pass
|
||||
both.
|
||||
|
||||
### Remaining (frontend, next PR)
|
||||
|
||||
- Thread `jellyfinServiceId` through Media / Applications / Dashboard / Users:
|
||||
list `jellyfin` service instances instead of `useMonitoringSettings()`
|
||||
Jellyfin machines; pass `jellyfin_service_id` to Jellyfin API calls.
|
||||
- Files page keeps `machine_id`.
|
||||
- Settings UI: remove machine-level Jellyfin/Jellyseerr fields.
|
||||
- Remove machine app fields from `settings_store.py` + `routers/settings.py`
|
||||
once the UI no longer writes them.
|
||||
|
||||
### Frontend half (this PR)
|
||||
|
||||
- [x] `api/client.ts`: Jellyfin-backed calls (`fetchCounts`, `fetchLibraries`,
|
||||
`fetchActivity`, `fetchUsers`, Media status/build/stop/force-stop, and
|
||||
`queryMedia`) now send `jellyfin_service_id` instead of `machine_id`.
|
||||
- [x] `hooks/useDashboard.ts`, `hooks/useUsers.ts`, `hooks/useMedia.ts`: renamed
|
||||
the selector param to `jellyfinServiceId`.
|
||||
- [x] `pages/Media.tsx` + `pages/Applications.tsx`: select a `jellyfin` service
|
||||
instance via `useServiceInstances("jellyfin")` and persist
|
||||
`jellyfin_service_id` in the URL.
|
||||
- [x] Dashboard (widget-based) and Users (default-instance) need no selector
|
||||
change.
|
||||
- [x] Updated Applications + Media tests for the new hook/param.
|
||||
|
||||
### Deferred (explicit follow-up)
|
||||
|
||||
- Remove machine-level Jellyfin/Jellyseerr fields from `settings_store.py`,
|
||||
`routers/settings.py`, and the Settings UI. Low urgency now that the runtime
|
||||
reads from services; the machine fields are simply unused for Jellyfin.
|
||||
|
||||
### Verification (backend half)
|
||||
|
||||
```bash
|
||||
cd backend
|
||||
.venv/bin/ruff check . # clean
|
||||
PYTHONPATH=src .venv/bin/python -m pytest # 222 passed
|
||||
cd ../frontend
|
||||
npm run lint && npm run build && npm run test # green (unchanged)
|
||||
```
|
||||
@@ -0,0 +1,420 @@
|
||||
# Design: Runtime Service Registry
|
||||
|
||||
**Change:** `service-registry`
|
||||
**Phase:** design
|
||||
**Date:** 2026-06-19
|
||||
|
||||
## 1. Architecture overview
|
||||
|
||||
```
|
||||
┌────────────────────────────────────────────────────────────────────┐
|
||||
│ Browser │
|
||||
│ /services/:type/:id ─► ServicePage ─► frontend SERVICE_REGISTRY
|
||||
│ Dashboard ─► WidgetInstance ─► widget component │
|
||||
└────────────────────────────────────────────────────────────────────┘
|
||||
│
|
||||
▼
|
||||
┌────────────────────────────────────────────────────────────────────┐
|
||||
│ FastAPI /api/services + /api/widgets │
|
||||
│ CRUD service instances · registry metadata · widget data │
|
||||
└────────────────────────────────────────────────────────────────────┘
|
||||
│
|
||||
┌──────────────────────────┼───────────────────────────┐
|
||||
▼ ▼ ▼
|
||||
ServiceStore (SQLite) integrations/ definitions source adapters
|
||||
services table (Pydantic, closed registry) (resolve service
|
||||
dashboard_widgets table grafana/prometheus/jellyfin/ → decrypt → call)
|
||||
nextcloud/ssh_tasks
|
||||
```
|
||||
|
||||
Two closed, compile-time registries cooperate:
|
||||
|
||||
- **`integrations.registry.SERVICE_DEFINITIONS`** maps `service_type → ServiceDefinition`.
|
||||
Each definition declares config schema, secret fields, and widget kinds.
|
||||
- The widget types available to the dashboard are **derived** from
|
||||
`SERVICE_DEFINITIONS` at startup, not hand-maintained.
|
||||
|
||||
## 2. Backend data model
|
||||
|
||||
### 2.1 New `services` table
|
||||
|
||||
Extend `SettingsStore.init_schema()`:
|
||||
|
||||
```sql
|
||||
CREATE TABLE IF NOT EXISTS services (
|
||||
id TEXT PRIMARY KEY,
|
||||
service_type TEXT NOT NULL,
|
||||
name TEXT NOT NULL,
|
||||
config_json TEXT NOT NULL DEFAULT '{}',
|
||||
secrets_json TEXT NOT NULL DEFAULT '{}', -- encrypted blob (Fernet)
|
||||
enabled INTEGER NOT NULL DEFAULT 1,
|
||||
created_at INTEGER NOT NULL,
|
||||
updated_at INTEGER NOT NULL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_services_type ON services(service_type);
|
||||
```
|
||||
|
||||
- `config_json` — non-secret config validated against the service definition's
|
||||
`config_schema`.
|
||||
- `secrets_json` — a JSON object of `{field_name: ciphertext}` produced by the
|
||||
encryption helper. Never returned to the client in plaintext; only the boolean
|
||||
"is set" flags are surfaced.
|
||||
|
||||
### 2.2 `dashboard_widgets` schema change
|
||||
|
||||
The existing table gains two columns and loses the global meaning of `widget_type`:
|
||||
|
||||
```sql
|
||||
ALTER TABLE dashboard_widgets ADD COLUMN service_id TEXT;
|
||||
ALTER TABLE dashboard_widgets ADD COLUMN widget_kind TEXT;
|
||||
```
|
||||
|
||||
- `widget_kind` is the kind declared by the service definition (e.g. `"link"`,
|
||||
`"metric"`, `"activity"`).
|
||||
- `service_id` references `services.id`.
|
||||
- `widget_type` is retained temporarily as `"{service_type}.{widget_kind}"` for
|
||||
backwards-compatible reads during the transition, then dropped in the final slice.
|
||||
- The old `addon_id` column is dropped; addon identity is now `service_type`.
|
||||
|
||||
## 3. Service definitions (Pydantic, in repo)
|
||||
|
||||
New package: `backend/src/media_library_viewer_api/integrations/`
|
||||
(chosen to avoid collision with the existing `services/` infra package).
|
||||
|
||||
### 3.1 Base classes — `integrations/base.py`
|
||||
|
||||
```python
|
||||
from typing import Any, ClassVar
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
class SecretField(BaseModel):
|
||||
key: str
|
||||
label: str
|
||||
required: bool = False
|
||||
helper: str | None = None
|
||||
|
||||
class WidgetKind(BaseModel):
|
||||
kind: str # e.g. "link", "metric", "activity"
|
||||
name: str
|
||||
description: str
|
||||
config_schema: dict[str, Any] # JSON schema for widget config
|
||||
default_config: dict[str, Any] = {}
|
||||
refresh_interval_ms: int = 0
|
||||
|
||||
class ServiceConfigBase(BaseModel):
|
||||
"""Subclass per service to define non-secret config fields."""
|
||||
|
||||
class ServiceDefinition(BaseModel):
|
||||
service_type: ClassVar[str]
|
||||
name: ClassVar[str]
|
||||
description: ClassVar[str]
|
||||
config_schema: ClassVar[dict[str, Any]]
|
||||
secret_fields: ClassVar[list[SecretField]]
|
||||
widget_kinds: ClassVar[list[WidgetKind]]
|
||||
|
||||
# Adapters are referenced by dotted path or registered separately;
|
||||
# see §4. The definition itself stays a pure data/schema object.
|
||||
```
|
||||
|
||||
### 3.2 Example — `integrations/grafana.py`
|
||||
|
||||
```python
|
||||
class GrafanaConfig(ServiceConfigBase):
|
||||
base_url: str = Field(..., description="Grafana base URL, e.g. https://grafana.example.com")
|
||||
|
||||
GRAFANA_DEFINITION = ServiceDefinition(
|
||||
service_type="grafana",
|
||||
name="Grafana",
|
||||
description="Dashboards, metrics, and logs.",
|
||||
config_schema=GrafanaConfig.model_json_schema(),
|
||||
secret_fields=[SecretField(key="api_key", label="API key", helper="Service account token")],
|
||||
widget_kinds=[
|
||||
WidgetKind(
|
||||
kind="link",
|
||||
name="Dashboard link",
|
||||
description="Deep-link to a Grafana dashboard or panel.",
|
||||
config_schema={
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"dashboard_uid": {"type": "string"},
|
||||
"panel_id": {"type": "integer"},
|
||||
},
|
||||
"required": ["dashboard_uid"],
|
||||
},
|
||||
default_config={"dashboard_uid": ""},
|
||||
refresh_interval_ms=0,
|
||||
),
|
||||
],
|
||||
)
|
||||
```
|
||||
|
||||
Other definition modules follow the same shape: `prometheus.py`, `jellyfin.py`,
|
||||
`nextcloud.py`, `ssh_tasks.py`.
|
||||
|
||||
### 3.3 Registry — `integrations/registry.py`
|
||||
|
||||
```python
|
||||
SERVICE_DEFINITIONS: dict[str, ServiceDefinition] = {
|
||||
"grafana": GRAFANA_DEFINITION,
|
||||
"prometheus": PROMETHEUS_DEFINITION,
|
||||
"jellyfin": JELLYFIN_DEFINITION,
|
||||
"nextcloud": NEXTCLOUD_DEFINITION,
|
||||
"ssh_tasks": SSH_TASKS_DEFINITION,
|
||||
}
|
||||
|
||||
def list_service_types() -> list[str]: ...
|
||||
def get_service_definition(service_type: str) -> ServiceDefinition | None: ...
|
||||
def get_widget_kind(service_type: str, widget_kind: str) -> WidgetKind | None: ...
|
||||
```
|
||||
|
||||
The closed `widgets/registry.py` from Phase 1 is **retired**; its metadata is now derived
|
||||
from `SERVICE_DEFINITIONS`.
|
||||
|
||||
## 4. Source adapters
|
||||
|
||||
`widgets/sources.py` is refactored so each adapter resolves a **service instance** rather
|
||||
than reading `get_settings()`:
|
||||
|
||||
```python
|
||||
class WidgetSource(Protocol):
|
||||
async def fetch(
|
||||
self,
|
||||
service: ServiceRecord, # config + decrypted secrets
|
||||
widget_kind: str,
|
||||
config: dict[str, Any],
|
||||
) -> dict[str, Any]: ...
|
||||
```
|
||||
|
||||
- `ServiceRecord` is a runtime object built by `ServiceStore` carrying the decrypted
|
||||
secret dict in memory for the duration of the fetch.
|
||||
- `SOURCE_ADAPTERS` is keyed by `service_type`.
|
||||
- The data endpoint loads the widget's `service_id`, builds the `ServiceRecord`, then
|
||||
calls `adapter.fetch(service, widget_kind, widget_config)`.
|
||||
|
||||
## 5. Encryption — `services/secrets.py`
|
||||
|
||||
```python
|
||||
from cryptography.fernet import Fernet, InvalidToken
|
||||
|
||||
def get_encryption_key() -> bytes:
|
||||
raw = os.environ.get("MANAGE_ENCRYPTION_KEY")
|
||||
if not raw:
|
||||
raise RuntimeError("MANAGE_ENCRYPTION_KEY is required")
|
||||
return raw.encode()
|
||||
|
||||
def encrypt_secrets(values: dict[str, str]) -> dict[str, str]: ...
|
||||
def decrypt_secrets(blob: dict[str, str]) -> dict[str, str]: ...
|
||||
```
|
||||
|
||||
- `cryptography.fernet.Fernet` (already a transitive dependency to verify).
|
||||
- Startup validation: `validate_auth_settings` is extended to require
|
||||
`MANAGE_ENCRYPTION_KEY` and to reject an obviously invalid key.
|
||||
- Secrets are encrypted field-by-field so the "which secrets are set" metadata is cheap
|
||||
to compute without decrypting.
|
||||
|
||||
## 6. REST API
|
||||
|
||||
### Services
|
||||
|
||||
| Method | Path | Handler |
|
||||
|--------|------|---------|
|
||||
| GET | `/api/services/types` | List service definitions (metadata + config schema + widget kinds). |
|
||||
| GET | `/api/services` | List service instances (no plaintext secrets; only "set" flags). |
|
||||
| POST | `/api/services` | Create instance (validates type, config, secret schema). |
|
||||
| PUT | `/api/services/{id}` | Update instance. |
|
||||
| DELETE | `/api/services/{id}` | Delete instance; **cascade-deletes** widgets referencing it in the same transaction. |
|
||||
|
||||
### Widgets (unchanged paths, new semantics)
|
||||
|
||||
| Method | Path | Handler |
|
||||
|--------|------|---------|
|
||||
| GET | `/api/widgets/instances` | List widgets; each carries `service_id`, `widget_kind`. |
|
||||
| POST/PUT/DELETE | `/api/widgets/instances/{id}` | CRUD; validation uses service definition's widget schema. |
|
||||
| GET | `/api/widgets/instances/{id}/data` | Resolve service → adapter → fetch. |
|
||||
|
||||
`GET /api/widgets/types` and `/api/widgets/sources` are removed; widget metadata is
|
||||
served via `/api/services/types` (widget kinds under each service).
|
||||
|
||||
## 7. Frontend
|
||||
|
||||
### 7.1 New `frontend/src/integrations/registry.ts`
|
||||
|
||||
Closed frontend registry mirroring the backend: `serviceType → ServiceDefinition`
|
||||
(config fields, secret fields with `secret: true`, widget kinds, default refresh
|
||||
intervals, and a `component` for the service page).
|
||||
|
||||
### 7.2 Service pages
|
||||
|
||||
- Route: `/services/:serviceType/:serviceId` (replaces `/addons/:addonId`).
|
||||
- `ServicePage` looks up the definition and renders the service-specific component,
|
||||
a config editor, and the list of widget kinds that can be added to the dashboard.
|
||||
- `App.tsx` removes the `/addons/:addonId` route; old addon URLs redirect to the
|
||||
default service of that type (or a not-found alert).
|
||||
|
||||
### 7.3 Dashboard config dialog
|
||||
|
||||
- "Add widget" flow becomes: **pick service → pick widget kind → configure**.
|
||||
- The widget card shows the parent service name.
|
||||
|
||||
### 7.4 Types / API / hooks
|
||||
|
||||
- `frontend/src/api/services.ts` + `hooks/useServices.ts` for the services API.
|
||||
- `frontend/src/types/index.ts` gains `ServiceInstance`, `ServiceInstanceInput`,
|
||||
`ServiceTypeInfo`, `ServiceWidgetKind`.
|
||||
|
||||
## 8. Migration and breaking changes
|
||||
|
||||
- **DB migration on startup:** add `services` table; add `service_id` / `widget_kind`
|
||||
columns to `dashboard_widgets`; drop `addon_id`.
|
||||
- **Machine app fields removed:** `jellyfin_url`, `jellyfin_user_id`, `jellyfin_api_key`,
|
||||
`jellyseerr_url`, `jellyseerr_api_key` are dropped from machine records and the
|
||||
`MonitoringMachine` model. Machines keep SSH + node_exporter transport fields only.
|
||||
- **Env vars removed from `config.py`:** `grafana_url`, `prometheus_url`. (Grafana/Prometheus
|
||||
URLs now live on service records.) `MANAGE_ENCRYPTION_KEY` is added as required.
|
||||
- **Default widget seeding** is removed; a fresh install starts with no widgets. The user
|
||||
adds Jellyfin/Backups widgets after configuring the corresponding services.
|
||||
- **`docs/REQUIREMENTS.md` and `README.md`** updated to describe services, the
|
||||
`MANAGE_ENCRYPTION_KEY` requirement, and the breaking upgrade note.
|
||||
|
||||
## 9. File-level plan
|
||||
|
||||
### Create (backend)
|
||||
|
||||
| File | Purpose |
|
||||
|------|---------|
|
||||
| `integrations/__init__.py` | Package marker. |
|
||||
| `integrations/base.py` | `ServiceDefinition`, `WidgetKind`, `SecretField`, `ServiceConfigBase`. |
|
||||
| `integrations/registry.py` | Closed `SERVICE_DEFINITIONS` + helpers. |
|
||||
| `integrations/grafana.py`, `prometheus.py`, `jellyfin.py`, `nextcloud.py`, `ssh_tasks.py` | One module per service. |
|
||||
| `services/secrets.py` | Fernet encrypt/decrypt + key validation. |
|
||||
| `services/service_store.py` | CRUD for `services` table; decrypt-on-read for adapters. |
|
||||
| `routers/services.py` | `/api/services*` endpoints. |
|
||||
| `models/services.py` | Pydantic request/response models. |
|
||||
|
||||
### Modify (backend)
|
||||
|
||||
| File | Change |
|
||||
|-------|--------|
|
||||
| `services/settings_store.py` | `services` table; widget columns; drop machine app fields. |
|
||||
| `widgets/sources.py` | Adapters take a `ServiceRecord`. |
|
||||
| `widgets/registry.py` | Retired (metadata served by `integrations/registry.py`). |
|
||||
| `routers/widgets.py` | Validate against service widget schema; resolve service on data fetch. |
|
||||
| `config.py` | Remove `grafana_url`/`prometheus_url`; document `MANAGE_ENCRYPTION_KEY` (read in `secrets.py`). |
|
||||
| `main.py` | Register `services_router`; validate encryption key on startup. |
|
||||
| `dependencies.py` | Jellyfin/SSH resolution now goes via services, not machine app fields. |
|
||||
|
||||
### Create (frontend)
|
||||
|
||||
| File | Purpose |
|
||||
|------|---------|
|
||||
| `integrations/registry.ts` | Closed frontend service registry. |
|
||||
| `api/services.ts`, `hooks/useServices.ts` | Services API + hooks. |
|
||||
| `pages/ServicePage.tsx` | Generic `/services/:type/:id` page. |
|
||||
| `integrations/components/*` | Per-service page components. |
|
||||
|
||||
### Modify (frontend)
|
||||
|
||||
| File | Change |
|
||||
|-------|--------|
|
||||
| `App.tsx` | Replace `/addons/:addonId` with `/services/:serviceType/:serviceId`. |
|
||||
| `components/WidgetConfigDialog.tsx` | Service → widget-kind picker. |
|
||||
| `widgets/registry.ts` | Retired; widgets derived from service registry. |
|
||||
| `types/index.ts` | Service types; widget gains `service_id` + `widget_kind`. |
|
||||
| `pages/Settings.tsx` | Remove machine Jellyfin/Jellyseerr fields. |
|
||||
|
||||
## 10. Slice boundaries (chained PRs)
|
||||
|
||||
Each slice keeps `pytest`, `ruff`, `npm run lint`, and `npm run build` green.
|
||||
|
||||
1. **Backend foundation** — encryption helper, `integrations/` base + 5 definitions +
|
||||
registry, `services` table + store, `/api/services*` endpoints, tests. No widget
|
||||
changes yet.
|
||||
2. **Backend widget rebind** — add `service_id`/`widget_kind` to widgets, refactor
|
||||
adapters to take a `ServiceRecord`, retire old `widgets/registry.py`, update data
|
||||
endpoint.
|
||||
3. **Frontend services runtime** — types, API, hooks, `integrations/registry.ts`,
|
||||
service pages, route swap, remove addon pages.
|
||||
4. **Frontend dashboard + settings rework** — service-based widget picker, drop machine
|
||||
app fields from Settings, remove `grafana_url`/`prometheus_url` from config,
|
||||
re-seed behavior, docs (`README.md`, `REQUIREMENTS.md`), changelog breaking-change
|
||||
note.
|
||||
|
||||
Estimated total: ~2,000–2,400 changed lines across four PRs.
|
||||
|
||||
## 11. Decisions resolved
|
||||
|
||||
1. **Deleting a service that still has widgets** → **cascade delete.** The store deletes
|
||||
every `dashboard_widgets` row referencing the service inside the same transaction as
|
||||
the service delete. Simple and safe in SQLite; no 409 pre-check.
|
||||
2. **`MANAGE_ENCRYPTION_KEY` dev default** → **always required.** No fallback, even when
|
||||
`AUTH_ENABLED=false`. Startup fails fast if it is missing or not a valid Fernet key.
|
||||
3. **SSH task runner shape** → **multi-instance, reusable tasks, persisted run history.**
|
||||
See §12 for the full model.
|
||||
|
||||
## 12. SSH task runner model
|
||||
|
||||
The SSH task runner is the most involved service type. Instances absorb the SSH task
|
||||
execution role currently held by machines; tasks stay global and reusable; every
|
||||
invocation is logged.
|
||||
|
||||
### 12.1 Instances
|
||||
|
||||
- `service_type = "ssh_tasks"`.
|
||||
- Each instance is an SSH endpoint: `host`, `port`, `username`, `ssh_key_id`, optional
|
||||
`passphrase`. Connection config lives on the service record; the SSH key itself stays
|
||||
in the existing saved-key registry (referenced by `ssh_key_id`).
|
||||
- Multi-instance by design ("home server", "media box", …).
|
||||
|
||||
### 12.2 Tasks (global, reusable)
|
||||
|
||||
- Saved tasks remain a **global** registry (`name`, `task_type` shell/python, `content`,
|
||||
`enabled`). A task is **not** owned by an instance.
|
||||
- Each task gains `default_service_id` (replaces the old `default_machine_id`) — the
|
||||
instance it targets by default. At run time the caller may override the target
|
||||
instance.
|
||||
- A task can therefore run against any instance; the link is captured per-run.
|
||||
|
||||
### 12.3 Run history (logs)
|
||||
|
||||
A new `service_task_runs` table records every invocation:
|
||||
|
||||
```sql
|
||||
CREATE TABLE IF NOT EXISTS service_task_runs (
|
||||
id TEXT PRIMARY KEY,
|
||||
task_id TEXT NOT NULL,
|
||||
service_id TEXT NOT NULL,
|
||||
status TEXT NOT NULL, -- success | failure | timeout | error
|
||||
exit_status INTEGER,
|
||||
duration_ms INTEGER,
|
||||
stdout_tail TEXT,
|
||||
stderr_tail TEXT,
|
||||
error TEXT,
|
||||
created_at INTEGER NOT NULL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_service_task_runs_service ON service_task_runs(service_id, created_at DESC);
|
||||
CREATE INDEX IF NOT EXISTS idx_service_task_runs_task ON service_task_runs(task_id, created_at DESC);
|
||||
```
|
||||
|
||||
- Populated by the SSH task adapter on every widget data fetch and by the Actions
|
||||
runner on manual runs.
|
||||
- Surfaced on the instance's service page as a log/history list, and on the task detail
|
||||
as recent runs.
|
||||
- Replaces the legacy `saved_task_runs` concept once the Actions page is rebuilt on
|
||||
services (Slice 4 / a follow-up).
|
||||
|
||||
### 12.4 SSH task widget
|
||||
|
||||
Widget config for `ssh_tasks` becomes `{ task_id, service_id? }`:
|
||||
|
||||
- If `service_id` is omitted, the task's `default_service_id` is used.
|
||||
- The adapter loads the task, resolves the instance, runs it, appends a
|
||||
`service_task_runs` row, and returns the trimmed stdout/stderr/exit status.
|
||||
|
||||
### 12.5 Relationship to machines
|
||||
|
||||
- The SSH task execution role moves **out of machines** into `ssh_tasks` instances.
|
||||
- Machines **keep** their role for the File Browser and node_exporter monitoring
|
||||
transport in this change, to avoid also reworking Files/Monitoring here.
|
||||
- Practical consequence: an SSH host used for both files and tasks may be defined twice
|
||||
(once as a machine, once as an ssh_tasks instance) during the transition. Unifying
|
||||
machines under services is an explicit **follow-up change**, not part of this one.
|
||||
@@ -0,0 +1,99 @@
|
||||
# Proposal: Runtime Service Registry
|
||||
|
||||
**Change:** `service-registry`
|
||||
**Phase:** proposal
|
||||
**Date:** 2026-06-19
|
||||
**Status:** awaiting review (design only — no implementation yet)
|
||||
|
||||
## Context and problem
|
||||
|
||||
Phase 1 shipped a configurable dashboard widget system whose service URLs (Grafana,
|
||||
Prometheus) and app credentials (Jellyfin, Jellyseerr) are driven by environment
|
||||
variables and machine-level fields. This has three problems:
|
||||
|
||||
1. **Operators cannot change services without a redeploy.** Adding a second Grafana,
|
||||
pointing Prometheus at a different host, or rotating a Jellyfin API key requires
|
||||
editing env vars and restarting containers.
|
||||
2. **Configuration is split across three places.** Service URLs live in env vars
|
||||
(`GRAFANA_URL`, `PROMETHEUS_URL`), Jellyfin/Jellyseerr live on machine records, and
|
||||
widget instances live in the widget table. There is no single "what is configured"
|
||||
view.
|
||||
3. **The widget registry is decoupled from the services it depends on.** A Grafana
|
||||
widget does not know which Grafana instance it talks to; the widget config holds a
|
||||
`dashboard_uid` while the base URL is global.
|
||||
|
||||
## Proposal
|
||||
|
||||
Introduce a **runtime service registry** persisted in the backend SQLite database:
|
||||
|
||||
- Each **service instance** (e.g. "Production Grafana", "Home Jellyfin") is a DB record
|
||||
carrying its non-secret config and encrypted secret fields.
|
||||
- **Service definitions** live as Python modules with Pydantic classes in the repo. Each
|
||||
definition declares its config schema, its secret fields, and the **widget kinds** it
|
||||
provides (with their own config schemas).
|
||||
- **Service pages** at `/services/:serviceType/:serviceId` render the service-specific UI
|
||||
and list the widgets that service can contribute to the dashboard. These replace the
|
||||
existing addon pages.
|
||||
- **Dashboard widgets** become service-bound: a widget instance references a `service_id`
|
||||
and a `widget_kind` drawn from that service's definition.
|
||||
- Machine records are reduced to **transport only** (SSH + node_exporter); the
|
||||
machine-level Jellyfin/Jellyseerr app fields are removed.
|
||||
|
||||
## Goals
|
||||
|
||||
- One source of truth for every external service the app talks to.
|
||||
- Add/reconfigure/rotate a service from the UI with no redeploy.
|
||||
- Multiple instances per service type (two Grafanas, two Jellyfins).
|
||||
- Centralized, version-controlled service definitions that are easy to extend.
|
||||
- Widgets discoverable per-service and individually addable to the dashboard.
|
||||
- Secrets (API keys / tokens) encrypted at rest.
|
||||
|
||||
## Non-goals
|
||||
|
||||
- **No general-purpose plugin/marketplace system.** Service definitions are closed,
|
||||
compile-time code. Adding a brand-new service still requires a backend deploy and a
|
||||
Python module.
|
||||
- **No OAuth token exchange per service in this change.** Only API keys / tokens are
|
||||
stored (encrypted). OAuth-proxy flows (e.g. Grafana behind Authentik) continue to be
|
||||
handled externally.
|
||||
- **No drag-and-drop dashboard layout, no grid, no per-user dashboards.** This change
|
||||
keeps the existing single stacked-column dashboard model.
|
||||
- **No in-app charting.** The thin-dashboard observability rule still holds; service
|
||||
pages surface deep-links and metadata only.
|
||||
- **No silent data migration.** Machine-level Jellyfin/Jellyseerr config is removed
|
||||
without an automatic converter (see Decisions).
|
||||
|
||||
## Decisions (from grilling)
|
||||
|
||||
| Topic | Decision |
|
||||
|-------|----------|
|
||||
| Scope of services | All current services: Grafana, Prometheus, Jellyfin, Nextcloud, and the SSH task runner. Definitions centralized in repo. |
|
||||
| Definition format | Python modules with Pydantic classes for service config and widget config, combined under each service definition. |
|
||||
| Auth storage | API keys / tokens only, encrypted at rest. |
|
||||
| Encryption key | Single env-provided master key (`MANAGE_ENCRYPTION_KEY`). |
|
||||
| Machine app config | Services **replace** machine-level Jellyfin/Jellyseerr app config. Machines become SSH/monitoring transport only. |
|
||||
| Migration | **Break backwards compatibility.** Users re-enter service config after upgrade; no automatic converter. |
|
||||
| Multi-instance | Yes — multiple service records per service type. |
|
||||
| Addon pages | Replaced by generic service pages at `/services/:serviceType/:serviceId`. |
|
||||
| Widget binding | The service definition **owns** its widget config schemas. Widgets are instantiated from a service instance + a widget kind. |
|
||||
|
||||
## Risks
|
||||
|
||||
- **Breaking upgrade.** Existing deployments lose their Jellyfin config and must re-enter
|
||||
it. We must document this loudly in the changelog and README.
|
||||
- **Encryption key management.** Losing `MANAGE_ENCRYPTION_KEY` makes all stored secrets
|
||||
unrecoverable. Key rotation requires re-encrypting every service record.
|
||||
- **Large surface area.** This change touches backend models, settings store, widget
|
||||
registry, adapters, frontend routing, dashboard config UI, and docs. It must be split
|
||||
into reviewable PRs (see `tasks.md`).
|
||||
- **SSH task runner as a service** needs care: saved tasks already have their own
|
||||
registry. The service record should hold connection/auth; the task registry stays.
|
||||
- **Env vars are not fully eliminated.** The encryption key and core auth/OIDC settings
|
||||
still require env vars; only service URLs/credentials move to the DB.
|
||||
|
||||
## Out of scope for this proposal
|
||||
|
||||
- Automatic migration tooling from machine app config to service records.
|
||||
- Secret rotation UI or key-rotation workflow.
|
||||
- Per-user or multi-dashboard support.
|
||||
- Runtime/hot-reload of service definition files (definitions are loaded at startup).
|
||||
@@ -0,0 +1,212 @@
|
||||
# Tasks: Runtime Service Registry
|
||||
|
||||
**Change:** `service-registry`
|
||||
**Phase:** tasks
|
||||
**Date:** 2026-06-19
|
||||
|
||||
## Review workload forecast
|
||||
|
||||
| Field | Value |
|
||||
|-------|-------|
|
||||
| Estimated changed lines | ~2,000–2,400 |
|
||||
| 400-line budget risk | High |
|
||||
| Chained PRs recommended | Yes (4 PRs) |
|
||||
| Chain strategy | stacked-to-main |
|
||||
|
||||
```text
|
||||
Decision needed before apply: Yes (see design §11 open questions)
|
||||
Chained PRs recommended: Yes
|
||||
Chain strategy: stacked-to-main
|
||||
```
|
||||
|
||||
## Slice 1: Backend service foundation (no widget changes)
|
||||
|
||||
**Goal:** Persist service instances with encrypted secrets and expose CRUD + metadata.
|
||||
|
||||
- [ ] **1.1 Add encryption helper**
|
||||
- Files: `backend/src/media_library_viewer_api/services/secrets.py` (new)
|
||||
- Lines: ~60
|
||||
- Details: Fernet-based `encrypt_secrets` / `decrypt_secrets` / `get_encryption_key`.
|
||||
Raise on missing `MANAGE_ENCRYPTION_KEY`. Add `cryptography` dependency if missing.
|
||||
- [ ] **1.2 Add integrations base classes**
|
||||
- Files: `integrations/__init__.py`, `integrations/base.py` (new)
|
||||
- Lines: ~80
|
||||
- Details: `ServiceDefinition`, `WidgetKind`, `SecretField`, `ServiceConfigBase`.
|
||||
- [ ] **1.3 Add five service definitions + registry**
|
||||
- Files: `integrations/grafana.py`, `prometheus.py`, `jellyfin.py`, `nextcloud.py`,
|
||||
`ssh_tasks.py`, `integrations/registry.py` (new)
|
||||
- Lines: ~220
|
||||
- Details: One `ServiceDefinition` per service with config schema, secret fields, and
|
||||
widget kinds. `SERVICE_DEFINITIONS` + `get_service_definition` /
|
||||
`get_widget_kind` helpers.
|
||||
- [ ] **1.4 Add service store + `services` table**
|
||||
- Files: `services/settings_store.py` (modify), `services/service_store.py` (new)
|
||||
- Lines: ~120
|
||||
- Details: `services` table in `init_schema`; CRUD helpers; decrypt-on-read for
|
||||
adapters; "set" flags for the API without plaintext. **Cascade delete:** removing a
|
||||
service deletes its widgets in the same transaction. Also add the
|
||||
`service_task_runs` table (design §12.3) now so later slices can populate it.
|
||||
- [ ] **1.5 Add service Pydantic models + router**
|
||||
- Files: `models/services.py` (new), `routers/services.py` (new), `main.py` (modify)
|
||||
- Lines: ~110
|
||||
- Details: `GET /api/services/types`, `GET /api/services`, `POST/PUT/DELETE
|
||||
/api/services/{id}`. Validate type, config, and secret schema against the definition.
|
||||
- [ ] **1.6 Validate encryption key on startup**
|
||||
- Files: `auth.py` or `main.py` lifespan (modify)
|
||||
- Lines: ~10
|
||||
- Details: Extend startup validation to require `MANAGE_ENCRYPTION_KEY`.
|
||||
- [ ] **1.7 Add backend tests**
|
||||
- Files: `backend/tests/test_services.py` (new)
|
||||
- Lines: ~140
|
||||
- Details: Registry contents, CRUD round-trip, secret encryption/decryption,
|
||||
unknown service type → 422, missing/invalid encryption key → startup error,
|
||||
cascade-delete removes a service's widgets.
|
||||
- [ ] **1.8 Verify**
|
||||
- Run: `cd backend && .venv/bin/ruff check . && PYTHONPATH=src .venv/bin/python -m pytest`
|
||||
|
||||
**Slice 1 total:** ~720 changed lines (smallest coherent backend foundation).
|
||||
|
||||
## Slice 2: Backend widget rebind to services
|
||||
|
||||
**Goal:** Widgets reference a service instance + widget kind; adapters resolve services.
|
||||
|
||||
- [ ] **2.1 Add widget columns + migrate table**
|
||||
- Files: `services/settings_store.py` (modify)
|
||||
- Lines: ~40
|
||||
- Details: Add `service_id`, `widget_kind` to `dashboard_widgets`; keep `widget_type`
|
||||
as `{service_type}.{kind}` during transition; drop `addon_id`.
|
||||
- [ ] **2.2 Refactor source adapters**
|
||||
- Files: `widgets/sources.py` (modify)
|
||||
- Lines: ~160
|
||||
- Details: Each adapter takes `(service: ServiceRecord, widget_kind, config)`.
|
||||
`SOURCE_ADAPTERS` keyed by `service_type`. Jellyfin/Grafana/Prometheus/SSH adapters
|
||||
resolve connection from the service record. The SSH adapter resolves the task +
|
||||
instance, runs it, and **appends a `service_task_runs` row** (design §12.3).
|
||||
- [ ] **2.3 Retire old widget registry**
|
||||
- Files: `widgets/registry.py` (delete or hollow out), `widgets/__init__.py`
|
||||
- Lines: ~-60
|
||||
- Details: Widget metadata now comes from `integrations/registry.py`.
|
||||
- [ ] **2.4 Update widgets router + models**
|
||||
- Files: `routers/widgets.py`, `models/widgets.py` (modify)
|
||||
- Lines: ~90
|
||||
- Details: Validation uses the service definition's widget schema; data endpoint
|
||||
loads service, builds `ServiceRecord`, calls adapter.
|
||||
- [ ] **2.5 Update widget tests**
|
||||
- Files: `backend/tests/test_widgets.py` (modify)
|
||||
- Lines: ~120
|
||||
- Details: Rewrite adapter/data tests around service instances; cover
|
||||
service-missing, wrong-kind, and encrypted-secret resolution.
|
||||
- [ ] **2.6 Verify**
|
||||
- Run: `cd backend && .venv/bin/ruff check . && PYTHONPATH=src .venv/bin/python -m pytest`
|
||||
|
||||
**Slice 2 total:** ~330 changed lines.
|
||||
|
||||
## Slice 3: Frontend services runtime
|
||||
|
||||
**Goal:** Service types/API/hooks, frontend service registry, service pages, route swap.
|
||||
|
||||
- [ ] **3.1 Add service types**
|
||||
- Files: `frontend/src/types/index.ts` (modify)
|
||||
- Lines: ~50
|
||||
- Details: `ServiceInstance`, `ServiceInstanceInput`, `ServiceTypeInfo`,
|
||||
`ServiceWidgetKind`. Widget gains `service_id`, `widget_kind`.
|
||||
- [ ] **3.2 Add services API + hooks**
|
||||
- Files: `frontend/src/api/services.ts`, `frontend/src/hooks/useServices.ts` (new)
|
||||
- Lines: ~110
|
||||
- Details: Fetch/create/update/delete service instances and types.
|
||||
- [ ] **3.3 Add frontend service registry**
|
||||
- Files: `frontend/src/integrations/registry.ts` (new)
|
||||
- Lines: ~120
|
||||
- Details: Closed registry mirroring backend: config fields, secret fields
|
||||
(`secret: true`), widget kinds, service page components.
|
||||
- [ ] **3.4 Add service page + components**
|
||||
- Files: `frontend/src/pages/ServicePage.tsx`, `frontend/src/integrations/components/*`
|
||||
(new)
|
||||
- Lines: ~180
|
||||
- Details: Generic page dispatches by service type; renders config editor + widget
|
||||
kinds. Add per-service components (Grafana, Prometheus, Jellyfin, Nextcloud,
|
||||
SSH tasks).
|
||||
- [ ] **3.5 Swap routes; remove addon pages**
|
||||
- Files: `frontend/src/App.tsx`, `frontend/src/pages/AddonPage.tsx`,
|
||||
`frontend/src/addons/*` (modify/delete)
|
||||
- Lines: ~-40 net
|
||||
- Details: `/services/:serviceType/:serviceId`; redirect old `/addons/*` to the
|
||||
default service of that type.
|
||||
- [ ] **3.6 Add frontend registry test**
|
||||
- Files: `frontend/src/integrations/registry.test.ts` (new)
|
||||
- Lines: ~40
|
||||
- Details: Assert all five service types and their widget kinds.
|
||||
- [ ] **3.7 Verify**
|
||||
- Run: `cd frontend && npm run lint && npm run build && npm run test -- src/integrations/registry.test.ts`
|
||||
|
||||
**Slice 3 total:** ~460 changed lines.
|
||||
|
||||
## Slice 4: Dashboard picker, settings rework, cleanup, docs
|
||||
|
||||
**Goal:** End-to-end service-based dashboard; remove legacy machine app config + env vars.
|
||||
|
||||
- [ ] **4.1 Rework widget config dialog**
|
||||
- Files: `frontend/src/components/WidgetConfigDialog.tsx` (modify)
|
||||
- Lines: ~120
|
||||
- Details: "Add widget" = pick service → pick widget kind → configure. Widget cards
|
||||
show parent service name.
|
||||
- [ ] **4.2 Update widget components to service model**
|
||||
- Files: `frontend/src/widgets/*` (modify)
|
||||
- Lines: ~120
|
||||
- Details: Components read `widget_kind`; data shapes unchanged but sourced from the
|
||||
service adapter. SSH task widget shows last run status from `service_task_runs`.
|
||||
- [ ] **4.3 Remove machine Jellyfin/Jellyseerr fields**
|
||||
- Files: `frontend/src/pages/Settings.tsx`, `frontend/src/types/index.ts`
|
||||
(modify)
|
||||
- Lines: ~-60
|
||||
- Details: Machines are SSH/monitoring transport only.
|
||||
- [ ] **4.4 Remove grafana_url / prometheus_url from backend config**
|
||||
- Files: `backend/src/media_library_viewer_api/config.py`,
|
||||
`docker-compose.yml`, `docker-compose.dev.yml`, `.env.example`
|
||||
- Lines: ~-10
|
||||
- Details: URLs now live on service records. Add `MANAGE_ENCRYPTION_KEY` to compose
|
||||
- `.env.example`.
|
||||
- [ ] **4.5 Stop default widget seeding**
|
||||
- Files: `services/settings_store.py` (modify)
|
||||
- Lines: ~-20
|
||||
- Details: Fresh installs start with no widgets; user adds them after configuring
|
||||
services.
|
||||
- [ ] **4.6 Docs + changelog**
|
||||
- Files: `docs/REQUIREMENTS.md`, `README.md`, `docs/CHANGELOG.md` (new or modify)
|
||||
- Lines: ~80
|
||||
- Details: Service registry section; `MANAGE_ENCRYPTION_KEY` requirement; breaking
|
||||
upgrade note (re-enter Jellyfin config).
|
||||
- [ ] **4.7 Verify full stack**
|
||||
- Run: backend `ruff` + `pytest`; frontend `lint` + `build` + `test`.
|
||||
|
||||
**Slice 4 total:** ~330 changed lines.
|
||||
|
||||
## Integration and acceptance
|
||||
|
||||
- [ ] **5.1 Backend full test run** — `PYTHONPATH=src pytest`, all green.
|
||||
- [ ] **5.2 Frontend full build/lint/test** — `npm run lint && npm run build && npm run test`.
|
||||
- [ ] **5.3 Manual dev-stack check** — `docker compose -f docker-compose.dev.yml up --build`:
|
||||
- Create a Grafana service from the UI; verify the dashboard link widget works.
|
||||
- Create a Jellyfin service; verify the activity widget resolves it.
|
||||
- Delete a service with widgets → widgets are cascade-deleted and the service is gone.
|
||||
- Restart the stack; secrets remain usable (key stable).
|
||||
- Missing `MANAGE_ENCRYPTION_KEY` → backend refuses to start.
|
||||
- SSH task runner: define two instances, run the same reusable task against each,
|
||||
and see both runs in the instance's history log.
|
||||
|
||||
## Guards
|
||||
|
||||
```text
|
||||
Decision needed before apply: No (design §11 resolved)
|
||||
Chained PRs recommended: Yes
|
||||
Chain strategy: stacked-to-main
|
||||
400-line budget risk: High
|
||||
```
|
||||
|
||||
## Explicit follow-ups (out of scope for this change)
|
||||
|
||||
- Rebuild the Actions page UI on top of services (global reusable tasks +
|
||||
`default_service_id`), replacing the current machine-based saved-task runner.
|
||||
- Unify machines under services so an SSH host is defined once (today machines still
|
||||
own File Browser + node_exporter transport; see design §12.5).
|
||||
- Key rotation / re-encrypt workflow for `MANAGE_ENCRYPTION_KEY`.
|
||||
@@ -0,0 +1,177 @@
|
||||
# Design: Unify Saved Tasks on SSH Services
|
||||
|
||||
**Change:** `unify-tasks-on-services`
|
||||
**Phase:** design
|
||||
**Date:** 2026-06-19
|
||||
|
||||
## 1. Architecture overview
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────┐
|
||||
│ saved_tasks (global, reusable) │
|
||||
│ default_service_id → ssh_tasks │
|
||||
└─────────────────────────────────────┘
|
||||
│ │
|
||||
Actions page │ │ SSH task widget
|
||||
▼ ▼
|
||||
┌─────────────────────────────────────┐
|
||||
│ run_saved_task(store, task, svc) │ ← shared helper
|
||||
│ build client → run → log │
|
||||
└─────────────────────────────────────┘
|
||||
│
|
||||
▼
|
||||
┌─────────────────────────────────────┐
|
||||
│ service_task_runs (one history) │
|
||||
└─────────────────────────────────────┘
|
||||
```
|
||||
|
||||
Both the Actions runner and the SSH task widget call one shared helper, so there
|
||||
is a single execution path and a single history table.
|
||||
|
||||
## 2. Shared execution helper
|
||||
|
||||
New: `backend/src/media_library_viewer_api/services/task_runner.py`
|
||||
|
||||
```python
|
||||
from dataclasses import dataclass
|
||||
from media_library_viewer_api.services.settings_store import SettingsStore
|
||||
from media_library_viewer_api.widgets.sources import ServiceRecord, _build_ssh_client
|
||||
|
||||
@dataclass
|
||||
class TaskRunResult:
|
||||
exit_status: int
|
||||
stdout: str
|
||||
stderr: str
|
||||
duration_ms: int
|
||||
status: str # "success" | "failure" | "timeout" | "error"
|
||||
error: str
|
||||
|
||||
def run_saved_task(
|
||||
store: SettingsStore,
|
||||
task: dict,
|
||||
service: ServiceRecord,
|
||||
*,
|
||||
request_id: str = "",
|
||||
) -> TaskRunResult:
|
||||
"""Run a saved task on an ssh_tasks service instance and log it.
|
||||
|
||||
Builds the SSH client from the service record, renders the command (shell or
|
||||
python3 -c), runs it with the service's timeout, appends a service_task_runs
|
||||
row, and returns the result.
|
||||
"""
|
||||
...
|
||||
```
|
||||
|
||||
- The widget adapter (`SshTaskWidgetSource.fetch`) is refactored to call
|
||||
`run_saved_task`, removing its inline copy.
|
||||
- `routers/tasks.py` `run_task` calls `run_saved_task` instead of
|
||||
`_client_for_machine` + `record_task_run`.
|
||||
- `_build_ssh_client` (currently private in `widgets/sources.py`) is promoted to
|
||||
the helper module or a shared location so both callers use it.
|
||||
|
||||
## 3. Data model changes
|
||||
|
||||
### 3.1 `saved_tasks`
|
||||
|
||||
```sql
|
||||
-- default_machine_id replaced by default_service_id
|
||||
ALTER TABLE saved_tasks RENAME COLUMN default_machine_id TO default_service_id;
|
||||
```
|
||||
|
||||
In SQLite (3.25+) `RENAME COLUMN` is supported. The column still stores an id,
|
||||
now pointing at `services.id` (an `ssh_tasks` instance) instead of a machine.
|
||||
|
||||
### 3.2 `saved_task_runs` dropped
|
||||
|
||||
```sql
|
||||
DROP TABLE IF EXISTS saved_task_runs;
|
||||
```
|
||||
|
||||
All history lives in `service_task_runs` (added in the service-registry change).
|
||||
The `record_task_run` / `list_task_runs` methods on `SettingsStore` are removed.
|
||||
|
||||
## 4. Backend API
|
||||
|
||||
### `routers/tasks.py`
|
||||
|
||||
| Method | Path | Change |
|
||||
|--------|------|--------|
|
||||
| GET | `/api/tasks` | Unchanged (task now carries `default_service_id`). |
|
||||
| POST | `/api/tasks` | `TaskInput.default_service_id` replaces `default_machine_id`. |
|
||||
| PUT | `/api/tasks/{id}` | Same field rename. |
|
||||
| DELETE | `/api/tasks/{id}` | Unchanged. |
|
||||
| GET | `/api/tasks/{id}/runs` | Reads `service_task_runs` (filtered by `task_id`). |
|
||||
| POST | `/api/tasks/run?service_id=...` | `service_id` replaces `machine_id`; resolves an `ssh_tasks` service (override) or the task's `default_service_id`; calls `run_saved_task`. |
|
||||
|
||||
`_resolve_machine_for_task` and `_client_for_machine` are removed (replaced by
|
||||
service resolution + the shared helper).
|
||||
|
||||
### Resolution + validation
|
||||
|
||||
- `run_task`: load the task; if `service_id` query param is given, use it
|
||||
(override), else use `task.default_service_id`; load the `ssh_tasks` service
|
||||
record; build a `ServiceRecord` (decrypt secrets); call `run_saved_task`.
|
||||
- 400 if the task is disabled; 400 if no service resolves; 404 if the task or
|
||||
service is missing.
|
||||
|
||||
## 5. Frontend
|
||||
|
||||
### 5.1 Types
|
||||
|
||||
`SavedTask` / `SavedTaskInput` / `SavedTaskRun` (`frontend/src/types/index.ts`):
|
||||
|
||||
- `default_machine_id` → `default_service_id`.
|
||||
- `SavedTaskRun` fields align with `service_task_runs` (`service_id`,
|
||||
`exit_status`, `stdout_tail`, …).
|
||||
|
||||
### 5.2 API client + hooks
|
||||
|
||||
- `runTask(taskId, serviceId?)` sends `service_id`.
|
||||
- `fetchSavedTaskRuns(taskId)` reads `/api/tasks/{id}/runs` (now
|
||||
`service_task_runs`-backed).
|
||||
|
||||
### 5.3 Actions page
|
||||
|
||||
- Task editor: "Default service" `<Select>` lists `ssh_tasks` service instances
|
||||
(via `useServiceInstances("ssh_tasks")`), not machines.
|
||||
- Run dialog: "Run on" `<Select>` lists `ssh_tasks` instances (override).
|
||||
- Run history: reads the task's `service_task_runs`.
|
||||
- `useMonitoringSettings` removed from the Actions page (no longer needed).
|
||||
|
||||
## 6. Migration and breaking changes
|
||||
|
||||
- **DB:** `saved_tasks.default_machine_id` renamed to `default_service_id`
|
||||
(existing values become stale references to machine ids; inert — the user
|
||||
re-points). `saved_task_runs` dropped.
|
||||
- **Local execution removed.** Deployments relying on local tasks must use an
|
||||
`ssh_tasks` service (e.g. pointing at localhost with a key).
|
||||
- **Changelog + README** note the breaking change.
|
||||
|
||||
## 7. File-level plan
|
||||
|
||||
### Create (backend)
|
||||
|
||||
- `services/task_runner.py` — `run_saved_task` shared helper.
|
||||
|
||||
### Modify (backend)
|
||||
|
||||
- `services/settings_store.py` — rename column; drop `saved_task_runs` +
|
||||
`record_task_run` / `list_task_runs` (task-run flavor).
|
||||
- `routers/tasks.py` — service resolution; call `run_saved_task`; `service_id`
|
||||
param; read `service_task_runs`.
|
||||
- `widgets/sources.py` — `SshTaskWidgetSource.fetch` delegates to
|
||||
`run_saved_task`.
|
||||
|
||||
### Modify (frontend)
|
||||
|
||||
- `types/index.ts` — field rename + `SavedTaskRun` alignment.
|
||||
- `api/client.ts` — `runTask` sends `service_id`.
|
||||
- `pages/Actions.tsx` — service selectors + history source.
|
||||
|
||||
## 8. Slice boundaries
|
||||
|
||||
1. **Backend** — `run_saved_task` helper; saved_tasks column rename; tasks router
|
||||
rewired; widget delegates; `saved_task_runs` dropped; tests.
|
||||
2. **Frontend** — types + API + Actions page rewire; tests.
|
||||
|
||||
Estimated ~600–800 changed lines across two PRs.
|
||||
@@ -0,0 +1,78 @@
|
||||
# Proposal: Unify Saved Tasks on SSH Services
|
||||
|
||||
**Change:** `unify-tasks-on-services`
|
||||
**Phase:** proposal
|
||||
**Date:** 2026-06-19
|
||||
**Status:** awaiting review (design only — no implementation yet)
|
||||
|
||||
## Context and problem
|
||||
|
||||
Saved tasks (the Actions page) currently have **two execution paths**:
|
||||
|
||||
1. **Actions page** → resolves a *machine* (`default_machine_id`) → runs via
|
||||
`_client_for_machine` → logs to `saved_task_runs`.
|
||||
2. **SSH task widget** → resolves an `ssh_tasks` *service instance* → runs via
|
||||
`_build_ssh_client` → logs to `service_task_runs`.
|
||||
|
||||
Same saved-task records, two runners, two history tables, two target models. This
|
||||
is the leftover inconsistency from the service-registry change (design §12): the
|
||||
widget was migrated to services but the Actions page was not.
|
||||
|
||||
## Proposal
|
||||
|
||||
Migrate the Actions page onto the same `ssh_tasks` service model the widget
|
||||
already uses, so there is **one execution path** and **one history table**.
|
||||
|
||||
- Saved tasks gain `default_service_id` (replaces `default_machine_id`), pointing
|
||||
at an `ssh_tasks` service instance.
|
||||
- The Actions runner resolves an `ssh_tasks` service (the task's default, or an
|
||||
explicit run-time override), builds the SSH client from the service record, runs
|
||||
the task, and logs to `service_task_runs`.
|
||||
- `saved_task_runs` is dropped; both the Actions page and the widget read
|
||||
`service_task_runs`.
|
||||
- Local (API-host) task execution is dropped — all tasks run over SSH against
|
||||
`ssh_tasks` services.
|
||||
|
||||
## Goals
|
||||
|
||||
- One execution path for saved tasks (Actions page + widget share it).
|
||||
- One run-history table (`service_task_runs`).
|
||||
- Tasks target `ssh_tasks` service instances, consistent with the rest of the
|
||||
service registry.
|
||||
- Run-time override preserved: a task can be run against any `ssh_tasks` instance.
|
||||
|
||||
## Non-goals
|
||||
|
||||
- **No change to the jobs router** (`/api/jobs/run`, the `disk_usage` template,
|
||||
etc.). That stays machine-based for the File Browser's on-demand SSH checks.
|
||||
- **No machine/service unification** (follow-up #3). Machines still own File
|
||||
Browser + node_exporter transport.
|
||||
- **No local execution mode.** Dropped per decision; tasks are SSH-only.
|
||||
- **No automatic data migration** of `default_machine_id` → `default_service_id`.
|
||||
Break backwards compatibility (consistent with the service-registry change):
|
||||
existing tasks lose their default target and the user re-points them.
|
||||
|
||||
## Decisions (from grilling)
|
||||
|
||||
| Topic | Decision |
|
||||
|-------|----------|
|
||||
| Local execution | **SSH-only.** Drop local mode; `ssh_tasks` services handle all task execution. |
|
||||
| Run history | **`service_task_runs` only.** Drop `saved_task_runs`. |
|
||||
| Run-time override | **Keep.** A task can run against any `ssh_tasks` instance at run time. |
|
||||
|
||||
## Risks
|
||||
|
||||
- **Breaking upgrade.** Existing tasks lose `default_machine_id`; users re-point
|
||||
to an `ssh_tasks` service. Document in changelog.
|
||||
- **Local-mode loss.** Any deployment relying on local task execution must set up
|
||||
an SSH loopback (or an ssh_tasks service pointing at localhost with a key) to
|
||||
keep running local tasks.
|
||||
- **Shared execution code.** The Actions runner and the widget must share one
|
||||
`run_saved_task` helper to avoid divergence; extracting it is the core refactor.
|
||||
|
||||
## Out of scope
|
||||
|
||||
- Machine/service unification (follow-up #3).
|
||||
- Migrating the jobs router (`/api/jobs`) off machines.
|
||||
- A UI for browsing `service_task_runs` across all services (the service page
|
||||
already shows per-instance history; the Actions page shows per-task history).
|
||||
@@ -0,0 +1,105 @@
|
||||
# Tasks: Unify Saved Tasks on SSH Services
|
||||
|
||||
**Change:** `unify-tasks-on-services`
|
||||
**Phase:** tasks
|
||||
**Date:** 2026-06-19
|
||||
|
||||
## Review workload forecast
|
||||
|
||||
| Field | Value |
|
||||
|-------|-------|
|
||||
| Estimated changed lines | ~600–800 |
|
||||
| Chained PRs recommended | Yes (2 PRs) |
|
||||
| Chain strategy | stacked-to-main |
|
||||
|
||||
## Slice 1: Backend — shared runner + service-based tasks
|
||||
|
||||
**Goal:** One execution path; tasks target ssh_tasks services; one history table.
|
||||
|
||||
- [x] **1.1 Add shared `run_saved_task` helper**
|
||||
- Files: `backend/src/media_library_viewer_api/services/task_runner.py` (new)
|
||||
- Lines: ~90
|
||||
- Details: `run_saved_task(store, task, service, *, request_id)` builds the SSH
|
||||
client from the service record (promote `_build_ssh_client`), renders the
|
||||
command, runs with the service timeout, appends a `service_task_runs` row,
|
||||
returns a `TaskRunResult`.
|
||||
- [x] **1.2 Rename saved_tasks column**
|
||||
- Files: `services/settings_store.py` (modify)
|
||||
- Lines: ~20
|
||||
- Details: `default_machine_id` → `default_service_id` (ALTER TABLE RENAME
|
||||
COLUMN on startup; update `_row_to_task`, `_normalize_task_payload`,
|
||||
`upsert_task`).
|
||||
- [x] **1.3 Drop saved_task_runs**
|
||||
- Files: `services/settings_store.py` (modify)
|
||||
- Lines: ~-60
|
||||
- Details: `DROP TABLE IF EXISTS saved_task_runs`; remove `record_task_run`
|
||||
and `list_task_runs` (task flavor).
|
||||
- [x] **1.4 Rewire tasks router**
|
||||
- Files: `routers/tasks.py` (modify)
|
||||
- Lines: ~70
|
||||
- Details: `TaskInput.default_service_id`; `run_task` takes `service_id`
|
||||
(override), resolves an ssh_tasks service, calls `run_saved_task`;
|
||||
`/api/tasks/{id}/runs` reads `service_task_runs`. Remove
|
||||
`_resolve_machine_for_task` and `_client_for_machine`.
|
||||
- [x] **1.5 Widget delegates to shared helper**
|
||||
- Files: `widgets/sources.py` (modify)
|
||||
- Lines: ~-40
|
||||
- Details: `SshTaskWidgetSource.fetch` calls `run_saved_task` instead of its
|
||||
inline run+log block.
|
||||
- [x] **1.6 Add `list_service_task_runs` by task (if not present)**
|
||||
- Files: `services/settings_store.py` (modify)
|
||||
- Lines: ~10
|
||||
- Details: Confirm `list_service_task_runs(task_id=...)` covers the tasks
|
||||
router needs.
|
||||
- [x] **1.7 Update backend tests**
|
||||
- Files: `backend/tests/test_jobs.py`, `test_api.py` (modify)
|
||||
- Lines: ~60
|
||||
- Details: Update task-run tests to the service model; cover override +
|
||||
default + disabled-service paths.
|
||||
- [x] **1.8 Verify**
|
||||
- Run: `cd backend && .venv/bin/ruff check . && PYTHONPATH=src .venv/bin/python -m pytest`
|
||||
|
||||
**Slice 1 total:** ~250 changed lines.
|
||||
|
||||
## Slice 2: Frontend — Actions page on services
|
||||
|
||||
**Goal:** Actions page targets ssh_tasks services; reads service_task_runs.
|
||||
|
||||
- [x] **2.1 Update types**
|
||||
- Files: `frontend/src/types/index.ts` (modify)
|
||||
- Lines: ~15
|
||||
- Details: `SavedTask` / `SavedTaskInput` `default_service_id`;
|
||||
`SavedTaskRun` aligned to `service_task_runs`.
|
||||
- [x] **2.2 Update API client**
|
||||
- Files: `frontend/src/api/client.ts` (modify)
|
||||
- Lines: ~10
|
||||
- Details: `runTask(taskId, serviceId?)` sends `service_id`.
|
||||
- [x] **2.3 Rewire Actions page**
|
||||
- Files: `frontend/src/pages/Actions.tsx` (modify)
|
||||
- Lines: ~120
|
||||
- Details: Task editor "Default service" select lists ssh_tasks services via
|
||||
`useServiceInstances("ssh_tasks")`; run dialog "Run on" selects an instance;
|
||||
run history reads `service_task_runs`. Remove `useMonitoringSettings`.
|
||||
- [x] **2.4 Update Actions tests**
|
||||
- Files: `frontend/src/pages/__tests__/Actions.test.tsx` (modify)
|
||||
- Lines: ~30
|
||||
- Details: Mock `useServiceInstances`; update fixtures.
|
||||
- [x] **2.5 Docs + changelog**
|
||||
- Files: `docs/REQUIREMENTS.md`, `CHANGELOG.md` (modify)
|
||||
- Lines: ~30
|
||||
- Details: Saved-actions section: tasks target ssh_tasks services; local mode
|
||||
dropped; breaking-upgrade note.
|
||||
- [x] **2.6 Verify**
|
||||
- Run: `cd frontend && npm run lint && npm run build && npm run test`
|
||||
|
||||
**Slice 2 total:** ~200 changed lines.
|
||||
|
||||
## Integration and acceptance
|
||||
|
||||
- [x] **3.1 Backend full test run** — `PYTHONPATH=src pytest`, all green.
|
||||
- [x] **3.2 Frontend full build/lint/test**.
|
||||
- [ ] **3.3 Manual dev-stack check**:
|
||||
- Create an ssh_tasks service; create a task with that default; run from
|
||||
Actions; see the run in both the Actions history and the service page.
|
||||
- Override the target at run time.
|
||||
- SSH task widget uses the same history.
|
||||
Reference in New Issue
Block a user