Add detailed router update outcomes and fix mobile terminal layout

This commit is contained in:
kzolotarev95 committed 2026-10-16 04:35:54 +04:00
1 parent 2a47adb32a
commit e5048f260b
5 files changed
+135 -12

No files matched your search

+21 -2
View File
@@ -66,6 +66,20 @@ storage. Из вывода удаляются пароль и строки с и
Сводка очереди оформлена карточками: всего, обновляются, ожидают, успешно,
ошибки, не подтверждено, остановлено и пропущено. Полоса прогресса считает
обработанные устройства всех итоговых категорий; 100% не означает успех всех.
Под статистикой автоматически показывается подробный список роутеров с
ошибками, неподтверждённым результатом, остановкой или пропуском. Для каждого
видны имя из UCI/Heartbeat, отдельный ID, точная причина и раскрываемый вывод
команды, если он получен. Нажатие на соответствующую карточку статистики
оставляет только её категорию; «Показать все категории» возвращает общий
список проблем. Нулевой счётчик открывает понятное сообщение об отсутствии
устройств в категории. Список и счётчики обновляются вместе каждые три секунды,
выбранная категория, прокрутка и раскрытый вывод сохраняются. В новой очереди
снова показываются все проблемные результаты. Дополнительные запросы к
роутерам или повторная установка для просмотра списка не выполняются.
Мобильная вкладка терминала обновления адаптируется к ширине от 320 пикселей:
кнопки идут одной колонкой, карточки статистики — двумя, поля ввода имеют
шрифт 16 px, длинные имена, ID, команды и причины переносятся в своих блоках.
Списки и вывод команды ограничены по высоте; предусмотрены отступы safe area.
Рядом с «Вернуться в Hub» есть «Обновить список роутеров»: после завершения
очереди кнопка убирает её результаты и получает текущий список, имена и статусы.
Во время работающей очереди она только обновляет статусы, не удаляя задачу.
@@ -92,7 +106,7 @@ powershell.exe -NoProfile -ExecutionPolicy Bypass -File "C:\Users\k.zolotarev95\
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "C:\Users\k.zolotarev95\Documents\openwrt overlay\vps\deploy-router-updates.ps1" -Vps "root@193.233.82.38" -Action Rollback
```
Резервная копия: `/opt/owrt-remote/owrt-remote-hub.py.bak-before-router-updates-control-v117`.
Резервная копия: `/opt/owrt-remote/owrt-remote-hub.py.bak-before-router-updates-mobile-v117`.
Не устанавливай/не откатывай Hub, пока его очередь работает.
## Проверки
@@ -108,4 +122,9 @@ Dropbear и обновление физического OpenWrt требуют
`node tests/test_router_updates_ui.cjs` проверяет desktop/mobile, ввод команды,
очистку пароля, итоги, дашборд из 35 устройств, обновление списка и живых статусов,
сохранение раскрытого вывода и возобновление просмотра.
сохранение раскрытого вывода и возобновление просмотра. Проверяется список
проблемных роутеров, причины, фильтры четырёх категорий и нулевые результаты,
сохранение выбора и прокрутки при автообновлении, безопасный вывод текста и
сброс списка при обновлении роутеров. Дополнительно проверяются мобильные
ширины 320/360/390/430 px, альбомный режим, сохранение настоящей ширины viewport
при длинном тексте, размеры полей/кнопок и отсутствие горизонтального выезда.
+1 -1
View File
@@ -21,7 +21,7 @@ class RouterUpdatesDeployTests(unittest.TestCase):
self.target = self.root / 'hub.py'
self.previous = b'print("previous Hub")\n'
self.target.write_bytes(self.previous)
self.backup = self.root / 'hub.py.bak-before-router-updates-control-v117'
self.backup = self.root / 'hub.py.bak-before-router-updates-mobile-v117'
source = (ROOT / 'vps/deploy-router-updates.ps1').read_text(encoding='utf-8')
self.script = source.split("$RemoteScript = @'\n", 1)[1].split("\n'@", 1)[0]
self.script = self.script.replace('/opt/owrt-remote/owrt-remote-hub.py', self.target.as_posix())
+81 -3
View File
@@ -65,6 +65,7 @@ const server = http.createServer((req,res)=>{
assert.equal(await page.locator('.router small').textContent(),'ID: node-5');
assert.equal(await page.locator('#countTotal').textContent(),'1');
assert.equal(await page.locator('#countSuccess').textContent(),'0');
assert.equal(await page.locator('#queueOutcomePanel').isVisible(),false);
assert.equal(await page.locator('.live-badge').textContent(),'● Онлайн');
assert.equal(await page.locator('#command').inputValue(),'wget -O - "'+defaultRepo+'/install.sh?v=$(date +%s)" | sh');
const command=mobile?'https://another.example/updates/router.sh?v=2&from=hub':'wget -O - "https://repo.example/install.sh?v=$(date +%s)" | sh';
@@ -108,17 +109,69 @@ const server = http.createServer((req,res)=>{
assert.equal(await page.locator('#queueProgress').getAttribute('aria-valuenow'),'100');
await page.locator('#command').fill(command);
assert.equal(starts.length,count);
assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);
assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth&&innerWidth===visualViewport.width),true);
assert.equal(await page.evaluate(()=>JSON.stringify({...localStorage,...sessionStorage}).includes('test-password')),false);
await page.screenshot({path:path.join(root,mobile?'mobile.png':'desktop.png'),fullPage:true});
// Match the user's example exactly, including all finished outcomes.
job.items=Array.from({length:35},(_,i)=>({id:'node-'+(i+1),name:'Роутер '+(i+1),state:i<21?'success':i<25?'error':i<26?'unknown':i<27?'cancelled':'skipped',message:'Итог установки'}));
job.items=Array.from({length:35},(_,i)=>({id:'node-'+(i+1),name:i===21?'АНТОН ВПН':'Роутер '+(i+1),state:i<21?'success':i<25?'error':i<26?'unknown':i<27?'cancelled':'skipped',message:i===21?'Общий SSH-пароль не принят. Команда обновления не запускалась.':i===25?'SSH недоступен: результат и остановка не подтверждены.':'Итог установки: причина '+(i+1),output:i===21?'Permission denied\n'+Array.from({length:50},(_,i)=>'Диагностика '+i).join('\n'):''}));
await page.waitForFunction(()=>document.getElementById('countTotal').textContent==='35');
for(const [key,value] of Object.entries({Success:21,Error:4,Unknown:1,Cancelled:1,Skipped:8,Total:35,Active:0,Queued:0})) {
assert.equal(await page.locator('#count'+key).textContent(),String(value));
}
assert.equal(await page.locator('#queueProgress').getAttribute('aria-valuenow'),'100');
assert.equal(await page.locator('#queueOutcomePanel').isVisible(),true);
assert.equal(await page.locator('#outcomeTitle').textContent(),'Проблемы обновления · 14');
assert.equal(await page.locator('#outcomeList article').count(),14);
assert.equal(await page.locator('#outcomeList strong').first().textContent(),'АНТОН ВПН');
assert.equal(await page.locator('#outcomeList small').first().textContent(),'ID: node-22');
assert.match(await page.locator('#outcomeList .outcome-reason').first().textContent(),/Общий SSH-пароль не принят/);
assert.equal(await page.locator('#outcomeList article[data-router="node-1"]').count(),0);
const outcomeButton=state=>page.locator('.outcome-toggle[data-state="'+state+'"]');
await outcomeButton('error').click();
assert.equal(await page.locator('#outcomeTitle').textContent(),'Ошибки · 4');
assert.equal(await page.locator('#outcomeList article').count(),4);
assert.equal(await outcomeButton('error').getAttribute('aria-pressed'),'true');
assert.equal(await outcomeButton('unknown').getAttribute('aria-pressed'),'false');
assert.equal(await page.locator('#showAllOutcomes').isVisible(),true);
const errorRow=page.locator('#outcomeList article[data-router="node-22"]');
await errorRow.locator('summary').click();
await errorRow.locator('pre').evaluate(node=>{node.scrollTop=72;});
await page.locator('#outcomeList').evaluate(node=>{node.scrollTop=55;});
const savedScroll=await page.locator('#outcomeList').evaluate(node=>node.scrollTop);
const pollCount=polls;
job.items[21].output+='\nНовая строка';job.items[21].message+=' Ответ SSH сохранён.';
await page.waitForFunction(()=>document.querySelector('#outcomeList pre').textContent.includes('Новая строка'));
assert.ok(polls>pollCount);
assert.equal(await outcomeButton('error').getAttribute('aria-pressed'),'true');
assert.equal(await errorRow.locator('details').evaluate(node=>node.open),true);
assert.equal(await errorRow.locator('pre').evaluate(node=>node.scrollTop),72);
assert.equal(await page.locator('#outcomeList').evaluate(node=>node.scrollTop),savedScroll);
for(const [state,title,total] of [['unknown','Не подтверждено',1],['cancelled','Остановлено',1],['skipped','Пропущено',8]]) {
await outcomeButton(state).click();
assert.equal(await page.locator('#outcomeTitle').textContent(),title+' · '+total);
assert.equal(await page.locator('#outcomeList article').count(),total);
}
await page.locator('#showAllOutcomes').click();
assert.equal(await page.locator('#outcomeList article').count(),14);
assert.equal(await page.locator('#showAllOutcomes').isVisible(),false);
assert.equal(starts.length,count,'Viewing outcome details must never execute an update');
await page.evaluate(()=>document.querySelector('.queue-dashboard').scrollIntoView());
assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);
await page.locator('.queue-dashboard').screenshot({path:path.join(root,mobile?'mobile-summary.png':'desktop-summary.png')});
// Reproduce 5 errors and zero entries in the other result categories.
job.items=job.items.slice(0,5).map((item,i)=>({...item,state:'error',name:i===0?'<img src=x onerror="window.outcomeInjected=true">':item.name,message:'Ошибка SSH <script>window.outcomeInjected=true</script>'}));
await page.waitForFunction(()=>document.getElementById('countError').textContent==='5');
assert.equal(await page.locator('#outcomeList article').count(),5);
assert.equal(await page.evaluate(()=>window.outcomeInjected===true),false);
assert.equal(await page.locator('#outcomeList img,#outcomeList script').count(),0);
for(const state of ['unknown','cancelled','skipped']) {
await outcomeButton(state).click();
assert.equal(await page.locator('#outcomeList article').count(),0);
assert.equal(await page.locator('#outcomeList .outcome-empty').textContent(),'Роутеров в этой категории нет.');
}
// A different queue resets the previous category instead of hiding failures.
job={...job,id:'next-task'};
await page.waitForFunction(()=>document.getElementById('outcomeTitle').textContent==='Проблемы обновления · 5');
routers=[{id:'node-5',name:'АНТОН ВПН',online:true,last_seen:Math.floor(Date.now()/1000),xray:'running'},{id:'node-36',name:'Новый роутер',online:false,last_seen:0,xray:'unknown'}];
await page.locator('#refreshRouters').click();
await page.waitForFunction(()=>document.getElementById('status').textContent.includes('Можно запустить новую очередь'));
@@ -128,6 +181,8 @@ const server = http.createServer((req,res)=>{
assert.equal(await page.locator('.router strong').first().textContent(),'АНТОН ВПН');
assert.equal(await page.locator('#countTotal').textContent(),'2');
assert.equal(await page.locator('#countSuccess').textContent(),'0');
assert.equal(await page.locator('#queueOutcomePanel').isVisible(),false);
assert.equal(await page.locator('#outcomeList article').count(),0);
assert.equal(await page.locator('#start').isEnabled(),true);
assert.equal(await page.locator('#command').inputValue(),command);
await page.reload();
@@ -137,6 +192,29 @@ const server = http.createServer((req,res)=>{
assert.deepEqual(errors,[]);
await page.close();
}
// Long content must wrap without widening the mobile layout viewport.
const longName='Советская_30_Удалённый_роутер_'.repeat(8),longId='node-'+ 'x'.repeat(95);
for(const viewport of [{width:320,height:740},{width:360,height:800},{width:390,height:844},{width:430,height:932},{width:844,height:390}]) {
const page=await browser.newPage({viewport,isMobile:true,hasTouch:true,deviceScaleFactor:2});
const errors=[];page.on('pageerror',error=>errors.push(error.message));
routers=[{id:longId,name:longName,online:true,last_seen:Math.floor(Date.now()/1000),xray:'running'}];
job={id:'mobile-wrap',state:'finished',cancel_requested:false,items:[{id:longId,name:longName,state:'error',message:'Не удалось скачать https://updates.example/'+ 'abcdef'.repeat(100)+' — SSH не ответил.',output:'diagnostic='+ '0123456789'.repeat(150)}]};
await page.goto(`http://127.0.0.1:${server.address().port}/router-updates/`);
await page.waitForFunction(()=>document.getElementById('countError').textContent==='1');
await page.locator('#command').fill('wget -O - "https://updates.example/'+ 'longpath'.repeat(100)+'" | sh');
await page.locator('#sshPassword').fill('password');await page.locator('#sshPassword').focus();
await page.locator('#outcomeList summary').click();
await page.locator('#results summary').click();
const layout=await page.evaluate(()=>({width:innerWidth,visual:visualViewport.width,scroll:document.documentElement.scrollWidth,fields:['command','sshPassword'].map(id=>parseFloat(getComputedStyle(document.getElementById(id)).fontSize)),buttons:[...document.querySelectorAll('.head-actions button,.head-actions .btn,.actions button')].map(node=>({height:node.getBoundingClientRect().height,width:node.getBoundingClientRect().width})),panels:[...document.querySelectorAll('.panel')].map(node=>node.getBoundingClientRect().width),overflow:[...document.querySelectorAll('.head,.head-actions,.actions,.note,textarea,input,.queue-heading,.metric,.router,.outcome-router,pre')].filter(node=>{const rect=node.getBoundingClientRect();return rect.width&& (rect.left<0||rect.right>innerWidth+1);}).map(node=>node.id||node.className)}));
assert.equal(layout.width,viewport.width,JSON.stringify(layout));
assert.ok(layout.scroll<=viewport.width,JSON.stringify(layout));
assert.ok(Math.abs(layout.visual-viewport.width)<1,JSON.stringify(layout));
assert.deepEqual(layout.overflow,[]);
if(viewport.width<=680){assert.ok(layout.fields.every(size=>size>=16));assert.ok(layout.buttons.every(button=>button.height>=44));assert.equal(layout.buttons[0].width,layout.buttons[1].width);}
await page.screenshot({path:path.join(root,'mobile-layout-'+viewport.width+'.png'),fullPage:true});
assert.deepEqual(errors,[]);await page.close();
}
job=null;routers=[];
const dashboard=await browser.newPage();
await dashboard.goto(`http://127.0.0.1:${server.address().port}/`);
const link=dashboard.locator('#routerUpdatesGroup a');
@@ -144,6 +222,6 @@ const server = http.createServer((req,res)=>{
assert.equal(await link.getAttribute('href'),'/router-updates/');
assert.match(await link.getAttribute('rel'),/noopener/);
await dashboard.close();
console.log('Router updates desktop/mobile dashboard, live statuses, refresh, polling, reload, privacy and new-tab link: PASS');
console.log('Router updates desktop/mobile dashboard, outcome lists, 320/360/390/430px and landscape layouts, live statuses, refresh, polling, reload, privacy and new-tab link: PASS');
} finally {await browser.close();await new Promise(resolve=>server.close(resolve));}
})().catch(error=>{console.error(error);process.exitCode=1;});
+4 -1
View File
@@ -15,7 +15,7 @@ $RemoteScript = @'
set -eu
stage=/tmp/__UPLOAD_NAME__
target=/opt/owrt-remote/owrt-remote-hub.py
backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-router-updates-control-v117
backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-router-updates-mobile-v117
candidate=$target.new-__UPLOAD_NAME__
changed=0
@@ -70,6 +70,9 @@ required = (
"OWRT_UPDATE_OUTPUT_TEXT=",
"refreshRouters",
"queue-dashboard",
"queueOutcomePanel",
"function renderOutcomes(){",
"grid-template-columns:minmax(0,1fr)",
"def clear_finished(self, job_id):",
"\u041e\u0441\u0442\u0430\u043d\u043e\u0432\u0438\u0442\u044c \u0432\u0441\u0451",
"routerUpdatesGroup",
+28 -5
View File
@@ -12226,7 +12226,9 @@ def router_updates_html(csrf):
.wrap{max-width:1100px;margin:auto;padding:20px}.panel{margin-bottom:14px;padding:18px;border:1px solid var(--line);border-radius:12px;background:#191226e8}.head,.actions{display:flex;align-items:center;justify-content:space-between;gap:10px;flex-wrap:wrap}h1{font-size:22px;margin:0}h2{font-size:16px;margin:0 0 10px}.hint{color:var(--muted);font-size:13px}.note{margin:14px 0;padding:10px 12px;border:1px solid #f59e0b70;border-left:3px solid #f59e0b;border-radius:8px;background:#f59e0b12;color:#fde68a}
label{display:block;margin:14px 0 6px;font-weight:700}textarea,input{display:block;width:100%;min-width:0;border:1px solid var(--line);border-radius:8px;background:#0d0917;color:#f7f2ff;padding:11px;font:14px/1.5 ui-monospace,Consolas,monospace}textarea{min-height:110px;resize:vertical}input{max-width:480px}button,.btn{display:inline-flex;align-items:center;justify-content:center;min-height:42px;border:1px solid var(--line);border-radius:8px;padding:9px 14px;background:#393044;color:#f7f2ff;font:700 13px system-ui;cursor:pointer;text-decoration:none}.primary{background:#7c3aed}button:disabled{opacity:.5;cursor:default}.actions{justify-content:flex-start;margin-top:16px}.ok{color:#86efac}.error{color:#fda4af}.warn{color:#fde68a}#status{margin:12px 0;overflow-wrap:anywhere}.router{border-top:1px solid var(--line);padding:13px 0}.router:first-child{border-top:0}.router strong{display:block;overflow-wrap:anywhere}.router p{margin:5px 0;overflow-wrap:anywhere}.router small{color:var(--muted)}pre{max-height:260px;overflow:auto;white-space:pre-wrap;overflow-wrap:anywhere;background:#0d0917;border:1px solid var(--line);border-radius:8px;padding:10px;font:12px/1.5 ui-monospace,Consolas,monospace}summary{cursor:pointer;color:var(--muted)}
.head-actions{display:flex;gap:8px;flex-wrap:wrap}.queue-dashboard{margin:18px 0 14px;padding:18px;border:1px solid var(--line);border-radius:12px;background:linear-gradient(120deg,#30203e90,#141521b0)}.queue-heading{display:flex;align-items:center;justify-content:space-between;gap:12px;margin-bottom:12px}.queue-heading h2{margin:0;font-size:17px}.queue-badge{padding:4px 10px;border:1px solid #a78bfa50;border-radius:20px;background:#a78bfa12;color:#d8c8ff;font-size:12px;font-weight:700}.progress-label{display:flex;justify-content:space-between;gap:12px;margin-bottom:7px;color:var(--muted);font-size:12px}.progress-track{height:7px;overflow:hidden;border-radius:8px;background:#ffffff0b}.progress-fill{height:100%;width:0;background:linear-gradient(90deg,#8b5cf6,#38bdf8);border-radius:8px;transition:width .25s}.metrics{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:10px;margin-top:16px}.metric{--accent:#c4b5fd;min-width:0;padding:13px 12px;border:1px solid #ffffff12;border-top:2px solid var(--accent);border-radius:9px;background:#100b1b90}.metric[data-state=success]{--accent:#86efac}.metric[data-state=error]{--accent:#fda4af}.metric[data-state=unknown]{--accent:#fcd34d}.metric[data-state=cancelled]{--accent:#fdba74}.metric[data-state=skipped]{--accent:#b9adc9}.metric[data-state=active]{--accent:#7dd3fc}.metric span{display:block;color:var(--muted);font-size:12px;overflow-wrap:anywhere}.metric strong{display:block;margin-top:5px;color:var(--accent);font-size:27px;line-height:1.1;font-variant-numeric:tabular-nums}.router-live{display:flex;align-items:center;gap:7px;flex-wrap:wrap;margin:7px 0;color:var(--muted);font-size:12px}.live-badge{padding:2px 8px;border-radius:20px;background:#ffffff08;border:1px solid #ffffff16}.live-badge.online{color:#86efac;border-color:#86efac40;background:#86efac0a}.live-badge.offline{color:#fda4af;border-color:#fda4af40;background:#fda4af0a}
@media(max-width:680px){.wrap{padding:10px}.panel{padding:12px}.head{align-items:stretch;flex-direction:column}h1{font-size:19px}.actions,.head-actions{display:grid;grid-template-columns:1fr}.btn,button{width:100%}input{max-width:none}body{background-attachment:scroll}.queue-dashboard{padding:12px}.queue-heading{align-items:flex-start}.queue-heading h2{font-size:16px}.metrics{grid-template-columns:repeat(2,minmax(0,1fr));gap:8px}.metric{padding:12px}.metric strong{font-size:26px}}
.metrics{grid-auto-rows:1fr}.metric.outcome-toggle{display:block;width:100%;text-align:left;font:inherit}.outcome-toggle::after{content:'Подробнее ›';display:block;margin-top:7px;color:var(--muted);font-size:11px}.outcome-toggle:hover,.outcome-toggle[aria-pressed=true]{background:#ffffff0c;border-color:var(--accent)}.outcome-toggle:focus-visible{outline:2px solid var(--accent);outline-offset:3px}.queue-outcomes{margin-top:16px;padding-top:16px;border-top:1px solid var(--line)}.outcome-heading{display:flex;align-items:center;justify-content:space-between;gap:10px;flex-wrap:wrap}.outcome-heading h3{margin:0;font-size:15px}.outcome-list{max-height:440px;overflow:auto;scrollbar-gutter:stable;margin-top:10px}.outcome-router{padding:12px;border:1px solid var(--line);border-radius:8px;background:#100b1b70}.outcome-router+.outcome-router{margin-top:8px}.outcome-title{display:flex;align-items:center;gap:8px;justify-content:space-between;flex-wrap:wrap}.outcome-title strong{min-width:0;overflow-wrap:anywhere}.outcome-badge{flex-shrink:0;font-size:12px}.outcome-router small{display:block;color:var(--muted);overflow-wrap:anywhere}.outcome-reason{margin:7px 0 0;white-space:pre-wrap;overflow-wrap:anywhere}.outcome-router details{margin-top:7px}.outcome-empty{margin:8px 0;color:var(--muted)}[hidden]{display:none!important}
.wrap,.panel,form,.head,.head-actions,.actions,.queue-dashboard,.queue-heading,.queue-outcomes,.outcome-heading,.outcome-list,.router,.outcome-router{min-width:0;max-width:100%}.head>*{min-width:0}h1,h2,h3,.hint,.note,.router small,.router-live span,.outcome-badge{overflow-wrap:anywhere}button,.btn{white-space:normal;overflow-wrap:anywhere}textarea{white-space:pre-wrap;overflow-wrap:anywhere}pre{max-width:100%;min-width:0}.outcome-title strong{flex:1 1 160px}.outcome-badge{max-width:100%}
@media(max-width:680px){body{background-attachment:scroll;-webkit-text-size-adjust:100%;text-size-adjust:100%}.wrap{width:100%;padding:10px;padding-top:max(10px,env(safe-area-inset-top,0px));padding-right:max(10px,env(safe-area-inset-right,0px));padding-bottom:max(10px,env(safe-area-inset-bottom,0px));padding-left:max(10px,env(safe-area-inset-left,0px))}.panel{padding:12px}.head{align-items:stretch;flex-direction:column;gap:12px}h1{font-size:19px;line-height:1.35}.actions,.head-actions{display:grid;grid-template-columns:minmax(0,1fr);width:100%;gap:8px}.btn,button{width:100%;min-height:44px;padding:11px 12px}.head-actions .btn,.head-actions button,.actions button{font-size:14px}textarea,input{max-width:100%;font-size:16px;line-height:1.5}textarea{min-height:150px}input{max-width:none;min-height:46px}.note{margin:14px 0;padding:10px 12px;font-size:12px}.hint{font-size:12px}label{line-height:1.4}.queue-dashboard{padding:12px}.queue-heading{align-items:flex-start;flex-wrap:wrap;gap:8px}.queue-heading h2{font-size:16px;flex:1 1 160px}.queue-badge{max-width:100%;overflow-wrap:anywhere}.progress-label{font-size:11px}.progress-label>:first-child{min-width:0;overflow-wrap:anywhere}#progressPercent{flex-shrink:0}.metrics{grid-template-columns:repeat(2,minmax(0,1fr));gap:8px}.metric{padding:12px 10px}.metric span{font-size:12px;line-height:1.4}.metric strong{font-size:26px}.outcome-heading{align-items:stretch}.outcome-heading h3{width:100%;line-height:1.4}.outcome-list{max-height:min(440px,60vh);-webkit-overflow-scrolling:touch}.outcome-router{padding:10px}.outcome-title{align-items:flex-start}.outcome-badge{flex-shrink:1;text-align:left}summary{min-height:44px;padding:10px 0;line-height:1.5}.router{padding:14px 0}.router-live{align-items:flex-start;gap:6px}.router-live span{max-width:100%}pre{max-height:240px;padding:9px;font-size:12px}.outcome-reason{font-size:13px}}
</style></head><body><main class="wrap">
<section class="panel"><div class="head"><h1>Обновить все роутеры разом</h1><div class="head-actions"><button id="refreshRouters" type="button" disabled>Обновить список роутеров</button><a class="btn" href="/">Вернуться в Hub</a></div></div>
<blockquote class="note">Команда выполняется на роутерах по очереди через SSH. Укажи один общий SSH-пароль root. Для каждого роутера будет отдельный итог. Если туннель не работает, обновить этот роутер через VPS не получится.</blockquote>
@@ -12238,14 +12240,16 @@ label{display:block;margin:14px 0 6px;font-weight:700}textarea,input{display:blo
<div class="hint">«Остановить всё» сразу прекращает очередь и отправляет остановку текущей задачи. Уже внесённые установщиком изменения не откатываются. Если SSH недоступен, панель покажет, что остановка на роутере не подтверждена.</div>
<section class="queue-dashboard" aria-label="Статистика очереди"><div class="queue-heading"><h2 id="queueTitle">Список роутеров</h2><span class="queue-badge" id="queueBadge">Загрузка</span></div>
<div class="progress-label"><span id="progressText">Получаю данные…</span><span id="progressPercent">0%</span></div><div class="progress-track" id="queueProgress" role="progressbar" aria-label="Ход очереди" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0"><div class="progress-fill" id="progressFill"></div></div>
<div class="metrics"><div class="metric" data-state="total"><span>Всего роутеров</span><strong id="countTotal">0</strong></div><div class="metric" data-state="active"><span>Обновляются</span><strong id="countActive">0</strong></div><div class="metric" data-state="queued"><span>Ожидают</span><strong id="countQueued">0</strong></div><div class="metric" data-state="success"><span>Успешно</span><strong id="countSuccess">0</strong></div><div class="metric" data-state="error"><span>Ошибок</span><strong id="countError">0</strong></div><div class="metric" data-state="unknown"><span>Не подтверждено</span><strong id="countUnknown">0</strong></div><div class="metric" data-state="cancelled"><span>Остановлено</span><strong id="countCancelled">0</strong></div><div class="metric" data-state="skipped"><span>Пропущено</span><strong id="countSkipped">0</strong></div></div></section>
<div class="metrics"><div class="metric" data-state="total"><span>Всего роутеров</span><strong id="countTotal">0</strong></div><div class="metric" data-state="active"><span>Обновляются</span><strong id="countActive">0</strong></div><div class="metric" data-state="queued"><span>Ожидают</span><strong id="countQueued">0</strong></div><div class="metric" data-state="success"><span>Успешно</span><strong id="countSuccess">0</strong></div><button type="button" class="metric outcome-toggle" data-state="error" aria-controls="queueOutcomePanel" aria-pressed="false"><span>Ошибок</span><strong id="countError">0</strong></button><button type="button" class="metric outcome-toggle" data-state="unknown" aria-controls="queueOutcomePanel" aria-pressed="false"><span>Не подтверждено</span><strong id="countUnknown">0</strong></button><button type="button" class="metric outcome-toggle" data-state="cancelled" aria-controls="queueOutcomePanel" aria-pressed="false"><span>Остановлено</span><strong id="countCancelled">0</strong></button><button type="button" class="metric outcome-toggle" data-state="skipped" aria-controls="queueOutcomePanel" aria-pressed="false"><span>Пропущено</span><strong id="countSkipped">0</strong></button></div>
<section class="queue-outcomes" id="queueOutcomePanel" aria-labelledby="outcomeTitle" hidden><div class="outcome-heading"><h3 id="outcomeTitle">Проблемы обновления</h3><button type="button" id="showAllOutcomes" hidden>Показать все категории</button></div><p class="hint" id="outcomeHint">Здесь перечислены роутеры без подтверждённого успешного обновления и причины результата.</p><div class="outcome-list" id="outcomeList"></div></section></section>
<div id="status" role="status" aria-live="polite">Получаю список роутеров…</div></section>
<section class="panel"><h2>Роутеры</h2><div class="hint">Текущая связь определяется по Heartbeat. Итог установки показан отдельно и не означает, что роутер сейчас онлайн.</div><div id="results"></div></section>
</main><script>
(()=>{
const csrf=__CSRF__, endpoint='/api/router-updates', form=document.getElementById('updateForm'), command=document.getElementById('command'), password=document.getElementById('sshPassword'), start=document.getElementById('start'), cancel=document.getElementById('cancel'), status=document.getElementById('status'), results=document.getElementById('results');
const refreshRouters=document.getElementById('refreshRouters');
let timer=null, pending=false, refreshing=false, job=null, routers=[], lastRender='', stopped=false, generation=0;
const refreshRouters=document.getElementById('refreshRouters'),outcomePanel=document.getElementById('queueOutcomePanel'),outcomeList=document.getElementById('outcomeList'),showAllOutcomes=document.getElementById('showAllOutcomes');
const outcomeLabels={error:'Ошибка',unknown:'Не подтверждено',cancelled:'Остановлено',skipped:'Пропущено'},outcomeTitles={error:'Ошибки',unknown:'Не подтверждено',cancelled:'Остановлено',skipped:'Пропущено'};
let timer=null, pending=false, refreshing=false, job=null, routers=[], lastRender='', stopped=false, generation=0,outcomeFilter='all',lastOutcomeRender='',outcomeJobId=null;
let requestId='';
const requestKey='owrt-router-update-request';
try{requestId=sessionStorage.getItem(requestKey)||'';}catch(error){}
@@ -12260,8 +12264,25 @@ label{display:block;margin:14px 0 6px;font-weight:700}textarea,input{display:blo
document.getElementById('progressText').textContent=job?'Обработано '+done+' из '+counts.Total:'Актуальный список · '+routers.filter(x=>x.online===true).length+' в сети';
document.getElementById('progressPercent').textContent=percent+'%';document.getElementById('progressFill').style.width=percent+'%';document.getElementById('queueProgress').setAttribute('aria-valuenow',percent);
}
function renderOutcomes(){
const jobId=job?job.id:null;
if(jobId!==outcomeJobId){outcomeJobId=jobId;outcomeFilter='all';lastOutcomeRender='';outcomeList.scrollTop=0;}
outcomePanel.hidden=!job&&outcomeFilter==='all';showAllOutcomes.hidden=outcomeFilter==='all';
document.querySelectorAll('.outcome-toggle').forEach(button=>button.setAttribute('aria-pressed',String(button.dataset.state===outcomeFilter)));
const items=(job?job.items:[]).filter(item=>Object.hasOwn(outcomeLabels,item.state)&&(outcomeFilter==='all'||item.state===outcomeFilter));
document.getElementById('outcomeTitle').textContent=(outcomeFilter==='all'?'Проблемы обновления':outcomeTitles[outcomeFilter])+' · '+items.length;
const signature=JSON.stringify([jobId,outcomeFilter,items]);if(signature===lastOutcomeRender)return;lastOutcomeRender=signature;
const scrollTop=outcomeList.scrollTop,open=new Map(Array.from(outcomeList.querySelectorAll('article')).map(row=>[row.dataset.router,{open:!!row.querySelector('details[open]'),top:row.querySelector('pre')?.scrollTop||0}])),fragment=document.createDocumentFragment();
if(!items.length){const empty=document.createElement('p');empty.className='outcome-empty';empty.textContent=!job?'Сначала запусти очередь обновления.':outcomeFilter==='all'?'Роутеров с ошибками, без подтверждения, остановленных или пропущенных пока нет.':'Роутеров в этой категории нет.';fragment.append(empty);}
items.forEach(item=>{
const row=document.createElement('article'),header=document.createElement('div'),name=document.createElement('strong'),badge=document.createElement('span'),id=document.createElement('small'),reason=document.createElement('p');
row.className='outcome-router';row.dataset.router=item.id;header.className='outcome-title';name.textContent=item.name||'Имя роутера не получено';badge.className='outcome-badge '+(item.state==='error'?'error':'warn');badge.textContent=outcomeLabels[item.state];header.append(name,badge);id.textContent='ID: '+item.id;reason.className='outcome-reason';reason.textContent=item.message||'Причина не получена от задачи обновления.';row.append(header,id,reason);
if(item.output){const details=document.createElement('details'),summary=document.createElement('summary'),output=document.createElement('pre');summary.textContent='Вывод команды';output.textContent=item.output;details.open=!!open.get(item.id)?.open;details.append(summary,output);row.append(details);}fragment.append(row);
});
outcomeList.replaceChildren(fragment);outcomeList.scrollTop=scrollTop;outcomeList.querySelectorAll('article').forEach(row=>{const output=row.querySelector('pre');if(output)output.scrollTop=open.get(row.dataset.router)?.top||0;});
}
function render(data){
job=data.job;routers=data.routers||[];controls();dashboard();const items=job?job.items:routers, signature=JSON.stringify([items,routers]);if(signature===lastRender)return;lastRender=signature;
job=data.job;routers=data.routers||[];controls();dashboard();renderOutcomes();const items=job?job.items:routers, signature=JSON.stringify([items,routers]);if(signature===lastRender)return;lastRender=signature;
const open=new Map(Array.from(results.querySelectorAll('article')).map(row=>[row.dataset.router,{open:!!row.querySelector('details[open]'),top:row.querySelector('pre')?.scrollTop||0}])), fragment=document.createDocumentFragment();
items.forEach(item=>{const row=document.createElement('article'), title=document.createElement('strong'), detail=document.createElement('p'), id=document.createElement('small');
row.className='router';row.dataset.router=item.id;title.textContent=(item.state==='success'?'Успешно — ':item.state==='error'?'Ошибка — ':item.state==='unknown'?'Не подтверждено — ':item.state==='cancelled'?'Остановлено — ':'')+(item.name||'Имя роутера не получено');title.className=item.state==='success'?'ok':item.state==='error'?'error':['unknown','cancelled'].includes(item.state)?'warn':'';detail.textContent=item.message||'Готов к постановке в очередь';id.textContent='ID: '+item.id;row.append(title,id,detail);
@@ -12274,6 +12295,8 @@ label{display:block;margin:14px 0 6px;font-weight:700}textarea,input{display:blo
async function refresh(){if(stopped||pending)return;const current=++generation;if(timer!==null)clearTimeout(timer);timer=null;try{const data=await api('');if(current!==generation||pending)return;render(data);status.className='';status.textContent=summary();if(job&&job.state!=='running'&&job.request_id===requestId)forgetRequest();}catch(error){if(current===generation){status.className='error';status.textContent='Не удалось получить состояние: '+error.message;}}finally{if(!stopped&&!pending&&current===generation)timer=setTimeout(refresh,3000);}}
form.addEventListener('submit',async event=>{event.preventDefault();if(pending||(job&&job.state==='running'))return;generation++;pending=true;controls();if(timer!==null)clearTimeout(timer);try{const body={command:command.value,ssh_password:password.value,request_id:requestToken()};const data=await api('/start',body);password.value='';render(data);status.className='';status.textContent=summary();}catch(error){password.value='';status.className='error';status.textContent='Запуск не подтверждён: '+error.message+'. Проверяю состояние очереди.';}finally{pending=false;controls();if(!stopped)timer=setTimeout(refresh,1000);}});
cancel.addEventListener('click',async()=>{if(!job||pending)return;generation++;if(timer!==null)clearTimeout(timer);pending=true;controls();status.textContent='Останавливаю текущую задачу и очередь…';try{const data=await api('/cancel',{id:job.id});render(data);status.textContent=summary();}catch(error){status.textContent='Остановка не подтверждена: '+error.message;}finally{pending=false;controls();if(!stopped)timer=setTimeout(refresh,1000);}});
document.querySelectorAll('.outcome-toggle').forEach(button=>button.addEventListener('click',()=>{outcomeFilter=button.dataset.state;outcomeList.scrollTop=0;renderOutcomes();}));
showAllOutcomes.addEventListener('click',()=>{outcomeFilter='all';outcomeList.scrollTop=0;renderOutcomes();});
refreshRouters.addEventListener('click',async()=>{if(pending)return;const current=++generation;if(timer!==null)clearTimeout(timer);pending=true;refreshing=true;controls();status.className='';status.textContent='Обновляю список и статусы роутеров…';try{const data=await api('/refresh',{id:job?job.id:''});if(current!==generation)return;render(data);if(!job)forgetRequest();status.textContent=job?'Статусы обновлены. '+summary():'Список и статусы обновлены. Можно запустить новую очередь.';}catch(error){status.className='error';status.textContent='Не удалось обновить список: '+error.message;}finally{pending=false;refreshing=false;controls();if(!stopped)timer=setTimeout(refresh,3000);}});
window.addEventListener('pagehide',()=>{stopped=true;if(timer!==null)clearTimeout(timer);password.value='';});
window.addEventListener('pageshow',()=>{if(stopped){stopped=false;refresh();}});refresh();