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
Pass cwd to agents from backend (#8491)
Shahmir Varqha73fc8f70bbf2
diff --git a/frontend/src/components/chat/acp/agent-panel.tsx b/frontend/src/components/chat/acp/agent-panel.tsxindex 81830ac844..3d7783e9dc 100644--- a/frontend/src/components/chat/acp/agent-panel.tsx+++ b/frontend/src/components/chat/acp/agent-panel.tsx@@ -60,11 +60,11 @@ import {import { toast } from "@/components/ui/use-toast";import { DelayMount } from "@/components/utils/delay-mount";import { useRequestClient } from "@/core/network/requests";-import { filenameAtom } from "@/core/saving/file-state";+import { cwdAtom, filenameAtom } from "@/core/saving/file-state";import { store } from "@/core/state/jotai";import { ErrorBanner } from "@/plugins/impl/common/error-banner";import { Functions } from "@/utils/functions";-import { Paths } from "@/utils/paths";+import { PathBuilder, Paths } from "@/utils/paths";import {AddContextButton,AttachFileButton,@@ -614,7 +614,11 @@ ChatContent.displayName = "ChatContent";const NO_WS_SET = "_skip_auto_connect_";-function getCwd() {+function getCwd(): string {+ const cwd = store.get(cwdAtom);+ if (cwd) {+ return cwd;+ }const filename = store.get(filenameAtom);if (!filename) {throw new Error(@@ -624,6 +628,21 @@ function getCwd() {return Paths.dirname(filename);}+function getAbsoluteFilename(): string {+ const filename = store.get(filenameAtom);+ if (!filename) {+ throw new Error(+ "Please save the notebook and refresh the browser to use the agent",+ );+ }+ const cwd = store.get(cwdAtom);+ if (cwd) {+ const builder = PathBuilder.guessDeliminator(cwd);+ return builder.join(cwd, String(Paths.basename(filename)));+ }+ return filename;+}+const AgentPanel: React.FC = () => {const [isLoading, setIsLoading] = useState(false);const [error, setError] = useState<Error | string | null>(null);@@ -862,8 +881,10 @@ const AgentPanel: React.FC = () => {setSessionState((prev) => updateSessionTitle(prev, prompt));}- const filename = store.get(filenameAtom);- if (!filename) {+ let absoluteFilename: string;+ try {+ absoluteFilename = getAbsoluteFilename();+ } catch {toast({title: "Notebook must be named",description: "Please name the notebook to use the agent",@@ -894,16 +915,16 @@ const AgentPanel: React.FC = () => {promptBlocks.push({type: "resource_link",- uri: filename,+ uri: absoluteFilename,mimeType: "text/x-python",- name: filename,+ name: absoluteFilename,},{type: "resource",resource: {uri: "marimo_rules.md",mimeType: "text/plain",- text: getAgentPrompt(filename),+ text: getAgentPrompt(absoluteFilename),},},);diff --git a/frontend/src/core/saving/file-state.ts b/frontend/src/core/saving/file-state.tsindex 4157bd7a3a..68e6866937 100644--- a/frontend/src/core/saving/file-state.ts+++ b/frontend/src/core/saving/file-state.ts@@ -9,6 +9,13 @@ import { getFilenameFromDOM } from "../dom/htmlUtils";*/export const filenameAtom = atom<string | null>(getFilenameFromDOM());+/**+ * Atom for storing the notebook's working directory (absolute path).+ * In directory mode, filenameAtom may be a relative display path;+ * this atom holds the absolute directory containing the notebook.+ */+export const cwdAtom = atom<string | null>(null);+/*** Set for static notebooks.*/diff --git a/frontend/src/mount.tsx b/frontend/src/mount.tsxindex 3368a73ff9..e836e07b2d 100644--- a/frontend/src/mount.tsx+++ b/frontend/src/mount.tsx@@ -36,7 +36,7 @@ import {DEFAULT_RUNTIME_CONFIG,runtimeConfigAtom,} from "./core/runtime/config";-import { codeAtom, filenameAtom } from "./core/saving/file-state";+import { codeAtom, cwdAtom, filenameAtom } from "./core/saving/file-state";import { store } from "./core/state/jotai";import { patchFetch, patchVegaLoader } from "./core/static/files";import {@@ -146,6 +146,10 @@ const mountOptionsSchema = z.object({Logger.warn("No filename provided, using fallback");return getFilenameFromDOM();}),+ /**+ * absolute working directory of the notebook+ */+ cwd: z.string().nullish().default(null),/*** notebook code*/@@ -282,6 +286,7 @@ function initStore(options: unknown) {// Filesstore.set(filenameAtom, parsedOptions.data.filename);+ store.set(cwdAtom, parsedOptions.data.cwd ?? null);store.set(codeAtom, parsedOptions.data.code);store.set(initialModeAtom, mode);diff --git a/marimo/_server/templates/templates.py b/marimo/_server/templates/templates.pyindex c865e17812..8d7ba2545c 100644--- a/marimo/_server/templates/templates.py+++ b/marimo/_server/templates/templates.py@@ -46,6 +46,7 @@ def json_script(data: Any) -> str:def _get_mount_config(*,filename: Optional[str],+ cwd: Optional[str] = None,mode: Literal["edit", "home", "read", "gallery"],server_token: SkewProtectionToken,user_config: MarimoConfig,@@ -63,6 +64,7 @@ def _get_mount_config(options: dict[str, Any] = {"filename": filename or "",+ "cwd": cwd or "","mode": mode,"version": version or get_version(),"server_token": str(server_token),@@ -81,6 +83,7 @@ def _get_mount_config(return """{{"filename": {filename},+ "cwd": {cwd},"mode": {mode},"version": {version},"serverToken": {server_token},@@ -251,10 +254,12 @@ def notebook_page_template(html = _replace_asset_urls(html, asset_url)+ cwd = os.path.dirname(filepath) if filepath else Nonehtml = html.replace(MOUNT_CONFIG_TEMPLATE,_get_mount_config(filename=filename,+ cwd=cwd,mode="read" if mode == SessionMode.RUN else "edit",server_token=server_token,user_config=user_config,@@ -343,6 +348,7 @@ def static_notebook_template(MOUNT_CONFIG_TEMPLATE,_get_mount_config(filename=filename,+ cwd=None, # We don't need the cwd for static notebooksmode="read",server_token=server_token,user_config=user_config,diff --git a/tests/_server/templates/snapshots/export1.txt b/tests/_server/templates/snapshots/export1.txtindex 4960aec3e6..d628e934ba 100644--- a/tests/_server/templates/snapshots/export1.txt+++ b/tests/_server/templates/snapshots/export1.txt@@ -56,6 +56,7 @@<script data-marimo="true">window.__MARIMO_MOUNT_CONFIG__ = {"filename": "notebook.py",+ "cwd": "","mode": "read","version": "0.0.0","serverToken": "token",diff --git a/tests/_server/templates/snapshots/export2.txt b/tests/_server/templates/snapshots/export2.txtindex 67ec275fbd..22288b4bc3 100644--- a/tests/_server/templates/snapshots/export2.txt+++ b/tests/_server/templates/snapshots/export2.txt@@ -56,6 +56,7 @@<script data-marimo="true">window.__MARIMO_MOUNT_CONFIG__ = {"filename": "",+ "cwd": "","mode": "read","version": "0.0.0","serverToken": "token",diff --git a/tests/_server/templates/snapshots/export3.txt b/tests/_server/templates/snapshots/export3.txtindex 524d867b40..1adec1aad5 100644--- a/tests/_server/templates/snapshots/export3.txt+++ b/tests/_server/templates/snapshots/export3.txt@@ -56,6 +56,7 @@<script data-marimo="true">window.__MARIMO_MOUNT_CONFIG__ = {"filename": "notebook.py",+ "cwd": "","mode": "read","version": "0.0.0","serverToken": "token",diff --git a/tests/_server/templates/snapshots/export4.txt b/tests/_server/templates/snapshots/export4.txtindex 3784693448..03ef22a988 100644--- a/tests/_server/templates/snapshots/export4.txt+++ b/tests/_server/templates/snapshots/export4.txt@@ -56,6 +56,7 @@<script data-marimo="true">window.__MARIMO_MOUNT_CONFIG__ = {"filename": "notebook.py",+ "cwd": "","mode": "read","version": "0.0.0","serverToken": "token",diff --git a/tests/_server/templates/snapshots/export5.txt b/tests/_server/templates/snapshots/export5.txtindex 004c3aff72..edfbc21b4d 100644--- a/tests/_server/templates/snapshots/export5.txt+++ b/tests/_server/templates/snapshots/export5.txt@@ -56,6 +56,7 @@<script data-marimo="true">window.__MARIMO_MOUNT_CONFIG__ = {"filename": "notebook.py",+ "cwd": "","mode": "read","version": "0.0.0","serverToken": "token",diff --git a/tests/_server/templates/snapshots/export6.txt b/tests/_server/templates/snapshots/export6.txtindex cb2f6178ae..f16e149ae8 100644--- a/tests/_server/templates/snapshots/export6.txt+++ b/tests/_server/templates/snapshots/export6.txt@@ -56,6 +56,7 @@<script data-marimo="true">window.__MARIMO_MOUNT_CONFIG__ = {"filename": "notebook.py",+ "cwd": "","mode": "read","version": "0.0.0","serverToken": "token",diff --git a/tests/_server/templates/test_templates.py b/tests/_server/templates/test_templates.pyindex 92dd52ee4c..ef6db064e6 100644--- a/tests/_server/templates/test_templates.py+++ b/tests/_server/templates/test_templates.py@@ -78,6 +78,27 @@ class TestNotebookPageTemplate(unittest.TestCase):assert str(self.server_token) in resultassert self.filename.name in resultassert "read" in result+ assert '"cwd": ""' in result+ _assert_no_leftover_replacements(result)++ def test_notebook_page_template_with_filepath(self) -> None:+ absolute_path = str(self.filename.resolve())+ expected_cwd = str(self.filename.resolve().parent)+ result = templates.notebook_page_template(+ html=self.html,+ base_url=self.base_url,+ user_config=self.user_config,+ config_overrides=self.config_overrides,+ server_token=self.server_token,+ app_config=self.app_config,+ filename=self.filename.name,+ filepath=absolute_path,+ mode=self.mode,+ )++ assert self.filename.name in result+ # json.dumps to match JSON-escaped backslashes on Windows paths+ assert f'"cwd": {json.dumps(expected_cwd)}' in result_assert_no_leftover_replacements(result)def test_notebook_page_template_no_filename(self) -> None:@@ -96,6 +117,7 @@ class TestNotebookPageTemplate(unittest.TestCase):assert str(self.server_token) in resultassert "<title>marimo</title>" in resultassert "read" in result+ assert '"cwd": ""' in result_assert_no_leftover_replacements(result)def test_notebook_page_template_edit_mode(self) -> None: