From 681232f7de356571f1c6e6a41dfd43a74c9162a7 Mon Sep 17 00:00:00 2001 From: Scott Halver <76669202+scott-tp@users.noreply.github.com> Date: Tue, 10 Nov 2026 18:05:02 -0500 Subject: [PATCH 01/12] Stop storing previews and add Replace API key Match the privacy promise: live screenshots stay in the browser Cache Storage, unused schema columns drop on init, and device cards can replace an Automation API key without removing the device. --- README.md | 10 +- app/__init__.py | 2 +- app/api.py | 117 +++---- app/db.py | 60 +++- app/snapshot_service.py | 22 -- app/static/css/dashboard.css | 113 +++++++ app/static/js/api.js | 30 +- app/static/js/components/device-card.js | 404 +++++++++++++++++++----- app/static/js/dashboard-app.js | 19 +- app/static/js/lib/preview-cache.js | 32 ++ tests/test_api_connections.py | 69 ++-- tests/test_db_schema_cleanup.py | 103 ++++++ tests/test_preview_cache_js.py | 33 ++ tests/test_remove_device_ui.py | 4 +- tests/test_replace_api_key.py | 66 ++++ tests/test_snapshot_service.py | 11 - 16 files changed, 866 insertions(+), 229 deletions(-) delete mode 100644 app/snapshot_service.py create mode 100644 app/static/js/lib/preview-cache.js create mode 100644 tests/test_db_schema_cleanup.py create mode 100644 tests/test_preview_cache_js.py create mode 100644 tests/test_replace_api_key.py delete mode 100644 tests/test_snapshot_service.py diff --git a/README.md b/README.md index c8f4e7e..38d4090 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,10 @@ 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). + **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 +161,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 +171,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..5e9821b 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,77 @@ def refresh_screenshot(device_id: int): try: screenshot = client.get_screenshot() + except ValueError as exc: + # TinyPilotClient raises ValueError for HTTP 204 / empty body (no signal). + current_app.logger.warning('TinyPilot screenshot no signal: %s', exc) + return jsonify({ + 'error': 'No signal from computer', + '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 {} + api_key = (payload.get('api_key') or '').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 + SELECT id + FROM devices + WHERE id = ? + """, + (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() + auth = db.execute( + """ + SELECT device_id + FROM device_auth WHERE device_id = ? """, - ( - str(screenshot_path), - captured_at, - device_id, - ), - ) + (device_id,), + ).fetchone() + if auth is None: + db.execute( + """ + INSERT INTO device_auth ( + device_id, + encrypted_automation_token, + automation_token_refreshed_at + ) VALUES (?, ?, ?) + """, + (device_id, encrypted, now), + ) + else: + db.execute( + """ + UPDATE device_auth + SET encrypted_automation_token = ?, + automation_token_refreshed_at = ? + WHERE device_id = ? + """, + (encrypted, now, device_id), + ) 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 +332,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..81c7c22 100644 --- a/app/static/css/dashboard.css +++ b/app/static/css/dashboard.css @@ -294,6 +294,119 @@ 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-offline-badge { + position: absolute; + top: 0.6rem; + left: 0.6rem; + z-index: 2; + padding: 0.15rem 0.45rem; + font-size: 0.75rem; + font-weight: 600; + letter-spacing: 0.02em; + color: #0b1220; + background: color-mix(in srgb, var(--color-warning) 85%, white); +} + +.preview-placeholder { + position: absolute; + inset: 0; + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + gap: 0.4rem; + padding: 1rem; + text-align: center; + color: color-mix(in srgb, var(--color-text) 70%, transparent); +} + +.preview-placeholder--shimmer { + background: linear-gradient( + 110deg, + #1a2233 25%, + #243049 37%, + #1a2233 63% + ); + background-size: 200% 100%; + animation: preview-shimmer 1.4s ease-in-out infinite; +} + +.preview-placeholder--offline { + background: #1a2233; + color: color-mix(in srgb, var(--color-text) 75%, transparent); +} + +.preview-placeholder--no_signal { + background: #05070c; + color: color-mix(in srgb, var(--color-text) 80%, transparent); +} + +.preview-placeholder-title { + margin: 0; + font-size: 0.95rem; + font-weight: 600; +} + +.preview-placeholder-detail { + margin: 0; + font-size: 0.8rem; + opacity: 0.85; +} + +.preview-monitor-icon { + width: 3rem; + height: 2.25rem; + opacity: 0.7; +} + +@keyframes preview-shimmer { + 0% { background-position: 200% 0; } + 100% { background-position: -200% 0; } +} + +.replace-api-key-details { + margin-top: var(--space-3); +} + +.replace-api-key-details summary { + cursor: pointer; + font-weight: 600; +} + +.actions-replace-api-key { + margin-top: var(--space-2); + align-items: center; +} + +.replace-api-key-input { + flex: 1 1 12rem; + min-width: 0; +} + +.sr-only { + position: absolute; + width: 1px; + height: 1px; + padding: 0; + margin: -1px; + overflow: hidden; + clip: rect(0, 0, 0, 0); + white-space: nowrap; + border: 0; +} + .launch-link { color: var(--color-accent); text-decoration: none; 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..8335e24 100644 --- a/app/static/js/components/device-card.js +++ b/app/static/js/components/device-card.js @@ -4,11 +4,19 @@ 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; const UPDATE_POLL_MAX_ERRORS = 10; +const MONITOR_SVG = ` + +`; + function formatCollapsedSnapshotSummary(c) { const checkedAt = c.last_checked || ''; const checkedText = formatRelativeTime(checkedAt); @@ -47,8 +55,8 @@ 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) { @@ -58,7 +66,7 @@ function setPreviewStatus(el, text, kind) { el.textContent = text; el.classList.toggle( 'connected-status--caution', - kind === 'cached' || kind === 'error', + kind === 'cached' || kind === 'error' || kind === 'offline' || kind === 'no_signal', ); if (kind) { el.dataset.previewKind = kind; @@ -85,6 +93,12 @@ class DeviceCard extends HTMLElement { this._elements = {}; this._updatePollTimer = null; this._desiredUpdateVersion = null; + this._online = null; + this._lastChecked = ''; + this._capturedAt = null; + this._hasCachedImage = false; + this._objectUrl = null; + this._previewState = 'loading'; } set device(value) { @@ -110,18 +124,31 @@ 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}`), + offlineBadge: this.querySelector(`#preview-offline-badge-${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}`), expandedDetails: this.querySelector(`#device-details-${id}`), + replaceKeyInput: this.querySelector(`#replace-api-key-${id}`), + replaceKeyStatus: this.querySelector(`#replace-api-key-status-${id}`), }; } @@ -157,11 +184,16 @@ class DeviceCard extends HTMLElement { aria-disabled="true" aria-label="Control ${escapeHtml(device.friendly_name)}" > - Latest screenshot for ${escapeHtml(device.friendly_name)} +
+ + + +
@@ -199,110 +231,325 @@ class DeviceCard extends HTMLElement { Expanded TinyPilot device info
+
+ Replace API key +

Create a key on the device under System → Automation, then paste it here.

+
+ + + +
+

+
`; this._cacheElements(); - this._primeCachedScreenshot(); + this._showLoadingPlaceholder(); + void this._primeFromCache(); } - _primeCachedScreenshot() { - const device = this._device; - if (!device?.latest_screenshot_captured_at) { - return; + _showLoadingPlaceholder() { + const { screenshot, placeholder, offlineBadge, 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--shimmer'; + placeholder.innerHTML = ''; + } + if (offlineBadge) { + offlineBadge.hidden = true; + } + if (frame) { + frame.className = 'preview-frame preview-frame--loading'; } - const { screenshot, link, connectedStatus } = this._elements; + this._previewState = 'loading'; + } + + _showPanelPlaceholder(kind, title, detail) { + const { screenshot, placeholder, offlineBadge, 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 = ` + ${MONITOR_SVG} +

${escapeHtml(title)}

+ ${detail ? `

${escapeHtml(detail)}

` : ''} + `; + } + if (offlineBadge) { + offlineBadge.hidden = kind !== 'offline'; + } + if (frame) { + frame.className = `preview-frame preview-frame--${kind}`; + } + deactivateScreenshotLink(link); + this._previewState = kind; + } + + _showImage({ blobUrl, capturedAt, kind }) { + const { screenshot, placeholder, offlineBadge, 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._showPanelPlaceholder( + 'offline', + 'Device offline', + this._lastChecked + ? `Last checked ${formatRelativeTime(this._lastChecked)}` + : '', + ); + setPreviewStatus( + this._elements.connectedStatus, + this._lastChecked + ? `Last checked ${formatRelativeTime(this._lastChecked)}.` + : 'Device offline', + 'offline', + ); + } 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 (placeholder) { + placeholder.hidden = true; + placeholder.innerHTML = ''; + } + if (offlineBadge) { + offlineBadge.hidden = kind !== 'offline'; + } + if (frame) { + frame.className = `preview-frame preview-frame--${kind}`; + } + if (deviceLaunchHref(this._device)) { activateScreenshotLink(link); } - setPreviewStatus(connectedStatus, cachedPreviewCopy(capturedAt), 'cached'); + this._capturedAt = capturedAt; + this._hasCachedImage = true; + this._previewState = kind; + if (kind === 'live') { + setPreviewStatus( + this._elements.connectedStatus, + livePreviewCopy(capturedAt), + 'live', + ); + } else if (kind === 'offline') { + setPreviewStatus( + this._elements.connectedStatus, + this._lastChecked + ? `Last seen ${formatRelativeTime(this._lastChecked)}.` + : 'Offline', + 'offline', + ); + } else { + setPreviewStatus( + this._elements.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 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); - } - }; + 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', + }); + } - if (result.error || !screenshot) { - if (cachedAt) { - screenshot?.classList.add('connected-screenshot--cached'); - enableLaunch(); + _syncPreviewState() { + if (this._previewState === 'no_signal' && this._online !== false) { + return; + } + if (this._online === false) { + if (this._hasCachedImage && this._objectUrl) { + this._showImage({ + blobUrl: this._objectUrl, + capturedAt: this._capturedAt || new Date().toISOString(), + kind: 'offline', + }); + } else if (!this._hasCachedImage) { + this._showPanelPlaceholder( + 'offline', + 'Device offline', + this._lastChecked + ? `Last checked ${formatRelativeTime(this._lastChecked)}` + : '', + ); setPreviewStatus( - connectedStatus, - cachedPreviewCopy(cachedAt), - 'cached', + this._elements.connectedStatus, + this._lastChecked + ? `Last checked ${formatRelativeTime(this._lastChecked)}.` + : 'Device offline', + 'offline', ); - } else { - setPreviewStatus(connectedStatus, missingPreviewCopy(), 'error'); } return; } + if (this._previewState === 'offline' && this._hasCachedImage && this._objectUrl) { + this._showImage({ + blobUrl: this._objectUrl, + capturedAt: this._capturedAt || new Date().toISOString(), + kind: 'cached', + }); + } + } - capturedAtByDevice.set(String(id), result.captured_at || new Date().toISOString()); - const busted = `/api/devices/${id}/latest-screenshot?t=${Date.now()}`; + async refreshScreenshot(capturedAtByDevice) { + if (!this._device) { + return; + } + const id = this._device.id; + const { link } = this._elements; + deactivateScreenshotLink(link); - const markLive = () => { - screenshot.classList.remove('connected-screenshot--cached'); - enableLaunch(); + if (!this._hasCachedImage) { + this._showLoadingPlaceholder(); + } + + const result = await window.dashboardApi.postScreenshot( + `/api/devices/${id}/refresh-screenshot`, + ); + + if (result.code === 'no_signal') { + this._showPanelPlaceholder('no_signal', 'No signal from computer', ''); setPreviewStatus( - connectedStatus, - `Live preview, updated ${formatRelativeTime(result.captured_at)}.`, - 'live', + this._elements.connectedStatus, + 'No signal from computer', + 'no_signal', ); - }; + 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._hasCachedImage && 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._showPanelPlaceholder( + 'offline', + 'Device offline', + this._lastChecked + ? `Last checked ${formatRelativeTime(this._lastChecked)}` + : '', + ); setPreviewStatus( - connectedStatus, - cachedPreviewCopy(cachedAt), - 'cached', + this._elements.connectedStatus, + this._lastChecked + ? `Last checked ${formatRelativeTime(this._lastChecked)}.` + : 'Device offline', + 'offline', ); } else { - setPreviewStatus(connectedStatus, missingPreviewCopy(), 'error'); - deactivateScreenshotLink(link); + this._showLoadingPlaceholder(); + setPreviewStatus( + this._elements.connectedStatus, + result.error || 'Could not capture a screenshot.', + 'error', + ); } - }; - preload.src = busted; + return; + } + + if (result.cacheCopy) { + try { + await putPreview(id, result.cacheCopy); + } catch { + // Cache Storage is best-effort; live image still shows. + } + } - // If already cached, onload may have fired synchronously — handle that case. - if (preload.complete && preload.naturalWidth > 0 && screenshot.src !== busted) { - screenshot.src = busted; - markLive(); + capturedAtByDevice.set(String(id), result.capturedAt); + this._revokeObjectUrl(); + this._objectUrl = URL.createObjectURL(result.blob); + this._showImage({ + blobUrl: this._objectUrl, + capturedAt: result.capturedAt, + kind: 'live', + }); + } + + async replaceApiKey() { + if (!this._device) { + return false; + } + const { replaceKeyInput, replaceKeyStatus } = this._elements; + const apiKey = (replaceKeyInput?.value || '').trim(); + if (!apiKey) { + if (replaceKeyStatus) { + replaceKeyStatus.textContent = 'Enter a new API key.'; + } + return false; + } + if (replaceKeyStatus) { + replaceKeyStatus.textContent = 'Saving…'; + } + const result = await window.dashboardApi.putJson( + `/api/devices/${this._device.id}/api-key`, + { api_key: apiKey }, + ); + if (replaceKeyInput) { + replaceKeyInput.value = ''; + } + if (result.error) { + if (replaceKeyStatus) { + replaceKeyStatus.textContent = result.error; + } + return false; + } + if (replaceKeyStatus) { + replaceKeyStatus.textContent = 'API key updated.'; } + await this.refreshSnapshot(); + return true; } _setExpandedVisible(visible) { @@ -326,6 +573,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..85d359f 100644 --- a/app/static/js/dashboard-app.js +++ b/app/static/js/dashboard-app.js @@ -1,5 +1,12 @@ import './components/device-card.js'; import { formatRelativeTime } from './lib/strings.js'; +import { clearPreviewCache, PREVIEW_CACHE_NAME } from './lib/preview-cache.js'; + +// Re-export for Cloud gateway sign-out (and any host page that clears previews). +window.tinypilotPreviewCache = window.tinypilotPreviewCache || { + PREVIEW_CACHE_NAME, + clearPreviewCache, +}; const ADD_DEVICE_TOGGLE_LABEL = 'Add a device'; const ADD_DEVICE_MODAL_LABEL = 'Add a TinyPilot device'; @@ -381,6 +388,13 @@ class DashboardApp extends HTMLElement { await card.refreshScreenshot(this._screenshotCapturedAtByDevice); return; } + if (action === 'replace-api-key') { + const replaced = await card.replaceApiKey(); + if (replaced) { + await card.refreshScreenshot(this._screenshotCapturedAtByDevice); + } + return; + } if (action === 'save-screenshot-interval') { const input = card.querySelector(`#screenshot-interval-${deviceId}`); const interval = Number.parseInt(input?.value || '0', 10); @@ -551,11 +565,6 @@ class DashboardApp extends HTMLElement { return; } this._allDevices = payload.devices; - for (const device of this._allDevices) { - if (device.latest_screenshot_captured_at) { - this._screenshotCapturedAtByDevice.set(String(device.id), device.latest_screenshot_captured_at); - } - } const totalPages = this._totalPages(); this._currentPage = Math.min(this._currentPage, totalPages); this._renderCurrentPage(); diff --git a/app/static/js/lib/preview-cache.js b/app/static/js/lib/preview-cache.js new file mode 100644 index 0000000..9a40e89 --- /dev/null +++ b/app/static/js/lib/preview-cache.js @@ -0,0 +1,32 @@ +/** Browser Cache Storage for the last live preview per device (origin-scoped). */ + +export const PREVIEW_CACHE_NAME = 'tinypilot-dashboard-previews-v1'; + +function previewRequest(deviceId) { + return new Request(`/device-preview/${deviceId}`); +} + +export async function putPreview(deviceId, response) { + if (!('caches' in window)) { + return; + } + const cache = await caches.open(PREVIEW_CACHE_NAME); + await cache.put(previewRequest(deviceId), response); +} + +export async function getPreview(deviceId) { + if (!('caches' in window)) { + return null; + } + const cache = await caches.open(PREVIEW_CACHE_NAME); + return cache.match(previewRequest(deviceId)); +} + +export async function clearPreviewCache() { + if (!('caches' in window)) { + return false; + } + return caches.delete(PREVIEW_CACHE_NAME); +} + +window.tinypilotPreviewCache = { PREVIEW_CACHE_NAME, clearPreviewCache }; diff --git a/tests/test_api_connections.py b/tests/test_api_connections.py index 0a62dc8..e084406 100644 --- a/tests/test_api_connections.py +++ b/tests/test_api_connections.py @@ -1,3 +1,4 @@ +from pathlib import Path from unittest.mock import patch import requests @@ -95,7 +96,7 @@ def test_delete_device_removes_device_and_related_rows(client): assert all(device['id'] != device_id for device in list_response.json['devices']) -def test_refresh_screenshot_endpoint(client): +def test_refresh_screenshot_endpoint(client, tmp_path): create_payload = { 'friendly_name': 'Screenshot Device', 'base_url': 'https://192.168.1.51', @@ -110,14 +111,39 @@ def test_refresh_screenshot_endpoint(client): response = client.post(f'/api/devices/{device_id}/refresh-screenshot') assert response.status_code == 200 - assert response.json['screenshot_refreshed'] is True - assert response.json['screenshot_path'].endswith(f'device-{device_id}-latest.jpg') + assert response.content_type.startswith('image/jpeg') + assert response.data == b'jpeg-bytes' + assert response.headers.get('X-Captured-At') _args, kwargs = client_cls.call_args assert kwargs.get('api_key') == 'test-api-key' - screenshot_response = client.get(f'/api/devices/{device_id}/latest-screenshot') - assert screenshot_response.status_code == 200 - assert screenshot_response.data == b'jpeg-bytes' + db_parent = Path(client.application.config['DATABASE_PATH']).parent + shots = db_parent / 'screenshots' + assert not shots.exists() or list(shots.glob('*')) == [] + + gone = client.get(f'/api/devices/{device_id}/latest-screenshot') + assert gone.status_code == 404 + + +def test_refresh_screenshot_no_signal_code(client): + create_payload = { + 'friendly_name': 'No Signal Device', + 'base_url': 'https://192.168.1.52', + 'api_key': 'test-api-key', + } + create_response = client.post('/api/devices', json=create_payload) + device_id = create_response.json['device']['id'] + + with patch('app.api.TinyPilotClient') as client_cls: + client_cls.return_value.get_screenshot.side_effect = ValueError( + 'TinyPilot returned no screenshot image (HTTP 204 or empty body); ' + 'often means no video signal from the target.', + ) + response = client.post(f'/api/devices/{device_id}/refresh-screenshot') + + assert response.status_code == 502 + assert response.json['code'] == 'no_signal' + assert response.json['error'] == 'No signal from computer' def test_set_screenshot_refresh_interval_endpoint(client): @@ -250,37 +276,6 @@ def test_device_snapshot_prefers_automation_state_resolution(client): tp_client.get_automation_state.assert_called_once_with() -def test_latest_screenshot_rejects_paths_outside_screenshots_dir(client, tmp_path): - create_payload = { - 'friendly_name': 'Path Test', - 'base_url': 'https://192.168.1.80', - 'api_key': 'test-api-key', - } - create_response = client.post('/api/devices', json=create_payload) - device_id = create_response.json['device']['id'] - - rogue_path = tmp_path / 'rogue.jpg' - rogue_path.write_bytes(b'should-not-be-served') - - with client.application.app_context(): - from app.db import get_db - db = get_db() - db.execute( - """ - UPDATE device_runtime_state - SET latest_screenshot_path = ? - WHERE device_id = ? - """, - (str(rogue_path), device_id), - ) - db.commit() - - response = client.get(f'/api/devices/{device_id}/latest-screenshot') - - assert response.status_code == 404 - assert response.data != b'should-not-be-served' - - def test_refresh_screenshot_surfaces_api_errors(client): create_payload = { 'friendly_name': 'Retry Device', diff --git a/tests/test_db_schema_cleanup.py b/tests/test_db_schema_cleanup.py new file mode 100644 index 0000000..b10934a --- /dev/null +++ b/tests/test_db_schema_cleanup.py @@ -0,0 +1,103 @@ +"""Schema cleanup: drop unused columns and clear leftover screenshot files.""" + +import sqlite3 +from pathlib import Path + +from app import create_app +from app.db import get_db +from app.db import init_db + +DROPPED = { + 'devices': {'last_seen_at', 'last_status', 'role'}, + 'device_auth': { + 'encrypted_automation_license_key', + 'encrypted_web_username', + 'encrypted_web_password', + 'encrypted_csrf_token', + 'csrf_refreshed_at', + }, + 'device_runtime_state': { + 'latest_screenshot_path', + 'latest_screenshot_captured_at', + 'latest_screenshot_error', + 'last_connection_check_at', + 'last_connection_check_error', + }, +} + + +def _columns(db, table): + return {row['name'] for row in db.execute(f'PRAGMA table_info({table})')} + + +def test_init_db_drops_legacy_columns_and_is_idempotent(tmp_path): + db_path = tmp_path / 'dashboard.sqlite' + conn = sqlite3.connect(db_path) + conn.executescript( + """ + CREATE TABLE devices ( + id INTEGER PRIMARY KEY, + friendly_name TEXT NOT NULL, + base_url TEXT NOT NULL, + software_version TEXT, + role TEXT, + last_seen_at TEXT, + last_status TEXT + ); + CREATE TABLE 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 + ); + CREATE TABLE 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 + ); + """ + ) + conn.commit() + conn.close() + + shots = tmp_path / 'screenshots' + shots.mkdir() + (shots / 'device-1-latest.jpg').write_bytes(b'x') + (shots / 'device-1-latest.jpg.enc').write_bytes(b'y') + + app = create_app({ + 'TESTING': True, + 'DATABASE_PATH': str(db_path), + 'SECRET_KEY_PATH': str(tmp_path / 'secret.key'), + }) + with app.app_context(): + for table, cols in DROPPED.items(): + assert cols.isdisjoint(_columns(get_db(), table)) + init_db() + for table, cols in DROPPED.items(): + assert cols.isdisjoint(_columns(get_db(), table)) + assert list(shots.glob('*')) == [] + + +def test_fresh_schema_omits_dropped_columns(tmp_path): + db_path = tmp_path / 'dashboard.sqlite' + app = create_app({ + 'TESTING': True, + 'DATABASE_PATH': str(db_path), + 'SECRET_KEY_PATH': str(tmp_path / 'secret.key'), + }) + with app.app_context(): + for table, cols in DROPPED.items(): + assert cols.isdisjoint(_columns(get_db(), table)) + assert 'screenshot_refresh_interval_minutes' in _columns( + get_db(), 'device_runtime_state' + ) + assert 'encrypted_automation_token' in _columns(get_db(), 'device_auth') diff --git a/tests/test_preview_cache_js.py b/tests/test_preview_cache_js.py new file mode 100644 index 0000000..47f1659 --- /dev/null +++ b/tests/test_preview_cache_js.py @@ -0,0 +1,33 @@ +"""Static contracts for browser preview cache + labeled preview states.""" + +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +CACHE = ROOT / 'app/static/js/lib/preview-cache.js' +API = ROOT / 'app/static/js/api.js' +CARD = ROOT / 'app/static/js/components/device-card.js' + + +def test_preview_cache_exports_stable_name_and_clear(): + source = CACHE.read_text(encoding='utf-8') + assert 'tinypilot-dashboard-previews-v1' in source + assert 'export async function clearPreviewCache' in source + assert 'window.tinypilotPreviewCache' in source + + +def test_api_js_has_post_screenshot_and_preserves_code(): + source = API.read_text(encoding='utf-8') + assert 'postScreenshot' in source + assert 'code: data.code' in source + + +def test_device_card_preview_state_labels(): + source = CARD.read_text(encoding='utf-8') + assert 'Cached preview from' in source + assert 'Live preview, updated' in source + assert 'No signal from computer' in source + assert 'Device offline' in source + assert 'preview-placeholder--shimmer' in source + assert 'latest-screenshot' not in source + assert '_primeFromCache' in source + assert 'Replace API key' in source diff --git a/tests/test_remove_device_ui.py b/tests/test_remove_device_ui.py index 8fd6c3b..b6b7f01 100644 --- a/tests/test_remove_device_ui.py +++ b/tests/test_remove_device_ui.py @@ -73,7 +73,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 +160,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..f6820a2 --- /dev/null +++ b/tests/test_replace_api_key.py @@ -0,0 +1,66 @@ +"""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_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() From b119a478de9ed207e698e7e2427f1581d23ee12a Mon Sep 17 00:00:00 2001 From: Scott Halver <76669202+scott-tp@users.noreply.github.com> Date: Wed, 11 Nov 2026 08:25:28 -0500 Subject: [PATCH 02/12] Fix live preview hidden behind shimmer placeholder Author display:flex on .preview-placeholder overrode the hidden attribute, so a successful JPEG stayed covered by the loading gradient. --- app/static/css/dashboard.css | 6 ++++++ tests/test_preview_cache_js.py | 6 ++++++ 2 files changed, 12 insertions(+) diff --git a/app/static/css/dashboard.css b/app/static/css/dashboard.css index 81c7c22..9f441b5 100644 --- a/app/static/css/dashboard.css +++ b/app/static/css/dashboard.css @@ -332,6 +332,12 @@ button.button-danger-quiet:hover { color: color-mix(in srgb, var(--color-text) 70%, transparent); } +/* Author `display: flex` otherwise overrides the hidden attribute and the + shimmer stays painted over a successful live/cached . */ +.preview-placeholder[hidden] { + display: none !important; +} + .preview-placeholder--shimmer { background: linear-gradient( 110deg, diff --git a/tests/test_preview_cache_js.py b/tests/test_preview_cache_js.py index 47f1659..4f7b4c1 100644 --- a/tests/test_preview_cache_js.py +++ b/tests/test_preview_cache_js.py @@ -31,3 +31,9 @@ def test_device_card_preview_state_labels(): assert 'latest-screenshot' not in source assert '_primeFromCache' in source assert 'Replace API key' in source + + +def test_preview_placeholder_hidden_overrides_flex_display(): + css = (ROOT / 'app/static/css/dashboard.css').read_text(encoding='utf-8') + assert '.preview-placeholder[hidden]' in css + assert 'display: none !important' in css From 24ac06374a745848c7d19286e3c7b1ac1d2dff93 Mon Sep 17 00:00:00 2001 From: Scott Halver <76669202+scott-tp@users.noreply.github.com> Date: Wed, 11 Nov 2026 08:28:32 -0500 Subject: [PATCH 03/12] Use a muted spinner for preview loading and shorten no-signal copy Drop the shimmer and monitor icon so empty preview states match the dashboard subtitle style; Connected already implies the computer side. --- app/api.py | 2 +- app/static/css/dashboard.css | 52 ++++++++++++------------- app/static/js/components/device-card.js | 22 ++++------- tests/test_api_connections.py | 2 +- tests/test_preview_cache_js.py | 9 ++++- 5 files changed, 43 insertions(+), 44 deletions(-) diff --git a/app/api.py b/app/api.py index 5e9821b..e886d3f 100644 --- a/app/api.py +++ b/app/api.py @@ -225,7 +225,7 @@ def refresh_screenshot(device_id: int): # TinyPilotClient raises ValueError for HTTP 204 / empty body (no signal). current_app.logger.warning('TinyPilot screenshot no signal: %s', exc) return jsonify({ - 'error': 'No signal from computer', + 'error': 'No signal', 'code': 'no_signal', }), 502 except Exception as err: # pylint: disable=broad-exception-caught diff --git a/app/static/css/dashboard.css b/app/static/css/dashboard.css index 9f441b5..60d9b08 100644 --- a/app/static/css/dashboard.css +++ b/app/static/css/dashboard.css @@ -326,60 +326,60 @@ button.button-danger-quiet:hover { flex-direction: column; align-items: center; justify-content: center; - gap: 0.4rem; - padding: 1rem; + gap: var(--space-2); + padding: var(--space-4); text-align: center; - color: color-mix(in srgb, var(--color-text) 70%, transparent); + color: var(--color-muted); } /* Author `display: flex` otherwise overrides the hidden attribute and the - shimmer stays painted over a successful live/cached . */ + spinner stays painted over a successful live/cached . */ .preview-placeholder[hidden] { display: none !important; } -.preview-placeholder--shimmer { - background: linear-gradient( - 110deg, - #1a2233 25%, - #243049 37%, - #1a2233 63% - ); - background-size: 200% 100%; - animation: preview-shimmer 1.4s ease-in-out infinite; +.preview-placeholder--loading { + background: #0b1220; } .preview-placeholder--offline { background: #1a2233; - color: color-mix(in srgb, var(--color-text) 75%, transparent); } .preview-placeholder--no_signal { background: #05070c; - color: color-mix(in srgb, var(--color-text) 80%, transparent); } .preview-placeholder-title { margin: 0; - font-size: 0.95rem; - font-weight: 600; + font-size: 0.9rem; + font-weight: 400; + line-height: 1.35; + color: var(--color-muted); } .preview-placeholder-detail { margin: 0; - font-size: 0.8rem; - opacity: 0.85; + font-size: 0.9rem; + font-weight: 400; + line-height: 1.35; + color: var(--color-muted); } -.preview-monitor-icon { - width: 3rem; - height: 2.25rem; - opacity: 0.7; +/* Same shape as TinyPilot Pro's progress-spinner, muted for the preview well. */ +.preview-spinner { + width: 2.5rem; + height: 2.5rem; + border: 3px solid color-mix(in srgb, var(--color-muted) 28%, transparent); + border-top-color: color-mix(in srgb, var(--color-accent) 55%, var(--color-muted)); + border-radius: 50%; + box-sizing: border-box; + animation: preview-spin 1.5s linear infinite; } -@keyframes preview-shimmer { - 0% { background-position: 200% 0; } - 100% { background-position: -200% 0; } +@keyframes preview-spin { + 0% { transform: rotate(0deg); } + 100% { transform: rotate(360deg); } } .replace-api-key-details { diff --git a/app/static/js/components/device-card.js b/app/static/js/components/device-card.js index 8335e24..f3abd77 100644 --- a/app/static/js/components/device-card.js +++ b/app/static/js/components/device-card.js @@ -10,13 +10,6 @@ const AUTOMATION_LICENSE_INFO_URL = 'https://tinypilotkvm.com/pages/automation'; const UPDATE_POLL_INTERVAL_MS = 3000; const UPDATE_POLL_MAX_ERRORS = 10; -const MONITOR_SVG = ` - -`; - function formatCollapsedSnapshotSummary(c) { const checkedAt = c.last_checked || ''; const checkedText = formatRelativeTime(checkedAt); @@ -66,7 +59,7 @@ function setPreviewStatus(el, text, kind) { el.textContent = text; el.classList.toggle( 'connected-status--caution', - kind === 'cached' || kind === 'error' || kind === 'offline' || kind === 'no_signal', + kind === 'cached' || kind === 'error' || kind === 'offline', ); if (kind) { el.dataset.previewKind = kind; @@ -191,7 +184,9 @@ class DeviceCard extends HTMLElement { alt="Latest screenshot for ${escapeHtml(device.friendly_name)}" hidden > - + @@ -269,8 +264,8 @@ class DeviceCard extends HTMLElement { } if (placeholder) { placeholder.hidden = false; - placeholder.className = 'preview-placeholder preview-placeholder--shimmer'; - placeholder.innerHTML = ''; + placeholder.className = 'preview-placeholder preview-placeholder--loading'; + placeholder.innerHTML = ''; } if (offlineBadge) { offlineBadge.hidden = true; @@ -296,7 +291,6 @@ class DeviceCard extends HTMLElement { placeholder.hidden = false; placeholder.className = `preview-placeholder preview-placeholder--${kind}`; placeholder.innerHTML = ` - ${MONITOR_SVG}

${escapeHtml(title)}

${detail ? `

${escapeHtml(detail)}

` : ''} `; @@ -456,10 +450,10 @@ class DeviceCard extends HTMLElement { ); if (result.code === 'no_signal') { - this._showPanelPlaceholder('no_signal', 'No signal from computer', ''); + this._showPanelPlaceholder('no_signal', 'No signal', ''); setPreviewStatus( this._elements.connectedStatus, - 'No signal from computer', + 'No signal', 'no_signal', ); return; diff --git a/tests/test_api_connections.py b/tests/test_api_connections.py index e084406..3a27c79 100644 --- a/tests/test_api_connections.py +++ b/tests/test_api_connections.py @@ -143,7 +143,7 @@ def test_refresh_screenshot_no_signal_code(client): assert response.status_code == 502 assert response.json['code'] == 'no_signal' - assert response.json['error'] == 'No signal from computer' + assert response.json['error'] == 'No signal' def test_set_screenshot_refresh_interval_endpoint(client): diff --git a/tests/test_preview_cache_js.py b/tests/test_preview_cache_js.py index 4f7b4c1..748b353 100644 --- a/tests/test_preview_cache_js.py +++ b/tests/test_preview_cache_js.py @@ -25,9 +25,12 @@ def test_device_card_preview_state_labels(): source = CARD.read_text(encoding='utf-8') assert 'Cached preview from' in source assert 'Live preview, updated' in source - assert 'No signal from computer' in source + assert 'No signal' in source + assert 'No signal from computer' not in source assert 'Device offline' in source - assert 'preview-placeholder--shimmer' in source + assert 'preview-placeholder--loading' in source + assert 'preview-spinner' in source + assert 'preview-monitor-icon' not in source assert 'latest-screenshot' not in source assert '_primeFromCache' in source assert 'Replace API key' in source @@ -37,3 +40,5 @@ def test_preview_placeholder_hidden_overrides_flex_display(): css = (ROOT / 'app/static/css/dashboard.css').read_text(encoding='utf-8') assert '.preview-placeholder[hidden]' in css assert 'display: none !important' in css + assert 'preview-spinner' in css + assert 'preview-shimmer' not in css From 3da93630830751b7ba40f19e78805c7c2c58b21d Mon Sep 17 00:00:00 2001 From: Scott Halver <76669202+scott-tp@users.noreply.github.com> Date: Wed, 11 Nov 2026 08:33:57 -0500 Subject: [PATCH 04/12] Center Offline on the dimmed preview and enlarge empty-state labels Match No signal / Offline as large centered labels; drop the corner badge so offline-with-cache uses the same treatment. --- app/static/css/dashboard.css | 37 +++++++++---------- app/static/js/components/device-card.js | 48 +++++++++++++------------ tests/test_preview_cache_js.py | 5 ++- 3 files changed, 46 insertions(+), 44 deletions(-) diff --git a/app/static/css/dashboard.css b/app/static/css/dashboard.css index 60d9b08..57e6de3 100644 --- a/app/static/css/dashboard.css +++ b/app/static/css/dashboard.css @@ -306,22 +306,10 @@ button.button-danger-quiet:hover { background: #0b1220; } -.preview-offline-badge { - position: absolute; - top: 0.6rem; - left: 0.6rem; - z-index: 2; - padding: 0.15rem 0.45rem; - font-size: 0.75rem; - font-weight: 600; - letter-spacing: 0.02em; - color: #0b1220; - background: color-mix(in srgb, var(--color-warning) 85%, white); -} - .preview-placeholder { position: absolute; inset: 0; + z-index: 1; display: flex; flex-direction: column; align-items: center; @@ -350,12 +338,19 @@ button.button-danger-quiet:hover { 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: 0.9rem; - font-weight: 400; - line-height: 1.35; - color: var(--color-muted); + font-size: 1.25rem; + font-weight: 500; + line-height: 1.3; + letter-spacing: 0.01em; + color: var(--color-text); } .preview-placeholder-detail { @@ -368,10 +363,10 @@ button.button-danger-quiet:hover { /* Same shape as TinyPilot Pro's progress-spinner, muted for the preview well. */ .preview-spinner { - width: 2.5rem; - height: 2.5rem; - border: 3px solid color-mix(in srgb, var(--color-muted) 28%, transparent); - border-top-color: color-mix(in srgb, var(--color-accent) 55%, var(--color-muted)); + 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; diff --git a/app/static/js/components/device-card.js b/app/static/js/components/device-card.js index f3abd77..219ef3b 100644 --- a/app/static/js/components/device-card.js +++ b/app/static/js/components/device-card.js @@ -134,7 +134,6 @@ class DeviceCard extends HTMLElement { screenshot: this.querySelector(`#connected-screenshot-${id}`), link: this.querySelector(`#connected-screenshot-link-${id}`), connectedStatus: this.querySelector(`#connected-status-${id}`), - offlineBadge: this.querySelector(`#preview-offline-badge-${id}`), placeholder: this.querySelector(`#preview-placeholder-${id}`), summaryOutput: this.querySelector(`#device-collapsed-summary-${id}`), metricsOutput: this.querySelector(`#device-metrics-output-${id}`), @@ -187,7 +186,6 @@ class DeviceCard extends HTMLElement { -
@@ -253,7 +251,7 @@ class DeviceCard extends HTMLElement { } _showLoadingPlaceholder() { - const { screenshot, placeholder, offlineBadge, frame } = this._elements; + const { screenshot, placeholder, frame } = this._elements; if (screenshot) { screenshot.hidden = true; screenshot.removeAttribute('src'); @@ -267,9 +265,6 @@ class DeviceCard extends HTMLElement { placeholder.className = 'preview-placeholder preview-placeholder--loading'; placeholder.innerHTML = ''; } - if (offlineBadge) { - offlineBadge.hidden = true; - } if (frame) { frame.className = 'preview-frame preview-frame--loading'; } @@ -277,7 +272,7 @@ class DeviceCard extends HTMLElement { } _showPanelPlaceholder(kind, title, detail) { - const { screenshot, placeholder, offlineBadge, frame, link } = this._elements; + const { screenshot, placeholder, frame, link } = this._elements; this._revokeObjectUrl(); if (screenshot) { screenshot.hidden = true; @@ -295,9 +290,6 @@ class DeviceCard extends HTMLElement { ${detail ? `

${escapeHtml(detail)}

` : ''} `; } - if (offlineBadge) { - offlineBadge.hidden = kind !== 'offline'; - } if (frame) { frame.className = `preview-frame preview-frame--${kind}`; } @@ -305,8 +297,19 @@ class DeviceCard extends HTMLElement { this._previewState = kind; } + _showCenteredLabel(text) { + const { placeholder } = this._elements; + if (!placeholder) { + return; + } + placeholder.hidden = false; + placeholder.className = 'preview-placeholder preview-placeholder--overlay'; + placeholder.innerHTML = + `

${escapeHtml(text)}

`; + } + _showImage({ blobUrl, capturedAt, kind }) { - const { screenshot, placeholder, offlineBadge, frame, link } = this._elements; + const { screenshot, placeholder, frame, link } = this._elements; if (!screenshot) { return; } @@ -316,7 +319,7 @@ class DeviceCard extends HTMLElement { if (this._online === false) { this._showPanelPlaceholder( 'offline', - 'Device offline', + 'Offline', this._lastChecked ? `Last checked ${formatRelativeTime(this._lastChecked)}` : '', @@ -325,7 +328,7 @@ class DeviceCard extends HTMLElement { this._elements.connectedStatus, this._lastChecked ? `Last checked ${formatRelativeTime(this._lastChecked)}.` - : 'Device offline', + : 'Offline', 'offline', ); } else { @@ -336,18 +339,19 @@ class DeviceCard extends HTMLElement { screenshot.src = blobUrl; screenshot.classList.toggle('connected-screenshot--cached', kind === 'cached'); screenshot.classList.toggle('connected-screenshot--offline', kind === 'offline'); - if (placeholder) { + if (kind === 'offline') { + this._showCenteredLabel('Offline'); + } else if (placeholder) { placeholder.hidden = true; placeholder.innerHTML = ''; } - if (offlineBadge) { - offlineBadge.hidden = kind !== 'offline'; - } if (frame) { frame.className = `preview-frame preview-frame--${kind}`; } - if (deviceLaunchHref(this._device)) { + if (deviceLaunchHref(this._device) && kind !== 'offline') { activateScreenshotLink(link); + } else { + deactivateScreenshotLink(link); } this._capturedAt = capturedAt; this._hasCachedImage = true; @@ -409,7 +413,7 @@ class DeviceCard extends HTMLElement { } else if (!this._hasCachedImage) { this._showPanelPlaceholder( 'offline', - 'Device offline', + 'Offline', this._lastChecked ? `Last checked ${formatRelativeTime(this._lastChecked)}` : '', @@ -418,7 +422,7 @@ class DeviceCard extends HTMLElement { this._elements.connectedStatus, this._lastChecked ? `Last checked ${formatRelativeTime(this._lastChecked)}.` - : 'Device offline', + : 'Offline', 'offline', ); } @@ -470,7 +474,7 @@ class DeviceCard extends HTMLElement { } else if (this._online === false) { this._showPanelPlaceholder( 'offline', - 'Device offline', + 'Offline', this._lastChecked ? `Last checked ${formatRelativeTime(this._lastChecked)}` : '', @@ -479,7 +483,7 @@ class DeviceCard extends HTMLElement { this._elements.connectedStatus, this._lastChecked ? `Last checked ${formatRelativeTime(this._lastChecked)}.` - : 'Device offline', + : 'Offline', 'offline', ); } else { diff --git a/tests/test_preview_cache_js.py b/tests/test_preview_cache_js.py index 748b353..1fb94f1 100644 --- a/tests/test_preview_cache_js.py +++ b/tests/test_preview_cache_js.py @@ -27,10 +27,13 @@ def test_device_card_preview_state_labels(): assert 'Live preview, updated' in source assert 'No signal' in source assert 'No signal from computer' not in source - assert 'Device offline' in source + assert "_showCenteredLabel('Offline')" in source + assert 'Device offline' not in source assert 'preview-placeholder--loading' in source + assert 'preview-placeholder--overlay' in source assert 'preview-spinner' in source assert 'preview-monitor-icon' not in source + assert 'preview-offline-badge' not in source assert 'latest-screenshot' not in source assert '_primeFromCache' in source assert 'Replace API key' in source From 5772fe498d7f23e23b5f772b93a7e17a315ba5e2 Mon Sep 17 00:00:00 2001 From: Scott Halver <76669202+scott-tp@users.noreply.github.com> Date: Wed, 11 Nov 2026 08:48:50 -0500 Subject: [PATCH 05/12] Poll visible device snapshots every five minutes Also align empty Offline with the dark No signal well, yellow-caution non-live preview status copy, and Offline/No signal checked phrasing. --- app/static/css/dashboard.css | 7 +-- app/static/js/components/device-card.js | 74 ++++++++++++------------- app/static/js/dashboard-app.js | 44 +++++++++++++-- 3 files changed, 77 insertions(+), 48 deletions(-) diff --git a/app/static/css/dashboard.css b/app/static/css/dashboard.css index 57e6de3..deb8c79 100644 --- a/app/static/css/dashboard.css +++ b/app/static/css/dashboard.css @@ -330,10 +330,9 @@ button.button-danger-quiet:hover { background: #0b1220; } -.preview-placeholder--offline { - background: #1a2233; -} - +/* 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; } diff --git a/app/static/js/components/device-card.js b/app/static/js/components/device-card.js index 219ef3b..ce7dc73 100644 --- a/app/static/js/components/device-card.js +++ b/app/static/js/components/device-card.js @@ -52,20 +52,28 @@ 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' || kind === 'offline', - ); + // 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) { @@ -317,19 +325,13 @@ class DeviceCard extends HTMLElement { screenshot.hidden = true; screenshot.removeAttribute('src'); if (this._online === false) { - this._showPanelPlaceholder( - 'offline', - 'Offline', - this._lastChecked - ? `Last checked ${formatRelativeTime(this._lastChecked)}` - : '', - ); + const checkedAt = this._lastChecked || new Date().toISOString(); + this._showPanelPlaceholder('offline', 'Offline', ''); setPreviewStatus( this._elements.connectedStatus, - this._lastChecked - ? `Last checked ${formatRelativeTime(this._lastChecked)}.` - : 'Offline', + checkedStatusCopy('Offline', checkedAt), 'offline', + checkedAt, ); } else { this._showLoadingPlaceholder(); @@ -361,20 +363,22 @@ class DeviceCard extends HTMLElement { this._elements.connectedStatus, livePreviewCopy(capturedAt), 'live', + capturedAt, ); } else if (kind === 'offline') { + const checkedAt = this._lastChecked || capturedAt || new Date().toISOString(); setPreviewStatus( this._elements.connectedStatus, - this._lastChecked - ? `Last seen ${formatRelativeTime(this._lastChecked)}.` - : 'Offline', + checkedStatusCopy('Offline', checkedAt), 'offline', + checkedAt, ); } else { setPreviewStatus( this._elements.connectedStatus, cachedPreviewCopy(capturedAt), 'cached', + capturedAt, ); } } @@ -411,19 +415,13 @@ class DeviceCard extends HTMLElement { kind: 'offline', }); } else if (!this._hasCachedImage) { - this._showPanelPlaceholder( - 'offline', - 'Offline', - this._lastChecked - ? `Last checked ${formatRelativeTime(this._lastChecked)}` - : '', - ); + const checkedAt = this._lastChecked || new Date().toISOString(); + this._showPanelPlaceholder('offline', 'Offline', ''); setPreviewStatus( this._elements.connectedStatus, - this._lastChecked - ? `Last checked ${formatRelativeTime(this._lastChecked)}.` - : 'Offline', + checkedStatusCopy('Offline', checkedAt), 'offline', + checkedAt, ); } return; @@ -454,11 +452,13 @@ class DeviceCard extends HTMLElement { ); if (result.code === 'no_signal') { + const checkedAt = this._lastChecked || new Date().toISOString(); this._showPanelPlaceholder('no_signal', 'No signal', ''); setPreviewStatus( this._elements.connectedStatus, - 'No signal', + checkedStatusCopy('No signal', checkedAt), 'no_signal', + checkedAt, ); return; } @@ -472,26 +472,22 @@ class DeviceCard extends HTMLElement { kind, }); } else if (this._online === false) { - this._showPanelPlaceholder( - 'offline', - 'Offline', - this._lastChecked - ? `Last checked ${formatRelativeTime(this._lastChecked)}` - : '', - ); + const checkedAt = this._lastChecked || new Date().toISOString(); + this._showPanelPlaceholder('offline', 'Offline', ''); setPreviewStatus( this._elements.connectedStatus, - this._lastChecked - ? `Last checked ${formatRelativeTime(this._lastChecked)}.` - : 'Offline', + checkedStatusCopy('Offline', checkedAt), 'offline', + checkedAt, ); } else { + const checkedAt = new Date().toISOString(); this._showLoadingPlaceholder(); setPreviewStatus( this._elements.connectedStatus, result.error || 'Could not capture a screenshot.', 'error', + checkedAt, ); } return; diff --git a/app/static/js/dashboard-app.js b/app/static/js/dashboard-app.js index 85d359f..7909610 100644 --- a/app/static/js/dashboard-app.js +++ b/app/static/js/dashboard-app.js @@ -15,6 +15,7 @@ const DELETE_DEVICE_MODAL_LABEL = 'Remove device'; 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() { @@ -26,6 +27,7 @@ class DashboardApp extends HTMLElement { this._pendingUpdateCard = null; this._screenshotAutoRefreshTimers = new Map(); this._screenshotCapturedAtByDevice = new Map(); + this._snapshotAutoRefreshTimer = null; } connectedCallback() { @@ -136,6 +138,7 @@ class DashboardApp extends HTMLElement { this._bind(); void this._refreshDeviceList(); window.setInterval(() => this._refreshConnectedStatusTimes(), CONNECTED_STATUS_REFRESH_INTERVAL_MS); + this._scheduleSnapshotAutoRefresh(); } _bind() { @@ -512,6 +515,27 @@ class DashboardApp extends HTMLElement { } } + _scheduleSnapshotAutoRefresh() { + if (this._snapshotAutoRefreshTimer) { + window.clearInterval(this._snapshotAutoRefreshTimer); + } + this._snapshotAutoRefreshTimer = window.setInterval(() => { + void this._refreshVisibleDeviceSnapshots(); + }, DEVICE_SNAPSHOT_REFRESH_INTERVAL_MS); + } + + async _refreshVisibleDeviceSnapshots() { + const visibleDevices = this._getVisibleDevices(); + await Promise.allSettled( + visibleDevices.map(async (device) => { + const card = this._deviceCard(String(device.id)); + if (card) { + await card.refreshSnapshot(); + } + }), + ); + } + _renderCurrentPage() { const visibleDevices = this._getVisibleDevices(); this._renderDeviceSections(visibleDevices); @@ -520,17 +544,27 @@ class DashboardApp extends HTMLElement { } _refreshConnectedStatusTimes() { - for (const [deviceId, capturedAt] of this._screenshotCapturedAtByDevice.entries()) { - const card = this._deviceCard(deviceId); - const connectedStatus = card?.querySelector(`#connected-status-${deviceId}`); + for (const card of this._elements.deviceSections.querySelectorAll('device-card')) { + const deviceId = card.dataset.deviceId; + const connectedStatus = card.querySelector(`#connected-status-${deviceId}`); if (!connectedStatus) { continue; } const kind = connectedStatus.dataset.previewKind; + const checkedAt = + connectedStatus.dataset.checkedAt + || this._screenshotCapturedAtByDevice.get(String(deviceId)); + if (!checkedAt) { + continue; + } if (kind === 'cached') { - connectedStatus.textContent = `Cached preview from ${formatRelativeTime(capturedAt)}.`; + connectedStatus.textContent = `Cached preview from ${formatRelativeTime(checkedAt)}.`; } else if (kind === 'live') { - connectedStatus.textContent = `Live preview, updated ${formatRelativeTime(capturedAt)}.`; + connectedStatus.textContent = `Live preview, updated ${formatRelativeTime(checkedAt)}.`; + } else if (kind === 'offline') { + connectedStatus.textContent = `Offline, checked ${formatRelativeTime(checkedAt)}.`; + } else if (kind === 'no_signal') { + connectedStatus.textContent = `No signal, checked ${formatRelativeTime(checkedAt)}.`; } } // Relative "checked … ago" is baked in at snapshot time; refresh the From 09be653d47b82384ec75f6696a2cca3223452ad6 Mon Sep 17 00:00:00 2001 From: Scott Halver <76669202+scott-tp@users.noreply.github.com> Date: Wed, 11 Nov 2026 08:49:06 -0500 Subject: [PATCH 06/12] Tighten preview-state contract tests for snapshot polling --- tests/test_preview_cache_js.py | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/tests/test_preview_cache_js.py b/tests/test_preview_cache_js.py index 1fb94f1..84df296 100644 --- a/tests/test_preview_cache_js.py +++ b/tests/test_preview_cache_js.py @@ -27,6 +27,7 @@ def test_device_card_preview_state_labels(): assert 'Live preview, updated' in source assert 'No signal' in source assert 'No signal from computer' not in source + assert 'checkedStatusCopy' in source assert "_showCenteredLabel('Offline')" in source assert 'Device offline' not in source assert 'preview-placeholder--loading' in source @@ -37,6 +38,14 @@ def test_device_card_preview_state_labels(): assert 'latest-screenshot' not in source assert '_primeFromCache' in source assert 'Replace API key' in source + assert "kind !== 'live'" in source + + +def test_dashboard_polls_visible_snapshots_every_five_minutes(): + app = (ROOT / 'app/static/js/dashboard-app.js').read_text(encoding='utf-8') + assert 'DEVICE_SNAPSHOT_REFRESH_INTERVAL_MS = 5 * 60 * 1000' in app + assert '_refreshVisibleDeviceSnapshots' in app + assert '_scheduleSnapshotAutoRefresh' in app def test_preview_placeholder_hidden_overrides_flex_display(): @@ -45,3 +54,5 @@ def test_preview_placeholder_hidden_overrides_flex_display(): assert 'display: none !important' in css assert 'preview-spinner' in css assert 'preview-shimmer' not in css + assert '.preview-placeholder--offline' in css + assert '.preview-placeholder--no_signal' in css From 265fc9484264dd3e9242b3d2c2f18db7473c23fd Mon Sep 17 00:00:00 2001 From: Scott Halver <76669202+scott-tp@users.noreply.github.com> Date: Wed, 11 Nov 2026 09:02:29 -0500 Subject: [PATCH 07/12] Move Replace API key into a non-danger confirm modal Place the action beside Remove device and reuse the remove-modal layout with a password field, hint, and Save/Cancel. --- app/static/css/dashboard.css | 34 +------ app/static/js/components/device-card.js | 55 +---------- app/static/js/dashboard-app.js | 123 ++++++++++++++++++++++-- tests/test_preview_cache_js.py | 2 +- tests/test_remove_device_ui.py | 23 +++++ 5 files changed, 144 insertions(+), 93 deletions(-) diff --git a/app/static/css/dashboard.css b/app/static/css/dashboard.css index deb8c79..1081e00 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); @@ -376,37 +379,6 @@ button.button-danger-quiet:hover { 100% { transform: rotate(360deg); } } -.replace-api-key-details { - margin-top: var(--space-3); -} - -.replace-api-key-details summary { - cursor: pointer; - font-weight: 600; -} - -.actions-replace-api-key { - margin-top: var(--space-2); - align-items: center; -} - -.replace-api-key-input { - flex: 1 1 12rem; - min-width: 0; -} - -.sr-only { - position: absolute; - width: 1px; - height: 1px; - padding: 0; - margin: -1px; - overflow: hidden; - clip: rect(0, 0, 0, 0); - white-space: nowrap; - border: 0; -} - .launch-link { color: var(--color-accent); text-decoration: none; diff --git a/app/static/js/components/device-card.js b/app/static/js/components/device-card.js index ce7dc73..50e4cf3 100644 --- a/app/static/js/components/device-card.js +++ b/app/static/js/components/device-card.js @@ -147,8 +147,6 @@ class DeviceCard extends HTMLElement { metricsOutput: this.querySelector(`#device-metrics-output-${id}`), intervalInput: this.querySelector(`#screenshot-interval-${id}`), expandedDetails: this.querySelector(`#device-details-${id}`), - replaceKeyInput: this.querySelector(`#replace-api-key-${id}`), - replaceKeyStatus: this.querySelector(`#replace-api-key-status-${id}`), }; } @@ -223,6 +221,7 @@ class DeviceCard extends HTMLElement {
+
@@ -232,23 +231,6 @@ class DeviceCard extends HTMLElement { Expanded TinyPilot device info
-
- Replace API key -

Create a key on the device under System → Automation, then paste it here.

-
- - - -
-

-
@@ -511,41 +493,6 @@ class DeviceCard extends HTMLElement { }); } - async replaceApiKey() { - if (!this._device) { - return false; - } - const { replaceKeyInput, replaceKeyStatus } = this._elements; - const apiKey = (replaceKeyInput?.value || '').trim(); - if (!apiKey) { - if (replaceKeyStatus) { - replaceKeyStatus.textContent = 'Enter a new API key.'; - } - return false; - } - if (replaceKeyStatus) { - replaceKeyStatus.textContent = 'Saving…'; - } - const result = await window.dashboardApi.putJson( - `/api/devices/${this._device.id}/api-key`, - { api_key: apiKey }, - ); - if (replaceKeyInput) { - replaceKeyInput.value = ''; - } - if (result.error) { - if (replaceKeyStatus) { - replaceKeyStatus.textContent = result.error; - } - return false; - } - if (replaceKeyStatus) { - replaceKeyStatus.textContent = 'API key updated.'; - } - await this.refreshSnapshot(); - return true; - } - _setExpandedVisible(visible) { const { expandedDetails, metricsOutput } = this._elements; if (expandedDetails) { diff --git a/app/static/js/dashboard-app.js b/app/static/js/dashboard-app.js index 7909610..dc14876 100644 --- a/app/static/js/dashboard-app.js +++ b/app/static/js/dashboard-app.js @@ -12,6 +12,7 @@ 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; @@ -24,6 +25,7 @@ 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(); @@ -95,6 +97,27 @@ class DashboardApp extends HTMLElement {

+ ', 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(): source = CARD.read_text(encoding='utf-8') assert 'function renderHeaderOpenWebUi' in source From 789500f4a7eb4b6aa8646df9a944bddec6ad2f57 Mon Sep 17 00:00:00 2001 From: Scott Halver <76669202+scott-tp@users.noreply.github.com> Date: Wed, 11 Nov 2026 09:12:10 -0500 Subject: [PATCH 08/12] Tighten remove and replace modal instruction copy Drop the remove re-add disclaimer, split replace-key instructions onto two spaced lines, and give modal instructions consistent spacing. --- app/static/css/dashboard.css | 22 ++++++++++++++++++++++ app/static/js/dashboard-app.js | 7 +++++-- tests/test_remove_device_ui.py | 8 ++++++++ 3 files changed, 35 insertions(+), 2 deletions(-) diff --git a/app/static/css/dashboard.css b/app/static/css/dashboard.css index 1081e00..fe909c6 100644 --- a/app/static/css/dashboard.css +++ b/app/static/css/dashboard.css @@ -399,6 +399,28 @@ button.button-danger-quiet:hover { color: var(--color-muted); } +.modal-instructions { + margin: 0 0 var(--space-3); +} + +.modal-instructions .subtitle { + margin: 0; + font-size: 0.9rem; + font-weight: 400; + line-height: 1.45; +} + +.modal-instructions .subtitle + .subtitle { + margin-top: var(--space-2); +} + +.modal-panel > .subtitle.modal-instructions { + margin: 0 0 var(--space-3); + font-size: 0.9rem; + font-weight: 400; + line-height: 1.45; +} + .connected-system .subtitle { margin: var(--space-2) 0 0; font-size: 0.9rem; diff --git a/app/static/js/dashboard-app.js b/app/static/js/dashboard-app.js index dc14876..b70cec1 100644 --- a/app/static/js/dashboard-app.js +++ b/app/static/js/dashboard-app.js @@ -83,7 +83,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.

+