Speed up Console navigation and widen service details

This commit is contained in:
Andrei Smaliak 2026-11-02 08:58:15 +01:00
parent 3edce30416
commit 16d0e5959a
11 changed files with 106 additions and 74 deletions

View File

@ -0,0 +1,16 @@
# Console 3.1.37 — faster navigation and wide technical values
- Let service details with long values span the complete card width. USB device
paths and FFmpeg build strings remain readable without narrow word columns.
- Reuse one provider snapshot across Health, Network and G-Box instead of
executing the complete system-service diagnostics separately for every tab.
- Keep the shared snapshot for 15 seconds during normal navigation. Explicit
Refresh bypasses the snapshot, so an operator can still request current data.
- Mark SHA-fingerprinted CSS and JavaScript as immutable browser resources while
keeping the HTML entry point uncached. A changed asset receives a new URL.
- Activate the selected tab immediately before its data request completes, so
navigation always gives visible feedback while live diagnostics are loading.
- The pre-change browser baseline on the local Edge was 1.7 seconds for initial
Health, 6.1 seconds for Network, 1.1 seconds for Modbus and 2.6 seconds for
G-Box. These timings identified repeated provider diagnostics as the main
avoidable delay.

View File

@ -14,7 +14,7 @@
"version": "1.0.1"
},
"stage_ui": {
"version": "3.1.36"
"version": "3.1.37"
},
"stage_avahi": {
"version": "1.0.0"

View File

@ -61,7 +61,7 @@ APP_DIR = "/opt/iomatex-console"
PUBLIC_DIR = os.path.join(APP_DIR, "public")
PROVIDERS_DIR = os.path.join(APP_DIR, "providers.d")
CONFIG_PATH = "/etc/iomatex/console.json"
UI_VERSION = "V 3.1.36"
UI_VERSION = "V 3.1.37"
STORAGE_HEALTH_COMMAND = "/usr/local/sbin/iomatex-storage-health"
ZONEINFO_ROOT = "/usr/share/zoneinfo"
@ -69,13 +69,11 @@ DEFAULT_CONFIG = {
"bind": "0.0.0.0",
"port": 80,
"extra_ports": [],
"cache_ttl_sec": 3,
"cache_ttl_sec": 15,
}
_CACHE = {"expires_at": 0.0, "payload": None}
_HEALTH_SERVICES_CACHE = {"expires_at": 0.0, "payload": None}
_CACHE_LOCK = threading.Lock()
_HEALTH_SERVICES_CACHE_LOCK = threading.Lock()
_CPU_SAMPLE = {"total": None, "idle": None}
_NET_SAMPLE = {}
_WIFI_SCAN_CACHE = {"expires_at": 0.0, "payload": None}
@ -169,6 +167,9 @@ STATIC_NO_CACHE_HEADERS = {
"Cache-Control": "no-store, no-cache, must-revalidate",
"Pragma": "no-cache",
}
STATIC_ASSET_CACHE_HEADERS = {
"Cache-Control": "public, max-age=31536000, immutable",
}
_AUTH_SESSIONS = {}
_AUTH_SESSIONS_LOCK = threading.Lock()
CAMERA_PREVIEW_PATH_RE = re.compile(
@ -1530,8 +1531,6 @@ def ap_status_card():
def invalidate_cache():
_CACHE["payload"] = None
_CACHE["expires_at"] = 0.0
_HEALTH_SERVICES_CACHE["payload"] = None
_HEALTH_SERVICES_CACHE["expires_at"] = 0.0
_ITSCREEN_STATUS_CACHE["payload"] = None
_ITSCREEN_STATUS_CACHE["expires_at"] = 0.0
@ -2049,7 +2048,7 @@ def summarize_interface(iface, kind="ethernet"):
}
def get_network_summary(include_service_cards=True):
def get_network_summary(include_service_cards=True, force_provider_refresh=False):
iface = get_primary_interface()
profile = read_wifi_profile_state()
script_status = parse_wifi_status_script()
@ -2076,7 +2075,7 @@ def get_network_summary(include_service_cards=True):
}
avahi_card = None
if include_service_cards:
cards, _ = collect_provider_cards(build_provider_context())
cards = build_status_payload(force=force_provider_refresh).get("services", [])
avahi_card = next((card for card in cards if card.get("id") == "avahi"), None)
return {
"ok": True,
@ -2551,15 +2550,15 @@ def collect_provider_cards(context, entrypoint="get_cards"):
return cards, provider_names
def build_status_payload():
def build_status_payload(force=False):
now = time.time()
cfg = load_config()
if _CACHE["payload"] is not None and now < _CACHE["expires_at"]:
if not force and _CACHE["payload"] is not None and now < _CACHE["expires_at"]:
return _CACHE["payload"]
with _CACHE_LOCK:
now = time.time()
if _CACHE["payload"] is not None and now < _CACHE["expires_at"]:
if not force and _CACHE["payload"] is not None and now < _CACHE["expires_at"]:
return _CACHE["payload"]
cards, provider_names = collect_provider_cards(build_provider_context())
@ -2571,7 +2570,7 @@ def build_status_payload():
"providers": provider_names,
}
_CACHE["payload"] = payload
_CACHE["expires_at"] = time.time() + max(1, int(cfg.get("cache_ttl_sec", 3)))
_CACHE["expires_at"] = time.time() + max(1, int(cfg.get("cache_ttl_sec", 15)))
return payload
@ -2695,17 +2694,7 @@ def build_runtime_profile_payload():
}
def build_health_services_payload():
now = time.time()
cfg = load_config()
if _HEALTH_SERVICES_CACHE["payload"] is not None and now < _HEALTH_SERVICES_CACHE["expires_at"]:
return _HEALTH_SERVICES_CACHE["payload"]
with _HEALTH_SERVICES_CACHE_LOCK:
now = time.time()
if _HEALTH_SERVICES_CACHE["payload"] is not None and now < _HEALTH_SERVICES_CACHE["expires_at"]:
return _HEALTH_SERVICES_CACHE["payload"]
def build_health_services_payload(force=False):
allowed_ids = {
"itscreen",
"mosquitto",
@ -2719,16 +2708,13 @@ def build_health_services_payload():
"environment",
"console",
}
cards, _ = collect_provider_cards(build_provider_context())
payload = {
status = build_status_payload(force=force)
return {
"ok": True,
"generated_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
"identity": get_identity_payload(),
"services": [card for card in cards if card.get("id") in allowed_ids],
"generated_at": status.get("generated_at", ""),
"identity": status.get("identity", {}),
"services": [card for card in status.get("services", []) if card.get("id") in allowed_ids],
}
_HEALTH_SERVICES_CACHE["payload"] = payload
_HEALTH_SERVICES_CACHE["expires_at"] = time.time() + max(1, int(cfg.get("cache_ttl_sec", 3)))
return payload
def find_service_card(service_id):
@ -3658,7 +3644,7 @@ class Handler(BaseHTTPRequestHandler):
)
return
if parsed.path == "/api/status":
self.send_json(build_status_payload())
self.send_json(build_status_payload(force=query.get("refresh", ["0"])[0] == "1"))
return
if parsed.path == "/api/display":
payload = find_service_card("display")
@ -3669,7 +3655,7 @@ class Handler(BaseHTTPRequestHandler):
return
if parsed.path == "/api/health/services":
try:
payload = build_health_services_payload()
payload = build_health_services_payload(force=query.get("refresh", ["0"])[0] == "1")
cards = [dict(card) for card in payload["services"]]
updates = stage_versions.snapshot(cards)
for card in cards:
@ -3718,7 +3704,7 @@ class Handler(BaseHTTPRequestHandler):
if parsed.path == "/api/network/summary":
try:
self.send_json({
**get_network_summary(),
**get_network_summary(force_provider_refresh=query.get("refresh", ["0"])[0] == "1"),
"identity": get_identity_payload(),
})
except Exception as exc:
@ -3819,13 +3805,13 @@ class Handler(BaseHTTPRequestHandler):
self.send_file(os.path.join(PUBLIC_DIR, "index.html"), "text/html; charset=utf-8", extra_headers=STATIC_NO_CACHE_HEADERS)
return
if parsed.path == "/console.css":
self.send_file(os.path.join(PUBLIC_DIR, "console.css"), "text/css; charset=utf-8", extra_headers=STATIC_NO_CACHE_HEADERS)
self.send_file(os.path.join(PUBLIC_DIR, "console.css"), "text/css; charset=utf-8", extra_headers=STATIC_ASSET_CACHE_HEADERS if "sha" in query else STATIC_NO_CACHE_HEADERS)
return
if parsed.path == "/console.i18n.js":
self.send_file(os.path.join(PUBLIC_DIR, "console.i18n.js"), "application/javascript; charset=utf-8", extra_headers=STATIC_NO_CACHE_HEADERS)
self.send_file(os.path.join(PUBLIC_DIR, "console.i18n.js"), "application/javascript; charset=utf-8", extra_headers=STATIC_ASSET_CACHE_HEADERS if "sha" in query else STATIC_NO_CACHE_HEADERS)
return
if parsed.path == "/console.js":
self.send_file(os.path.join(PUBLIC_DIR, "console.js"), "application/javascript; charset=utf-8", extra_headers=STATIC_NO_CACHE_HEADERS)
self.send_file(os.path.join(PUBLIC_DIR, "console.js"), "application/javascript; charset=utf-8", extra_headers=STATIC_ASSET_CACHE_HEADERS if "sha" in query else STATIC_NO_CACHE_HEADERS)
return
if parsed.path == "/logo.png":
self.send_file(os.path.join(PUBLIC_DIR, "logo.png"), "image/png")

View File

@ -31,4 +31,9 @@ class AssetVersionTest(unittest.TestCase):
self.assertIn('fingerprint_console_assets(data, os.path.dirname(path))', handler)
self.assertLess(handler.index('fingerprint_console_assets'), handler.index('Content-Length'))
def test_fingerprinted_assets_are_immutable(self):
self.assertIn('"Cache-Control": "public, max-age=31536000, immutable"', source)
route = source.split('if parsed.path == "/console.css":', 1)[1].split('if parsed.path == "/logo.png":', 1)[0]
self.assertEqual(3, route.count('STATIC_ASSET_CACHE_HEADERS if "sha" in query else STATIC_NO_CACHE_HEADERS'))
if __name__ == '__main__': unittest.main()

View File

@ -10,12 +10,15 @@ assert.equal((js.match(/serviceCard serviceProfileCard/g) || []).length, 2);
assert.match(js, /function renderServiceSummary\(card\)/);
assert.match(js, /serviceCard serviceProfileCard itscreenServiceCard/);
assert.match(js, /if \(card\.id === "itscreen"\) return content/);
assert.match(js, /serviceDetailsWide/);
assert.match(js, /state\.activeTab = nextTab;\s+renderActiveTab\(\);\s+await loadForActiveTab\(\)/);
assert.match(css, /\.shell\{max-width:1600px/);
assert.match(css, /\.healthServiceGrid\{\s*grid-template-columns:repeat\(3,minmax\(0,1fr\)\)/);
assert.match(css, /@media \(max-width:1100px\)[\s\S]*?\.healthServiceGrid\{grid-template-columns:repeat\(2,minmax\(0,1fr\)\)\}/);
assert.match(css, /@media \(max-width:720px\)[\s\S]*?\.healthServiceGrid\{grid-template-columns:1fr\}/);
assert.match(css, /\.healthServiceGrid \.serviceProfileCard\{[\s\S]*?grid-template-columns:repeat\(2,minmax\(0,1fr\)\)/);
assert.match(css, /\.healthServiceGrid \.itscreenServiceCard\{[\s\S]*?grid-column:span 2;[\s\S]*?grid-template-columns:repeat\(3,minmax\(0,1fr\)\)/);
assert.match(css, /\.serviceDetailsWide \.compactMeta\{grid-template-columns:minmax\(90px,24%\) minmax\(0,1fr\)\}/);
assert.match(css, /@media \(max-width:940px\)[\s\S]*?\.healthServiceGrid \.serviceProfileCard\{grid-template-columns:1fr\}/);
console.log('Health layout owner: 1600px shell and 3/2/1 service columns passed');

View File

@ -16,7 +16,7 @@ SPEC.loader.exec_module(app)
class HealthServicesCacheTest(unittest.TestCase):
def setUp(self):
app._HEALTH_SERVICES_CACHE.update({"expires_at": 0.0, "payload": None})
app._CACHE.update({"expires_at": 0.0, "payload": None})
def test_ttl_starts_after_slow_collection_finishes(self):
clock = iter([100.0, 100.0, 110.0, 110.0])
@ -26,7 +26,24 @@ class HealthServicesCacheTest(unittest.TestCase):
mock.patch.object(app, "get_identity_payload", return_value={}):
app.build_health_services_payload()
self.assertEqual(113.0, app._HEALTH_SERVICES_CACHE["expires_at"])
self.assertEqual(113.0, app._CACHE["expires_at"])
def test_status_and_health_share_one_provider_collection(self):
calls = []
def collect(_context):
calls.append(True)
return [{"id": "edge_api"}], ["core.py"]
with mock.patch.object(app, "load_config", return_value={"cache_ttl_sec": 15}), \
mock.patch.object(app, "collect_provider_cards", side_effect=collect), \
mock.patch.object(app, "get_identity_payload", return_value={}):
health = app.build_health_services_payload()
status = app.build_status_payload()
self.assertEqual([{"id": "edge_api"}], health["services"])
self.assertEqual([{"id": "edge_api"}], status["services"])
self.assertEqual(1, len(calls))
def test_concurrent_requests_share_one_collection(self):
started = threading.Event()

View File

@ -422,6 +422,8 @@ h1{margin:0;font-size:34px;line-height:1.02;font-weight:650;letter-spacing:-.03e
.serviceSummaryItem .key{color:var(--muted);font-size:11px;text-transform:uppercase;letter-spacing:.06em}
.serviceSummaryValue{min-width:0;overflow-wrap:anywhere;font-size:13px}
.healthServiceGrid .serviceProfileCard > .list{min-width:0;align-self:start}
.healthServiceGrid .serviceProfileCard > .serviceDetailsWide{grid-column:1 / -1}
.serviceDetailsWide .compactMeta{grid-template-columns:minmax(90px,24%) minmax(0,1fr)}
.serviceProfileAside{min-width:0}
.card h2{margin:0;font-size:19px}
.cardSubtitle{margin:6px 0 0;color:var(--muted);font-size:13px}

View File

@ -49,7 +49,7 @@
{ mode: "test_by", label: "test.it-screen.by", host: "rest.test.it-screen.by" },
{ mode: "custom", label: "Custom", host: "" }
];
const UI_VERSION = "V 3.1.36";
const UI_VERSION = "V 3.1.37";
const ITSCREEN_LOG_INITIAL_LINES = 50;
const ITSCREEN_LOG_BUFFER_LIMIT = 300;
const ITSCREEN_LOG_BATCH_MS = 250;
@ -2535,6 +2535,7 @@
const warnings = Array.isArray(card.warnings) ? card.warnings : [];
const errors = Array.isArray(card.errors) ? card.errors : [];
const details = Array.isArray(card.details) ? card.details : [];
const wideDetails = details.some((detail) => textValue(detail && detail.value, "").length > 32);
const mqttSelfTest = state.mqttSelfTest || {};
const showMqttSelfTest = card.id === "mosquitto";
const showMqttBridgeTest = card.id === "mqtt_bridge";
@ -2548,7 +2549,7 @@
</div>
</div>
${renderServiceSummary(card)}
${details.length ? `<div class="list"><div class="listTitle">${esc(t("Details"))}</div><div class="meta compactMeta">${renderKeyValueRows(details)}</div></div>` : ""}
${details.length ? `<div class="list serviceDetailsSection${wideDetails ? " serviceDetailsWide" : ""}"><div class="listTitle">${esc(t("Details"))}</div><div class="meta compactMeta">${renderKeyValueRows(details)}</div></div>` : ""}
${showMqttSelfTest ? renderMqttSelfTestPanel() : ""}
${showMqttBridgeTest ? renderMqttBridgeTestPanel() : ""}
<div class="list">
@ -4988,8 +4989,8 @@
state.healthServices.services = state.healthServices.services.map((card) => (card && card.id === nextCard.id ? nextCard : card));
}
async function loadStatus() {
state.status = await fetchJson("/api/status", { cache: "no-store" });
async function loadStatus(options = {}) {
state.status = await fetchJson(`/api/status${options.force ? "?refresh=1" : ""}`, { cache: "no-store" });
updateIdentity(state.status.identity || {});
updateHeaderMeta(state.status);
}
@ -5008,13 +5009,13 @@
requestController.abort();
}
async function loadHealth() {
async function loadHealth(options = {}) {
const generation = state.sessionGeneration;
if (state.healthRequest) return state.healthRequest;
state.healthRequest = (async () => {
const [summary, services] = await Promise.all([
fetchJson("/api/health/summary", { cache: "no-store" }),
fetchJson("/api/health/services", { cache: "no-store" })
fetchJson(`/api/health/services${options.force ? "?refresh=1" : ""}`, { cache: "no-store" })
]);
state.health = summary;
state.healthServices = services;
@ -5046,10 +5047,10 @@
}
}
async function loadNetwork() {
async function loadNetwork(options = {}) {
if (state.networkRequest) return state.networkRequest;
state.networkRequest = (async () => {
state.network = await fetchJson("/api/network/summary", { cache: "no-store" });
state.network = await fetchJson(`/api/network/summary${options.force ? "?refresh=1" : ""}`, { cache: "no-store" });
updateIdentity(state.network.identity || state.identity || {});
updateHeaderMeta(state.network);
syncNetworkFormFromBackend();
@ -5330,22 +5331,23 @@
return;
}
const generation = state.sessionGeneration;
const force = !!options.force;
const preserveEditing = !!options.preserveEditing;
nodes.refreshBtn.disabled = true;
if (nodes.rebootBtn) nodes.rebootBtn.disabled = state.rebootPending;
try {
if (state.activeTab === "health") {
await Promise.all([loadHealth(), loadItscreenInitialData()]);
await Promise.all([loadHealth({ force }), loadItscreenInitialData({ force })]);
} else if (state.activeTab === "security") {
await loadTimezone();
} else if (state.activeTab === "network") {
await loadNetwork();
await loadNetwork({ force });
} else if (state.activeTab === "modbus") {
await loadModbus();
await loadModbus({ force });
} else if (state.activeTab === "tscreen") {
await loadItscreenInitialData();
await loadItscreenInitialData({ force });
} else {
await loadStatus();
await loadStatus({ force });
}
if (generation !== state.sessionGeneration) return;
if (!(preserveEditing && state.activeTab === "network" && networkFormIsInteractive()) && !(preserveEditing && state.activeTab === "tscreen" && itscreenFormIsInteractive()) && !(preserveEditing && state.activeTab === "security" && timezoneFormIsInteractive())) {
@ -7013,6 +7015,7 @@
await releaseModbusLeaseSilently();
}
state.activeTab = nextTab;
renderActiveTab();
await loadForActiveTab();
if (state.activeTab === "tscreen") {
activateItscreenLogs().catch(() => {});
@ -7024,7 +7027,7 @@
nodes.refreshBtn.addEventListener("click", async () => {
if (!state.auth.authenticated) return;
closeActionMenu();
await loadForActiveTab();
await loadForActiveTab({ force: true });
});
}
if (nodes.rebootBtn) nodes.rebootBtn.addEventListener("click", window.__rebootDevice);

View File

@ -23,7 +23,7 @@
} catch (error) {}
})();
</script>
<link rel="stylesheet" href="/console.css?v=3.1.36&amp;rev=edge-runtime-profile-1">
<link rel="stylesheet" href="/console.css?v=3.1.37&amp;rev=edge-runtime-profile-1">
</head>
<body>
<main class="shell">
@ -109,7 +109,7 @@
</main>
<div id="menuBackdrop" class="menuBackdrop" hidden></div>
<div id="toastStack" class="toastStack" aria-live="polite" aria-atomic="true"></div>
<script src="/console.i18n.js?v=3.1.36&amp;rev=edge-runtime-profile-1"></script>
<script src="/console.js?v=3.1.36&amp;rev=edge-runtime-profile-1"></script>
<script src="/console.i18n.js?v=3.1.37&amp;rev=edge-runtime-profile-1"></script>
<script src="/console.js?v=3.1.37&amp;rev=edge-runtime-profile-1"></script>
</body>
</html>

View File

@ -255,7 +255,7 @@ cat > "$CFG_PATH" <<JSON
"bind": "${APP_BIND}",
"port": ${APP_PORT},
"extra_ports": [${APP_EXTRA_PORT}],
"cache_ttl_sec": 3
"cache_ttl_sec": 15
}
JSON

View File

@ -1,3 +1,3 @@
{
"version": "3.1.36"
"version": "3.1.37"
}