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.

improvement: parse urls and install commands from console outputs (#7479)

Myles Scolnick7a391fefde41
diff --git a/frontend/src/components/data-table/__tests__/columns.test.tsx b/frontend/src/components/data-table/__tests__/columns.test.tsx
index c4b2158cd9..70b44d8fcf 100644
--- a/frontend/src/components/data-table/__tests__/columns.test.tsx
+++ b/frontend/src/components/data-table/__tests__/columns.test.tsx
@@ -5,6 +5,7 @@ import { render } from "@testing-library/react";
import { I18nProvider } from "react-aria";
import { describe, expect, it, test } from "vitest";
import { TooltipProvider } from "@/components/ui/tooltip";
+import { parseContent } from "@/utils/url-parser";
import {
generateColumns,
inferFieldTypes,
@@ -14,7 +15,7 @@ import {
import { getMimeValues, isMimeValue, MimeCell } from "../mime-cell";
import type { FieldTypesWithExternalType } from "../types";
import { uniformSample } from "../uniformSample";
-import { parseContent, UrlDetector } from "../url-detector";
+import { UrlDetector } from "../url-detector";
test("uniformSample", () => {
const items = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"];
diff --git a/frontend/src/components/data-table/__tests__/header-items.test.tsx b/frontend/src/components/data-table/__tests__/header-items.test.tsx
index 3f0db55f95..8e02ecaf17 100644
--- a/frontend/src/components/data-table/__tests__/header-items.test.tsx
+++ b/frontend/src/components/data-table/__tests__/header-items.test.tsx
@@ -5,13 +5,14 @@ import { describe, expect, it, vi } from "vitest";
describe("multi-column sorting logic", () => {
// Extract the core sorting logic to test in isolation
- const handleSort = (
- columnId: string,
- desc: boolean,
- sortingState: SortingState,
- setSorting: (state: SortingState) => void,
- clearSorting: () => void,
- ) => {
+ const handleSort = (options: {
+ columnId: string;
+ desc: boolean;
+ sortingState: SortingState;
+ setSorting: (state: SortingState) => void;
+ clearSorting: () => void;
+ }) => {
+ const { columnId, desc, sortingState, setSorting, clearSorting } = options;
const currentSort = sortingState.find((s) => s.id === columnId);
if (currentSort && currentSort.desc === desc) {
@@ -34,7 +35,13 @@ describe("multi-column sorting logic", () => {
const clearSorting = vi.fn();
// Click Desc on age - should move age to end with desc=true
- handleSort("age", true, sortingState, setSorting, clearSorting);
+ handleSort({
+ columnId: "age",
+ desc: true,
+ sortingState,
+ setSorting,
+ clearSorting,
+ });
expect(setSorting).toHaveBeenCalledWith([
{ id: "name", desc: false },
@@ -49,7 +56,13 @@ describe("multi-column sorting logic", () => {
const clearSorting = vi.fn();
// Click Asc on age again - should remove the sort
- handleSort("age", false, sortingState, setSorting, clearSorting);
+ handleSort({
+ columnId: "age",
+ desc: false,
+ sortingState,
+ setSorting,
+ clearSorting,
+ });
expect(clearSorting).toHaveBeenCalled();
expect(setSorting).not.toHaveBeenCalled();
@@ -61,7 +74,13 @@ describe("multi-column sorting logic", () => {
const clearSorting = vi.fn();
// Click Asc on age - should add age to end
- handleSort("age", false, sortingState, setSorting, clearSorting);
+ handleSort({
+ columnId: "age",
+ desc: false,
+ sortingState,
+ setSorting,
+ clearSorting,
+ });
expect(setSorting).toHaveBeenCalledWith([
{ id: "name", desc: false },
@@ -76,7 +95,13 @@ describe("multi-column sorting logic", () => {
const clearSorting = vi.fn();
// Click Desc on age - should toggle to descending
- handleSort("age", true, sortingState, setSorting, clearSorting);
+ handleSort({
+ columnId: "age",
+ desc: true,
+ sortingState,
+ setSorting,
+ clearSorting,
+ });
expect(setSorting).toHaveBeenCalledWith([{ id: "age", desc: true }]);
expect(clearSorting).not.toHaveBeenCalled();
@@ -109,7 +134,13 @@ describe("multi-column sorting logic", () => {
const clearSorting = vi.fn();
// Click Desc on age again - should remove it
- handleSort("age", true, sortingState, setSorting, clearSorting);
+ handleSort({
+ columnId: "age",
+ desc: true,
+ sortingState,
+ setSorting,
+ clearSorting,
+ });
expect(clearSorting).toHaveBeenCalled();
// After removal, dept should move from priority 3 to priority 2
diff --git a/frontend/src/components/data-table/__tests__/url-detector.test.tsx b/frontend/src/components/data-table/__tests__/url-detector.test.tsx
index 3105bcebe5..ac036faf40 100644
--- a/frontend/src/components/data-table/__tests__/url-detector.test.tsx
+++ b/frontend/src/components/data-table/__tests__/url-detector.test.tsx
@@ -1,65 +1,8 @@
/* Copyright 2024 Marimo. All rights reserved. */
import { fireEvent, render, screen } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
-import { isMarkdown, parseContent, UrlDetector } from "../url-detector";
-
-describe("parseContent", () => {
- it("handles data URIs", () => {
- const parts = parseContent("data:image/png;base64,iVBOR");
- expect(parts).toEqual([
- {
- type: "image",
- url: "data:image/png;base64,iVBOR",
- },
- ]);
- });
-
- it("handles complete URLs", () => {
- const parts = parseContent("https://marimo.io/path?query=value");
- expect(parts).toEqual([
- { type: "url", url: "https://marimo.io/path?query=value" },
- ]);
- });
-
- it("handles multiple URLs with text", () => {
- const parts = parseContent(
- "Visit https://marimo.io and https://github.com/marimo-team",
- );
- expect(parts).toEqual([
- { type: "text", value: "Visit " },
- { type: "url", url: "https://marimo.io" },
- { type: "text", value: " and " },
- { type: "url", url: "https://github.com/marimo-team" },
- ]);
- });
-
- // Currently doesn't detect mixed content
- it.fails("handles text with data URIs", () => {
- const parts = parseContent("Image: data:image/png;base64,iVBOR");
- expect(parts).toEqual([
- {
- type: "text",
- value: "Image: ",
- },
- {
- type: "image",
- url: "data:image/png;base64,iVBOR",
- },
- ]);
- });
-
- it.fails("handles data URIs, text and images", () => {
- const parts = parseContent(
- "this is a picture: https://avatars.githubusercontent.com/u/123 and data:image/png;base64,iVBOR",
- );
- expect(parts).toEqual([
- { type: "text", value: "this is a picture: " },
- { type: "image", url: "https://avatars.githubusercontent.com/u/123" },
- { type: "text", value: " and " },
- { type: "image", url: "data:image/png;base64,iVBOR" },
- ]);
- });
-});
+import { parseContent } from "@/utils/url-parser";
+import { isMarkdown, UrlDetector } from "../url-detector";
describe("UrlDetector", () => {
it("renders plain text without URLs", () => {
diff --git a/frontend/src/components/data-table/columns.tsx b/frontend/src/components/data-table/columns.tsx
index 347f8f3f2f..e650d28033 100644
--- a/frontend/src/components/data-table/columns.tsx
+++ b/frontend/src/components/data-table/columns.tsx
@@ -14,6 +14,7 @@ import { Logger } from "@/utils/Logger";
import { Maps } from "@/utils/maps";
import { maxFractionalDigits } from "@/utils/numbers";
import { Objects } from "@/utils/objects";
+import { parseContent } from "@/utils/url-parser";
import { EmotionCacheProvider } from "../editor/output/EmotionCacheProvider";
import { JsonOutput } from "../editor/output/JsonOutput";
import { CopyClipboardIcon } from "../icons/copy-icon";
@@ -35,7 +36,7 @@ import {
INDEX_COLUMN_NAME,
} from "./types";
import { uniformSample } from "./uniformSample";
-import { MarkdownUrlDetector, parseContent, UrlDetector } from "./url-detector";
+import { MarkdownUrlDetector, UrlDetector } from "./url-detector";
// Artificial limit to display long strings
const MAX_STRING_LENGTH = 50;
diff --git a/frontend/src/components/data-table/url-detector.tsx b/frontend/src/components/data-table/url-detector.tsx
index 2d6f84b632..b19f1bea71 100644
--- a/frontend/src/components/data-table/url-detector.tsx
+++ b/frontend/src/components/data-table/url-detector.tsx
@@ -9,11 +9,7 @@ import {
PopoverTrigger,
} from "@/components/ui/popover";
import { Events } from "@/utils/events";
-
-const urlRegex = /(https?:\/\/\S+)/;
-const imageRegex = /\.(png|jpe?g|gif|webp|svg|ico)(\?.*)?$/i;
-const dataImageRegex = /^data:image\//i;
-const knownImageDomains = ["avatars.githubusercontent.com"];
+import type { ContentPart } from "@/utils/url-parser";
const ImageWithFallback = ({ url }: { url: string }) => {
const [error, setError] = useState(false);
@@ -56,34 +52,6 @@ const ImageWithFallback = ({ url }: { url: string }) => {
);
};
-export type ContentPart =
- | { type: "text"; value: string }
- | { type: "url"; url: string }
- | { type: "image"; url: string };
-
-export function parseContent(text: string): ContentPart[] {
- if (dataImageRegex.test(text)) {
- return [{ type: "image", url: text }];
- }
-
- const parts = text.split(urlRegex).filter((part) => part.trim() !== "");
- return parts.map((part) => {
- const isUrl = urlRegex.test(part);
- if (isUrl) {
- const isImage =
- imageRegex.test(part) ||
- dataImageRegex.test(part) ||
- knownImageDomains.some((domain) => part.includes(domain));
-
- if (isImage) {
- return { type: "image", url: part };
- }
- return { type: "url", url: part };
- }
- return { type: "text", value: part };
- });
-}
-
export function isMarkdown(text: string): boolean {
const tokens = marked.lexer(text);
diff --git a/frontend/src/components/editor/notebook-cell.tsx b/frontend/src/components/editor/notebook-cell.tsx
index da2a276787..95408fa8c2 100644
--- a/frontend/src/components/editor/notebook-cell.tsx
+++ b/frontend/src/components/editor/notebook-cell.tsx
@@ -87,7 +87,7 @@ import {
useTemporarilyShownCodeActions,
} from "./navigation/state";
import { type OnRefactorWithAI, OutputArea } from "./Output";
-import { ConsoleOutput } from "./output/ConsoleOutput";
+import { ConsoleOutput } from "./output/console/ConsoleOutput";
import { CellDragHandle, SortableCell } from "./SortableCell";
/**
diff --git a/frontend/src/components/editor/output/TextOutput.tsx b/frontend/src/components/editor/output/TextOutput.tsx
index 7111f69883..0a565c7707 100644
--- a/frontend/src/components/editor/output/TextOutput.tsx
+++ b/frontend/src/components/editor/output/TextOutput.tsx
@@ -1,11 +1,9 @@
/* Copyright 2024 Marimo. All rights reserved. */
-import { AnsiUp } from "ansi_up";
import type { JSX } from "react";
import type { OutputChannel } from "@/core/kernel/messages";
import { cn } from "@/utils/cn";
-
-const ansiUp = new AnsiUp();
+import { RenderTextWithLinks } from "./console/text-rendering";
interface Props {
text: string;
@@ -22,8 +20,9 @@ export const TextOutput = ({ text, channel, wrapText }: Props): JSX.Element => {
className={
wrapText ? "whitespace-pre-wrap break-words" : "whitespace-pre"
}
- dangerouslySetInnerHTML={{ __html: ansiUp.ansi_to_html(text) }}
- />
+ >
+ <RenderTextWithLinks text={text} />
+ </span>
);
};
diff --git a/frontend/src/components/editor/output/ConsoleOutput.tsx b/frontend/src/components/editor/output/console/ConsoleOutput.tsx
similarity index 89%
rename from frontend/src/components/editor/output/ConsoleOutput.tsx
rename to frontend/src/components/editor/output/console/ConsoleOutput.tsx
index 0ca0695226..2473b2edaf 100644
--- a/frontend/src/components/editor/output/ConsoleOutput.tsx
+++ b/frontend/src/components/editor/output/console/ConsoleOutput.tsx
@@ -1,6 +1,5 @@
/* Copyright 2024 Marimo. All rights reserved. */
-import { AnsiUp } from "ansi_up";
import { ChevronRightIcon, WrapTextIcon } from "lucide-react";
import React, { useLayoutEffect } from "react";
import { ToggleButton } from "react-aria-components";
@@ -14,15 +13,13 @@ import type { WithResponse } from "@/core/cells/types";
import type { OutputMessage } from "@/core/kernel/messages";
import { useSelectAllContent } from "@/hooks/useSelectAllContent";
import { cn } from "@/utils/cn";
-import { ansiToPlainText, parseHtmlContent } from "@/utils/dom";
import { invariant } from "@/utils/invariant";
-import { Strings } from "@/utils/strings";
-import { NameCellContentEditable } from "../actions/name-cell-input";
-import { ErrorBoundary } from "../boundary/ErrorBoundary";
-import { type OnRefactorWithAI, OutputRenderer } from "../Output";
-import { useWrapText } from "./useWrapText";
-
-const ansiUp = new AnsiUp();
+import { NameCellContentEditable } from "../../actions/name-cell-input";
+import { ErrorBoundary } from "../../boundary/ErrorBoundary";
+import { type OnRefactorWithAI, OutputRenderer } from "../../Output";
+import { useWrapText } from "../useWrapText";
+import { processOutput } from "./process-output";
+import { RenderTextWithLinks } from "./text-rendering";
interface Props {
cellId: CellId;
@@ -268,20 +265,5 @@ const renderText = (text: string | null) => {
return null;
}
- return (
- <span dangerouslySetInnerHTML={{ __html: ansiUp.ansi_to_html(text) }} />
- );
-};
-
-/** Convert cell or console output to a string, while handling html and ansi codes */
-export const processOutput = (output: OutputMessage): string => {
- if (
- output.mimetype.startsWith("application/vnd.marimo") ||
- output.mimetype === "text/html"
- ) {
- return parseHtmlContent(Strings.asString(output.data));
- }
-
- // Convert ANSI to HTML, then parse as HTML
- return ansiToPlainText(Strings.asString(output.data));
+ return <RenderTextWithLinks text={text} />;
};
diff --git a/frontend/src/components/editor/output/console/__tests__/ConsoleOutput.test.tsx b/frontend/src/components/editor/output/console/__tests__/ConsoleOutput.test.tsx
new file mode 100644
index 0000000000..69f3ea28db
--- /dev/null
+++ b/frontend/src/components/editor/output/console/__tests__/ConsoleOutput.test.tsx
@@ -0,0 +1,50 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+
+import { render, screen } from "@testing-library/react";
+import { describe, expect, it } from "vitest";
+import { TooltipProvider } from "@/components/ui/tooltip";
+import type { CellId } from "@/core/cells/ids";
+import type { OutputMessage } from "@/core/kernel/messages";
+import { ConsoleOutput } from "../ConsoleOutput";
+
+describe("ConsoleOutput integration", () => {
+ const createOutput = (data: string, channel = "stdout"): OutputMessage => ({
+ channel: channel as "stdout" | "stderr",
+ mimetype: "text/plain",
+ data,
+ timestamp: 0,
+ });
+
+ const defaultProps = {
+ cellId: "cell-1" as CellId,
+ cellName: "test_cell",
+ consoleOutputs: [],
+ stale: false,
+ debuggerActive: false,
+ onSubmitDebugger: () => {
+ // noop
+ },
+ };
+
+ it("should render console output with clickable URLs", () => {
+ const props = {
+ ...defaultProps,
+ consoleOutputs: [
+ {
+ ...createOutput("Check out https://marimo.io for more info"),
+ response: undefined,
+ },
+ ],
+ };
+
+ render(
+ <TooltipProvider>
+ <ConsoleOutput {...props} />
+ </TooltipProvider>,
+ );
+
+ const link = screen.getByRole("link", { name: "https://marimo.io" });
+ expect(link).toBeInTheDocument();
+ expect(link).toHaveAttribute("href", "https://marimo.io");
+ });
+});
diff --git a/frontend/src/components/editor/output/console/__tests__/text-rendering.test.tsx b/frontend/src/components/editor/output/console/__tests__/text-rendering.test.tsx
new file mode 100644
index 0000000000..8ca5cde571
--- /dev/null
+++ b/frontend/src/components/editor/output/console/__tests__/text-rendering.test.tsx
@@ -0,0 +1,272 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+
+import { render, screen } from "@testing-library/react";
+import { describe, expect, it, vi } from "vitest";
+import { cleanAnsiCodes, RenderTextWithLinks } from "../text-rendering";
+
+// Mock the useInstallPackages hook
+vi.mock("@/core/packages/useInstallPackage", () => ({
+ useInstallPackages: () => ({
+ handleInstallPackages: vi.fn(),
+ }),
+}));
+
+describe("RenderTextWithLinks", () => {
+ describe("URL detection", () => {
+ it("should render plain text without URLs", () => {
+ render(<RenderTextWithLinks text="Hello, world!" />);
+ expect(screen.getByText("Hello, world!")).toBeInTheDocument();
+ });
+
+ it("should make URLs clickable", () => {
+ render(
+ <RenderTextWithLinks text="Check out https://marimo.io for more info" />,
+ );
+ const link = screen.getByRole("link", { name: "https://marimo.io" });
+ expect(link).toBeInTheDocument();
+ expect(link).toHaveAttribute("href", "https://marimo.io");
+ expect(link).toHaveAttribute("target", "_blank");
+ expect(link).toHaveAttribute("rel", "noopener noreferrer");
+ });
+
+ it("should handle multiple URLs in one line", () => {
+ render(
+ <RenderTextWithLinks text="Visit https://marimo.io or https://github.com/marimo-team/marimo" />,
+ );
+ expect(
+ screen.getByRole("link", { name: "https://marimo.io" }),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByRole("link", {
+ name: "https://github.com/marimo-team/marimo",
+ }),
+ ).toBeInTheDocument();
+ });
+
+ it("should handle http URLs", () => {
+ render(<RenderTextWithLinks text="Link: http://example.com" />);
+ const link = screen.getByRole("link", { name: "http://example.com" });
+ expect(link).toBeInTheDocument();
+ });
+
+ it("should handle URLs with query parameters", () => {
+ render(
+ <RenderTextWithLinks text="Visit https://marimo.io/docs?page=1&section=intro" />,
+ );
+ const link = screen.getByRole("link", {
+ name: "https://marimo.io/docs?page=1&section=intro",
+ });
+ expect(link).toBeInTheDocument();
+ expect(link).toHaveAttribute(
+ "href",
+ "https://marimo.io/docs?page=1&section=intro",
+ );
+ });
+
+ it("should handle URLs at the start of text", () => {
+ render(<RenderTextWithLinks text="https://marimo.io is awesome" />);
+ expect(
+ screen.getByRole("link", { name: "https://marimo.io" }),
+ ).toBeInTheDocument();
+ expect(screen.getByText("is awesome")).toBeInTheDocument();
+ });
+
+ it("should handle URLs at the end of text", () => {
+ render(<RenderTextWithLinks text="Check out https://marimo.io" />);
+ expect(screen.getByText("Check out")).toBeInTheDocument();
+ expect(
+ screen.getByRole("link", { name: "https://marimo.io" }),
+ ).toBeInTheDocument();
+ });
+
+ it("should not break on text without protocols", () => {
+ render(<RenderTextWithLinks text="Visit marimo.io or github.com" />);
+ // These should be rendered as plain text, not links
+ expect(
+ screen.queryByRole("link", { name: "marimo.io" }),
+ ).not.toBeInTheDocument();
+ expect(
+ screen.getByText(/Visit marimo.io or github.com/),
+ ).toBeInTheDocument();
+ });
+ });
+
+ describe("XSS safety", () => {
+ it("should safely handle URLs with special characters", () => {
+ render(
+ <RenderTextWithLinks text="Visit https://example.com/<script>alert('xss')</script>" />,
+ );
+ // The URL should be rendered but script should not execute
+ expect(screen.getByText(/Visit/)).toBeInTheDocument();
+ // Should not have a script element in the DOM
+ const scripts = document.querySelectorAll("script");
+ const hasXSSScript = [...scripts].some((script) =>
+ script.textContent?.includes("alert('xss')"),
+ );
+ expect(hasXSSScript).toBe(false);
+ });
+
+ it("should handle javascript: protocol URLs safely", () => {
+ render(<RenderTextWithLinks text="Link: javascript:alert('xss')" />);
+ // javascript: protocol should not be detected as a valid URL
+ expect(
+ screen.queryByRole("link", { name: /javascript:/ }),
+ ).not.toBeInTheDocument();
+ });
+ });
+});
+
+describe("cleanAnsiCodes", () => {
+ it("should remove basic ANSI color codes", () => {
+ const text = "\u001B[31mRed text\u001B[0m";
+ const cleaned = cleanAnsiCodes(text);
+ expect(cleaned).toBe("Red text");
+ });
+
+ it("should remove multiple ANSI codes", () => {
+ const text =
+ "\u001B[31mRed\u001B[0m \u001B[32mGreen\u001B[0m \u001B[34mBlue\u001B[0m";
+ const cleaned = cleanAnsiCodes(text);
+ expect(cleaned).toBe("Red Green Blue");
+ });
+
+ it("should handle text without ANSI codes", () => {
+ const text = "Plain text";
+ const cleaned = cleanAnsiCodes(text);
+ expect(cleaned).toBe("Plain text");
+ });
+
+ it("should remove ANSI codes with multiple parameters", () => {
+ const text = "\u001B[1;31mBold Red\u001B[0m";
+ const cleaned = cleanAnsiCodes(text);
+ expect(cleaned).toBe("Bold Red");
+ });
+
+ it("should clean ANSI codes from URLs", () => {
+ const text = "https://marimo.io\u001B[0m";
+ const cleaned = cleanAnsiCodes(text);
+ expect(cleaned).toBe("https://marimo.io");
+ });
+
+ it("should handle empty string", () => {
+ const text = "";
+ const cleaned = cleanAnsiCodes(text);
+ expect(cleaned).toBe("");
+ });
+
+ it("should remove complex ANSI sequences", () => {
+ const text = "\u001B[38;5;208mOrange text\u001B[0m";
+ const cleaned = cleanAnsiCodes(text);
+ expect(cleaned).toBe("Orange text");
+ });
+
+ it("should handle text with only ANSI codes", () => {
+ const text = "\u001B[31m\u001B[0m";
+ const cleaned = cleanAnsiCodes(text);
+ expect(cleaned).toBe("");
+ });
+
+ it("should preserve special characters and whitespace", () => {
+ const text = "\u001B[31mSpecial: !@#$%^&*()\n\tTab and newline\u001B[0m";
+ const cleaned = cleanAnsiCodes(text);
+ expect(cleaned).toBe("Special: !@#$%^&*()\n\tTab and newline");
+ });
+});
+
+describe("RenderTextWithLinks - pip install detection", () => {
+ it("should render pip install command with install button", () => {
+ render(<RenderTextWithLinks text="pip install pandas" />);
+
+ expect(screen.getByText(/pip install pandas/)).toBeInTheDocument();
+ expect(screen.getByRole("button")).toBeInTheDocument();
+ });
+
+ it("should handle pip install with package extras", () => {
+ render(<RenderTextWithLinks text="pip install package[extra,dep]" />);
+
+ expect(
+ screen.getByText(/pip install package\[extra,dep]/),
+ ).toBeInTheDocument();
+ expect(screen.getByRole("button")).toBeInTheDocument();
+ });
+
+ it("should handle multiple packages", () => {
+ render(<RenderTextWithLinks text="pip install pandas numpy scipy" />);
+
+ expect(screen.getByText(/pip install pandas/)).toBeInTheDocument();
+ const button = screen.getByRole("button");
+ expect(button).toBeInTheDocument();
+ expect(button.textContent).toContain("pandas");
+ });
+
+ it("should handle pip install with surrounding text", () => {
+ render(
+ <RenderTextWithLinks text="Error: please run pip install pandas to fix this issue" />,
+ );
+
+ expect(screen.getByText(/Error: please run/)).toBeInTheDocument();
+ expect(screen.getByText(/pip install pandas/)).toBeInTheDocument();
+ expect(screen.getByText(/to fix this issue/)).toBeInTheDocument();
+ expect(screen.getByRole("button")).toBeInTheDocument();
+ });
+
+ it("should not render button for non-pip install text", () => {
+ render(<RenderTextWithLinks text="Install the package manually" />);
+
+ expect(screen.queryByRole("button")).not.toBeInTheDocument();
+ });
+ it("should handle pip install with ANSI codes", () => {
+ // ANSI codes create nested spans which makes the replacer logic complex
+ // For now, just verify it renders without crashing
+ const { container } = render(
+ <RenderTextWithLinks text="\u001B[31mError: pip install pandas\u001B[0m" />,
+ );
+ expect(container).toBeInTheDocument();
+ });
+
+ it("should handle pip install with hyphens in package name", () => {
+ render(<RenderTextWithLinks text="pip install scikit-learn" />);
+
+ expect(screen.getByRole("button")).toBeInTheDocument();
+ });
+
+ it("should handle pip install with dots in package name", () => {
+ render(<RenderTextWithLinks text="pip install types.boto3" />);
+
+ expect(screen.getByRole("button")).toBeInTheDocument();
+ });
+
+ it("should handle both pip install and URLs in the same text", () => {
+ render(
+ <RenderTextWithLinks text="Run pip install pandas and visit https://marimo.io for docs" />,
+ );
+
+ expect(screen.getByRole("button")).toBeInTheDocument();
+ expect(
+ screen.getByRole("link", { name: "https://marimo.io" }),
+ ).toBeInTheDocument();
+ });
+
+ it("should handle multiple separate pip install commands in the same text", () => {
+ render(
+ <RenderTextWithLinks text="You need to: pip install polars pandas to fix this." />,
+ );
+
+ // Should create button for the first package in the command
+ const buttons = screen.getAllByRole("button");
+ expect(buttons).toHaveLength(1);
+ expect(buttons[0].textContent).toContain("pip install polars");
+ });
+
+ it("should handle multiple distinct pip install commands", () => {
+ render(
+ <RenderTextWithLinks text="First run pip install polars. Then run pip install pandas." />,
+ );
+
+ // Should create separate buttons for each command
+ const buttons = screen.getAllByRole("button");
+ expect(buttons).toHaveLength(2);
+ expect(buttons[0].textContent).toContain("polars");
+ expect(buttons[1].textContent).toContain("pandas");
+ });
+});
diff --git a/frontend/src/components/editor/output/console/process-output.ts b/frontend/src/components/editor/output/console/process-output.ts
new file mode 100644
index 0000000000..1ad72c78ba
--- /dev/null
+++ b/frontend/src/components/editor/output/console/process-output.ts
@@ -0,0 +1,17 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import type { OutputMessage } from "@/core/kernel/messages";
+import { ansiToPlainText, parseHtmlContent } from "@/utils/dom";
+import { Strings } from "@/utils/strings";
+
+/** Convert cell or console output to a string, while handling html and ansi codes */
+export function processOutput(output: OutputMessage): string {
+ if (
+ output.mimetype.startsWith("application/vnd.marimo") ||
+ output.mimetype === "text/html"
+ ) {
+ return parseHtmlContent(Strings.asString(output.data));
+ }
+
+ // Convert ANSI to HTML, then parse as HTML
+ return ansiToPlainText(Strings.asString(output.data));
+}
diff --git a/frontend/src/components/editor/output/console/text-rendering.tsx b/frontend/src/components/editor/output/console/text-rendering.tsx
new file mode 100644
index 0000000000..79d909580d
--- /dev/null
+++ b/frontend/src/components/editor/output/console/text-rendering.tsx
@@ -0,0 +1,332 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+
+import { AnsiUp } from "ansi_up";
+import parse, { type DOMNode, Text } from "html-react-parser";
+import React, { useMemo } from "react";
+import { useInstallPackages } from "@/core/packages/useInstallPackage";
+import { Events } from "@/utils/events";
+import { parseContent } from "@/utils/url-parser";
+
+const ansiUp = new AnsiUp();
+
+/**
+ * Helper to clean ANSI escape codes from text
+ */
+export const cleanAnsiCodes = (text: string): string => {
+ // Remove ANSI escape sequences (ESC[ followed by numbers/semicolons and 'm')
+ // Using String.fromCharCode to avoid linter error
+ const ansiRegex = new RegExp(`${String.fromCharCode(27)}\\[[0-9;]*m`, "g");
+ return text.replaceAll(ansiRegex, "");
+};
+
+// Regex to match install commands: pip install, uv add, uv pip install
+const INSTALL_COMMAND_REGEX =
+ /(pip\s+install|uv\s+add|uv\s+pip\s+install)\s+/gi;
+
+/**
+ * Parse install command to extract a single package name
+ * Supports: pip install, uv add, uv pip install
+ * Handles flags like -U, --upgrade that can appear before or after the package name
+ */
+function parsePipInstallCommand(
+ text: string,
+): { package: string; endIndex: number } | null {
+ INSTALL_COMMAND_REGEX.lastIndex = 0;
+ const match = INSTALL_COMMAND_REGEX.exec(text);
+ if (!match) {
+ return null;
+ }
+
+ const commandEndIndex = match.index + match[0].length;
+ const afterCommand = text.slice(commandEndIndex);
+
+ // Skip any flags (tokens starting with -)
+ // Split by whitespace and find the first non-flag token
+ const tokens = afterCommand.split(/\s+/);
+ let packageName = "";
+ let packageStartOffset = 0;
+
+ for (const token_ of tokens) {
+ const token = token_.trim();
+ if (!token) {
+ continue;
+ }
+
+ // Skip flags (anything starting with -)
+ if (token.startsWith("-")) {
+ // Add to offset: token length + space
+ packageStartOffset += token.length + 1;
+ continue;
+ }
+
+ // Found the package name - extract it using character matching
+ // Match until we hit a character that's not valid in package names
+ const packageMatch = token.match(/^[\w,.[\]-]+/);
+ if (packageMatch) {
+ packageName = packageMatch[0];
+ break;
+ }
+
+ break;
+ }
+
+ if (!packageName) {
+ return null;
+ }
+
+ const endIndex = commandEndIndex + packageStartOffset + packageName.length;
+
+ return { package: packageName, endIndex };
+}
+
+/**
+ * Type for a replacer function that can transform DOM nodes during parsing
+ * Returns a React element, string, boolean, null, or undefined (to skip replacement)
+ */
+type Replacer = (
+ domNode: DOMNode,
+) => React.ReactElement | string | boolean | null | undefined;
+
+/**
+ * Helper function to process text content for URLs and images
+ * This is used by multiple replacers to avoid code duplication
+ */
+function processTextForUrls(text: string, keyPrefix = ""): React.ReactNode {
+ if (!text) {
+ return null;
+ }
+
+ // Quick check to avoid unnecessary parsing
+ if (!/https?:\/\//.test(text)) {
+ return text;
+ }
+
+ const parts = parseContent(text);
+
+ // If no URLs detected, return original text
+ if (parts.length === 1 && parts[0].type === "text") {
+ return text;
+ }
+
+ // Render parts with clickable links
+ return (
+ <>
+ {parts.map((part, idx) => {
+ const key = keyPrefix ? `${keyPrefix}-${idx}` : idx;
+ if (part.type === "url") {
+ const cleanUrl = cleanAnsiCodes(part.url);
+ return (
+ <a
+ key={key}
+ href={cleanUrl}
+ target="_blank"
+ rel="noopener noreferrer"
+ onClick={Events.stopPropagation()}
+ className="text-link hover:underline"
+ >
+ {cleanUrl}
+ </a>
+ );
+ }
+ if (part.type === "image") {
+ // For console output, just render images as links
+ const cleanUrl = cleanAnsiCodes(part.url);
+ return (
+ <a
+ key={key}
+ href={cleanUrl}
+ target="_blank"
+ rel="noopener noreferrer"
+ onClick={Events.stopPropagation()}
+ className="text-link hover:underline"
+ >
+ {cleanUrl}
+ </a>
+ );
+ }
+ return <React.Fragment key={key}>{part.value}</React.Fragment>;
+ })}
+ </>
+ );
+}
+
+const InstallPackageLink = ({
+ packages,
+ children,
+}: {
+ packages: string[];
+ children: React.ReactNode;
+}) => {
+ const { handleInstallPackages } = useInstallPackages();
+ return (
+ <button
+ onClick={(e) => {
+ handleInstallPackages(packages);
+ e.preventDefault();
+ }}
+ className="text-link hover:underline"
+ type="button"
+ >
+ {children}
+ </button>
+ );
+};
+
+/**
+ * Replacer that detects pip install commands and renders an install button
+ */
+export const pipInstallReplacer: Replacer = (domNode: DOMNode) => {
+ // Only process text nodes
+ if (!(domNode instanceof Text)) {
+ return undefined;
+ }
+
+ const textContent = cleanAnsiCodes(domNode.data);
+
+ // Quick check to avoid unnecessary regex
+ if (!/(pip\s+install|uv\s+add|uv\s+pip\s+install)/i.test(textContent)) {
+ return undefined;
+ }
+
+ // Find all matches in the text
+ const matches: {
+ match: RegExpExecArray;
+ result: { package: string; endIndex: number };
+ }[] = [];
+
+ // Create a new regex for iteration (don't reuse the global one)
+ const regex = /(pip\s+install|uv\s+add|uv\s+pip\s+install)\s+/gi;
+ let match: RegExpExecArray | null;
+
+ while ((match = regex.exec(textContent)) !== null) {
+ const startIndex = match.index;
+ const textFromMatch = textContent.slice(startIndex);
+ const result = parsePipInstallCommand(textFromMatch);
+
+ if (result) {
+ matches.push({ match, result });
+ }
+ }
+
+ // If no valid matches found, return undefined
+ if (matches.length === 0) {
+ return undefined;
+ }
+
+ // Build the result by splitting text into segments
+ const segments: React.ReactNode[] = [];
+ let lastIndex = 0;
+
+ matches.forEach((matchInfo, idx) => {
+ const { match, result } = matchInfo;
+ const startIndex = match.index;
+ const endIndex = startIndex + result.endIndex;
+
+ // Add text before this match (with URL processing)
+ if (lastIndex < startIndex) {
+ const beforeText = textContent.slice(lastIndex, startIndex);
+ segments.push(
+ <React.Fragment key={`before-${idx}`}>
+ {processTextForUrls(beforeText, `before-${idx}`)}
+ </React.Fragment>,
+ );
+ }
+
+ // Add the install button
+ const commandText = textContent.slice(startIndex, endIndex);
+ segments.push(
+ <InstallPackageLink key={`install-${idx}`} packages={[result.package]}>
+ {commandText}
+ </InstallPackageLink>,
+ );
+
+ lastIndex = endIndex;
+ });
+
+ // Add any remaining text after the last match
+ if (lastIndex < textContent.length) {
+ const afterText = textContent.slice(lastIndex);
+ segments.push(
+ <React.Fragment key="after">
+ {processTextForUrls(afterText, "after")}
+ </React.Fragment>,
+ );
+ }
+
+ return <>{segments}</>;
+};
+
+/**
+ * Replacer that detects URLs in text nodes and makes them clickable
+ */
+export const urlReplacer: Replacer = (domNode: DOMNode) => {
+ // Only process text nodes
+ if (!(domNode instanceof Text)) {
+ return undefined;
+ }
+
+ const textContent = domNode.data;
+
+ // Check if text contains URLs (fast check before parsing)
+ if (!/https?:\/\//.test(textContent)) {
+ return undefined;
+ }
+
+ // Use the shared helper to process URLs
+ const result = processTextForUrls(textContent);
+
+ // If no change was made (just plain text), return undefined to let other replacers try
+ if (typeof result === "string") {
+ return undefined;
+ }
+
+ return <>{result}</>;
+};
+
+/**
+ * Creates a composed replacer function from multiple replacers
+ * Replacers are applied in order, and the first one that returns a value wins
+ */
+export const composeReplacers = (...replacers: Replacer[]): Replacer => {
+ return (domNode: DOMNode) => {
+ for (const replacer of replacers) {
+ const result = replacer(domNode);
+ if (result !== undefined) {
+ return result;
+ }
+ }
+ return undefined;
+ };
+};
+
+/**
+ * Convert text to React element with ANSI colors and custom replacers applied
+ */
+export const renderTextWithReplacers = (
+ text: string,
+ replacer: Replacer,
+): React.ReactNode => {
+ const html = ansiUp.ansi_to_html(text);
+
+ const content = parse(html, {
+ replace: (domNode: DOMNode) => {
+ return replacer(domNode);
+ },
+ });
+
+ return <span>{content}</span>;
+};
+
+/**
+ * Convert text to React element with ANSI colors, clickable URLs, and pip install buttons
+ */
+export const RenderTextWithLinks = ({ text }: { text: string }) => {
+ const content = useMemo(() => {
+ return renderTextWithReplacers(
+ text,
+ composeReplacers(pipInstallReplacer, urlReplacer),
+ );
+ }, [text]);
+
+ return <>{content}</>;
+};
diff --git a/frontend/src/components/editor/renderers/vertical-layout/vertical-layout.tsx b/frontend/src/components/editor/renderers/vertical-layout/vertical-layout.tsx
index a27e083e67..4eb9bac25c 100644
--- a/frontend/src/components/editor/renderers/vertical-layout/vertical-layout.tsx
+++ b/frontend/src/components/editor/renderers/vertical-layout/vertical-layout.tsx
@@ -13,7 +13,7 @@ import { memo, useRef, useState } from "react";
import { z } from "zod";
import { ReadonlyCode } from "@/components/editor/code/readonly-python-code";
import { OutputArea } from "@/components/editor/Output";
-import { ConsoleOutput } from "@/components/editor/output/ConsoleOutput";
+import { ConsoleOutput } from "@/components/editor/output/console/ConsoleOutput";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import { Button } from "@/components/ui/button";
import {
diff --git a/frontend/src/components/scratchpad/scratchpad.tsx b/frontend/src/components/scratchpad/scratchpad.tsx
index b39a2803d2..5120a7e040 100644
--- a/frontend/src/components/scratchpad/scratchpad.tsx
+++ b/frontend/src/components/scratchpad/scratchpad.tsx
@@ -27,7 +27,7 @@ import { Functions } from "@/utils/functions";
import { CellEditor } from "../editor/cell/code/cell-editor";
import { HideInKioskMode } from "../editor/kiosk-mode";
import { OutputArea } from "../editor/Output";
-import { ConsoleOutput } from "../editor/output/ConsoleOutput";
+import { ConsoleOutput } from "../editor/output/console/ConsoleOutput";
import { Spinner } from "../icons/spinner";
import { renderShortcut } from "../shortcuts/renderShortcut";
import { Button } from "../ui/button";
diff --git a/frontend/src/core/ai/context/providers/cell-output.ts b/frontend/src/core/ai/context/providers/cell-output.ts
index 0ad858000e..c1d00f1ffc 100644
--- a/frontend/src/core/ai/context/providers/cell-output.ts
+++ b/frontend/src/core/ai/context/providers/cell-output.ts
@@ -3,7 +3,7 @@
import type { Completion } from "@codemirror/autocomplete";
import type { FileUIPart } from "ai";
import { toPng } from "html-to-image";
-import { processOutput } from "@/components/editor/output/ConsoleOutput";
+import { processOutput } from "@/components/editor/output/console/process-output";
import { type NotebookState, notebookAtom } from "@/core/cells/cells";
import { type CellId, CellOutputId } from "@/core/cells/ids";
import { displayCellName } from "@/core/cells/names";
diff --git a/frontend/src/core/codemirror/copilot/__tests__/language-server.test.ts b/frontend/src/core/codemirror/copilot/__tests__/language-server.test.ts
index 18e3c9cddb..9366b3dac7 100644
--- a/frontend/src/core/codemirror/copilot/__tests__/language-server.test.ts
+++ b/frontend/src/core/codemirror/copilot/__tests__/language-server.test.ts
@@ -1,18 +1,18 @@
/* Copyright 2024 Marimo. All rights reserved. */
+/* eslint-disable @typescript-eslint/no-explicit-any */
-import type { Transport } from "@open-rpc/client-js/build/transports/Transport";
+import { Transport } from "@open-rpc/client-js/build/transports/Transport";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { CopilotLanguageServerClient } from "../language-server";
// Mock transport
-class MockTransport implements Transport {
- connect = vi.fn().mockResolvedValue(undefined);
- close = vi.fn();
- sendData = vi.fn().mockResolvedValue({});
- subscribe = vi.fn();
- unsubscribe = vi.fn();
- transportRequestManager = {} as any;
- parseData = vi.fn();
+class MockTransport extends Transport {
+ override connect = vi.fn().mockResolvedValue(undefined);
+ override close = vi.fn();
+ override sendData = vi.fn().mockResolvedValue({});
+ override subscribe = vi.fn();
+ override unsubscribe = vi.fn();
+ override parseData = vi.fn();
}
describe("CopilotLanguageServerClient", () => {
diff --git a/frontend/src/core/codemirror/copilot/__tests__/transport.test.ts b/frontend/src/core/codemirror/copilot/__tests__/transport.test.ts
index 94b041a43d..583e0c06cf 100644
--- a/frontend/src/core/codemirror/copilot/__tests__/transport.test.ts
+++ b/frontend/src/core/codemirror/copilot/__tests__/transport.test.ts
@@ -155,7 +155,7 @@ describe("LazyWebsocketTransport", () => {
expect(mockShowError).toHaveBeenCalledTimes(1);
expect(mockShowError).toHaveBeenCalledWith(
"GitHub Copilot Connection Error",
- "Failed to connect to GitHub Copilot. Please check your settings and try again.",
+ "Failed to connect to GitHub Copilot. Please check your settings and try again.\n\nConnection failed",
);
expect((transport as any).delegate).toBeUndefined();
});
diff --git a/frontend/src/core/codemirror/copilot/language-server.ts b/frontend/src/core/codemirror/copilot/language-server.ts
index 38c9ce7e4e..265b882939 100644
--- a/frontend/src/core/codemirror/copilot/language-server.ts
+++ b/frontend/src/core/codemirror/copilot/language-server.ts
@@ -66,11 +66,11 @@ export type EnhancedNotification = {
export class CopilotLanguageServerClient extends LanguageServerClient {
private documentVersion = 0;
private hasOpenedDocument = false;
- private copilotSettings: Record<string, any> = {};
+ private copilotSettings: Record<string, unknown> = {};
constructor(
options: ConstructorParameters<typeof LanguageServerClient>[0] & {
- copilotSettings?: Record<string, any>;
+ copilotSettings?: Record<string, unknown>;
},
) {
super(options);
diff --git a/frontend/src/core/layout/useTogglePresenting.ts b/frontend/src/core/layout/useTogglePresenting.ts
index fba130962b..32985f932c 100644
--- a/frontend/src/core/layout/useTogglePresenting.ts
+++ b/frontend/src/core/layout/useTogglePresenting.ts
@@ -14,7 +14,7 @@ interface ScrollAnchor {
function findScrollAnchor(): ScrollAnchor | null {
const outputAreas = document.getElementsByClassName(CSSClasses.outputArea);
- for (const elem of Array.from(outputAreas)) {
+ for (const elem of outputAreas) {
const rect = elem.getBoundingClientRect();
// Find first visible output area
diff --git a/frontend/src/plugins/impl/anywidget/AnyWidgetPlugin.tsx b/frontend/src/plugins/impl/anywidget/AnyWidgetPlugin.tsx
index 9f8a970270..1e709cb3ab 100644
--- a/frontend/src/plugins/impl/anywidget/AnyWidgetPlugin.tsx
+++ b/frontend/src/plugins/impl/anywidget/AnyWidgetPlugin.tsx
@@ -37,6 +37,7 @@ interface Data {
type T = Record<string, unknown>;
+// eslint-disable-next-line @typescript-eslint/consistent-type-definitions
type PluginFunctions = {
send_to_widget: <T>(req: {
content: unknown;
diff --git a/frontend/src/utils/__tests__/data-views.test.ts b/frontend/src/utils/__tests__/data-views.test.ts
index 7d1ed24a39..0f567129e7 100644
--- a/frontend/src/utils/__tests__/data-views.test.ts
+++ b/frontend/src/utils/__tests__/data-views.test.ts
@@ -300,7 +300,7 @@ describe("dataViewToBase64", () => {
for (let i = 0; i < decoded.length; i++) {
decodedBytes[i] = decoded.charCodeAt(i);
}
- expect(Array.from(decodedBytes)).toEqual([0, 1, 2, 255, 254, 253]);
+ expect([...decodedBytes]).toEqual([0, 1, 2, 255, 254, 253]);
});
});
diff --git a/frontend/src/utils/__tests__/url-parser.test.ts b/frontend/src/utils/__tests__/url-parser.test.ts
new file mode 100644
index 0000000000..767b76a496
--- /dev/null
+++ b/frontend/src/utils/__tests__/url-parser.test.ts
@@ -0,0 +1,79 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import { describe, expect, it } from "vitest";
+import { parseContent } from "../url-parser";
+
+describe("parseContent", () => {
+ it("handles data URIs", () => {
+ const parts = parseContent("data:image/png;base64,iVBOR");
+ expect(parts).toEqual([
+ {
+ type: "image",
+ url: "data:image/png;base64,iVBOR",
+ },
+ ]);
+ });
+
+ it("handles complete URLs", () => {
+ const parts = parseContent("https://marimo.io/path?query=value");
+ expect(parts).toEqual([
+ { type: "url", url: "https://marimo.io/path?query=value" },
+ ]);
+ });
+
+ it("handles multiple URLs with text", () => {
+ const parts = parseContent(
+ "Visit https://marimo.io and https://github.com/marimo-team",
+ );
+ expect(parts).toEqual([
+ { type: "text", value: "Visit " },
+ { type: "url", url: "https://marimo.io" },
+ { type: "text", value: " and " },
+ { type: "url", url: "https://github.com/marimo-team" },
+ ]);
+ });
+
+ it("handles text with data URIs", () => {
+ // Currently doesn't detect mixed content
+ const parts = parseContent("Image: data:image/png;base64,iVBOR");
+ expect(parts).toEqual([
+ { type: "text", value: "Image: data:image/png;base64,iVBOR" },
+ ]);
+ });
+
+ it("handles data URIs, text and images", () => {
+ const parts = parseContent(
+ "this is a picture: https://avatars.githubusercontent.com/u/123 and data:image/png;base64,iVBOR",
+ );
+ expect(parts).toEqual([
+ { type: "text", value: "this is a picture: " },
+ { type: "image", url: "https://avatars.githubusercontent.com/u/123" },
+ { type: "text", value: " and data:image/png;base64,iVBOR" },
+ ]);
+ });
+
+ it("handles plain text without URLs", () => {
+ const parts = parseContent("Hello world");
+ expect(parts).toEqual([{ type: "text", value: "Hello world" }]);
+ });
+
+ it("handles image URLs with various extensions", () => {
+ const extensions = ["png", "jpg", "jpeg", "gif", "webp", "svg", "ico"];
+ extensions.forEach((ext) => {
+ const parts = parseContent(`Image: https://example.com/image.${ext}`);
+ expect(parts).toContainEqual({
+ type: "image",
+ url: `https://example.com/image.${ext}`,
+ });
+ });
+ });
+
+ it("handles known image domains", () => {
+ const parts = parseContent(
+ "Avatar: https://avatars.githubusercontent.com/u/123",
+ );
+ expect(parts).toContainEqual({
+ type: "image",
+ url: "https://avatars.githubusercontent.com/u/123",
+ });
+ });
+});
diff --git a/frontend/src/utils/data-views.ts b/frontend/src/utils/data-views.ts
index 6eaec3051c..2836fecf1c 100644
--- a/frontend/src/utils/data-views.ts
+++ b/frontend/src/utils/data-views.ts
@@ -37,8 +37,8 @@ function findDataViewPaths(
if (obj instanceof DataView) {
paths.push(currentPath);
} else if (Array.isArray(obj)) {
- for (let i = 0; i < obj.length; i++) {
- paths.push(...findDataViewPaths(obj[i], [...currentPath, i]));
+ for (const [i, element] of obj.entries()) {
+ paths.push(...findDataViewPaths(element, [...currentPath, i]));
}
} else if (obj !== null && typeof obj === "object") {
for (const [key, value] of Object.entries(obj)) {
diff --git a/frontend/src/utils/url-parser.ts b/frontend/src/utils/url-parser.ts
new file mode 100644
index 0000000000..62e559dab3
--- /dev/null
+++ b/frontend/src/utils/url-parser.ts
@@ -0,0 +1,38 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+
+const urlRegex = /(https?:\/\/\S+)/;
+const imageRegex = /\.(png|jpe?g|gif|webp|svg|ico)(\?.*)?$/i;
+const dataImageRegex = /^data:image\//i;
+const knownImageDomains = ["avatars.githubusercontent.com"];
+
+export type ContentPart =
+ | { type: "text"; value: string }
+ | { type: "url"; url: string }
+ | { type: "image"; url: string };
+
+/**
+ * Parse text content to detect URLs and images
+ * Returns an array of content parts that can be text, URL, or image
+ */
+export function parseContent(text: string): ContentPart[] {
+ if (dataImageRegex.test(text)) {
+ return [{ type: "image", url: text }];
+ }
+
+ const parts = text.split(urlRegex).filter((part) => part.trim() !== "");
+ return parts.map((part) => {
+ const isUrl = urlRegex.test(part);
+ if (isUrl) {
+ const isImage =
+ imageRegex.test(part) ||
+ dataImageRegex.test(part) ||
+ knownImageDomains.some((domain) => part.includes(domain));
+
+ if (isImage) {
+ return { type: "image", url: part };
+ }
+ return { type: "url", url: part };
+ }
+ return { type: "text", value: part };
+ });
+}
diff --git a/marimo/_smoke_tests/outputs/console_with_links.py b/marimo/_smoke_tests/outputs/console_with_links.py
new file mode 100644
index 0000000000..4e8ea01164
--- /dev/null
+++ b/marimo/_smoke_tests/outputs/console_with_links.py
@@ -0,0 +1,102 @@
+import marimo
+
+__generated_with = "0.18.4"
+app = marimo.App(width="medium")
+
+
+def _():
+ import altair as alt
+ import polars as pl
+ import vegafusion
+
+ # Enable VegaFusion data transformer
+ alt.data_transformers.enable("vegafusion")
+
+ _df = pl.DataFrame(
+ {"category": ["A", "B", "C", "D", "E"], "value": [28, 55, 43, 91, 81]}
+ )
+
+ _chart = (
+ alt.Chart(_df)
+ .mark_bar()
+ .encode(
+ x=alt.X("category", title="Category"),
+ y=alt.Y("value", title="Value"),
+ tooltip=["category", "value"],
+ )
+ .properties(title="Basic VegaFusion Example")
+ .interactive()
+ )
+ _chart
+ return
+
+
+def _():
+ import marimo as mo
+ return
+
+
+def _():
+ import sys
+ return (sys,)
+
+
+def _(sys):
+ sys.stdout.write("Here is a link in stdout: https://marimo.io\n")
+ return
+
+
+def _(sys):
+ sys.stderr.write(
+ "Here is a link in stderr: https://github.com/marimo-team/marimo\n"
+ )
+ return
+
+
+def _():
+ print("Here is a link in a print statement: https://docs.marimo.io")
+ return
+
+
+def _(sys):
+ sys.stdout.write(
+ "Here is a command in stdout: pip install pydantic[openai,google]\n"
+ )
+ sys.stderr.write("Here is a command in stderr: pip install pandas\n")
+ print("Here is a command in a print statement: pip install polars")
+ return
+
+
+def _():
+ print("You need to: pip install polars")
+ return
+
+
+def _():
+ print("Original functionality: pip install pandas")
+ print("Complex package: pip install package[extra,dep]")
+ print("Hyphenated package: pip install scikit-learn")
+
+ print("New uv support: uv add polars")
+ print("New uv pip support: uv pip install numpy")
+
+ print("Flags before package: pip install -U pandas")
+ print("Flags before package (uv): uv add -U polars")
+ print("Flags before package (uv pip): uv pip install --upgrade numpy")
+
+ print("Flags after package: uv add polars -U")
+ print("Flags after package: pip install pandas --upgrade")
+ return
+
+
+if __name__ == "__main__":
+ app.run()