Unify Hub effects and cursor tracking across pages

This commit is contained in:
kzolotarev95 committed 2026-11-04 01:57:42 +04:00
1 parent 41ab4387fc
commit 607837ef1f
9 files changed
+1693 -892

No files matched your search

+59
View File
@@ -0,0 +1,59 @@
# Дизайн панели Hub (локально, v120)
В разделе «Эффекты → Эффекты Hub» ниже переключателей эффектов добавлен
раздел «Дизайн», одинаковый на ПК и мобильных устройствах:
- Обычный — прежнее оформление.
- Зимний — синяя палитра, ледяные панели, статичные снежные детали.
Падающий снег включается отдельно в эффектах.
- Для слабых устройств — сплошной фон, без CSS-анимаций, переходов,
размытия, теней и canvas-эффектов. Частицы удаляются, буфер canvas
уменьшается до 1×1, цикл requestAnimationFrame отменяется.
Выбор хранится в localStorage этого браузера, применяется перед отрисовкой
страницы и синхронизируется между вкладками. Настройка применяется ко всем
сгенерированным страницам Hub: к главной панели, авторизации, VPS/SSH-терминалу,
логам, заметкам и очереди обновления. Ответы проксируемого LuCI намеренно
остаются без изменений.
Выбранный эффект Hub также читается на этих страницах из того же значения
`owrtRemote:seasonEffectMode`: снег, дождь, космос, угли, орбита, призма,
пульс и лучи имеют отдельную отрисовку. В lite-режиме эффекты отключены.
На страницах авторизации, терминала и очереди старые фоновые aura-анимации
отключаются, чтобы они не смешивались с выбранным эффектом Hub.
При возврате из облегчённого дизайна восстанавливается выбранный ранее эффект.
В лёгком режиме ресурсы VPS обновляются раз в 5 секунд, роутеры — раз в 10.
В остальных дизайнах сохраняются интервалы 1 и 5 секунд. Скрытые вкладки
приостанавливают эффекты и автоматические запросы статистики/роутеров.
Автоматические запросы списка роутеров не перекрываются, имеют тайм-аут 10 с.
Неизменившийся ответ в лёгком режиме не вызывает пересоздание карточек.
Уведомления, Heartbeat, Xray, WAN и настройки роутеров не менялись.
Установка на VPS из PowerShell Windows 11:
```powershell
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "C:\Users\k.zolotarev95\Documents\openwrt overlay\vps\deploy-hub-design.ps1" -Vps "root@138.124.79.58" -Action Install
```
После установки обновить страницу и открыть «Эффекты → Дизайн».
Откат — та же команда с `-Action Rollback`. Резервная копия:
`/opt/owrt-remote/owrt-remote-hub.py.bak-before-hub-design-v120`.
При сбое установки возвращается файл, который был до этой попытки.
Скрипт подтверждает SHA-256 реально запущенного Hub через health endpoint.
Проверки:
```text
python -m unittest tests.test_hub_design_deploy tests.test_vps_resources -q
python -m unittest tests.test_hub_design_global -q
node tests/test_hub_design_ui.cjs
node tests/test_hub_design_polling.cjs .test-output/hub-design/dashboard.js
node tests/test_vps_resources_ui.cjs .test-output/hub-design/dashboard.js
```
Браузерные проверки используют Playwright/Chrome и локальные ответы API.
Проверяют ПК, телефон и горизонтальный экран; сохранение после перезагрузки,
отключение эффектов/буфера в lite, восстановление эффектов, отсутствие
горизонтального переполнения. Снимки сохраняются в `.test-output/hub-design/`.
Это функциональные проверки экономии работы браузера, а не замер FPS или
потребления памяти на физическом слабом устройстве.
+8
View File
@@ -0,0 +1,8 @@
"""Local design install and rollback use exact running build verification."""
from tests import test_update_status_ui_deploy as deploy_tests
class HubDesignDeployTests(deploy_tests.UpdateStatusDeployTests):
deploy_file = 'deploy-hub-design.ps1'
backup_name = 'hub.py.bak-before-hub-design-v120'
success_marker = 'HUB_DESIGN_V120_Install_OK'
+63
View File
@@ -0,0 +1,63 @@
import importlib.util
import json
import os
import pathlib
import sys
import tempfile
import unittest
from unittest import mock
ROOT = pathlib.Path(__file__).resolve().parents[1]
SPEC = importlib.util.spec_from_file_location("owrt_remote_hub_global_design", ROOT / "vps" / "owrt-remote-hub.py")
hub = importlib.util.module_from_spec(SPEC)
STATE = tempfile.TemporaryDirectory(prefix="owrt-global-design-")
sys.modules[SPEC.name] = hub
with mock.patch.dict(os.environ, {"OWRT_REMOTE_STATE_DIR": STATE.name}):
SPEC.loader.exec_module(hub)
def preview_pages():
router = {"id": "main", "name": "Test router", "permissions": {"manage": True}}
with mock.patch.object(hub, "web_push_backend_status", return_value={"ready": False}):
pages = {
"/": hub.dashboard_html([], "root", auth_bootstrap={"is_owner": True}),
"/login": hub.login_html(),
"/vps-terminal/": hub.ssh_terminal_html_v2(hub.vps_terminal_row(), "test"),
"/router-updates/": hub.router_updates_html("test"),
"/router/main/logs": hub.router_logs_html(router),
"/router/main/notes": hub.router_notes_html(router),
"/ssh/main/": hub.ssh_terminal_html_v2(hub.vps_terminal_row(), "test"),
}
return {path: hub.inject_hub_appearance(path, page.encode("utf-8"), "text/html").decode("utf-8")
for path, page in pages.items()}
class GlobalHubDesignTests(unittest.TestCase):
def test_generated_pages_receive_the_shared_head(self):
pages = {
"login": hub.login_html(),
"terminal": hub.ssh_terminal_html_v2(hub.vps_terminal_row(), "token"),
"updates": hub.router_updates_html("csrf"),
}
for path, page in pages.items():
result = hub.inject_hub_appearance("/" + path, page.encode("utf-8"), "text/html; charset=utf-8")
text = result.decode("utf-8")
self.assertEqual(text.count("owrt-hub-design-head"), 1, path)
self.assertIn("DESIGN_KEY", text, path)
for mode in ("snow", "rain", "cosmos", "embers", "orbit", "prism", "pulse", "laser"):
self.assertIn("'" + mode + "'", text, path)
self.assertIn("#routerSearchToggle", text, path)
def test_existing_dashboard_and_luci_are_not_double_injected(self):
dashboard = hub.dashboard_html([], "root")
self.assertEqual(dashboard.count("owrt-hub-design-head"), 1)
luci = b"<html><head><title>LuCI</title></head><body>router</body></html>"
self.assertEqual(hub.inject_hub_appearance("/access/main/", luci, "text/html"), luci)
if __name__ == "__main__":
if len(sys.argv) == 3 and sys.argv[1] == "--export-preview":
pathlib.Path(sys.argv[2]).write_text(json.dumps(preview_pages(), ensure_ascii=False), encoding="utf-8")
else:
unittest.main()
+47
View File
@@ -0,0 +1,47 @@
// Check request frequency and repaint work without relying on real-time sleeps.
const assert = require('node:assert/strict');
const fs = require('node:fs');
const vm = require('node:vm');
const source = fs.readFileSync(process.argv[2], 'utf8');
const start = source.indexOf('async function loadRouters(options = {}) {');
const end = source.indexOf('\nif (routerGroupFilter)', start);
assert(start>=0 && end>start);
let clock = 10000, calls = 0, renders = 0, wol = false, finish;
const timers = new Map();
const fixture = {
hubDesignMode:'lite', lastAutomaticRouterPoll:0, routerPollInFlight:false,
AbortController, Date:{now:()=>clock}, document:{hidden:false}, window:{ROUTERS:[{id:'main',name:'Router'}]},
hasOpenWolPanel:()=>wol, renderRouterGroups(){},syncRouterNotesState(){},shouldDeferRouterRender:()=>false,
renderRouterView(){renders++;},fillRouterForm(){},refreshDiagnosticPanel(){},
setTimeout(fn,delay){timers.set(1,{fn,delay});return 1;},clearTimeout(id){timers.delete(id);},
fetch(url,options){calls++;return fixture.respond(url,options);},
respond:async()=>({ok:true,json:async()=>({routers:fixture.window.ROUTERS})}),
};
vm.createContext(fixture);
vm.runInContext(source.slice(start,end), fixture);
(async()=>{
await fixture.loadRouters({automatic:true});
assert.equal(calls,1);assert.equal(renders,0,'identical lite data does not rebuild cards');
clock=15000;await fixture.loadRouters({automatic:true});assert.equal(calls,1);
clock=20000;
fixture.respond=()=>new Promise(resolve=>{finish=resolve;});
const first=fixture.loadRouters({automatic:true});
await fixture.loadRouters({automatic:true});assert.equal(calls,2,'no parallel automatic router fetches');
finish({ok:true,json:async()=>({routers:[{id:'main',name:'Renamed'}]})});await first;
assert.equal(renders,1);assert.equal(timers.size,0);
fixture.document.hidden=true;clock=30000;
await fixture.loadRouters({automatic:true});assert.equal(calls,2);
fixture.document.hidden=false;wol=true;
await fixture.loadRouters({automatic:true});assert.equal(calls,2,'preserve open WOL picker');
wol=false;
fixture.respond=(url,options)=>new Promise((resolve,reject)=>options.signal.addEventListener('abort',()=>reject(new Error('timeout'))));
const pending=fixture.loadRouters({automatic:true});
assert.equal(timers.get(1).delay,10000);timers.get(1).fn();
await assert.rejects(pending,/timeout/);
assert.equal(fixture.routerPollInFlight,false,'timeouts release the polling guard');
fixture.respond=async()=>({ok:true,json:async()=>({routers:fixture.window.ROUTERS})});
fixture.hubDesignMode='winter';clock=35000;
await fixture.loadRouters({automatic:true});assert.equal(calls,4,'normal designs retain the 5-second interval');
assert.equal(renders,2);
console.log('HUB_DESIGN_POLLING_OK: lite 10s, normal 5s, no parallel fetches or idle repaints, timeout recovery, hidden tabs and WOL');
})().catch(error=>{console.error(error);process.exitCode=1;});
+85
View File
@@ -0,0 +1,85 @@
// Local browser checks; all Hub API calls are fixtures, no VPS is contacted.
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const {execFileSync} = require('node:child_process');
const {chromium} = require('playwright');
const output = path.resolve('.test-output/hub-design');
execFileSync(process.env.TEST_PYTHON || 'python', ['tests/test_vps_resources.py', '--export-preview', output],
{env:{...process.env,PYTHONIOENCODING:'utf-8'}});
const template = fs.readFileSync(path.join(output, 'dashboard.html'), 'utf8');
const routers = Array.from({length:18}, (_, i) => ({id:'node-'+i,name:'Роутер '+(i+1),role:'node',
online:i!==2,entry_port:18000+i,ssh_entry_port:19000+i,last_seen:1700000000,
permissions:{manage:true,admin:true,ssh:true},status:{model:'Xiaomi Mi Router AX3000T',
release:'OpenWrt 24.10.3',xray:'running',ssh:'running',mem_total_kb:239720,mem_available_kb:72000}}));
const html = template.replace('window.ROUTERS = [];', 'window.ROUTERS = '+JSON.stringify(routers)+';');
(async () => {
const browser = await chromium.launch({headless:true,channel:'chrome'});
try {
for (const [width,height,mobile] of [[1366,960,false],[390,844,true],[844,390,true]]) {
const context = await browser.newContext({viewport:{width,height},isMobile:mobile,hasTouch:mobile});
const page = await context.newPage(), errors = [];
page.on('pageerror', error => errors.push(error.message));
await page.route('**/*', async route => {
const url = new URL(route.request().url());
if (url.pathname === '/') return route.fulfill({contentType:'text/html',body:html});
if (url.pathname === '/api/routers') return route.fulfill({json:{routers}});
if (url.pathname === '/api/router-groups') return route.fulfill({json:{groups:[]}});
if (url.pathname === '/api/notifications/wait') return route.fulfill({status:429,json:{busy:true},headers:{'Retry-After':'5'}});
if (url.pathname === '/api/vps/resources') return route.fulfill({json:{ok:true,cpu:{percent:15},memory:{percent:35},disk:{percent:40}}});
if (url.pathname === '/api/hub-update') return route.fulfill({json:{ok:true,checked:true,available:false,current_version:'v120'}});
if (url.pathname.startsWith('/api/')) return route.fulfill({json:{ok:true,auth:{username:'root',is_owner:true,can_add_router:true}}});
return route.abort();
});
await page.goto('http://127.0.0.1:9999/');
await page.waitForFunction(() => typeof setHubDesign === 'function' && document.querySelectorAll('.card').length === 18);
const mobileLayout = width<=680 || mobile;
const toggle = page.locator(mobileLayout?'#mobileSeasonToggle':'#seasonToggle');
const panel = page.locator(mobileLayout?'#mobileSeasonPanel':'#seasonPanel');
await toggle.click();
await panel.locator('[data-hub-design="winter"]').click();
assert.equal(await page.evaluate(() => document.documentElement.dataset.hubDesign), 'winter');
assert.equal(await page.locator('body').evaluate(el => getComputedStyle(el).backgroundColor), 'rgb(6, 20, 38)');
assert.equal(await page.locator('.card').first().evaluate(el => getComputedStyle(el).backdropFilter), 'none');
assert.equal(await panel.locator('[data-hub-design="winter"]').getAttribute('aria-pressed'), 'true');
assert.equal(await page.evaluate(() => localStorage.getItem('owrtRemote:hubDesign')), 'winter');
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth<=innerWidth),true);
await page.screenshot({path:path.join(output, 'winter-'+width+'.png'),fullPage:false});
await panel.locator('[data-season-mode="snow"]').click();
await page.waitForFunction(() => seasonalFxFrame>0 && seasonalFxParticles.length>0);
// Pausing a hidden tab cancels the animation, returning resumes one loop.
await page.evaluate(() => {Object.defineProperty(document,'hidden',{configurable:true,get:()=>true});document.dispatchEvent(new Event('visibilitychange'));});
assert.equal(await page.evaluate(() => seasonalFxFrame),0);
await page.evaluate(() => {Object.defineProperty(document,'hidden',{configurable:true,get:()=>false});document.dispatchEvent(new Event('visibilitychange'));});
await page.waitForFunction(() => seasonalFxFrame>0);
await panel.locator('[data-hub-design="lite"]').click();
assert.deepEqual(await page.evaluate(() => [seasonalFxFrame,seasonalFxParticles.length,seasonalFxCanvas.width,seasonalFxCanvas.height]), [0,0,1,1]);
assert.equal(await panel.locator('[data-season-mode="snow"]').isDisabled(),true);
assert.equal(await page.locator('.card').first().evaluate(el => getComputedStyle(el).boxShadow),'none');
assert.equal(await page.locator('.card').first().evaluate(el => getComputedStyle(el).backdropFilter),'none');
assert.equal(await page.evaluate(() => document.getAnimations().filter(a=>a.playState==='running').length),0);
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth<=innerWidth),true);
await page.screenshot({path:path.join(output, 'lite-'+width+'.png'),fullPage:false});
// The palette is restored on reload before canvas allocation.
await page.reload();
await page.waitForFunction(() => hubDesignMode==='lite');
assert.deepEqual(await page.evaluate(() => [seasonalFxFrame,seasonalFxParticles.length,seasonalFxCanvas.width]), [0,0,1]);
await toggle.click();
assert.equal(await panel.locator('[data-hub-design="lite"]').getAttribute('aria-pressed'),'true');
await panel.locator('[data-hub-design="default"]').click();
await page.waitForFunction(() => seasonalFxFrame>0);
assert.equal(await page.evaluate(() => seasonEffectMode),'snow','restore the saved effect after leaving lite mode');
await page.evaluate(() => setSeasonEffectMode('off'));
await page.evaluate(() => {localStorage.setItem('owrtRemote:hubDesign','lite');});
await page.reload();
await page.waitForFunction(() => hubDesignMode==='lite');
// Storage unavailable: changing designs still works in the current tab.
await page.evaluate(() => {Storage.prototype.setItem=()=>{throw new Error('disabled');};setHubDesign('winter');});
assert.equal(await page.evaluate(() => hubDesignMode),'winter');
assert.deepEqual(errors,[]);
await context.close();
}
console.log('HUB_DESIGN_UI_OK: desktop/mobile/landscape, persistence, no overflow, lite has no animations or canvas, hidden tab pause/resume');
} finally { await browser.close(); }
})().catch(error => {console.error(error);process.exitCode=1;});
+112
View File
@@ -0,0 +1,112 @@
// Compare actual canvas output and pointer physics across Hub pages. All APIs
// are local fixtures; no router, terminal session, or VPS is contacted.
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const {execFileSync} = require('node:child_process');
const {chromium} = require('playwright');
const output = path.resolve('.test-output/hub-design');
fs.mkdirSync(output, {recursive:true});
const preview = path.join(output, 'shared-pages.json');
execFileSync(process.env.TEST_PYTHON || 'python', ['tests/test_hub_design_global.py','--export-preview',preview],
{env:{...process.env,PYTHONIOENCODING:'utf-8'}});
const pages = JSON.parse(fs.readFileSync(preview, 'utf8'));
const modes = ['snow','rain','cosmos','embers','orbit','prism','pulse','laser'];
async function renderSample(page, mode, usePointer) {
return page.evaluate(({mode,usePointer}) => {
seasonFxStop();
const random = Math.random, now = Date.now;
let seed = 12345;
Math.random = () => ((seed = Math.imul(1664525,seed)+1013904223>>>0)/4294967296);
Date.now = () => 1000;
try {
Object.assign(seasonalFxPointer,{x:0,y:0,lastX:0,lastY:0,targetWind:0,wind:0,lastMoveTs:0,active:false});
setSeasonEffectMode(mode,{persist:false});
if (usePointer) {
window.dispatchEvent(new PointerEvent('pointermove',{clientX:90,clientY:110}));
window.dispatchEvent(new PointerEvent('pointermove',{clientX:140,clientY:120}));
}
for (let i=1;i<=12;i++) window.testFrame(i*16);
const bytes=seasonalFxCtx.getImageData(0,0,seasonalFxCanvas.width,seasonalFxCanvas.height).data;
let digest=2166136261, visible=0;
for(let i=0;i<bytes.length;i++) {digest=Math.imul(digest^bytes[i],16777619)>>>0;if(i%4===3&&bytes[i])visible++;}
return {digest,visible,count:seasonalFxParticles.length,
pointer:JSON.parse(JSON.stringify(seasonalFxPointer)),
size:seasonalFxSize,pending:window.testFrames.size,
particles:JSON.parse(JSON.stringify(seasonalFxParticles.slice(0,3)))};
} finally {Math.random=random;Date.now=now;seasonFxStop();}
}, {mode,usePointer});
}
(async()=>{
const browser=await chromium.launch({headless:true,channel:'chrome'});
try {
const context=await browser.newContext({viewport:{width:900,height:700},deviceScaleFactor:1});
await context.addInitScript(()=>{
window.testFrames=new Map();let frameId=0;
window.requestAnimationFrame=callback=>{window.testFrames.set(++frameId,callback);return frameId;};
window.cancelAnimationFrame=id=>window.testFrames.delete(id);
window.testFrame=ts=>{const callbacks=[...window.testFrames.values()];window.testFrames.clear();callbacks.forEach(fn=>fn(ts));};
Object.defineProperty(document,'hidden',{configurable:true,get:()=>false});
});
await context.route('**/*',route=>{
const url=new URL(route.request().url());
if(pages[url.pathname])return route.fulfill({contentType:'text/html',body:pages[url.pathname]});
if(url.pathname==='/api/routers')return route.fulfill({json:{routers:[]}});
if(url.pathname==='/api/router-groups')return route.fulfill({json:{groups:[]}});
if(url.pathname==='/api/notifications/wait')return route.fulfill({status:429,headers:{'Retry-After':'5'},json:{busy:true}});
if(url.pathname.startsWith('/api/'))return route.fulfill({json:{ok:true,routers:[],auth:{username:'root',is_owner:true}}});
return route.abort();
});
const all=[],errors=[];
const baseline={};
for(const route of Object.keys(pages)){
const page=await context.newPage();all.push(page);
page.on('pageerror',error=>errors.push(route+': '+error.message));
await page.goto('http://hub.test'+route);
await page.waitForFunction(()=>hubAppearanceInitialized&&seasonEffectsInitialized,null,{polling:50,timeout:10000});
await page.evaluate(()=>setHubDesign('winter',{persist:false}));
assert.equal(await page.locator('canvas.seasonalFx').count(),1,route+' has one canvas');
for(const mode of modes){
const pointed=await renderSample(page,mode,true);
const neutral=await renderSample(page,mode,false);
assert.equal(pointed.pointer.x,140,route+' '+mode+' pointer X');
assert.equal(pointed.pointer.y,120,route+' '+mode+' pointer Y');
assert.equal(pointed.pointer.active,true);
assert.equal(pointed.pending,1,'one animation loop');
assert(pointed.visible>0,route+' '+mode+' actually draws pixels');
assert.notEqual(pointed.digest,neutral.digest,route+' '+mode+' responds to pointer');
if(route==='/')baseline[mode]=pointed;
else assert.deepEqual(pointed,baseline[mode],route+' '+mode+' matches dashboard pixels and physics');
}
// Repeated initialization must not add a second pointer handler or loop.
await page.evaluate(()=>{initHubAppearance();initSeasonEffects();setSeasonEffectMode('prism',{persist:false});});
assert.equal(await page.evaluate(()=>testFrames.size),1,route+' repeated initialization');
}
// Changes from the dashboard reach already-open login, terminal, queue,
// logs and notes tabs, including lite suppression and effect restoration.
const main=all[0];
for(const mode of modes){
await main.evaluate(mode=>setSeasonEffectMode(mode),mode);
for(const page of all.slice(1))await page.waitForFunction(mode=>seasonEffectMode===mode,mode,{polling:50,timeout:10000});
}
await main.evaluate(()=>setHubDesign('lite'));
for(const page of all){
await page.waitForFunction(()=>hubDesignMode==='lite',null,{polling:50,timeout:10000});
assert.deepEqual(await page.evaluate(()=>[seasonalFxFrame,seasonalFxParticles.length,seasonalFxCanvas.width,seasonalFxCanvas.height]),[0,0,1,1]);
}
await main.evaluate(()=>setHubDesign('winter'));
for(const page of all){
await page.waitForFunction(()=>hubDesignMode==='winter'&&seasonalFxFrame>0,null,{polling:50,timeout:10000});
assert.equal(await page.evaluate(()=>seasonEffectMode),'laser');
await page.evaluate(()=>{window.dispatchEvent(new PointerEvent('pointermove',{clientX:280,clientY:210}));});
assert.deepEqual(await page.evaluate(()=>[seasonalFxPointer.x,seasonalFxPointer.y,seasonalFxPointer.active]),[280,210,true]);
await page.evaluate(()=>window.dispatchEvent(new Event('blur')));
assert.deepEqual(await page.evaluate(()=>[seasonalFxPointer.active,seasonalFxPointer.targetWind]),[false,0]);
}
assert.deepEqual(errors,[]);
await context.close();
console.log('HUB_SHARED_EFFECTS_OK: 8 effects, 7 pages, identical canvas pixels and cursor physics, single loop, cross-tab design/effect sync, lite pause/restore');
} finally {await browser.close();}
})().catch(error=>{console.error(error);process.exitCode=1;});
+12 -1
View File
@@ -20,7 +20,7 @@ function fixture(initialPending = false) {
const metrics = {ok: true, cpu: {percent: 25, cores: 2}, memory: {percent: 40, used_bytes: 1024, total_bytes: 2048}, disk: {percent: 60, used_bytes: 2048, total_bytes: 4096}}; const metrics = {ok: true, cpu: {percent: 25, cores: 2}, memory: {percent: 40, used_bytes: 1024, total_bytes: 2048}, disk: {percent: 60, used_bytes: 2048, total_bytes: 4096}};
const context = { const context = {
Intl, AbortController, Intl, AbortController,
document: {hidden: false, querySelectorAll() { return widgets; }, addEventListener(key, fn) { documentEvents[key] = fn; }}, document: {hidden: false, documentElement:{dataset:{hubDesign:'default'}}, querySelectorAll() { return widgets; }, addEventListener(key, fn) { documentEvents[key] = fn; }},
window: {addEventListener(key, fn) { windowEvents[key] = fn; }}, window: {addEventListener(key, fn) { windowEvents[key] = fn; }},
setInterval(fn, ms) { const id = nextId++; timers.set(id, {fn, ms, interval: true}); return id; }, setInterval(fn, ms) { const id = nextId++; timers.set(id, {fn, ms, interval: true}); return id; },
setTimeout(fn, ms) { const id = nextId++; timers.set(id, {fn, ms}); return id; }, setTimeout(fn, ms) { const id = nextId++; timers.set(id, {fn, ms}); return id; },
@@ -92,6 +92,17 @@ function fixture(initialPending = false) {
f.documentEvents.visibilitychange(); await flush(); f.documentEvents.visibilitychange(); await flush();
assert.equal(f.calls.length, count); assert.equal(f.calls.length, count);
const lite = fixture(); await flush();
lite.context.document.documentElement.dataset.hubDesign = 'lite';
lite.windowEvents.hubdesignchange(); await flush();
assert.equal(lite.intervals().length, 1, 'changing design must not duplicate widget timers');
assert.equal(lite.intervals()[0].ms, 5000, 'lite mode polls resources every 5 seconds');
lite.context.document.documentElement.dataset.hubDesign = 'winter';
lite.windowEvents.hubdesignchange(); await flush();
assert.equal(lite.intervals().length, 1);
assert.equal(lite.intervals()[0].ms, 1000, 'winter restores the regular update interval');
lite.windowEvents.pagehide();
const g = fixture(); await flush(); const g = fixture(); await flush();
g.context.respond = (url, options) => new Promise((resolve, reject) => options.signal.addEventListener('abort', () => reject(new Error('timeout')))); g.context.respond = (url, options) => new Promise((resolve, reject) => options.signal.addEventListener('abort', () => reject(new Error('timeout'))));
g.tick(); g.tick();
+177
View File
@@ -0,0 +1,177 @@
param(
[Parameter(Mandatory = $true)][ValidateNotNullOrEmpty()][string]$Vps,
[ValidateSet('Install', 'Rollback')][string]$Action = 'Install',
[switch]$PrepareOnly
)
$ErrorActionPreference = 'Stop'
$RepoRoot = Split-Path -Parent $PSScriptRoot
$UploadName = 'owrt-hub-design-' + [guid]::NewGuid().ToString('N')
$StageRoot = Join-Path ([System.IO.Path]::GetTempPath()) $UploadName
$Utf8 = [System.Text.UTF8Encoding]::new($false)
$RemoteScript = @'
#!/bin/sh
set -eu
stage=/tmp/__UPLOAD_NAME__
target=/opt/owrt-remote/owrt-remote-hub.py
backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-hub-design-v120
candidate=$target.new-__UPLOAD_NAME__
changed=0
show_failure() {
echo '--- owrt-remote status ---' >&2
systemctl --no-pager -l status owrt-remote >&2 || true
echo '--- owrt-remote journal ---' >&2
journalctl -u owrt-remote -n 80 --no-pager -l >&2 || true
}
cleanup() {
code=$?
trap - EXIT
if [ "$code" -ne 0 ]; then
echo "Remote step failed with rc=$code" >&2
show_failure
fi
if [ "$code" -ne 0 ] && [ "$changed" = 1 ] && [ -s "$stage/previous.py" ]; then
echo 'Restoring the previous Hub file...' >&2
cp -p "$stage/previous.py" "$candidate"
mv -f "$candidate" "$target"
systemctl restart owrt-remote || true
fi
rm -f "$candidate"
rm -rf "$stage"
exit "$code"
}
trap cleanup EXIT
test -s "$target"
python_bin=/opt/owrt-remote/venv/bin/python
[ -x "$python_bin" ] || python_bin=python3
if [ '__ACTION__' = Install ]; then
test -s "$stage/hub.py"
echo 'Validating candidate...'
"$python_bin" -m py_compile "$stage/hub.py"
"$python_bin" - "$stage/hub.py" <<'PY'
from pathlib import Path
import sys
source = Path(sys.argv[1]).read_text(encoding='utf-8')
required = ('def hub_design_controls_html():', 'def hub_design_head():',
'function setHubDesign(', 'function initHubDesign()',
'def hub_design_runtime_script():', 'function initHubAppearance()',
'function seasonFxHandlePointerMove(',
'hubdesignchange', "hubDesignMode === 'lite'", 'data-hub-design="winter"')
for marker in required:
if marker not in source:
raise SystemExit('Candidate is missing: ' + marker)
print('Candidate validation OK')
PY
if [ ! -e "$backup" ]; then
cp -p "$target" "$backup"
fi
source_file="$stage/hub.py"
else
test -s "$backup"
"$python_bin" -m py_compile "$backup"
source_file="$backup"
fi
expected_revision=$("$python_bin" - "$source_file" <<'PY'
import hashlib
from pathlib import Path
import sys
print(hashlib.sha256(Path(sys.argv[1]).read_bytes()).hexdigest())
PY
)
cp -p "$target" "$stage/previous.py"
cp "$source_file" "$candidate"
chmod 0755 "$candidate"
changed=1
mv -f "$candidate" "$target"
echo 'Restarting owrt-remote...'
if ! systemctl restart owrt-remote; then
show_failure
exit 1
fi
healthy=0
for attempt in 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15; do
if systemctl is-active --quiet owrt-remote && "$python_bin" - "$expected_revision" > "$stage/health-check" 2>&1 <<'PY'
import json
import sys
import urllib.request
try:
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
with opener.open('http://127.0.0.1:8088/health?panel-update=1', timeout=3) as response:
data = json.loads(response.read(4096))
revision = data.get('revision', '')
if not data.get('ok') or revision != sys.argv[1]:
raise RuntimeError('Running Hub revision does not match the uploaded file: '
+ (revision or '(not reported)') + '; expected ' + sys.argv[1])
print('Running Hub revision verified: ' + revision)
except Exception as error:
print('Health verification failed: ' + str(error), file=sys.stderr)
raise SystemExit(1)
PY
then
healthy=1
break
fi
sleep 2
done
if [ "$healthy" -ne 1 ]; then
echo 'The uploaded Hub build did not become ready; installation was not confirmed.' >&2
cat "$stage/health-check" >&2 2>/dev/null || true
show_failure
exit 1
fi
cat "$stage/health-check"
cmp "$source_file" "$target"
printf '\nBackup: %s\nHUB_DESIGN_V120_%s_OK\n' "$backup" '__ACTION__'
if [ '__ACTION__' = Install ]; then
echo 'Refresh the Hub page and open Effects to choose the panel design.'
echo 'This fix is LOCAL. The panel update button can replace it with the published repository build.'
fi
'@
$RemoteScript = $RemoteScript.Replace('__UPLOAD_NAME__', $UploadName).Replace('__ACTION__', $Action)
try {
[System.IO.Directory]::CreateDirectory($StageRoot) | Out-Null
[System.IO.File]::WriteAllText(
(Join-Path $StageRoot 'run.sh'),
$RemoteScript.Replace("`r`n", "`n") + "`n",
$Utf8
)
if ($Action -eq 'Install') {
$Content = [System.IO.File]::ReadAllText((Join-Path $RepoRoot 'vps\owrt-remote-hub.py')).Replace("`r`n", "`n")
[System.IO.File]::WriteAllText((Join-Path $StageRoot 'hub.py'), $Content, $Utf8)
}
if ($PrepareOnly) {
Write-Host "Prepared only: $StageRoot"
return
}
& scp -O -r -- $StageRoot "${Vps}:/tmp/"
if ($LASTEXITCODE -ne 0) { throw 'Upload failed. VPS was not changed.' }
& ssh -T -o ConnectTimeout=10 $Vps "sh /tmp/$UploadName/run.sh"
if ($LASTEXITCODE -ne 0) { throw "$Action failed. See the output above; success was not confirmed." }
Write-Host "Hub design $Action finished successfully."
}
finally {
if (-not $PrepareOnly) {
$Resolved = [System.IO.Path]::GetFullPath($StageRoot)
$Expected = [System.IO.Path]::GetFullPath((Join-Path ([System.IO.Path]::GetTempPath()) $UploadName))
if ($Resolved -ne $Expected -or (Split-Path -Leaf $Resolved) -ne $UploadName) {
throw 'Unsafe staging cleanup path.'
}
if (Test-Path -LiteralPath $Resolved) {
Remove-Item -LiteralPath $Resolved -Recurse -Force
}
}
}
+1130 -891
View File
File diff suppressed because it is too large. Load diff