Skip to content

Commit 7ab7e71

Browse files
net0wellclaude
andcommitted
feat(painel): filtro por trilha nas Etapas e recarga de tela que não carregou (spec 008)
- Lista de Etapas: o filtro "Trilha" mostra as Etapas da versão publicada da trilha, na ordem dos passos, e fica na URL (`?trilha=`). O detalhe da trilha ganha o link "Ver Etapas desta trilha". Uma trilha sem versão publicada mostra um aviso (AC-26). - Quando o código de uma tela não baixa (rede oscilou ou versão nova do painel), a página recarrega uma vez na rota pedida. Se falhar de novo em até 10 s, aparece "Não foi possível carregar esta tela" com Recarregar, sem laço (AC-27, D-163). Essa tela é importada direto e é pública, para abrir mesmo sem rede. - Testes: E2E do AC-26 e do AC-27, e Vitest da detecção da falha e da trava de 10 s. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 7f75b06 commit 7ab7e71

12 files changed

Lines changed: 284 additions & 10 deletions

File tree

‎README.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -161,8 +161,8 @@ O host `hosts/PythonScriptRunner.WorkerHost` é um worker pronto, configurado po
161161
Com `PythonScriptRunner.Dashboard`, o painel é embutido na sua aplicação, no estilo do Hangfire: API interna, atualizações
162162
em tempo real (SignalR) e a interface Vue servida no prefixo escolhido. Sem `MapPythonScriptRunnerDashboard` não existe painel.
163163

164-
A interface (em pt-BR, tema claro/escuro) cobre a visão geral, Etapas (editor Monaco com construtor de campos, testar
165-
pela fila e publicar), Trilhas (editor visual com *handles* tipados, ou lista editável, testar e publicar), execuções ao
164+
A interface (em pt-BR, tema claro/escuro) cobre a visão geral, Etapas (lista filtrável por trilha, editor Monaco com
165+
construtor de campos, testar pela fila e publicar), Trilhas (editor visual com *handles* tipados, ou lista editável, testar e publicar), execuções ao
166166
vivo (fluxo por status, logs, arquivos, linha do tempo, cancelar e reprocessar), agendamentos com prévia do cron,
167167
auditoria e administração. Ela vai dentro do pacote: não há nada para hospedar à parte.
168168

‎panel/src/api/schema.d.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2240,6 +2240,7 @@ export interface operations {
22402240
query?: {
22412241
search?: string;
22422242
status?: components["schemas"]["VersionStatus"];
2243+
pipelineKey?: string;
22432244
page?: number;
22442245
pageSize?: number;
22452246
};

‎panel/src/components/common/CatalogList.vue‎

Lines changed: 67 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
<script setup lang="ts">
2-
import { ref, watch } from 'vue'
2+
import { computed, onMounted, ref, watch } from 'vue'
33
import { useI18n } from 'vue-i18n'
4-
import { useRouter } from 'vue-router'
4+
import { useRoute, useRouter } from 'vue-router'
55
import { api, apiFetch, ensureOk, unwrap, type Schemas } from '@/api/client'
66
import PageHeader from '@/components/common/PageHeader.vue'
77
import { useApiAction, useErrorText } from '@/composables/useApiAction'
@@ -11,9 +11,10 @@ import { formatDateTime } from '@/utils/format'
1111
1212
type Summary = Schemas['StageSummary'] | Schemas['PipelineSummary']
1313
14-
/** Lista de Etapas ou Trilhas (spec 008): busca, filtro por status, versão publicada, uso; Autor cria e importa. */
14+
/** Lista de Etapas ou Trilhas (spec 008): busca, filtro por status (e por trilha, nas Etapas), versão publicada, uso; Autor cria e importa. */
1515
const props = defineProps<{ kind: 'stages' | 'pipelines' }>()
1616
const { t } = useI18n()
17+
const route = useRoute()
1718
const router = useRouter()
1819
const session = useSession()
1920
const notify = useNotify()
@@ -31,6 +32,13 @@ const createError = ref<string | null>(null)
3132
const draft = ref({ key: '', name: '', description: '' })
3233
const importing = ref(false)
3334
35+
// Filtro "Trilha" das Etapas (D-164, D-165): só as Etapas da última versão publicada da trilha, na ordem dos passos.
36+
// Fica na URL (`?trilha=`) para o link poder ser compartilhado.
37+
const queryPipeline = () => (props.kind === 'stages' && typeof route.query.trilha === 'string' && route.query.trilha) || null
38+
const pipelineKey = ref<string | null>(queryPipeline())
39+
const pipelines = ref<Schemas['PipelineSummary'][]>([])
40+
const selectedPipeline = computed(() => pipelines.value.find((p) => p.key === pipelineKey.value) ?? null)
41+
3442
const headers = [
3543
{ title: t('catalog.key'), key: 'key', sortable: false },
3644
{ title: t('catalog.name'), key: 'name', sortable: false },
@@ -49,7 +57,7 @@ async function load() {
4957
}
5058
const result = await run(() =>
5159
props.kind === 'stages'
52-
? unwrap(api.GET('/stages', { params: { query } }))
60+
? unwrap(api.GET('/stages', { params: { query: { ...query, pipelineKey: pipelineKey.value ?? undefined } } }))
5361
: unwrap(api.GET('/pipelines', { params: { query } })),
5462
)
5563
if (result) {
@@ -70,6 +78,41 @@ watch(search, () => {
7078
}, 300)
7179
})
7280
watch([status, page, pageSize], () => void load(), { immediate: true })
81+
watch(pipelineKey, (key) => {
82+
void router.replace({ query: { ...route.query, trilha: key ?? undefined } })
83+
if (page.value === 1) {
84+
void load()
85+
} else {
86+
page.value = 1
87+
}
88+
})
89+
watch(
90+
() => route.query.trilha,
91+
() => {
92+
if (queryPipeline() !== pipelineKey.value) {
93+
pipelineKey.value = queryPipeline()
94+
}
95+
},
96+
)
97+
98+
async function loadPipelines() {
99+
const all: Schemas['PipelineSummary'][] = []
100+
for (let number = 1; ; number++) {
101+
const result = await unwrap(api.GET('/pipelines', { params: { query: { page: number, pageSize: 100 } } }))
102+
all.push(...result.items)
103+
if (result.items.length === 0 || all.length >= result.total) {
104+
break
105+
}
106+
}
107+
108+
pipelines.value = all
109+
}
110+
111+
onMounted(() => {
112+
if (props.kind === 'stages') {
113+
void run(loadPipelines)
114+
}
115+
})
73116
74117
const detailRoute = (key: string) => ({ name: props.kind === 'stages' ? 'stage' : 'pipeline', params: { key } })
75118
@@ -156,7 +199,27 @@ function usedBy(item: Summary) {
156199
hide-details
157200
style="max-width: 220px"
158201
/>
202+
<v-autocomplete
203+
v-if="kind === 'stages'"
204+
v-model="pipelineKey"
205+
:items="pipelines.map((p) => ({ value: p.key, title: p.name }))"
206+
:label="t('catalog.pipeline')"
207+
clearable
208+
hide-details
209+
style="max-width: 320px"
210+
data-testid="pipeline-filter"
211+
/>
159212
</v-card-text>
213+
<v-alert
214+
v-if="selectedPipeline && !selectedPipeline.latestPublishedVersion"
215+
type="info"
216+
variant="tonal"
217+
density="compact"
218+
class="mx-4 mb-2"
219+
data-testid="pipeline-unpublished"
220+
>
221+
{{ t('catalog.pipelineUnpublished') }}
222+
</v-alert>
160223
<v-data-table-server
161224
v-model:page="page"
162225
v-model:items-per-page="pageSize"

‎panel/src/i18n/pt-BR.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,11 @@ export default {
4646
forbidden: { title: 'Sem permissão', text: 'Seu papel não permite abrir esta página.' },
4747
},
4848
notFound: { title: 'Página não encontrada', text: 'O endereço não existe no painel.' },
49+
loadFailed: {
50+
title: 'Não foi possível carregar esta tela',
51+
text: 'A conexão oscilou ou o painel foi atualizado enquanto você navegava.',
52+
reload: 'Recarregar',
53+
},
4954
realtime: { unavailable: 'Atualização em tempo real indisponível; a tela continua atualizando a cada 5 segundos.' },
5055
common: {
5156
cancel: 'Cancelar',
@@ -199,6 +204,7 @@ export default {
199204
version: 'Versão',
200205
publishedAt: 'Publicada em',
201206
pipeline: 'Trilha',
207+
pipelineUnpublished: 'Esta trilha ainda não tem versão publicada.',
202208
export: 'Exportar',
203209
archive: 'Arquivar',
204210
import: 'Importar zip',
@@ -268,6 +274,7 @@ export default {
268274
deleteText: 'Excluir a trilha {key}, as versões e os agendamentos? Não dá para desfazer.',
269275
recentRuns: 'Execuções recentes',
270276
allRuns: 'Ver todas as execuções',
277+
stagesLink: 'Ver Etapas desta trilha',
271278
run: {
272279
open: 'Disparar',
273280
title: 'Disparar {name}',

‎panel/src/router/index.ts‎

Lines changed: 24 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,9 @@ import { createRouter, createWebHistory, type RouteLocationNormalized, type Rout
22
import { basePath, type Role } from '@/api/client'
33
import { useSession } from '@/stores/session'
44
import AppShell from '@/components/layout/AppShell.vue'
5+
import LoadFailedView from '@/views/LoadFailedView.vue'
6+
import { safeReturn } from './paths'
7+
import { claimReload, isLoadError, sessionStore } from './reload'
58

69
declare module 'vue-router' {
710
interface RouteMeta {
@@ -33,6 +36,13 @@ export const routes: RouteRecordRaw[] = [
3336
component: () => import('@/views/NoRoleView.vue'),
3437
meta: { public: true, title: 'auth.noRole.title' },
3538
},
39+
{
40+
// Importada direto e pública: tem de abrir mesmo quando a rede não entrega os outros pedaços (AC-27).
41+
path: '/falha-ao-carregar',
42+
name: 'load-failed',
43+
component: LoadFailedView,
44+
meta: { public: true, title: 'loadFailed.title' },
45+
},
3646
{
3747
path: '/',
3848
component: AppShell,
@@ -125,10 +135,7 @@ export const routes: RouteRecordRaw[] = [
125135
},
126136
]
127137

128-
/** Destino interno seguro para "voltar" depois do login (sem redirecionamento aberto). */
129-
export function safeReturn(value: unknown): string {
130-
return typeof value === 'string' && value.startsWith('/') && !value.startsWith('//') && !value.startsWith('/\\') ? value : '/'
131-
}
138+
export { safeReturn } from './paths'
132139

133140
/**
134141
* Entrada conforme o modo de acesso (spec 008 §0): login fixo → /entrar; host → loginUrl; filtro ou local negado →
@@ -175,5 +182,18 @@ export async function guard(to: RouteLocationNormalized) {
175182
export function createAppRouter() {
176183
const router = createRouter({ history: createWebHistory(basePath), routes })
177184
router.beforeEach(guard)
185+
// Tela cujo código não baixou (rede oscilou, versão nova do painel): recarrega uma vez na rota pedida; se falhar de
186+
// novo em até 10 s, mostra o aviso com Recarregar (D-163).
187+
router.onError((error, to) => {
188+
if (!isLoadError(error)) {
189+
return
190+
}
191+
192+
if (claimReload(to.fullPath, Date.now(), sessionStore())) {
193+
window.location.assign(router.resolve(to.fullPath).href)
194+
} else {
195+
void router.replace({ name: 'load-failed', query: { rota: to.fullPath } })
196+
}
197+
})
178198
return router
179199
}

‎panel/src/router/paths.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
/** Destino interno seguro para "voltar" depois do login (sem redirecionamento aberto). */
2+
export function safeReturn(value: unknown): string {
3+
return typeof value === 'string' && value.startsWith('/') && !value.startsWith('//') && !value.startsWith('/\\') ? value : '/'
4+
}

‎panel/src/router/reload.spec.ts‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
import { describe, expect, it } from 'vitest'
2+
import { claimReload, isLoadError } from './reload'
3+
4+
function memory(): Pick<Storage, 'getItem' | 'setItem'> {
5+
const items = new Map<string, string>()
6+
return { getItem: (key) => items.get(key) ?? null, setItem: (key, value) => void items.set(key, value) }
7+
}
8+
9+
describe('Recarga de tela que não carregou', () => {
10+
it('Spec008_AC27 reconhece a falha de baixar um pedaço do painel nos três navegadores', () => {
11+
expect(isLoadError(new TypeError('Failed to fetch dynamically imported module: http://x/psr/assets/RunListView-a1.js'))).toBe(
12+
true,
13+
)
14+
expect(isLoadError(new TypeError('error loading dynamically imported module'))).toBe(true)
15+
expect(isLoadError(new TypeError('Importing a module script failed.'))).toBe(true)
16+
expect(isLoadError(new Error('Unable to preload CSS for /psr/assets/RunListView-a1.css'))).toBe(true)
17+
expect(isLoadError(new Error('Request failed with status 500'))).toBe(false)
18+
})
19+
20+
it('Spec008_AC27 recarrega uma vez por rota e não entra em laço dentro de 10 s', () => {
21+
const storage = memory()
22+
23+
expect(claimReload('/execucoes', 1_000, storage)).toBe(true)
24+
expect(claimReload('/execucoes', 5_000, storage)).toBe(false)
25+
expect(claimReload('/agendamentos', 6_000, storage)).toBe(true)
26+
expect(claimReload('/agendamentos', 16_001, storage)).toBe(true)
27+
})
28+
29+
it('Spec008_AC27 sem onde guardar a marca, não recarrega (melhor o aviso do que um laço)', () => {
30+
const blocked: Pick<Storage, 'getItem' | 'setItem'> = {
31+
getItem: () => null,
32+
setItem: () => {
33+
throw new DOMException('quota', 'QuotaExceededError')
34+
},
35+
}
36+
37+
expect(claimReload('/execucoes', 1_000, null)).toBe(false)
38+
expect(claimReload('/execucoes', 1_000, blocked)).toBe(false)
39+
})
40+
})

‎panel/src/router/reload.ts‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/** Tela cujo código não baixou: recarrega uma vez e, se falhar de novo, avisa (spec 008, AC-27; D-163). */
2+
const storageKey = 'psr.reload'
3+
const window = 10_000
4+
5+
/** Falha ao baixar um pedaço do painel (import dinâmico ou CSS pré-carregado), nos textos do Chromium, Firefox e Safari. */
6+
export function isLoadError(error: unknown): boolean {
7+
const message = error instanceof Error ? error.message : String(error)
8+
return /dynamically imported module|Importing a module script failed|Unable to preload CSS/i.test(message)
9+
}
10+
11+
/**
12+
* Decide se recarrega a página para `path`: sim na primeira falha; não se já recarregou para a mesma rota há menos de
13+
* 10 s (sem laço) ou se o navegador não deixa guardar a marca.
14+
*/
15+
export function claimReload(path: string, now: number, storage: Pick<Storage, 'getItem' | 'setItem'> | null): boolean {
16+
if (!storage) {
17+
return false
18+
}
19+
20+
try {
21+
const last = JSON.parse(storage.getItem(storageKey) ?? 'null') as { path: string; at: number } | null
22+
if (last && last.path === path && now - last.at < window) {
23+
return false
24+
}
25+
26+
storage.setItem(storageKey, JSON.stringify({ path, at: now }))
27+
return true
28+
} catch {
29+
return false
30+
}
31+
}
32+
33+
/** O `sessionStorage`, ou `null` quando o navegador o bloqueia. */
34+
export function sessionStore(): Storage | null {
35+
try {
36+
return globalThis.sessionStorage ?? null
37+
} catch {
38+
return null
39+
}
40+
}

‎panel/src/views/LoadFailedView.vue‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
<script setup lang="ts">
2+
import { useI18n } from 'vue-i18n'
3+
import { useRoute, useRouter } from 'vue-router'
4+
import { safeReturn } from '@/router/paths'
5+
6+
/** Tela que não carregou nem depois de recarregar (spec 008, AC-27). Importada direto, sem depender da rede. */
7+
const { t } = useI18n()
8+
const route = useRoute()
9+
const router = useRouter()
10+
11+
function reload() {
12+
window.location.assign(router.resolve(safeReturn(route.query.rota)).href)
13+
}
14+
</script>
15+
16+
<template>
17+
<v-container class="py-12 text-center">
18+
<v-icon icon="mdi-wifi-alert" size="64" color="warning" aria-hidden="true" />
19+
<h1 class="text-h5 mt-4">{{ t('loadFailed.title') }}</h1>
20+
<p class="text-medium-emphasis mt-2">{{ t('loadFailed.text') }}</p>
21+
<v-btn class="mt-6" color="primary" prepend-icon="mdi-refresh" data-testid="reload" @click="reload">{{
22+
t('loadFailed.reload')
23+
}}</v-btn>
24+
</v-container>
25+
</template>

‎panel/src/views/pipelines/PipelineDetailView.vue‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -201,6 +201,14 @@ const exportUrl = (v: number) => `${apiBase}/pipelines/${encodeURIComponent(key.
201201
>
202202
{{ t('pipelines.run.open') }}
203203
</v-btn>
204+
<v-btn
205+
variant="text"
206+
prepend-icon="mdi-language-python"
207+
:to="{ name: 'stages', query: { trilha: pipeline.key } }"
208+
data-testid="pipeline-stages"
209+
>
210+
{{ t('pipelines.stagesLink') }}
211+
</v-btn>
204212
<v-btn
205213
v-if="session.hasRole('Author')"
206214
variant="tonal"

0 commit comments

Comments
 (0)