Skip to content

ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.

feat(dashboard): boards that survive the browser they were built in

Juan Denis010b632530d7
diff --git a/backend/app/__init__.py b/backend/app/__init__.py
index 3ca897bd..b071f102 100644
--- a/backend/app/__init__.py
+++ b/backend/app/__init__.py
@@ -467,6 +467,10 @@ def create_app(config_name=None):
from app.api.themes import themes_bp
app.register_blueprint(themes_bp, url_prefix='/api/v1/themes')
+ # Register blueprints - Dashboard boards (plan 62, per-user widget grid)
+ from app.api.dashboards import dashboards_bp
+ app.register_blueprint(dashboards_bp, url_prefix='/api/v1/dashboards')
+
# Register blueprints - Plugins
from app.api.plugins import plugins_bp
app.register_blueprint(plugins_bp, url_prefix='/api/v1/plugins')
diff --git a/backend/app/api/dashboards.py b/backend/app/api/dashboards.py
new file mode 100644
index 00000000..623b12f3
--- /dev/null
+++ b/backend/app/api/dashboards.py
@@ -0,0 +1,223 @@
+"""Dashboard boards API (plan 62) — /api/v1/dashboards.
+
+Per-user dashboard tabs and their widget layout. Everything here is scoped to
+the calling user: a board that belongs to somebody else is indistinguishable
+from a board that does not exist, so cross-user access returns 404 rather than
+403 — a 403 would confirm the id is real.
+
+``GET /`` seeds the shipped default boards the first time a user asks for
+theirs, so a fresh account lands on a populated dashboard it can then edit,
+rearrange or delete like anything else.
+
+The widget payload is validated defensively before it is stored: the panel
+hands this JSON straight back to the grid renderer, so a malformed instance
+would be a broken dashboard the user cannot fix without an API call.
+"""
+import logging
+
+from flask import Blueprint, jsonify, request
+from flask_jwt_extended import jwt_required, get_jwt_identity
+
+from app.services import dashboard_service
+from app.services.dashboard_service import GRID_COLS, MAX_WIDGETS_PER_BOARD
+
+logger = logging.getLogger(__name__)
+
+dashboards_bp = Blueprint('dashboards', __name__)
+
+# Defensive ceilings on the geometry. The grid is 12 columns wide and rows are
+# 88px; nothing legitimate is thousands of rows tall.
+MAX_ROW = 1000
+MAX_SPAN = 100
+MAX_ID_LEN = 64
+MAX_NAME_LEN = 120
+
+
+def _validate_widgets(raw):
+ """Normalise a widget-instance list. Returns ``(widgets, error)``.
+
+ Each instance must be an object carrying a string ``i`` unique within the
+ board, a string ``type``, and integer ``x``/``y``/``w``/``h`` that fit the
+ 12-column grid. ``cfg`` is free-form but must be an object; it is stored
+ verbatim because only the widget renderer knows what it means.
+ """
+ if not isinstance(raw, list):
+ return None, 'widgets must be a list'
+ if len(raw) > MAX_WIDGETS_PER_BOARD:
+ return None, f'A board holds at most {MAX_WIDGETS_PER_BOARD} widgets'
+
+ seen = set()
+ out = []
+ for index, item in enumerate(raw):
+ if not isinstance(item, dict):
+ return None, f'widget {index} must be an object'
+
+ wid = item.get('i')
+ if not isinstance(wid, str) or not wid.strip():
+ return None, f'widget {index} needs a string id "i"'
+ if len(wid) > MAX_ID_LEN:
+ return None, f'widget {index} id is too long'
+ if wid in seen:
+ return None, f'duplicate widget id "{wid}"'
+ seen.add(wid)
+
+ wtype = item.get('type')
+ if not isinstance(wtype, str) or not wtype.strip():
+ return None, f'widget "{wid}" needs a string type'
+ if len(wtype) > MAX_ID_LEN:
+ return None, f'widget "{wid}" type is too long'
+
+ geometry = {}
+ for field in ('x', 'y', 'w', 'h'):
+ value = item.get(field)
+ # bool is a subclass of int in Python; True is not a coordinate.
+ if isinstance(value, bool) or not isinstance(value, int):
+ return None, f'widget "{wid}" needs an integer {field}'
+ geometry[field] = value
+
+ if geometry['x'] < 0 or geometry['y'] < 0:
+ return None, f'widget "{wid}" cannot have negative coordinates'
+ if geometry['w'] < 1 or geometry['h'] < 1:
+ return None, f'widget "{wid}" must span at least one cell'
+ if geometry['x'] + geometry['w'] > GRID_COLS:
+ return None, f'widget "{wid}" does not fit the {GRID_COLS}-column grid'
+ if geometry['y'] > MAX_ROW or geometry['h'] > MAX_SPAN:
+ return None, f'widget "{wid}" is out of bounds'
+
+ cfg = item.get('cfg')
+ if cfg is None:
+ cfg = {}
+ if not isinstance(cfg, dict):
+ return None, f'widget "{wid}" cfg must be an object'
+
+ out.append({
+ 'i': wid,
+ 'type': wtype,
+ 'x': geometry['x'],
+ 'y': geometry['y'],
+ 'w': geometry['w'],
+ 'h': geometry['h'],
+ 'cfg': cfg,
+ })
+
+ return out, None
+
+
+def _validate_name(value):
+ if not isinstance(value, str) or not value.strip():
+ return None, 'name is required'
+ name = value.strip()
+ if len(name) > MAX_NAME_LEN:
+ return None, f'name must be {MAX_NAME_LEN} characters or fewer'
+ return name, None
+
+
+def _validate_icon(value):
+ if not isinstance(value, str) or not value.strip():
+ return None, 'icon must be a string'
+ icon = value.strip()
+ if len(icon) > MAX_ID_LEN:
+ return None, f'icon must be {MAX_ID_LEN} characters or fewer'
+ return icon, None
+
+
+@dashboards_bp.route('', methods=['GET'])
+@dashboards_bp.route('/', methods=['GET'])
+@jwt_required()
+def list_boards():
+ """This user's boards, seeding the shipped defaults on the first call."""
+ user_id = get_jwt_identity()
+ boards = dashboard_service.get_boards_for_user(user_id)
+ return jsonify({'boards': [b.to_dict() for b in boards]})
+
+
+@dashboards_bp.route('', methods=['POST'])
+@dashboards_bp.route('/', methods=['POST'])
+@jwt_required()
+def create_board():
+ """Add a board for this user. ``widgets`` is optional — a new tab usually
+ starts empty and gets filled from the widget library."""
+ user_id = get_jwt_identity()
+ body = request.get_json(silent=True) or {}
+
+ name, err = _validate_name(body.get('name'))
+ if err:
+ return jsonify({'error': err}), 400
+
+ icon = 'grid'
+ if body.get('icon') is not None:
+ icon, err = _validate_icon(body.get('icon'))
+ if err:
+ return jsonify({'error': err}), 400
+
+ widgets = []
+ if body.get('widgets') is not None:
+ widgets, err = _validate_widgets(body.get('widgets'))
+ if err:
+ return jsonify({'error': err}), 400
+
+ board = dashboard_service.create_board(user_id, name, icon=icon, widgets=widgets)
+ return jsonify(board.to_dict()), 201
+
+
+@dashboards_bp.route('/<int:board_id>', methods=['PUT'])
+@jwt_required()
+def update_board(board_id):
+ """Rename / re-icon / reorder a board, or store a new widget layout."""
+ user_id = get_jwt_identity()
+ board = dashboard_service.get_board_for_user(user_id, board_id)
+ if not board:
+ return jsonify({'error': 'Board not found'}), 404
+
+ body = request.get_json(silent=True) or {}
+ name = icon = position = widgets = None
+
+ if body.get('name') is not None:
+ name, err = _validate_name(body.get('name'))
+ if err:
+ return jsonify({'error': err}), 400
+
+ if body.get('icon') is not None:
+ icon, err = _validate_icon(body.get('icon'))
+ if err:
+ return jsonify({'error': err}), 400
+
+ if body.get('position') is not None:
+ position = body.get('position')
+ if isinstance(position, bool) or not isinstance(position, int) or position < 0:
+ return jsonify({'error': 'position must be a non-negative integer'}), 400
+
+ if body.get('widgets') is not None:
+ widgets, err = _validate_widgets(body.get('widgets'))
+ if err:
+ return jsonify({'error': err}), 400
+
+ board = dashboard_service.update_board(
+ board, name=name, icon=icon, position=position, widgets=widgets)
+ return jsonify(board.to_dict())
+
+
+@dashboards_bp.route('/<int:board_id>', methods=['DELETE'])
+@jwt_required()
+def delete_board(board_id):
+ user_id = get_jwt_identity()
+ board = dashboard_service.get_board_for_user(user_id, board_id)
+ if not board:
+ return jsonify({'error': 'Board not found'}), 404
+ dashboard_service.delete_board(board)
+ return jsonify({'success': True}), 200
+
+
+@dashboards_bp.route('/<int:board_id>/reset', methods=['POST'])
+@jwt_required()
+def reset_board(board_id):
+ """Restore a shipped default board. Boards the user created have no default
+ to fall back to, so those are refused rather than silently emptied."""
+ user_id = get_jwt_identity()
+ board = dashboard_service.get_board_for_user(user_id, board_id)
+ if not board:
+ return jsonify({'error': 'Board not found'}), 404
+ restored = dashboard_service.reset_board(board)
+ if not restored:
+ return jsonify({'error': 'This board has no shipped default to reset to'}), 400
+ return jsonify(restored.to_dict())
diff --git a/backend/app/models/dashboard.py b/backend/app/models/dashboard.py
new file mode 100644
index 00000000..43d72cec
--- /dev/null
+++ b/backend/app/models/dashboard.py
@@ -0,0 +1,61 @@
+"""Per-user dashboard boards (plan 62).
+
+A *board* is one tab on the dashboard — a name, an icon, and an ordered bag of
+widget instances laid out on a 12-column grid. Boards belong to a user, not to
+the panel: two operators looking at the same server keep their own tabs, their
+own widget placement and their own per-widget config.
+
+The shipped defaults ('overview', 'infra', 'apps') are seeded as real rows the
+first time a user reads their boards, so a user can drag, resize and delete them
+like anything else. ``slug`` remembers which shipped default a row came from,
+which is what makes ``POST /<id>/reset`` able to restore it; user-created boards
+leave it NULL.
+
+``widgets`` is a native JSON column (the dominant pattern in this codebase, and
+dialect-agnostic across SQLite and PostgreSQL) holding the widget-instance list
+``[{i, type, x, y, w, h, cfg}, …]``. The panel does not interpret ``cfg`` — that
+is the widget renderer's business — but the API layer does validate the shape of
+the geometry fields before storing anything.
+"""
+
+from datetime import datetime
+
+from app import db
+
+
+class DashboardBoard(db.Model):
+ """One dashboard tab belonging to one user."""
+
+ __tablename__ = 'dashboard_boards'
+
+ id = db.Column(db.Integer, primary_key=True)
+ user_id = db.Column(
+ db.Integer,
+ db.ForeignKey('users.id', ondelete='CASCADE'),
+ nullable=False,
+ index=True,
+ )
+ # The shipped-default id this board came from ('overview' / 'infra' /
+ # 'apps'). NULL for boards the user created themselves — those have no
+ # default to reset to.
+ slug = db.Column(db.String(64), nullable=True)
+ name = db.Column(db.String(120), nullable=False)
+ icon = db.Column(db.String(64), nullable=True, default='grid')
+ position = db.Column(db.Integer, nullable=False, default=0)
+ widgets = db.Column(db.JSON, nullable=False, default=list)
+
+ created_at = db.Column(db.DateTime, default=datetime.utcnow)
+ updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
+
+ def to_dict(self):
+ return {
+ 'id': self.id,
+ 'slug': self.slug,
+ 'name': self.name,
+ 'icon': self.icon or 'grid',
+ 'position': self.position if self.position is not None else 0,
+ 'widgets': self.widgets or [],
+ }
+
+ def __repr__(self):
+ return f'<DashboardBoard {self.id} u{self.user_id} {self.name!r}>'
diff --git a/backend/app/services/dashboard_service.py b/backend/app/services/dashboard_service.py
new file mode 100644
index 00000000..90dd2cfe
--- /dev/null
+++ b/backend/app/services/dashboard_service.py
@@ -0,0 +1,238 @@
+"""Dashboard board service (plan 62).
+
+Owns the shipped default boards and the per-user CRUD around them. A board is a
+dashboard tab; a widget instance is ``{i, type, x, y, w, h, cfg}`` placed on a
+12-column grid.
+
+Grid rules the defaults below obey (the frontend's ``grid/layout.js`` enforces
+the same ones at runtime):
+
+* 12 columns. ``x + w <= 12`` for every widget.
+* No two widgets on a board overlap.
+* Gravity-up: no widget can float higher without colliding, so there are no
+ floating rows or holes above a widget.
+* Every widget respects its type's minimum size from the widget registry.
+
+``cfg`` is free-form per widget type and the backend never interprets it — it is
+stored and handed back verbatim. The shapes used here mirror the widget table in
+the plan contract:
+
+* ``stat`` ``{metric, agg, resource, thresholds}``
+* ``timeseries`` ``{metrics: [...], resource}``
+* ``gauge`` ``{metric, resource, thresholds}``
+* ``topn`` ``{metric, source, limit}``
+* ``table`` ``{source: 'apps'|'servers'|'containers'|'deploys', limit}``
+* ``logs`` ``{resource, lines}``
+* ``deploys`` / ``alerts`` / ``status`` / ``feed`` ``{limit, …}``
+* ``actions`` ``{actions: [...]}``
+* ``specs`` ``{resource}``
+
+``resource: '$server'`` is the server variable the dashboard topbar binds, so a
+default board follows whichever server the operator has selected.
+
+Metrics are limited to the ones the panel actually records
+(``MetricsHistory``): cpu, ram, disk and load.
+"""
+
+import copy
+
+from app import db
+from app.models.dashboard import DashboardBoard
+
+# Grid width. Mirrors GRID_COLS in the frontend's grid/layout.js.
+GRID_COLS = 12
+
+# Hard ceiling on widgets per board, enforced by the API layer. Generous for a
+# real dashboard, small enough that a runaway client can't store a megabyte of
+# JSON per board.
+MAX_WIDGETS_PER_BOARD = 100
+
+
+DEFAULT_BOARDS = [
+ {
+ 'slug': 'overview',
+ 'name': 'Overview',
+ 'icon': 'grid',
+ 'position': 0,
+ 'widgets': [
+ # Row 0-1: four stats across the top.
+ {'i': 'w1', 'type': 'stat', 'x': 0, 'y': 0, 'w': 3, 'h': 2,
+ 'cfg': {'metric': 'cpu', 'agg': 'last', 'resource': '$server',
+ 'thresholds': [70, 90]}},
+ {'i': 'w2', 'type': 'stat', 'x': 3, 'y': 0, 'w': 3, 'h': 2,
+ 'cfg': {'metric': 'ram', 'agg': 'last', 'resource': '$server',
+ 'thresholds': [80, 92]}},
+ {'i': 'w3', 'type': 'stat', 'x': 6, 'y': 0, 'w': 3, 'h': 2,
+ 'cfg': {'metric': 'disk', 'agg': 'last', 'resource': '$server',
+ 'thresholds': [75, 90]}},
+ {'i': 'w4', 'type': 'stat', 'x': 9, 'y': 0, 'w': 3, 'h': 2,
+ 'cfg': {'metric': 'load', 'agg': 'last', 'resource': '$server',
+ 'thresholds': None}},
+ # Rows 2-5: the wide chart, with quick actions + host details stacked
+ # in the right-hand column.
+ {'i': 'w5', 'type': 'timeseries', 'x': 0, 'y': 2, 'w': 8, 'h': 4,
+ 'cfg': {'metrics': ['cpu', 'ram'], 'resource': '$server'}},
+ {'i': 'w6', 'type': 'actions', 'x': 8, 'y': 2, 'w': 4, 'h': 2,
+ 'cfg': {'actions': ['new-app', 'deploy', 'terminal', 'backup']}},
+ {'i': 'w7', 'type': 'specs', 'x': 8, 'y': 4, 'w': 4, 'h': 2,
+ 'cfg': {'resource': '$server'}},
+ # Rows 6-9: inventory + what happened.
+ {'i': 'w8', 'type': 'table', 'x': 0, 'y': 6, 'w': 8, 'h': 4,
+ 'cfg': {'source': 'apps', 'limit': 8}},
+ {'i': 'w9', 'type': 'feed', 'x': 8, 'y': 6, 'w': 4, 'h': 4,
+ 'cfg': {'limit': 10}},
+ ],
+ },
+ {
+ 'slug': 'infra',
+ 'name': 'Infrastructure',
+ 'icon': 'server',
+ 'position': 1,
+ 'widgets': [
+ # Rows 0-3: fleet-wide chart + the ranked hot list.
+ {'i': 'w1', 'type': 'timeseries', 'x': 0, 'y': 0, 'w': 8, 'h': 4,
+ 'cfg': {'metrics': ['cpu', 'ram', 'disk'], 'resource': '$server'}},
+ {'i': 'w2', 'type': 'topn', 'x': 8, 'y': 0, 'w': 4, 'h': 4,
+ 'cfg': {'metric': 'cpu', 'source': 'servers', 'limit': 5}},
+ # Rows 4-6: two dials and the up/down matrix.
+ {'i': 'w3', 'type': 'gauge', 'x': 0, 'y': 4, 'w': 3, 'h': 3,
+ 'cfg': {'metric': 'cpu', 'resource': '$server',
+ 'thresholds': [70, 90]}},
+ {'i': 'w4', 'type': 'gauge', 'x': 3, 'y': 4, 'w': 3, 'h': 3,
+ 'cfg': {'metric': 'ram', 'resource': '$server',
+ 'thresholds': [80, 92]}},
+ {'i': 'w5', 'type': 'status', 'x': 6, 'y': 4, 'w': 6, 'h': 3,
+ 'cfg': {'limit': 12}},
+ # Rows 7-10: containers + anything currently shouting.
+ {'i': 'w6', 'type': 'table', 'x': 0, 'y': 7, 'w': 8, 'h': 4,
+ 'cfg': {'source': 'containers', 'limit': 8}},
+ {'i': 'w7', 'type': 'alerts', 'x': 8, 'y': 7, 'w': 4, 'h': 4,
+ 'cfg': {'limit': 8, 'severity': 'all'}},
+ ],
+ },
+ {
+ 'slug': 'apps',
+ 'name': 'Apps',
+ 'icon': 'rocket',
+ 'position': 2,
+ 'widgets': [
+ # Rows 0-1: three wider stats, averaged over the selected range.
+ {'i': 'w1', 'type': 'stat', 'x': 0, 'y': 0, 'w': 4, 'h': 2,
+ 'cfg': {'metric': 'cpu', 'agg': 'avg', 'resource': '$server',
+ 'thresholds': [70, 90]}},
+ {'i': 'w2', 'type': 'stat', 'x': 4, 'y': 0, 'w': 4, 'h': 2,
+ 'cfg': {'metric': 'ram', 'agg': 'avg', 'resource': '$server',
+ 'thresholds': [80, 92]}},
+ {'i': 'w3', 'type': 'stat', 'x': 8, 'y': 0, 'w': 4, 'h': 2,
+ 'cfg': {'metric': 'load', 'agg': 'last', 'resource': '$server',
+ 'thresholds': None}},
+ # Rows 2-5: load over time next to the deploy stream.
+ {'i': 'w4', 'type': 'timeseries', 'x': 0, 'y': 2, 'w': 8, 'h': 4,
+ 'cfg': {'metrics': ['cpu', 'ram'], 'resource': '$server'}},
+ {'i': 'w5', 'type': 'deploys', 'x': 8, 'y': 2, 'w': 4, 'h': 4,
+ 'cfg': {'limit': 8}},
+ # Rows 6-9: full-width tail.
+ {'i': 'w6', 'type': 'logs', 'x': 0, 'y': 6, 'w': 12, 'h': 4,
+ 'cfg': {'resource': '$server', 'lines': 60}},
+ ],
+ },
+]
+
+
+def get_default_board(slug):
+ """A deep copy of one shipped default, or None when the slug is unknown."""
+ for spec in DEFAULT_BOARDS:
+ if spec['slug'] == slug:
+ return copy.deepcopy(spec)
+ return None
+
+
+def seed_defaults(user_id):
+ """Create the shipped default boards for a user. Returns the new rows."""
+ created = []
+ for spec in DEFAULT_BOARDS:
+ board = DashboardBoard(
+ user_id=user_id,
+ slug=spec['slug'],
+ name=spec['name'],
+ icon=spec['icon'],
+ position=spec['position'],
+ widgets=copy.deepcopy(spec['widgets']),
+ )
+ db.session.add(board)
+ created.append(board)
+ db.session.commit()
+ return created
+
+
+def get_boards_for_user(user_id):
+ """Every board owned by this user, seeding the shipped defaults on the
+ first read for a user who has none."""
+ boards = (DashboardBoard.query
+ .filter_by(user_id=user_id)
+ .order_by(DashboardBoard.position, DashboardBoard.id)
+ .all())
+ if boards:
+ return boards
+ seed_defaults(user_id)
+ return (DashboardBoard.query
+ .filter_by(user_id=user_id)
+ .order_by(DashboardBoard.position, DashboardBoard.id)
+ .all())
+
+
+def get_board_for_user(user_id, board_id):
+ """One board, scoped to its owner. None means "not yours / not there" — the
+ caller must not distinguish the two."""
+ return DashboardBoard.query.filter_by(id=board_id, user_id=user_id).first()
+
+
+def create_board(user_id, name, icon=None, widgets=None):
+ """Add a user-created board after the existing ones. ``slug`` stays NULL:
+ a board the user invented has no shipped default to reset to."""
+ last = (db.session.query(db.func.max(DashboardBoard.position))
+ .filter(DashboardBoard.user_id == user_id).scalar())
+ board = DashboardBoard(
+ user_id=user_id,
+ slug=None,
+ name=name,
+ icon=icon or 'grid',
+ position=(last + 1) if last is not None else 0,
+ widgets=list(widgets or []),
+ )
+ db.session.add(board)
+ db.session.commit()
+ return board
+
+
+def update_board(board, name=None, icon=None, position=None, widgets=None):
+ """Patch the fields that were actually supplied."""
+ if name is not None:
+ board.name = name
+ if icon is not None:
+ board.icon = icon
+ if position is not None:
+ board.position = position
+ if widgets is not None:
+ board.widgets = list(widgets)
+ db.session.commit()
+ return board
+
+
+def delete_board(board):
+ db.session.delete(board)
+ db.session.commit()
+ return True
+
+
+def reset_board(board):
+ """Restore a board to its shipped default. Returns None when the board was
+ created by the user and therefore has no default to go back to."""
+ spec = get_default_board(board.slug) if board.slug else None
+ if not spec:
+ return None
+ board.name = spec['name']
+ board.icon = spec['icon']
+ board.widgets = copy.deepcopy(spec['widgets'])
+ db.session.commit()
+ return board
diff --git a/backend/migrations/versions/080_dashboard_boards.py b/backend/migrations/versions/080_dashboard_boards.py
new file mode 100644
index 00000000..12d8bdb0
--- /dev/null
+++ b/backend/migrations/versions/080_dashboard_boards.py
@@ -0,0 +1,51 @@
+"""Per-user dashboard boards.
+
+One row is one dashboard tab for one user: name, icon, ordering position and a
+native JSON list of widget instances (SQLAlchemy renders JSON as JSON on
+PostgreSQL and TEXT on SQLite). ``slug`` records which shipped default the board
+was seeded from so it can be reset; user-created boards leave it NULL.
+
+Idempotent: guards on table presence like the other migrations here.
+
+Revision ID: 080_dashboard_boards
+Revises: 079_plugin_store
+Create Date: 2026-07-25
+"""
+from alembic import op
+import sqlalchemy as sa
+
+revision = '080_dashboard_boards'
+down_revision = '079_plugin_store'
+branch_labels = None
+depends_on = None
+
+
+def upgrade():
+ conn = op.get_bind()
+ inspector = sa.inspect(conn)
+ if 'dashboard_boards' in set(inspector.get_table_names()):
+ return
+ op.create_table(
+ 'dashboard_boards',
+ sa.Column('id', sa.Integer(), nullable=False),
+ sa.Column('user_id', sa.Integer(), nullable=False),
+ sa.Column('slug', sa.String(length=64), nullable=True),
+ sa.Column('name', sa.String(length=120), nullable=False),
+ sa.Column('icon', sa.String(length=64), nullable=True),
+ sa.Column('position', sa.Integer(), nullable=False, server_default='0'),
+ sa.Column('widgets', sa.JSON(), nullable=False),
+ sa.Column('created_at', sa.DateTime(), nullable=True),
+ sa.Column('updated_at', sa.DateTime(), nullable=True),
+ sa.ForeignKeyConstraint(['user_id'], ['users.id'], ondelete='CASCADE'),
+ sa.PrimaryKeyConstraint('id'),
+ )
+ op.create_index('ix_dashboard_boards_user_id', 'dashboard_boards', ['user_id'])
+
+
+def downgrade():
+ conn = op.get_bind()
+ inspector = sa.inspect(conn)
+ if 'dashboard_boards' not in set(inspector.get_table_names()):
+ return
+ op.drop_index('ix_dashboard_boards_user_id', table_name='dashboard_boards')
+ op.drop_table('dashboard_boards')
diff --git a/backend/tests/test_dashboards.py b/backend/tests/test_dashboards.py
new file mode 100644
index 00000000..7c87e4b8
--- /dev/null
+++ b/backend/tests/test_dashboards.py
@@ -0,0 +1,299 @@
+"""Dashboard board persistence tests (plan 62).
+
+Proves the backend contract behind the widget grid: shipped defaults are seeded
+once per user, boards are CRUD-able, a default board can be restored, one user
+can never see or touch another's board (404, never 403), and a malformed widget
+payload is refused before it reaches the database.
+"""
+import pytest
+
+from app.services.dashboard_service import DEFAULT_BOARDS, GRID_COLS
+
+
+def _headers_for(app, username):
+ """A second (non-admin) user's auth headers — the neighbour whose boards
+ must stay invisible."""
+ from app import db
+ from app.models import User
+ from flask_jwt_extended import create_access_token
+ from werkzeug.security import generate_password_hash
+
+ with app.app_context():
+ user = User(
+ email=f'{username}@test.local', username=username,
+ password_hash=generate_password_hash('x'),
+ role=User.ROLE_DEVELOPER, is_active=True,
+ )
+ db.session.add(user)
+ db.session.commit()
+ return {'Authorization': f'Bearer {create_access_token(identity=user.id)}'}
+
+
+def other_headers(app):
+ return _headers_for(app, 'boardneighbour')
+
+
+def _widget(i='w1', wtype='stat', x=0, y=0, w=3, h=2, cfg=None):
+ return {'i': i, 'type': wtype, 'x': x, 'y': y, 'w': w, 'h': h, 'cfg': cfg or {}}
+
+
+# ---------------------------------------------------------------- auth gate
+
+def test_boards_require_auth(client):
+ assert client.get('/api/v1/dashboards').status_code == 401
+
+
+# ------------------------------------------------------------- seed defaults
+
+def test_first_get_seeds_shipped_defaults(client, auth_headers):
+ resp = client.get('/api/v1/dashboards', headers=auth_headers)
+ assert resp.status_code == 200
+ boards = resp.get_json()['boards']
+
+ assert [b['slug'] for b in boards] == ['overview', 'infra', 'apps']
+ assert [b['position'] for b in boards] == [0, 1, 2]
+ assert [b['icon'] for b in boards] == ['grid', 'server', 'rocket']
+ assert all(b['widgets'] for b in boards)
+
+ overview = boards[0]
+ types = [w['type'] for w in overview['widgets']]
+ assert types.count('stat') == 4
+ assert {'timeseries', 'actions', 'specs', 'table', 'feed'}.issubset(set(types))
+ table = next(w for w in overview['widgets'] if w['type'] == 'table')
+ assert table['cfg']['source'] == 'apps'
+
+
+def test_defaults_are_seeded_only_once(client, auth_headers):
+ first = client.get('/api/v1/dashboards', headers=auth_headers).get_json()['boards']
+ second = client.get('/api/v1/dashboards', headers=auth_headers).get_json()['boards']
+ assert [b['id'] for b in first] == [b['id'] for b in second]
+ assert len(second) == len(DEFAULT_BOARDS)
+
+
+def test_default_layouts_obey_the_grid_rules():
+ """12 columns, no overlaps, gravity-up — the same invariants the frontend
+ grid enforces at runtime."""
+ for spec in DEFAULT_BOARDS:
+ widgets = spec['widgets']
+ assert len({w['i'] for w in widgets}) == len(widgets), spec['slug']
+
+ cells = {}
+ for w in widgets:
+ assert w['x'] >= 0 and w['y'] >= 0, (spec['slug'], w['i'])
+ assert w['w'] >= 1 and w['h'] >= 1, (spec['slug'], w['i'])
+ assert w['x'] + w['w'] <= GRID_COLS, (spec['slug'], w['i'])
+ for col in range(w['x'], w['x'] + w['w']):
+ for row in range(w['y'], w['y'] + w['h']):
+ assert (col, row) not in cells, (
+ f"{spec['slug']}: {w['i']} overlaps {cells.get((col, row))}")
+ cells[(col, row)] = w['i']
+
+ # Gravity-up: nothing may float. A widget below row 0 must be blocked
+ # by something directly above it.
+ for w in widgets:
+ if w['y'] == 0:
+ continue
+ blocked = any((col, w['y'] - 1) in cells
+ for col in range(w['x'], w['x'] + w['w']))
+ assert blocked, f"{spec['slug']}: {w['i']} floats above a hole"
+
+
+# --------------------------------------------------------------------- CRUD
+
+def test_create_board(client, auth_headers):
+ client.get('/api/v1/dashboards', headers=auth_headers) # seed the defaults
+ resp = client.post('/api/v1/dashboards', headers=auth_headers, json={
+ 'name': 'Night shift', 'icon': 'zap',
+ 'widgets': [_widget(wtype='gauge', w=3, h=3)],
+ })
+ assert resp.status_code == 201, resp.get_json()
+ board = resp.get_json()
+ assert board['name'] == 'Night shift'
+ assert board['icon'] == 'zap'
+ assert board['slug'] is None
+ assert len(board['widgets']) == 1
+
+ listing = client.get('/api/v1/dashboards', headers=auth_headers).get_json()['boards']
+ assert len(listing) == len(DEFAULT_BOARDS) + 1
+ # Created boards land after the seeded defaults.
+ assert listing[-1]['id'] == board['id']
+
+
+def test_create_board_requires_a_name(client, auth_headers):
+ resp = client.post('/api/v1/dashboards', headers=auth_headers, json={'icon': 'zap'})
+ assert resp.status_code == 400
+ assert 'error' in resp.get_json()
+
+
+def test_update_board_stores_layout(client, auth_headers):
+ boards = client.get('/api/v1/dashboards', headers=auth_headers).get_json()['boards']
+ board_id = boards[0]['id']
+
+ layout = [_widget('a', 'stat', 0, 0, 4, 2), _widget('b', 'logs', 4, 0, 8, 4)]
+ resp = client.put(f'/api/v1/dashboards/{board_id}', headers=auth_headers,
+ json={'name': 'Renamed', 'icon': 'cpu', 'widgets': layout})
+ assert resp.status_code == 200, resp.get_json()
+ updated = resp.get_json()
+ assert updated['name'] == 'Renamed'
+ assert updated['icon'] == 'cpu'
+ assert [w['i'] for w in updated['widgets']] == ['a', 'b']
+
+ reread = client.get('/api/v1/dashboards', headers=auth_headers).get_json()['boards']
+ assert reread[0]['widgets'][1]['type'] == 'logs'
+
+
+def test_update_board_accepts_partial_payload(client, auth_headers):
+ boards = client.get('/api/v1/dashboards', headers=auth_headers).get_json()['boards']
+ board = boards[1]
+ resp = client.put(f"/api/v1/dashboards/{board['id']}", headers=auth_headers,
+ json={'position': 9})
+ assert resp.status_code == 200
+ updated = resp.get_json()
+ assert updated['position'] == 9
+ assert updated['name'] == board['name']
+ assert updated['widgets'] == board['widgets']
+
+
+def test_delete_board(client, auth_headers):
+ boards = client.get('/api/v1/dashboards', headers=auth_headers).get_json()['boards']
+ victim = boards[2]['id']
+
+ assert client.delete(f'/api/v1/dashboards/{victim}',
+ headers=auth_headers).status_code == 200
+
+ remaining = client.get('/api/v1/dashboards', headers=auth_headers).get_json()['boards']
+ assert victim not in [b['id'] for b in remaining]
+ # The survivors are NOT re-seeded — seeding only happens for a user with no
+ # boards at all.
+ assert len(remaining) == len(DEFAULT_BOARDS) - 1
+
+
+def test_unknown_board_is_404(client, auth_headers):
+ assert client.put('/api/v1/dashboards/99999', headers=auth_headers,
+ json={'name': 'x'}).status_code == 404
+ assert client.delete('/api/v1/dashboards/99999',
+ headers=auth_headers).status_code == 404
+ assert client.post('/api/v1/dashboards/99999/reset',
+ headers=auth_headers).status_code == 404
+
+
+# -------------------------------------------------------------------- reset
+
+def test_reset_restores_the_shipped_default(client, auth_headers):
+ boards = client.get('/api/v1/dashboards', headers=auth_headers).get_json()['boards']
+ overview = boards[0]
+ original = overview['widgets']
+
+ client.put(f"/api/v1/dashboards/{overview['id']}", headers=auth_headers,
+ json={'name': 'Wrecked', 'widgets': [_widget('solo', 'note')]})
+
+ resp = client.post(f"/api/v1/dashboards/{overview['id']}/reset", headers=auth_headers)
+ assert resp.status_code == 200, resp.get_json()
+ restored = resp.get_json()
+ assert restored['name'] == 'Overview'
+ assert restored['widgets'] == original
+
+
+def test_reset_refuses_a_user_created_board(client, auth_headers):
+ created = client.post('/api/v1/dashboards', headers=auth_headers,
+ json={'name': 'Mine'}).get_json()
+ resp = client.post(f"/api/v1/dashboards/{created['id']}/reset", headers=auth_headers)
+ assert resp.status_code == 400
+ assert 'error' in resp.get_json()
+
+
+# ----------------------------------------------------------- user isolation
+
+def test_boards_are_scoped_per_user(client, auth_headers, other_headers):
+ mine = client.get('/api/v1/dashboards', headers=auth_headers).get_json()['boards']
+ theirs = client.get('/api/v1/dashboards', headers=other_headers).get_json()['boards']
+
+ # Each user got their own seeded copy — same slugs, different rows.
+ assert [b['slug'] for b in mine] == [b['slug'] for b in theirs]
+ assert not set(b['id'] for b in mine) & set(b['id'] for b in theirs)
+
+
+def test_a_foreign_board_is_404_not_403(client, auth_headers, other_headers):
+ mine = client.get('/api/v1/dashboards', headers=auth_headers).get_json()['boards']
+ target = mine[0]['id']
+
+ # Seed the neighbour so their own boards exist and the id is simply not theirs.
+ client.get('/api/v1/dashboards', headers=other_headers)
+
+ assert client.put(f'/api/v1/dashboards/{target}', headers=other_headers,
+ json={'name': 'stolen'}).status_code == 404
+ assert client.post(f'/api/v1/dashboards/{target}/reset',
+ headers=other_headers).status_code == 404
+ assert client.delete(f'/api/v1/dashboards/{target}',
+ headers=other_headers).status_code == 404
+
+ # The owner's board is untouched.
+ still = client.get('/api/v1/dashboards', headers=auth_headers).get_json()['boards']
+ assert still[0]['id'] == target
+ assert still[0]['name'] == 'Overview'
+
+
+# ------------------------------------------------------- payload validation
+
[email protected]('payload,reason', [
+ ('not-a-list', 'widgets must be a list'),
+ ({'i': 'w1'}, 'a dict is not a list'),
+ ([{'type': 'stat', 'x': 0, 'y': 0, 'w': 3, 'h': 2}], 'missing i'),
+ ([{'i': 5, 'type': 'stat', 'x': 0, 'y': 0, 'w': 3, 'h': 2}], 'non-string i'),
+ ([{'i': 'w1', 'x': 0, 'y': 0, 'w': 3, 'h': 2}], 'missing type'),
+ ([{'i': 'w1', 'type': 'stat', 'x': '0', 'y': 0, 'w': 3, 'h': 2}], 'string x'),
+ ([{'i': 'w1', 'type': 'stat', 'x': 0, 'y': 0, 'w': 3.5, 'h': 2}], 'float w'),
+ ([{'i': 'w1', 'type': 'stat', 'x': True, 'y': 0, 'w': 3, 'h': 2}], 'bool x'),
+ ([{'i': 'w1', 'type': 'stat', 'x': -1, 'y': 0, 'w': 3, 'h': 2}], 'negative x'),
+ ([{'i': 'w1', 'type': 'stat', 'x': 0, 'y': 0, 'w': 0, 'h': 2}], 'zero width'),
+ ([{'i': 'w1', 'type': 'stat', 'x': 10, 'y': 0, 'w': 4, 'h': 2}], 'overflows 12 cols'),
+ ([{'i': 'w1', 'type': 'stat', 'x': 0, 'y': 0, 'w': 3, 'h': 2, 'cfg': 'nope'}], 'cfg not an object'),
+ (['just-a-string'], 'entry is not an object'),
+])
+def test_bad_widget_payloads_are_rejected(client, auth_headers, payload, reason):
+ resp = client.post('/api/v1/dashboards', headers=auth_headers,
+ json={'name': 'Bad', 'widgets': payload})
+ assert resp.status_code == 400, f'{reason} should be rejected'
+ assert 'error' in resp.get_json()
+
+
+def test_duplicate_widget_ids_are_rejected(client, auth_headers):
+ resp = client.post('/api/v1/dashboards', headers=auth_headers, json={
+ 'name': 'Dupes', 'widgets': [_widget('w1'), _widget('w1', x=3)],
+ })
+ assert resp.status_code == 400
+ assert 'duplicate' in resp.get_json()['error'].lower()
+
+
+def test_oversized_widget_payload_is_rejected(client, auth_headers):
+ huge = [_widget(f'w{n}', x=(n % 4) * 3, y=n) for n in range(101)]
+ resp = client.post('/api/v1/dashboards', headers=auth_headers,
+ json={'name': 'Huge', 'widgets': huge})
+ assert resp.status_code == 400
+ assert '100' in resp.get_json()['error']
+
+
+def test_update_rejects_a_bad_layout_without_touching_the_board(client, auth_headers):
+ boards = client.get('/api/v1/dashboards', headers=auth_headers).get_json()['boards']
+ board = boards[0]
+
+ resp = client.put(f"/api/v1/dashboards/{board['id']}", headers=auth_headers,
+ json={'name': 'Attempted', 'widgets': [{'i': 'w1'}]})
+ assert resp.status_code == 400
+
+ unchanged = client.get('/api/v1/dashboards', headers=auth_headers).get_json()['boards']
+ assert unchanged[0]['name'] == board['name']
+ assert unchanged[0]['widgets'] == board['widgets']
+
+
+def test_widget_cfg_round_trips_verbatim(client, auth_headers):
+ cfg = {'metric': 'cpu', 'agg': 'p95', 'resource': '$server',
+ 'thresholds': [70, 90], 'nested': {'deep': ['a', 1, None]}}
+ created = client.post('/api/v1/dashboards', headers=auth_headers, json={
+ 'name': 'Cfg', 'widgets': [_widget(cfg=cfg)],
+ }).get_json()
+ assert created['widgets'][0]['cfg'] == cfg
+
+ reread = client.get('/api/v1/dashboards', headers=auth_headers).get_json()['boards']
+ assert reread[-1]['widgets'][0]['cfg'] == cfg
diff --git a/frontend/src/services/api/dashboards.js b/frontend/src/services/api/dashboards.js
new file mode 100644
index 00000000..62c076a0
--- /dev/null
+++ b/frontend/src/services/api/dashboards.js
@@ -0,0 +1,36 @@
+// Dashboard board persistence (plan 62).
+// A board is one dashboard tab: { id, slug, name, icon, position, widgets }.
+// Boards are per-user — the backend scopes every call to the caller, and the
+// first getDashboards() of a new account seeds the shipped default boards.
+
+// This user's boards, ordered by position. Seeds the defaults on first call.
+export async function getDashboards() {
+ return this.request('/dashboards');
+}
+
+// Add a board. { name, icon?, widgets? } — a new tab usually starts empty.
+export async function createDashboard(payload) {
+ return this.request('/dashboards', {
+ method: 'POST',
+ body: JSON.stringify(payload),
+ });
+}
+
+// Patch a board. { name?, icon?, position?, widgets? } — this is also how a
+// drag/resize is persisted, by sending the whole widget list back.
+export async function updateDashboard(id, payload) {
+ return this.request(`/dashboards/${id}`, {
+ method: 'PUT',
+ body: JSON.stringify(payload),
+ });
+}
+
+export async function deleteDashboard(id) {
+ return this.request(`/dashboards/${id}`, { method: 'DELETE' });
+}
+
+// Restore a shipped default board (overview / infra / apps). Boards the user
+// created themselves have no default and are refused with a 400.
+export async function resetDashboard(id) {
+ return this.request(`/dashboards/${id}/reset`, { method: 'POST' });
+}
diff --git a/frontend/src/services/api/index.js b/frontend/src/services/api/index.js
index e5408bc1..8214450b 100644
--- a/frontend/src/services/api/index.js
+++ b/frontend/src/services/api/index.js
@@ -45,6 +45,7 @@ import * as dnsCutoverMethods from './dnsCutover.js';
import * as searchMethods from './search.js';
import * as testSandboxMethods from './testSandbox.js';
import * as themeMethods from './themes.js';
+import * as dashboardMethods from './dashboards.js';
class ApiService extends ApiClient {
constructor() {
@@ -97,6 +98,7 @@ class ApiService extends ApiClient {
searchMethods,
testSandboxMethods,
themeMethods,
+ dashboardMethods,
];
for (const mod of modules) {
for (const [key, fn] of Object.entries(mod)) {