A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
improvement: allow for different backends (#5187)
Myles Scolnicka5e0296cf51a
diff --git a/frontend/src/components/chat/chat-panel.tsx b/frontend/src/components/chat/chat-panel.tsxindex 3fb291b24b..09c34a5b96 100644--- a/frontend/src/components/chat/chat-panel.tsx+++ b/frontend/src/components/chat/chat-panel.tsx@@ -34,8 +34,6 @@ import { useChat } from "@ai-sdk/react";import { PromptInput } from "../editor/ai/add-cell-with-ai";import type { ReactCodeMirrorRef } from "@uiw/react-codemirror";import { Tooltip, TooltipProvider } from "../ui/tooltip";-import { asURL } from "@/utils/url";-import { API } from "@/core/network/api";import { cn } from "@/utils/cn";import { MarkdownRenderer } from "./markdown-renderer";import { Logger } from "@/utils/Logger";@@ -50,6 +48,7 @@ import { PanelEmptyState } from "../editor/chrome/panels/empty-state";import { CopyClipboardIcon } from "../icons/copy-icon";import { timeAgo } from "@/utils/dates";import { ReasoningAccordion } from "./reasoning-accordion";+import { useRuntimeManager } from "@/core/runtime/config";interface ChatHeaderProps {onNewChat: () => void;@@ -276,6 +275,7 @@ const ChatPanelBody = () => {const scrollContainerRef = useRef<HTMLDivElement>(null);const messagesEndRef = useRef<HTMLDivElement>(null);const { theme } = useTheme();+ const runtimeManager = useRuntimeManager();const {messages,@@ -303,8 +303,8 @@ const ChatPanelBody = () => {keepLastMessageOnError: true,// Throttle the messages and data updates to 100msexperimental_throttle: 100,- api: asURL("api/ai/chat").toString(),- headers: API.headers(),+ api: runtimeManager.getAiURL("chat").toString(),+ headers: runtimeManager.headers(),experimental_prepareRequestBody: (options) => {return {...options,diff --git a/frontend/src/components/data-table/__tests__/chart-spec-model.test.ts b/frontend/src/components/data-table/__tests__/chart-spec-model.test.tsindex e5835b5192..b64885a213 100644--- a/frontend/src/components/data-table/__tests__/chart-spec-model.test.ts+++ b/frontend/src/components/data-table/__tests__/chart-spec-model.test.ts@@ -1,8 +1,18 @@/* Copyright 2024 Marimo. All rights reserved. */-import { describe, it, expect } from "vitest";+import { describe, it, expect, vi } from "vitest";import { ColumnChartSpecModel } from "../chart-spec-model";import type { ColumnHeaderStats, ColumnName, FieldTypes } from "../types";+// Mock the runtime config+vi.mock("@/core/runtime/config", () => ({+ asRemoteURL: vi.fn((path: string) => {+ if (path.startsWith("http")) {+ return new URL(path);+ }+ return new URL(path, "http://localhost:8080/");+ }),+}));+describe("ColumnChartSpecModel", () => {const mockData = "http://example.com/data.json";const mockFieldTypes: FieldTypes = {@@ -136,4 +146,98 @@ describe("ColumnChartSpecModel", () => {expect(model.getHeaderSummary("a").spec).toMatchSnapshot();});});++ describe("file URL handling", () => {+ it("should handle marimo file URLs with ./@file prefix", () => {+ const model = new ColumnChartSpecModel(+ "./@file/data.csv",+ mockFieldTypes,+ mockStats,+ { includeCharts: true },+ );++ const summary = model.getHeaderSummary("date");+ expect(summary.spec).toBeDefined();+ // @ts-expect-error accessing internal dataSpec+ expect(model.dataSpec?.url).toBe("http://localhost:8080/@file/data.csv");+ });++ it("should handle marimo file URLs with /@file prefix", () => {+ const model = new ColumnChartSpecModel(+ "/@file/data.csv",+ mockFieldTypes,+ mockStats,+ { includeCharts: true },+ );++ const summary = model.getHeaderSummary("date");+ expect(summary.spec).toBeDefined();+ // @ts-expect-error accessing internal dataSpec+ expect(model.dataSpec?.url).toBe("http://localhost:8080/@file/data.csv");+ });++ it("should handle absolute HTTP URLs", () => {+ const model = new ColumnChartSpecModel(+ "https://external.com/data.csv",+ mockFieldTypes,+ mockStats,+ { includeCharts: true },+ );++ const summary = model.getHeaderSummary("date");+ expect(summary.spec).toBeDefined();+ // @ts-expect-error accessing internal dataSpec+ expect(model.dataSpec?.url).toBeUndefined();+ });++ it("should handle data URLs", () => {+ const dataUrl = "data:text/csv;base64,YSxiLGMKMSwyLDMKNCw1LDY=";+ const model = new ColumnChartSpecModel(+ dataUrl,+ mockFieldTypes,+ mockStats,+ { includeCharts: true },+ );++ const summary = model.getHeaderSummary("date");+ expect(summary.spec).toBeDefined();+ // Data URLs should be handled by parseCsvData, not as URL+ // @ts-expect-error accessing internal dataSpec+ expect(model.dataSpec?.values).toBeDefined();+ });++ it("should handle CSV string data", () => {+ const csvString = "a,b,c\n1,2,3\n4,5,6";+ const model = new ColumnChartSpecModel(+ csvString,+ mockFieldTypes,+ mockStats,+ { includeCharts: true },+ );++ const summary = model.getHeaderSummary("date");+ expect(summary.spec).toBeDefined();+ // CSV strings should be parsed, not treated as URLs+ // @ts-expect-error accessing internal dataSpec+ expect(model.dataSpec?.values).toBeDefined();+ });++ it("should handle array data", () => {+ const arrayData = [+ { a: 1, b: 2, c: 3 },+ { a: 4, b: 5, c: 6 },+ ];+ const model = new ColumnChartSpecModel(+ arrayData,+ mockFieldTypes,+ mockStats,+ { includeCharts: true },+ );++ const summary = model.getHeaderSummary("date");+ expect(summary.spec).toBeDefined();+ // @ts-expect-error accessing internal dataSpec+ expect(model.dataSpec?.values).toEqual(arrayData);+ });+ });});diff --git a/frontend/src/components/data-table/chart-spec-model.tsx b/frontend/src/components/data-table/chart-spec-model.tsxindex 80ed123d43..77d0b25940 100644--- a/frontend/src/components/data-table/chart-spec-model.tsx+++ b/frontend/src/components/data-table/chart-spec-model.tsx@@ -2,10 +2,10 @@import type { TopLevelFacetedUnitSpec } from "@/plugins/impl/data-explorer/queries/types";import { mint, orange, slate } from "@radix-ui/colors";import type { ColumnHeaderStats, FieldTypes, ColumnName } from "./types";-import { asURL } from "@/utils/url";import { parseCsvData } from "@/plugins/impl/vega/loader";import { logNever } from "@/utils/assertNever";import type { TopLevelSpec } from "vega-lite";+import { asRemoteURL } from "@/core/runtime/config";// We rely on vega's built-in binning to determine bar widths.const MAX_BAR_HEIGHT = 20; // px@@ -44,7 +44,7 @@ export class ColumnChartSpecModel<T> {if (typeof this.data === "string") {if (this.data.startsWith("./@file") || this.data.startsWith("/@file")) {this.dataSpec = {- url: asURL(this.data).href,+ url: asRemoteURL(this.data).href,};this.sourceName = "source_0";} else if (this.data.startsWith("data:text/csv;base64,")) {diff --git a/frontend/src/components/editor/ai/add-cell-with-ai.tsx b/frontend/src/components/editor/ai/add-cell-with-ai.tsxindex 0ddd7e6496..2c44af3fca 100644--- a/frontend/src/components/editor/ai/add-cell-with-ai.tsx+++ b/frontend/src/components/editor/ai/add-cell-with-ai.tsx@@ -4,7 +4,6 @@ import { cn } from "@/utils/cn";import { Button } from "@/components/ui/button";import { ChevronsUpDown, Loader2Icon, SparklesIcon, XIcon } from "lucide-react";import { toast } from "@/components/ui/use-toast";-import { API } from "@/core/network/api";import { prettyError } from "@/utils/errors";import { useCompletion } from "ai/react";import ReactCodeMirror, {@@ -15,7 +14,6 @@ import ReactCodeMirror, {} from "@uiw/react-codemirror";import { Prec } from "@codemirror/state";import { customPythonLanguageSupport } from "@/core/codemirror/language/languages/python";-import { asURL } from "@/utils/url";import { useMemo, useState } from "react";import { useAtom, useAtomValue } from "jotai";import {@@ -45,6 +43,7 @@ import {getVariableMentionCompletions,} from "./completions";import useEvent from "react-use-event-hook";+import { useRuntimeManager } from "@/core/runtime/config";const pythonExtensions = [customPythonLanguageSupport(),@@ -68,6 +67,7 @@ export const AddCellWithAI: React.FC<{const [completionBody, setCompletionBody] = useState<object>({});const [language, setLanguage] = useAtom(languageAtom);const { theme } = useTheme();+ const runtimeManager = useRuntimeManager();const {completion,@@ -78,8 +78,8 @@ export const AddCellWithAI: React.FC<{setInput,handleSubmit,} = useCompletion({- api: asURL("api/ai/completion").toString(),- headers: API.headers(),+ api: runtimeManager.getAiURL("completion").toString(),+ headers: runtimeManager.headers(),streamProtocol: "text",// Throttle the messages and data updates to 100msexperimental_throttle: 100,diff --git a/frontend/src/components/editor/ai/ai-completion-editor.tsx b/frontend/src/components/editor/ai/ai-completion-editor.tsxindex 314508e614..1449a913a7 100644--- a/frontend/src/components/editor/ai/ai-completion-editor.tsx+++ b/frontend/src/components/editor/ai/ai-completion-editor.tsx@@ -2,7 +2,6 @@import React, { useEffect, useState } from "react";import CodeMirrorMerge from "react-codemirror-merge";import { useCompletion } from "@ai-sdk/react";-import { API } from "@/core/network/api";import { EditorView } from "@codemirror/view";import { customPythonLanguageSupport } from "@/core/codemirror/language/languages/python";import { Button } from "@/components/ui/button";@@ -19,12 +18,12 @@ import { includeOtherCellsAtom } from "@/core/ai/state";import { Checkbox } from "@/components/ui/checkbox";import { getCodes } from "@/core/codemirror/copilot/getCodes";import { useTheme } from "@/theme/useTheme";-import { asURL } from "@/utils/url";import type { LanguageAdapterType } from "@/core/codemirror/language/types";import { PromptInput } from "./add-cell-with-ai";import { getAICompletionBody } from "./completion-utils";import type { ReactCodeMirrorRef } from "@uiw/react-codemirror";import { selectAllText } from "@/core/codemirror/utils";+import { useRuntimeManager } from "@/core/runtime/config";const Original = CodeMirrorMerge.Original;const Modified = CodeMirrorMerge.Modified;@@ -68,6 +67,8 @@ export const AiCompletionEditor: React.FC<Props> = ({includeOtherCellsAtom,);+ const runtimeManager = useRuntimeManager();+const {completion,input,@@ -77,8 +78,8 @@ export const AiCompletionEditor: React.FC<Props> = ({setInput,handleSubmit,} = useCompletion({- api: asURL("api/ai/completion").toString(),- headers: API.headers(),+ api: runtimeManager.getAiURL("completion").toString(),+ headers: runtimeManager.headers(),initialInput: initialPrompt,streamProtocol: "text",// Throttle the messages and data updates to 100msdiff --git a/frontend/src/components/editor/chrome/wrapper/footer-items/backend-status.tsx b/frontend/src/components/editor/chrome/wrapper/footer-items/backend-status.tsxindex eeaef6922b..753836f0bb 100644--- a/frontend/src/components/editor/chrome/wrapper/footer-items/backend-status.tsx+++ b/frontend/src/components/editor/chrome/wrapper/footer-items/backend-status.tsx@@ -1,30 +1,100 @@/* Copyright 2024 Marimo. All rights reserved. */import { Spinner } from "@/components/icons/spinner";-import { Tooltip } from "@/components/ui/tooltip";import { connectionAtom } from "@/core/network/connection";import { WebSocketState } from "@/core/websocket/types";+import { useRuntimeManager } from "@/core/runtime/config";import { useAtomValue } from "jotai";import { startCase } from "lodash-es";-import { CheckCircle2Icon, PowerOffIcon } from "lucide-react";+import { CheckCircle2Icon, PowerOffIcon, AlertCircleIcon } from "lucide-react";import type React from "react";+import { useInterval } from "@/hooks/useInterval";+import { FooterItem } from "../footer-item";+import { useAsyncData } from "@/hooks/useAsyncData";++const CHECK_HEALTH_INTERVAL_MS = 30_000;export const BackendConnection: React.FC = () => {const connection = useAtomValue(connectionAtom).state;+ const runtime = useRuntimeManager();++ const { loading, error, data, reload } = useAsyncData(async () => {+ if (connection !== WebSocketState.OPEN) {+ return;+ }++ try {+ const isHealthy = await runtime.isHealthy();+ return {+ isHealthy,+ lastChecked: new Date(),+ error: undefined,+ };+ } catch (error) {+ return {+ isHealthy: false,+ lastChecked: new Date(),+ error: error instanceof Error ? error.message : "Unknown error",+ };+ }+ }, [runtime, connection]);++ useInterval(reload, {+ delayMs:+ connection === WebSocketState.OPEN ? CHECK_HEALTH_INTERVAL_MS : null,+ whenVisible: true,+ });++ const getStatusInfo = () => {+ const baseStatus = startCase(connection.toLowerCase());+ const healthInfo = data?.lastChecked+ ? data.isHealthy+ ? "✓ Healthy"+ : "✗ Unhealthy"+ : "Health: Unknown";++ const errorInfo = error ? `Error: ${error}` : "";++ return [baseStatus, healthInfo, errorInfo].filter(Boolean).join("\n");+ };++ const getStatusIcon = () => {+ if (loading || connection === WebSocketState.CONNECTING) {+ return <Spinner size="small" />;+ }++ if (connection === WebSocketState.CLOSING) {+ return <Spinner className="text-destructive" size="small" />;+ }++ if (connection === WebSocketState.OPEN) {+ if (data?.isHealthy) {+ return <CheckCircle2Icon className="w-4 h-4 text-[var(--green-9)]" />;+ }+ if (data?.lastChecked) {+ return <AlertCircleIcon className="w-4 h-4 text-[var(--yellow-9)]" />;+ }+ return <CheckCircle2Icon className="w-4 h-4" />;+ }++ return <PowerOffIcon className="w-4 h-4 text-red-500" />;+ };return (- <Tooltip delayDuration={200} content={startCase(connection.toLowerCase())}>- <div className="px-2">- {connection === WebSocketState.OPEN && (- <CheckCircle2Icon className="w-4 h-4" />- )}- {connection === WebSocketState.CLOSED && (- <PowerOffIcon className="w-4 h-4" />- )}- {connection === WebSocketState.CONNECTING && <Spinner size="small" />}- {connection === WebSocketState.CLOSING && (- <Spinner className="text-destructive" size="small" />- )}- </div>- </Tooltip>+ <FooterItem+ tooltip={+ <div className="text-sm whitespace-pre-line">+ {getStatusInfo()}+ {connection === WebSocketState.OPEN && (+ <div className="mt-2 text-xs text-muted-foreground">+ Click to refresh health status+ </div>+ )}+ </div>+ }+ selected={false}+ onClick={reload}+ >+ {getStatusIcon()}+ </FooterItem>);};diff --git a/frontend/src/components/terminal/terminal.tsx b/frontend/src/components/terminal/terminal.tsxindex ce75967e43..7f8d5827d8 100644--- a/frontend/src/components/terminal/terminal.tsx+++ b/frontend/src/components/terminal/terminal.tsx@@ -5,7 +5,7 @@ import { AttachAddon } from "@xterm/addon-attach";import { FitAddon } from "@xterm/addon-fit";import "@xterm/xterm/css/xterm.css";import "./xterm.css";-import { resolveToWsUrl } from "@/core/websocket/createWsUrl";+import { useRuntimeManager } from "@/core/runtime/config";const TerminalComponent: React.FC<{visible: boolean;@@ -25,6 +25,7 @@ const TerminalComponent: React.FC<{return { terminal: term, fitAddon };});const [initialized, setInitialized] = React.useState(false);+ const runtimeManager = useRuntimeManager();// Websocket ConnectionuseEffect(() => {@@ -32,7 +33,7 @@ const TerminalComponent: React.FC<{return;}- const socket = new WebSocket(resolveToWsUrl("terminal/ws"));+ const socket = new WebSocket(runtimeManager.getTerminalWsURL());const attachAddon = new AttachAddon(socket);terminal.loadAddon(attachAddon);diff --git a/frontend/src/core/codemirror/ai/request.ts b/frontend/src/core/codemirror/ai/request.tsindex a41c2f24dc..e787623de6 100644--- a/frontend/src/core/codemirror/ai/request.ts+++ b/frontend/src/core/codemirror/ai/request.ts@@ -1,7 +1,6 @@/* Copyright 2024 Marimo. All rights reserved. */-import { API } from "@/core/network/api";-import { asURL } from "@/utils/url";+import { getRuntimeManager } from "@/core/runtime/config";import type { LanguageAdapterType } from "../language/types";import type { AiCompletionRequest } from "@/core/network/types";@@ -26,17 +25,22 @@ ${opts.selection}${opts.codeAfter}`.trim();- const response = await fetch(asURL("api/ai/completion").toString(), {- method: "POST",- headers: API.headers(),- body: JSON.stringify({- prompt: opts.prompt,- code: codeWithReplacement,- selectedText: opts.selection,- includeOtherCode: "",- language: opts.language,- } satisfies AiCompletionRequest),- });+ const runtimeManager = getRuntimeManager();++ const response = await fetch(+ runtimeManager.getAiURL("completion").toString(),+ {+ method: "POST",+ headers: runtimeManager.headers(),+ body: JSON.stringify({+ prompt: opts.prompt,+ code: codeWithReplacement,+ selectedText: opts.selection,+ includeOtherCode: "",+ language: opts.language,+ } satisfies AiCompletionRequest),+ },+ );const firstLineIndent = opts.selection.match(/^\s*/)?.[0] || "";diff --git a/frontend/src/core/codemirror/copilot/client.ts b/frontend/src/core/codemirror/copilot/client.tsindex 9046897c74..4d78a2d5f3 100644--- a/frontend/src/core/codemirror/copilot/client.ts+++ b/frontend/src/core/codemirror/copilot/client.ts@@ -8,8 +8,8 @@ import type { JSONRPCRequestData } from "@open-rpc/client-js/build/Request";import { waitForEnabledCopilot } from "./state";import { Logger } from "@/utils/Logger";import { toast } from "@/components/ui/use-toast";-import { resolveToWsUrl } from "@/core/websocket/createWsUrl";import { waitForConnectionOpen } from "@/core/network/connection";+import { getRuntimeManager } from "@/core/runtime/config";// Dummy file for the copilot language serverexport const COPILOT_FILENAME = "/__marimo_copilot__.py";@@ -27,19 +27,23 @@ export const createWSTransport = once(() => {*/class LazyWebsocketTransport extends Transport {private delegate: WebSocketTransport | undefined;- private readonly WS_URL = resolveToWsUrl("lsp/copilot");constructor() {super();this.delegate = undefined;}+ private getWsUrl(): string {+ const runtimeManager = getRuntimeManager();+ return runtimeManager.getLSPURL("copilot").toString();+ }+private async tryConnect(retries = 3, delayMs = 1000): Promise<void> {for (let attempt = 1; attempt <= retries; attempt++) {try {// Create delegate, if it doesn't existif (!this.delegate) {- this.delegate = new WebSocketTransport(this.WS_URL);+ this.delegate = new WebSocketTransport(this.getWsUrl());}await this.delegate.connect();Logger.log("Copilot#connect: Connected successfully");diff --git a/frontend/src/core/codemirror/language/languages/python.ts b/frontend/src/core/codemirror/language/languages/python.tsindex 055d7338b4..85364212cb 100644--- a/frontend/src/core/codemirror/language/languages/python.ts+++ b/frontend/src/core/codemirror/language/languages/python.ts@@ -27,7 +27,6 @@ import {languageServerWithClient,documentUri,} from "@marimo-team/codemirror-languageserver";-import { resolveToWsUrl } from "@/core/websocket/createWsUrl";import { WebSocketTransport } from "@open-rpc/client-js";import { NotebookLanguageServerClient } from "../../lsp/notebook-lsp";import { once } from "@/utils/once";@@ -41,9 +40,13 @@ import { openFile } from "@/core/network/requests";import { Logger } from "@/utils/Logger";import { CellDocumentUri } from "../../lsp/types";import { hasCapability } from "@/core/config/capabilities";+import { getRuntimeManager } from "@/core/runtime/config";const pylspTransport = once(() => {- const transport = new WebSocketTransport(resolveToWsUrl("/lsp/pylsp"));+ const runtimeManager = getRuntimeManager();+ const transport = new WebSocketTransport(+ runtimeManager.getLSPURL("pylsp").toString(),+ );return transport;});diff --git a/frontend/src/core/codemirror/rtc/extension.ts b/frontend/src/core/codemirror/rtc/extension.tsindex 3c3ceb7ffb..a02b4f21b6 100644--- a/frontend/src/core/codemirror/rtc/extension.ts+++ b/frontend/src/core/codemirror/rtc/extension.ts@@ -5,7 +5,6 @@ import type { CellId } from "@/core/cells/ids";import { isWasm } from "@/core/wasm/utils";import type { Extension } from "@codemirror/state";import ReconnectingWebSocket from "partysocket/ws";-import { createWsUrl } from "@/core/websocket/createWsUrl";import { getSessionId } from "@/core/kernel/session";import { once } from "@/utils/once";import { loroSyncAnnotation, loroSyncPlugin } from "./loro/sync";@@ -38,6 +37,7 @@ import {import { invariant } from "@/utils/invariant";import { isEqual } from "lodash-es";import { getInitialAppMode } from "@/core/mode";+import { getRuntimeManager } from "@/core/runtime/config";const logger = Logger.get("rtc");const awarenessLogger = logger.get("awareness").disabled();@@ -73,7 +73,8 @@ const awareness = new Awareness<AwarenessState>(doc.peerIdStr);const getWs = once(() => {logger.debug("creating websocket");- const url = createWsUrl(getSessionId()).replace("/ws", "/ws_sync");+ const runtimeManager = getRuntimeManager();+ const url = runtimeManager.getWsSyncURL(getSessionId()).toString();// Create the websocket, but don't connect it yetconst ws = new ReconnectingWebSocket(url, undefined, {diff --git a/frontend/src/core/network/api.ts b/frontend/src/core/network/api.tsindex 2ce5f9615a..1971758a45 100644--- a/frontend/src/core/network/api.ts+++ b/frontend/src/core/network/api.ts@@ -1,17 +1,8 @@/* Copyright 2024 Marimo. All rights reserved. */-import { once } from "@/utils/once";import { Logger } from "../../utils/Logger";-import { getSessionId } from "../kernel/session";import { createMarimoClient } from "@marimo-team/marimo-api";-import { store } from "@/core/state/jotai";-import { serverTokenAtom } from "@/core/meta/state";-import { assertExists } from "@/utils/assertExists";--const getServerTokenOnce = once(() => {- const token = store.get(serverTokenAtom);- assertExists(token, "internal-error: server token not found");- return token;-});+import { getRuntimeManager } from "../runtime/config";+import type { RuntimeManager } from "../runtime/runtime";function getBaseUriWithoutQueryParams(): string {// Remove query params and hash@@ -100,10 +91,8 @@ export const API = {});},headers() {- return {- "Marimo-Session-Id": getSessionId(),- "Marimo-Server-Token": getServerTokenOnce(),- };+ const runtimeManager = getRuntimeManager();+ return runtimeManager.headers();},handleResponse: <T>(response: {data?: T | undefined;@@ -128,19 +117,21 @@ export const API = {},};-export const marimoClient = createMarimoClient({- // eslint-disable-next-line ssr-friendly/no-dom-globals-in-module-scope- baseUrl:- typeof document === "undefined"- ? undefined- : getBaseUriWithoutQueryParams(),-});+export function createClientWithRuntimeManager(runtimeManager: RuntimeManager) {+ const marimoClient = createMarimoClient({+ baseUrl: runtimeManager.httpURL.toString(),+ });-marimoClient.use({- onRequest: (req) => {- for (const [key, value] of Object.entries(API.headers())) {- req.headers.set(key, value);- }- return req;- },-});+ marimoClient.use({+ onRequest: (req) => {+ const headers = runtimeManager.headers();++ for (const [key, value] of Object.entries(headers)) {+ req.headers.set(key, value);+ }+ return req;+ },+ });++ return marimoClient;+}diff --git a/frontend/src/core/network/requests-network.ts b/frontend/src/core/network/requests-network.tsindex f59467578b..1457d24e6a 100644--- a/frontend/src/core/network/requests-network.ts+++ b/frontend/src/core/network/requests-network.ts@@ -1,47 +1,55 @@/* Copyright 2024 Marimo. All rights reserved. */-import { API, marimoClient } from "./api";++import { getRuntimeManager } from "../runtime/config";+import { API, createClientWithRuntimeManager } from "./api";import { waitForConnectionOpen } from "./connection";import type { RunRequests, EditRequests } from "./types";+import { once } from "lodash-es";const { handleResponse, handleResponseReturnNull } = API;export function createNetworkRequests(): EditRequests & RunRequests {+ const getClient = once(() => {+ const runtimeManager = getRuntimeManager();+ return createClientWithRuntimeManager(runtimeManager);+ });+return {sendComponentValues: (request) => {- return marimoClient+ return getClient().POST("/api/kernel/set_ui_element_value", {body: request,}).then(handleResponseReturnNull);},sendModelValue: (request) => {- return marimoClient+ return getClient().POST("/api/kernel/set_model_value", {body: request,}).then(handleResponseReturnNull);},sendRestart: () => {- return marimoClient+ return getClient().POST("/api/kernel/restart_session").then(handleResponseReturnNull);},syncCellIds: (request) => {- return marimoClient+ return getClient().POST("/api/kernel/sync/cell_ids", {body: request,}).then(handleResponseReturnNull);},sendRename: (request) => {- return marimoClient+ return getClient().POST("/api/kernel/rename", {body: request,}).then(handleResponseReturnNull);},sendSave: (request) => {- return marimoClient+ return getClient().POST("/api/kernel/save", {body: request,parseAs: "text",@@ -49,7 +57,7 @@ export function createNetworkRequests(): EditRequests & RunRequests {.then(handleResponseReturnNull);},sendCopy: (request) => {- return marimoClient+ return getClient().POST("/api/kernel/copy", {body: request,parseAs: "text",@@ -57,66 +65,66 @@ export function createNetworkRequests(): EditRequests & RunRequests {.then(handleResponseReturnNull);},sendFormat: (request) => {- return marimoClient+ return getClient().POST("/api/kernel/format", {body: request,}).then(handleResponse);},sendInterrupt: () => {- return marimoClient+ return getClient().POST("/api/kernel/interrupt").then(handleResponseReturnNull);},sendShutdown: () => {- return marimoClient+ return getClient().POST("/api/kernel/shutdown").then(handleResponseReturnNull);},sendRun: (request) => {- return marimoClient+ return getClient().POST("/api/kernel/run", {body: request,}).then(handleResponseReturnNull);},sendRunScratchpad: (request) => {- return marimoClient+ return getClient().POST("/api/kernel/scratchpad/run", {body: request,}).then(handleResponseReturnNull);},sendInstantiate: (request) => {- return marimoClient+ return getClient().POST("/api/kernel/instantiate", {body: request,}).then(handleResponseReturnNull);},sendDeleteCell: (request) => {- return marimoClient+ return getClient().POST("/api/kernel/delete", {body: request,}).then(handleResponseReturnNull);},sendCodeCompletionRequest: (request) => {- return marimoClient+ return getClient().POST("/api/kernel/code_autocomplete", {body: request,}).then(handleResponseReturnNull);},saveUserConfig: (request) => {- return marimoClient+ return getClient().POST("/api/kernel/save_user_config", {body: request,}).then(handleResponseReturnNull);},saveAppConfig: (request) => {- return marimoClient+ return getClient().POST("/api/kernel/save_app_config", {body: request,parseAs: "text",@@ -124,71 +132,71 @@ export function createNetworkRequests(): EditRequests & RunRequests {.then(handleResponseReturnNull);},saveCellConfig: (request) => {- return marimoClient+ return getClient().POST("/api/kernel/set_cell_config", {body: request,}).then(handleResponseReturnNull);},sendFunctionRequest: (request) => {- return marimoClient+ return getClient().POST("/api/kernel/function_call", {body: request,}).then(handleResponseReturnNull);},sendStdin: (request) => {- return marimoClient+ return getClient().POST("/api/kernel/stdin", {body: request,}).then(handleResponseReturnNull);},sendInstallMissingPackages: (request) => {- return marimoClient+ return getClient().POST("/api/kernel/install_missing_packages", {body: request,}).then(handleResponseReturnNull);},readCode: () => {- return marimoClient.POST("/api/kernel/read_code").then(handleResponse);+ return getClient().POST("/api/kernel/read_code").then(handleResponse);},readSnippets: () => {- return marimoClient+ return getClient().GET("/api/documentation/snippets").then(handleResponse);},previewDatasetColumn: (request) => {- return marimoClient+ return getClient().POST("/api/datasources/preview_column", {body: request,}).then(handleResponseReturnNull);},previewSQLTable: (request) => {- return marimoClient+ return getClient().POST("/api/datasources/preview_sql_table", {body: request,}).then(handleResponseReturnNull);},previewSQLTableList: (request) => {- return marimoClient+ return getClient().POST("/api/datasources/preview_sql_table_list", {body: request,}).then(handleResponseReturnNull);},previewDataSourceConnection: (request) => {- return marimoClient+ return getClient().POST("/api/datasources/preview_datasource_connection", {body: request,}).then(handleResponseReturnNull);},openFile: async (request) => {- await marimoClient+ await getClient().POST("/api/files/open", {body: request,})@@ -196,81 +204,81 @@ export function createNetworkRequests(): EditRequests & RunRequests {return null;},getUsageStats: () => {- return marimoClient.GET("/api/usage").then(handleResponse);+ return getClient().GET("/api/usage").then(handleResponse);},sendPdb: (request) => {- return marimoClient+ return getClient().POST("/api/kernel/pdb/pm", {body: request,}).then(handleResponseReturnNull);},sendListFiles: (request) => {- return marimoClient+ return getClient().POST("/api/files/list_files", {body: request,}).then(handleResponse);},sendCreateFileOrFolder: (request) => {- return marimoClient+ return getClient().POST("/api/files/create", {body: request,}).then(handleResponse);},sendDeleteFileOrFolder: (request) => {- return marimoClient+ return getClient().POST("/api/files/delete", {body: request,}).then(handleResponse);},sendRenameFileOrFolder: (request) => {- return marimoClient+ return getClient().POST("/api/files/move", {body: request,}).then(handleResponse);},sendUpdateFile: (request) => {- return marimoClient+ return getClient().POST("/api/files/update", {body: request,}).then(handleResponse);},sendFileDetails: (request) => {- return marimoClient+ return getClient().POST("/api/files/file_details", {body: request,}).then(handleResponse);},openTutorial: (request) => {- return marimoClient+ return getClient().POST("/api/home/tutorial/open", {body: request,}).then(handleResponse);},getRecentFiles: () => {- return marimoClient.POST("/api/home/recent_files").then(handleResponse);+ return getClient().POST("/api/home/recent_files").then(handleResponse);},getWorkspaceFiles: (request) => {- return marimoClient+ return getClient().POST("/api/home/workspace_files", {body: request,}).then(handleResponse);},getRunningNotebooks: () => {- return marimoClient+ return getClient().POST("/api/home/running_notebooks").then(handleResponse);},shutdownSession: (request) => {- return marimoClient+ return getClient().POST("/api/home/shutdown_session", {body: request,})@@ -283,7 +291,7 @@ export function createNetworkRequests(): EditRequests & RunRequests {) {request.assetUrl = window.location.origin;}- return marimoClient+ return getClient().POST("/api/export/html", {body: request,parseAs: "text",@@ -291,7 +299,7 @@ export function createNetworkRequests(): EditRequests & RunRequests {.then(handleResponse);},exportAsMarkdown: async (request) => {- return marimoClient+ return getClient().POST("/api/export/markdown", {body: request,parseAs: "text",@@ -299,35 +307,35 @@ export function createNetworkRequests(): EditRequests & RunRequests {.then(handleResponse);},autoExportAsHTML: async (request) => {- return marimoClient+ return getClient().POST("/api/export/auto_export/html", {body: request,}).then(handleResponseReturnNull);},autoExportAsMarkdown: async (request) => {- return marimoClient+ return getClient().POST("/api/export/auto_export/markdown", {body: request,}).then(handleResponseReturnNull);},autoExportAsIPYNB: async (request) => {- return marimoClient+ return getClient().POST("/api/export/auto_export/ipynb", {body: request,}).then(handleResponseReturnNull);},addPackage: (request) => {- return marimoClient+ return getClient().POST("/api/packages/add", {body: request,}).then(handleResponse);},removePackage: (request) => {- return marimoClient+ return getClient().POST("/api/packages/remove", {body: request,})@@ -336,19 +344,19 @@ export function createNetworkRequests(): EditRequests & RunRequests {getPackageList: async () => {// If the sidebar is already open, it may try to load before the session has been initializedawait waitForConnectionOpen();- return marimoClient.GET("/api/packages/list").then(handleResponse);+ return getClient().GET("/api/packages/list").then(handleResponse);},listSecretKeys: async (request) => {// If the sidebar is already open, it may try to load before the session has been initializedawait waitForConnectionOpen();- return marimoClient+ return getClient().POST("/api/secrets/keys", {body: request,}).then(handleResponseReturnNull);},writeSecret: async (request) => {- return marimoClient+ return getClient().POST("/api/secrets/create", {body: request,})diff --git a/frontend/src/core/runtime/__tests__/config.test.ts b/frontend/src/core/runtime/__tests__/config.test.tsnew file mode 100644index 0000000000..5ee2204400--- /dev/null+++ b/frontend/src/core/runtime/__tests__/config.test.ts@@ -0,0 +1,161 @@+/* Copyright 2024 Marimo. All rights reserved. */++import { beforeEach, describe, expect, it, type Mocked, vi } from "vitest";+import { asRemoteURL, getRuntimeManager } from "../config";+import { store } from "@/core/state/jotai";+import type { RuntimeManager } from "../runtime";++// Mock the store+vi.mock("@/core/state/jotai", () => ({+ store: {+ get: vi.fn(),+ },+}));++// Mock the RuntimeManager+vi.mock("../runtime", () => ({+ RuntimeManager: vi.fn(),+}));++// Mock jotai hooks+vi.mock("jotai", () => ({+ atom: vi.fn((value) => ({ init: value })),+ useAtomValue: vi.fn(),+}));++const mockedStore = store as Mocked<typeof store>;++describe("runtime config", () => {+ const mockRuntimeManager = {+ httpURL: new URL("http://localhost:8080"),+ } as RuntimeManager;++ beforeEach(() => {+ vi.clearAllMocks();+ mockedStore.get.mockReturnValue(mockRuntimeManager);+ });++ describe("asRemoteURL", () => {+ it("should return URL as-is for absolute HTTP URLs", () => {+ const result = asRemoteURL("https://example.com/data.csv");+ expect(result.toString()).toBe("https://example.com/data.csv");+ });++ it("should return URL as-is for absolute HTTPS URLs", () => {+ const result = asRemoteURL("https://example.com/api/data");+ expect(result.toString()).toBe("https://example.com/api/data");+ });++ it("should resolve relative paths against runtime manager base URL", () => {+ const result = asRemoteURL("/api/data");+ expect(result.toString()).toBe("http://localhost:8080/api/data");+ });++ it("should handle relative paths without leading slash", () => {+ const result = asRemoteURL("api/data");+ expect(result.toString()).toBe("http://localhost:8080/api/data");+ });++ it("should handle file paths", () => {+ const result = asRemoteURL("/@file/data.csv");+ expect(result.toString()).toBe("http://localhost:8080/@file/data.csv");+ });++ it("should handle data URLs", () => {+ const dataURL = "data:text/csv;base64,YSxiLGMKMSwyLDM=";+ const result = asRemoteURL(dataURL);+ expect(result.toString()).toBe(dataURL);+ });++ it("should handle empty paths", () => {+ const result = asRemoteURL("");+ expect(result.toString()).toBe("http://localhost:8080/");+ });++ it("should handle query parameters", () => {+ const result = asRemoteURL("/api/data?param=value");+ expect(result.toString()).toBe(+ "http://localhost:8080/api/data?param=value",+ );+ });++ it("should handle fragments", () => {+ const result = asRemoteURL("/api/data#section");+ expect(result.toString()).toBe("http://localhost:8080/api/data#section");+ });++ it("should handle complex relative paths", () => {+ const result = asRemoteURL("./api/../data/file.csv");+ expect(result.toString()).toBe("http://localhost:8080/data/file.csv");+ });++ it("should handle URLs with different base paths", () => {+ const customRuntimeManager = {+ httpURL: new URL("https://custom.marimo.io/app/"),+ } as RuntimeManager;+ mockedStore.get.mockReturnValue(customRuntimeManager);++ const result = asRemoteURL("/api/data");+ expect(result.toString()).toBe("https://custom.marimo.io/api/data");+ });+ });++ describe("getRuntimeManager", () => {+ it("should return runtime manager from store", () => {+ const result = getRuntimeManager();+ expect(result).toBe(mockRuntimeManager);+ expect(store.get).toHaveBeenCalled();+ });+ });++ describe("edge cases", () => {+ it("should handle malformed URLs gracefully", () => {+ expect(() => asRemoteURL("not a url with spaces")).not.toThrow();+ });++ it("should handle URLs with unusual protocols", () => {+ const result = asRemoteURL("ftp://example.com/file.txt");+ expect(result.toString()).toBe("ftp://example.com/file.txt");+ });++ it("should handle localhost URLs", () => {+ const result = asRemoteURL("http://localhost:3000/api");+ expect(result.toString()).toBe("http://localhost:3000/api");+ });++ it("should handle IP address URLs", () => {+ const result = asRemoteURL("http://192.168.1.1:8080/api");+ expect(result.toString()).toBe("http://192.168.1.1:8080/api");+ });+ });++ describe("runtime manager integration", () => {+ it("should work with different runtime manager base URLs", () => {+ const testCases = [+ {+ baseURL: "http://localhost:8080",+ path: "/api",+ expected: "http://localhost:8080/api",+ },+ {+ baseURL: "https://marimo.app",+ path: "/data",+ expected: "https://marimo.app/data",+ },+ {+ baseURL: "http://192.168.1.1:3000",+ path: "files",+ expected: "http://192.168.1.1:3000/files",+ },+ ];++ testCases.forEach(({ baseURL, path, expected }) => {+ const customManager = { httpURL: new URL(baseURL) } as RuntimeManager;+ mockedStore.get.mockReturnValue(customManager);++ const result = asRemoteURL(path);+ expect(result.toString()).toBe(expected);+ });+ });+ });+});diff --git a/frontend/src/core/runtime/__tests__/createWsUrl.test.ts b/frontend/src/core/runtime/__tests__/createWsUrl.test.tsnew file mode 100644index 0000000000..5de8d2b5a1--- /dev/null+++ b/frontend/src/core/runtime/__tests__/createWsUrl.test.ts@@ -0,0 +1,44 @@+/* Copyright 2024 Marimo. All rights reserved. */++import { describe, expect, it } from "vitest";+import { KnownQueryParams } from "@/core/constants";+import { RuntimeManager } from "../runtime";+import type { SessionId } from "@/core/kernel/session";++describe("RuntimeManager.getWsURL", () => {+ it("should return a URL with the wss protocol when the baseURI uses https", () => {+ const runtime = new RuntimeManager({ url: "https://marimo.app/" });+ const sessionId = "1234" as SessionId;+ const url = runtime.getWsURL(sessionId);+ expect(url.toString()).toBe("wss://marimo.app/ws?session_id=1234");+ expect(url.searchParams.get(KnownQueryParams.sessionId)).toBe(sessionId);+ });++ it("should return a URL with the ws protocol when the baseURI uses http", () => {+ const runtime = new RuntimeManager({ url: "http://marimo.app/" });+ const sessionId = "1234" as SessionId;+ const url = runtime.getWsURL(sessionId);+ expect(url.toString()).toBe("ws://marimo.app/ws?session_id=1234");+ expect(url.searchParams.get(KnownQueryParams.sessionId)).toBe(sessionId);+ });++ it("should work with nested baseURI", () => {+ const runtime = new RuntimeManager({ url: "http://marimo.app/nested/" });+ const sessionId = "1234" as SessionId;+ const url = runtime.getWsURL(sessionId);+ expect(url.toString()).toBe("ws://marimo.app/nested/ws?session_id=1234");+ expect(url.searchParams.get(KnownQueryParams.sessionId)).toBe(sessionId);+ });++ it("should work with nested baseURI and query params", () => {+ const runtime = new RuntimeManager({+ url: "http://marimo.app/nested/?foo=bar",+ });+ const sessionId = "1234" as SessionId;+ const url = runtime.getWsURL(sessionId);+ expect(url.toString()).toBe(+ "ws://marimo.app/nested/ws?foo=bar&session_id=1234",+ );+ expect(url.searchParams.get(KnownQueryParams.sessionId)).toBe(sessionId);+ });+});diff --git a/frontend/src/core/runtime/__tests__/runtime.test.ts b/frontend/src/core/runtime/__tests__/runtime.test.tsnew file mode 100644index 0000000000..8ff36510e4--- /dev/null+++ b/frontend/src/core/runtime/__tests__/runtime.test.ts@@ -0,0 +1,280 @@+/* Copyright 2024 Marimo. All rights reserved. */++import { describe, expect, it, vi } from "vitest";+import { RuntimeManager } from "../runtime";+import type { RuntimeConfig } from "../types";+import type { SessionId } from "@/core/kernel/session";++// Mock the session module+vi.mock("@/core/kernel/session", () => ({+ getSessionId: () => "test-session-id" as SessionId,+}));++// Mock the Logger module+vi.mock("@/utils/Logger", () => ({+ Logger: {+ error: vi.fn(),+ },+}));++describe("RuntimeManager", () => {+ const mockConfig: RuntimeConfig = {+ url: "https://example.com",+ authToken: "test-token",+ };++ const mockConfigWithoutToken: RuntimeConfig = {+ url: "http://localhost:8080",+ };++ describe("constructor", () => {+ it("should create instance with config", () => {+ const runtime = new RuntimeManager(mockConfig);+ expect(runtime).toBeInstanceOf(RuntimeManager);+ });+ });++ describe("httpURL", () => {+ it("should return base URL as URL object", () => {+ const runtime = new RuntimeManager(mockConfig);+ const url = runtime.httpURL;+ expect(url).toBeInstanceOf(URL);+ expect(url.toString()).toBe("https://example.com/");+ });++ it("should handle URLs without trailing slash", () => {+ const runtime = new RuntimeManager({ url: "https://example.com/path" });+ expect(runtime.httpURL.toString()).toBe("https://example.com/path");+ });+ });++ describe("getWsURL", () => {+ it("should return WebSocket URL with session ID for https", () => {+ const runtime = new RuntimeManager(mockConfig);+ const sessionId = "1234" as SessionId;+ const url = runtime.getWsURL(sessionId);++ expect(url.protocol).toBe("wss:");+ expect(url.hostname).toBe("example.com");+ expect(url.pathname).toBe("/ws");+ expect(url.searchParams.get("session_id")).toBe(sessionId);+ });++ it("should return WebSocket URL for http", () => {+ const runtime = new RuntimeManager(mockConfigWithoutToken);+ const sessionId = "1234" as SessionId;+ const url = runtime.getWsURL(sessionId);++ expect(url.protocol).toBe("ws:");+ expect(url.hostname).toBe("localhost");+ expect(url.port).toBe("8080");+ expect(url.searchParams.get("session_id")).toBe(sessionId);+ });++ it("should preserve existing query params", () => {+ const runtime = new RuntimeManager({ url: "http://example.com?foo=bar" });+ const sessionId = "1234" as SessionId;+ const url = runtime.getWsURL(sessionId);++ expect(url.searchParams.get("foo")).toBe("bar");+ expect(url.searchParams.get("session_id")).toBe(sessionId);+ });+ });++ describe("getWsSyncURL", () => {+ it("should return WebSocket Sync URL", () => {+ const runtime = new RuntimeManager(mockConfig);+ const sessionId = "1234" as SessionId;+ const url = runtime.getWsSyncURL(sessionId);++ expect(url.protocol).toBe("wss:");+ expect(url.pathname).toBe("/ws_sync");+ expect(url.searchParams.get("session_id")).toBe(sessionId);+ });+ });++ describe("getTerminalWsURL", () => {+ it("should return terminal WebSocket URL", () => {+ const runtime = new RuntimeManager(mockConfig);+ const url = runtime.getTerminalWsURL();++ expect(url.protocol).toBe("wss:");+ expect(url.pathname).toBe("/terminal/ws");+ });+ });++ describe("getLSPURL", () => {+ it("should return pylsp URL", () => {+ const runtime = new RuntimeManager(mockConfig);+ const url = runtime.getLSPURL("pylsp");++ expect(url.protocol).toBe("wss:");+ expect(url.pathname).toBe("/lsp/pylsp");+ });++ it("should return copilot URL", () => {+ const runtime = new RuntimeManager(mockConfig);+ const url = runtime.getLSPURL("copilot");++ expect(url.protocol).toBe("wss:");+ expect(url.pathname).toBe("/lsp/copilot");+ });+ });++ describe("getAiURL", () => {+ it("should return AI completion URL", () => {+ const runtime = new RuntimeManager(mockConfig);+ const url = runtime.getAiURL("completion");++ expect(url.protocol).toBe("https:");+ expect(url.pathname).toBe("/api/ai/completion");+ });++ it("should return AI chat URL", () => {+ const runtime = new RuntimeManager(mockConfig);+ const url = runtime.getAiURL("chat");++ expect(url.protocol).toBe("https:");+ expect(url.pathname).toBe("/api/ai/chat");+ });+ });++ describe("healthURL", () => {+ it("should return health check URL", () => {+ const runtime = new RuntimeManager(mockConfig);+ const url = runtime.healthURL();++ expect(url.protocol).toBe("https:");+ expect(url.pathname).toBe("/health");+ });+ });++ describe("isHealthy", () => {+ it("should return true for successful health check", async () => {+ global.fetch = vi.fn().mockResolvedValue({+ ok: true,+ });++ const runtime = new RuntimeManager(mockConfig);+ const result = await runtime.isHealthy();++ expect(result).toBe(true);+ expect(fetch).toHaveBeenCalledWith("https://example.com/health");+ });++ it("should return false for failed health check", async () => {+ global.fetch = vi.fn().mockResolvedValue({+ ok: false,+ });++ const runtime = new RuntimeManager(mockConfig);+ const result = await runtime.isHealthy();++ expect(result).toBe(false);+ });++ it("should return false and log error when fetch throws", async () => {+ const error = new Error("Network error");+ global.fetch = vi.fn().mockRejectedValue(error);++ const runtime = new RuntimeManager(mockConfig);+ const result = await runtime.isHealthy();++ expect(result).toBe(false);+ });+ });++ describe("waitForHealthy", () => {+ it("should resolve immediately if healthy", async () => {+ const runtime = new RuntimeManager(mockConfig);+ vi.spyOn(runtime, "isHealthy").mockResolvedValue(true);++ await expect(runtime.waitForHealthy()).resolves.toBeUndefined();+ });++ it("should retry and eventually succeed", async () => {+ const runtime = new RuntimeManager(mockConfig);+ const healthySpy = vi+ .spyOn(runtime, "isHealthy")+ .mockResolvedValueOnce(false)+ .mockResolvedValueOnce(false)+ .mockResolvedValueOnce(true);++ await expect(runtime.waitForHealthy()).resolves.toBeUndefined();+ expect(healthySpy).toHaveBeenCalledTimes(3);+ });++ it.skip("should throw after max retries", async () => {+ const runtime = new RuntimeManager(mockConfig);+ vi.spyOn(runtime, "isHealthy").mockResolvedValue(false);++ await expect(runtime.waitForHealthy()).rejects.toThrow(+ "Failed to connect after 5 retries",+ );+ });+ });++ describe("headers", () => {+ it("should return headers with auth token", () => {+ const runtime = new RuntimeManager(mockConfig);+ const headers = runtime.headers();++ expect(headers).toMatchInlineSnapshot(`+ {+ "Authorization": "Bearer test-token",+ "Marimo-Server-Token": "",+ "Marimo-Session-Id": "test-session-id",+ }+ `);+ });++ it("should return headers with empty token when not provided", () => {+ const runtime = new RuntimeManager(mockConfigWithoutToken);+ const headers = runtime.headers();++ expect(headers).toEqual({+ "Marimo-Session-Id": "test-session-id",+ "Marimo-Server-Token": "",+ });+ });+ });++ describe("edge cases", () => {+ it("should handle URLs with nested paths", () => {+ const runtime = new RuntimeManager({+ url: "https://example.com/nested/path/",+ });+ const wsUrl = runtime.getWsURL("test" as SessionId);+ const aiUrl = runtime.getAiURL("completion");++ expect(wsUrl.pathname).toBe("/nested/path/ws");+ expect(aiUrl.pathname).toBe("/nested/path/api/ai/completion");+ });++ it("should handle URLs with query parameters and fragments", () => {+ const runtime = new RuntimeManager({+ url: "https://example.com/path?existing=param#fragment",+ });+ const wsUrl = runtime.getWsURL("test" as SessionId);++ expect(wsUrl.searchParams.get("existing")).toBe("param");+ expect(wsUrl.searchParams.get("session_id")).toBe("test");+ // Fragment should not be preserved in WebSocket URLs+ expect(wsUrl.hash).toBe("");+ });++ it("should throw for invalid URLs", () => {+ expect(() => {+ new RuntimeManager({ url: "not-a-url" });+ }).toThrow();+ });++ it("should handle http to ws conversion correctly", () => {+ const httpRuntime = new RuntimeManager({ url: "http://localhost" });+ const httpsRuntime = new RuntimeManager({ url: "https://localhost" });++ expect(httpRuntime.getWsURL("test" as SessionId).protocol).toBe("ws:");+ expect(httpsRuntime.getWsURL("test" as SessionId).protocol).toBe("wss:");+ });+ });+});diff --git a/frontend/src/core/runtime/config.ts b/frontend/src/core/runtime/config.tsnew file mode 100644index 0000000000..1d4c310798--- /dev/null+++ b/frontend/src/core/runtime/config.ts@@ -0,0 +1,40 @@+/* Copyright 2024 Marimo. All rights reserved. */+import { atom, useAtomValue } from "jotai";+import type { RuntimeConfig } from "./types";+import { RuntimeManager } from "./runtime";+import { store } from "../state/jotai";++function getBaseURI(): string {+ const url = new URL(document.baseURI);+ url.search = "";+ url.hash = "";+ return url.toString();+}++export const DEFAULT_RUNTIME_CONFIG: RuntimeConfig = {+ url: getBaseURI(),+};++export const runtimeConfigAtom = atom<RuntimeConfig>(DEFAULT_RUNTIME_CONFIG);+const runtimeManagerAtom = atom<RuntimeManager>((get) => {+ const config = get(runtimeConfigAtom);+ return new RuntimeManager(config);+});++export function useRuntimeManager(): RuntimeManager {+ return useAtomValue(runtimeManagerAtom);+}++/**+ * Prefer to use useRuntimeManager instead of this function.+ */+export function getRuntimeManager(): RuntimeManager {+ return store.get(runtimeManagerAtom);+}++export function asRemoteURL(path: string): URL {+ if (path.startsWith("http")) {+ return new URL(path);+ }+ return new URL(path, getRuntimeManager().httpURL.toString());+}diff --git a/frontend/src/core/runtime/runtime.ts b/frontend/src/core/runtime/runtime.tsnew file mode 100644index 0000000000..f2d00ebcfb--- /dev/null+++ b/frontend/src/core/runtime/runtime.ts@@ -0,0 +1,128 @@+/* Copyright 2024 Marimo. All rights reserved. */+import { invariant } from "@/utils/invariant";+import type { RuntimeConfig } from "./types";+import { urlJoin } from "./utils";+import { Logger } from "@/utils/Logger";+import { getSessionId, type SessionId } from "../kernel/session";+import { KnownQueryParams } from "../constants";++export class RuntimeManager {+ constructor(private config: RuntimeConfig) {+ // Validate the URL on construction+ try {+ new URL(this.config.url);+ } catch (error) {+ throw new Error(+ `Invalid runtime URL: ${this.config.url}. ${error instanceof Error ? error.message : "Unknown error"}`,+ );+ }+ }++ /**+ * The base URL of the runtime.+ */+ get httpURL(): URL {+ return new URL(this.config.url);+ }++ /**+ * The WebSocket URL of the runtime.+ */+ getWsURL(sessionId: SessionId): URL {+ const wsUrl = asWsUrl(this.config.url);+ const baseUrl = new URL(wsUrl);+ const searchParams = new URLSearchParams(baseUrl.search);+ searchParams.set(KnownQueryParams.sessionId, sessionId);+ return new URL(+ urlJoin(wsUrl.split("?")[0], `ws?${searchParams.toString()}`),+ );+ }++ /**+ * The WebSocket Sync URL of the runtime, for real-time updates.+ */+ getWsSyncURL(sessionId: SessionId): URL {+ const wsSyncUrl = asWsUrl(this.config.url);+ const baseUrl = new URL(wsSyncUrl);+ const searchParams = new URLSearchParams(baseUrl.search);+ searchParams.set(KnownQueryParams.sessionId, sessionId);+ return new URL(+ urlJoin(wsSyncUrl.split("?")[0], `ws_sync?${searchParams.toString()}`),+ );+ }++ /**+ * The WebSocket URL of the terminal.+ */+ getTerminalWsURL(): URL {+ const terminalUrl = asWsUrl(this.config.url);+ return new URL(urlJoin(terminalUrl, "terminal/ws"));+ }++ /**+ * The URL of the copilot server.+ */+ getLSPURL(lsp: "pylsp" | "copilot"): URL {+ const lspUrl = asWsUrl(this.config.url);+ return new URL(urlJoin(lspUrl, `lsp/${lsp}`));+ }++ getAiURL(path: "completion" | "chat"): URL {+ return new URL(urlJoin(this.httpURL.toString(), `api/ai/${path}`));+ }++ /**+ * The URL of the health check endpoint.+ */+ healthURL(): URL {+ return new URL(urlJoin(this.httpURL.toString(), "health"));+ }++ async isHealthy(): Promise<boolean> {+ try {+ const response = await fetch(this.healthURL().toString());+ return response.ok;+ } catch (error) {+ Logger.error("Failed to check health", error);+ return false;+ }+ }++ /**+ * Wait for the runtime to be healthy.+ * @throws if the runtime is not healthy after 5 retries+ */+ async waitForHealthy(): Promise<void> {+ let retries = 0;+ const maxRetries = 5;+ const baseDelay = 1000;++ while (!(await this.isHealthy())) {+ if (retries >= maxRetries) {+ throw new Error("Failed to connect after 5 retries");+ }+ const delay = baseDelay * 2 ** retries;+ await new Promise((resolve) => setTimeout(resolve, delay));+ retries++;+ }+ }++ headers(): Record<string, string> {+ const headers: Record<string, string> = {+ "Marimo-Session-Id": getSessionId(),+ "Marimo-Server-Token": this.config.serverToken ?? "",+ };++ if (this.config.authToken) {+ headers.Authorization = `Bearer ${this.config.authToken}`;+ }++ return headers;+ }+}++function asWsUrl(url: string): string {+ invariant(url.startsWith("http"), "URL must start with http");+ // Replace the protocol http with ws+ return url.replace(/^http/, "ws");+}diff --git a/frontend/src/core/runtime/types.ts b/frontend/src/core/runtime/types.tsnew file mode 100644index 0000000000..9c6ce2d304--- /dev/null+++ b/frontend/src/core/runtime/types.ts@@ -0,0 +1,7 @@+/* Copyright 2024 Marimo. All rights reserved. */++export interface RuntimeConfig {+ url: string;+ serverToken?: string; // Skew protection token+ authToken?: string; // API key or JWT token for remote backend+}diff --git a/frontend/src/core/runtime/utils.ts b/frontend/src/core/runtime/utils.tsnew file mode 100644index 0000000000..5073e0e8a0--- /dev/null+++ b/frontend/src/core/runtime/utils.ts@@ -0,0 +1,9 @@+/* Copyright 2024 Marimo. All rights reserved. */++import { Strings } from "@/utils/strings";++export function urlJoin(first: string, second: string): string {+ first = Strings.withoutTrailingSlash(first);+ second = Strings.withoutLeadingSlash(second);+ return `${first}/${second}`;+}diff --git a/frontend/src/core/websocket/__tests__/createWsUrl.test.ts b/frontend/src/core/websocket/__tests__/createWsUrl.test.tsdeleted file mode 100644index 6c57a57002..0000000000--- a/frontend/src/core/websocket/__tests__/createWsUrl.test.ts+++ /dev/null@@ -1,69 +0,0 @@-/* Copyright 2024 Marimo. All rights reserved. */--import { describe, expect, it } from "vitest";-import { createWsUrl } from "../createWsUrl";-import { KnownQueryParams } from "@/core/constants";--describe("createWsUrl", () => {- it("should return a URL with the wss protocol when the baseURI uses https", () => {- // Mock the document.baseURI to return an https URL- Object.defineProperty(document, "baseURI", {- value: "https://marimo.app/",- writable: true,- });-- const sessionId = "1234";- const result = createWsUrl(sessionId);- const url = new URL(result, document.baseURI);- expect(url.toString()).toBe("wss://marimo.app/ws?session_id=1234");- expect(url.searchParams.get(KnownQueryParams.sessionId)).toBe(sessionId);- });-- it("should return a URL with the ws protocol when the baseURI uses http", () => {- // Mock the document.baseURI to return an http URL- Object.defineProperty(document, "baseURI", {- value: "http://marimo.app/",- writable: true,- });-- const sessionId = "1234";- const result = createWsUrl(sessionId);- const url = new URL(result, document.baseURI);- expect(url.toString()).toBe("ws://marimo.app/ws?session_id=1234");- expect(url.searchParams.get(KnownQueryParams.sessionId)).toBe(sessionId);- });-- it("should work with nested baseURI", () => {- // Mock the document.baseURI to return an http URL- Object.defineProperty(document, "baseURI", {- value: "http://marimo.app/nested/",- writable: true,- });-- const sessionId = "1234";- const result = createWsUrl(sessionId);- const url = new URL(result, document.baseURI);- expect(url.toString()).toBe("ws://marimo.app/nested/ws?session_id=1234");- expect(url.searchParams.get(KnownQueryParams.sessionId)).toBe(sessionId);- });-- it("should work with nested baseURI and query params", () => {- // Mock the document.baseURI to return an http URL- Object.defineProperty(document, "baseURI", {- value: "http://marimo.app/nested/?foo=bar",- writable: true,- });- Object.defineProperty(window, "location", {- value: { search: "?foo=bar" },- writable: true,- });-- const sessionId = "1234";- const result = createWsUrl(sessionId);- const url = new URL(result, document.baseURI);- expect(url.toString()).toBe(- "ws://marimo.app/nested/ws?foo=bar&session_id=1234",- );- expect(url.searchParams.get(KnownQueryParams.sessionId)).toBe(sessionId);- });-});diff --git a/frontend/src/core/websocket/createWsUrl.ts b/frontend/src/core/websocket/createWsUrl.tsdeleted file mode 100644index 8ccd4ad809..0000000000--- a/frontend/src/core/websocket/createWsUrl.ts+++ /dev/null@@ -1,23 +0,0 @@-/* Copyright 2024 Marimo. All rights reserved. */-import { Strings } from "@/utils/strings";-import { KnownQueryParams } from "../constants";--export function createWsUrl(sessionId: string): string {- const searchParams = new URLSearchParams(window.location.search);- searchParams.set(KnownQueryParams.sessionId, sessionId);-- return resolveToWsUrl(`ws?${searchParams.toString()}`);-}--export function resolveToWsUrl(- relativeUrl: string,-): `ws://${string}` | `wss://${string}` {- if (relativeUrl.startsWith("ws:") || relativeUrl.startsWith("wss:")) {- return relativeUrl as `ws://${string}` | `wss://${string}`;- }- const baseUri = new URL(document.baseURI);- const protocol = baseUri.protocol === "https:" ? "wss:" : "ws:";- const host = baseUri.host;- const pathname = baseUri.pathname;- return `${protocol}//${host}${Strings.withoutTrailingSlash(pathname)}/${Strings.withoutLeadingSlash(relativeUrl)}`;-}diff --git a/frontend/src/core/websocket/useMarimoWebSocket.tsx b/frontend/src/core/websocket/useMarimoWebSocket.tsxindex 9f35007991..9dc2efa5ff 100644--- a/frontend/src/core/websocket/useMarimoWebSocket.tsx+++ b/frontend/src/core/websocket/useMarimoWebSocket.tsx@@ -26,7 +26,6 @@ import { jsonParseWithSpecialChar } from "@/utils/json/json-parser";import type { SessionId } from "../kernel/session";import { useBannersActions } from "../errors/state";import { useAlertActions } from "../alerts/state";-import { createWsUrl } from "./createWsUrl";import { useSetAppConfig } from "../config/config";import {handleCellOperation,@@ -55,6 +54,7 @@ import {isMessageWidgetState,MODEL_MANAGER,} from "@/plugins/impl/anywidget/model";+import { useRuntimeManager } from "../runtime/config";/*** WebSocket that connects to the Marimo kernel and handles incoming messages.@@ -83,6 +83,7 @@ export function useMarimoWebSocket(opts: {const { addPackageAlert } = useAlertActions();const setKioskMode = useSetAtom(kioskModeAtom);const setCapabilities = useSetAtom(capabilitiesAtom);+ const runtimeManager = useRuntimeManager();const handleMessage = (e: MessageEvent<JsonString<OperationMessage>>) => {const msg = jsonParseWithSpecialChar(e.data);@@ -275,7 +276,7 @@ export function useMarimoWebSocket(opts: {/*** Unique URL for this session.*/- url: createWsUrl(sessionId),+ url: runtimeManager.getWsURL(sessionId).toString(),/*** Open callback. Set the connection status to open.diff --git a/frontend/src/mount.tsx b/frontend/src/mount.tsxindex af9bead574..8a590e663f 100644--- a/frontend/src/mount.tsx+++ b/frontend/src/mount.tsx@@ -29,6 +29,10 @@ import {} from "@/core/meta/state";import { appConfigAtom, userConfigAtom } from "@/core/config/config";import { configOverridesAtom } from "@/core/config/config";+import {+ DEFAULT_RUNTIME_CONFIG,+ runtimeConfigAtom,+} from "./core/runtime/config";import { getMarimoCode } from "@/core/meta/globals";import type * as api from "@marimo-team/marimo-api";import { notebookAtom } from "./core/cells/cells";@@ -215,6 +219,14 @@ const mountOptionsSchema = z.object({.passthrough().transform((val) => val as api.Notebook["NotebookV1"]),]),++ /**+ * Runtime configs+ */+ runtimeConfig: z+ .array(z.object({ url: z.string() }))+ .nullish()+ .transform((val) => val ?? []),});function initStore(options: unknown) {@@ -261,6 +273,21 @@ function initStore(options: unknown) {store.set(userConfigAtom, parseUserConfig(parsedOptions.data.config));store.set(appConfigAtom, parseAppConfig(parsedOptions.data.appConfig));+ // Runtime config+ if (parsedOptions.data.runtimeConfig.length > 0) {+ const firstRuntimeConfig = parsedOptions.data.runtimeConfig[0];+ Logger.debug("⚡ Runtime URL", firstRuntimeConfig.url);+ store.set(runtimeConfigAtom, {+ ...firstRuntimeConfig,+ serverToken: parsedOptions.data.serverToken,+ });+ } else {+ store.set(runtimeConfigAtom, {+ ...DEFAULT_RUNTIME_CONFIG,+ serverToken: parsedOptions.data.serverToken,+ });+ }+// Session/notebookconst notebook = notebookStateFromSession(parsedOptions.data.session,diff --git a/frontend/src/plugins/impl/vega/fix-relative-url.ts b/frontend/src/plugins/impl/vega/fix-relative-url.tsindex 3bd784b825..c70b1db67e 100644--- a/frontend/src/plugins/impl/vega/fix-relative-url.ts+++ b/frontend/src/plugins/impl/vega/fix-relative-url.ts@@ -1,7 +1,6 @@/* Copyright 2024 Marimo. All rights reserved. */--import { asURL } from "@/utils/url";import type { VegaLiteSpec } from "./types";+import { asRemoteURL } from "@/core/runtime/config";/*** If the URL in the data-spec if relative, we need to fix it to be absolute,@@ -9,7 +8,7 @@ import type { VegaLiteSpec } from "./types";*/export function fixRelativeUrl(spec: VegaLiteSpec) {if (spec.data && "url" in spec.data) {- spec.data.url = asURL(spec.data.url).href;+ spec.data.url = asRemoteURL(spec.data.url).href;}return spec;}diff --git a/frontend/src/plugins/impl/vega/resolve-data.ts b/frontend/src/plugins/impl/vega/resolve-data.tsindex 633534e9d3..ec0660a8ea 100644--- a/frontend/src/plugins/impl/vega/resolve-data.ts+++ b/frontend/src/plugins/impl/vega/resolve-data.ts@@ -1,5 +1,5 @@/* Copyright 2024 Marimo. All rights reserved. */-import { asURL } from "@/utils/url";+import { vegaLoadData } from "./loader";import type {Field,@@ -9,6 +9,7 @@ import type {GenericFacetSpec,FacetedUnitSpec,} from "./types";+import { asRemoteURL } from "@/core/runtime/config";type AnySpec =| VegaLiteSpec@@ -75,7 +76,7 @@ export async function resolveVegaSpecData(// Parse URLlet url: URL;try {- url = asURL(spec.data.url);+ url = asRemoteURL(spec.data.url);} catch {return spec;}diff --git a/marimo/_cli/cli.py b/marimo/_cli/cli.pyindex 276936b5f2..777bfd7fce 100644--- a/marimo/_cli/cli.py+++ b/marimo/_cli/cli.py@@ -345,6 +345,14 @@ edit_help_msg = "\n".join(type=bool,help="Watch the file for changes and reload the code when saved in another editor.",)+ "--skew-protection/--no-skew-protection",+ is_flag=True,+ default=True,+ show_default=True,+ type=bool,+ help="Enable skew protection middleware to prevent version mismatch issues.",+)@click.argument("name",required=False,@@ -364,6 +372,7 @@ def edit(sandbox: Optional[bool],profile_dir: Optional[str],watch: bool,+ skew_protection: bool,name: Optional[str],args: tuple[str, ...],) -> None:@@ -447,6 +456,7 @@ def edit(mode=SessionMode.EDIT,include_code=True,watch=watch,+ skew_protection=skew_protection,cli_args=parse_args(args),argv=list(args),auth_token=_resolve_token(token, token_password),@@ -544,6 +554,14 @@ new_help_msg = "\n".join(type=bool,help=sandbox_message,)+ "--skew-protection/--no-skew-protection",+ is_flag=True,+ default=True,+ show_default=True,+ type=bool,+ help="Enable skew protection middleware to prevent version mismatch issues.",+)@click.argument("prompt", required=False)def new(port: Optional[int],@@ -554,6 +572,7 @@ def new(token_password: Optional[str],base_url: str,sandbox: Optional[bool],+ skew_protection: bool,prompt: Optional[str],) -> None:if sandbox:@@ -625,6 +644,7 @@ def new(mode=SessionMode.EDIT,include_code=True,watch=False,+ skew_protection=skew_protection,cli_args={},argv=[],auth_token=_resolve_token(token, token_password),@@ -714,6 +734,14 @@ Example:"Otherwise, file watcher will poll the file every 1s."),)+ "--skew-protection/--no-skew-protection",+ is_flag=True,+ default=True,+ show_default=True,+ type=bool,+ help="Enable skew protection middleware to prevent version mismatch issues.",+)@click.option("--base-url",default="",@@ -760,6 +788,7 @@ def run(include_code: bool,session_ttl: int,watch: bool,+ skew_protection: bool,base_url: str,allow_origins: tuple[str, ...],redirect_console_to_browser: bool,@@ -813,6 +842,7 @@ def run(include_code=include_code,ttl_seconds=session_ttl,watch=watch,+ skew_protection=skew_protection,base_url=base_url,allow_origins=allow_origins,cli_args=parse_args(args),@@ -893,6 +923,14 @@ Recommended sequence:type=str,help=token_password_message,)+ "--skew-protection/--no-skew-protection",+ is_flag=True,+ default=True,+ show_default=True,+ type=bool,+ help="Enable skew protection middleware to prevent version mismatch issues.",+)@click.argument("name",required=True,@@ -905,6 +943,7 @@ def tutorial(headless: bool,token: bool,token_password: Optional[str],+ skew_protection: bool,name: Tutorial,) -> None:temp_dir = tempfile.TemporaryDirectory()@@ -921,6 +960,7 @@ def tutorial(include_code=True,headless=headless,watch=False,+ skew_protection=skew_protection,cli_args={},argv=[],auth_token=_resolve_token(token, token_password),diff --git a/marimo/_server/main.py b/marimo/_server/main.pyindex 00fc47e1c8..20de74608e 100644--- a/marimo/_server/main.py+++ b/marimo/_server/main.py@@ -52,6 +52,7 @@ def create_starlette_app(enable_auth: bool = True,allow_origins: Optional[tuple[str, ...]] = None,lsp_servers: Optional[list[LspServer]] = None,+ skew_protection: bool = True,) -> Starlette:final_middlewares: list[Middleware] = []@@ -85,11 +86,13 @@ def create_starlette_app(allow_methods=["*"],allow_headers=["*"],),- Middleware(SkewProtectionMiddleware),_create_mpl_proxy_middleware(),])+ if skew_protection:+ final_middlewares.append(Middleware(SkewProtectionMiddleware))+if lsp_servers is not None:final_middlewares.extend(_create_lsps_proxy_middleware(servers=lsp_servers)diff --git a/marimo/_server/start.py b/marimo/_server/start.pyindex ebdfa6a3fd..3fd27747ed 100644--- a/marimo/_server/start.py+++ b/marimo/_server/start.py@@ -88,6 +88,7 @@ def start(allow_origins: Optional[tuple[str, ...]] = None,auth_token: Optional[AuthToken],redirect_console_to_browser: bool,+ skew_protection: bool,) -> None:"""Start the server.@@ -178,6 +179,7 @@ def start(lsp_servers=list(lsp_composite_server.servers.values())if lsp_composite_server is not Noneelse None,+ skew_protection=skew_protection,)app.state.port = external_portdiff --git a/tests/_server/api/test_middleware.py b/tests/_server/api/test_middleware.pyindex 708ead3212..9de9a56e98 100644--- a/tests/_server/api/test_middleware.py+++ b/tests/_server/api/test_middleware.py@@ -109,6 +109,30 @@ def test_skew_protection(edit_app: Starlette) -> None:assert response.status_code == 401, response.text+def test_skew_protection_disabled() -> None:+ """Test that skew protection can be disabled via CLI flag"""+ app = create_starlette_app(base_url="", skew_protection=False)+ app.state.session_manager = get_mock_session_manager()+ app.state.session_manager.mode = SessionMode.EDIT+ app.state.config_manager = MarimoConfigManager(UserConfigManager())+ # Mock out the server+ uvicorn_server = uvicorn.Server(uvicorn.Config(app))+ uvicorn_server.servers = []+ app.state.server = uvicorn_server+ app.state.host = "localhost"+ app.state.port = 1234+ app.state.base_url = ""++ client = TestClient(app)++ # POST with an invalid skew protection token should succeed when disabled+ response = client.post(+ "/api/home/running_notebooks",+ headers=token_header("fake-token", "old-skew-id"),+ )+ assert response.status_code == 200, response.text++@pytest.fixturedef edit_app() -> Starlette:app = create_starlette_app(base_url="")