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: autofocus generate with AI (#5592)
Myles Scolnicke4daa1692777
diff --git a/frontend/src/components/editor/ai/add-cell-with-ai.tsx b/frontend/src/components/editor/ai/add-cell-with-ai.tsxindex fdb3e9fcfa..53406a8101 100644--- a/frontend/src/components/editor/ai/add-cell-with-ai.tsx+++ b/frontend/src/components/editor/ai/add-cell-with-ai.tsx@@ -354,7 +354,6 @@ export const PromptInput = ({<ReactCodeMirrorref={inputRef}className={cn("flex-1 font-sans overflow-auto my-1", className)}- autoFocus={true}width="100%"maxHeight={maxHeight}value={value}diff --git a/frontend/src/components/editor/ai/ai-completion-editor.tsx b/frontend/src/components/editor/ai/ai-completion-editor.tsxindex 5cf7cf408f..541cf0b248 100644--- a/frontend/src/components/editor/ai/ai-completion-editor.tsx+++ b/frontend/src/components/editor/ai/ai-completion-editor.tsx@@ -23,6 +23,7 @@ import { useRuntimeManager } from "@/core/runtime/config";import { useTheme } from "@/theme/useTheme";import { cn } from "@/utils/cn";import { prettyError } from "@/utils/errors";+import { retryWithTimeout } from "@/utils/timeout";import { PromptInput } from "./add-cell-with-ai";import { getAICompletionBody } from "./completion-utils";@@ -107,11 +108,19 @@ export const AiCompletionEditor: React.FC<Props> = ({// Focus the inputuseEffect(() => {- const input = inputRef.current;- if (enabled && input) {- requestAnimationFrame(() => {- input.view?.focus();- });+ if (enabled) {+ retryWithTimeout(+ () => {+ const input = inputRef.current;+ if (input?.view) {+ input.view.focus();+ return true;+ }+ return false;+ },+ { retries: 3, delay: 100, initialDelay: 100 },+ ); // Wait for animation to complete+selectAllText(inputRef.current?.view);}}, [enabled]);diff --git a/frontend/src/utils/__tests__/timeout.test.ts b/frontend/src/utils/__tests__/timeout.test.tsnew file mode 100644index 0000000000..d193bc5200--- /dev/null+++ b/frontend/src/utils/__tests__/timeout.test.ts@@ -0,0 +1,153 @@+/* Copyright 2024 Marimo. All rights reserved. */+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { retryWithTimeout } from "../timeout";++describe("retryWithTimeout", () => {+ beforeEach(() => {+ vi.useFakeTimers();+ });++ afterEach(() => {+ vi.useRealTimers();+ vi.clearAllMocks();+ });++ it("should be called immediately when function returns true on first call and no initial delay", async () => {+ const mockFn = vi.fn().mockReturnValue(true);+ retryWithTimeout(mockFn, { retries: 3, delay: 1000 });+ expect(mockFn).toHaveBeenCalledTimes(1);++ // Should not call again after success+ await vi.advanceTimersByTimeAsync(1000);+ expect(mockFn).toHaveBeenCalledTimes(1);+ });++ it("should be called with initial delay", async () => {+ const mockFn = vi.fn().mockReturnValue(true);+ retryWithTimeout(mockFn, { retries: 3, delay: 1000, initialDelay: 1000 });++ // Function should not be called immediately+ expect(mockFn).toHaveBeenCalledTimes(0);++ // After first delay, function should be called and succeed+ await vi.advanceTimersByTimeAsync(1000);+ expect(mockFn).toHaveBeenCalledTimes(1);++ // Should not call again after success+ await vi.advanceTimersByTimeAsync(1000);+ expect(mockFn).toHaveBeenCalledTimes(1);+ });++ it("should retry when function returns false initially", async () => {+ const mockFn = vi+ .fn()+ .mockReturnValueOnce(false)+ .mockReturnValueOnce(false)+ .mockReturnValueOnce(true);++ retryWithTimeout(mockFn, {+ retries: 3,+ delay: 1000,+ initialDelay: 1000,+ });++ // Function should not be called immediately+ expect(mockFn).toHaveBeenCalledTimes(0);++ // After first delay+ await vi.advanceTimersByTimeAsync(1000);+ expect(mockFn).toHaveBeenCalledTimes(1);++ // After second delay+ await vi.advanceTimersByTimeAsync(1000);+ expect(mockFn).toHaveBeenCalledTimes(2);++ // After third delay - should succeed and stop+ await vi.advanceTimersByTimeAsync(1000);+ expect(mockFn).toHaveBeenCalledTimes(3);++ // Should not call again after success+ await vi.advanceTimersByTimeAsync(1000);+ expect(mockFn).toHaveBeenCalledTimes(3);+ });++ it("should stop retrying after max retries reached", async () => {+ const mockFn = vi.fn().mockReturnValue(false);++ retryWithTimeout(mockFn, {+ retries: 2,+ delay: 1000,+ initialDelay: 1000,+ });++ // Function should not be called immediately+ expect(mockFn).toHaveBeenCalledTimes(0);++ // After first delay+ await vi.advanceTimersByTimeAsync(1000);+ expect(mockFn).toHaveBeenCalledTimes(1);++ // After second delay+ await vi.advanceTimersByTimeAsync(1000);+ expect(mockFn).toHaveBeenCalledTimes(2);++ // Should not call again after max retries+ await vi.advanceTimersByTimeAsync(1000);+ expect(mockFn).toHaveBeenCalledTimes(2);+ });++ it("should handle zero retries", async () => {+ const mockFn = vi.fn().mockReturnValue(false);++ retryWithTimeout(mockFn, { retries: 0, delay: 1000 });++ // Function should not be called immediately+ expect(mockFn).toHaveBeenCalledTimes(0);++ // Should not call again+ await vi.advanceTimersByTimeAsync(1000);+ expect(mockFn).toHaveBeenCalledTimes(0);+ });++ it("should handle zero delay", async () => {+ const mockFn = vi.fn().mockReturnValueOnce(false).mockReturnValueOnce(true);++ retryWithTimeout(mockFn, { retries: 3, delay: 0 });++ // Called immediately+ expect(mockFn).toHaveBeenCalledTimes(1);++ // After zero delay - should call and succeed+ await vi.advanceTimersByTimeAsync(0);+ expect(mockFn).toHaveBeenCalledTimes(2);++ // Should not call again after success+ await vi.advanceTimersByTimeAsync(0);+ expect(mockFn).toHaveBeenCalledTimes(2);+ });++ it("should handle function that throws an error", async () => {+ const mockFn = vi+ .fn()+ .mockImplementationOnce(() => {+ throw new Error("Test error");+ })+ .mockReturnValueOnce(true);++ // Should not throw - the function handles errors gracefully+ expect(() => {+ retryWithTimeout(mockFn, { retries: 3, delay: 1000 });+ }).not.toThrow();++ // Function should be called but does not throw an error+ expect(mockFn).toHaveBeenCalledTimes(1);++ // After first delay - should call and succeed+ await vi.advanceTimersByTimeAsync(1000);+ expect(mockFn).toHaveBeenCalledTimes(2);++ // Should not call again after success+ await vi.advanceTimersByTimeAsync(1000);+ expect(mockFn).toHaveBeenCalledTimes(2);+ });+});diff --git a/frontend/src/utils/timeout.ts b/frontend/src/utils/timeout.tsnew file mode 100644index 0000000000..41172e894b--- /dev/null+++ b/frontend/src/utils/timeout.ts@@ -0,0 +1,42 @@+/* Copyright 2024 Marimo. All rights reserved. */++import { Logger } from "./Logger";++/**+ * Retry a function with a timeout.+ * @param fn - The function to retry.+ * @param opts.retries - The number of times to retry.+ * @param opts.delay - The delay between retries.+ * @param opts.initialDelay - The initial delay before the first retry.+ */+export function retryWithTimeout(+ fn: () => boolean,+ opts: { retries: number; delay: number; initialDelay?: number },+) {+ const { retries, delay, initialDelay = 0 } = opts;++ let attempts = 0;+ const retry = () => {+ if (attempts < retries) {+ try {+ if (fn()) {+ return;+ }+ } catch (error) {+ Logger.error(+ `Error executing function on attempt ${attempts + 1}, retrying`,+ { error },+ );+ }++ attempts++;+ setTimeout(retry, delay);+ }+ };++ if (initialDelay > 0) {+ setTimeout(retry, initialDelay);+ } else {+ retry();+ }+}