diff --git a/README.md b/README.md index c8f4e7e..04caea5 100644 --- a/README.md +++ b/README.md @@ -10,8 +10,8 @@ A self-hosted dashboard for monitoring and controlling multiple TinyPilot device ## What you get -- One web UI that lists your TinyPilot devices, up to four per page, with a live screenshot of the connected system on each card. -- One-click device addition (friendly name + TinyPilot URL + Automation API key). +- One web UI that lists your TinyPilot devices, up to four per page, with a live preview of the connected system on each card (cached in the browser only). +- One-click device addition (friendly name + TinyPilot URL + Automation API key), plus Replace API key on an existing card. - Per-device snapshot of TinyPilot status: connected display resolution, streaming mode (H.264 with bitrate, or MJPEG with framerate and quality), firmware version, network info, and more. - Encrypted at-rest storage for Automation API keys. @@ -131,9 +131,12 @@ If none of those apply to your environment, please **do not run this alpha**. Everything persistent lives in `./data`: - `dashboard.sqlite` — devices and encrypted credentials. -- `screenshots/` — latest screenshot per device. - `secret.key` — the encryption key for the SQLite secrets. +Live previews are **not** stored on the server. The browser keeps the last image per device in Cache Storage (cache name `tinypilot-dashboard-previews-v1`). Clear it with `window.tinypilotPreviewCache.clearPreviewCache()` (for example on sign-out in a host that wraps this dashboard). Cache Storage requires a [secure context](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS or `http://localhost` / `http://127.0.0.1`). On plain `http://:8080`, the API is unavailable: live refresh still works, but cached and offline-with-image states do not persist across reloads. + +Schema migrations use SQLite `DROP COLUMN` (SQLite **3.35** or later). The Docker image is fine; bare-metal hosts on older SQLite need an upgrade before starting 0.4.0 against an existing DB. + **To back up: copy the entire `data/` directory.** `secret.key` must be backed up alongside `dashboard.sqlite` — without it the encrypted columns cannot be recovered. ## Troubleshooting @@ -160,7 +163,7 @@ Source layout and conventions for anyone reading the code or auditing what the d - `templates/index.html` — Jinja shell that loads the `` web component and static assets. - `static/js/dashboard-app.js` — root custom element with shadow DOM: top bar, theme toggle, Add-a-device modal, paging (four devices per page), and a responsive device grid (1 → 2 → 4 columns). - `static/js/components/device-card.js` — one custom element per TinyPilot target. Owns the screenshot controls and the collapsed/expanded TinyPilot snapshot panel. -- `static/js/lib/` — shared helpers (`strings.js`, `snapshot-view.js`). +- `static/js/lib/` — shared helpers (`strings.js`, `snapshot-view.js`, `preview-cache.js`). - `static/js/api.js` — thin `fetch` wrappers attached to `window.dashboardApi`. **Backend** (`app/`) @@ -170,7 +173,6 @@ Source layout and conventions for anyone reading the code or auditing what the d - `db.py` — SQLite connection helper and schema bootstrap. - `tinypilot_client.py` — HTTP client for TinyPilot Automation API-key routes. - `resolution.py` — normalizers for the various shapes TinyPilot uses to report "connected device resolution". -- `snapshot_service.py` — atomic latest-screenshot writer. - `auth_store.py`, `crypto.py` — Fernet-encrypted at-rest secrets. ### TinyPilot APIs the dashboard uses diff --git a/app/__init__.py b/app/__init__.py index 62a561b..27efa97 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -15,7 +15,7 @@ # 0.5.x -> beta # 1.0.0 -> first stable release # Bump this on every customer-visible release. -__version__ = '0.3.0' +__version__ = '0.4.0' def create_app(test_config=None): diff --git a/app/api.py b/app/api.py index 3355e0d..2795776 100644 --- a/app/api.py +++ b/app/api.py @@ -1,7 +1,7 @@ """HTTP API blueprint for the TinyPilot Dashboard. All routes live under the ``/api`` prefix and return JSON (except -``/api/devices//latest-screenshot`` which streams an image). Database +``/api/devices//refresh-screenshot`` which returns a JPEG). Database access goes through ``app.db.get_db``; secrets are read or written through ``app.auth_store`` so they are encrypted at rest. @@ -16,10 +16,10 @@ import requests from flask import Blueprint +from flask import Response from flask import current_app from flask import jsonify from flask import request -from flask import send_file from app.auth_store import decrypt_secret from app.auth_store import encrypt_secret @@ -28,7 +28,6 @@ from app.device_update import update_available from app.resolution import connected_resolution_from_web_ui from app.resolution import resolution_from_automation_state -from app.snapshot_service import write_latest_screenshot from app.tinypilot_client import TinyPilotClient api_blueprint = Blueprint('api', __name__, url_prefix='/api') @@ -91,7 +90,6 @@ def list_devices(): devices.id, devices.friendly_name, devices.base_url, - device_runtime_state.latest_screenshot_captured_at, device_runtime_state.screenshot_refresh_interval_minutes, CASE WHEN device_auth.encrypted_automation_token IS NOT NULL THEN 1 @@ -108,7 +106,6 @@ def list_devices(): 'id': row['id'], 'friendly_name': row['friendly_name'], 'base_url': row['base_url'], - 'latest_screenshot_captured_at': row['latest_screenshot_captured_at'], 'screenshot_refresh_interval_minutes': row['screenshot_refresh_interval_minutes'] or 0, 'api_key_configured': bool(row['api_key_configured']), } @@ -224,36 +221,73 @@ def refresh_screenshot(device_id: int): try: screenshot = client.get_screenshot() + except requests.RequestException as err: + # requests.*Error subclasses often also inherit ValueError; handle first. + return jsonify( + {'error': f'failed to refresh screenshot: {_customer_error(err)}'} + ), 502 + except ValueError as exc: + # TinyPilotClient raises ValueError only for HTTP 204 / empty body. + if 'no screenshot image' not in str(exc): + return jsonify( + {'error': f'failed to refresh screenshot: {_customer_error(exc)}'} + ), 502 + current_app.logger.warning('TinyPilot screenshot no signal: %s', exc) + return jsonify({ + 'error': 'No signal', + 'code': 'no_signal', + }), 502 except Exception as err: # pylint: disable=broad-exception-caught return jsonify( {'error': f'failed to refresh screenshot: {_customer_error(err)}'} ), 502 - db = get_db() - data_root = Path(current_app.config['DATABASE_PATH']).resolve().parent - screenshot_path = write_latest_screenshot(data_root / 'screenshots', device_id, screenshot) captured_at = datetime.now(timezone.utc).isoformat() - db.execute( + response = Response(screenshot, mimetype='image/jpeg') + response.headers['X-Captured-At'] = captured_at + return response + + +@api_blueprint.put('/devices//api-key') +def replace_api_key(device_id: int): + payload = request.get_json(silent=True) or {} + raw_key = payload.get('api_key') + if not isinstance(raw_key, str): + return jsonify({'error': 'api_key is required'}), 400 + api_key = raw_key.strip() + if not api_key: + return jsonify({'error': 'api_key is required'}), 400 + + db = get_db() + existing = db.execute( """ - UPDATE device_runtime_state - SET latest_screenshot_path = ?, latest_screenshot_captured_at = ?, latest_screenshot_error = NULL - WHERE device_id = ? + SELECT id + FROM devices + WHERE id = ? """, - ( - str(screenshot_path), - captured_at, + (device_id,), + ).fetchone() + if existing is None: + return jsonify({'error': 'device not found'}), 404 + + key_path = Path(current_app.config['SECRET_KEY_PATH']) + encrypted = encrypt_secret(key_path, api_key) + now = datetime.now(timezone.utc).isoformat() + db.execute( + """ + INSERT INTO device_auth ( device_id, - ), + encrypted_automation_token, + automation_token_refreshed_at + ) VALUES (?, ?, ?) + ON CONFLICT(device_id) DO UPDATE SET + encrypted_automation_token = excluded.encrypted_automation_token, + automation_token_refreshed_at = excluded.automation_token_refreshed_at + """, + (device_id, encrypted, now), ) db.commit() - return jsonify( - { - 'device_id': device_id, - 'screenshot_refreshed': True, - 'screenshot_path': str(screenshot_path), - 'captured_at': captured_at, - } - ) + return jsonify({'device_id': device_id, 'api_key_configured': True}) @api_blueprint.post('/devices//screenshot-refresh-config') @@ -294,35 +328,6 @@ def set_screenshot_refresh_config(device_id: int): ) -@api_blueprint.get('/devices//latest-screenshot') -def get_latest_screenshot(device_id: int): - row = get_db().execute( - """ - SELECT latest_screenshot_path - FROM device_runtime_state - WHERE device_id = ? - """, - (device_id,), - ).fetchone() - if row is None or not row['latest_screenshot_path']: - return jsonify({'error': 'screenshot not available'}), 404 - - screenshot_path = Path(row['latest_screenshot_path']).resolve() - screenshots_root = ( - Path(current_app.config['DATABASE_PATH']).resolve().parent / 'screenshots' - ).resolve() - # Defense-in-depth: the stored path is dashboard-controlled, but reject - # anything that resolves outside the screenshots directory so a tampered - # database row cannot expose arbitrary files via send_file. - try: - screenshot_path.relative_to(screenshots_root) - except ValueError: - return jsonify({'error': 'screenshot path is outside data directory'}), 404 - if not screenshot_path.is_file(): - return jsonify({'error': 'screenshot file missing'}), 404 - return send_file(screenshot_path, mimetype='image/jpeg') - - def _safe_fetch(fetcher): try: return fetcher(), None diff --git a/app/db.py b/app/db.py index 83120ca..096fa2e 100644 --- a/app/db.py +++ b/app/db.py @@ -12,6 +12,23 @@ from flask import current_app from flask import g +# Columns removed in 0.4.0. Dropped on upgrade; omitted from CREATE for new DBs. +_DROPPED_COLUMNS = ( + ('devices', 'last_seen_at'), + ('devices', 'last_status'), + ('devices', 'role'), + ('device_auth', 'encrypted_automation_license_key'), + ('device_auth', 'encrypted_web_username'), + ('device_auth', 'encrypted_web_password'), + ('device_auth', 'encrypted_csrf_token'), + ('device_auth', 'csrf_refreshed_at'), + ('device_runtime_state', 'latest_screenshot_path'), + ('device_runtime_state', 'latest_screenshot_captured_at'), + ('device_runtime_state', 'latest_screenshot_error'), + ('device_runtime_state', 'last_connection_check_at'), + ('device_runtime_state', 'last_connection_check_error'), +) + def get_db() -> sqlite3.Connection: """Return the per-request SQLite connection, creating it on demand.""" @@ -38,32 +55,19 @@ def init_db() -> None: id INTEGER PRIMARY KEY AUTOINCREMENT, friendly_name TEXT NOT NULL, base_url TEXT NOT NULL, - software_version TEXT, - role TEXT, - last_seen_at TEXT, - last_status TEXT + software_version TEXT ); CREATE TABLE IF NOT EXISTS device_auth ( device_id INTEGER PRIMARY KEY, - encrypted_automation_license_key BLOB, encrypted_automation_token BLOB, automation_token_refreshed_at TEXT, - encrypted_web_username BLOB, - encrypted_web_password BLOB, - encrypted_csrf_token BLOB, - csrf_refreshed_at TEXT, FOREIGN KEY(device_id) REFERENCES devices(id) ); CREATE TABLE IF NOT EXISTS device_runtime_state ( device_id INTEGER PRIMARY KEY, - latest_screenshot_path TEXT, - latest_screenshot_captured_at TEXT, - latest_screenshot_error TEXT, screenshot_refresh_interval_minutes INTEGER NOT NULL DEFAULT 0, - last_connection_check_at TEXT, - last_connection_check_error TEXT, FOREIGN KEY(device_id) REFERENCES devices(id) ); """ @@ -74,6 +78,11 @@ def init_db() -> None: column='screenshot_refresh_interval_minutes', column_def='INTEGER NOT NULL DEFAULT 0', ) + for table, column in _DROPPED_COLUMNS: + _drop_column_if_exists(db, table, column) + _delete_screenshot_files( + Path(current_app.config['DATABASE_PATH']).resolve().parent + ) db.commit() @@ -101,3 +110,26 @@ def _ensure_column( if column in existing_names: return db.execute(f'ALTER TABLE {table} ADD COLUMN {column} {column_def}') + + +def _drop_column_if_exists( + db: sqlite3.Connection, + table: str, + column: str, +) -> None: + """Drop ``column`` from ``table`` when present (SQLite 3.35+).""" + existing = db.execute(f'PRAGMA table_info({table})').fetchall() + existing_names = {row['name'] for row in existing} + if column not in existing_names: + return + db.execute(f'ALTER TABLE {table} DROP COLUMN {column}') + + +def _delete_screenshot_files(data_root: Path) -> None: + """Remove leftover on-disk previews (plaintext or encrypted).""" + shots = data_root / 'screenshots' + if not shots.is_dir(): + return + for path in shots.iterdir(): + if path.is_file(): + path.unlink() diff --git a/app/snapshot_service.py b/app/snapshot_service.py deleted file mode 100644 index 6fbe38a..0000000 --- a/app/snapshot_service.py +++ /dev/null @@ -1,22 +0,0 @@ -"""Atomic write helpers for device screenshots. - -The dashboard stores only the *latest* screenshot per device so the data -directory does not grow unbounded. Writing is two-step (``.tmp`` then atomic -``rename``) so a partially-written file is never visible to readers. -""" - -from pathlib import Path - - -def write_latest_screenshot( - root: Path, - device_id: int, - image_bytes: bytes, -) -> Path: - """Write ``image_bytes`` as the latest screenshot for ``device_id``.""" - root.mkdir(parents=True, exist_ok=True) - tmp_path = root / f'device-{device_id}-latest.jpg.tmp' - latest_path = root / f'device-{device_id}-latest.jpg' - tmp_path.write_bytes(image_bytes) - tmp_path.replace(latest_path) - return latest_path diff --git a/app/static/css/dashboard.css b/app/static/css/dashboard.css index d3631ce..30d822b 100644 --- a/app/static/css/dashboard.css +++ b/app/static/css/dashboard.css @@ -152,6 +152,7 @@ button.button-danger-quiet:hover { } .delete-device-actions, +.replace-api-key-actions, .update-device-actions { margin-top: var(--space-2); align-items: center; @@ -159,6 +160,7 @@ button.button-danger-quiet:hover { } .delete-device-actions button, +.replace-api-key-actions button, .update-device-actions button { margin-top: 0; min-width: 0; @@ -169,6 +171,7 @@ button.button-danger-quiet:hover { } .delete-device-actions #delete-device-cancel, +.replace-api-key-actions #replace-api-key-cancel, .update-device-actions #update-device-cancel { background: transparent; color: var(--color-text); @@ -294,6 +297,88 @@ button.button-danger-quiet:hover { box-shadow: inset 0 0 0 2px color-mix(in srgb, var(--color-warning) 70%, transparent); } +.connected-screenshot.connected-screenshot--offline { + filter: grayscale(1) brightness(0.85); + opacity: 0.85; +} + +.preview-frame { + position: absolute; + inset: 0; + overflow: hidden; + background: #0b1220; +} + +.preview-placeholder { + position: absolute; + inset: 0; + z-index: 1; + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + gap: var(--space-2); + padding: var(--space-4); + text-align: center; + color: var(--color-muted); +} + +/* Author `display: flex` otherwise overrides the hidden attribute and the + spinner stays painted over a successful live/cached . */ +.preview-placeholder[hidden] { + display: none !important; +} + +.preview-placeholder--loading { + background: #0b1220; +} + +/* Offline (no image) and no-signal share the same dark empty well so the + centered label treatment matches; reachability is told by copy, not tint. */ +.preview-placeholder--offline, +.preview-placeholder--no_signal { + background: #05070c; +} + +/* Centered label over a dimmed cached frame (offline with image). */ +.preview-placeholder--overlay { + background: transparent; + pointer-events: none; +} + +.preview-placeholder-title { + margin: 0; + font-size: 1.25rem; + font-weight: 500; + line-height: 1.3; + letter-spacing: 0.01em; + color: var(--color-text); +} + +.preview-placeholder-detail { + margin: 0; + font-size: 0.9rem; + font-weight: 400; + line-height: 1.35; + color: var(--color-muted); +} + +/* Same shape as TinyPilot Pro's progress-spinner, muted for the preview well. */ +.preview-spinner { + width: 3rem; + height: 3rem; + border: 3px solid color-mix(in srgb, var(--color-muted) 35%, transparent); + border-top-color: color-mix(in srgb, var(--color-accent) 70%, var(--color-muted)); + border-radius: 50%; + box-sizing: border-box; + animation: preview-spin 1.5s linear infinite; +} + +@keyframes preview-spin { + 0% { transform: rotate(0deg); } + 100% { transform: rotate(360deg); } +} + .launch-link { color: var(--color-accent); text-decoration: none; @@ -314,6 +399,19 @@ button.button-danger-quiet:hover { color: var(--color-muted); } +/* Modal body copy: same font as other .subtitle text; loosen line breaks + from
and keep steady space above the form. */ +.modal-panel > .subtitle { + margin: 0 0 var(--space-3); + line-height: 1.5; +} + +/* Status line under the form (Save / Remove result): only when it has text. */ +.modal-panel > form + .subtitle:not(:empty) { + margin-top: var(--space-3); + margin-bottom: 0; +} + .connected-system .subtitle { margin: var(--space-2) 0 0; font-size: 0.9rem; diff --git a/app/static/js/api.js b/app/static/js/api.js index f4bf61c..565e229 100644 --- a/app/static/js/api.js +++ b/app/static/js/api.js @@ -24,7 +24,7 @@ async function fetchJson(path, { method = 'GET', body } = {}) { const response = await fetch(path, init); const data = await response.json().catch(() => ({})); if (!response.ok) { - return { error: httpErrorMessage(data, response) }; + return { error: httpErrorMessage(data, response), code: data.code }; } return data; } catch { @@ -48,9 +48,37 @@ async function deleteJson(path) { return fetchJson(path, { method: 'DELETE' }); } +async function postScreenshot(path) { + try { + const response = await fetch(path, { + method: 'POST', + credentials: 'same-origin', + headers: { 'Content-Type': 'application/json' }, + body: '{}', + signal: AbortSignal.timeout(30_000), + }); + const contentType = response.headers.get('Content-Type') || ''; + if (!response.ok) { + const data = await response.json().catch(() => ({})); + return { error: httpErrorMessage(data, response), code: data.code }; + } + if (!contentType.includes('image/jpeg')) { + return { error: 'Unexpected screenshot response' }; + } + const capturedAt = + response.headers.get('X-Captured-At') || new Date().toISOString(); + const cacheCopy = response.clone(); + const blob = await response.blob(); + return { blob, capturedAt, cacheCopy }; + } catch { + return { error: 'Could not reach the dashboard.' }; + } +} + window.dashboardApi = { deleteJson, getJson, postJson, + postScreenshot, putJson, }; diff --git a/app/static/js/components/device-card.js b/app/static/js/components/device-card.js index 191cae0..e7d1749 100644 --- a/app/static/js/components/device-card.js +++ b/app/static/js/components/device-card.js @@ -4,6 +4,7 @@ import { latestVersionFrom, updateBannerKind, } from '../lib/device-update.js'; +import { getPreview, putPreview } from '../lib/preview-cache.js'; const AUTOMATION_LICENSE_INFO_URL = 'https://tinypilotkvm.com/pages/automation'; const UPDATE_POLL_INTERVAL_MS = 3000; @@ -47,24 +48,32 @@ function cachedPreviewCopy(capturedAt) { return `Cached preview from ${formatRelativeTime(capturedAt)}.`; } -function missingPreviewCopy() { - return 'Could not capture a screenshot.'; +function livePreviewCopy(capturedAt) { + return `Live preview, updated ${formatRelativeTime(capturedAt)}.`; } -function setPreviewStatus(el, text, kind) { +function checkedStatusCopy(label, checkedAt) { + const at = checkedAt || new Date().toISOString(); + return `${label}, checked ${formatRelativeTime(at)}.`; +} + +function setPreviewStatus(el, text, kind, checkedAt) { if (!el) { return; } el.textContent = text; - el.classList.toggle( - 'connected-status--caution', - kind === 'cached' || kind === 'error', - ); + // Live stays muted; every other preview status uses the caution (yellow) style. + el.classList.toggle('connected-status--caution', Boolean(kind) && kind !== 'live'); if (kind) { el.dataset.previewKind = kind; } else { delete el.dataset.previewKind; } + if (checkedAt) { + el.dataset.checkedAt = checkedAt; + } else { + delete el.dataset.checkedAt; + } } function renderHeaderOpenWebUi(device) { @@ -85,6 +94,11 @@ class DeviceCard extends HTMLElement { this._elements = {}; this._updatePollTimer = null; this._desiredUpdateVersion = null; + this._online = null; + this._lastChecked = ''; + this._capturedAt = null; + this._objectUrl = null; + this._previewState = 'loading'; } set device(value) { @@ -110,14 +124,24 @@ class DeviceCard extends HTMLElement { disconnectedCallback() { this._stopUpdatePoll(); + this._revokeObjectUrl(); + } + + _revokeObjectUrl() { + if (this._objectUrl) { + URL.revokeObjectURL(this._objectUrl); + this._objectUrl = null; + } } _cacheElements() { const id = this._device.id; this._elements = { + frame: this.querySelector(`#preview-frame-${id}`), screenshot: this.querySelector(`#connected-screenshot-${id}`), link: this.querySelector(`#connected-screenshot-link-${id}`), connectedStatus: this.querySelector(`#connected-status-${id}`), + placeholder: this.querySelector(`#preview-placeholder-${id}`), summaryOutput: this.querySelector(`#device-collapsed-summary-${id}`), metricsOutput: this.querySelector(`#device-metrics-output-${id}`), intervalInput: this.querySelector(`#screenshot-interval-${id}`), @@ -157,11 +181,17 @@ class DeviceCard extends HTMLElement { aria-disabled="true" aria-label="Control ${escapeHtml(device.friendly_name)}" > - Latest screenshot for ${escapeHtml(device.friendly_name)} +
+ + +
@@ -190,6 +220,7 @@ class DeviceCard extends HTMLElement {
+
@@ -204,105 +235,250 @@ class DeviceCard extends HTMLElement { `; this._cacheElements(); - this._primeCachedScreenshot(); + this._showLoadingPlaceholder(); + void this._primeFromCache(); } - _primeCachedScreenshot() { - const device = this._device; - if (!device?.latest_screenshot_captured_at) { + _showLoadingPlaceholder() { + const { screenshot, placeholder, frame } = this._elements; + if (screenshot) { + screenshot.hidden = true; + screenshot.removeAttribute('src'); + screenshot.classList.remove( + 'connected-screenshot--cached', + 'connected-screenshot--offline', + ); + } + if (placeholder) { + placeholder.hidden = false; + placeholder.className = 'preview-placeholder preview-placeholder--loading'; + placeholder.innerHTML = ''; + } + if (frame) { + frame.className = 'preview-frame preview-frame--loading'; + } + this._previewState = 'loading'; + } + + _showPanelPlaceholder(kind, title, detail) { + const { screenshot, placeholder, frame, link } = this._elements; + this._revokeObjectUrl(); + if (screenshot) { + screenshot.hidden = true; + screenshot.removeAttribute('src'); + screenshot.classList.remove( + 'connected-screenshot--cached', + 'connected-screenshot--offline', + ); + } + if (placeholder) { + placeholder.hidden = false; + placeholder.className = `preview-placeholder preview-placeholder--${kind}`; + placeholder.innerHTML = ` +

${escapeHtml(title)}

+ ${detail ? `

${escapeHtml(detail)}

` : ''} + `; + } + if (frame) { + frame.className = `preview-frame preview-frame--${kind}`; + } + deactivateScreenshotLink(link); + this._previewState = kind; + } + + _showCenteredLabel(text) { + const { placeholder } = this._elements; + if (!placeholder) { return; } - const { screenshot, link, connectedStatus } = this._elements; + placeholder.hidden = false; + placeholder.className = 'preview-placeholder preview-placeholder--overlay'; + placeholder.innerHTML = + `

${escapeHtml(text)}

`; + } + + _showImage({ blobUrl, capturedAt, kind }) { + const { screenshot, placeholder, frame, link } = this._elements; if (!screenshot) { return; } - const capturedAt = device.latest_screenshot_captured_at; - const busted = `/api/devices/${device.id}/latest-screenshot?t=${encodeURIComponent(capturedAt)}`; - screenshot.src = busted; - screenshot.classList.add('connected-screenshot--cached'); - if (deviceLaunchHref(device)) { + screenshot.onerror = () => { + screenshot.hidden = true; + screenshot.removeAttribute('src'); + if (this._online === false) { + this._showOfflineEmpty(); + } else { + this._showLoadingPlaceholder(); + } + }; + screenshot.hidden = false; + screenshot.src = blobUrl; + screenshot.classList.toggle('connected-screenshot--cached', kind === 'cached'); + screenshot.classList.toggle('connected-screenshot--offline', kind === 'offline'); + if (kind === 'offline') { + this._showCenteredLabel('Offline'); + } else if (placeholder) { + placeholder.hidden = true; + placeholder.innerHTML = ''; + } + if (frame) { + frame.className = `preview-frame preview-frame--${kind}`; + } + if (deviceLaunchHref(this._device) && kind !== 'offline') { activateScreenshotLink(link); + } else { + deactivateScreenshotLink(link); + } + this._capturedAt = capturedAt; + this._previewState = kind; + if (kind === 'live') { + setPreviewStatus( + this._elements.connectedStatus, + livePreviewCopy(capturedAt), + 'live', + capturedAt, + ); + } else if (kind === 'offline') { + const checkedAt = this._lastChecked || capturedAt || new Date().toISOString(); + setPreviewStatus( + this._elements.connectedStatus, + checkedStatusCopy('Offline', checkedAt), + 'offline', + checkedAt, + ); + } else { + setPreviewStatus( + this._elements.connectedStatus, + cachedPreviewCopy(capturedAt), + 'cached', + capturedAt, + ); } - setPreviewStatus(connectedStatus, cachedPreviewCopy(capturedAt), 'cached'); } - async refreshScreenshot(capturedAtByDevice) { + async _primeFromCache() { if (!this._device) { return; } - const id = this._device.id; - const { screenshot, link, connectedStatus } = this._elements; - - // Do NOT clear screenshot.src here — keep showing the current frame - // until the replacement is ready to avoid a visible blank state. - deactivateScreenshotLink(link); + const cached = await getPreview(this._device.id); + if (!cached || !this.isConnected) { + return; + } + const blob = await cached.blob(); + const capturedAt = + cached.headers.get('X-Captured-At') || new Date().toISOString(); + this._revokeObjectUrl(); + this._objectUrl = URL.createObjectURL(blob); + this._showImage({ + blobUrl: this._objectUrl, + capturedAt, + kind: 'cached', + }); + } - const result = await window.dashboardApi.postJson(`/api/devices/${id}/refresh-screenshot`); - const cachedAt = - capturedAtByDevice.get(String(id)) || - this._device.latest_screenshot_captured_at; - const enableLaunch = () => { - if (deviceLaunchHref(this._device)) { - activateScreenshotLink(link); - } - }; + _showOfflineEmpty(checkedAt) { + const at = checkedAt || this._lastChecked || new Date().toISOString(); + this._showPanelPlaceholder('offline', 'Offline', ''); + setPreviewStatus( + this._elements.connectedStatus, + checkedStatusCopy('Offline', at), + 'offline', + at, + ); + } - if (result.error || !screenshot) { - if (cachedAt) { - screenshot?.classList.add('connected-screenshot--cached'); - enableLaunch(); - setPreviewStatus( - connectedStatus, - cachedPreviewCopy(cachedAt), - 'cached', - ); + _syncPreviewState() { + if (this._previewState === 'no_signal' && this._online !== false) { + return; + } + if (this._online === false) { + if (this._objectUrl) { + this._showImage({ + blobUrl: this._objectUrl, + capturedAt: this._capturedAt || new Date().toISOString(), + kind: 'offline', + }); } else { - setPreviewStatus(connectedStatus, missingPreviewCopy(), 'error'); + this._showOfflineEmpty(); } return; } + if (this._previewState === 'offline' && this._objectUrl) { + this._showImage({ + blobUrl: this._objectUrl, + capturedAt: this._capturedAt || new Date().toISOString(), + kind: 'cached', + }); + } + } + + async refreshScreenshot(capturedAtByDevice) { + if (!this._device) { + return; + } + const id = this._device.id; + const { link } = this._elements; + deactivateScreenshotLink(link); + + if (!this._objectUrl) { + this._showLoadingPlaceholder(); + } - capturedAtByDevice.set(String(id), result.captured_at || new Date().toISOString()); - const busted = `/api/devices/${id}/latest-screenshot?t=${Date.now()}`; + const result = await window.dashboardApi.postScreenshot( + `/api/devices/${id}/refresh-screenshot`, + ); - const markLive = () => { - screenshot.classList.remove('connected-screenshot--cached'); - enableLaunch(); + if (result.code === 'no_signal') { + const checkedAt = this._lastChecked || new Date().toISOString(); + this._showPanelPlaceholder('no_signal', 'No signal', ''); setPreviewStatus( - connectedStatus, - `Live preview, updated ${formatRelativeTime(result.captured_at)}.`, - 'live', + this._elements.connectedStatus, + checkedStatusCopy('No signal', checkedAt), + 'no_signal', + checkedAt, ); - }; + return; + } - // Pre-load into an off-screen Image. Only swap the displayed src - // after the browser has fully decoded the new frame so it never goes blank. - const preload = new Image(); - preload.onload = () => { - screenshot.src = busted; - markLive(); - }; - preload.onerror = () => { - if (cachedAt) { - screenshot.classList.add('connected-screenshot--cached'); - enableLaunch(); + if (result.error || !result.blob) { + if (this._objectUrl) { + const kind = this._online === false ? 'offline' : 'cached'; + this._showImage({ + blobUrl: this._objectUrl, + capturedAt: this._capturedAt || new Date().toISOString(), + kind, + }); + } else if (this._online === false) { + this._showOfflineEmpty(); + } else { + const checkedAt = new Date().toISOString(); + this._showLoadingPlaceholder(); setPreviewStatus( - connectedStatus, - cachedPreviewCopy(cachedAt), - 'cached', + this._elements.connectedStatus, + result.error || 'Could not capture a screenshot.', + 'error', + checkedAt, ); - } else { - setPreviewStatus(connectedStatus, missingPreviewCopy(), 'error'); - deactivateScreenshotLink(link); } - }; - preload.src = busted; + return; + } - // If already cached, onload may have fired synchronously — handle that case. - if (preload.complete && preload.naturalWidth > 0 && screenshot.src !== busted) { - screenshot.src = busted; - markLive(); + if (result.cacheCopy) { + try { + await putPreview(id, result.cacheCopy); + } catch { + // Cache Storage is best-effort; live image still shows. + } } + + capturedAtByDevice.set(String(id), result.capturedAt); + this._revokeObjectUrl(); + this._objectUrl = URL.createObjectURL(result.blob); + this._showImage({ + blobUrl: this._objectUrl, + capturedAt: result.capturedAt, + kind: 'live', + }); } _setExpandedVisible(visible) { @@ -326,6 +502,9 @@ class DeviceCard extends HTMLElement { const { summaryOutput, metricsOutput } = this._elements; const snapshot = await window.dashboardApi.getJson(`/api/devices/${id}/device/snapshot`); const online = Boolean(snapshot.collapsed?.online); + this._online = snapshot.error ? false : online; + this._lastChecked = snapshot.collapsed?.last_checked || ''; + this._syncPreviewState(); if (summaryOutput) { if (snapshot.error) { diff --git a/app/static/js/dashboard-app.js b/app/static/js/dashboard-app.js index 0102668..352669b 100644 --- a/app/static/js/dashboard-app.js +++ b/app/static/js/dashboard-app.js @@ -1,13 +1,16 @@ import './components/device-card.js'; import { formatRelativeTime } from './lib/strings.js'; +// preview-cache.js (imported via device-card) sets window.tinypilotPreviewCache. const ADD_DEVICE_TOGGLE_LABEL = 'Add a device'; const ADD_DEVICE_MODAL_LABEL = 'Add a TinyPilot device'; const ADD_DEVICE_SUBMIT_LABEL = 'Add device'; const DELETE_DEVICE_MODAL_LABEL = 'Remove device'; +const REPLACE_API_KEY_MODAL_LABEL = 'Replace API key'; const UPDATE_DEVICE_MODAL_LABEL = 'Update TinyPilot'; const DEVICES_PER_PAGE = 4; const CONNECTED_STATUS_REFRESH_INTERVAL_MS = 30_000; +const DEVICE_SNAPSHOT_REFRESH_INTERVAL_MS = 5 * 60 * 1000; class DashboardApp extends HTMLElement { constructor() { @@ -16,9 +19,11 @@ class DashboardApp extends HTMLElement { this._allDevices = []; this._currentPage = 1; this._pendingDeleteDeviceId = null; + this._pendingReplaceApiKeyDeviceId = null; this._pendingUpdateCard = null; this._screenshotAutoRefreshTimers = new Map(); this._screenshotCapturedAtByDevice = new Map(); + this._snapshotAutoRefreshTimer = null; } connectedCallback() { @@ -72,7 +77,7 @@ class DashboardApp extends HTMLElement {

${DELETE_DEVICE_MODAL_LABEL}

-

Type REMOVE to remove this device from your Dashboard.
You will need to add it again from the device.

+

Type REMOVE to remove this device from your Dashboard.

+ ', 1)[0] + assert 'Replace API key' in actions + assert 'Remove device' in actions + assert actions.index('Replace API key') < actions.index('Remove device') def test_device_card_open_webui_header_and_remove_label(): @@ -73,7 +102,7 @@ def test_device_card_keeps_cached_preview_copy(): assert ' · ' not in app assert 'Could not capture a screenshot.' in source assert "kind === 'cached'" in source - assert '_primeCachedScreenshot' in source + assert '_primeFromCache' in source def test_tinypilot_device_heading_matches_target_system(): @@ -160,7 +189,7 @@ def test_screenshot_click_opens_device_webui(): assert 'Open latest screenshot in new tab' not in source assert 'aria-label="Control ${escapeHtml(device.friendly_name)}"' in source assert 'href="/api/devices/${id}/latest-screenshot"' not in source - assert 'latest-screenshot' in source + assert 'latest-screenshot' not in source assert 'device.base_url' in source link = source.split('id="connected-screenshot-link-${id}"', 1)[1] link = link.split('>', 1)[0] diff --git a/tests/test_replace_api_key.py b/tests/test_replace_api_key.py new file mode 100644 index 0000000..a4ae539 --- /dev/null +++ b/tests/test_replace_api_key.py @@ -0,0 +1,81 @@ +"""Replace API key endpoint.""" + +from unittest.mock import patch + + +def test_replace_api_key_updates_secret_without_echo(client): + create = client.post('/api/devices', json={ + 'friendly_name': 'Rack', + 'base_url': 'https://192.168.1.9', + 'api_key': 'old-key', + }) + device_id = create.json['device']['id'] + response = client.put( + f'/api/devices/{device_id}/api-key', + json={'api_key': 'new-key'}, + ) + assert response.status_code == 200 + assert response.json == { + 'device_id': device_id, + 'api_key_configured': True, + } + body = response.get_data(as_text=True) + assert 'new-key' not in body + assert 'old-key' not in body + + with patch('app.api.TinyPilotClient') as client_cls: + tp = client_cls.return_value + tp.get_status.return_value = {'ok': True} + tp.get_version.return_value = {'version': '3.2.0'} + tp.get_network_status.return_value = {'interfaces': []} + tp.get_video_settings.return_value = {} + tp.get_automation_state.return_value = {} + tp.get_latest_release.return_value = { + 'version': '3.2.0', + 'kind': 'automatic', + 'data': None, + 'licenseCheckStatus': 'VALID', + } + tp.get_update_status.return_value = { + 'status': 'NOT_RUNNING', + 'updateError': None, + } + snap = client.get(f'/api/devices/{device_id}/device/snapshot') + + assert snap.status_code == 200 + _args, kwargs = client_cls.call_args + assert kwargs.get('api_key') == 'new-key' + + +def test_replace_api_key_rejects_blank(client): + create = client.post('/api/devices', json={ + 'friendly_name': 'Rack', + 'base_url': 'https://192.168.1.10', + 'api_key': 'old-key', + }) + device_id = create.json['device']['id'] + response = client.put( + f'/api/devices/{device_id}/api-key', + json={'api_key': ' '}, + ) + assert response.status_code == 400 + + +def test_replace_api_key_rejects_non_string(client): + create = client.post('/api/devices', json={ + 'friendly_name': 'Rack', + 'base_url': 'https://192.168.1.11', + 'api_key': 'old-key', + }) + device_id = create.json['device']['id'] + response = client.put( + f'/api/devices/{device_id}/api-key', + json={'api_key': 12345}, + ) + assert response.status_code == 400 + assert response.json['error'] == 'api_key is required' + + +def test_replace_api_key_unknown_device(client): + response = client.put('/api/devices/9999/api-key', json={'api_key': 'x'}) + assert response.status_code == 404 diff --git a/tests/test_snapshot_service.py b/tests/test_snapshot_service.py deleted file mode 100644 index a16d703..0000000 --- a/tests/test_snapshot_service.py +++ /dev/null @@ -1,11 +0,0 @@ -from app.snapshot_service import write_latest_screenshot - - -def test_atomic_latest_screenshot_write(tmp_path): - screenshots_dir = tmp_path / 'screenshots' - - result = write_latest_screenshot(screenshots_dir, 7, b'jpeg-data') - - assert result.name == 'device-7-latest.jpg' - assert result.exists() - assert not (screenshots_dir / 'device-7-latest.jpg.tmp').exists()