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.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
fix: cache favicon requests (#3736)
Myles Scolnick5b81faf55472
diff --git a/frontend/src/components/editor/__tests__/dynamic-favicon.test.tsx b/frontend/src/components/editor/__tests__/dynamic-favicon.test.tsxnew file mode 100644index 0000000000..5e95a0c34c--- /dev/null+++ b/frontend/src/components/editor/__tests__/dynamic-favicon.test.tsx@@ -0,0 +1,129 @@+/* Copyright 2024 Marimo. All rights reserved. */+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { render } from "@testing-library/react";+import { DynamicFavicon } from "../dynamic-favicon";+import { useCellErrors } from "@/core/cells/cells";++// Mock useCellErrors hook+vi.mock("@/core/cells/cells", () => ({+ useCellErrors: vi.fn(),+}));++describe("DynamicFavicon", () => {+ let favicon: HTMLLinkElement;+ let mockFetch: ReturnType<typeof vi.fn>;+ let mockCreateObjectURL: ReturnType<typeof vi.fn>;+ let mockRevokeObjectURL: ReturnType<typeof vi.fn>;++ beforeEach(() => {+ // Mock favicon element+ favicon = document.createElement("link");+ favicon.rel = "icon";+ favicon.href = "./favicon.ico";+ document.head.append(favicon);++ // Mock fetch+ mockFetch = vi.fn().mockResolvedValue({+ blob: () => new Blob(),+ });+ global.fetch = mockFetch;++ // Mock URL methods+ mockCreateObjectURL = vi.fn().mockReturnValue("blob:mock-url");+ mockRevokeObjectURL = vi.fn();+ global.URL.createObjectURL = mockCreateObjectURL;+ global.URL.revokeObjectURL = mockRevokeObjectURL;++ // Mock document.hasFocus+ vi.spyOn(document, "hasFocus").mockReturnValue(true);++ // Mock useCellErrors to return no errors by default+ (useCellErrors as ReturnType<typeof vi.fn>).mockReturnValue([]);+ });++ afterEach(() => {+ favicon.remove();+ vi.clearAllMocks();+ vi.useRealTimers();+ });++ it("should update favicon when running state changes", async () => {+ render(<DynamicFavicon isRunning={true} />);++ expect(mockFetch).toHaveBeenCalledWith("./circle-play.ico");+ });++ it("should not reset favicon when not in focus", async () => {+ vi.spyOn(document, "hasFocus").mockReturnValue(false);+ vi.useFakeTimers();+ render(<DynamicFavicon isRunning={false} />);+ vi.clearAllMocks();++ await vi.advanceTimersByTimeAsync(3000);++ expect(mockFetch).not.toHaveBeenCalledWith("./favicon.ico");+ });++ it("should create favicon link if none exists", () => {+ favicon.remove();+ render(<DynamicFavicon isRunning={true} />);++ const newFavicon = document.querySelector("link[rel~='icon']");+ expect(newFavicon).not.toBeNull();+ });++ it("should cleanup object URLs on unmount", () => {+ const { unmount } = render(<DynamicFavicon isRunning={true} />);+ unmount();++ expect(mockRevokeObjectURL).toHaveBeenCalled();+ });++ describe("notifications", () => {+ beforeEach(() => {+ vi.spyOn(document, "visibilityState", "get").mockReturnValue("hidden");+ // @ts-expect-error ok in tests+ global.Notification = vi.fn();+ // @ts-expect-error ok in tests+ global.Notification.permission = "granted";+ });++ it("should send success notification when run completes without errors", () => {+ // @ts-expect-error ok in tests+ global.Notification = vi.fn().mockImplementation((title, options) => {+ expect(title).toBe("Execution completed");+ expect(options).toEqual({+ body: "Your notebook run completed successfully.",+ icon: expect.any(String),+ });+ });+ // @ts-expect-error ok in tests+ global.Notification.permission = "granted";++ const { rerender } = render(<DynamicFavicon isRunning={true} />);+ rerender(<DynamicFavicon isRunning={false} />);+ });++ it("should not send notification when document is visible", () => {+ vi.spyOn(document, "visibilityState", "get").mockReturnValue("visible");+ const { rerender } = render(<DynamicFavicon isRunning={true} />);+ rerender(<DynamicFavicon isRunning={false} />);++ expect(Notification).not.toHaveBeenCalled();+ });++ it("should request permission if not granted", () => {+ // @ts-expect-error ok in tests+ global.Notification.permission = "default";+ global.Notification.requestPermission = vi+ .fn()+ .mockResolvedValue("granted");++ const { rerender } = render(<DynamicFavicon isRunning={true} />);+ rerender(<DynamicFavicon isRunning={false} />);++ // eslint-disable-next-line @typescript-eslint/unbound-method+ expect(Notification.requestPermission).toHaveBeenCalled();+ });+ });+});diff --git a/frontend/src/components/editor/dynamic-favicon.tsx b/frontend/src/components/editor/dynamic-favicon.tsxindex 9bcdfcfea3..b721586610 100644--- a/frontend/src/components/editor/dynamic-favicon.tsx+++ b/frontend/src/components/editor/dynamic-favicon.tsx@@ -4,12 +4,29 @@ import { useEventListener } from "@/hooks/useEventListener";import { usePrevious } from "@dnd-kit/utilities";import { useEffect } from "react";-const FAVICONS = {+const FAVICON_PATHS = {idle: "./favicon.ico",success: "./circle-check.ico",running: "./circle-play.ico",error: "./circle-x.ico",-};+} as const;++// Cache favicon object URLs lazily+type FaviconKey = keyof typeof FAVICON_PATHS;+const cache = new Map<FaviconKey, string>();++async function getFaviconUrl(key: FaviconKey): Promise<string> {+ const cached = cache.get(key);+ if (cached) {+ return cached;+ }++ const response = await fetch(FAVICON_PATHS[key]);+ const blob = await response.blob();+ const url = URL.createObjectURL(blob);+ cache.set(key, url);+ return url;+}interface Props {isRunning: boolean;@@ -20,16 +37,16 @@ function maybeSendNotification(numErrors: number) {return;}- const sendNotification = () => {+ const sendNotification = async () => {if (numErrors === 0) {new Notification("Execution completed", {body: "Your notebook run completed successfully.",- icon: FAVICONS.success,+ icon: await getFaviconUrl("success"),});} else {new Notification("Execution failed", {body: `Your notebook run encountered ${numErrors} error(s).`,- icon: FAVICONS.error,+ icon: await getFaviconUrl("error"),});}};@@ -62,32 +79,45 @@ export const DynamicFavicon = (props: Props) => {document.getElementsByTagName("head")[0].append(favicon);}+ useEffect(() => {+ // Cleanup on unmount+ return () => {+ cache.forEach((url) => URL.revokeObjectURL(url));+ };+ }, []);+useEffect(() => {// No change on startup (autorun enabled or not)// Treat the default marimo favicon as "idle"if (!isRunning && favicon.href.includes("favicon")) {return;}- // When notebook is running, display running favicon- if (isRunning) {- favicon.href = FAVICONS.running;- return;- }- // When run is complete, display success or error favicon- favicon.href = errors.length === 0 ? FAVICONS.success : FAVICONS.error;- // If notebook is in focus, reset favicon after 3 seconds- // If not in focus, the focus event listener handles it- if (!document.hasFocus()) {- return;- }- const timeoutId = setTimeout(() => {- favicon.href = FAVICONS.idle;- }, 3000);- return () => {- favicon.href = FAVICONS.idle;- clearTimeout(timeoutId);+ const updateFavicon = async () => {+ let key: FaviconKey;+ // When notebook is running, display running favicon+ if (isRunning) {+ key = "running";+ } else {+ // When run is complete, display success or error favicon+ key = errors.length === 0 ? "success" : "error";+ }+ favicon.href = await getFaviconUrl(key);++ // If notebook is in focus, reset favicon after 3 seconds+ // If not in focus, the focus event listener handles it+ if (!document.hasFocus()) {+ return;+ }++ const timeoutId = setTimeout(async () => {+ favicon.href = await getFaviconUrl("idle");+ }, 3000);++ return () => clearTimeout(timeoutId);};++ updateFavicon();}, [isRunning, errors, favicon]);// Send user notification when run has completed@@ -99,9 +129,9 @@ export const DynamicFavicon = (props: Props) => {}, [errors, prevRunning, isRunning]);// When notebook comes back in focus, reset favicon- useEventListener(window, "focus", (_) => {+ useEventListener(window, "focus", async (_) => {if (!isRunning) {- favicon.href = FAVICONS.idle;+ favicon.href = await getFaviconUrl("idle");}});