feat(ops): show upload percent, speed and ETA for ingest files
Build and Push Images / Build jorgecuadros-web (push) Successful in 1m46s
Build and Push Images / Build jorgecuadros-api (push) Successful in 3m3s

The ingest upload used fetch(), which cannot report request-body
progress, so the only feedback was a static "Cargando…" label — no way
to tell a stalled 2 GB upload from a working one.

Switch uploadFile() to XMLHttpRequest and expose an optional onProgress
callback reporting loaded/total bytes, a smoothed transfer rate and a
remaining-time estimate. The Operaciones ingest table renders a progress
bar row under the file being uploaded. Once the bytes are all sent the
server still has to write the file, so that tail reads "Procesando en el
servidor…" rather than parking at 100%.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
2026-08-01 01:38:22 -07:00
co-authored by Claude Opus 5
parent a9b4aab7ec
commit 783ec83464
3 changed files with 244 additions and 56 deletions
+40
View File
@@ -837,6 +837,46 @@ button {
display: inline-block;
}
/* Upload progress (Operaciones ingest) */
.upload-progress {
display: flex;
flex-direction: column;
gap: 6px;
padding: 4px 0 8px;
}
.progress-track {
position: relative;
overflow: hidden;
height: 8px;
border-radius: 999px;
background: var(--paper-2);
}
.progress-fill {
height: 100%;
border-radius: 999px;
background: var(--brand-500);
transition: width 0.2s linear;
}
.progress-indeterminate .progress-fill {
width: 40% !important;
animation: progress-slide 1.2s var(--ease-out-quart) infinite;
}
@keyframes progress-slide {
0% {
transform: translateX(-100%);
}
100% {
transform: translateX(250%);
}
}
.upload-progress-stats {
display: flex;
flex-wrap: wrap;
gap: 12px;
font-size: 12px;
color: var(--muted);
}
@keyframes shimmer {
0% {
background-position: -420px 0;
+72 -3
View File
@@ -1,6 +1,6 @@
"use client";
import { useCallback, useEffect, useRef, useState } from "react";
import { Fragment, useCallback, useEffect, useRef, useState } from "react";
import { AppShell } from "@/components/AppShell";
import { useCan } from "@/lib/abilities";
import {
@@ -20,6 +20,7 @@ import {
startOpsJob,
uploadIngest,
} from "@/lib/api";
import type { UploadProgress } from "@/lib/api";
import type {
BackupFile,
IngestFile,
@@ -56,6 +57,7 @@ function Operaciones() {
const [confirm, setConfirm] = useState<ConfirmState>(null);
const [confirmText, setConfirmText] = useState("");
const [uploading, setUploading] = useState<string | null>(null);
const [progress, setProgress] = useState<UploadProgress | null>(null);
const [starting, setStarting] = useState(false);
const fileInputs = useRef<Record<string, HTMLInputElement | null>>({});
@@ -119,14 +121,16 @@ function Operaciones() {
setError(null);
setNotice(null);
setUploading(name);
setProgress(null);
try {
await uploadIngest(name, file);
await uploadIngest(name, file, setProgress);
setNotice(`${name} cargado.`);
refreshLists();
} catch (e) {
setError((e as Error)?.message ?? "No se pudo cargar el archivo.");
} finally {
setUploading(null);
setProgress(null);
const input = fileInputs.current[name];
if (input) input.value = "";
}
@@ -243,7 +247,8 @@ function Operaciones() {
</thead>
<tbody>
{(ingest ?? []).map((f) => (
<tr key={f.name}>
<Fragment key={f.name}>
<tr>
<td className="mono">{f.name}</td>
<td>
<span className={`badge ${f.present ? "badge-positive" : "badge-negative"}`}>
@@ -274,6 +279,7 @@ function Operaciones() {
<button
className="btn btn-ghost"
type="button"
disabled={uploading === f.name}
onClick={() => handleDeleteIngest(f.name)}
>
Eliminar
@@ -282,6 +288,14 @@ function Operaciones() {
</div>
</td>
</tr>
{uploading === f.name && (
<tr>
<td colSpan={5}>
<UploadProgressBar progress={progress} />
</td>
</tr>
)}
</Fragment>
))}
</tbody>
</table>
@@ -496,6 +510,61 @@ function Operaciones() {
);
}
/** "1:05" / "0:09" — remaining time, coarse on purpose. */
function formatEta(seconds: number): string {
const s = Math.max(0, Math.round(seconds));
if (s >= 3600) {
const h = Math.floor(s / 3600);
const m = Math.round((s % 3600) / 60);
return `${h} h ${m} min`;
}
return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, "0")}`;
}
/**
* Live upload readout. The bar tracks bytes handed to the network; once those
* are all sent the server still has to write the file, so the tail of the
* upload reads "Procesando…" instead of sitting at 100%.
*/
function UploadProgressBar({ progress }: { progress: UploadProgress | null }) {
const pct = progress?.fraction != null ? Math.round(progress.fraction * 100) : null;
return (
<div className="upload-progress">
<div
className={`progress-track${pct === null ? " progress-indeterminate" : ""}`}
role="progressbar"
aria-valuemin={0}
aria-valuemax={100}
aria-valuenow={pct ?? undefined}
>
<div className="progress-fill" style={{ width: `${pct ?? 100}%` }} />
</div>
<div className="upload-progress-stats mono">
{progress === null ? (
"Preparando…"
) : progress.finishing ? (
`Procesando en el servidor… (${formatBytes(progress.total)} enviados)`
) : (
<>
{pct !== null && <strong>{pct}%</strong>}
{progress.total > 0 && (
<span>
{formatBytes(progress.loaded)} / {formatBytes(progress.total)}
</span>
)}
{progress.bytesPerSecond > 0 && (
<span>{formatBytes(progress.bytesPerSecond)}/s</span>
)}
{progress.secondsRemaining !== null && progress.bytesPerSecond > 0 && (
<span>faltan {formatEta(progress.secondsRemaining)}</span>
)}
</>
)}
</div>
</div>
);
}
function OpTile({
title,
desc,
+94 -15
View File
@@ -803,38 +803,117 @@ export function listIngest(): Promise<IngestFile[]> {
return apiFetch<IngestFile[]>("/ops/ingest");
}
/** Live upload stats reported to `uploadFile`'s `onProgress` callback. */
export type UploadProgress = {
loaded: number;
/** 0 when the browser can't compute the request size. */
total: number;
/** 0..1, or null when `total` is unknown. */
fraction: number | null;
/** Smoothed transfer rate. */
bytesPerSecond: number;
/** null until a rate and a total are both known. */
secondsRemaining: number | null;
/** True once the bytes are sent and we're waiting on the server's reply. */
finishing: boolean;
};
/**
* Multipart upload — not JSON, so it bypasses apiFetch's Content-Type. `path`
* is API-relative (may include a query string); `filename` overrides the part
* name sent to the server.
* name sent to the server. Uses XHR rather than fetch because fetch has no way
* to report request-body progress.
*/
export async function uploadFile(
export function uploadFile(
path: string,
file: File,
filename?: string,
onProgress?: (p: UploadProgress) => void,
): Promise<unknown> {
const body = new FormData();
body.append("file", file, filename ?? file.name);
const res = await fetch(`${API_ORIGIN}${path}`, {
method: "POST",
credentials: "include",
body,
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open("POST", `${API_ORIGIN}${path}`);
xhr.withCredentials = true;
if (onProgress) {
// Exponentially smoothed rate — raw per-chunk deltas jump around too
// much to read.
let lastAt = performance.now();
let lastLoaded = 0;
let rate = 0;
xhr.upload.onprogress = (e) => {
const now = performance.now();
const dt = (now - lastAt) / 1000;
if (dt >= 0.15) {
const sample = (e.loaded - lastLoaded) / dt;
rate = rate === 0 ? sample : rate * 0.7 + sample * 0.3;
lastAt = now;
lastLoaded = e.loaded;
}
const total = e.lengthComputable ? e.total : 0;
onProgress({
loaded: e.loaded,
total,
fraction: total ? e.loaded / total : null,
bytesPerSecond: rate,
secondsRemaining:
total && rate > 0 ? (total - e.loaded) / rate : null,
finishing: false,
});
if (!res.ok) {
let message = `Error ${res.status}`;
};
// Bytes are out the door; the server still has to write the file.
xhr.upload.onload = () => {
onProgress({
loaded: file.size,
total: file.size,
fraction: 1,
bytesPerSecond: rate,
secondsRemaining: 0,
finishing: true,
});
};
}
xhr.onload = () => {
let parsed: unknown;
try {
const b = await res.json();
if (b?.message) message = b.message;
parsed = xhr.responseText ? JSON.parse(xhr.responseText) : undefined;
} catch {
/* ignore */
parsed = undefined;
}
throw new ApiError(res.status, message);
if (xhr.status >= 200 && xhr.status < 300) {
resolve(parsed);
return;
}
return res.status === 204 ? undefined : res.json().catch(() => undefined);
const message =
(parsed as { message?: string } | undefined)?.message ??
`Error ${xhr.status}`;
reject(new ApiError(xhr.status, message));
};
xhr.onerror = () =>
reject(new ApiError(0, "Fallo de red durante la carga."));
xhr.onabort = () => reject(new ApiError(0, "Carga cancelada."));
xhr.ontimeout = () => reject(new ApiError(0, "Tiempo de carga agotado."));
xhr.send(body);
});
}
export function uploadIngest(name: string, file: File): Promise<unknown> {
return uploadFile(`/ops/ingest/${encodeURIComponent(name)}`, file, name);
export function uploadIngest(
name: string,
file: File,
onProgress?: (p: UploadProgress) => void,
): Promise<unknown> {
return uploadFile(
`/ops/ingest/${encodeURIComponent(name)}`,
file,
name,
onProgress,
);
}
export function deleteIngest(name: string): Promise<unknown> {