Skip to content

Never stop coding. Free MIT AI gateway: one endpoint, 375 providers (150+ free), 1,400+ models Kimi, Claude, GPT, Gemini, GLM, DeepSeek, MiniMax. Works with Claude Code, Codex, Cursor, OpenCode, Cline & Copilot. Quota-aware auto-fallback, RTK+Caveman compression saves 15-95% tokens, MCP/A2A, Desktop/PWA. Built by 900+ contributors

feat(batch): add action footer to BatchDetailModal (cancel/download/retry) + tests (F7)

diegosouzapw0a4a7fabcebf
diff --git a/src/app/(dashboard)/dashboard/batch/BatchDetailModal.tsx b/src/app/(dashboard)/dashboard/batch/BatchDetailModal.tsx
index 005b931b95..c7874b9d15 100644
--- a/src/app/(dashboard)/dashboard/batch/BatchDetailModal.tsx
+++ b/src/app/(dashboard)/dashboard/batch/BatchDetailModal.tsx
@@ -2,6 +2,7 @@
import { useEffect } from "react";
import { useTranslations } from "next-intl";
+import { useBatchActions } from "./components/useBatchActions";
function relativeTime(ts: number): string {
const diffMs = Date.now() - ts * 1000;
@@ -64,6 +65,8 @@ interface BatchDetailModalProps {
batch: BatchRecord;
files: FileRecord[];
onClose: () => void;
+ /** Called after a successful cancel/retry action so the parent can refresh its list. */
+ onActionDone?: () => void;
}
const STATUS_STYLES: Record<string, string> = {
@@ -135,8 +138,18 @@ function formatTs(ts: number | null | undefined): string {
});
}
-export default function BatchDetailModal({ batch, files, onClose }: BatchDetailModalProps) {
+export default function BatchDetailModal({ batch, files, onClose, onActionDone }: BatchDetailModalProps) {
const t = useTranslations("common");
+
+ // ── Action hook (F7) ─────────────────────────────────────────────────────────
+ const { cancelling, retrying, error: actionError, cancel, retry, downloadHrefOutput, downloadHrefErrors } =
+ useBatchActions({ onRefresh: onActionDone, t });
+
+ // ── Status flags ──────────────────────────────────────────────────────────────
+ const isTerminal = ["completed", "failed", "cancelled", "expired"].includes(batch.status);
+ const canCancel = ["validating", "in_progress", "finalizing"].includes(batch.status);
+ const canRetry = isTerminal && !!batch.errorFileId && (batch.requestCountsFailed ?? 0) > 0;
+
useEffect(() => {
const handler = (e: KeyboardEvent) => {
if (e.key === "Escape") onClose();
@@ -382,6 +395,93 @@ export default function BatchDetailModal({ batch, files, onClose }: BatchDetailM
</div>
)}
</div>
+
+ {/* ── Action footer (F7) ─────────────────────────────────────────── */}
+ {(canCancel || canRetry || batch.outputFileId || batch.errorFileId) && (
+ <div className="flex flex-wrap gap-2 px-6 py-4 border-t border-[var(--color-border)] flex-shrink-0">
+ {/* Download output */}
+ {batch.outputFileId && (
+ <a
+ href={downloadHrefOutput(batch.outputFileId) ?? "#"}
+ download={`batch-${batch.id}-output.jsonl`}
+ className="flex items-center gap-2 px-3 py-2 text-sm font-medium rounded-lg bg-[var(--color-bg-alt)] border border-[var(--color-border)] text-[var(--color-text-main)] hover:opacity-90 transition-opacity"
+ >
+ <span className="material-symbols-outlined text-[16px]">download</span>
+ {t("batchActionDownloadOutput")}
+ </a>
+ )}
+
+ {/* Download errors */}
+ {batch.errorFileId && (
+ <a
+ href={downloadHrefErrors(batch.errorFileId) ?? "#"}
+ download={`batch-${batch.id}-errors.jsonl`}
+ className="flex items-center gap-2 px-3 py-2 text-sm font-medium rounded-lg bg-red-500/10 border border-red-500/25 text-red-400 hover:text-red-300 transition-colors"
+ >
+ <span className="material-symbols-outlined text-[16px]">error_outline</span>
+ {t("batchActionDownloadErrors")}
+ </a>
+ )}
+
+ {/* Retry failed */}
+ {canRetry && (
+ <button
+ onClick={async () => {
+ if (
+ window.confirm(
+ t("batchDetailActionRetry") +
+ ` (${batch.requestCountsFailed} ${t("batchActionRetry")})?`,
+ )
+ ) {
+ const result = await retry({
+ id: batch.id,
+ inputFileId: batch.inputFileId,
+ errorFileId: batch.errorFileId,
+ endpoint: batch.endpoint,
+ });
+ if (result?.newBatchId) onClose();
+ }
+ }}
+ disabled={retrying}
+ className="flex items-center gap-2 px-3 py-2 text-sm font-medium rounded-lg bg-blue-500/10 border border-blue-500/25 text-blue-400 hover:text-blue-300 transition-colors disabled:opacity-50"
+ >
+ <span className="material-symbols-outlined text-[16px]">
+ {retrying ? "hourglass_empty" : "refresh"}
+ </span>
+ {retrying ? t("batchDetailRetrying") : t("batchDetailActionRetry")}
+ </button>
+ )}
+
+ {/* Cancel */}
+ {canCancel && (
+ <button
+ onClick={async () => {
+ if (window.confirm("Cancel this batch? In-progress requests will stop.")) {
+ await cancel(batch.id);
+ onClose();
+ }
+ }}
+ disabled={cancelling}
+ className="flex items-center gap-2 px-3 py-2 text-sm font-medium rounded-lg bg-orange-500/10 border border-orange-500/25 text-orange-400 hover:text-orange-300 transition-colors disabled:opacity-50 ml-auto"
+ >
+ <span className="material-symbols-outlined text-[16px]">
+ {cancelling ? "hourglass_empty" : "close"}
+ </span>
+ {cancelling ? t("batchDetailCancelling") : t("batchDetailActionCancel")}
+ </button>
+ )}
+
+ {/* Action error — uses i18n key set by hook (D14: never raw err.message/stack) */}
+ {actionError && (
+ <div role="alert" className="basis-full mt-1 text-xs text-red-400">
+ {/* actionError is an i18n key from the hook (e.g. "batchActionCancel").
+ Cast is needed because next-intl types its arg as a specific union;
+ the hook guarantees this is always a valid message key. */}
+ {t(actionError as Parameters<typeof t>[0])}
+ </div>
+ )}
+ </div>
+ )}
</div>
</div>
);
diff --git a/tests/unit/dashboard/batch/components/BatchDetailModal.test.tsx b/tests/unit/dashboard/batch/components/BatchDetailModal.test.tsx
new file mode 100644
index 0000000000..adc22cfd51
--- /dev/null
+++ b/tests/unit/dashboard/batch/components/BatchDetailModal.test.tsx
@@ -0,0 +1,363 @@
+// @vitest-environment jsdom
+/**
+ * Tests for BatchDetailModal (F7) — action footer.
+ *
+ * Coverage cases:
+ * 1. Render batch in_progress → footer shows Cancel (no Download Output/Errors)
+ * 2. Render batch completed with outputFileId → shows Download Output link with download attr
+ * 3. Render batch failed + errorFileId + requestCountsFailed > 0 → shows Download Errors + Retry
+ * 4. Render batch failed (no errorFileId, no failures) → Cancel does NOT appear
+ * 5. Click Cancel → window.confirm → cancel hook called → onClose called
+ * 5b. Cancel confirm dismissed → cancel NOT called
+ * 6. Click Retry → window.confirm → retry hook called → onClose if newBatchId returned
+ * 6b. Retry returns null → onClose NOT called
+ * 7. actionError set → role="alert" shown in DOM
+ * 8. Sanitization: error displayed via i18n key — never raw paths or stack traces
+ * 9. Escape key → onClose called
+ */
+
+import React, { act } from "react";
+import { createRoot } from "react-dom/client";
+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
+
+// ── Mocks ──────────────────────────────────────────────────────────────────────
+
+// next-intl: return key as-is for straightforward assertions
+vi.mock("next-intl", () => ({
+ useTranslations: () => (key: string) => key,
+}));
+
+// useBatchActions: fully controlled mock
+const mockCancel = vi.fn();
+const mockRetry = vi.fn();
+const mockDownloadHrefOutput = vi.fn((id: string | null | undefined) =>
+ id ? `/api/v1/files/${id}/content` : null,
+);
+const mockDownloadHrefErrors = vi.fn((id: string | null | undefined) =>
+ id ? `/api/v1/files/${id}/content` : null,
+);
+
+// Factory state — tests mutate this before each render
+const hookState = {
+ cancelling: false,
+ retrying: false,
+ error: null as string | null,
+};
+
+vi.mock(
+ "../../../../../src/app/(dashboard)/dashboard/batch/components/useBatchActions",
+ () => ({
+ useBatchActions: vi.fn(() => ({
+ cancel: mockCancel,
+ retry: mockRetry,
+ downloadHrefOutput: mockDownloadHrefOutput,
+ downloadHrefErrors: mockDownloadHrefErrors,
+ cancelling: hookState.cancelling,
+ retrying: hookState.retrying,
+ error: hookState.error,
+ })),
+ }),
+);
+
+// ── Import after mocks ─────────────────────────────────────────────────────────
+
+const { default: BatchDetailModal } = await import(
+ "../../../../../src/app/(dashboard)/dashboard/batch/BatchDetailModal"
+);
+
+// ── Types ─────────────────────────────────────────────────────────────────────
+
+type BatchLike = Parameters<typeof BatchDetailModal>[0]["batch"];
+type FileLike = Parameters<typeof BatchDetailModal>[0]["files"][number];
+
+// ── Fixtures ──────────────────────────────────────────────────────────────────
+
+function makeBatch(overrides: Partial<BatchLike> = {}): BatchLike {
+ return {
+ id: "batch_abc123",
+ endpoint: "/v1/chat/completions",
+ completionWindow: "24h",
+ status: "in_progress",
+ inputFileId: "file_input_1",
+ outputFileId: null,
+ errorFileId: null,
+ createdAt: Math.floor(Date.now() / 1000) - 300,
+ inProgressAt: Math.floor(Date.now() / 1000) - 200,
+ expiresAt: null,
+ finalizingAt: null,
+ completedAt: null,
+ failedAt: null,
+ expiredAt: null,
+ cancellingAt: null,
+ cancelledAt: null,
+ requestCountsTotal: 100,
+ requestCountsCompleted: 40,
+ requestCountsFailed: 0,
+ metadata: null,
+ errors: null,
+ model: "gpt-4o-mini",
+ usage: null,
+ ...overrides,
+ };
+}
+
+const FILES: FileLike[] = [
+ { id: "file_input_1", filename: "input.jsonl", bytes: 10240, purpose: "batch", createdAt: 1700000000 },
+ { id: "file_output_1", filename: "output.jsonl", bytes: 20480, purpose: "batch_output", createdAt: 1700000100 },
+ { id: "file_error_1", filename: "errors.jsonl", bytes: 512, purpose: "batch_output", createdAt: 1700000100 },
+];
+
+// ── Render helpers ────────────────────────────────────────────────────────────
+
+type Container = { root: ReturnType<typeof createRoot>; el: HTMLDivElement };
+const containers: Container[] = [];
+
+function renderModal(
+ batchOverrides: Partial<BatchLike> = {},
+ onClose = vi.fn(),
+ onActionDone?: () => void,
+): { el: HTMLDivElement } {
+ const batch = makeBatch(batchOverrides);
+ const el = document.createElement("div");
+ document.body.appendChild(el);
+ const root = createRoot(el);
+ act(() => {
+ root.render(
+ <BatchDetailModal
+ batch={batch}
+ files={FILES}
+ onClose={onClose}
+ onActionDone={onActionDone}
+ />,
+ );
+ });
+ containers.push({ root, el });
+ return { el };
+}
+
+// ── Setup / teardown ──────────────────────────────────────────────────────────
+
+beforeEach(() => {
+ hookState.cancelling = false;
+ hookState.retrying = false;
+ hookState.error = null;
+ mockCancel.mockReset();
+ mockRetry.mockReset();
+ mockDownloadHrefOutput.mockImplementation((id: string | null | undefined) =>
+ id ? `/api/v1/files/${id}/content` : null,
+ );
+ mockDownloadHrefErrors.mockImplementation((id: string | null | undefined) =>
+ id ? `/api/v1/files/${id}/content` : null,
+ );
+});
+
+afterEach(() => {
+ for (const { root, el } of containers.splice(0)) {
+ act(() => root.unmount());
+ el.remove();
+ }
+ vi.clearAllMocks();
+ vi.restoreAllMocks();
+});
+
+// ── Tests ─────────────────────────────────────────────────────────────────────
+
+describe("BatchDetailModal — action footer (F7)", () => {
+ // 1. in_progress → Cancel visible, no Download buttons
+ it("shows Cancel button for in_progress batch without download buttons", () => {
+ const { el } = renderModal({ status: "in_progress", outputFileId: null, errorFileId: null });
+
+ const buttons = Array.from(el.querySelectorAll("button"));
+ const cancelBtn = buttons.find((b) => b.textContent?.includes("batchDetailActionCancel"));
+ expect(cancelBtn).toBeTruthy();
+ expect(el.textContent).not.toContain("batchActionDownloadOutput");
+ expect(el.textContent).not.toContain("batchActionDownloadErrors");
+ });
+
+ // 2. completed + outputFileId → Download Output link with download attribute
+ it("shows Download Output link when batch is completed with outputFileId", () => {
+ const { el } = renderModal({
+ status: "completed",
+ outputFileId: "file_output_1",
+ errorFileId: null,
+ requestCountsFailed: 0,
+ });
+
+ const links = Array.from(el.querySelectorAll("a"));
+ const outputLink = links.find((a) => a.textContent?.includes("batchActionDownloadOutput"));
+ expect(outputLink).toBeTruthy();
+ expect(outputLink!.getAttribute("download")).not.toBeNull();
+ expect(outputLink!.getAttribute("href")).toBe("/api/v1/files/file_output_1/content");
+
+ // Cancel must NOT appear for completed
+ const buttons = Array.from(el.querySelectorAll("button"));
+ const cancelBtn = buttons.find((b) => b.textContent?.includes("batchDetailActionCancel"));
+ expect(cancelBtn).toBeFalsy();
+ });
+
+ // 3. failed + errorFileId + failures → Download Errors + Retry button
+ it("shows Download Errors and Retry when batch failed with errorFileId and failures", () => {
+ const { el } = renderModal({
+ status: "failed",
+ outputFileId: null,
+ errorFileId: "file_error_1",
+ requestCountsFailed: 5,
+ });
+
+ const errLink = Array.from(el.querySelectorAll("a")).find((a) =>
+ a.textContent?.includes("batchActionDownloadErrors"),
+ );
+ expect(errLink).toBeTruthy();
+
+ const retryBtn = Array.from(el.querySelectorAll("button")).find((b) =>
+ b.textContent?.includes("batchDetailActionRetry"),
+ );
+ expect(retryBtn).toBeTruthy();
+
+ // Cancel must NOT appear for failed
+ const cancelBtn = Array.from(el.querySelectorAll("button")).find((b) =>
+ b.textContent?.includes("batchDetailActionCancel"),
+ );
+ expect(cancelBtn).toBeFalsy();
+ });
+
+ // 4. failed, no errorFileId, no failures → no footer action buttons
+ it("does not show Cancel or Retry for failed batch without errors", () => {
+ const { el } = renderModal({
+ status: "failed",
+ outputFileId: null,
+ errorFileId: null,
+ requestCountsFailed: 0,
+ });
+
+ const buttons = Array.from(el.querySelectorAll("button"));
+ expect(buttons.find((b) => b.textContent?.includes("batchDetailActionCancel"))).toBeFalsy();
+ expect(buttons.find((b) => b.textContent?.includes("batchDetailActionRetry"))).toBeFalsy();
+ });
+
+ // 5. Click Cancel → confirm → cancel hook called → onClose called
+ it("calls cancel hook then onClose after user confirms cancel", async () => {
+ const onClose = vi.fn();
+ mockCancel.mockResolvedValueOnce(undefined);
+ vi.spyOn(window, "confirm").mockReturnValueOnce(true);
+
+ const { el } = renderModal({ status: "in_progress" }, onClose);
+
+ const cancelBtn = Array.from(el.querySelectorAll("button")).find((b) =>
+ b.textContent?.includes("batchDetailActionCancel"),
+ )!;
+ await act(async () => {
+ cancelBtn.click();
+ await Promise.resolve();
+ });
+
+ expect(window.confirm).toHaveBeenCalled();
+ expect(mockCancel).toHaveBeenCalledWith("batch_abc123");
+ expect(onClose).toHaveBeenCalled();
+ });
+
+ // 5b. Cancel confirm dismissed → cancel NOT called
+ it("does not call cancel when user dismisses the confirm dialog", async () => {
+ vi.spyOn(window, "confirm").mockReturnValueOnce(false);
+
+ const { el } = renderModal({ status: "in_progress" });
+
+ const cancelBtn = Array.from(el.querySelectorAll("button")).find((b) =>
+ b.textContent?.includes("batchDetailActionCancel"),
+ )!;
+ await act(async () => {
+ cancelBtn.click();
+ await Promise.resolve();
+ });
+
+ expect(mockCancel).not.toHaveBeenCalled();
+ });
+
+ // 6. Click Retry → confirm → retry called → onClose when newBatchId returned
+ it("calls retry hook then onClose when retry returns a newBatchId", async () => {
+ const onClose = vi.fn();
+ mockRetry.mockResolvedValueOnce({ newBatchId: "batch_new_xyz" });
+ vi.spyOn(window, "confirm").mockReturnValueOnce(true);
+
+ const { el } = renderModal(
+ { status: "failed", errorFileId: "file_error_1", requestCountsFailed: 3 },
+ onClose,
+ );
+
+ const retryBtn = Array.from(el.querySelectorAll("button")).find((b) =>
+ b.textContent?.includes("batchDetailActionRetry"),
+ )!;
+ await act(async () => {
+ retryBtn.click();
+ await Promise.resolve();
+ });
+
+ expect(window.confirm).toHaveBeenCalled();
+ expect(mockRetry).toHaveBeenCalledWith({
+ id: "batch_abc123",
+ inputFileId: "file_input_1",
+ errorFileId: "file_error_1",
+ endpoint: "/v1/chat/completions",
+ });
+ expect(onClose).toHaveBeenCalled();
+ });
+
+ // 6b. Retry returns null → onClose NOT called
+ it("does not call onClose when retry returns null", async () => {
+ const onClose = vi.fn();
+ mockRetry.mockResolvedValueOnce(null);
+ vi.spyOn(window, "confirm").mockReturnValueOnce(true);
+
+ const { el } = renderModal(
+ { status: "failed", errorFileId: "file_error_1", requestCountsFailed: 2 },
+ onClose,
+ );
+
+ const retryBtn = Array.from(el.querySelectorAll("button")).find((b) =>
+ b.textContent?.includes("batchDetailActionRetry"),
+ )!;
+ await act(async () => {
+ retryBtn.click();
+ await Promise.resolve();
+ });
+
+ expect(mockRetry).toHaveBeenCalled();
+ expect(onClose).not.toHaveBeenCalled();
+ });
+
+ // 7. actionError set → role="alert" shown in DOM
+ it("shows role=alert when hook provides an actionError", () => {
+ hookState.error = "batchActionCancel";
+
+ const { el } = renderModal({ status: "in_progress" });
+
+ const alert = el.querySelector("[role='alert']");
+ expect(alert).not.toBeNull();
+ // t() mock returns key — confirms the i18n route is used, never raw err.message
+ expect(alert!.textContent).toContain("batchActionCancel");
+ });
+
+ // 8. Sanitization: error text never leaks paths or stack traces
+ it("never exposes stack traces or file paths in error display", () => {
+ hookState.error = "batchActionCancel";
+
+ const { el } = renderModal({ status: "in_progress" });
+
+ const bodyText = el.textContent ?? "";
+ expect(bodyText).not.toContain("/home/");
+ expect(bodyText).not.toContain("at /");
+ expect(bodyText).not.toContain(".ts:");
+ expect(bodyText).not.toMatch(/Error:/);
+ });
+
+ // 9. Escape key → onClose called
+ it("calls onClose when the Escape key is pressed", () => {
+ const onClose = vi.fn();
+ renderModal({}, onClose);
+
+ const event = new KeyboardEvent("keydown", { key: "Escape", bubbles: true });
+ document.dispatchEvent(event);
+
+ expect(onClose).toHaveBeenCalled();
+ });
+});