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.

feat: previewable issue diagnostics in the feedback modal (#10251)

Kiran Gadhaved8fe44ba890e
diff --git a/.github/ISSUE_TEMPLATE/bug_report.yaml b/.github/ISSUE_TEMPLATE/bug_report.yaml
index f87356aa73..102d81f318 100644
--- a/.github/ISSUE_TEMPLATE/bug_report.yaml
+++ b/.github/ISSUE_TEMPLATE/bug_report.yaml
@@ -30,15 +30,10 @@ body:
id: env
attributes:
label: Environment
- description: Paste the output of `marimo env`
- value: |
- <details>
-
- ```
- Replace this line with the output of marimo env. Leave the backticks in place.
- ```
-
- </details>
+ description: |
+ In marimo, open **Send feedback → Report an issue** and click **Copy issue details**, then paste below. Otherwise, paste the output of `marimo env`.
+ placeholder: |
+ Paste the copied issue details here; they render as collapsible sections. If you ran `marimo env` instead, paste its output.
validations:
required: true
- type: textarea
diff --git a/frontend/src/__mocks__/requests.ts b/frontend/src/__mocks__/requests.ts
index eb2bea69da..8ab35ebc11 100644
--- a/frontend/src/__mocks__/requests.ts
+++ b/frontend/src/__mocks__/requests.ts
@@ -44,6 +44,9 @@ export const MockRequestClient = {
validateSQL: vi.fn().mockResolvedValue({}),
openFile: vi.fn().mockResolvedValue({}),
getUsageStats: vi.fn().mockResolvedValue({}),
+ getEnvironmentInfo: vi
+ .fn()
+ .mockRejectedValue(new Error("Environment information unavailable")),
sendPdb: vi.fn().mockResolvedValue({}),
sendSetBreakpoints: vi.fn().mockResolvedValue({}),
sendListFiles: vi.fn().mockResolvedValue({ files: [] }),
diff --git a/frontend/src/components/editor/actions/useNotebookActions.tsx b/frontend/src/components/editor/actions/useNotebookActions.tsx
index fd9b340fc0..a765fcd443 100644
--- a/frontend/src/components/editor/actions/useNotebookActions.tsx
+++ b/frontend/src/components/editor/actions/useNotebookActions.tsx
@@ -28,6 +28,7 @@ import {
KeyboardIcon,
LayoutTemplateIcon,
LinkIcon,
+ MessageCircleQuestionIcon,
MessagesSquareIcon,
NotebookIcon,
PanelLeftIcon,
@@ -44,6 +45,7 @@ import {
settingDialogAtom,
useOpenSettingsToTab,
} from "@/components/app-config/state";
+import { FeedbackModal } from "@/components/editor/chrome/components/feedback-button";
import { MarkdownIcon } from "@/components/editor/cell/code/icons";
import { GitHubIcon } from "@/components/icons/github";
import { MarimoPlusIcon } from "@/components/icons/marimo-icons";
@@ -642,6 +644,12 @@ export function useNotebookActions() {
redundant: true,
additionalKeywords: ["preferences", "options", "configuration"],
},
+ {
+ icon: <MessageCircleQuestionIcon size={14} strokeWidth={1.5} />,
+ label: "Report an issue",
+ additionalKeywords: ["feedback", "bug", "issue", "report", "diagnostics"],
+ handle: () => openModal(<FeedbackModal onClose={closeModal} />),
+ },
{
icon: <ExternalLinkIcon size={14} strokeWidth={1.5} />,
label: "Resources",
diff --git a/frontend/src/components/editor/chrome/components/__tests__/feedback-button.test.tsx b/frontend/src/components/editor/chrome/components/__tests__/feedback-button.test.tsx
new file mode 100644
index 0000000000..765a7dfcc3
--- /dev/null
+++ b/frontend/src/components/editor/chrome/components/__tests__/feedback-button.test.tsx
@@ -0,0 +1,221 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import { fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { Provider } from "jotai";
+import type React from "react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { MockRequestClient } from "@/__mocks__/requests";
+import { Dialog } from "@/components/ui/dialog";
+import { Constants } from "@/core/constants";
+import { TooltipProvider } from "@/components/ui/tooltip";
+import { viewStateAtom } from "@/core/mode";
+import { connectionAtom } from "@/core/network/connection";
+import { requestClientAtom } from "@/core/network/requests";
+import type { EnvironmentInfo } from "@/core/network/types";
+import { filenameAtom } from "@/core/saving/file-state";
+import { store } from "@/core/state/jotai";
+import { WebSocketState } from "@/core/websocket/types";
+import * as copyModule from "@/utils/copy";
+import { FeedbackModal } from "../feedback-button";
+
+vi.mock("@/utils/copy", () => ({
+ copyToClipboard: vi.fn().mockResolvedValue(undefined),
+}));
+
+const environment: EnvironmentInfo = {
+ marimo: "1.2.3",
+ editable: false,
+ location: "~/.venv/site-packages/marimo",
+ OS: "Darwin",
+ "OS Version": "25.0",
+ Processor: "arm",
+ "Python Version": "3.12.9",
+ Locale: "en_US",
+ Binaries: { Browser: "chrome 140", Node: "v22", uv: "0.11" },
+ Dependencies: { click: "8.4.2" },
+ "Optional Dependencies": { pandas: "3.0.0" },
+ "Experimental Flags": {},
+};
+
+function wrapper({ children }: { children: React.ReactNode }) {
+ return (
+ <Provider store={store}>
+ <TooltipProvider>
+ <Dialog open={true}>{children}</Dialog>
+ </TooltipProvider>
+ </Provider>
+ );
+}
+
+describe("FeedbackModal issue reporting", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ store.set(requestClientAtom, MockRequestClient.create());
+ store.set(viewStateAtom, { mode: "edit", cellAnchor: null });
+ store.set(connectionAtom, { state: WebSocketState.OPEN });
+ store.set(filenameAtom, "/project/example.py");
+ });
+
+ it("loads and previews issue environment details", async () => {
+ store.set(
+ requestClientAtom,
+ MockRequestClient.create({
+ getEnvironmentInfo: vi.fn().mockResolvedValue(environment),
+ }),
+ );
+ render(<FeedbackModal onClose={vi.fn()} />, { wrapper });
+
+ expect(screen.getByText("Loading environment details…")).toBeVisible();
+ await screen.findByText("Environment details");
+ expect(screen.getByText(/"marimo": "1.2.3"/)).toBeInTheDocument();
+ });
+
+ it("toggles the environment preview between show more and show less", async () => {
+ store.set(
+ requestClientAtom,
+ MockRequestClient.create({
+ getEnvironmentInfo: vi.fn().mockResolvedValue(environment),
+ }),
+ );
+ render(<FeedbackModal onClose={vi.fn()} />, { wrapper });
+ await screen.findByText("Environment details");
+
+ const toggle = screen.getByRole("button", { name: "Show more" });
+ fireEvent.click(toggle);
+ expect(
+ screen.getByRole("button", { name: "Show less" }),
+ ).toBeInTheDocument();
+ });
+
+ it("copies partial details when the environment request fails", async () => {
+ store.set(
+ requestClientAtom,
+ MockRequestClient.create({
+ getEnvironmentInfo: vi.fn().mockRejectedValue(new Error("offline")),
+ }),
+ );
+ render(<FeedbackModal onClose={vi.fn()} />, { wrapper });
+
+ await screen.findByText("Server environment information unavailable");
+ fireEvent.click(screen.getByRole("button", { name: "Copy issue details" }));
+ await waitFor(() =>
+ expect(copyModule.copyToClipboard).toHaveBeenCalledWith(
+ expect.stringContaining("Environment Collection Error"),
+ ),
+ );
+ });
+
+ it("copies raw environment JSON", async () => {
+ store.set(
+ requestClientAtom,
+ MockRequestClient.create({
+ getEnvironmentInfo: vi.fn().mockResolvedValue(environment),
+ }),
+ );
+ render(<FeedbackModal onClose={vi.fn()} />, { wrapper });
+ await screen.findByText("Environment details");
+
+ fireEvent.click(
+ screen.getByRole("button", { name: "Copy environment JSON" }),
+ );
+ await waitFor(() =>
+ expect(copyModule.copyToClipboard).toHaveBeenCalledWith(
+ expect.stringContaining('"marimo": "1.2.3"'),
+ ),
+ );
+ });
+
+ it("includes notebook source only after explicit opt-in", async () => {
+ const readCode = vi.fn().mockResolvedValue({
+ contents: "secret = 'review before posting'",
+ });
+ store.set(
+ requestClientAtom,
+ MockRequestClient.create({
+ getEnvironmentInfo: vi.fn().mockResolvedValue(environment),
+ readCode,
+ }),
+ );
+ render(<FeedbackModal onClose={vi.fn()} />, { wrapper });
+ await screen.findByText("Environment details");
+
+ expect(readCode).not.toHaveBeenCalled();
+ fireEvent.click(
+ screen.getByRole("checkbox", { name: "Include full notebook source" }),
+ );
+ await waitFor(() => expect(readCode).toHaveBeenCalledOnce());
+
+ fireEvent.click(screen.getByRole("button", { name: "Copy issue details" }));
+ await waitFor(() =>
+ expect(copyModule.copyToClipboard).toHaveBeenCalledWith(
+ expect.stringContaining("Notebook source: example.py"),
+ ),
+ );
+ });
+
+ it("discards notebook source after unchecking", async () => {
+ const readCode = vi.fn().mockResolvedValue({ contents: "x = 1" });
+ store.set(
+ requestClientAtom,
+ MockRequestClient.create({
+ getEnvironmentInfo: vi.fn().mockResolvedValue(environment),
+ readCode,
+ }),
+ );
+ render(<FeedbackModal onClose={vi.fn()} />, { wrapper });
+ await screen.findByText("Environment details");
+
+ const checkbox = screen.getByRole("checkbox", {
+ name: "Include full notebook source",
+ });
+ fireEvent.click(checkbox);
+ await waitFor(() => expect(readCode).toHaveBeenCalledOnce());
+ fireEvent.click(checkbox);
+
+ fireEvent.click(screen.getByRole("button", { name: "Copy issue details" }));
+ await waitFor(() =>
+ expect(copyModule.copyToClipboard).toHaveBeenCalledWith(
+ expect.not.stringContaining("Notebook source"),
+ ),
+ );
+ });
+
+ it("disables the notebook option and explains why when disconnected", async () => {
+ store.set(connectionAtom, { state: WebSocketState.CONNECTING });
+ store.set(
+ requestClientAtom,
+ MockRequestClient.create({
+ getEnvironmentInfo: vi.fn().mockResolvedValue(environment),
+ }),
+ );
+ render(<FeedbackModal onClose={vi.fn()} />, { wrapper });
+ await screen.findByText("Environment details");
+
+ expect(
+ screen.getByRole("checkbox", { name: "Include full notebook source" }),
+ ).toBeDisabled();
+ expect(
+ screen.getByText("Connect the notebook to include its source."),
+ ).toBeInTheDocument();
+ });
+
+ it("prefills the GitHub issue link with the environment once loaded", async () => {
+ store.set(
+ requestClientAtom,
+ MockRequestClient.create({
+ getEnvironmentInfo: vi.fn().mockResolvedValue(environment),
+ }),
+ );
+ render(<FeedbackModal onClose={vi.fn()} />, { wrapper });
+
+ const link = screen.getByRole("link", { name: "Open GitHub issue" });
+ expect(link).toHaveAttribute("href", Constants.bugReportUrl);
+
+ await screen.findByText("Environment details");
+ await waitFor(() => {
+ const href = link.getAttribute("href") ?? "";
+ expect(href).toContain("&env=");
+ expect(href).toContain(encodeURIComponent('"marimo": "1.2.3"'));
+ });
+ });
+});
diff --git a/frontend/src/components/editor/chrome/components/feedback-button.tsx b/frontend/src/components/editor/chrome/components/feedback-button.tsx
index 648275fc31..b6beb89796 100644
--- a/frontend/src/components/editor/chrome/components/feedback-button.tsx
+++ b/frontend/src/components/editor/chrome/components/feedback-button.tsx
@@ -4,16 +4,75 @@ import { Slot as SlotPrimitive } from "radix-ui";
const Slot = SlotPrimitive.Slot;
-import React, { type PropsWithChildren } from "react";
+import { useAtomValue } from "jotai";
+import { CheckIcon, ExternalLinkIcon, TriangleAlertIcon } from "lucide-react";
+import React, { type PropsWithChildren, useMemo, useState } from "react";
+import { CopyClipboardIcon } from "@/components/icons/copy-icon";
import { useImperativeModal } from "@/components/modal/ImperativeModal";
+import { Button } from "@/components/ui/button";
+import { Checkbox } from "@/components/ui/checkbox";
import {
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
+import { Skeleton } from "@/components/ui/skeleton";
import { toast } from "@/components/ui/use-toast";
+import { notebookAtom } from "@/core/cells/cells";
import { Constants } from "@/core/constants";
+import {
+ buildBugReportUrl,
+ buildIssueDetails,
+ createPartialEnvironment,
+ type EnvironmentDiagnostics,
+ enrichEnvironment,
+ type NotebookSource,
+} from "@/core/diagnostics/issue-details";
+import {
+ formatCellError,
+ getCellErrorEntries,
+} from "@/core/errors/error-entries";
+import { useNotebookCodeAvailable } from "@/core/meta/code-visibility";
+import { getMarimoVersion } from "@/core/meta/globals";
+import { connectionAtom } from "@/core/network/connection";
+import { useRequestClient } from "@/core/network/requests";
+import { filenameAtom } from "@/core/saving/file-state";
+import { store } from "@/core/state/jotai";
+import { WebSocketState } from "@/core/websocket/types";
+import { useAsyncData } from "@/hooks/useAsyncData";
+import { cn } from "@/utils/cn";
+import { copyToClipboard } from "@/utils/copy";
+
+const CollapsiblePreview: React.FC<{ content: string }> = ({ content }) => {
+ const [expanded, setExpanded] = useState(false);
+ return (
+ <div className="flex flex-col gap-1">
+ <div className="relative">
+ <pre
+ className={cn(
+ "text-xs bg-muted rounded p-2 overflow-x-auto whitespace-pre-wrap",
+ !expanded && "max-h-24 overflow-hidden",
+ )}
+ >
+ {content}
+ </pre>
+ {!expanded && (
+ <div className="pointer-events-none absolute inset-x-0 bottom-0 h-10 rounded-b bg-gradient-to-b from-transparent to-muted" />
+ )}
+ </div>
+ <Button
+ type="button"
+ variant="link"
+ size="xs"
+ className="self-start"
+ onClick={() => setExpanded((value) => !value)}
+ >
+ {expanded ? "Show less" : "Show more"}
+ </Button>
+ </div>
+ );
+};
export const FeedbackButton: React.FC<PropsWithChildren> = ({ children }) => {
const { openModal, closeModal } = useImperativeModal();
@@ -25,84 +84,256 @@ export const FeedbackButton: React.FC<PropsWithChildren> = ({ children }) => {
);
};
-const FeedbackModal: React.FC<{
+export const FeedbackModal: React.FC<{
onClose: () => void;
-}> = ({ onClose }) => {
+}> = () => {
+ const { getEnvironmentInfo, readCode } = useRequestClient();
+ const environmentRequest = useAsyncData(
+ async () => getEnvironmentInfo(),
+ [getEnvironmentInfo],
+ );
+
+ const notebook = useAtomValue(notebookAtom);
+ // biome-ignore lint/correctness/useExhaustiveDependencies: recompute when the notebook changes
+ const errors = useMemo(() => getCellErrorEntries(store), [notebook]);
+
+ const cells = notebook.cellIds.inOrderIds.map(
+ (cellId) => notebook.cellData[cellId],
+ );
+ const codeAvailable = useNotebookCodeAvailable(cells);
+ const filename = useAtomValue(filenameAtom);
+ const connection = useAtomValue(connectionAtom);
+ const notebookSourceAvailable =
+ filename !== null &&
+ codeAvailable &&
+ connection.state === WebSocketState.OPEN;
+
+ const [includeNotebook, setIncludeNotebook] = useState(false);
+
+ const notebookSourceReason = notebookSourceAvailable
+ ? undefined
+ : filename === null
+ ? "Save the notebook first."
+ : !codeAvailable
+ ? "Notebook source is hidden in this view."
+ : "Connect the notebook to include its source.";
+
+ const notebookSourceRequest = useAsyncData(async () => {
+ if (!includeNotebook || !notebookSourceAvailable || filename === null) {
+ return undefined;
+ }
+ const { contents } = await readCode();
+ return { filename, contents } satisfies NotebookSource;
+ }, [includeNotebook, notebookSourceAvailable, filename, readCode]);
+
+ const environment: EnvironmentDiagnostics | undefined =
+ environmentRequest.data
+ ? enrichEnvironment(environmentRequest.data, navigator.userAgent)
+ : environmentRequest.status === "error"
+ ? createPartialEnvironment(
+ getMarimoVersion(),
+ navigator.userAgent,
+ navigator.language,
+ "Server environment information unavailable",
+ )
+ : undefined;
+
+ const [issueDetailsCopied, setIssueDetailsCopied] = useState(false);
+
+ const githubIssueUrl = useMemo(() => {
+ if (!environment) {
+ return Constants.bugReportUrl;
+ }
+ return buildBugReportUrl(
+ Constants.bugReportUrl,
+ buildIssueDetails({ environment, errors }),
+ );
+ }, [environment, errors]);
+
+ const copyIssueDetails = async () => {
+ if (!environment) {
+ return;
+ }
+ const notebookForReport = includeNotebook
+ ? notebookSourceRequest.data
+ : undefined;
+ await copyToClipboard(
+ buildIssueDetails({ environment, errors, notebook: notebookForReport }),
+ );
+ setIssueDetailsCopied(true);
+ setTimeout(() => setIssueDetailsCopied(false), 2000);
+ toast({
+ title:
+ environmentRequest.status === "error"
+ ? "Partial issue details copied"
+ : "Issue details copied",
+ });
+ };
+
return (
- <DialogContent className="w-fit">
- <form
- onSubmit={async (e) => {
- e.preventDefault();
-
- const formData = new FormData(e.target as HTMLFormElement);
- const rating = formData.get("rating");
- const message = formData.get("message");
-
- // Fire-and-forget we don't care about the response
- void fetch("https://marimo.io/api/feedback", {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- },
- body: JSON.stringify({
- rating: rating,
- message,
- }),
- });
- onClose();
- toast({
- title: "Feedback sent!",
- description: "Thank you for your feedback!",
- });
- }}
- >
- <DialogHeader>
- <DialogTitle>Send Feedback</DialogTitle>
- <DialogDescription>
- <p className="my-2 prose dark:prose-invert">
- We want to hear from you — from minor bug reports to wishlist
- features and everything in between. Here are some ways you can get
- in touch:
- </p>
- <ul className="list-disc ml-8 my-2 prose dark:prose-invert">
- <li className="my-0">
- Take our{" "}
- <a
- href={Constants.feedbackForm}
- target="_blank"
- className="underline"
- >
- two-minute survey.
- </a>
- </li>
- <li className="my-0">
- File a{" "}
- <a
- href={Constants.issuesPage}
- target="_blank"
- className="underline"
- >
- GitHub issue.
- </a>
- </li>
- <li className="my-0">
- Chat with us on{" "}
- <a
- href={Constants.discordLink}
- target="_blank"
- className="underline"
- >
- Discord.
- </a>
- </li>
- </ul>
- <p className="my-2 prose dark:prose-invert">
- We're excited you're here as we build the future of Python data
- tooling. Thanks for being part of our community!
- </p>
- </DialogDescription>
- </DialogHeader>
- </form>
+ <DialogContent className="w-[540px] max-w-[90vw]">
+ <DialogHeader>
+ <DialogTitle>Report an issue</DialogTitle>
+ <DialogDescription>
+ Copy your environment and any current errors to include in a GitHub
+ bug report. Nothing is uploaded automatically; review the details
+ before posting.
+ </DialogDescription>
+ </DialogHeader>
+
+ <div className="flex flex-col gap-4 max-h-[60vh] overflow-y-auto">
+ <div className="flex flex-wrap gap-2">
+ <Button
+ type="button"
+ variant="default"
+ size="xs"
+ disabled={
+ !environment ||
+ (includeNotebook && notebookSourceRequest.isFetching)
+ }
+ onClick={copyIssueDetails}
+ >
+ {issueDetailsCopied && (
+ <CheckIcon
+ className="w-4 h-4 mr-2 text-(--grass-11)"
+ color="white"
+ />
+ )}
+ {issueDetailsCopied ? "Copied!" : "Copy issue details"}
+ </Button>
+ <Button type="button" variant="outline" size="xs" asChild={true}>
+ <a href={githubIssueUrl} target="_blank" rel="noreferrer">
+ <ExternalLinkIcon className="w-4 h-4 mr-2" />
+ Open GitHub issue
+ </a>
+ </Button>
+ </div>
+
+ {includeNotebook && (
+ <p className="text-xs text-muted-foreground">
+ The GitHub link prefills your environment only. Use Copy issue
+ details to include the full notebook source.
+ </p>
+ )}
+
+ {environmentRequest.status === "pending" && (
+ <div className="flex flex-col gap-2">
+ <span className="text-sm text-muted-foreground">
+ Loading environment details…
+ </span>
+ <Skeleton className="h-4 w-full" />
+ <Skeleton className="h-4 w-3/4" />
+ <Skeleton className="h-4 w-1/2" />
+ </div>
+ )}
+
+ {environmentRequest.status === "error" && (
+ <div className="flex items-center gap-2 text-sm">
+ <TriangleAlertIcon className="w-4 h-4 text-(--yellow-11) shrink-0" />
+ <span>Server environment information unavailable</span>
+ <Button
+ type="button"
+ variant="link"
+ size="xs"
+ onClick={() => environmentRequest.refetch()}
+ >
+ Retry
+ </Button>
+ </div>
+ )}
+
+ {environment && (
+ <div className="flex flex-col gap-1">
+ <div className="flex items-center justify-between">
+ <span className="text-sm font-medium">Environment details</span>
+ <CopyClipboardIcon
+ className="w-3.5 h-3.5"
+ value={JSON.stringify(environment, null, 2)}
+ ariaLabel="Copy environment JSON"
+ toastTitle="Environment details copied"
+ />
+ </div>
+ <CollapsiblePreview
+ content={JSON.stringify(environment, null, 2)}
+ />
+ </div>
+ )}
+
+ {environment && errors.length > 0 && (
+ <div className="flex flex-col gap-1">
+ <span className="text-sm font-medium">Current errors</span>
+ <CollapsiblePreview
+ content={errors.map(formatCellError).join("\n\n---\n\n")}
+ />
+ </div>
+ )}
+
+ {environment && errors.length === 0 && (
+ <span className="text-sm text-muted-foreground">
+ No current errors detected.
+ </span>
+ )}
+
+ <div className="flex flex-col gap-1">
+ <div className="flex items-start gap-2 text-sm">
+ <Checkbox
+ id="issue-include-notebook"
+ className="mt-0.5"
+ checked={includeNotebook}
+ disabled={!notebookSourceAvailable}
+ onCheckedChange={(checked) =>
+ setIncludeNotebook(checked === true)
+ }
+ aria-label="Include full notebook source"
+ />
+ <label htmlFor="issue-include-notebook">
+ Include full notebook source
+ </label>
+ </div>
+ <p className="text-xs text-muted-foreground ml-6">
+ Copies the entire saved Python source, including comments, literal
+ data, embedded credentials, and package metadata. Outputs and
+ external files are not included. Review it before posting.{" "}
+ <span className="font-bold">
+ For private notebooks, paste a minimal reproduction instead.
+ </span>
+ </p>
+ {notebookSourceReason && (
+ <span className="text-xs text-muted-foreground ml-6">
+ {notebookSourceReason}
+ </span>
+ )}
+ {includeNotebook && notebookSourceRequest.status === "error" && (
+ <span className="text-xs text-(--red-11) ml-6">
+ Notebook source could not be loaded.
+ </span>
+ )}
+ </div>
+
+ <div className="border-t pt-3">
+ <p className="text-sm text-muted-foreground">
+ Other feedback? Take our{" "}
+ <a
+ href={Constants.feedbackForm}
+ target="_blank"
+ rel="noreferrer"
+ className="underline"
+ >
+ two-minute survey
+ </a>{" "}
+ or chat with us on{" "}
+ <a
+ href={Constants.discordLink}
+ target="_blank"
+ rel="noreferrer"
+ className="underline"
+ >
+ Discord
+ </a>
+ .
+ </p>
+ </div>
+ </div>
</DialogContent>
);
};
diff --git a/frontend/src/core/ai/context/providers/error.ts b/frontend/src/core/ai/context/providers/error.ts
index 599139bef1..fba69aa186 100644
--- a/frontend/src/core/ai/context/providers/error.ts
+++ b/frontend/src/core/ai/context/providers/error.ts
@@ -1,13 +1,13 @@
/* Copyright 2026 Marimo. All rights reserved. */
import type { Completion } from "@codemirror/autocomplete";
-import { notebookAtom } from "@/core/cells/cells";
-import type { CellId } from "@/core/cells/ids";
-import { displayCellName } from "@/core/cells/names";
-import type { MarimoError, OutputMessage } from "@/core/kernel/messages";
-import { isErrorMime, isMarimoErrorsMime, isTracebackMime } from "@/core/mime";
+import {
+ type CellErrorEntry,
+ describeError,
+ formatSingleError,
+ getCellErrorEntries,
+} from "@/core/errors/error-entries";
import type { JotaiStore } from "@/core/state/jotai";
-import { logNever } from "@/utils/assertNever";
import { parseHtmlContent } from "@/utils/dom";
import { PluralWord } from "@/utils/pluralize";
import { type AIContextItem, AIContextProvider } from "../registry";
@@ -15,14 +15,6 @@ import { contextToXml } from "../utils";
import { Sections } from "./common";
import { formatDatasourceContextForCell } from "./datasource";
-export interface CellErrorEntry {
- cellId: CellId;
- cellName: string;
- cellCode: string;
- errorData: MarimoError[];
- tracebackHtml?: string;
-}
-
export type ErrorContextItemData =
| {
type: "all-errors";
@@ -38,150 +30,6 @@ export interface ErrorContextItem extends AIContextItem {
data: ErrorContextItemData;
}
-function parseCellErrorOutput(
- output: OutputMessage,
-): Pick<CellErrorEntry, "errorData" | "tracebackHtml"> | null {
- if (isMarimoErrorsMime(output.mimetype)) {
- if (!Array.isArray(output.data)) {
- return null;
- }
- const errorData = output.data.filter(
- (error) => !error.type.includes("ancestor"),
- );
- if (errorData.length === 0) {
- return null;
- }
- return { errorData };
- }
-
- if (isTracebackMime(output.mimetype)) {
- if (typeof output.data !== "string" || output.data.length === 0) {
- return null;
- }
- return { errorData: [], tracebackHtml: output.data };
- }
-
- return null;
-}
-
-function errorDataHasTraceback(errorData: MarimoError[]): boolean {
- return errorData.some((error) => "traceback" in error && error.traceback);
-}
-
-function getTracebackFromConsole(
- consoleOutputs: OutputMessage[] | undefined,
-): string | undefined {
- const tracebackOutput = consoleOutputs?.find((output) =>
- isTracebackMime(output.mimetype),
- );
- if (
- !tracebackOutput ||
- typeof tracebackOutput.data !== "string" ||
- tracebackOutput.data.length === 0
- ) {
- return undefined;
- }
- return tracebackOutput.data;
-}
-
-function resolveTracebackHtml(
- parsed: Pick<CellErrorEntry, "errorData" | "tracebackHtml">,
- consoleOutputs: OutputMessage[] | undefined,
-): string | undefined {
- if (parsed.tracebackHtml) {
- return parsed.tracebackHtml;
- }
- if (errorDataHasTraceback(parsed.errorData)) {
- return undefined;
- }
- return getTracebackFromConsole(consoleOutputs);
-}
-
-export function getCellErrorEntries(store: JotaiStore): CellErrorEntry[] {
- const { cellIds, cellRuntime, cellData } = store.get(notebookAtom);
- const entries: CellErrorEntry[] = [];
-
- for (const [cellIndex, cellId] of cellIds.inOrderIds.entries()) {
- const cell = cellRuntime[cellId];
- const output = cell.output;
- if (!output || !isErrorMime(output.mimetype)) {
- continue;
- }
-
- const parsed = parseCellErrorOutput(output);
- if (!parsed) {
- continue;
- }
-
- const cellName = displayCellName(cellData[cellId].name, cellIndex);
- // Prefer the code from the last execution: runtime errors correspond to
- // the previous run, while `code` may already contain unsaved edits.
- const cellCode = cellData[cellId].lastCodeRun ?? cellData[cellId].code;
-
- entries.push({
- cellId,
- cellName,
- cellCode,
- errorData: parsed.errorData,
- tracebackHtml: resolveTracebackHtml(parsed, cell.consoleOutputs),
- });
- }
-
- return entries;
-}
-
-function describeError(error: MarimoError): string {
- if (error.type === "setup-refs") {
- return "The setup cell cannot have references";
- }
- if (error.type === "cycle") {
- return "This cell is in a cycle";
- }
- if (error.type === "multiple-defs") {
- return `The variable '${error.name}' was defined by another cell`;
- }
- if (error.type === "import-star") {
- return error.msg;
- }
- if (error.type === "ancestor-stopped") {
- return error.msg;
- }
- if (error.type === "ancestor-prevented") {
- return error.msg;
- }
- if (error.type === "exception") {
- return error.msg;
- }
- if (error.type === "strict-exception") {
- return error.msg;
- }
- if (error.type === "interruption") {
- return "This cell was interrupted and needs to be re-run";
- }
- if (error.type === "syntax") {
- return error.msg;
- }
- if (error.type === "unknown") {
- return error.msg;
- }
- if (error.type === "sql-error") {
- return error.msg;
- }
- if (error.type === "internal") {
- return error.msg || "An internal error occurred";
- }
- logNever(error);
- return "Unknown error";
-}
-
-function formatSingleError(error: MarimoError): string {
- let text = describeError(error);
- if ("traceback" in error && error.traceback) {
- text += `\n\nTraceback:\n${parseHtmlContent(error.traceback)}`;
- }
- return text;
-}
-
function formatCellErrorDetails(
entry: CellErrorEntry,
store: JotaiStore,
diff --git a/frontend/src/core/constants.ts b/frontend/src/core/constants.ts
index 4276ed7033..546b9d04fe 100644
--- a/frontend/src/core/constants.ts
+++ b/frontend/src/core/constants.ts
@@ -3,6 +3,8 @@ export const Constants = {
githubPage: "https://github.com/marimo-team/marimo",
releasesPage: "https://github.com/marimo-team/marimo/releases",
issuesPage: "https://github.com/marimo-team/marimo/issues",
+ bugReportUrl:
+ "https://github.com/marimo-team/marimo/issues/new?template=bug_report.yaml",
feedbackForm: "https://marimo.io/feedback",
discordLink: "https://marimo.io/discord?ref=notebook",
docsPage: "https://docs.marimo.io",
diff --git a/frontend/src/core/diagnostics/__tests__/issue-details.test.ts b/frontend/src/core/diagnostics/__tests__/issue-details.test.ts
new file mode 100644
index 0000000000..6de14d6ba0
--- /dev/null
+++ b/frontend/src/core/diagnostics/__tests__/issue-details.test.ts
@@ -0,0 +1,173 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import { describe, expect, it } from "vitest";
+import { cellId } from "@/__tests__/branded";
+import type { CellErrorEntry } from "@/core/errors/error-entries";
+import type { EnvironmentInfo } from "@/core/network/types";
+import {
+ buildBugReportUrl,
+ buildIssueDetails,
+ createPartialEnvironment,
+ enrichEnvironment,
+ markdownCodeFence,
+ MAX_PREFILL_URL_LENGTH,
+} from "../issue-details";
+
+const environment: EnvironmentInfo = {
+ marimo: "1.2.3",
+ editable: false,
+ location: "~/.venv/site-packages/marimo",
+ OS: "Darwin",
+ "OS Version": "25.0",
+ Processor: "arm",
+ "Python Version": "3.12.9",
+ Locale: "en_US",
+ Binaries: { Browser: "chrome 140", Node: "v22", uv: "0.11" },
+ Dependencies: { click: "8.4.2" },
+ "Optional Dependencies": { pandas: "3.0.0" },
+ "Experimental Flags": {},
+};
+
+describe("enrichEnvironment", () => {
+ it("replaces server Chrome detection with the active browser", () => {
+ const result = enrichEnvironment(environment, "Firefox/140");
+ expect(result.Binaries.Browser).toBe("Firefox/140");
+ expect(result.Binaries.Node).toBe("v22");
+ });
+
+ it("does not mutate the input", () => {
+ enrichEnvironment(environment, "Firefox/140");
+ expect(environment.Binaries.Browser).toBe("chrome 140");
+ });
+});
+
+describe("createPartialEnvironment", () => {
+ it("records the collection error and keeps the active browser", () => {
+ const partial = createPartialEnvironment(
+ "1.2.3",
+ "Firefox/140",
+ "en_US",
+ "Server environment information unavailable",
+ );
+ expect(partial.marimo).toBe("1.2.3");
+ expect(partial.Binaries?.Browser).toBe("Firefox/140");
+ expect(partial.Locale).toBe("en_US");
+ expect(partial["Environment Collection Error"]).toBe(
+ "Server environment information unavailable",
+ );
+ });
+
+ it("omits empty fields rather than filling placeholders", () => {
+ const partial = createPartialEnvironment(
+ "1.2.3",
+ "Firefox/140",
+ "",
+ "boom",
+ );
+ expect(partial.Locale).toBeUndefined();
+ expect(partial.location).toBeUndefined();
+ expect(partial.OS).toBeUndefined();
+ expect(partial.Dependencies).toBeUndefined();
+ });
+});
+
+describe("markdownCodeFence", () => {
+ it("uses a fence longer than any backtick run in the content", () => {
+ const block = markdownCodeFence("python", 'text = "```"');
+ expect(block.startsWith("````python\n")).toBe(true);
+ expect(block.endsWith("\n````")).toBe(true);
+ expect(block).toContain('text = "```"');
+ });
+
+ it("uses a minimum fence of three backticks", () => {
+ const block = markdownCodeFence("json", "{}");
+ expect(block.startsWith("```json\n")).toBe(true);
+ expect(block.endsWith("\n```")).toBe(true);
+ });
+});
+
+describe("buildIssueDetails", () => {
+ it("includes the environment and omits notebook source unless provided", () => {
+ const markdown = buildIssueDetails({
+ environment,
+ errors: [],
+ notebook: undefined,
+ });
+ expect(markdown).toContain("<summary>Environment</summary>");
+ expect(markdown).toContain('"marimo": "1.2.3"');
+ expect(markdown).not.toContain("Notebook source");
+ expect(markdown).not.toContain("Current errors");
+ });
+
+ it("includes current errors as plain text without notebook source", () => {
+ const errors: CellErrorEntry[] = [
+ {
+ cellId: cellId("cell-1"),
+ cellName: "Cell 1",
+ cellCode: "password = 'private'",
+ errorData: [],
+ tracebackHtml:
+ '<span class="gr">ValueError</span>: <span class="n">bad value</span>',
+ },
+ ];
+ const markdown = buildIssueDetails({ environment, errors });
+ expect(markdown).toContain("<summary>Current errors</summary>");
+ expect(markdown).toContain("ValueError: bad value");
+ expect(markdown).not.toContain("password");
+ });
+
+ it("includes notebook source under its basename when provided", () => {
+ const markdown = buildIssueDetails({
+ environment,
+ errors: [],
+ notebook: {
+ filename: "/project/example.py",
+ contents: "x = 1",
+ },
+ });
+ expect(markdown).toContain(
+ "<summary>Notebook source: example.py</summary>",
+ );
+ expect(markdown).toContain("x = 1");
+ });
+
+ it("escapes the summary label as text", () => {
+ const markdown = buildIssueDetails({
+ environment,
+ errors: [],
+ notebook: {
+ filename: "/project/<script>.py",
+ contents: "x = 1",
+ },
+ });
+ expect(markdown).toContain("&lt;script&gt;.py");
+ expect(markdown).not.toContain("<script>.py");
+ });
+});
+
+describe("buildBugReportUrl", () => {
+ const baseUrl =
+ "https://github.com/marimo-team/marimo/issues/new?template=bug_report.yaml";
+
+ it("prefills the env field with the encoded issue details", () => {
+ const url = buildBugReportUrl(baseUrl, "hello world");
+ expect(url).toBe(`${baseUrl}&env=hello%20world`);
+ });
+
+ it("appends env with a query separator when the base URL has none", () => {
+ const url = buildBugReportUrl("https://example.com/new", "x");
+ expect(url).toBe("https://example.com/new?env=x");
+ });
+
+ it("encodes markdown so it survives as a single query param", () => {
+ const details = buildIssueDetails({ environment, errors: [] });
+ const url = buildBugReportUrl(baseUrl, details);
+ expect(url).toContain("&env=");
+ expect(new URL(url).searchParams.get("env")).toBe(details);
+ });
+
+ it("falls back to the plain base URL when the prefill exceeds the cap", () => {
+ const huge = "x".repeat(MAX_PREFILL_URL_LENGTH);
+ expect(buildBugReportUrl(baseUrl, huge)).toBe(baseUrl);
+ });
+});
diff --git a/frontend/src/core/diagnostics/issue-details.ts b/frontend/src/core/diagnostics/issue-details.ts
new file mode 100644
index 0000000000..73e461d254
--- /dev/null
+++ b/frontend/src/core/diagnostics/issue-details.ts
@@ -0,0 +1,139 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import {
+ type CellErrorEntry,
+ formatCellError,
+} from "@/core/errors/error-entries";
+import type { EnvironmentInfo } from "@/core/network/types";
+import { Paths } from "@/utils/paths";
+import { Strings } from "@/utils/strings";
+
+/**
+ * Environment information augmented with a client-side collection error, used
+ * when the server environment request fails and only partial data is available.
+ * Fields are optional because a partial environment only carries what the
+ * client could determine without the server.
+ */
+export type EnvironmentDiagnostics = Partial<EnvironmentInfo> & {
+ "Environment Collection Error"?: string;
+};
+
+export interface NotebookSource {
+ filename: string;
+ contents: string;
+}
+
+export interface IssueDetailsInput {
+ environment: EnvironmentDiagnostics;
+ errors: CellErrorEntry[];
+ notebook?: NotebookSource;
+}
+
+/**
+ * Replace the server-detected browser with the active browser's user agent.
+ *
+ * The server cannot know which browser is driving the UI, so diagnostics
+ * generated from the modal reflect the live `navigator.userAgent` instead.
+ */
+export function enrichEnvironment(
+ environment: EnvironmentInfo,
+ userAgent: string,
+): EnvironmentInfo {
+ return {
+ ...environment,
+ Binaries: {
+ ...environment.Binaries,
+ Browser: userAgent,
+ },
+ };
+}
+
+export function createPartialEnvironment(
+ marimoVersion: string,
+ userAgent: string,
+ locale: string,
+ message: string,
+): EnvironmentDiagnostics {
+ return {
+ marimo: marimoVersion,
+ Locale: locale || undefined,
+ Binaries: { Browser: userAgent },
+ "Environment Collection Error": message,
+ };
+}
+
+/**
+ * Wrap `contents` in a Markdown code fence long enough to survive backtick runs
+ * inside it, so pasted diagnostics render as a single block on GitHub.
+ */
+export function markdownCodeFence(language: string, contents: string): string {
+ const longest = Math.max(
+ 2,
+ ...Array.from(contents.matchAll(/`+/g), (match) => match[0].length),
+ );
+ const fence = "`".repeat(longest + 1);
+ return `${fence}${language}\n${contents}\n${fence}`;
+}
+
+/**
+ * GitHub returns HTTP 414 for issue-form URLs beyond roughly 8 KB, so prefill is
+ * skipped once the encoded body would push the URL past this conservative cap.
+ */
+export const MAX_PREFILL_URL_LENGTH = 6000;
+
+/**
+ * Build a bug-report URL with `issueDetails` prefilled into the form's `env`
+ * field. Falls back to `baseUrl` unchanged when the prefilled URL would exceed
+ * `MAX_PREFILL_URL_LENGTH`.
+ */
+export function buildBugReportUrl(
+ baseUrl: string,
+ issueDetails: string,
+): string {
+ const separator = baseUrl.includes("?") ? "&" : "?";
+ const prefilled = `${baseUrl}${separator}env=${encodeURIComponent(issueDetails)}`;
+ return prefilled.length > MAX_PREFILL_URL_LENGTH ? baseUrl : prefilled;
+}
+
+function detailsSection(summary: string, body: string): string {
+ return [
+ "<details>",
+ `<summary>${Strings.htmlEscape(summary) ?? ""}</summary>`,
+ "",
+ body,
+ "",
+ "</details>",
+ ].join("\n");
+}
+
+export function buildIssueDetails(input: IssueDetailsInput): string {
+ const sections = [
+ detailsSection(
+ "Environment",
+ markdownCodeFence("json", JSON.stringify(input.environment, null, 2)),
+ ),
+ ];
+
+ if (input.errors.length > 0) {
+ sections.push(
+ detailsSection(
+ "Current errors",
+ markdownCodeFence(
+ "text",
+ input.errors.map(formatCellError).join("\n\n---\n\n"),
+ ),
+ ),
+ );
+ }
+
+ if (input.notebook) {
+ sections.push(
+ detailsSection(
+ `Notebook source: ${Paths.basename(input.notebook.filename)}`,
+ markdownCodeFence("python", input.notebook.contents),
+ ),
+ );
+ }
+
+ return sections.join("\n\n");
+}
diff --git a/frontend/src/core/errors/__tests__/error-entries.test.ts b/frontend/src/core/errors/__tests__/error-entries.test.ts
new file mode 100644
index 0000000000..78e15b1c5d
--- /dev/null
+++ b/frontend/src/core/errors/__tests__/error-entries.test.ts
@@ -0,0 +1,25 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import { describe, expect, it } from "vitest";
+import { cellId } from "@/__tests__/branded";
+import { type CellErrorEntry, formatCellError } from "../error-entries";
+
+describe("formatCellError", () => {
+ it("formats current tracebacks without notebook source", () => {
+ const entry: CellErrorEntry = {
+ cellId: cellId("cell-1"),
+ cellName: "Cell 1",
+ cellCode: "password = 'private'",
+ errorData: [],
+ tracebackHtml:
+ '<span class="gr">ValueError</span>: <span class="n">bad value</span>',
+ };
+
+ const text = formatCellError(entry);
+
+ expect(text).toContain("Cell 1");
+ expect(text).toContain("ValueError: bad value");
+ expect(text).not.toContain("password");
+ expect(text).not.toContain("<span");
+ });
+});
diff --git a/frontend/src/core/errors/error-entries.ts b/frontend/src/core/errors/error-entries.ts
new file mode 100644
index 0000000000..e27bf85a27
--- /dev/null
+++ b/frontend/src/core/errors/error-entries.ts
@@ -0,0 +1,176 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import { notebookAtom } from "@/core/cells/cells";
+import type { CellId } from "@/core/cells/ids";
+import { displayCellName } from "@/core/cells/names";
+import type { MarimoError, OutputMessage } from "@/core/kernel/messages";
+import { isErrorMime, isMarimoErrorsMime, isTracebackMime } from "@/core/mime";
+import type { JotaiStore } from "@/core/state/jotai";
+import { logNever } from "@/utils/assertNever";
+import { parseHtmlContent } from "@/utils/dom";
+
+export interface CellErrorEntry {
+ cellId: CellId;
+ cellName: string;
+ cellCode: string;
+ errorData: MarimoError[];
+ tracebackHtml?: string;
+}
+
+function parseCellErrorOutput(
+ output: OutputMessage,
+): Pick<CellErrorEntry, "errorData" | "tracebackHtml"> | null {
+ if (isMarimoErrorsMime(output.mimetype)) {
+ if (!Array.isArray(output.data)) {
+ return null;
+ }
+ const errorData = output.data.filter(
+ (error) => !error.type.includes("ancestor"),
+ );
+ if (errorData.length === 0) {
+ return null;
+ }
+ return { errorData };
+ }
+
+ if (isTracebackMime(output.mimetype)) {
+ if (typeof output.data !== "string" || output.data.length === 0) {
+ return null;
+ }
+ return { errorData: [], tracebackHtml: output.data };
+ }
+
+ return null;
+}
+
+function errorDataHasTraceback(errorData: MarimoError[]): boolean {
+ return errorData.some((error) => "traceback" in error && error.traceback);
+}
+
+function getTracebackFromConsole(
+ consoleOutputs: OutputMessage[] | undefined,
+): string | undefined {
+ const tracebackOutput = consoleOutputs?.find((output) =>
+ isTracebackMime(output.mimetype),
+ );
+ if (
+ !tracebackOutput ||
+ typeof tracebackOutput.data !== "string" ||
+ tracebackOutput.data.length === 0
+ ) {
+ return undefined;
+ }
+ return tracebackOutput.data;
+}
+
+function resolveTracebackHtml(
+ parsed: Pick<CellErrorEntry, "errorData" | "tracebackHtml">,
+ consoleOutputs: OutputMessage[] | undefined,
+): string | undefined {
+ if (parsed.tracebackHtml) {
+ return parsed.tracebackHtml;
+ }
+ if (errorDataHasTraceback(parsed.errorData)) {
+ return undefined;
+ }
+ return getTracebackFromConsole(consoleOutputs);
+}
+
+export function getCellErrorEntries(store: JotaiStore): CellErrorEntry[] {
+ const { cellIds, cellRuntime, cellData } = store.get(notebookAtom);
+ const entries: CellErrorEntry[] = [];
+
+ for (const [cellIndex, cellId] of cellIds.inOrderIds.entries()) {
+ const cell = cellRuntime[cellId];
+ const output = cell.output;
+ if (!output || !isErrorMime(output.mimetype)) {
+ continue;
+ }
+
+ const parsed = parseCellErrorOutput(output);
+ if (!parsed) {
+ continue;
+ }
+
+ const cellName = displayCellName(cellData[cellId].name, cellIndex);
+ // Prefer the code from the last execution: runtime errors correspond to
+ // the previous run, while `code` may already contain unsaved edits.
+ const cellCode = cellData[cellId].lastCodeRun ?? cellData[cellId].code;
+
+ entries.push({
+ cellId,
+ cellName,
+ cellCode,
+ errorData: parsed.errorData,
+ tracebackHtml: resolveTracebackHtml(parsed, cell.consoleOutputs),
+ });
+ }
+
+ return entries;
+}
+
+export function describeError(error: MarimoError): string {
+ if (error.type === "setup-refs") {
+ return "The setup cell cannot have references";
+ }
+ if (error.type === "cycle") {
+ return "This cell is in a cycle";
+ }
+ if (error.type === "multiple-defs") {
+ return `The variable '${error.name}' was defined by another cell`;
+ }
+ if (error.type === "import-star") {
+ return error.msg;
+ }
+ if (error.type === "ancestor-stopped") {
+ return error.msg;
+ }
+ if (error.type === "ancestor-prevented") {
+ return error.msg;
+ }
+ if (error.type === "exception") {
+ return error.msg;
+ }
+ if (error.type === "strict-exception") {
+ return error.msg;
+ }
+ if (error.type === "interruption") {
+ return "This cell was interrupted and needs to be re-run";
+ }
+ if (error.type === "syntax") {
+ return error.msg;
+ }
+ if (error.type === "unknown") {
+ return error.msg;
+ }
+ if (error.type === "sql-error") {
+ return error.msg;
+ }
+ if (error.type === "internal") {
+ return error.msg || "An internal error occurred";
+ }
+ logNever(error);
+ return "Unknown error";
+}
+
+export function formatSingleError(error: MarimoError): string {
+ let text = describeError(error);
+ if ("traceback" in error && error.traceback) {
+ text += `\n\nTraceback:\n${parseHtmlContent(error.traceback)}`;
+ }
+ return text;
+}
+
+export function formatCellError(entry: CellErrorEntry): string {
+ const parts = [entry.cellName];
+
+ if (entry.tracebackHtml) {
+ parts.push(parseHtmlContent(entry.tracebackHtml));
+ }
+
+ if (entry.errorData.length > 0) {
+ parts.push(entry.errorData.map(formatSingleError).join("\n\n"));
+ }
+
+ return parts.join("\n\n");
+}
diff --git a/frontend/src/core/islands/bridge.ts b/frontend/src/core/islands/bridge.ts
index 2ccc781618..c2d06367b5 100644
--- a/frontend/src/core/islands/bridge.ts
+++ b/frontend/src/core/islands/bridge.ts
@@ -295,6 +295,7 @@ export class IslandsPyodideBridge implements RunRequests, EditRequests {
// ============================================================================
getUsageStats = throwNotImplemented;
+ getEnvironmentInfo = throwNotImplemented;
sendRename = throwNotImplemented;
sendSave = throwNotImplemented;
sendCopy = throwNotImplemented;
diff --git a/frontend/src/core/network/__tests__/requests-lazy.test.ts b/frontend/src/core/network/__tests__/requests-lazy.test.ts
index 6ea29b2726..9638fa7a8d 100644
--- a/frontend/src/core/network/__tests__/requests-lazy.test.ts
+++ b/frontend/src/core/network/__tests__/requests-lazy.test.ts
@@ -54,6 +54,24 @@ describe("createLazyRequests", () => {
} as unknown as EditRequests & RunRequests;
});
+ it("passes server-only requests through without starting a kernel", async () => {
+ const environment = { marimo: "1.2.3" };
+ mockDelegate.getEnvironmentInfo = vi
+ .fn()
+ .mockResolvedValue(environment) as EditRequests["getEnvironmentInfo"];
+
+ const lazyRequests = createLazyRequests(
+ mockDelegate,
+ mockGetRuntimeManager,
+ );
+
+ await expect(lazyRequests.getEnvironmentInfo()).resolves.toEqual(
+ environment,
+ );
+ expect(mockInit).not.toHaveBeenCalled();
+ expect(mockDelegate.getEnvironmentInfo).toHaveBeenCalledOnce();
+ });
+
it("should call init once before first request", async () => {
const lazyRequests = createLazyRequests(
mockDelegate,
diff --git a/frontend/src/core/network/__tests__/requests-network.test.ts b/frontend/src/core/network/__tests__/requests-network.test.ts
index 4ffd87e163..cfbd260606 100644
--- a/frontend/src/core/network/__tests__/requests-network.test.ts
+++ b/frontend/src/core/network/__tests__/requests-network.test.ts
@@ -114,6 +114,13 @@ describe("createNetworkRequests", () => {
);
});
+ it("getEnvironmentInfo should GET /api/environment", async () => {
+ const requests = createNetworkRequests();
+ await requests.getEnvironmentInfo();
+
+ expect(mockClient.GET).toHaveBeenCalledWith("/api/environment");
+ });
+
it("exportAsIPYNB should call the new endpoint as text", async () => {
const requests = createNetworkRequests();
await requests.exportAsIPYNB({
diff --git a/frontend/src/core/network/requests-lazy.ts b/frontend/src/core/network/requests-lazy.ts
index fe49af0311..d3ccd9670e 100644
--- a/frontend/src/core/network/requests-lazy.ts
+++ b/frontend/src/core/network/requests-lazy.ts
@@ -29,12 +29,17 @@ type AllRequests = EditRequests & RunRequests;
// - waitForConnectionOpen: Waits for an existing connection but won't start one.
// Use for operations that depend on a running kernel but shouldn't be the
// trigger to start it (e.g., saving, interrupting).
+//
+// - serverOnly: Calls the HTTP delegate directly without touching the kernel.
+// Use for requests served by the marimo server itself, which resolve without
+// a session (e.g., fetching environment diagnostics).
type Action =
| "throwError"
| "dropRequest"
| "startConnection"
- | "waitForConnectionOpen";
+ | "waitForConnectionOpen"
+ | "serverOnly";
const ACTIONS: Record<keyof AllRequests, Action> = {
// These will start a connection if not already connected and then wait until the connection is open
@@ -96,6 +101,9 @@ const ACTIONS: Record<keyof AllRequests, Action> = {
sendFileDetails: "throwError",
openFile: "throwError",
+ // Served by the marimo server without a kernel session
+ getEnvironmentInfo: "serverOnly",
+
// Home operations throw errors
getRecentFiles: "startConnection",
getWorkspaceFiles: "startConnection",
@@ -155,6 +163,10 @@ export function createLazyRequests(
}
switch (action) {
+ case "serverOnly":
+ // Served by the marimo server itself; no kernel required
+ return request(...args);
+
case "dropRequest":
Logger.debug(
`Dropping request: ${key}, since not connected to a kernel.`,
diff --git a/frontend/src/core/network/requests-network.ts b/frontend/src/core/network/requests-network.ts
index e0e9b72ba0..731965ae1b 100644
--- a/frontend/src/core/network/requests-network.ts
+++ b/frontend/src/core/network/requests-network.ts
@@ -285,6 +285,9 @@ export function createNetworkRequests(): EditRequests & RunRequests {
await waitForConnectionOpen();
return getClient().GET("/api/usage").then(handleResponse);
},
+ getEnvironmentInfo: () => {
+ return getClient().GET("/api/environment").then(handleResponse);
+ },
sendPdb: (request) => {
return getClient()
.POST("/api/kernel/pdb/pm", {
diff --git a/frontend/src/core/network/requests-static.ts b/frontend/src/core/network/requests-static.ts
index 494c283cd1..d5818af616 100644
--- a/frontend/src/core/network/requests-static.ts
+++ b/frontend/src/core/network/requests-static.ts
@@ -65,6 +65,7 @@ export function createStaticRequests(): EditRequests & RunRequests {
validateSQL: throwNotInEditMode,
openFile: throwNotInEditMode,
getUsageStats: throwNotInEditMode,
+ getEnvironmentInfo: throwNotInEditMode,
sendListFiles: throwNotInEditMode,
sendSearchFiles: throwNotInEditMode,
sendPdb: throwNotInEditMode,
diff --git a/frontend/src/core/network/requests-toasting.tsx b/frontend/src/core/network/requests-toasting.tsx
index d84bab9056..6576ee792e 100644
--- a/frontend/src/core/network/requests-toasting.tsx
+++ b/frontend/src/core/network/requests-toasting.tsx
@@ -46,6 +46,7 @@ export function createErrorToastingRequests(
validateSQL: "Failed to validate SQL",
openFile: "Failed to open file",
getUsageStats: "", // No toast
+ getEnvironmentInfo: "", // No toast
sendListFiles: "Failed to list files",
sendSearchFiles: "Failed to search files",
sendPdb: "Failed to start debug session",
diff --git a/frontend/src/core/network/types.ts b/frontend/src/core/network/types.ts
index 6b8e39c315..d208eb38bc 100644
--- a/frontend/src/core/network/types.ts
+++ b/frontend/src/core/network/types.ts
@@ -107,6 +107,8 @@ export type UpdateUIElementValuesRequest =
schemas["UpdateUIElementValuesRequest"];
export type UsageResponse =
paths["/api/usage"]["get"]["responses"]["200"]["content"]["application/json"];
+export type EnvironmentInfo =
+ paths["/api/environment"]["get"]["responses"]["200"]["content"]["application/json"];
export type WorkspaceFilesRequest = schemas["WorkspaceFilesRequest"];
export type WorkspaceFilesResponse = schemas["WorkspaceFilesResponse"];
export type RunningNotebooksResponse = schemas["RunningNotebooksResponse"];
@@ -171,6 +173,7 @@ export interface EditRequests {
validateSQL: (request: ValidateSQLRequest) => Promise<null>;
openFile: (request: { path: string; lineNumber?: number }) => Promise<null>;
getUsageStats: () => Promise<UsageResponse>;
+ getEnvironmentInfo: () => Promise<EnvironmentInfo>;
// Debugger
sendPdb: (request: DebugCellRequest) => Promise<null>;
sendSetBreakpoints: (request: SetBreakpointsRequest) => Promise<null>;
diff --git a/frontend/src/core/wasm/bridge.ts b/frontend/src/core/wasm/bridge.ts
index 8ef174b4ed..689080793e 100644
--- a/frontend/src/core/wasm/bridge.ts
+++ b/frontend/src/core/wasm/bridge.ts
@@ -16,6 +16,7 @@ import { getInitialAppMode } from "../mode";
import { API } from "../network/api";
import type {
EditRequests,
+ EnvironmentInfo,
ExportAsHTMLRequest,
ExportAsMarkdownRequest,
FileCopyResponse,
@@ -629,6 +630,13 @@ export class PyodideBridge implements RunRequests, EditRequests {
};
getUsageStats = throwNotImplemented;
+ getEnvironmentInfo: EditRequests["getEnvironmentInfo"] = async () => {
+ const response = await this.rpc.proxy.request.bridge({
+ functionName: "get_environment_info",
+ payload: undefined,
+ });
+ return response as EnvironmentInfo;
+ };
openTutorial = throwNotImplemented;
getRecentFiles = throwNotImplemented;
getWorkspaceFiles = throwNotImplemented;
diff --git a/frontend/src/core/wasm/worker/types.ts b/frontend/src/core/wasm/worker/types.ts
index d58f07e845..1b61860634 100644
--- a/frontend/src/core/wasm/worker/types.ts
+++ b/frontend/src/core/wasm/worker/types.ts
@@ -9,6 +9,7 @@ import type { JsonString } from "@/utils/json/base64";
import type {
CodeCompletionRequest,
CopyNotebookRequest,
+ EnvironmentInfo,
ExportAsHTMLRequest,
ExportAsMarkdownRequest,
FileCopyRequest,
@@ -73,6 +74,7 @@ export interface RawBridge {
code_complete(request: CodeCompletionRequest): Promise<string>;
read_code(): Promise<{ contents: string }>;
read_snippets(): Promise<Snippets>;
+ get_environment_info(): Promise<EnvironmentInfo>;
format(request: FormatCellsRequest): Promise<FormatResponse>;
save(request: SaveNotebookRequest): Promise<string>;
copy(request: CopyNotebookRequest): Promise<string>;
diff --git a/marimo/_cli/envinfo.py b/marimo/_cli/envinfo.py
index a136a1274c..1784b2b2a6 100644
--- a/marimo/_cli/envinfo.py
+++ b/marimo/_cli/envinfo.py
@@ -1,114 +1,18 @@
# Copyright 2026 Marimo. All rights reserved.
from __future__ import annotations
-import platform
-import sys
-from pathlib import Path
-from typing import Any, cast
-
-from marimo import _loggers
-from marimo._config.manager import get_default_config_manager
-from marimo._utils.health import (
- get_chrome_version,
- get_node_version,
- get_optional_modules_list,
- get_required_modules_list,
- get_uv_version,
+from marimo._utils.diagnostics import (
+ abbreviate_home,
+ get_default_locale,
+ get_experimental_flags,
+ get_system_info,
+ is_win11,
)
-from marimo._utils.versions import is_editable
-from marimo._version import __version__
-
-LOGGER = _loggers.marimo_logger()
-
-
-def is_win11() -> bool:
- """
- Check if the operating system is Windows 11.
-
- Returns:
- bool: True if the OS is Windows 11, False otherwise.
- """
- if hasattr(sys, "getwindowsversion"):
- return cast(Any, sys).getwindowsversion().build >= 22000 # type: ignore[no-any-return]
- return False
-
-
-def get_experimental_flags() -> dict[str, str | bool | dict[str, Any]]:
- try:
- config = get_default_config_manager(current_path=None).get_config()
- experimental_config = config.get("experimental", {})
- return {
- k: v
- for k, v in experimental_config.items()
- if isinstance(v, (str, bool, dict))
- }
- except Exception:
- LOGGER.error("Failed to get experimental flags")
- return {}
-
-
-def get_default_locale() -> str:
- try:
- import locale
-
- # getdefaultlocale is deprecated in 3.13+ and removed in 3.15
- # Use getlocale() with LC_ALL as a fallback chain
- loc = locale.getlocale(locale.LC_ALL)
- if loc[0]:
- return loc[0]
- # Try LC_MESSAGES on Unix-like systems
- try:
- loc = locale.getlocale(locale.LC_MESSAGES)
- if loc[0]:
- return loc[0]
- except AttributeError:
- pass
- # Fall back to environment variable check
- import os
-
- for env_var in ("LC_ALL", "LC_MESSAGES", "LANG", "LANGUAGE"):
- val = os.environ.get(env_var)
- if val:
- # Extract locale name (e.g., "en_US" from "en_US.UTF-8")
- return val.split(".")[0]
- return "--"
- except Exception:
- return "--"
-
-
-def get_system_info() -> dict[str, str | bool | dict[str, Any]]:
- os_version = platform.release()
- if platform.system() == "Windows" and is_win11():
- os_version = "11"
-
- location = Path(__file__).parent.parent.as_posix()
- info: dict[str, str | bool | dict[str, Any]] = {
- "marimo": __version__,
- "editable": is_editable("marimo"),
- "location": location,
- "OS": platform.system(),
- "OS Version": os_version,
- # e.g., x86 or arm
- "Processor": platform.processor(),
- "Python Version": platform.python_version(),
- "Locale": get_default_locale(),
- }
-
- binaries = {
- # Check chrome specifically if invoked from cli, this value could be
- # back-filled in frontend
- "Browser": get_chrome_version() or "--",
- "Node": get_node_version() or "--",
- "uv": get_uv_version() or "--",
- }
- requirements = get_required_modules_list()
- optional_deps = get_optional_modules_list()
- experimental = get_experimental_flags()
- return {
- **info,
- "Binaries": binaries,
- "Dependencies": requirements,
- "Optional Dependencies": optional_deps,
- "Experimental Flags": experimental,
- }
+__all__ = [
+ "abbreviate_home",
+ "get_default_locale",
+ "get_experimental_flags",
+ "get_system_info",
+ "is_win11",
+]
diff --git a/marimo/_pyodide/pyodide_session.py b/marimo/_pyodide/pyodide_session.py
index 336a079c21..9818c4a66e 100644
--- a/marimo/_pyodide/pyodide_session.py
+++ b/marimo/_pyodide/pyodide_session.py
@@ -245,6 +245,11 @@ class PyodideBridge:
snippets = await read_snippets(self.session._initial_user_config)
return self._dump(snippets)
+ def get_environment_info(self) -> str:
+ from marimo._utils.diagnostics import get_system_info
+
+ return self._dump(get_system_info(redact_home=True))
+
async def format(self, request: str) -> str:
parsed = self._parse(request, FormatCellsRequest)
formatter = DefaultFormatter(line_length=parsed.line_length)
diff --git a/marimo/_server/api/endpoints/health.py b/marimo/_server/api/endpoints/health.py
index 84bd9f2ec2..b0bd1a8210 100644
--- a/marimo/_server/api/endpoints/health.py
+++ b/marimo/_server/api/endpoints/health.py
@@ -1,6 +1,7 @@
# Copyright 2026 Marimo. All rights reserved.
from __future__ import annotations
+import asyncio
from functools import lru_cache
from typing import TYPE_CHECKING, Any, Literal, TypedDict
@@ -11,6 +12,7 @@ from marimo import _loggers
from marimo._dependencies.dependencies import DependencyManager
from marimo._server.api.deps import AppState
from marimo._server.router import APIRouter
+from marimo._utils.diagnostics import get_system_info
from marimo._utils.health import (
get_cgroup_cpu_percent,
get_cgroup_mem_stats,
@@ -130,6 +132,70 @@ async def version(request: Request) -> PlainTextResponse:
return PlainTextResponse(__version__)
[email protected]("/api/environment")
+@requires("edit")
+async def environment(request: Request) -> JSONResponse:
+ """
+ responses:
+ 200:
+ description: Environment information for issue reporting
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ marimo:
+ type: string
+ editable:
+ type: boolean
+ location:
+ type: string
+ OS:
+ type: string
+ OS Version:
+ type: string
+ Processor:
+ type: string
+ Python Version:
+ type: string
+ Locale:
+ type: string
+ Binaries:
+ type: object
+ additionalProperties:
+ type: string
+ Dependencies:
+ type: object
+ additionalProperties:
+ type: string
+ Optional Dependencies:
+ type: object
+ additionalProperties:
+ type: string
+ Experimental Flags:
+ type: object
+ additionalProperties: {}
+ required:
+ - marimo
+ - editable
+ - location
+ - OS
+ - OS Version
+ - Processor
+ - Python Version
+ - Locale
+ - Binaries
+ - Dependencies
+ - Optional Dependencies
+ - Experimental Flags
+ """
+ del request # Unused
+ # Collect off the event loop; the install-location and dependency scans
+ # touch the filesystem and can block.
+ info = await asyncio.to_thread(get_system_info, redact_home=True)
+ return JSONResponse(info)
+
+
@router.get("/api/usage")
@requires("edit")
async def usage(request: Request) -> JSONResponse:
diff --git a/marimo/_utils/diagnostics.py b/marimo/_utils/diagnostics.py
new file mode 100644
index 0000000000..0526264f79
--- /dev/null
+++ b/marimo/_utils/diagnostics.py
@@ -0,0 +1,158 @@
+# Copyright 2026 Marimo. All rights reserved.
+from __future__ import annotations
+
+import platform
+import sys
+from pathlib import Path
+from typing import Any, cast
+
+from marimo import _loggers
+from marimo._config.manager import get_default_config_manager
+from marimo._utils.health import (
+ get_chrome_version,
+ get_node_version,
+ get_optional_modules_list,
+ get_required_modules_list,
+ get_uv_version,
+)
+from marimo._utils.versions import is_editable
+from marimo._version import __version__
+
+LOGGER = _loggers.marimo_logger()
+
+
+def is_win11() -> bool:
+ """
+ Check if the operating system is Windows 11.
+
+ Returns:
+ bool: True if the OS is Windows 11, False otherwise.
+ """
+ if hasattr(sys, "getwindowsversion"):
+ return cast(Any, sys).getwindowsversion().build >= 22000 # type: ignore[no-any-return]
+ return False
+
+
+def get_experimental_flags() -> dict[str, str | bool | dict[str, Any]]:
+ try:
+ config = get_default_config_manager(current_path=None).get_config()
+ experimental_config = config.get("experimental", {})
+ return {
+ k: v
+ for k, v in experimental_config.items()
+ if isinstance(v, (str, bool, dict))
+ }
+ except Exception:
+ LOGGER.error("Failed to get experimental flags")
+ return {}
+
+
+def get_default_locale() -> str:
+ try:
+ import locale
+
+ # locale.getlocale does not accept LC_ALL, so query the default
+ # category and fall back to LC_MESSAGES and the locale env vars.
+ loc = locale.getlocale()
+ if loc[0]:
+ return loc[0]
+ # Try LC_MESSAGES on Unix-like systems
+ try:
+ loc = locale.getlocale(locale.LC_MESSAGES)
+ if loc[0]:
+ return loc[0]
+ except AttributeError:
+ pass
+ # Fall back to environment variable check
+ import os
+
+ for env_var in ("LC_ALL", "LC_MESSAGES", "LANG", "LANGUAGE"):
+ val = os.environ.get(env_var)
+ if val:
+ # Extract locale name (e.g., "en_US" from "en_US.UTF-8")
+ return val.split(".")[0]
+ return "--"
+ except Exception:
+ return "--"
+
+
+def abbreviate_home(path: str, *, home: Path | None = None) -> str:
+ """
+ Replace the user's home directory prefix in `path` with `~`.
+
+ Paths outside the home directory are returned unchanged.
+
+ Args:
+ path (str): The path to abbreviate.
+ home (Path, optional): The home directory to match against. Defaults to
+ the current user's home directory.
+
+ Returns:
+ str: The path with the home prefix replaced by `~`, or unchanged.
+ """
+ normalized = Path(path).as_posix()
+ if home is None:
+ try:
+ home = Path.home()
+ except RuntimeError:
+ # Home directory is undeterminable; leave the path unredacted.
+ return normalized
+ home_path = home.as_posix().rstrip("/")
+ if normalized == home_path:
+ return "~"
+ if normalized.startswith(f"{home_path}/"):
+ return f"~{normalized[len(home_path) :]}"
+ return normalized
+
+
+def get_system_info(
+ *, redact_home: bool = False
+) -> dict[str, str | bool | dict[str, Any]]:
+ """
+ Collect environment information for diagnostics.
+
+ Args:
+ redact_home (bool, optional): When True, abbreviate the marimo install
+ location's home-directory prefix to `~`. Defaults to False.
+
+ Returns:
+ dict: Environment information keyed by field name.
+ """
+ os_version = platform.release()
+ if platform.system() == "Windows" and is_win11():
+ os_version = "11"
+
+ location = Path(__file__).parent.parent.as_posix()
+ if redact_home:
+ location = abbreviate_home(location)
+
+ info: dict[str, str | bool | dict[str, Any]] = {
+ "marimo": __version__,
+ "editable": is_editable("marimo"),
+ "location": location,
+ "OS": platform.system(),
+ "OS Version": os_version,
+ # e.g., x86 or arm
+ "Processor": platform.processor(),
+ "Python Version": platform.python_version(),
+ "Locale": get_default_locale(),
+ }
+
+ binaries = {
+ # Check chrome specifically if invoked from cli, this value could be
+ # back-filled in frontend
+ "Browser": get_chrome_version() or "--",
+ "Node": get_node_version() or "--",
+ "uv": get_uv_version() or "--",
+ }
+
+ requirements = get_required_modules_list()
+ optional_deps = get_optional_modules_list()
+ experimental = get_experimental_flags()
+ return {
+ **info,
+ "Binaries": binaries,
+ "Dependencies": requirements,
+ "Optional Dependencies": optional_deps,
+ "Experimental Flags": experimental,
+ }
diff --git a/marimo/_utils/health.py b/marimo/_utils/health.py
index cad7d2de82..bc981c218d 100644
--- a/marimo/_utils/health.py
+++ b/marimo/_utils/health.py
@@ -65,7 +65,9 @@ def get_node_version() -> str | None:
return stripped.split()[-1]
else:
return None
- except FileNotFoundError:
+ except OSError:
+ # Missing binary, or a platform without subprocess (e.g. Emscripten,
+ # which raises OSError "Function not implemented").
return None
@@ -87,7 +89,9 @@ def get_uv_version() -> str | None:
return stripped.removeprefix("uv ")
else:
return None
- except FileNotFoundError:
+ except OSError:
+ # Missing binary, or a platform without subprocess (e.g. Emscripten,
+ # which raises OSError "Function not implemented").
return None
diff --git a/packages/openapi/api.yaml b/packages/openapi/api.yaml
index d28251ad5c..0ae3365280 100644
--- a/packages/openapi/api.yaml
+++ b/packages/openapi/api.yaml
@@ -6235,6 +6235,60 @@ paths:
schema:
$ref: '#/components/schemas/Snippets'
description: Load the snippets for the documentation page
+ /api/environment:
+ get:
+ responses:
+ 200:
+ content:
+ application/json:
+ schema:
+ properties:
+ Binaries:
+ additionalProperties:
+ type: string
+ type: object
+ Dependencies:
+ additionalProperties:
+ type: string
+ type: object
+ Experimental Flags:
+ additionalProperties: {}
+ type: object
+ Locale:
+ type: string
+ OS:
+ type: string
+ OS Version:
+ type: string
+ Optional Dependencies:
+ additionalProperties:
+ type: string
+ type: object
+ Processor:
+ type: string
+ Python Version:
+ type: string
+ editable:
+ type: boolean
+ location:
+ type: string
+ marimo:
+ type: string
+ required:
+ - marimo
+ - editable
+ - location
+ - OS
+ - OS Version
+ - Processor
+ - Python Version
+ - Locale
+ - Binaries
+ - Dependencies
+ - Optional Dependencies
+ - Experimental Flags
+ type: object
+ description: Environment information for issue reporting
/api/export/auto_export/html:
post:
parameters:
diff --git a/packages/openapi/src/api.ts b/packages/openapi/src/api.ts
index 8633bcced8..638715dd74 100644
--- a/packages/openapi/src/api.ts
+++ b/packages/openapi/src/api.ts
@@ -649,6 +649,62 @@ export interface paths {
patch?: never;
trace?: never;
};
+ "/api/environment": {
+ parameters: {
+ query?: never;
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ get: {
+ parameters: {
+ query?: never;
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ requestBody?: never;
+ responses: {
+ /** @description Environment information for issue reporting */
+ 200: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": {
+ Binaries: {
+ [key: string]: string;
+ };
+ Dependencies: {
+ [key: string]: string;
+ };
+ "Experimental Flags": {
+ [key: string]: unknown;
+ };
+ Locale: string;
+ OS: string;
+ "OS Version": string;
+ "Optional Dependencies": {
+ [key: string]: string;
+ };
+ Processor: string;
+ "Python Version": string;
+ editable: boolean;
+ location: string;
+ marimo: string;
+ };
+ };
+ };
+ };
+ };
+ put?: never;
+ post?: never;
+ delete?: never;
+ options?: never;
+ head?: never;
+ patch?: never;
+ trace?: never;
+ };
"/api/export/auto_export/html": {
parameters: {
query?: never;
diff --git a/tests/_cli/test_envinfo.py b/tests/_cli/test_envinfo.py
index 590802532e..dc3fbe54e5 100644
--- a/tests/_cli/test_envinfo.py
+++ b/tests/_cli/test_envinfo.py
@@ -1,9 +1,12 @@
# Copyright 2026 Marimo. All rights reserved.
from __future__ import annotations
+from pathlib import Path
+
from marimo._cli.envinfo import (
get_system_info,
)
+from marimo._utils.diagnostics import abbreviate_home
def test_get_node_version() -> None:
@@ -37,3 +40,38 @@ def test_get_system_info() -> None:
assert "Binaries" in system_info
assert "Dependencies" in system_info
assert "Experimental Flags" in system_info
+
+
+def test_abbreviate_home() -> None:
+ assert (
+ abbreviate_home(
+ "/Users/example/.venv/lib/python3.12/site-packages/marimo",
+ home=Path("/Users/example"),
+ )
+ == "~/.venv/lib/python3.12/site-packages/marimo"
+ )
+
+
+def test_abbreviate_home_does_not_touch_other_paths() -> None:
+ assert (
+ abbreviate_home(
+ "/nix/store/marimo",
+ home=Path("/Users/example"),
+ )
+ == "/nix/store/marimo"
+ )
+
+
+def test_abbreviate_home_when_home_undeterminable(monkeypatch) -> None:
+ def raise_runtime_error() -> Path:
+ raise RuntimeError("Could not determine home directory")
+
+ monkeypatch.setattr(Path, "home", raise_runtime_error)
+ assert abbreviate_home("/some/path/marimo") == "/some/path/marimo"
+
+
+def test_get_system_info_can_redact_location() -> None:
+ raw = get_system_info(redact_home=False)
+ redacted = get_system_info(redact_home=True)
+ assert raw.keys() == redacted.keys()
+ assert redacted["location"] == abbreviate_home(raw["location"])
diff --git a/tests/_server/api/endpoints/test_health.py b/tests/_server/api/endpoints/test_health.py
index e7b969a9f4..58114b9b2a 100644
--- a/tests/_server/api/endpoints/test_health.py
+++ b/tests/_server/api/endpoints/test_health.py
@@ -149,6 +149,37 @@ def test_read_code(client: TestClient) -> None:
assert response.json()["active"] == 1
+def test_environment_requires_edit_auth(client: TestClient) -> None:
+ response = client.get("/api/environment")
+ assert response.status_code == 401, response.text
+
+
+def test_environment(client: TestClient) -> None:
+ expected = {
+ "marimo": "1.2.3",
+ "editable": False,
+ "location": "~/.venv/site-packages/marimo",
+ "OS": "Darwin",
+ "OS Version": "25.0",
+ "Processor": "arm",
+ "Python Version": "3.12.9",
+ "Locale": "en_US",
+ "Binaries": {"Browser": "--", "Node": "v22", "uv": "0.11"},
+ "Dependencies": {"click": "8.4.2"},
+ "Optional Dependencies": {"pandas": "3.0.0"},
+ "Experimental Flags": {},
+ }
+ with patch(
+ "marimo._server.api.endpoints.health.get_system_info",
+ return_value=expected,
+ ) as get_info:
+ response = client.get("/api/environment", headers=token_header())
+
+ assert response.status_code == 200, response.text
+ assert response.json() == expected
+ get_info.assert_called_once_with(redact_home=True)
+
+
def test_usage_without_psutil(client: TestClient) -> None:
"""psutil may not be available on all platforms (e.g. Android/Termux)."""
import sys
diff --git a/tests/_utils/test_diagnostics.py b/tests/_utils/test_diagnostics.py
new file mode 100644
index 0000000000..2d116adc5e
--- /dev/null
+++ b/tests/_utils/test_diagnostics.py
@@ -0,0 +1,45 @@
+# Copyright 2026 Marimo. All rights reserved.
+from __future__ import annotations
+
+import locale
+
+from marimo._utils.diagnostics import get_default_locale
+
+
+def test_get_default_locale_uses_default_category(monkeypatch):
+ """LC_ALL is not a valid getlocale category and must not be queried.
+
+ On some platforms getlocale(LC_ALL) raises; on others it returns a
+ mangled composite like "C/C". Either way the reported locale is wrong.
+ """
+ calls: list[int | None] = []
+
+ def fake_getlocale(category=locale.LC_CTYPE):
+ calls.append(category)
+ if category == locale.LC_ALL:
+ raise TypeError("category LC_ALL is not supported")
+ return ("en_US", "UTF-8")
+
+ monkeypatch.setattr(locale, "getlocale", fake_getlocale)
+
+ assert get_default_locale() == "en_US"
+ assert locale.LC_ALL not in calls
+
+
+def test_get_default_locale_falls_back_to_env(monkeypatch):
+ monkeypatch.setattr(locale, "getlocale", lambda *_: (None, None))
+ monkeypatch.delattr(locale, "LC_MESSAGES", raising=False)
+ for var in ("LC_ALL", "LC_MESSAGES", "LANG", "LANGUAGE"):
+ monkeypatch.delenv(var, raising=False)
+ monkeypatch.setenv("LANG", "fr_FR.UTF-8")
+
+ assert get_default_locale() == "fr_FR"
+
+
+def test_get_default_locale_returns_placeholder_when_unknown(monkeypatch):
+ monkeypatch.setattr(locale, "getlocale", lambda *_: (None, None))
+ monkeypatch.delattr(locale, "LC_MESSAGES", raising=False)
+ for var in ("LC_ALL", "LC_MESSAGES", "LANG", "LANGUAGE"):
+ monkeypatch.delenv(var, raising=False)
+
+ assert get_default_locale() == "--"