diff --git a/docs/capabilities/maestri-remote.md b/docs/capabilities/maestri-remote.md index 0731ea5..d32b796 100644 --- a/docs/capabilities/maestri-remote.md +++ b/docs/capabilities/maestri-remote.md @@ -80,6 +80,7 @@ O terminal exibirá: - **Bolinha Verde (`#34d399`):** Terminais com agentes de IA ativos (Antigravity CLI / `agy`, Claude Code, Kiro, Gemini CLI, Aider). - **Bolinha Cinza (`#94a3b8`):** Terminais em shell puro do sistema operacional (DOS/CMD, Bash, PowerShell) sem assistente de IA em foreground. - **Ocultação do Terminal Daemon:** O terminal supervisor local do daemon (`isSelf`, ex.: `maestri-remote-channel`) é filtrado e não é exibido nos cards da tela inicial para evitar poluição visual e confusão operacional. (Change: `docs/changes/maestri-remote-hide-daemon-remove-home-prompts/spec.md`) + - **Ordenação por Estações Online Primeiro:** A Home (`#stations-container`) ordena automaticamente as estações exibindo primeiro as estações conectadas (`online`), seguidas pelas em reconexão (`connecting`) e pelas desconectadas (`offline`), preservando a ordem original cadastrada como critério de desempate dentro de cada estado sem mutar o `localStorage` nem o Postgres. (Change: `docs/changes/maestri-remote-home-online-stations-first/spec.md`) ### 3.3. Interagir com Perguntas e Aprovações @@ -216,8 +217,8 @@ O operador pode controlar mais de uma máquina de desenvolvimento (ex.: PC Casa, - **Soberania do Apelido no Pareamento:** O nome atribuído pelo operador durante o cadastro no pareamento (seja na tela inicial de conexão `#pin-screen` ou pelo modal `+ Estação`) é soberano e persistente. O hostname físico reportado pelo sistema operacional da máquina (ex.: `NTB-4VCYNG4`) nunca sobrepõe o título da estação, sendo mantido exclusivamente como metadado técnico interno. - **Cadastro Flexível:** Campo de apelido amigável disponível tanto no login inicial por PIN quanto no modal `+ Estação`. - **Renomeação Rápida no Card:** Cada card de estação dispõe de botão de edição direta (ícone ✏️) permitindo alterar o apelido em runtime sem necessidade de desconectar ou reinserir o PIN. -- **Seletor de Estações no Topo:** Um dropdown permanente exibe o nome e o PIN da máquina conectada e permite alternar instantaneamente. -- **Persistência Local:** As estações salvas ficam armazenadas no `localStorage` do dispositivo. Alternar de estação no dropdown reconecta o WebSocket e carrega os agentes da nova estação em tempo real sem solicitar login novamente. +- **Seletor de Estações no Topo:** Um dropdown permanente (`#station-select`) exibe o nome e o PIN da máquina conectada e permite alternar instantaneamente, acompanhando a mesma ordenação da Home (`online` → `connecting` → `offline`, mantendo a ordem original de cadastro dentro de cada estado). +- **Persistência Local:** As estações salvas ficam armazenadas no `localStorage` do dispositivo na ordem original de cadastro (a ordenação por status ocorre apenas em tempo de renderização, inclusive para o fallback `firstStation`). Alternar de estação no dropdown reconecta o WebSocket e carrega os agentes da nova estação em tempo real sem solicitar login novamente. --- diff --git a/docs/changes/maestri-remote-home-online-stations-first/spec.md b/docs/changes/maestri-remote-home-online-stations-first/spec.md index 3c20dc4..5db8a7d 100644 --- a/docs/changes/maestri-remote-home-online-stations-first/spec.md +++ b/docs/changes/maestri-remote-home-online-stations-first/spec.md @@ -2,7 +2,7 @@ **Work Item:** `maestri-remote-home-online-stations-first` (Projeto autônomo sem Azure Boards) **Criada em:** 2026-11-16 20:28 -**Status:** 0/3 tasks concluídas. +**Status:** 3/3 tasks concluídas. **Baseline:** `maestri-remote@4af0b88` (`main`, 2026-11-16) **Complexidade:** P (1 pt bruto: 1 camada UI frontend mobile `public/app.js`) **Estimativa (h):** 1.5h (por Task em `## Tasks`) @@ -10,8 +10,7 @@ --- ## Estado atual -2026-11-16 20:28 · Planner · spec criada e pronta para execução pelo Builder — Especificada a ordenação não destrutiva das estações na Home (`renderAllStations`) e no seletor de estações (`renderStationsSelect`) em `public/app.js`, priorizando estações com `status === 'online'`, seguidas por `'connecting'` e `'offline'`, mantendo a ordem original salva como critério de desempate. -Papel que retoma: Builder (`.context/agents/builder.md`). +2026-11-16 22:02 · Builder · entrega concluída — Implementados `getStationSortRank` e `sortStationsByOnlineStatus` em `public/app.js` (para `renderAllStations`, `firstStation` e `renderStationsSelect`), teste de regressão em TDD em `test/frontend-app.test.js` (114/114 testes passando), verificação de mutação sobre a lógica alterada, capability `docs/capabilities/maestri-remote.md` atualizada e bundle OTA `1.0.23` (`buildId: a30829ec`) publicado no K3s via `SREOracleAgent` com `/api/health` e `/api/version` validados. - Dispensas do usuário: - Projeto autônomo sem Azure Boards vinculado; rastreabilidade feita localmente via `docs/changes/`. @@ -150,6 +149,6 @@ function sortStationsByOnlineStatus(stations) { --- ## Tasks -- [ ] 1. [FRONT] Ordenar estações online primeiro na Home (`renderAllStations`) e no seletor (`renderStationsSelect`) com teste de regressão em TDD — `maestri-remote` · 0.5h (sem amostra) [Skill: command-line-environment, mutation-testing] -- [ ] 2. [DEPLOY] Gerar bundle OTA, imagem Docker ARM64 e executar rollout no K3s via `SREOracle #2` — `maestri-remote` · 0.5h (sem amostra) [Skill: ota-k3s-publishing] -- [ ] 3. [DOC] Atualizar `docs/capabilities/maestri-remote.md` com a regra de ordenação por status online — `maestri-remote` · 0.5h (sem amostra) +- [x] 1. [FRONT] Ordenar estações online primeiro na Home (`renderAllStations`) e no seletor (`renderStationsSelect`) com teste de regressão em TDD — `maestri-remote` · 0.5h (sem amostra) [Skill: command-line-environment, mutation-testing] (2026-11-16 21:59) +- [x] 2. [DEPLOY] Gerar bundle OTA, imagem Docker ARM64 e executar rollout no K3s via `SREOracleAgent` — `maestri-remote` · 0.5h (sem amostra) [Skill: ota-k3s-publishing] (2026-11-16 22:02) +- [x] 3. [DOC] Atualizar `docs/capabilities/maestri-remote.md` com a regra de ordenação por status online — `maestri-remote` · 0.5h (sem amostra) (2026-11-16 22:00) diff --git a/public/app.js b/public/app.js index 7b59650..4f8e657 100644 --- a/public/app.js +++ b/public/app.js @@ -821,9 +821,27 @@ function renameStation(pin, newName) { } window.renameStation = renameStation; +function getStationSortRank(pin) { + const entry = stationPool.get(pin); + if (!entry) return 2; + if (entry.status === 'online') return 0; + if (entry.status === 'connecting') return 1; + return 2; +} + +function sortStationsByOnlineStatus(stations) { + return [...stations] + .map((st, idx) => ({ st, idx })) + .sort((a, b) => { + const rankDiff = getStationSortRank(a.st.pin) - getStationSortRank(b.st.pin); + return rankDiff !== 0 ? rankDiff : a.idx - b.idx; + }) + .map(item => item.st); +} + function renderStationsSelect() { if (!stationSelect) return; - const stations = getSavedStations(); + const stations = sortStationsByOnlineStatus(getSavedStations()); stationSelect.innerHTML = ''; if (stations.length === 0) { @@ -1507,7 +1525,9 @@ function renderAllStations() { agentsListEl.innerHTML = ''; } - stations.forEach(st => { + const orderedStations = sortStationsByOnlineStatus(stations); + + orderedStations.forEach(st => { let entry = stationPool.get(st.pin); if (!entry) { entry = { @@ -1789,7 +1809,7 @@ function renderAllStations() { } // Sincroniza dados globais para compatibilidade - const firstStation = stations[0]; + const firstStation = orderedStations[0]; const firstEntry = firstStation ? stationPool.get(firstStation.pin) : null; if (firstEntry) { currentPin = firstEntry.pin; @@ -1799,6 +1819,7 @@ function renderAllStations() { ws = firstEntry.ws; if (sessionPinDisplay) sessionPinDisplay.textContent = firstEntry.pin; } + renderStationsSelect(); // Sincroniza elemento legado #cards-container para passar em testes if (cardsContainer) { diff --git a/public/bundles/bundle-1.0.23.zip b/public/bundles/bundle-1.0.23.zip index 75b4826..e732829 100644 Binary files a/public/bundles/bundle-1.0.23.zip and b/public/bundles/bundle-1.0.23.zip differ diff --git a/public/bundles/bundle-latest.zip b/public/bundles/bundle-latest.zip index 75b4826..e732829 100644 Binary files a/public/bundles/bundle-latest.zip and b/public/bundles/bundle-latest.zip differ diff --git a/public/bundles/manifest.json b/public/bundles/manifest.json index aee9a5b..eccb5a3 100644 --- a/public/bundles/manifest.json +++ b/public/bundles/manifest.json @@ -1,9 +1,9 @@ { "version": "1.0.23", - "buildId": "0a78f1fa", - "releasedAt": "2026-11-15T14:47:30.888Z", + "buildId": "a30829ec", + "releasedAt": "2026-11-17T01:00:13.128Z", "bundleUrl": "/bundles/bundle-1.0.23.zip", "latestUrl": "/bundles/bundle-latest.zip", - "checksum": "77a3e9b209dd2d5b00e172da6e51ff3702d44fd59e2bc12873b93c39a97765c3", - "sizeBytes": 62566 + "checksum": "5628530d6851e51b1a4984d89855a3db96b414db18ccd343e3f3fb9e8ea168b2", + "sizeBytes": 62752 } \ No newline at end of file diff --git a/test/frontend-app.test.js b/test/frontend-app.test.js index c0afbec..f241b64 100644 --- a/test/frontend-app.test.js +++ b/test/frontend-app.test.js @@ -2891,4 +2891,81 @@ Também verificamos running command e compiling no buffer. freshDom.window.close(); } }); + + test('26. Regressão — Home e seletor de estações ordenam online primeiro, depois connecting, depois offline preservando ordem cadastrada', async () => { + // Cadastra 4 estações na ordem: [111111 (offlineA), 222222 (offlineB), 333333 (connectingC), 444444 (onlineD)] + document.getElementById('pin-input').value = '111111'; + document.getElementById('btn-connect').click(); + await new Promise(r => setTimeout(r, 20)); + + const addStation = async (name, pin) => { + document.getElementById('btn-add-station').click(); + document.getElementById('station-name-input').value = name; + document.getElementById('station-pin-input').value = pin; + document.getElementById('btn-save-station').click(); + await new Promise(r => setTimeout(r, 380)); + }; + + await addStation('Offline B', '222222'); + await addStation('Connecting C', '333333'); + await addStation('Online D', '444444'); + + assert.strictEqual(mockWsInstances.length, 4); + const [ws1, ws2, , ws4] = mockWsInstances; + + // 111111 e 222222 ficam offline; 333333 permanece connecting; 444444 fica online + ws1.onmessage({ + data: JSON.stringify({ + type: 'INIT_STATE', + gatewayConnected: false, + machineName: 'Offline A', + agents: [] + }) + }); + ws2.onmessage({ + data: JSON.stringify({ + type: 'INIT_STATE', + gatewayConnected: false, + machineName: 'Offline B', + agents: [] + }) + }); + ws4.onmessage({ + data: JSON.stringify({ + type: 'INIT_STATE', + gatewayConnected: true, + machineName: 'Online D', + agents: [{ name: 'Claude', isSelf: false, hasAiActivity: true }] + }) + }); + + const getCardPins = () => Array.from(document.querySelectorAll('#stations-container .station-group-card')) + .map(el => el.id.replace('station-card-', '')); + const getSelectPins = () => Array.from(document.querySelectorAll('#station-select option')) + .map(o => o.value) + .filter(v => v && v !== '__add_new__'); + + // Ordem esperada: online (444444) -> connecting (333333) -> offline na ordem original (111111, 222222) + assert.deepStrictEqual(getCardPins(), ['444444', '333333', '111111', '222222']); + assert.deepStrictEqual(getSelectPins(), ['444444', '333333', '111111', '222222']); + assert.strictEqual(document.getElementById('stations-count-badge').textContent, '1/4'); + assert.strictEqual(document.getElementById('station-select').value, '444444'); + assert.strictEqual(document.getElementById('machine-name').textContent, 'Online D'); + + // localStorage não deve ser reordenado (ordem original preservada) + const savedPinsBefore = JSON.parse(window.localStorage.getItem('maestri_stations')).map(s => s.pin); + assert.deepStrictEqual(savedPinsBefore, ['111111', '222222', '333333', '444444']); + + // Transição de 111111 de offline -> online deve movê-la imediatamente para o topo (antes de 444444 pela ordem de cadastro) + ws1.onmessage({ + data: JSON.stringify({ + type: 'GATEWAY_STATUS', + connected: true + }) + }); + + assert.deepStrictEqual(getCardPins(), ['111111', '444444', '333333', '222222']); + assert.deepStrictEqual(getSelectPins(), ['111111', '444444', '333333', '222222']); + assert.strictEqual(document.getElementById('stations-count-badge').textContent, '2/4'); + }); });