diff --git a/src/app/features/indicadores/cama-desarrollo/cama-desarrollo.html b/src/app/features/indicadores/cama-desarrollo/cama-desarrollo.html
new file mode 100644
index 0000000..e488cbb
--- /dev/null
+++ b/src/app/features/indicadores/cama-desarrollo/cama-desarrollo.html
@@ -0,0 +1,52 @@
+
Desarrollo del modelo
+@let l = lectura();
+@switch (l.tipo) {
+ @case ('cargando') { Cargando el desarrollo del modelo…
}
+ @case ('no-disponible') {
+ La versión en producción no trae el desarrollo del modelo. Entrena una nueva versión en Gobernanza para generarlo.
+ }
+ @case ('error') { No se pudo cargar el desarrollo del modelo. Intenta nuevamente más tarde.
}
+ @case ('listo') {
+
+ Depuración de variables, balanceo, regresión logística y red bayesiana, bootstrap, curvas por subgrupo y factores de
+ riesgo, calculados sobre las {{ l.datos.desarrollo.n }} pacientes de la cohorte (versión {{ l.datos.modelo.version }}).
+
+ @if (l.datos.desarrollo.variables_no_disponibles.length) {
+
+ El hospital todavía no reporta: {{ l.datos.desarrollo.variables_no_disponibles.join(', ') }}. Entran como «Desconocido»
+ y no explican nada hasta que existan.
+
+ }
+
+ @for (e of l.datos.desarrollo.etapas; track e.etapa) {
+ Etapa {{ e.etapa }}: {{ e.estado === 'error' ? 'con error' : 'completa' }}
+ }
+
+ @for (error of errores(l.datos); track error[0]) {
+ Etapa {{ error[0] }} no pudo calcularse con esta cohorte: {{ error[1] }}
+ }
+ @for (t of tablas(l.datos); track t.id) {
+
+ {{ t.titulo }} ({{ t.filas.length }})
+
+
+ }
+ @if (figuras(l.datos).length) {
+ Figuras
+
+ }
+ }
+}
diff --git a/src/app/features/indicadores/cama-desarrollo/cama-desarrollo.scss b/src/app/features/indicadores/cama-desarrollo/cama-desarrollo.scss
new file mode 100644
index 0000000..f1b291e
--- /dev/null
+++ b/src/app/features/indicadores/cama-desarrollo/cama-desarrollo.scss
@@ -0,0 +1,14 @@
+:host { display: block; margin-top: 2rem; }
+.lead, .note { max-width: 70ch; }
+.note { color: var(--mat-sys-on-surface-variant, #444); }
+.stages { display: flex; flex-wrap: wrap; gap: 0.5rem 1.5rem; padding: 0; list-style: none; }
+.stages .failed { font-weight: 600; }
+details { margin: 0.5rem 0; }
+summary { cursor: pointer; font-weight: 600; }
+.scroll { overflow-x: auto; max-height: 26rem; }
+table { border-collapse: collapse; font-size: 0.85rem; }
+th, td { padding: 0.25rem 0.6rem; text-align: left; border-bottom: 1px solid var(--mat-sys-outline-variant, #ccc); white-space: nowrap; }
+.figures { display: grid; grid-template-columns: repeat(auto-fill, minmax(20rem, 1fr)); gap: 1rem; }
+figure { margin: 0; }
+img { max-width: 100%; height: auto; background: #fff; }
+figcaption { font-size: 0.8rem; text-transform: capitalize; }
diff --git a/src/app/features/indicadores/cama-desarrollo/cama-desarrollo.service.ts b/src/app/features/indicadores/cama-desarrollo/cama-desarrollo.service.ts
new file mode 100644
index 0000000..8b3fa2e
--- /dev/null
+++ b/src/app/features/indicadores/cama-desarrollo/cama-desarrollo.service.ts
@@ -0,0 +1,58 @@
+import { HttpClient, HttpErrorResponse } from '@angular/common/http';
+import { inject, Injectable } from '@angular/core';
+import { catchError, map, Observable, of, throwError } from 'rxjs';
+
+// The development results of CaMa's model in production, `GET /cama/modelo/desarrollo`: what the SEER stages found over
+// the cohort (variables kept, odds ratios, Bayesian network arcs, risk factors, subgroup curves) as tables, and their
+// figures. They describe the cohort, never a patient. A 404 is "no version with a development record yet".
+export type FilaDeTabla = Record;
+export interface RegistroDesarrollo {
+ n: number;
+ etapas: { etapa: string; estado: string; segundos: number }[];
+ errores: Record;
+ variables_no_disponibles: string[];
+ tablas: Record;
+ figuras: Record;
+}
+export interface RespuestaDesarrollo {
+ simulado: boolean;
+ modelo: { nombre: string; version: string; mlflow_run_id: string };
+ desarrollo: RegistroDesarrollo;
+}
+
+const record = (v: unknown): v is Record => !!v && typeof v === 'object' && !Array.isArray(v);
+const text = (v: unknown): v is string => typeof v === 'string' && v.length > 0;
+
+function invalid(): never {
+ throw new Error('Respuesta de desarrollo del modelo inválida');
+}
+
+/** Validate at the boundary: the record's shapes, so a partial answer never reaches the page. */
+export function respuestaDesarrollo(v: unknown): RespuestaDesarrollo {
+ if (!record(v) || !record(v['modelo']) || !record(v['desarrollo'])) invalid();
+ const m = v['modelo'] as Record, d = v['desarrollo'] as Record;
+ if (!text(m['nombre']) || !text(m['version']) || !text(m['mlflow_run_id'])) invalid();
+ if (typeof d['n'] !== 'number' || !Array.isArray(d['etapas']) || !record(d['errores']) || !Array.isArray(d['variables_no_disponibles'])
+ || !record(d['tablas']) || !record(d['figuras'])) invalid();
+ for (const e of d['etapas'] as unknown[]) if (!record(e) || !text(e['etapa']) || !text(e['estado'])) invalid();
+ for (const rows of Object.values(d['tablas'] as Record)) if (!Array.isArray(rows) || !rows.every(record)) invalid();
+ for (const png of Object.values(d['figuras'] as Record)) if (!text(png) || !/^[A-Za-z0-9+/=]+$/.test(png)) invalid();
+ return {
+ simulado: v['simulado'] === true,
+ modelo: { nombre: m['nombre'] as string, version: m['version'] as string, mlflow_run_id: m['mlflow_run_id'] as string },
+ desarrollo: d as unknown as RegistroDesarrollo,
+ };
+}
+
+@Injectable({ providedIn: 'root' })
+export class CamaDesarrolloService {
+ private readonly http = inject(HttpClient);
+
+ /** The production version's development record, or `null` when there is none (a 404). */
+ desarrollo(): Observable {
+ return this.http.get('/cama/modelo/desarrollo').pipe(
+ map(respuestaDesarrollo),
+ catchError(error => error instanceof HttpErrorResponse && error.status === 404 ? of(null) : throwError(() => error)),
+ );
+ }
+}
diff --git a/src/app/features/indicadores/cama-desarrollo/cama-desarrollo.spec.ts b/src/app/features/indicadores/cama-desarrollo/cama-desarrollo.spec.ts
new file mode 100644
index 0000000..b338941
--- /dev/null
+++ b/src/app/features/indicadores/cama-desarrollo/cama-desarrollo.spec.ts
@@ -0,0 +1,97 @@
+// Covers CaMa's development view: the boundary validation of `GET /cama/modelo/desarrollo` (a malformed record never
+// reaches the page) and the component's states, its tables, its figures and the notice of what the hospital does not
+// report yet. Fixtures: `registroEjemplo`, a record like a training run publishes.
+import { provideHttpClient } from '@angular/common/http';
+import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
+import { TestBed } from '@angular/core/testing';
+import { CamaDesarrollo } from './cama-desarrollo';
+import { respuestaDesarrollo } from './cama-desarrollo.service';
+
+function registroEjemplo(): any {
+ return {
+ simulado: true,
+ modelo: { nombre: 'cama-survival', version: '3', mlflow_run_id: 'run-1' },
+ desarrollo: {
+ n: 500, etapas: [{ etapa: '01', estado: 'ok', segundos: 0 }, { etapa: '05', estado: 'error', segundos: 0 }],
+ errores: { '05': 'ValueError: sin subgrupos' }, variables_no_disponibles: ['Estadio_cat', 'Radioterapia_cat'],
+ tablas: { or_lr_balanceada: [{ indice: 'Grado_G3', OR: 2.5, p: 0.0123456 }], hbn_arcos: [] },
+ figuras: { sens_esp_edad: 'iVBORw0KGgo=' },
+ },
+ };
+}
+
+describe('Desarrollo CaMa: respuesta', () => {
+ it('accepts a record as published', () => {
+ expect(respuestaDesarrollo(registroEjemplo()).desarrollo.n).toBe(500);
+ });
+
+ // Fails if a record that would break the page (or inject markup through a figure) is accepted.
+ it.each([
+ ['no model version', (d: any) => { delete d.modelo.version; }],
+ ['a table that is not rows', (d: any) => { d.desarrollo.tablas.hbn_arcos = 'x'; }],
+ ['a figure that is not base64', (d: any) => { d.desarrollo.figuras.sens_esp_edad = '" onerror="x'; }],
+ ['no stages', (d: any) => { delete d.desarrollo.etapas; }],
+ ])('rejects %s', (_, estropear) => {
+ const d = registroEjemplo();
+ estropear(d);
+ expect(() => respuestaDesarrollo(d)).toThrow('Respuesta de desarrollo del modelo inválida');
+ });
+});
+
+describe('Desarrollo CaMa: componente', () => {
+ let http: HttpTestingController;
+ beforeEach(() => {
+ TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] });
+ http = TestBed.inject(HttpTestingController);
+ });
+ afterEach(() => http.verify());
+ const montar = (active: boolean) => {
+ const f = TestBed.createComponent(CamaDesarrollo);
+ f.componentRef.setInput('active', active);
+ f.detectChanges();
+ return f;
+ };
+ const texto = (f: ReturnType) => (f.nativeElement as HTMLElement).textContent!.replace(/\s+/g, ' ');
+
+ // Fails if the view asks before it is shown or asks again.
+ it('asks once, the first time it is shown', () => {
+ const f = montar(false);
+ http.expectNone('/cama/modelo/desarrollo');
+ f.componentRef.setInput('active', true);
+ f.detectChanges();
+ http.expectOne('/cama/modelo/desarrollo').flush(registroEjemplo());
+ f.componentRef.setInput('active', false);
+ f.detectChanges();
+ f.componentRef.setInput('active', true);
+ f.detectChanges();
+ http.expectNone('/cama/modelo/desarrollo');
+ });
+
+ // Fails if a table, a figure, a failed stage or the missing-variables notice stops being shown.
+ it('shows the tables that have rows, the figures, the failed stage and what the hospital does not report', () => {
+ const f = montar(true);
+ http.expectOne('/cama/modelo/desarrollo').flush(registroEjemplo());
+ f.detectChanges();
+
+ const el = f.nativeElement as HTMLElement, t = texto(f);
+ expect(t).toContain('Razones de momios de la regresión logística (1)');
+ expect(t).not.toContain('Arcos de la red bayesiana');
+ expect(t).toContain('0.01235');
+ expect(t).toContain('Estadio_cat, Radioterapia_cat');
+ expect(t).toContain('Etapa 05 no pudo calcularse');
+ expect(el.querySelector('img')!.getAttribute('src')).toBe('data:image/png;base64,iVBORw0KGgo=');
+ });
+
+ // Fails if no version with a record is shown as an error, or a failure as a page.
+ it('says there is no record on a 404 and fails closed on an error', () => {
+ const sin = montar(true);
+ http.expectOne('/cama/modelo/desarrollo').flush({ error: 'x' }, { status: 404, statusText: 'Not Found' });
+ sin.detectChanges();
+ expect(texto(sin)).toContain('no trae el desarrollo del modelo');
+
+ const roto = montar(true);
+ http.expectOne('/cama/modelo/desarrollo').flush({ desarrollo: {} });
+ roto.detectChanges();
+ expect(texto(roto)).toContain('No se pudo cargar el desarrollo del modelo');
+ });
+});
diff --git a/src/app/features/indicadores/cama-desarrollo/cama-desarrollo.ts b/src/app/features/indicadores/cama-desarrollo/cama-desarrollo.ts
new file mode 100644
index 0000000..54187e8
--- /dev/null
+++ b/src/app/features/indicadores/cama-desarrollo/cama-desarrollo.ts
@@ -0,0 +1,73 @@
+import { Component, DestroyRef, effect, inject, input, signal } from '@angular/core';
+import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
+import { CamaDesarrolloService, FilaDeTabla, RespuestaDesarrollo } from './cama-desarrollo.service';
+
+type Lectura = { tipo: 'cargando' } | { tipo: 'no-disponible' } | { tipo: 'error' } | { tipo: 'listo'; datos: RespuestaDesarrollo };
+
+/** Names the tables are shown under, in the order they are shown. */
+export const TABLAS: [string, string][] = [
+ ['factores_riesgo', 'Factores de riesgo (cuatro criterios)'],
+ ['factores_riesgo_variables', 'Resumen de factores de riesgo por variable'],
+ ['or_lr_balanceada', 'Razones de momios de la regresión logística'],
+ ['hbn_arcos', 'Arcos de la red bayesiana'],
+ ['metricas_diferenciacion', 'Métricas de diferenciación (LR y HBN)'],
+ ['auc_validacion_interna', 'AUC de validación interna'],
+ ['auc_bootstrap', 'AUC por réplica bootstrap'],
+ ['seleccion_bootstrap', 'Frecuencia de selección en el bootstrap'],
+ ['subgrupos_weibull', 'Subgrupos: Kaplan-Meier y Weibull fraccional'],
+ ['subgrupos_puntos', 'Subgrupos: supervivencia de LR y HBN'],
+ ['prueba_edad', 'Prueba de la edad continua contra la categorizada'],
+ ['cortes_edad', 'Comparación de cortes de edad'],
+ ['cortes_tumor', 'Comparación de cortes de tamaño tumoral'],
+ ['pesos_combinacion', 'Pesos de la combinación LR y HBN'],
+];
+
+/**
+ * How CaMa's model was developed, from the production version's record: the SEER stages' tables and figures over the
+ * cohort. Population results, never a patient's. Loads once, the first time the tab is shown.
+ */
+@Component({
+ selector: 'app-cama-desarrollo',
+ templateUrl: './cama-desarrollo.html',
+ styleUrl: './cama-desarrollo.scss',
+})
+export class CamaDesarrollo {
+ readonly active = input(false);
+ private readonly service = inject(CamaDesarrolloService);
+ private readonly destroy = inject(DestroyRef);
+ readonly lectura = signal({ tipo: 'cargando' });
+ private pedido = false;
+
+ constructor() {
+ effect(() => {
+ if (!this.active() || this.pedido) return;
+ this.pedido = true;
+ this.service.desarrollo().pipe(takeUntilDestroyed(this.destroy)).subscribe({
+ next: datos => this.lectura.set(datos === null ? { tipo: 'no-disponible' } : { tipo: 'listo', datos }),
+ error: () => this.lectura.set({ tipo: 'error' }),
+ });
+ });
+ }
+
+ /** The tables the record holds, in display order, with their rows' columns. */
+ tablas(datos: RespuestaDesarrollo): { id: string; titulo: string; columnas: string[]; filas: FilaDeTabla[] }[] {
+ return TABLAS.filter(([id]) => datos.desarrollo.tablas[id]?.length)
+ .map(([id, titulo]) => {
+ const filas = datos.desarrollo.tablas[id];
+ return { id, titulo, columnas: Object.keys(filas[0]), filas };
+ });
+ }
+
+ figuras(datos: RespuestaDesarrollo): { id: string; src: string }[] {
+ return Object.entries(datos.desarrollo.figuras).map(([id, png]) => ({ id, src: `data:image/png;base64,${png}` }));
+ }
+
+ errores(datos: RespuestaDesarrollo): [string, string][] {
+ return Object.entries(datos.desarrollo.errores);
+ }
+
+ celda(valor: string | number | boolean | null): string {
+ if (valor === null) return '';
+ return typeof valor === 'number' && !Number.isInteger(valor) ? valor.toPrecision(4) : String(valor);
+ }
+}
diff --git a/src/app/features/indicadores/indicadores-page.html b/src/app/features/indicadores/indicadores-page.html
index bb1625a..a1fd68e 100644
--- a/src/app/features/indicadores/indicadores-page.html
+++ b/src/app/features/indicadores/indicadores-page.html
@@ -141,6 +141,7 @@
@if (conSupervivencia) {
}
diff --git a/src/app/features/indicadores/indicadores-page.ts b/src/app/features/indicadores/indicadores-page.ts
index c13ac9f..3c0960c 100644
--- a/src/app/features/indicadores/indicadores-page.ts
+++ b/src/app/features/indicadores/indicadores-page.ts
@@ -32,6 +32,7 @@ import { SeleccionSeguimiento } from './indicadores-seguimiento-tabla';
import { IndicadoresAnalisis, SeleccionPacientes } from './indicadores-analisis';
import { IndicadoresHistorico } from './indicadores-historico';
import { CamaSupervivencia } from './cama-supervivencia/cama-supervivencia';
+import { CamaDesarrollo } from './cama-desarrollo/cama-desarrollo';
import { IndicadorHistopatologiaPendiente } from './indicador-histopatologia-pendiente';
import { TITULO_MASTOGRAFIAS_CAMA } from './indicadores-figure-labels';
@@ -54,7 +55,7 @@ const SECTIONS_CAMA: readonly { id: DashboardSection; label: string }[] = [
@Component({
selector: 'app-indicadores-page',
- imports: [FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatIconModule, MatSelectModule, MatProgressBarModule, IndicadorCatalogCard, IndicadorKpiPanel, IndicadorKpiCard, IndicadorHistopatologiaPendiente, IndicadorPeriodFilters, IndicadoresDefinitions, IndicadoresTracking, IndicadoresHistorico, TeaResumenPeriodo, CamaSupervivencia],
+ imports: [FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatIconModule, MatSelectModule, MatProgressBarModule, IndicadorCatalogCard, IndicadorKpiPanel, IndicadorKpiCard, IndicadorHistopatologiaPendiente, IndicadorPeriodFilters, IndicadoresDefinitions, IndicadoresTracking, IndicadoresHistorico, TeaResumenPeriodo, CamaSupervivencia, CamaDesarrollo],
templateUrl: './indicadores-page.html',
styleUrl: './indicadores-page.scss',
})
diff --git a/src/app/governance/api/governance.api.ts b/src/app/governance/api/governance.api.ts
index 2c700c3..b2c8637 100644
--- a/src/app/governance/api/governance.api.ts
+++ b/src/app/governance/api/governance.api.ts
@@ -10,6 +10,8 @@ import {
ModelVersion,
PromotionCheck,
ReportField,
+ TrainableScenario,
+ TrainingJob,
OcrJob,
OcrRowStatus,
OcrRowsResponse,
@@ -39,6 +41,20 @@ export class GovernanceApi {
return this.http.post<{ output: string }>(`/governance/model-versions/${domain}/${scenario}/train`, {});
}
+ /** The scenarios that can be trained from here. */
+ trainableScenarios(): Observable<{ scenarios: TrainableScenario[] }> {
+ return this.http.get<{ scenarios: TrainableScenario[] }>('/governance/scenarios');
+ }
+
+ /** Starts the training in the background: 202 with the job, 409 with the running one, 503 with no dbt manifest. */
+ startTrainingJob(domain: string, scenario: string): Observable<{ job: TrainingJob }> {
+ return this.http.post<{ job: TrainingJob }>(`/governance/model-versions/${domain}/${scenario}/train-jobs`, {});
+ }
+
+ trainingJobs(): Observable<{ jobs: TrainingJob[] }> {
+ return this.http.get<{ jobs: TrainingJob[] }>('/governance/training-jobs');
+ }
+
retireModelVersion(domain: string, scenario: string, version: string): Observable {
return this.http.post(`/governance/model-versions/${domain}/${scenario}/${version}/retire`, {});
}
diff --git a/src/app/governance/api/governance.types.ts b/src/app/governance/api/governance.types.ts
index 4f7ba44..d8f4abf 100644
--- a/src/app/governance/api/governance.types.ts
+++ b/src/app/governance/api/governance.types.ts
@@ -136,3 +136,28 @@ export interface OcrRunSummary {
failed: number;
needs_review: number;
}
+
+/** A scenario governance can train (`GET /governance/scenarios`); `produccion` is its version in production, if any. */
+export interface TrainableScenario {
+ domain: string;
+ scenario: string;
+ cohort: string | null;
+ outcome: string | null;
+ description: string;
+ kind: 'cohorte' | 'referencia';
+ produccion: string | null;
+}
+
+export type TrainingJobState = 'en_curso' | 'completado' | 'entrenado_sin_promover' | 'fallido' | 'interrumpido';
+
+/** A training in the background (`/governance/training-jobs`), with the tail of its outputs. */
+export interface TrainingJob {
+ id: string;
+ domain: string;
+ scenario: string;
+ iniciado: string;
+ estado: TrainingJobState;
+ codigo: number | null;
+ salida: string;
+ error: string;
+}
diff --git a/src/app/governance/components/model-versions-panel/model-versions-panel.html b/src/app/governance/components/model-versions-panel/model-versions-panel.html
index ade612e..77bb1e0 100644
--- a/src/app/governance/components/model-versions-panel/model-versions-panel.html
+++ b/src/app/governance/components/model-versions-panel/model-versions-panel.html
@@ -6,22 +6,51 @@
}
-
- model_training Entrenar cacu/cin2_logistic
-
+ @if (offered().length) {
+
+ Modelo a entrenar
+
+ @for (s of offered(); track keyOf(s)) {
+ {{ keyOf(s) }}{{ s.produccion ? ' · en producción v' + s.produccion : '' }}
+ }
+
+
+
+ model_training Entrenar
+
+ }
refresh
- @if (loading() || training()) {
+ @if (loading() || starting() || running()) {
}
@if (loadError(); as error) {
error {{ error }}
}
+ @if (jobs().length) {
+
+ Entrenamientos recientes
+
+ @for (job of jobs(); track job.id) {
+
+ {{ job.domain }}/{{ job.scenario }} · {{ job.iniciado | date: 'short' }} · {{ estados[job.estado] }}
+ @if (job.salida || job.error) {
+
+ Salida
+ {{ job.error || job.salida }}
+
+ }
+
+ }
+
+
+ }
+
Versión
diff --git a/src/app/governance/components/model-versions-panel/model-versions-panel.scss b/src/app/governance/components/model-versions-panel/model-versions-panel.scss
index 202edef..f9578b9 100644
--- a/src/app/governance/components/model-versions-panel/model-versions-panel.scss
+++ b/src/app/governance/components/model-versions-panel/model-versions-panel.scss
@@ -70,3 +70,29 @@
gap: var(--space-2);
margin: 0;
}
+
+.models__scenario {
+ min-width: 18rem;
+}
+
+.models__jobs ul {
+ list-style: none;
+ margin: 0;
+ padding: 0;
+}
+
+.models__jobs li {
+ padding: var(--space-1) 0;
+}
+
+.models__job--failed {
+ color: var(--mat-sys-error);
+}
+
+.models__jobs pre {
+ font-size: 0.8rem;
+ margin: var(--space-1) 0;
+ max-height: 12rem;
+ overflow: auto;
+ white-space: pre-wrap;
+}
diff --git a/src/app/governance/components/model-versions-panel/model-versions-panel.spec.ts b/src/app/governance/components/model-versions-panel/model-versions-panel.spec.ts
new file mode 100644
index 0000000..95b07fc
--- /dev/null
+++ b/src/app/governance/components/model-versions-panel/model-versions-panel.spec.ts
@@ -0,0 +1,83 @@
+// Covers the model versions panel's training: the scenarios the account can train are offered, a training starts in the
+// background and its state is shown while it runs, and the versions are read again when it ends. Fixtures: a stub of
+// `GovernanceApi` with the scenarios, the versions and the jobs the test sets, and an account that reaches every domain.
+import { TestBed } from '@angular/core/testing';
+import { of } from 'rxjs';
+import { vi } from 'vitest';
+import { AuthService } from '../../../auth/auth.service';
+import { GovernanceApi } from '../../api/governance.api';
+import { TrainingJob } from '../../api/governance.types';
+import { ModelVersionsPanel } from './model-versions-panel';
+
+const SCENARIOS = [
+ { domain: 'cacu', scenario: 'cin2_logistic', cohort: 'cacu/x', outcome: 'cin2', description: '', kind: 'cohorte', produccion: null },
+ { domain: 'cama', scenario: 'survival', cohort: 'cama/cohorte_total', outcome: 'muerte', description: '', kind: 'cohorte', produccion: '2' },
+];
+const job = (estado: TrainingJob['estado']): TrainingJob => ({
+ id: 'j1', domain: 'cama', scenario: 'survival', iniciado: '2026-01-01T00:00:00+00:00', estado, codigo: null, salida: 'trained: version 3', error: '',
+});
+
+describe('ModelVersionsPanel training', () => {
+ let api: Record>;
+ let jobs: TrainingJob[];
+
+ beforeEach(() => {
+ jobs = [];
+ api = {
+ listModelVersions: vi.fn(() => of({ model_versions: [] })),
+ trainableScenarios: vi.fn(() => of({ scenarios: SCENARIOS })),
+ trainingJobs: vi.fn(() => of({ jobs })),
+ startTrainingJob: vi.fn(() => of({ job: job('en_curso') })),
+ };
+ TestBed.configureTestingModule({
+ providers: [
+ { provide: GovernanceApi, useValue: api },
+ { provide: AuthService, useValue: { puedeVer: () => true, dominios: () => ['cacu', 'cama', 'tea'], esAdministrador: () => true, usuario: () => ({ dominios: ['cacu', 'cama', 'tea'] }) } },
+ ],
+ });
+ });
+
+ // Fails if the panel goes back to offering one hardcoded scenario, or hides a scenario the account can train.
+ it('offers every trainable scenario of the domains shown', () => {
+ const f = TestBed.createComponent(ModelVersionsPanel);
+ f.detectChanges();
+ const panel = f.componentInstance;
+
+ panel.domain.set(null);
+ expect(panel.offered().map((s) => panel.keyOf(s))).toEqual(['cacu/cin2_logistic', 'cama/survival']);
+ panel.domain.set('cama');
+ expect(panel.offered().map((s) => panel.keyOf(s))).toEqual(['cama/survival']);
+ });
+
+ // Fails if the button trains another scenario than the selected one, or waits for the training to end.
+ it('starts the selected scenario in the background and reads the jobs again', () => {
+ const f = TestBed.createComponent(ModelVersionsPanel);
+ f.detectChanges();
+ const panel = f.componentInstance;
+ panel.domain.set(null);
+ panel.selected.set('cama/survival');
+
+ panel.train();
+
+ expect(api['startTrainingJob']).toHaveBeenCalledExactlyOnceWith('cama', 'survival');
+ expect(api['trainingJobs']).toHaveBeenCalledTimes(2);
+ });
+
+ // Fails if the running state is lost or the versions are not read again when the running training ends.
+ it('knows a training is running and reads the versions when it ends', () => {
+ const f = TestBed.createComponent(ModelVersionsPanel);
+ jobs = [job('en_curso')];
+ f.detectChanges();
+ const panel = f.componentInstance;
+ expect(panel.running()).toBe(true);
+ const reads = api['listModelVersions'].mock.calls.length;
+
+ jobs = [job('completado')];
+ panel.refreshJobs();
+
+ expect(panel.running()).toBe(false);
+ expect(api['listModelVersions'].mock.calls.length).toBe(reads + 1);
+ f.detectChanges();
+ expect((f.nativeElement as HTMLElement).textContent).toContain('Entrenado y promovido');
+ });
+});
diff --git a/src/app/governance/components/model-versions-panel/model-versions-panel.ts b/src/app/governance/components/model-versions-panel/model-versions-panel.ts
index faa612b..a73a198 100644
--- a/src/app/governance/components/model-versions-panel/model-versions-panel.ts
+++ b/src/app/governance/components/model-versions-panel/model-versions-panel.ts
@@ -1,11 +1,14 @@
import { DatePipe } from '@angular/common';
import { Component, DestroyRef, OnInit, computed, inject, signal } from '@angular/core';
+import { timer } from 'rxjs';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { MatButtonModule } from '@angular/material/button';
import { MatDialog } from '@angular/material/dialog';
import { MatButtonToggleModule } from '@angular/material/button-toggle';
import { MatChipsModule } from '@angular/material/chips';
import { MatIconModule } from '@angular/material/icon';
+import { MatSelectModule } from '@angular/material/select';
+import { MatFormFieldModule } from '@angular/material/form-field';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar';
import { MatTableModule } from '@angular/material/table';
@@ -15,18 +18,27 @@ import { AuthService } from '../../../auth/auth.service';
import { alcanzaTodos, dominioInicial, dominiosPermitidos } from '../../../auth/dominios';
import { apiErrorMessage } from '../../../connect/api/api.types';
import { GovernanceApi } from '../../api/governance.api';
-import { ModelVersion } from '../../api/governance.types';
+import { ModelVersion, TrainableScenario, TrainingJob } from '../../api/governance.types';
import { ModelStatusChip } from '../model-status-chip/model-status-chip';
import { ModelVersionDialog } from '../model-version-dialog/model-version-dialog';
-/** The only scenario with a trainer today (ML-cin2_logistic, CaCu): `entrenar`'s own domain and scenario. */
-const TRAINABLE = { domain: 'cacu', scenario: 'cin2_logistic' };
+/** Milliseconds between asking for the state of a training that is still running. */
+export const SONDEO_MS = 3000;
+
+export const ESTADOS: Record = {
+ en_curso: 'En curso',
+ completado: 'Entrenado y promovido',
+ entrenado_sin_promover: 'Entrenado; faltan sus informes para promoverlo',
+ fallido: 'Falló',
+ interrumpido: 'Interrumpido',
+};
/**
* Every registered model version with its status (desarrollo, candidata,
* en producción, retirada). The detail dialog holds the promotion
- * checklist, lineage, artifacts and reports. The toolbar also offers
- * training the one scenario with a trainer, over HTTP instead of a shell.
+ * checklist, lineage, artifacts and reports. The toolbar trains any scenario
+ * that has a trainer, in the background, and lists the latest trainings with
+ * their state while they run.
*/
@Component({
selector: 'app-model-versions-panel',
@@ -37,6 +49,8 @@ const TRAINABLE = { domain: 'cacu', scenario: 'cin2_logistic' };
MatChipsModule,
MatIconModule,
MatProgressBarModule,
+ MatSelectModule,
+ MatFormFieldModule,
MatSnackBarModule,
MatTableModule,
MatTooltipModule,
@@ -61,12 +75,28 @@ export class ModelVersionsPanel implements OnInit {
readonly versions = signal([]);
readonly loading = signal(false);
readonly loadError = signal(null);
- readonly training = signal(false);
+ readonly scenarios = signal([]);
+ readonly selected = signal(null);
+ readonly jobs = signal([]);
+ readonly starting = signal(false);
+ readonly estados = ESTADOS;
+ /** The scenarios of the domain being shown, and only of the account's domains. */
+ readonly offered = computed(() =>
+ this.scenarios().filter((s) => this.auth.puedeVer(s.domain) && (this.domain() === null || s.domain === this.domain())));
+ readonly running = computed(() => this.jobs().some((j) => j.estado === 'en_curso'));
readonly displayedColumns = ['version', 'scenario', 'environment', 'armado', 'status', 'created_at', 'acciones'];
ngOnInit(): void {
this.reload();
+ this.api.trainableScenarios().pipe(takeUntilDestroyed(this.destroyRef)).subscribe({
+ next: ({ scenarios }) => this.scenarios.set(scenarios),
+ error: () => this.scenarios.set([]),
+ });
+ this.refreshJobs();
+ timer(SONDEO_MS, SONDEO_MS).pipe(takeUntilDestroyed(this.destroyRef)).subscribe(() => {
+ if (this.running()) this.refreshJobs();
+ });
}
setDomain(domain: string | null): void {
@@ -108,22 +138,41 @@ export class ModelVersionsPanel implements OnInit {
return Object.entries(version.metrics ?? {}).map(([key, value]) => ({ key, value }));
}
+ /** Asks for the latest trainings; when one that was running has ended, the versions are read again. */
+ refreshJobs(): void {
+ const before = this.running();
+ this.api.trainingJobs().pipe(takeUntilDestroyed(this.destroyRef)).subscribe({
+ next: ({ jobs }) => {
+ this.jobs.set(jobs.slice(0, 8));
+ if (before && !this.running()) this.reload();
+ },
+ error: () => undefined,
+ });
+ }
+
train(): void {
- this.training.set(true);
+ const key = this.selected() ?? (this.offered().length === 1 ? this.keyOf(this.offered()[0]) : null);
+ const scenario = this.offered().find((s) => this.keyOf(s) === key);
+ if (!scenario) return;
+ this.starting.set(true);
this.api
- .trainModelVersion(TRAINABLE.domain, TRAINABLE.scenario)
+ .startTrainingJob(scenario.domain, scenario.scenario)
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe({
next: () => {
- this.training.set(false);
- this.snackBar.open(`El modelo ${TRAINABLE.domain}/${TRAINABLE.scenario} se entrenó correctamente.`, 'OK', { duration: 3000 });
- this.reload();
+ this.starting.set(false);
+ this.snackBar.open(`Entrenamiento de ${key} iniciado.`, 'OK', { duration: 3000 });
+ this.refreshJobs();
},
error: (error) => {
- this.training.set(false);
- this.snackBar.open(apiErrorMessage(error, 'No se pudo entrenar el modelo.'), 'OK', { duration: 5000 });
- if (error?.status === 409) this.reload();
+ this.starting.set(false);
+ this.snackBar.open(apiErrorMessage(error, 'No se pudo iniciar el entrenamiento.'), 'OK', { duration: 5000 });
+ if (error?.status === 409) this.refreshJobs();
},
});
}
+
+ keyOf(s: { domain: string; scenario: string }): string {
+ return `${s.domain}/${s.scenario}`;
+ }
}