Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

add progress bar for download pdf (#8016)

Shahmir Varqha0330b96de756
diff --git a/frontend/e2e-tests/py/kitchen_sink.py b/frontend/e2e-tests/py/kitchen_sink.py
index a1ab8ea035..131f289e32 100644
--- a/frontend/e2e-tests/py/kitchen_sink.py
+++ b/frontend/e2e-tests/py/kitchen_sink.py
@@ -15,8 +15,8 @@
import marimo
-__generated_with = "0.19.4"
-app = marimo.App()
+__generated_with = "0.19.6"
+app = marimo.App(auto_download=["ipynb"])
@app.cell
diff --git a/frontend/src/components/editor/actions/useNotebookActions.tsx b/frontend/src/components/editor/actions/useNotebookActions.tsx
index 89f8c089e1..22fd5ba5d3 100644
--- a/frontend/src/components/editor/actions/useNotebookActions.tsx
+++ b/frontend/src/components/editor/actions/useNotebookActions.tsx
@@ -77,6 +77,7 @@ import {
} from "@/utils/download";
import { Filenames } from "@/utils/filenames";
import { Objects } from "@/utils/objects";
+import type { ProgressState } from "@/utils/progress";
import { newNotebookURL } from "@/utils/urls";
import { useRunAllCells } from "../cell/useRunCells";
import { useChromeActions, useChromeState } from "../chrome/state";
@@ -238,11 +239,12 @@ export function useNotebookActions() {
return;
}
- const downloadPDF = async () => {
- await updateCellOutputsWithScreenshots(
+ const downloadPDF = async (progress: ProgressState) => {
+ await updateCellOutputsWithScreenshots({
+ progress,
takeScreenshots,
updateCellOutputs,
- );
+ });
await downloadAsPDF({
filename: filename,
webpdf: false,
diff --git a/frontend/src/components/ui/progress.tsx b/frontend/src/components/ui/progress.tsx
index 2db9516341..b1d20c88b3 100644
--- a/frontend/src/components/ui/progress.tsx
+++ b/frontend/src/components/ui/progress.tsx
@@ -5,10 +5,18 @@ import * as React from "react";
import { cn } from "@/utils/cn";
+interface ProgressProps
+ extends React.ComponentPropsWithoutRef<typeof ProgressPrimitive.Root> {
+ /**
+ * When true, shows an indeterminate animated progress bar.
+ */
+ indeterminate?: boolean;
+}
+
const Progress = React.forwardRef<
- React.ElementRef<typeof ProgressPrimitive.Root>,
- React.ComponentPropsWithoutRef<typeof ProgressPrimitive.Root>
->(({ className, value, ...props }, ref) => (
+ React.ComponentRef<typeof ProgressPrimitive.Root>,
+ ProgressProps
+>(({ className, value, indeterminate, ...props }, ref) => (
<ProgressPrimitive.Root
ref={ref}
className={cn(
@@ -18,8 +26,17 @@ const Progress = React.forwardRef<
{...props}
>
<ProgressPrimitive.Indicator
- className="h-full w-full flex-1 bg-primary transition-all pulse"
- style={{ transform: `translateX(-${100 - (value || 0)}%)` }}
+ className={cn(
+ "h-full flex-1 bg-primary",
+ indeterminate
+ ? "w-1/3 animate-progress-indeterminate"
+ : "w-full transition-transform duration-300 ease-out",
+ )}
+ style={
+ indeterminate
+ ? undefined
+ : { transform: `translateX(-${100 - (value || 0)}%)` }
+ }
/>
</ProgressPrimitive.Root>
));
diff --git a/frontend/src/core/export/__tests__/hooks.test.ts b/frontend/src/core/export/__tests__/hooks.test.ts
index a03d7b4f3b..ad7fa1d8d3 100644
--- a/frontend/src/core/export/__tests__/hooks.test.ts
+++ b/frontend/src/core/export/__tests__/hooks.test.ts
@@ -8,6 +8,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
import type { CellId } from "@/core/cells/ids";
import { CellOutputId } from "@/core/cells/ids";
import type { CellRuntimeState } from "@/core/cells/types";
+import { ProgressState } from "@/utils/progress";
import {
updateCellOutputsWithScreenshots,
useEnrichCellOutputs,
@@ -38,6 +39,8 @@ vi.mock("@/core/cells/cells", async () => {
};
});
+const progress = ProgressState.indeterminate();
+
import { toPng } from "html-to-image";
import { toast } from "@/components/ui/use-toast";
import { cellsRuntimeAtom } from "@/core/cells/cells";
@@ -100,7 +103,7 @@ describe("useEnrichCellOutputs", () => {
const { result } = renderHook(() => useEnrichCellOutputs(), { wrapper });
const enrichCellOutputs = result.current;
- const output = await enrichCellOutputs();
+ const output = await enrichCellOutputs(progress);
expect(output).toEqual({});
expect(document.getElementById).not.toHaveBeenCalled();
@@ -132,7 +135,7 @@ describe("useEnrichCellOutputs", () => {
const { result } = renderHook(() => useEnrichCellOutputs(), { wrapper });
const enrichCellOutputs = result.current;
- const output = await enrichCellOutputs();
+ const output = await enrichCellOutputs(progress);
expect(document.getElementById).toHaveBeenCalledWith(
CellOutputId.create(cellId),
@@ -177,7 +180,7 @@ describe("useEnrichCellOutputs", () => {
// First call - should capture
let enrichCellOutputs = result.current;
- let output = await enrichCellOutputs();
+ let output = await enrichCellOutputs(progress);
expect(output).toEqual({ [cellId]: ["image/png", mockDataUrl] });
expect(toPng).toHaveBeenCalledTimes(1);
@@ -186,7 +189,7 @@ describe("useEnrichCellOutputs", () => {
// Second call with same output - should not capture again
enrichCellOutputs = result.current;
- output = await enrichCellOutputs();
+ output = await enrichCellOutputs(progress);
expect(output).toEqual({}); // Empty because output hasn't changed
expect(toPng).toHaveBeenCalledTimes(1); // Still only 1 call
});
@@ -215,7 +218,7 @@ describe("useEnrichCellOutputs", () => {
const { result } = renderHook(() => useEnrichCellOutputs(), { wrapper });
const enrichCellOutputs = result.current;
- const output = await enrichCellOutputs();
+ const output = await enrichCellOutputs(progress);
expect(output).toEqual({}); // Failed screenshot should be filtered out
expect(Logger.error).toHaveBeenCalledWith(
@@ -245,7 +248,7 @@ describe("useEnrichCellOutputs", () => {
const { result } = renderHook(() => useEnrichCellOutputs(), { wrapper });
const enrichCellOutputs = result.current;
- const output = await enrichCellOutputs();
+ const output = await enrichCellOutputs(progress);
expect(output).toEqual({});
expect(Logger.error).toHaveBeenCalledWith(
@@ -294,7 +297,7 @@ describe("useEnrichCellOutputs", () => {
const { result } = renderHook(() => useEnrichCellOutputs(), { wrapper });
const enrichCellOutputs = result.current;
- const output = await enrichCellOutputs();
+ const output = await enrichCellOutputs(progress);
expect(output).toEqual({
[cell1]: ["image/png", mockDataUrl1],
@@ -340,7 +343,7 @@ describe("useEnrichCellOutputs", () => {
const { result } = renderHook(() => useEnrichCellOutputs(), { wrapper });
const enrichCellOutputs = result.current;
- const output = await enrichCellOutputs();
+ const output = await enrichCellOutputs(progress);
// Only the successful screenshot should be in the result
expect(output).toEqual({
@@ -382,13 +385,13 @@ describe("useEnrichCellOutputs", () => {
// First screenshot
let enrichCellOutputs = result.current;
- let output = await enrichCellOutputs();
+ let output = await enrichCellOutputs(progress);
expect(output).toEqual({ [cellId]: ["image/png", mockDataUrl1] });
// Second call - same output, should not be captured
rerender();
enrichCellOutputs = result.current;
- output = await enrichCellOutputs();
+ output = await enrichCellOutputs(progress);
expect(output).toEqual({});
// Third call - output changed, should be captured
@@ -407,7 +410,7 @@ describe("useEnrichCellOutputs", () => {
rerender();
enrichCellOutputs = result.current;
- output = await enrichCellOutputs();
+ output = await enrichCellOutputs(progress);
expect(output).toEqual({ [cellId]: ["image/png", mockDataUrl2] });
expect(toPng).toHaveBeenCalledTimes(2);
});
@@ -447,7 +450,7 @@ describe("useEnrichCellOutputs", () => {
const { result } = renderHook(() => useEnrichCellOutputs(), { wrapper });
const enrichCellOutputs = result.current;
- const output = await enrichCellOutputs();
+ const output = await enrichCellOutputs(progress);
// None of these should trigger screenshots
expect(output).toEqual({});
@@ -472,7 +475,7 @@ describe("useEnrichCellOutputs", () => {
const { result } = renderHook(() => useEnrichCellOutputs(), { wrapper });
const enrichCellOutputs = result.current;
- const output = await enrichCellOutputs();
+ const output = await enrichCellOutputs(progress);
expect(output).toEqual({});
expect(document.getElementById).not.toHaveBeenCalled();
@@ -504,7 +507,7 @@ describe("useEnrichCellOutputs", () => {
const { result } = renderHook(() => useEnrichCellOutputs(), { wrapper });
const enrichCellOutputs = result.current;
- const output = await enrichCellOutputs();
+ const output = await enrichCellOutputs(progress);
// Verify the exact return type structure
expect(output).toHaveProperty(cellId);
@@ -535,7 +538,11 @@ describe("updateCellOutputsWithScreenshots", () => {
const takeScreenshots = vi.fn().mockResolvedValue(mockScreenshots);
const updateCellOutputs = vi.fn().mockResolvedValue(null);
- await updateCellOutputsWithScreenshots(takeScreenshots, updateCellOutputs);
+ await updateCellOutputsWithScreenshots({
+ progress,
+ takeScreenshots,
+ updateCellOutputs,
+ });
expect(takeScreenshots).toHaveBeenCalledTimes(1);
expect(updateCellOutputs).toHaveBeenCalledTimes(1);
@@ -548,7 +555,11 @@ describe("updateCellOutputsWithScreenshots", () => {
const takeScreenshots = vi.fn().mockResolvedValue({});
const updateCellOutputs = vi.fn().mockResolvedValue(null);
- await updateCellOutputsWithScreenshots(takeScreenshots, updateCellOutputs);
+ await updateCellOutputsWithScreenshots({
+ progress,
+ takeScreenshots,
+ updateCellOutputs,
+ });
expect(takeScreenshots).toHaveBeenCalledTimes(1);
expect(updateCellOutputs).not.toHaveBeenCalled();
@@ -571,7 +582,11 @@ describe("updateCellOutputsWithScreenshots", () => {
const takeScreenshots = vi.fn().mockResolvedValue(mockScreenshots);
const updateCellOutputs = vi.fn().mockResolvedValue(null);
- await updateCellOutputsWithScreenshots(takeScreenshots, updateCellOutputs);
+ await updateCellOutputsWithScreenshots({
+ progress,
+ takeScreenshots,
+ updateCellOutputs,
+ });
expect(updateCellOutputs).toHaveBeenCalledWith({
cellIdsToOutput: mockScreenshots,
@@ -584,7 +599,11 @@ describe("updateCellOutputsWithScreenshots", () => {
const updateCellOutputs = vi.fn().mockResolvedValue(null);
// Should not throw - errors are caught and shown via toast
- await updateCellOutputsWithScreenshots(takeScreenshots, updateCellOutputs);
+ await updateCellOutputsWithScreenshots({
+ progress,
+ takeScreenshots,
+ updateCellOutputs,
+ });
expect(updateCellOutputs).not.toHaveBeenCalled();
expect(Logger.error).toHaveBeenCalledWith(
@@ -613,7 +632,11 @@ describe("updateCellOutputsWithScreenshots", () => {
const updateCellOutputs = vi.fn().mockRejectedValue(error);
// Should not throw - errors are caught and shown via toast
- await updateCellOutputsWithScreenshots(takeScreenshots, updateCellOutputs);
+ await updateCellOutputsWithScreenshots({
+ progress,
+ takeScreenshots,
+ updateCellOutputs,
+ });
expect(Logger.error).toHaveBeenCalledWith(
"Error updating cell outputs with screenshots:",
diff --git a/frontend/src/core/export/hooks.ts b/frontend/src/core/export/hooks.ts
index e1c8d8859a..cca72e45ae 100644
--- a/frontend/src/core/export/hooks.ts
+++ b/frontend/src/core/export/hooks.ts
@@ -7,6 +7,7 @@ import { useInterval } from "@/hooks/useInterval";
import { getImageDataUrlForCell } from "@/utils/download";
import { Logger } from "@/utils/Logger";
import { Objects } from "@/utils/objects";
+import { ProgressState } from "@/utils/progress";
import { cellsRuntimeAtom } from "../cells/cells";
import type { CellId } from "../cells/ids";
import { connectionAtom } from "../network/connection";
@@ -63,10 +64,11 @@ export function useAutoExport() {
useInterval(
async () => {
- await updateCellOutputsWithScreenshots(
+ await updateCellOutputsWithScreenshots({
+ progress: ProgressState.indeterminate(),
takeScreenshots,
updateCellOutputs,
- );
+ });
await autoExportAsIPYNB({
download: false,
});
@@ -95,6 +97,8 @@ const MIME_TYPES_TO_CAPTURE_SCREENSHOTS = new Set<MimeType>([
"application/vnd.vega.v6+json",
]);
+type ScreenshotResults = Record<CellId, ["image/png", string]>;
+
/**
* Take screenshots of cells with HTML outputs. These images will be sent to the backend to be exported to IPYNB.
* @returns A map of cell IDs to their screenshots data.
@@ -103,7 +107,7 @@ export function useEnrichCellOutputs() {
const [richCellsOutput, setRichCellsOutput] = useAtom(richCellsToOutputAtom);
const cellRuntimes = useAtomValue(cellsRuntimeAtom);
- return async (): Promise<Record<CellId, ["image/png", string]>> => {
+ return async (progress: ProgressState): Promise<ScreenshotResults> => {
const trackedCellsOutput: Record<CellId, unknown> = {};
const cellsToCaptureScreenshot: [CellId, unknown][] = [];
@@ -129,43 +133,40 @@ export function useEnrichCellOutputs() {
}
// Capture screenshots
- const results = await Promise.all(
- cellsToCaptureScreenshot.map(async ([cellId]) => {
- try {
- const dataUrl = await getImageDataUrlForCell(cellId, false);
- if (!dataUrl) {
- Logger.error(`Failed to capture screenshot for cell ${cellId}`);
- return null;
- }
- return [cellId, ["image/png", dataUrl]] as [
- CellId,
- ["image/png", string],
- ];
- } catch (error) {
- Logger.error(`Error screenshotting cell ${cellId}:`, error);
- return null;
+ const total = cellsToCaptureScreenshot.length;
+ progress.addTotal(total);
+ const results: ScreenshotResults = {};
+ for (const [cellId] of cellsToCaptureScreenshot) {
+ try {
+ const dataUrl = await getImageDataUrlForCell(cellId, false);
+ if (!dataUrl) {
+ Logger.error(`Failed to capture screenshot for cell ${cellId}`);
+ continue;
}
- }),
- );
-
- return Objects.fromEntries(
- results.filter(
- (result): result is [CellId, ["image/png", string]] => result !== null,
- ),
- );
+ results[cellId] = ["image/png", dataUrl];
+ } catch (error) {
+ Logger.error(`Error screenshotting cell ${cellId}:`, error);
+ } finally {
+ progress.increment(1);
+ }
+ }
+
+ return results;
};
}
/**
* Utility function to take screenshots of cells with HTML outputs and update the cell outputs.
*/
-export async function updateCellOutputsWithScreenshots(
- takeScreenshots: () => Promise<Record<CellId, ["image/png", string]>>,
- updateCellOutputs: (request: UpdateCellOutputsRequest) => Promise<null>,
-) {
+export async function updateCellOutputsWithScreenshots(opts: {
+ progress: ProgressState;
+ takeScreenshots: (progress: ProgressState) => Promise<ScreenshotResults>;
+ updateCellOutputs: (request: UpdateCellOutputsRequest) => Promise<null>;
+}) {
+ const { progress, takeScreenshots, updateCellOutputs } = opts;
try {
- const cellIdsToOutput = await takeScreenshots();
- if (Object.keys(cellIdsToOutput).length > 0) {
+ const cellIdsToOutput = await takeScreenshots(progress);
+ if (Objects.size(cellIdsToOutput) > 0) {
await updateCellOutputs({ cellIdsToOutput });
}
} catch (error) {
diff --git a/frontend/src/utils/__tests__/download.test.tsx b/frontend/src/utils/__tests__/download.test.tsx
index 4b85e6dfb6..41d3f3b7f2 100644
--- a/frontend/src/utils/__tests__/download.test.tsx
+++ b/frontend/src/utils/__tests__/download.test.tsx
@@ -57,10 +57,12 @@ describe("withLoadingToast", () => {
});
expect(toast).toHaveBeenCalledTimes(1);
- expect(toast).toHaveBeenCalledWith({
- title: "Loading...",
- duration: Infinity,
- });
+ expect(toast).toHaveBeenCalledWith(
+ expect.objectContaining({
+ title: "Loading...",
+ duration: Infinity,
+ }),
+ );
expect(mockDismiss).toHaveBeenCalledTimes(1);
expect(result).toBe("success");
});
diff --git a/frontend/src/utils/__tests__/objects.test.ts b/frontend/src/utils/__tests__/objects.test.ts
new file mode 100644
index 0000000000..1046c99f85
--- /dev/null
+++ b/frontend/src/utils/__tests__/objects.test.ts
@@ -0,0 +1,263 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+import { describe, expect, it } from "vitest";
+import { Objects } from "../objects";
+
+describe("Objects", () => {
+ describe("EMPTY", () => {
+ it("should be an empty frozen object", () => {
+ expect(Objects.EMPTY).toEqual({});
+ expect(Object.isFrozen(Objects.EMPTY)).toBe(true);
+ });
+ });
+
+ describe("mapValues", () => {
+ it("should map values of an object", () => {
+ const obj = { a: 1, b: 2, c: 3 };
+ const result = Objects.mapValues(obj, (v) => v * 2);
+ expect(result).toEqual({ a: 2, b: 4, c: 6 });
+ });
+
+ it("should pass key as second argument", () => {
+ const obj = { a: 1, b: 2 };
+ const result = Objects.mapValues(obj, (v, k) => `${k}:${v}`);
+ expect(result).toEqual({ a: "a:1", b: "b:2" });
+ });
+
+ it("should handle empty objects", () => {
+ const result = Objects.mapValues({}, (v) => v);
+ expect(result).toEqual({});
+ });
+
+ it("should return falsy input unchanged", () => {
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ expect(Objects.mapValues(null as any, (v) => v)).toBe(null);
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ expect(Objects.mapValues(undefined as any, (v) => v)).toBe(undefined);
+ });
+ });
+
+ describe("fromEntries", () => {
+ it("should create object from entries", () => {
+ const entries: [string, number][] = [
+ ["a", 1],
+ ["b", 2],
+ ];
+ expect(Objects.fromEntries(entries)).toEqual({ a: 1, b: 2 });
+ });
+
+ it("should handle empty entries", () => {
+ expect(Objects.fromEntries([])).toEqual({});
+ });
+
+ it("should handle numeric keys", () => {
+ const entries: [number, string][] = [
+ [1, "a"],
+ [2, "b"],
+ ];
+ expect(Objects.fromEntries(entries)).toEqual({ 1: "a", 2: "b" });
+ });
+ });
+
+ describe("entries", () => {
+ it("should return entries of an object", () => {
+ const obj = { a: 1, b: 2 };
+ const entries = Objects.entries(obj);
+ expect(entries).toContainEqual(["a", 1]);
+ expect(entries).toContainEqual(["b", 2]);
+ expect(entries).toHaveLength(2);
+ });
+
+ it("should handle empty objects", () => {
+ expect(Objects.entries({})).toEqual([]);
+ });
+ });
+
+ describe("keys", () => {
+ it("should return keys of an object", () => {
+ const obj = { a: 1, b: 2, c: 3 };
+ const keys = Objects.keys(obj);
+ expect(keys).toContain("a");
+ expect(keys).toContain("b");
+ expect(keys).toContain("c");
+ expect(keys).toHaveLength(3);
+ });
+
+ it("should handle empty objects", () => {
+ expect(Objects.keys({})).toEqual([]);
+ });
+ });
+
+ describe("size", () => {
+ it("should return the number of keys", () => {
+ expect(Objects.size({ a: 1, b: 2, c: 3 })).toBe(3);
+ });
+
+ it("should return 0 for empty objects", () => {
+ expect(Objects.size({})).toBe(0);
+ });
+ });
+
+ describe("keyBy", () => {
+ it("should key items by specified key function", () => {
+ const items = [
+ { id: "a", value: 1 },
+ { id: "b", value: 2 },
+ ];
+ const result = Objects.keyBy(items, (item) => item.id);
+ expect(result).toEqual({
+ a: { id: "a", value: 1 },
+ b: { id: "b", value: 2 },
+ });
+ });
+
+ it("should skip items with undefined keys", () => {
+ const items = [
+ { id: "a", value: 1 },
+ { id: undefined as unknown as string, value: 2 },
+ { id: "c", value: 3 },
+ ];
+ const result = Objects.keyBy(items, (item) => item.id);
+ expect(result).toEqual({
+ a: { id: "a", value: 1 },
+ c: { id: "c", value: 3 },
+ });
+ });
+
+ it("should handle empty arrays", () => {
+ expect(Objects.keyBy([], (item) => item)).toEqual({});
+ });
+
+ it("should use last item when keys collide", () => {
+ const items = [
+ { id: "a", value: 1 },
+ { id: "a", value: 2 },
+ ];
+ const result = Objects.keyBy(items, (item) => item.id);
+ expect(result).toEqual({ a: { id: "a", value: 2 } });
+ });
+ });
+
+ describe("collect", () => {
+ it("should collect and transform items", () => {
+ const items = [
+ { id: "a", value: 1 },
+ { id: "b", value: 2 },
+ ];
+ const result = Objects.collect(
+ items,
+ (item) => item.id,
+ (item) => item.value * 2,
+ );
+ expect(result).toEqual({ a: 2, b: 4 });
+ });
+
+ it("should handle empty arrays", () => {
+ const result = Objects.collect(
+ [],
+ (item) => item,
+ (item) => item,
+ );
+ expect(result).toEqual({});
+ });
+ });
+
+ describe("groupBy", () => {
+ it("should group items by key", () => {
+ const items = [
+ { category: "a", value: 1 },
+ { category: "b", value: 2 },
+ { category: "a", value: 3 },
+ ];
+ const result = Objects.groupBy(
+ items,
+ (item) => item.category,
+ (item) => item.value,
+ );
+ expect(result).toEqual({
+ a: [1, 3],
+ b: [2],
+ });
+ });
+
+ it("should skip items with undefined keys", () => {
+ const items = [
+ { category: "a", value: 1 },
+ { category: undefined as unknown as string, value: 2 },
+ { category: "a", value: 3 },
+ ];
+ const result = Objects.groupBy(
+ items,
+ (item) => item.category,
+ (item) => item.value,
+ );
+ expect(result).toEqual({ a: [1, 3] });
+ });
+
+ it("should handle empty arrays", () => {
+ const result = Objects.groupBy(
+ [],
+ (item) => item,
+ (item) => item,
+ );
+ expect(result).toEqual({});
+ });
+ });
+
+ describe("filter", () => {
+ it("should filter object entries by predicate", () => {
+ const obj = { a: 1, b: 2, c: 3, d: 4 };
+ const result = Objects.filter(obj, (v) => v % 2 === 0);
+ expect(result).toEqual({ b: 2, d: 4 });
+ });
+
+ it("should pass key as second argument", () => {
+ const obj = { a: 1, b: 2, c: 3 };
+ const result = Objects.filter(obj, (_, k) => k !== "b");
+ expect(result).toEqual({ a: 1, c: 3 });
+ });
+
+ it("should handle empty objects", () => {
+ const result = Objects.filter({}, () => true);
+ expect(result).toEqual({});
+ });
+
+ it("should return empty object when nothing matches", () => {
+ const obj = { a: 1, b: 2 };
+ const result = Objects.filter(obj, () => false);
+ expect(result).toEqual({});
+ });
+ });
+
+ describe("omit", () => {
+ it("should omit specified keys from object", () => {
+ const obj = { a: 1, b: 2, c: 3 };
+ const result = Objects.omit(obj, ["b"]);
+ expect(result).toEqual({ a: 1, c: 3 });
+ });
+
+ it("should omit multiple keys", () => {
+ const obj = { a: 1, b: 2, c: 3, d: 4 };
+ const result = Objects.omit(obj, ["a", "c"]);
+ expect(result).toEqual({ b: 2, d: 4 });
+ });
+
+ it("should handle keys provided as Set", () => {
+ const obj = { a: 1, b: 2, c: 3 };
+ const result = Objects.omit(obj, new Set(["a", "c"] as const));
+ expect(result).toEqual({ b: 2 });
+ });
+
+ it("should handle omitting non-existent keys", () => {
+ const obj = { a: 1, b: 2 };
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ const result = Objects.omit(obj, ["c" as any]);
+ expect(result).toEqual({ a: 1, b: 2 });
+ });
+
+ it("should return all properties when omitting empty array", () => {
+ const obj = { a: 1, b: 2 };
+ const result = Objects.omit(obj, []);
+ expect(result).toEqual({ a: 1, b: 2 });
+ });
+ });
+});
diff --git a/frontend/src/utils/__tests__/progress.test.ts b/frontend/src/utils/__tests__/progress.test.ts
new file mode 100644
index 0000000000..7769196caa
--- /dev/null
+++ b/frontend/src/utils/__tests__/progress.test.ts
@@ -0,0 +1,156 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+import { describe, expect, it, vi } from "vitest";
+import { ProgressState } from "../progress";
+
+describe("ProgressState", () => {
+ describe("constructor", () => {
+ it("should initialize with a numeric total", () => {
+ const progress = new ProgressState(100);
+ expect(progress.getProgress()).toBe(0);
+ });
+
+ it("should initialize with indeterminate total", () => {
+ const progress = new ProgressState("indeterminate");
+ expect(progress.getProgress()).toBe("indeterminate");
+ });
+ });
+
+ describe("static indeterminate", () => {
+ it("should create an indeterminate progress state", () => {
+ const progress = ProgressState.indeterminate();
+ expect(progress.getProgress()).toBe("indeterminate");
+ });
+ });
+
+ describe("addTotal", () => {
+ it("should add to the total when numeric", () => {
+ const progress = new ProgressState(100);
+ progress.addTotal(50);
+ // Progress is 0, total is now 150
+ expect(progress.getProgress()).toBe(0);
+ progress.increment(75);
+ expect(progress.getProgress()).toBe(50); // 75/150 * 100 = 50
+ });
+
+ it("should convert indeterminate to numeric when adding total", () => {
+ const progress = ProgressState.indeterminate();
+ expect(progress.getProgress()).toBe("indeterminate");
+ progress.addTotal(100);
+ expect(progress.getProgress()).toBe(0);
+ });
+ });
+
+ describe("increment", () => {
+ it("should increment the progress", () => {
+ const progress = new ProgressState(100);
+ progress.increment(25);
+ expect(progress.getProgress()).toBe(25);
+ });
+
+ it("should accumulate multiple increments", () => {
+ const progress = new ProgressState(100);
+ progress.increment(25);
+ progress.increment(25);
+ progress.increment(25);
+ expect(progress.getProgress()).toBe(75);
+ });
+
+ it("should allow progress beyond 100%", () => {
+ const progress = new ProgressState(100);
+ progress.increment(150);
+ expect(progress.getProgress()).toBe(150);
+ });
+ });
+
+ describe("getProgress", () => {
+ it("should return indeterminate for indeterminate state", () => {
+ const progress = ProgressState.indeterminate();
+ progress.increment(50); // increment has no visible effect
+ expect(progress.getProgress()).toBe("indeterminate");
+ });
+
+ it("should return correct percentage", () => {
+ const progress = new ProgressState(200);
+ progress.increment(50);
+ expect(progress.getProgress()).toBe(25); // 50/200 * 100 = 25
+ });
+
+ it("should return 0 when no progress made", () => {
+ const progress = new ProgressState(100);
+ expect(progress.getProgress()).toBe(0);
+ });
+
+ it("should return 100 when complete", () => {
+ const progress = new ProgressState(100);
+ progress.increment(100);
+ expect(progress.getProgress()).toBe(100);
+ });
+ });
+
+ describe("subscribe", () => {
+ it("should notify listeners on increment", () => {
+ const progress = new ProgressState(100);
+ const listener = vi.fn();
+ progress.subscribe(listener);
+
+ progress.increment(25);
+ expect(listener).toHaveBeenCalledWith(25);
+
+ progress.increment(25);
+ expect(listener).toHaveBeenCalledWith(50);
+ expect(listener).toHaveBeenCalledTimes(2);
+ });
+
+ it("should notify listeners on addTotal", () => {
+ const progress = new ProgressState(100);
+ const listener = vi.fn();
+ progress.subscribe(listener);
+
+ progress.addTotal(100);
+ expect(listener).toHaveBeenCalledWith(0); // 0/200 = 0%
+ });
+
+ it("should notify listeners when converting from indeterminate", () => {
+ const progress = ProgressState.indeterminate();
+ const listener = vi.fn();
+ progress.subscribe(listener);
+
+ progress.addTotal(100);
+ expect(listener).toHaveBeenCalledWith(0);
+ });
+
+ it("should return unsubscribe function", () => {
+ const progress = new ProgressState(100);
+ const listener = vi.fn();
+ const unsubscribe = progress.subscribe(listener);
+
+ progress.increment(25);
+ expect(listener).toHaveBeenCalledTimes(1);
+
+ unsubscribe();
+ progress.increment(25);
+ expect(listener).toHaveBeenCalledTimes(1); // no additional calls
+ });
+
+ it("should support multiple listeners", () => {
+ const progress = new ProgressState(100);
+ const listener1 = vi.fn();
+ const listener2 = vi.fn();
+ progress.subscribe(listener1);
+ progress.subscribe(listener2);
+
+ progress.increment(50);
+ expect(listener1).toHaveBeenCalledWith(50);
+ expect(listener2).toHaveBeenCalledWith(50);
+ });
+
+ it("should pass indeterminate to listeners", () => {
+ const progress = ProgressState.indeterminate();
+ const listener = vi.fn();
+ progress.subscribe(listener);
+
+ progress.increment(50);
+ expect(listener).toHaveBeenCalledWith("indeterminate");
+ });
+ });
+});
diff --git a/frontend/src/utils/download.ts b/frontend/src/utils/download.ts
index 182f508bed..612e2c4ae8 100644
--- a/frontend/src/utils/download.ts
+++ b/frontend/src/utils/download.ts
@@ -1,5 +1,6 @@
/* Copyright 2026 Marimo. All rights reserved. */
+import React from "react";
import { toast } from "@/components/ui/use-toast";
import { type CellId, CellOutputId } from "@/core/cells/ids";
import { getRequestClient } from "@/core/network/requests";
@@ -9,6 +10,8 @@ import { prettyError } from "./errors";
import { toPng } from "./html-to-image";
import { captureIframeAsImage } from "./iframe";
import { Logger } from "./Logger";
+import { ProgressState } from "./progress";
+import { ToastProgress } from "./toast-progress";
/**
* Show a loading toast while an async operation is in progress.
@@ -16,14 +19,16 @@ import { Logger } from "./Logger";
*/
export async function withLoadingToast<T>(
title: string,
- fn: () => Promise<T>,
+ fn: (progress: ProgressState) => Promise<T>,
): Promise<T> {
+ const progress = ProgressState.indeterminate();
const loadingToast = toast({
title,
+ description: React.createElement(ToastProgress, { progress }),
duration: Infinity,
});
try {
- const result = await fn();
+ const result = await fn(progress);
loadingToast.dismiss();
return result;
} catch (error) {
diff --git a/frontend/src/utils/objects.ts b/frontend/src/utils/objects.ts
index 0b50512916..805ef28dd0 100644
--- a/frontend/src/utils/objects.ts
+++ b/frontend/src/utils/objects.ts
@@ -32,6 +32,9 @@ export const Objects = {
keys<K extends string | number>(obj: Record<K, unknown>): K[] {
return Object.keys(obj) as K[];
},
+ size<K extends string | number>(obj: Record<K, unknown>): number {
+ return Object.keys(obj).length;
+ },
/**
* Type-safe keyBy
*/
diff --git a/frontend/src/utils/progress.ts b/frontend/src/utils/progress.ts
new file mode 100644
index 0000000000..8f2cc2292c
--- /dev/null
+++ b/frontend/src/utils/progress.ts
@@ -0,0 +1,61 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+export type ProgressListener = (progress: number | "indeterminate") => void;
+
+export class ProgressState {
+ private progress = 0;
+ private total: number | "indeterminate";
+ private listeners = new Set<ProgressListener>();
+
+ constructor(total: number | "indeterminate") {
+ this.total = total;
+ }
+
+ static indeterminate(): ProgressState {
+ return new ProgressState("indeterminate");
+ }
+
+ addTotal(total: number) {
+ if (this.total === "indeterminate") {
+ this.total = total;
+ } else {
+ this.total += total;
+ }
+ this.notifyListeners();
+ }
+
+ /**
+ * Update the progress by the given increment.
+ */
+ increment(increment: number) {
+ this.progress += increment;
+ this.notifyListeners();
+ }
+
+ /**
+ * Get the progress as a percentage (0-100)
+ */
+ getProgress(): number | "indeterminate" {
+ if (this.total === "indeterminate") {
+ return "indeterminate";
+ }
+ return (this.progress / this.total) * 100;
+ }
+
+ /**
+ * Subscribe to progress updates.
+ * Returns an unsubscribe function.
+ */
+ subscribe(listener: ProgressListener): () => void {
+ this.listeners.add(listener);
+ return () => {
+ this.listeners.delete(listener);
+ };
+ }
+
+ private notifyListeners() {
+ const progress = this.getProgress();
+ for (const listener of this.listeners) {
+ listener(progress);
+ }
+ }
+}
diff --git a/frontend/src/utils/toast-progress.tsx b/frontend/src/utils/toast-progress.tsx
new file mode 100644
index 0000000000..38cfd88d34
--- /dev/null
+++ b/frontend/src/utils/toast-progress.tsx
@@ -0,0 +1,41 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import { useSyncExternalStore } from "react";
+import { Progress } from "@/components/ui/progress";
+import type { ProgressState } from "./progress";
+
+interface ToastProgressProps {
+ progress: ProgressState;
+ showPercentage?: boolean;
+}
+
+/**
+ * A progress bar component that subscribes to a ProgressState and updates reactively.
+ * Designed to be used inside toasts.
+ */
+export const ToastProgress = ({
+ progress,
+ showPercentage = false,
+}: ToastProgressProps) => {
+ const value = useSyncExternalStore(
+ (callback) => progress.subscribe(callback),
+ () => progress.getProgress(),
+ );
+
+ // if we are at 100%, we want to show the indeterminate progress bar
+ const isIndeterminate = value === "indeterminate" || value === 100;
+
+ return (
+ <div className="mt-2 w-full min-w-[200px]">
+ <Progress
+ value={isIndeterminate ? undefined : value}
+ indeterminate={isIndeterminate}
+ />
+ {!isIndeterminate && showPercentage && (
+ <div className="mt-1 text-xs text-muted-foreground text-right">
+ {Math.round(value)}%
+ </div>
+ )}
+ </div>
+ );
+};
diff --git a/frontend/tailwind.config.cjs b/frontend/tailwind.config.cjs
index dcf28807ab..6c93fcbb6f 100644
--- a/frontend/tailwind.config.cjs
+++ b/frontend/tailwind.config.cjs
@@ -120,6 +120,10 @@ module.exports = {
"0%": { transform: "translateX(-100%)" },
"100%": { transform: "translateX(400%)" },
},
+ "progress-indeterminate": {
+ "0%": { transform: "translateX(-100%)" },
+ "100%": { transform: "translateX(400%)" },
+ },
},
animation: {
"accordion-down": "accordion-down 0.2s ease-out",
@@ -128,6 +132,8 @@ module.exports = {
"delayed-show-400": "delayed-show 400ms ease-out",
"ellipsis-dot": "ellipsis-dot 400ms ease-in-out infinite",
slide: "slide 1.5s ease-in-out infinite",
+ "progress-indeterminate":
+ "progress-indeterminate 1.5s ease-in-out infinite",
},
gridTemplateColumns: {
"auto-fit": "repeat(auto-fit, minmax(0, 1fr))",