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
Resumable sessions (#654)
Myles Scolnickab3ba7800d4b
diff --git a/frontend/e2e-tests/py/shutdown.py b/frontend/e2e-tests/py/shutdown.pyindex a273d84362..8b4eed19f5 100644--- a/frontend/e2e-tests/py/shutdown.py+++ b/frontend/e2e-tests/py/shutdown.py@@ -1,12 +1,23 @@import marimo-__generated_with = "0.0.1"+__generated_with = "0.1.88"app = marimo.App()@app.celldef __():- print('123')+ import marimo as mo++ form = mo.ui.text().form()+ form+ return form, mo+++def __(form, mo):+ mo.stop(not form.value, "None")+ print(form.value[::-1])+ form.valuereturndiff --git a/frontend/e2e-tests/shutdown.spec.ts b/frontend/e2e-tests/shutdown.spec.tsindex f6fe6636d3..93610f78ff 100644--- a/frontend/e2e-tests/shutdown.spec.ts+++ b/frontend/e2e-tests/shutdown.spec.ts@@ -3,13 +3,47 @@ import { test, expect } from "@playwright/test";import { getAppUrl, startServer } from "../playwright.config";import { takeScreenshot } from "./helper";+test("can resume a session", async ({ page }) => {+ const appUrl = getAppUrl("shutdown.py");+ await page.goto(appUrl);++ await expect(page.getByText("None", { exact: true })).toBeVisible();+ // type in the form+ await page.locator("#output-Hbol").getByRole("textbox").fill("12345");+ // shift enter to run the form+ await page.keyboard.press("Meta+Enter");++ // wait for the output to appear+ let secondCell = await page.locator(".Cell").nth(1);+ await expect(secondCell.getByText("12345")).toBeVisible();+ await expect(secondCell.getByText("54321")).toBeVisible();++ // Refresh the page+ await page.reload();++ await expect(+ page.getByText("You have reconnected to an existing session.")+ ).toBeVisible();+ secondCell = await page.locator(".Cell").nth(1);+ await expect(page.getByText("12345")).toBeVisible();+ await expect(page.getByText("54321")).toBeVisible();+});++test("restart kernel", async ({ page }) => {+ const appUrl = getAppUrl("shutdown.py");+ await page.goto(appUrl);++ await page.getByTestId("notebook-menu-dropdown").click();+ await page.getByText("Restart kernel").click();+ await page.getByLabel("Confirm Restart").click();++ await expect(page.getByText("None", { exact: true })).toBeVisible();+});+test("shutdown shows disconnected text", async ({ page }) => {const appUrl = getAppUrl("shutdown.py");await page.goto(appUrl);await page.getByRole("button", { name: "Shutdown" }).click();- // TODO(akshayka): there's some kind of timing bug; just wait- // a small amount of time for now as a hack- await new Promise((resolve) => setTimeout(resolve, 100));// confirm shutdown on modalawait page.getByRole("button", { name: "Confirm Shutdown" }).click();@@ -23,8 +57,8 @@ test("shutdown shows disconnected text", async ({ page }) => {// when changes are made, recovery modal should be shownawait page.getByRole("textbox")- .filter({ hasText: "print('123')" })- .type("1234");+ .filter({ hasText: "import marimo" })+ .fill("1234");await page.getByRole("button", { name: "Save" }).click();await expect(page.getByText("Download unsaved changes?")).toHaveCount(1);diff --git a/frontend/package.json b/frontend/package.jsonindex 23963f7261..b9fce52bca 100644--- a/frontend/package.json+++ b/frontend/package.json@@ -116,7 +116,6 @@"ci": "CI=true run-s lint typecheck test build","start": "vite","dev": "vite",- "dev:msw": "VITE_MSW=true vite","build:watch": "vite build --watch --outDir ../marimo/_static","build": "vite build","build:library": "vite build -c vite.lib.config.ts && tsc --declaration --emitDeclarationOnly --declarationDir lib",@@ -174,7 +173,6 @@"eslint-plugin-vitest": "^0.3.20","jsdom": "^24.0.0","mock-socket": "^9.3.1",- "msw": "^1.3.2","npm-run-all2": "^5.0.0","postcss": "^8.4.33","prettier": "^2.8.8",@@ -189,8 +187,5 @@"vite": "^5.0.11","vite-tsconfig-paths": "^4.3.1","vitest": "^1.2.2"- },- "msw": {- "workerDirectory": "public"}}diff --git a/frontend/pnpm-lock.yaml b/frontend/pnpm-lock.yamlindex 0283df7c8b..4295f7dd34 100644--- a/frontend/pnpm-lock.yaml+++ b/frontend/pnpm-lock.yaml@@ -403,12 +403,9 @@ devDependencies:mock-socket:specifier: ^9.3.1version: 9.3.1- msw:- specifier: ^1.3.2- version: 1.3.2([email protected])npm-run-all2:specifier: ^5.0.0- version: 5.0.2+ version: 5.0.0postcss:specifier: ^8.4.33version: 8.4.33@@ -3062,30 +3059,6 @@ packages:react: 18.2.0dev: true- /@mswjs/[email protected]:- resolution: {integrity: sha512-mlN83YSrcFgk7Dm1Mys40DLssI1KdJji2CMKN8eOlBqsTADYzj2+jWzsANsUTFbxDMWPD5e9bfA1RGqBpS3O1g==}- engines: {node: '>=14'}- dependencies:- '@types/set-cookie-parser': 2.4.3- set-cookie-parser: 2.6.0- dev: true-- /@mswjs/[email protected]:- resolution: {integrity: sha512-N8x7eSLGcmUFNWZRxT1vsHvypzIRgQYdG0rJey/rZCy6zT/30qDt8Joj7FxzGNLSwXbeZqJOMqDurp7ra4hgbw==}- engines: {node: '>=14'}- dependencies:- '@open-draft/until': 1.0.3- '@types/debug': 4.1.7- '@xmldom/xmldom': 0.8.6- debug: 4.3.4- headers-polyfill: 3.2.5- outvariant: 1.4.0- strict-event-emitter: 0.2.8- web-encoding: 1.1.5- transitivePeerDependencies:- - supports-color- dev: true-resolution: {integrity: sha512-vy3TWLQYdGNecTaufR4wDNQFV2WEg6wRPi6BVbx6q1vP3K1mbxIn1+XOqOzfYBXjFHvMx0gZAo2TgWbaqfgvAA==}engines: {node: '>=12.0.0'}@@ -3283,10 +3256,6 @@ packages:'@nodelib/fs.scandir': 2.1.5fastq: 1.13.0- /@open-draft/[email protected]:- resolution: {integrity: sha512-Aq58f5HiWdyDlFffbbSjAlv596h/cOnt2DO1w3DOC7OJ5EHs0hd/nycJfiu9RJbT6Yk6F1knnRRXNSpxoIVZ9Q==}- dev: true-/@open-rpc/[email protected]:resolution: {integrity: sha512-vV+Hetl688nY/oWI9IFY0iKDrWuLdYhf7OIKI6U1DcnJV7r4gAgwRJjEr1QVYszUc0gjkHoQJzqevmXMGLyA0g==}dependencies:@@ -6305,10 +6274,6 @@ packages:dependencies:'@types/node': 20.8.10- /@types/[email protected]:- resolution: {integrity: sha512-XW/Aa8APYr6jSVVA1y/DEIZX0/GMKLEVekNG727R8cs56ahETkRAy/3DR7+fJyh7oUgGwNQaRfXCun0+KbWY7Q==}- dev: true-/@types/[email protected]:resolution: {integrity: sha512-KuwNhp3eza+Rhu8IFI5HUXRP0LIhqH5cAjubUvGXXthh4YYBuP2ntwEX+Cz8GJoZUHlKo247wPWOfA9LYEq4cw==}dependencies:@@ -6498,6 +6463,7 @@ packages:resolution: {integrity: sha512-9AonUzyTjXXhEOa0DnqpzZi6VHlqKMswga9EXjpXnnqxwLtdvPPtlO8evrI5D9S6asFRCQ6v+wpiUKbw+vKqyg==}dependencies:'@types/ms': 0.7.31+ dev: false/@types/[email protected]:resolution: {integrity: sha512-bV/jQlAJ/nPY3XqSatkGpu+nGzou+uSwrH1cROhn+jBFg47yaNH+blW4C7p9KhopC7QxCv/6M86s37k8dMk0Yg==}@@ -6611,10 +6577,6 @@ packages:resolution: {integrity: sha512-wkw9yd1kEXOPnvEeEV1Go1MmxtBJL0RR79aOTAApecWFVu7w0NNXNqhcWgvw2YgZDYadliXkl14pa3WXw5jlCQ==}dev: false- /@types/[email protected]:- resolution: {integrity: sha512-qC4bCqYGy1y/NP7dDVr7KJarn+PbX1nSpwA7JXdu0HxT3QYjO8MJ+cntENtHFVy2dRAyBV23OZ6MxsW1AM1L8g==}- dev: true-/@types/[email protected]:resolution: {integrity: sha512-/7kkMsC+/kMs7gAYmmBR9P0vGTnOoLhQhyhQJSlXGI5bzTHp6xdo0TtKWQAsz6pmSAeVqKSbqeyP6hytqr9FDw==}dependencies:@@ -6667,6 +6629,7 @@ packages:/@types/[email protected]:resolution: {integrity: sha512-iiUgKzV9AuaEkZqkOLDIvlQiL6ltuZd9tGcW3gwpnX8JbuiuhFlEGmmFXEXkN50Cvq7Os88IY2v0dkDqXYWVgA==}+ dev: false/@types/[email protected]:resolution: {integrity: sha512-1ZX9fcN4Rvkvgv4E6PAY5WXUFWFcRWxZa3EW83UjycOB9ljJCedb2CupIP4RZMEwF/M3eTcCihbBRgwtGbg5Rg==}@@ -6768,12 +6731,6 @@ packages:'@types/mime': 1.3.2'@types/node': 20.8.10- /@types/[email protected]:- resolution: {integrity: sha512-7QhnH7bi+6KAhBB+Auejz1uV9DHiopZqu7LfR/5gZZTkejJV5nYeZZpgfFoE0N8aDsXuiYpfKyfyMatCwQhyTQ==}- dependencies:- '@types/node': 20.8.10- dev: true-/@types/[email protected]:resolution: {integrity: sha512-vehbtyHUShPxIa9SioxDwCvgxukDMH//icJG90sXQBUm5lJOHLT5kNeU9tnivhnA/TkOFMzGIXN2cTc4hY8/kg==}dependencies:@@ -7271,11 +7228,6 @@ packages:'@xtuc/long': 4.2.2dev: false- /@xmldom/[email protected]:- resolution: {integrity: sha512-uRjjusqpoqfmRkTaNuLJ2VohVr67Q5YwDATW3VU7PfzTj6IRaihGrYI7zckGZjxQPBIp63nfvJbM+Yu5ICh0Bg==}- engines: {node: '>=10.0.0'}- dev: true-/@xtuc/[email protected]:resolution: {integrity: sha512-DX8nKgqcGwsc0eJSqYt5lwP4DH5FlHnmuWWBRy7X0NcaGR0ZtuyeESgMwTYVEtxmsNGY+qit4QYT/MIYTOTPeA==}dev: false@@ -7310,12 +7262,6 @@ packages:tslib: 1.14.1dev: true- /@zxing/[email protected]:- resolution: {integrity: sha512-U/4aVJ2mxI0aDNI8Uq0wEhMgY+u4CNtEb0om3+y3+niDAsoTCOB33UF0sxpzqzdqXLqmvc+vZyAt4O8pPdfkwA==}- requiresBuild: true- dev: true- optional: true-resolution: {integrity: sha512-d8XPSGjfyzlXC3Xx891DJRyZfqk5JU0BJrDQcsWomFIV1/BIzPW5HDH5iDdWpqWaav0YVIEzT1RHTwWr0FFshA==}dev: false@@ -7444,13 +7390,6 @@ packages:resolution: {integrity: sha512-0V/PkoculFl5+0Lp47JoxUcO0xSxhIBvm+BxHdD/OgXNmdRpRHCFnKVuUoWyS9EzQP+otSGv0m9Lb4yVkQBn2A==}dev: false- resolution: {integrity: sha512-gKXj5ALrKWQLsYG9jlTRmR/xKluxHV+Z9QEwNIgCfM1/uwPMCuzVVnh5mwTd+OuBZcwSIMbqssNWRm1lE51QaQ==}- engines: {node: '>=8'}- dependencies:- type-fest: 0.21.3- dev: true-resolution: {integrity: sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==}engines: {node: '>=8'}@@ -8033,10 +7972,6 @@ packages:resolution: {integrity: sha512-shx7oQ0Awen/BRIdkjkvz54PnEEI/EjwXDSIZp86/KKdbafHh1Df/RYGBhn4hbe2+uKC9FnT5UCEdyPz3ai9hQ==}dev: false- resolution: {integrity: sha512-mT8iDcrh03qDGRRmoA2hmBJnxpllMR+0/0qlzjqZES6NdiWDcZkCNAk4rPFZ9Q85r27unkiNNg8ZOiwZXBHwcA==}- dev: true-resolution: {integrity: sha512-iKEoDYaRmd1mxM90a2OEfWhjsjPpYPuQ+lMYsoxB126+t8fw7ySEO48nmDg5COTjxDI65/Y2OWpeEHk3ZOe8zg==}dependencies:@@ -8128,11 +8063,6 @@ packages:'@colors/colors': 1.5.0dev: true- resolution: {integrity: sha512-FxqpkPPwu1HjuN93Omfm4h8uIanXofW0RxVEW3k5RKx+mJJYSthzNhp32Kzxxy3YAEZ/Dc/EWN1vZRY0+kOhbw==}- engines: {node: '>= 10'}- dev: true-resolution: {integrity: sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==}engines: {node: '>=12'}@@ -8140,6 +8070,7 @@ packages:string-width: 4.2.3strip-ansi: 6.0.1wrap-ansi: 7.0.0+ dev: falseresolution: {integrity: sha512-neHB9xuzh/wk0dIHweyAXv2aPGZIVk3pLMe+/RNzINf17fe0OG96QroktYAUm7SM1PBnzTabaLboqqxDyMU+SQ==}@@ -8396,11 +8327,6 @@ packages:resolution: {integrity: sha512-QADzlaHc8icV8I7vbaJXJwod9HWYp8uCqf1xa4OfNu1T7JVxQIrUgOWtHdNDtPiywmFbiS12VjotIXLrKM3orQ==}dev: true- resolution: {integrity: sha512-aSWTXFzaKWkvHO1Ny/s+ePFpvKsPnjc551iI41v3ny/ow6tBG5Vd+FuqGNhh1LxOmVzOlGUriIlOaokOvhaStA==}- engines: {node: '>= 0.6'}- dev: true-resolution: {integrity: sha512-YZ3GUyn/o8gfKJlnlX7g7xq4gyO6OSuhGPKaaGssGB2qgDUS0gPgtTvoyZLTt9Ab6dC4hfc9dV5arkvc/OCmrw==}engines: {node: '>= 0.6'}@@ -9992,6 +9918,7 @@ packages:resolution: {integrity: sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q==}engines: {node: '>=0.8.x'}+ dev: falseresolution: {integrity: sha512-8uSpZZocAZRBAPIEINJj3Lo9HyGitllczc27Eh5YYojjMFMn8yHMDMaUHE2Jqfq05D/wucwI4JGURyXt1vchyg==}@@ -10072,15 +9999,6 @@ packages:resolution: {integrity: sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==}dev: true- resolution: {integrity: sha512-hMQ4CX1p1izmuLYyZqLMO/qGNw10wSv9QDCPfzXfyFrOaCSSoRfqE1Kf1s5an66J5JZC62NewG+mK49jOCtQew==}- engines: {node: '>=4'}- dependencies:- chardet: 0.7.0- iconv-lite: 0.4.24- tmp: 0.0.33- dev: true-resolution: {integrity: sha512-xoh5G1W/PB0/27lXgMQyIhP5DSY/LhoCsOyZgb+6iMmRtCwVBo55uKaMoEYrDCKQhWvqEip5ZPKAc6eFNyf/MA==}hasBin: true@@ -10160,13 +10078,6 @@ packages:resolution: {integrity: sha512-3yurQZ2hD9VISAhJJP9bpYFNQrHHBXE2JxxjY5aLEcDi46RmAzJE2OC9FAde0yis5ElW0jTTzs0zfg/Cca4XqQ==}dev: true- resolution: {integrity: sha512-yaduQFRKLXYOGgEn6AZau90j3ggSOyiqXU0F9JZfeXYhNa+Jk4X+s45A2zg5jns87GAFa34BBm2kXw4XpNcbdg==}- engines: {node: '>=8'}- dependencies:- escape-string-regexp: 1.0.5- dev: true-resolution: {integrity: sha512-7Gps/XWymbLk2QLYK4NzpMOrYjMhdIxXuIvy2QBsLE6ljuodKvdkWs/cpyJJ3CVIVpH0Oi1Hvg1ovbMzLdFBBg==}engines: {node: ^10.12.0 || >=12.0.0}@@ -10413,6 +10324,7 @@ packages:resolution: {integrity: sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==}engines: {node: 6.* || 8.* || >= 10.*}+ dev: falseresolution: {integrity: sha512-LnpfLf/TNzr9zVOGiIY6aKCz8EKuXmlYNV7CM2pUjBa/B+c2I15tS7KLySep75+FuerJdmArvJLcsAXWEy2H0A==}@@ -10761,11 +10673,6 @@ packages:resolution: {integrity: sha512-EtKwoO6kxCL9WO5xipiHTZlSzBm7WLT627TqC/uVRd0HKmq8NXyebnNYxDoBi7wt8eTWrUrKXCOVaFq9x1kgag==}- resolution: {integrity: sha512-59LZHPdGZVh695Ud9lRzPBVTtlX9ZCV150Er2W43ro37wVof0ctenSaskPPjN7lVTIN8mSZt8PHUNKZuNQUuxw==}- engines: {node: ^12.22.0 || ^14.16.0 || ^16.0.0 || >=17.0.0}- dev: true-resolution: {integrity: sha512-HZRwumpOGUrHyxO5bqKZL0B0GlUpwtCAzZ42sgxUPniu33R1LSFH5yrIcBCHjkctCAh3mtWKcKd9J4vDDdeVHA==}dev: false@@ -10856,10 +10763,6 @@ packages:dependencies:function-bind: 1.1.2- resolution: {integrity: sha512-tUCGvt191vNSQgttSyJoibR+VO+I6+iCHIUdhzEMJKE+EAL8BwCN7fUOZlY4ofOelNHsK+gEjxB/B+9N3EWtdA==}- dev: true-resolution: {integrity: sha512-2bsegYkkHO+h/9MGbn6KWcE45cHZgPANo5LXF7EvWdT0yT2EguSVO1nDgU5c8+ZOPwp2vMNa7YFsJhVcDR9Sdg==}dev: false@@ -11082,27 +10985,6 @@ packages:resolution: {integrity: sha512-EcKzdTHVe8wFVOGEYXiW9WmJXPjqi1T+234YpJr98RiFYKHV3cdy1+3mkTE+KHTHxFFLH51SfaGOoUdW+v7ViQ==}dev: false- resolution: {integrity: sha512-QAgPDQMEgrDssk1XiwwHoOGYF9BAbUcc1+j+FhEvaOt8/cKRqyLn0U5qA6F74fGhTMGxf92pOvPBeh29jQJDTQ==}- engines: {node: '>=12.0.0'}- dependencies:- ansi-escapes: 4.3.2- chalk: 4.1.2- cli-cursor: 3.1.0- cli-width: 3.0.0- external-editor: 3.1.0- figures: 3.2.0- lodash: 4.17.21- mute-stream: 0.0.8- ora: 5.4.1- run-async: 2.4.1- rxjs: 7.8.0- string-width: 4.2.3- strip-ansi: 6.0.1- through: 2.3.8- wrap-ansi: 7.0.0- dev: true-resolution: {integrity: sha512-Y+R5hJrzs52QCG2laLn4udYVnxsfny9CpOhNhUvk/SSSVyF6T27FzRbF0sroPidSu3X8oEAkOn2K804mjpt6UQ==}engines: {node: '>= 0.4'}@@ -11293,10 +11175,6 @@ packages:engines: {node: '>= 0.4'}dev: true- resolution: {integrity: sha512-Vg4o6/fqPxIjtxgUH5QLJhwZ7gW5diGCVlXpuUfELC62CuxM1iHcRe51f2W1FDy04Ai4KJkagKjx3XaqyfRKXw==}- dev: true-resolution: {integrity: sha512-k1U0IRzLMo7ZlYIfzRu23Oh6MiIFasgpb9X76eqfFZAqwH44UI4KTBvBYIZ1dSL9ZzChTB9ShHfLkR4pdW5krQ==}engines: {node: '>= 0.4'}@@ -11616,11 +11494,6 @@ packages:engines: {node: '>=14'}dev: false- resolution: {integrity: sha512-X2BB11YZtrRqY4EnQcLX5Rh373zbK4alC1FW7D7MBhL2gtcC17cTnr6DmfHZeS0s2rTHjUTMMHfG7gO8SSdw+g==}- engines: {node: '>=0.10.0'}- dev: true-resolution: {integrity: sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==}@@ -12576,42 +12449,6 @@ packages:resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==}- resolution: {integrity: sha512-wKLhFPR+NitYTkQl5047pia0reNGgf0P6a1eTnA5aNlripmiz0sabMvvHcicE8kQ3/gZcI0YiPFWmYfowfm3lA==}- engines: {node: '>=14'}- hasBin: true- requiresBuild: true- peerDependencies:- typescript: '>= 4.4.x <= 5.2.x'- peerDependenciesMeta:- typescript:- optional: true- dependencies:- '@mswjs/cookies': 0.2.2- '@mswjs/interceptors': 0.17.10- '@open-draft/until': 1.0.3- '@types/cookie': 0.4.1- '@types/js-levenshtein': 1.1.1- chalk: 4.1.2- chokidar: 3.5.3- cookie: 0.4.2- graphql: 16.8.1- headers-polyfill: 3.2.5- inquirer: 8.2.5- is-node-process: 1.2.0- js-levenshtein: 1.1.6- node-fetch: 2.6.7- outvariant: 1.4.0- path-to-regexp: 6.2.1- strict-event-emitter: 0.4.6- type-fest: 2.19.0- typescript: 5.3.3- yargs: 17.7.2- transitivePeerDependencies:- - encoding- - supports-color- dev: true-resolution: {integrity: sha512-VAFIOG6rsxoc7q/IaY3jdjmrsuX9f15KlRLYTHmixASBZkZEKC1IFqE2BC5CdhXmK6WLM1Re33z//AGmeRI6FA==}deprecated: Redundant dependency in your project.@@ -12623,10 +12460,6 @@ packages:resolution: {integrity: sha512-TvmkNhkv8yct0SVBSy+o8wYzXjE4Zz3PCesbfs8HiCXXdcTuocApFv11UWlNFWKYsP2okqrhb7JNlSm9InBhIw==}dev: false- resolution: {integrity: sha512-nnbWWOkoWyUsTjKrhgD0dcz22mdkSnpYqbEjIm2nhwhuxlSkpywJmBo8h0ZqJdkp73mb90SssHkN4rsRaBAfAA==}- dev: true-resolution: {integrity: sha512-z81GNO7nnYMEhrGh9LeymoE4+Yr0Wn5McHIZMK5cfQCl+NDX08sCZgUc9/6MHni9IWuFLm1Z3HTCXu2z9fN62Q==}dependencies:@@ -12754,12 +12587,12 @@ packages:svg-arc-to-cubic-bezier: 3.2.0dev: false- resolution: {integrity: sha512-S2G6FWZ3pNWAAKm2PFSOtEAG/N+XO/kz3+9l6V91IY+Y3XFSt7Lp7DV92KCgEboEW0hRTu0vFaMe4zXDZYaOyA==}+ resolution: {integrity: sha512-twczQhEpj55UROtg0Xz0nzn83TanS5Re12g5g1hcdnyAhlWOt9VNHdSHf2Z6MO3/wOVqy9tEdi0ruJt5NnMgmw==}engines: {node: '>= 10'}hasBin: truedependencies:- ansi-styles: 5.2.0+ ansi-styles: 4.3.0cross-spawn: 7.0.3memorystream: 0.3.1minimatch: 3.1.2@@ -12951,15 +12784,6 @@ packages:wcwidth: 1.0.1dev: true- resolution: {integrity: sha512-D2FR03Vir7FIu45XBY20mTb+/ZSWB00sjU9jdQXt83gDrI4Ztz5Fs7/yy74g2N5SVQY4xY1qDr4rNddwYRVX0g==}- engines: {node: '>=0.10.0'}- dev: true-- resolution: {integrity: sha512-AlWY719RF02ujitly7Kk/0QlV+pXGFDHrHf9O2OKqyqgBieaPOIeuSkL8sRK6j2WK+/ZAURq2kZsY0d8JapUiw==}- dev: true-resolution: {integrity: sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==}engines: {node: '>=6'}@@ -13102,10 +12926,6 @@ packages:resolution: {integrity: sha512-5DFkuoqlv1uYQKxy8omFBeJPQcdoE07Kv2sferDCrAq1ohOU+MSDswDIbnx3YAM60qIOnYa53wBhXW0EbMonrQ==}dev: true- resolution: {integrity: sha512-JLyh7xT1kizaEvcaXOQwOc2/Yhw6KZOvPf1S8401UyLk86CU79LN3vl7ztXGm/pZ+YjoyAJ4rxmHwbkBXJX+yw==}- dev: true-resolution: {integrity: sha512-gDKb8aZMDeD/tZWs9P6+q0J9Mwkdl6xMV8TjnGP3qJVJ06bdMgkbBlLU8IdfOsIsFz2BW1rNVT3XuNEl8zPAvw==}engines: {node: '>=8'}@@ -14567,6 +14387,7 @@ packages:resolution: {integrity: sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==}engines: {node: '>=0.10.0'}+ dev: falseresolution: {integrity: sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==}@@ -14705,11 +14526,6 @@ packages:resolution: {integrity: sha512-APM0Gt1KoXBz0iIkkdB/kfvGOwC4UuJFeG/c+yV7wSc7q96cG/kJ0HiYCnzivD9SB53cLV1MlHFNfOuPaadYSw==}dev: true- resolution: {integrity: sha512-tvVnVv01b8c1RrA6Ep7JkStj85Guv/YrMcwqYQnwjsAS2cTmmPGBBjAjpCW7RrSodNSoE2/qg9O4bceNvUuDgQ==}- engines: {node: '>=0.12.0'}- dev: true-resolution: {integrity: sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA==}dependencies:@@ -14719,12 +14535,6 @@ packages:resolution: {integrity: sha512-PdhdWy89SiZogBLaw42zdeqtRJ//zFd2PgQavcICDUgJT5oW10QCRKbJ6bg4r0/UY2M6BWd5tkxuGFRvCkgfHQ==}dev: false- resolution: {integrity: sha512-F2+gxDshqmIub1KdvZkaEfGDwLNpPvk9Fs6LD/MyQxNgMds/WH9OdDDXOmxUZpME+iSK3rQCctkL0DYyytUqMg==}- dependencies:- tslib: 2.6.2- dev: true-resolution: {integrity: sha512-xal3CZX1Xlo/k4ApwCFrHVACi9fBqJ7V+mwhBsuf/1IOKbBy098Fex+Wa/5QMubw09pSZ/u8EY8PWgevJsXp1A==}engines: {node: '>=6'}@@ -14862,10 +14672,6 @@ packages:- supports-colordev: true- resolution: {integrity: sha512-RVnVQxTXuerk653XfuliOxBP81Sf0+qfQE73LIYKcyMYHG94AuH0kgrQpRDuTZnSmjpysHmzxJXKNfa6PjFhyQ==}- dev: true-resolution: {integrity: sha512-4DBHDoyHlM1IRPGYcoxexgh67y4ueR53FKV1yyxwFMY7aCqcN/38M1+SwZ/qJQ8iLv7+ck385ot4CcisOAPT9w==}engines: {node: '>= 0.4'}@@ -15057,16 +14863,6 @@ packages:resolution: {integrity: sha512-Nk/brWYpD85WlOgzw5h173aci0Teyv8YdIAEtV+N88nDB0dLlazZyJMIsN6eo1/AR61l+p6CJTG1JIyFaoNEEA==}dev: false- resolution: {integrity: sha512-KDf/ujU8Zud3YaLtMCcTI4xkZlZVIYxTLr+XIULexP+77EEVWixeXroLUXQXiVtH4XH2W7jr/3PT1v3zBuvc3A==}- dependencies:- events: 3.3.0- dev: true-- resolution: {integrity: sha512-12KWeb+wixJohmnwNFerbyiBrAlq5qJLwIt38etRtKtmmHyDSoGlIqFE9wx+4IwG0aDjI7GV8tc8ZccjWZZtTg==}- dev: true-resolution: {integrity: sha512-KaJKY+hfpzNyet/emP81PJA9hTVSfxNLS9SFTWxdCnnW1/zOOwiV248+EfoX7IQFcBaOp4G5YE6xTJMF+pLg6A==}dependencies:@@ -15596,10 +15392,6 @@ packages:readable-stream: 2.3.8xtend: 4.0.2- resolution: {integrity: sha512-w89qg7PI8wAdvX60bMDP+bFoD5Dvhm9oLheFp5O4a2QF0cSBGsBX4qZmadPMvVqlLJBBci+WqGGOAPvcDeNSVg==}- dev: true-resolution: {integrity: sha512-U7ttxEdKWqHYJ96OGoJJR5gU8Nwkl3tlY0n7Jr4vcpLD2RkVZLE1Ph9k8ZRrZ7LYX9QCtd3M9OUaR9P8Z37QNg==}engines: {node: '>=12'}@@ -15630,13 +15422,6 @@ packages:engines: {node: '>=14.0.0'}dev: true- resolution: {integrity: sha512-jRCJlojKnZ3addtTOjdIqoRuPEKBvNXcGYqzO6zWZX8KfKEpnGY5jfggJQ3EjKuu8D4bJRr0y+cYJFmYbImXGw==}- engines: {node: '>=0.6.0'}- dependencies:- os-tmpdir: 1.0.2- dev: true-resolution: {integrity: sha512-3f0uOEAQwIqGuWW2MVzYg8fV/QNnc/IpuJNG837rLuczAaLVHslWHZQj4IGiEl5Hs3kkbhwL9Ab7Hrsmuj+Smw==}dev: true@@ -15778,11 +15563,6 @@ packages:resolution: {integrity: sha512-Ne+eE4r0/iWnpAxD852z3A+N0Bt5RN//NjJwRd2VFHEmrywxf5vsZlh4R6lixl6B+wz/8d+maTSAkN1FIkI3LQ==}engines: {node: '>=10'}- resolution: {integrity: sha512-t0rzBq87m3fVcduHDUFhKmyyX+9eo6WQjZvf51Ea/M0Q7+T374Jp1aUiyUl0GKxp8M/OETVHSDvmkyPgvX+X2w==}- engines: {node: '>=10'}- dev: true-resolution: {integrity: sha512-q+MB8nYR1KDLrgr4G5yemftpMC7/QLqVndBmEEdqzmNj5dcFOO4Oo8qlwZE3ULT3+Zim1F8Kq4cBnikNhlCMlg==}engines: {node: '>=8'}@@ -16673,14 +16453,6 @@ packages:resolution: {integrity: sha512-lNR9aAefbGPpHO7AEnY0hCFjz1eTkWCXYvkTRrTHs9qv8zJp+SkVYpzfLIFXQQiG3tVvbNFQgVg2bQS8YGgxyw==}dev: false- resolution: {integrity: sha512-HYLeVCdJ0+lBYV2FvNZmv3HJ2Nt0QYXqZojk3d9FJOLkwnuhzM9tmamh8d7HPM8QqjKH8DeHkFTx+CFlWpZZDA==}- dependencies:- util: 0.12.5- optionalDependencies:- '@zxing/text-encoding': 0.9.0- dev: true-resolution: {integrity: sha512-c0rhqNcHXRkY/ogGDJQxZ9Im9D19hDihbzSQJrsioex+KnFgmMzBiy57Z1EjkhX/+OjyBpclDCzz2ITtjokFmg==}dev: false@@ -16970,6 +16742,7 @@ packages:resolution: {integrity: sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==}engines: {node: '>=10'}+ dev: falseresolution: {integrity: sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==}@@ -16995,6 +16768,7 @@ packages:resolution: {integrity: sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==}engines: {node: '>=12'}+ dev: falseresolution: {integrity: sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w==}@@ -17007,6 +16781,7 @@ packages:string-width: 4.2.3y18n: 5.0.8yargs-parser: 21.1.1+ dev: falseresolution: {integrity: sha512-p4a9I6X6nu6IhoGmBqAcbJy1mlC4j27vEPZX9F4L4/vZT3Lyq1VkFHw/V/PUcB9Buo+DG3iHkT0x3Qya58zc3g==}diff --git a/frontend/public/mockServiceWorker.js b/frontend/public/mockServiceWorker.jsdeleted file mode 100644index 51d85eeebf..0000000000--- a/frontend/public/mockServiceWorker.js+++ /dev/null@@ -1,303 +0,0 @@-/* eslint-disable */-/* tslint:disable */--/**- * Mock Service Worker (1.3.2).- * @see https://github.com/mswjs/msw- * - Please do NOT modify this file.- * - Please do NOT serve this file on production.- */--const INTEGRITY_CHECKSUM = '3d6b9f06410d179a7f7404d4bf4c3c70'-const activeClientIds = new Set()--self.addEventListener('install', function () {- self.skipWaiting()-})--self.addEventListener('activate', function (event) {- event.waitUntil(self.clients.claim())-})--self.addEventListener('message', async function (event) {- const clientId = event.source.id-- if (!clientId || !self.clients) {- return- }-- const client = await self.clients.get(clientId)-- if (!client) {- return- }-- const allClients = await self.clients.matchAll({- type: 'window',- })-- switch (event.data) {- case 'KEEPALIVE_REQUEST': {- sendToClient(client, {- type: 'KEEPALIVE_RESPONSE',- })- break- }-- case 'INTEGRITY_CHECK_REQUEST': {- sendToClient(client, {- type: 'INTEGRITY_CHECK_RESPONSE',- payload: INTEGRITY_CHECKSUM,- })- break- }-- case 'MOCK_ACTIVATE': {- activeClientIds.add(clientId)-- sendToClient(client, {- type: 'MOCKING_ENABLED',- payload: true,- })- break- }-- case 'MOCK_DEACTIVATE': {- activeClientIds.delete(clientId)- break- }-- case 'CLIENT_CLOSED': {- activeClientIds.delete(clientId)-- const remainingClients = allClients.filter((client) => {- return client.id !== clientId- })-- // Unregister itself when there are no more clients- if (remainingClients.length === 0) {- self.registration.unregister()- }-- break- }- }-})--self.addEventListener('fetch', function (event) {- const { request } = event- const accept = request.headers.get('accept') || ''-- // Bypass server-sent events.- if (accept.includes('text/event-stream')) {- return- }-- // Bypass navigation requests.- if (request.mode === 'navigate') {- return- }-- // Opening the DevTools triggers the "only-if-cached" request- // that cannot be handled by the worker. Bypass such requests.- if (request.cache === 'only-if-cached' && request.mode !== 'same-origin') {- return- }-- // Bypass all requests when there are no active clients.- // Prevents the self-unregistered worked from handling requests- // after it's been deleted (still remains active until the next reload).- if (activeClientIds.size === 0) {- return- }-- // Generate unique request ID.- const requestId = Math.random().toString(16).slice(2)-- event.respondWith(- handleRequest(event, requestId).catch((error) => {- if (error.name === 'NetworkError') {- console.warn(- '[MSW] Successfully emulated a network error for the "%s %s" request.',- request.method,- request.url,- )- return- }-- // At this point, any exception indicates an issue with the original request/response.- console.error(- `\-[MSW] Caught an exception from the "%s %s" request (%s). This is probably not a problem with Mock Service Worker. There is likely an additional logging output above.`,- request.method,- request.url,- `${error.name}: ${error.message}`,- )- }),- )-})--async function handleRequest(event, requestId) {- const client = await resolveMainClient(event)- const response = await getResponse(event, client, requestId)-- // Send back the response clone for the "response:*" life-cycle events.- // Ensure MSW is active and ready to handle the message, otherwise- // this message will pend indefinitely.- if (client && activeClientIds.has(client.id)) {- ;(async function () {- const clonedResponse = response.clone()- sendToClient(client, {- type: 'RESPONSE',- payload: {- requestId,- type: clonedResponse.type,- ok: clonedResponse.ok,- status: clonedResponse.status,- statusText: clonedResponse.statusText,- body:- clonedResponse.body === null ? null : await clonedResponse.text(),- headers: Object.fromEntries(clonedResponse.headers.entries()),- redirected: clonedResponse.redirected,- },- })- })()- }-- return response-}--// Resolve the main client for the given event.-// Client that issues a request doesn't necessarily equal the client-// that registered the worker. It's with the latter the worker should-// communicate with during the response resolving phase.-async function resolveMainClient(event) {- const client = await self.clients.get(event.clientId)-- if (client?.frameType === 'top-level') {- return client- }-- const allClients = await self.clients.matchAll({- type: 'window',- })-- return allClients- .filter((client) => {- // Get only those clients that are currently visible.- return client.visibilityState === 'visible'- })- .find((client) => {- // Find the client ID that's recorded in the- // set of clients that have registered the worker.- return activeClientIds.has(client.id)- })-}--async function getResponse(event, client, requestId) {- const { request } = event- const clonedRequest = request.clone()-- function passthrough() {- // Clone the request because it might've been already used- // (i.e. its body has been read and sent to the client).- const headers = Object.fromEntries(clonedRequest.headers.entries())-- // Remove MSW-specific request headers so the bypassed requests- // comply with the server's CORS preflight check.- // Operate with the headers as an object because request "Headers"- // are immutable.- delete headers['x-msw-bypass']-- return fetch(clonedRequest, { headers })- }-- // Bypass mocking when the client is not active.- if (!client) {- return passthrough()- }-- // Bypass initial page load requests (i.e. static assets).- // The absence of the immediate/parent client in the map of the active clients- // means that MSW hasn't dispatched the "MOCK_ACTIVATE" event yet- // and is not ready to handle requests.- if (!activeClientIds.has(client.id)) {- return passthrough()- }-- // Bypass requests with the explicit bypass header.- // Such requests can be issued by "ctx.fetch()".- if (request.headers.get('x-msw-bypass') === 'true') {- return passthrough()- }-- // Notify the client that a request has been intercepted.- const clientMessage = await sendToClient(client, {- type: 'REQUEST',- payload: {- id: requestId,- url: request.url,- method: request.method,- headers: Object.fromEntries(request.headers.entries()),- cache: request.cache,- mode: request.mode,- credentials: request.credentials,- destination: request.destination,- integrity: request.integrity,- redirect: request.redirect,- referrer: request.referrer,- referrerPolicy: request.referrerPolicy,- body: await request.text(),- bodyUsed: request.bodyUsed,- keepalive: request.keepalive,- },- })-- switch (clientMessage.type) {- case 'MOCK_RESPONSE': {- return respondWithMock(clientMessage.data)- }-- case 'MOCK_NOT_FOUND': {- return passthrough()- }-- case 'NETWORK_ERROR': {- const { name, message } = clientMessage.data- const networkError = new Error(message)- networkError.name = name-- // Rejecting a "respondWith" promise emulates a network error.- throw networkError- }- }-- return passthrough()-}--function sendToClient(client, message) {- return new Promise((resolve, reject) => {- const channel = new MessageChannel()-- channel.port1.onmessage = (event) => {- if (event.data && event.data.error) {- return reject(event.data.error)- }-- resolve(event.data)- }-- client.postMessage(message, [channel.port2])- })-}--function sleep(timeMs) {- return new Promise((resolve) => {- setTimeout(resolve, timeMs)- })-}--async function respondWithMock(response) {- await sleep(response.delay)- return new Response(response.body, response)-}diff --git a/frontend/src/components/editor/Cell.tsx b/frontend/src/components/editor/Cell.tsxindex 8ac8d821da..ff4d469506 100644--- a/frontend/src/components/editor/Cell.tsx+++ b/frontend/src/components/editor/Cell.tsx@@ -419,6 +419,7 @@ const CellComponent = (edited={edited}disabled={cellConfig.disabled ?? false}elapsedTime={runElapsedTimeMs}+ runStartTimestamp={runStartTimestamp}/><div className="flex align-bottom"><RunButtondiff --git a/frontend/src/components/editor/ShutdownButton.tsx b/frontend/src/components/editor/ShutdownButton.tsxindex b9f9a8055d..abf478e8bf 100644--- a/frontend/src/components/editor/ShutdownButton.tsx+++ b/frontend/src/components/editor/ShutdownButton.tsx@@ -1,19 +1,10 @@/* Copyright 2024 Marimo. All rights reserved. */-import { XIcon } from "lucide-react";-import {- AlertDialog,- AlertDialogCancel,- AlertDialogContent,- AlertDialogDescription,- AlertDialogDestructiveAction,- AlertDialogFooter,- AlertDialogHeader,- AlertDialogTitle,- AlertDialogTrigger,-} from "../ui/alert-dialog";+import { AlertDialogDestructiveAction } from "../ui/alert-dialog";import { Button } from "./inputs/Inputs";import { Tooltip } from "../ui/tooltip";+import { useImperativeModal } from "../modal/ImperativeModal";+import { XIcon } from "lucide-react";interface ShutdownButtonProps {onShutdown: (e: React.MouseEvent<HTMLButtonElement>) => void;@@ -22,41 +13,39 @@ interface ShutdownButtonProps {export const ShutdownButton = ({onShutdown,}: ShutdownButtonProps): JSX.Element => {+ const { openConfirm, closeModal } = useImperativeModal();+return (- <AlertDialog>- <Tooltip content="Shutdown">- <AlertDialogTrigger asChild={true}>- <Button- aria-label="Shutdown"- shape="circle"- size="small"- color="red"- className="h-[27px] w-[27px]"- >- <XIcon strokeWidth={1} />- </Button>- </AlertDialogTrigger>- </Tooltip>- <AlertDialogContent>- <AlertDialogHeader>- <AlertDialogTitle className="text-destructive">- Shutdown?- </AlertDialogTitle>- <AlertDialogDescription>- This will terminate the Python kernel. You'll lose all data that's- in memory.- </AlertDialogDescription>- </AlertDialogHeader>- <AlertDialogFooter>- <AlertDialogCancel>Cancel</AlertDialogCancel>- <AlertDialogDestructiveAction- onClick={onShutdown}- aria-label="Confirm Shutdown"- >- Shutdown- </AlertDialogDestructiveAction>- </AlertDialogFooter>- </AlertDialogContent>- </AlertDialog>+ <Tooltip content="Shutdown">+ <Button+ aria-label="Shutdown"+ shape="circle"+ size="small"+ color="red"+ className="h-[27px] w-[27px]"+ onClick={(e) => {+ e.stopPropagation();+ openConfirm({+ title: "Shutdown",+ description:+ "This will terminate the Python kernel. You'll lose all data that's in memory.",+ variant: "destructive",+ confirmAction: (+ <AlertDialogDestructiveAction+ onClick={(e) => {+ onShutdown(e);+ closeModal();+ }}+ aria-label="Confirm Shutdown"+ >+ Shutdown+ </AlertDialogDestructiveAction>+ ),+ });+ }}+ >+ <XIcon strokeWidth={1} />+ </Button>+ </Tooltip>);};diff --git a/frontend/src/components/editor/actions/useNotebookActions.tsx b/frontend/src/components/editor/actions/useNotebookActions.tsxindex 998a8815d5..fdde1436d6 100644--- a/frontend/src/components/editor/actions/useNotebookActions.tsx+++ b/frontend/src/components/editor/actions/useNotebookActions.tsx@@ -11,6 +11,7 @@ import {FolderDownIcon,ClipboardCopyIcon,Share2Icon,+ PowerSquareIcon,} from "lucide-react";import { commandPaletteAtom } from "../CommandPalette";import {@@ -27,6 +28,7 @@ import { toast } from "@/components/ui/use-toast";import { useFilename } from "@/core/saving/filename";import { useImperativeModal } from "@/components/modal/ImperativeModal";import { ShareStaticNotebookModal } from "@/components/static-html/share-modal";+import { useRestartKernel } from "./useRestartKernel";export function useNotebookActions() {const [filename] = useFilename();@@ -34,6 +36,7 @@ export function useNotebookActions() {const notebook = useNotebook();const { updateCellConfig } = useCellActions();+ const restartKernel = useRestartKernel();const setCommandPaletteOpen = useSetAtom(commandPaletteAtom);const disabledCells = disabledCellIds(notebook);@@ -138,6 +141,13 @@ export function useNotebookActions() {window.open("https://docs.marimo.io", "_blank");},},++ {+ icon: <PowerSquareIcon size={14} strokeWidth={1.5} />,+ label: "Restart kernel",+ variant: "danger",+ handle: restartKernel,+ },];return actions.filter((a) => !a.hidden);diff --git a/frontend/src/components/editor/actions/useRestartKernel.tsx b/frontend/src/components/editor/actions/useRestartKernel.tsxnew file mode 100644index 0000000000..0b7e23b1be--- /dev/null+++ b/frontend/src/components/editor/actions/useRestartKernel.tsx@@ -0,0 +1,28 @@+/* Copyright 2024 Marimo. All rights reserved. */+import { useImperativeModal } from "@/components/modal/ImperativeModal";+import { AlertDialogDestructiveAction } from "@/components/ui/alert-dialog";+import { sendRestart } from "@/core/network/requests";++export function useRestartKernel() {+ const { openConfirm } = useImperativeModal();++ return () => {+ openConfirm({+ title: "Restart Kernel",+ description:+ "This will restart the Python kernel. You'll lose all data that's in memory.",+ variant: "destructive",+ confirmAction: (+ <AlertDialogDestructiveAction+ onClick={async () => {+ await sendRestart();+ window.location.reload();+ }}+ aria-label="Confirm Restart"+ >+ Restart+ </AlertDialogDestructiveAction>+ ),+ });+ };+}diff --git a/frontend/src/components/editor/cell/CellStatus.tsx b/frontend/src/components/editor/cell/CellStatus.tsxindex 1a5c2605c1..cb96d7cf8f 100644--- a/frontend/src/components/editor/cell/CellStatus.tsx+++ b/frontend/src/components/editor/cell/CellStatus.tsx@@ -6,18 +6,21 @@ import {RefreshCwIcon,} from "lucide-react";import { Tooltip } from "../../ui/tooltip";-import { CellStatus } from "../../../core/cells/types";+import { CellRuntimeState } from "../../../core/cells/types";import { useElapsedTime } from "../../../hooks/useElapsedTime";import { Logger } from "@/utils/Logger";import { MultiIcon } from "@/components/icons/multi-icon";import "./cell-status.css";+import { Time } from "@/utils/time";-export interface CellStatusComponentProps {+export interface CellStatusComponentProps+ extends Pick<+ CellRuntimeState,+ "status" | "runStartTimestamp" | "interrupted"+ > {editing: boolean;- status: CellStatus;edited: boolean;- interrupted: boolean;disabled: boolean;elapsedTime: number | null;}@@ -29,6 +32,7 @@ export const CellStatusComponent: React.FC<CellStatusComponentProps> = ({edited,interrupted,elapsedTime,+ runStartTimestamp,}) => {if (!editing) {return null;@@ -128,7 +132,9 @@ export const CellStatusComponent: React.FC<CellStatusComponentProps> = ({data-testid="cell-status"data-status="running">- <CellTimer />+ <CellTimer+ startTime={Time.fromSeconds(runStartTimestamp) || Time.now()}+ /></div></Tooltip>);@@ -223,7 +229,7 @@ function formatElapsedTime(elapsedTime: number | null) {}}-const CellTimer = () => {- const time = useElapsedTime();+const CellTimer = (props: { startTime: Time }) => {+ const time = useElapsedTime(props.startTime.toMilliseconds());return <span>{formatElapsedTime(time)}</span>;};diff --git a/frontend/src/components/editor/chrome/wrapper/app-chrome.tsx b/frontend/src/components/editor/chrome/wrapper/app-chrome.tsxindex b4a8ef70be..2f19abbc25 100644--- a/frontend/src/components/editor/chrome/wrapper/app-chrome.tsx+++ b/frontend/src/components/editor/chrome/wrapper/app-chrome.tsx@@ -22,9 +22,12 @@ import { DocumentationPanel } from "../panels/documentation-panel";import { FileExplorerPanel } from "../panels/file-explorer-panel";export const AppChrome: React.FC<PropsWithChildren> = ({ children }) => {- const { isOpen, selectedPanel, panelLocation } = useChromeState();+ const { isOpen, selectedPanel } = useChromeState();const { setIsOpen } = useChromeActions();const sidebarRef = React.useRef<ImperativePanelHandle>(null);+ // We only support 'left' for now+ // We may add support for a bottom bar, but currently it forces the app to remount+ const panelLocation = "left";// sync sidebaruseEffect(() => {@@ -106,8 +109,7 @@ export const AppChrome: React.FC<PropsWithChildren> = ({ children }) => {collapsible={true}className={cn("bg-white dark:bg-[var(--slate-1)] rounded-lg no-print shadow-mdNeutral",- isOpen && "m-4",- isOpen && panelLocation === "bottom" && "mt-2"+ isOpen && "m-4")}minSize={10}// We can't make the default size greater than 0, otherwise it will start opendiff --git a/frontend/src/components/editor/chrome/wrapper/footer.tsx b/frontend/src/components/editor/chrome/wrapper/footer.tsxindex 273b98d84d..b4e8408d6d 100644--- a/frontend/src/components/editor/chrome/wrapper/footer.tsx+++ b/frontend/src/components/editor/chrome/wrapper/footer.tsx@@ -1,8 +1,6 @@/* Copyright 2024 Marimo. All rights reserved. */import React, { PropsWithChildren } from "react";import {- PanelBottomIcon,- PanelLeftIcon,FunctionSquareIcon,XCircleIcon,ScrollTextIcon,@@ -20,8 +18,8 @@ import { cellErrorCount } from "@/core/cells/cells";import { FeedbackButton } from "../footer/feedback-button";export const Footer: React.FC = () => {- const { selectedPanel, panelLocation } = useChromeState();- const { openApplication, changePanelLocation } = useChromeActions();+ const { selectedPanel } = useChromeState();+ const { openApplication } = useChromeActions();const errorCount = useAtomValue(cellErrorCount);return (@@ -88,21 +86,6 @@ export const Footer: React.FC = () => {</FeedbackButton><div className="mx-auto" />-- <FooterItem- tooltip="Move panel to the left"- selected={panelLocation === "left"}- onClick={() => changePanelLocation("left")}- >- <PanelLeftIcon className="h-5 w-5" />- </FooterItem>- <FooterItem- tooltip="Move panel to the bottom"- selected={panelLocation === "bottom"}- onClick={() => changePanelLocation("bottom")}- >- <PanelBottomIcon className="h-5 w-5" />- </FooterItem></footer>);};diff --git a/frontend/src/components/editor/notebook-banner.tsx b/frontend/src/components/editor/notebook-banner.tsxindex 0e6080f21a..b1d4a5224c 100644--- a/frontend/src/components/editor/notebook-banner.tsx+++ b/frontend/src/components/editor/notebook-banner.tsx@@ -1,31 +1,57 @@/* Copyright 2024 Marimo. All rights reserved. */-import { bannerAtom } from "@/core/errors/state";+import { useBanners, useBannersActions } from "@/core/errors/state";import { renderHTML } from "@/plugins/core/RenderHTML";import { Banner } from "@/plugins/impl/common/error-banner";-import { useAtom } from "jotai";-import { AlertCircleIcon, XIcon } from "lucide-react";+import { AlertCircleIcon, RotateCcwIcon, XIcon } from "lucide-react";import React from "react";import { Button } from "../ui/button";+import { useRestartKernel } from "./actions/useRestartKernel";export const NotebookBanner: React.FC = (props) => {- const [banner, setBanner] = useAtom(bannerAtom);+ const { banners } = useBanners();+ const { removeBanner } = useBannersActions();- if (!banner) {+ if (banners.length === 0) {return null;}return (- <Banner kind={banner.variant} className="mb-10 flex flex-col rounded p-3">- <div className="flex justify-between">- <span className="font-bold text-lg flex items-center mb-2">- <AlertCircleIcon className="w-5 h-5 inline-block mr-2" />- {banner.title}- </span>- <Button variant="text" size="icon" onClick={() => setBanner(undefined)}>- <XIcon className="w-5 h-5" />- </Button>- </div>- <span>{renderHTML({ html: banner.description })}</span>- </Banner>+ <div className="flex flex-col gap-4 mb-5">+ {banners.map((banner) => (+ <Banner+ kind={banner.variant || "info"}+ key={banner.id}+ className="flex flex-col rounded p-3"+ >+ <div className="flex justify-between">+ <span className="font-bold text-lg flex items-center mb-2">+ <AlertCircleIcon className="w-5 h-5 inline-block mr-2" />+ {banner.title}+ </span>+ <Button+ variant="text"+ size="icon"+ onClick={() => removeBanner(banner.id)}+ >+ <XIcon className="w-5 h-5" />+ </Button>+ </div>+ <div className="flex justify-between items-end">+ <span>{renderHTML({ html: banner.description })}</span>+ {banner.action === "restart" && <RestartSessionButton />}+ </div>+ </Banner>+ ))}+ </div>+ );+};++const RestartSessionButton = () => {+ const restartKernel = useRestartKernel();+ return (+ <Button variant="link" size="sm" onClick={restartKernel}>+ <RotateCcwIcon className="w-4 h-4 mr-2" />+ Restart+ </Button>);};diff --git a/frontend/src/components/editor/notebook-menu-dropdown.tsx b/frontend/src/components/editor/notebook-menu-dropdown.tsxindex bed3a2feee..64b89d60c0 100644--- a/frontend/src/components/editor/notebook-menu-dropdown.tsx+++ b/frontend/src/components/editor/notebook-menu-dropdown.tsx@@ -34,6 +34,7 @@ export const NotebookMenuDropdown: React.FC = () => {{actions.map((action) => (<DropdownMenuItemkey={action.label}+ variant={action.variant}onSelect={(evt) => action.handle(evt)}data-testid={`notebook-menu-dropdown-${action.label}`}>diff --git a/frontend/src/components/modal/ImperativeModal.tsx b/frontend/src/components/modal/ImperativeModal.tsxindex d9a6b5ed37..fe844a8040 100644--- a/frontend/src/components/modal/ImperativeModal.tsx+++ b/frontend/src/components/modal/ImperativeModal.tsx@@ -6,6 +6,10 @@ import {AlertDialogAction,AlertDialogContent,AlertDialogFooter,+ AlertDialogCancel,+ AlertDialogDescription,+ AlertDialogHeader,+ AlertDialogTitle,} from "../ui/alert-dialog";interface ModalContextType {@@ -89,6 +93,42 @@ export function useImperativeModal() {</AlertDialog>);},+ openConfirm: (opts: {+ title: React.ReactNode;+ description?: React.ReactNode;+ confirmAction: React.ReactNode;+ variant?: "destructive";+ }) => {+ context.setModal(+ <AlertDialog+ open={true}+ onOpenChange={(open) => {+ if (!open) {+ closeModal();+ }+ }}+ >+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle+ className={+ opts.variant === "destructive" ? "text-destructive" : ""+ }+ >+ {opts.title}+ </AlertDialogTitle>+ <AlertDialogDescription>+ {opts.description}+ </AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel onClick={closeModal}>Cancel</AlertDialogCancel>+ {opts.confirmAction}+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ );+ },closeModal: closeModal,};}diff --git a/frontend/src/components/ui/dropdown-menu.tsx b/frontend/src/components/ui/dropdown-menu.tsxindex d3bc5ebfb1..ae8ab1dbaa 100644--- a/frontend/src/components/ui/dropdown-menu.tsx+++ b/frontend/src/components/ui/dropdown-menu.tsx@@ -13,6 +13,7 @@ import {import { cn } from "@/utils/cn";import React from "react";import { Check, ChevronRight, Circle } from "lucide-react";+import { VariantProps } from "class-variance-authority";const DropdownMenu = DropdownMenuPrimitive.Root;const DropdownMenuTrigger = DropdownMenuPrimitive.Trigger;@@ -77,13 +78,12 @@ DropdownMenuContent.displayName = DropdownMenuPrimitive.Content.displayName;const DropdownMenuItem = React.forwardRef<React.ElementRef<typeof DropdownMenuPrimitive.Item>,- React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Item> & {- inset?: boolean;- }->(({ className, inset, ...props }, ref) => (+ React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Item> &+ VariantProps<typeof menuItemVariants>+>(({ className, inset, variant, ...props }, ref) => (<DropdownMenuPrimitive.Itemref={ref}- className={menuItemVariants({ className, inset })}+ className={menuItemVariants({ className, inset, variant })}{...props}/>));diff --git a/frontend/src/core/App.tsx b/frontend/src/core/App.tsxindex bdf0612034..40a40d57d3 100644--- a/frontend/src/core/App.tsx+++ b/frontend/src/core/App.tsx@@ -14,7 +14,6 @@ import {import { Controls } from "@/components/editor/Controls";import { DirCompletionInput } from "@/components/editor/DirCompletionInput";import { FilenameForm } from "@/components/editor/FilenameForm";-import { UUID } from "../utils/uuid";import { WebSocketState } from "./websocket/types";import { useMarimoWebSocket } from "./websocket/useMarimoWebSocket";import {@@ -56,6 +55,7 @@ import { formatAll } from "./codemirror/format";import { cn } from "@/utils/cn";import { isStaticNotebook } from "./static/static-state";import { useFilename } from "./saving/filename";+import { getSessionId } from "./kernel/session";interface AppProps {userConfig: UserConfig;@@ -98,7 +98,7 @@ export const App: React.FC<AppProps> = ({ userConfig, appConfig }) => {const configs = cells.map((cell) => cell.config);setLastSavedNotebook({ names, codes, configs });},- sessionId: UUID,+ sessionId: getSessionId(),});const handleFilenameChange = useEvent(@@ -121,6 +121,7 @@ export const App: React.FC<AppProps> = ({ userConfig, appConfig }) => {);const cells = notebookCells(notebook);+ const cellIds = cells.map((cell) => cell.id);const codes = cells.map((cell) => cell.code);const cellNames = cells.map((cell) => cell.name);const configs = cells.map((cell) => cell.config);@@ -146,6 +147,7 @@ export const App: React.FC<AppProps> = ({ userConfig, appConfig }) => {Logger.log("saving to ", filename);sendSave({+ cellIds: cellIds,codes,names: cellNames,filename,diff --git a/frontend/src/core/cells/__tests__/cell.test.ts b/frontend/src/core/cells/__tests__/cell.test.tsindex d6f99f3e54..7ca3d6849c 100644--- a/frontend/src/core/cells/__tests__/cell.test.ts+++ b/frontend/src/core/cells/__tests__/cell.test.ts@@ -3,6 +3,7 @@ import { expect, describe, it } from "vitest";import { outputIsStale } from "../cell";import { CellStatus } from "../types";import { OutputMessage } from "@/core/kernel/messages";+import { Seconds } from "@/utils/time";const STATUSES: CellStatus[] = ["queued",@@ -53,7 +54,7 @@ describe("outputIsStale", () => {const cell = {status: "running" as CellStatus,output: createOutput(),- runStartTimestamp: Date.now() - 1000, // Output received after run started+ runStartTimestamp: (Date.now() - 1000) as Seconds, // Output received after run startedinterrupted: false,};const edited = false;@@ -86,7 +87,7 @@ describe("outputIsStale", () => {const cell = {status: "running" as CellStatus,output: createOutput(),- runStartTimestamp: Date.now() + 1000, // Output received before run started+ runStartTimestamp: (Date.now() + 1000) as Seconds, // Output received before run startedinterrupted: false,};const edited = false;@@ -119,7 +120,7 @@ describe("outputIsStale", () => {const cell = {status: "running" as CellStatus,output: null,- runStartTimestamp: Date.now(),+ runStartTimestamp: Date.now() as Seconds,interrupted: false,};const edited = false;diff --git a/frontend/src/core/cells/__tests__/cells.test.ts b/frontend/src/core/cells/__tests__/cells.test.tsindex 0cc173b119..75665bab27 100644--- a/frontend/src/core/cells/__tests__/cells.test.ts+++ b/frontend/src/core/cells/__tests__/cells.test.ts@@ -8,6 +8,7 @@ import {} from "../cells";import { CellId } from "@/core/cells/ids";import { OutputMessage } from "@/core/kernel/messages";+import { Seconds } from "@/utils/time";const { initialNotebookState, reducer, createActions } = exportedForTesting;@@ -257,7 +258,7 @@ describe("cell reducer", () => {output: null,console: null,status: "queued",- timestamp: new Date(10).getTime(),+ timestamp: new Date(10).getTime() as Seconds,},});cell = cells[0];@@ -276,7 +277,7 @@ describe("cell reducer", () => {output: null,console: null,status: "running",- timestamp: new Date(20).getTime(),+ timestamp: new Date(20).getTime() as Seconds,},});cell = cells[0];@@ -300,7 +301,7 @@ describe("cell reducer", () => {timestamp: 0,},status: null,- timestamp: new Date(22).getTime(),+ timestamp: new Date(22).getTime() as Seconds,},});cell = cells[0];@@ -328,7 +329,7 @@ describe("cell reducer", () => {timestamp: 0,},status: "idle",- timestamp: new Date(33).getTime(),+ timestamp: new Date(33).getTime() as Seconds,},});cell = cells[0];@@ -389,7 +390,7 @@ describe("cell reducer", () => {output: null,console: null,status: "queued",- timestamp: new Date(40).getTime(),+ timestamp: new Date(40).getTime() as Seconds,},});cell = cells[0];@@ -402,7 +403,7 @@ describe("cell reducer", () => {output: null,console: null,status: "running",- timestamp: new Date(50).getTime(),+ timestamp: new Date(50).getTime() as Seconds,},});cell = cells[0];@@ -422,7 +423,7 @@ describe("cell reducer", () => {},console: null,status: "idle",- timestamp: new Date(61).getTime(),+ timestamp: new Date(61).getTime() as Seconds,},});cell = cells[0];@@ -450,7 +451,7 @@ describe("cell reducer", () => {output: null,console: null,status: "queued",- timestamp: new Date(40).getTime(),+ timestamp: new Date(40).getTime() as Seconds,},});cell = cells[0];@@ -463,7 +464,7 @@ describe("cell reducer", () => {output: null,console: null,status: "running",- timestamp: new Date(50).getTime(),+ timestamp: new Date(50).getTime() as Seconds,},});cell = cells[0];@@ -481,7 +482,7 @@ describe("cell reducer", () => {},console: null,status: "idle",- timestamp: new Date(61).getTime(),+ timestamp: new Date(61).getTime() as Seconds,},});cell = cells[0];@@ -526,7 +527,7 @@ describe("cell reducer", () => {output: null,console: null,status: "queued",- timestamp: new Date(10).getTime(),+ timestamp: new Date(10).getTime() as Seconds,},});let cell = cells[1];@@ -545,7 +546,7 @@ describe("cell reducer", () => {output: null,console: null,status: "stale",- timestamp: new Date(20).getTime(),+ timestamp: new Date(20).getTime() as Seconds,},});cell = cells[1];@@ -590,7 +591,7 @@ describe("cell reducer", () => {timestamp: 0,},status: "idle",- timestamp: new Date(33).getTime(),+ timestamp: new Date(33).getTime() as Seconds,},});@@ -655,7 +656,7 @@ describe("cell reducer", () => {output: null,console: null,status: "queued",- timestamp: new Date(10).getTime(),+ timestamp: new Date(10).getTime() as Seconds,},});let cell = cells[0];@@ -676,7 +677,7 @@ describe("cell reducer", () => {output: null,console: null,status: "idle",- timestamp: new Date(20).getTime(),+ timestamp: new Date(20).getTime() as Seconds,},});cell = cells[0];@@ -697,11 +698,11 @@ describe("cell reducer", () => {type: "ancestor-stopped",},],- timestamp: new Date(20).getTime(),+ timestamp: new Date(20).getTime() as Seconds,},console: null,status: "idle",- timestamp: new Date(20).getTime(),+ timestamp: new Date(20).getTime() as Seconds,},});cell = cells[0];@@ -721,7 +722,7 @@ describe("cell reducer", () => {output: null,console: null,status: "queued",- timestamp: new Date(30).getTime(),+ timestamp: new Date(30).getTime() as Seconds,},});cell = cells[0];@@ -737,7 +738,7 @@ describe("cell reducer", () => {output: null,console: null,status: "running",- timestamp: new Date(40).getTime(),+ timestamp: new Date(40).getTime() as Seconds,},});cell = cells[0];@@ -790,7 +791,7 @@ describe("cell reducer", () => {output: null,console: null,status: "queued",- timestamp: new Date(10).getTime(),+ timestamp: new Date(10).getTime() as Seconds,},});cell = cells[0];@@ -805,7 +806,7 @@ describe("cell reducer", () => {output: null,console: null,status: "running",- timestamp: new Date(20).getTime(),+ timestamp: new Date(20).getTime() as Seconds,},});cell = cells[0];@@ -820,7 +821,7 @@ describe("cell reducer", () => {output: null,console: STDOUT,status: null,- timestamp: new Date(22).getTime(),+ timestamp: new Date(22).getTime() as Seconds,},});cell = cells[0];@@ -840,7 +841,7 @@ describe("cell reducer", () => {output: null,console: STD_IN_1,status: null,- timestamp: new Date(22).getTime(),+ timestamp: new Date(22).getTime() as Seconds,},});cell = cells[0];@@ -873,7 +874,7 @@ describe("cell reducer", () => {output: null,console: STD_IN_2,status: null,- timestamp: new Date(22).getTime(),+ timestamp: new Date(22).getTime() as Seconds,},});cell = cells[0];@@ -898,7 +899,7 @@ describe("cell reducer", () => {},console: null,status: "idle",- timestamp: new Date(61).getTime(),+ timestamp: new Date(61).getTime() as Seconds,},});cell = cells[0];@@ -938,7 +939,7 @@ describe("cell reducer", () => {output: null,console: [OLD_STDOUT],status: null,- timestamp: new Date(1).getTime(),+ timestamp: new Date(1).getTime() as Seconds,},});@@ -959,7 +960,7 @@ describe("cell reducer", () => {output: null,console: null,status: "queued",- timestamp: new Date(10).getTime(),+ timestamp: new Date(10).getTime() as Seconds,},});cell = cells[0];@@ -975,7 +976,7 @@ describe("cell reducer", () => {output: null,console: [], // Backend sends an empty array to clearustatus: "running",- timestamp: new Date(20).getTime(),+ timestamp: new Date(20).getTime() as Seconds,},});cell = cells[0];@@ -991,7 +992,7 @@ describe("cell reducer", () => {output: null,console: [STDOUT],status: "idle",- timestamp: new Date(22).getTime(),+ timestamp: new Date(22).getTime() as Seconds,},});cell = cells[0];diff --git a/frontend/src/core/cells/cell.ts b/frontend/src/core/cells/cell.tsindex 28c8f71321..8cbdb654e1 100644--- a/frontend/src/core/cells/cell.ts+++ b/frontend/src/core/cells/cell.ts@@ -4,6 +4,7 @@ import { CellMessage, OutputMessage } from "../kernel/messages";import { CellRuntimeState } from "./types";import { collapseConsoleOutputs } from "./collapseConsoleOutputs";import { parseOutline } from "../dom/outline";+import { Seconds, Time } from "@/utils/time";export function transitionCell(cell: CellRuntimeState,@@ -24,6 +25,9 @@ export function transitionCell(// the cell's current code if the user modified it.break;case "running":+ // Clear interrupted here in case we start as "running"+ // This can happen on a resumed session+ nextCell.interrupted = false;// If was previously stopped, clear the outputsif (cell.stopped) {nextCell.output = null;@@ -37,8 +41,9 @@ export function transitionCell(break;case "idle":if (cell.runStartTimestamp) {- nextCell.runElapsedTimeMs =- (message.timestamp - cell.runStartTimestamp) * 1000;+ nextCell.runElapsedTimeMs = Time.fromSeconds(+ (message.timestamp - cell.runStartTimestamp) as Seconds+ ).toMilliseconds();nextCell.runStartTimestamp = null;}nextCell.debuggerActive = false;@@ -58,6 +63,8 @@ export function transitionCell(nextCell.output = message.output ?? nextCell.output;nextCell.status = message.status ?? nextCell.status;+ let didInterruptFromThisMessage = false;+// Handle errors: marimo includes an error output when a cell is interrupted// or erroredif (@@ -67,6 +74,7 @@ export function transitionCell(if (message.output.data.some((error) => error.type === "interruption")) {// Interrupted helps distinguish that the cell is stalenextCell.interrupted = true;+ didInterruptFromThisMessage = true;} else if (message.output.data.some((error) => error.type === "ancestor-stopped")) {@@ -81,13 +89,26 @@ export function transitionCell(// Coalesce console outputs, which are streamed during execution.let consoleOutputs = cell.consoleOutputs;++ // If interrupted on the incoming message,+ // remove the debugger and resolve all stdin for previous console outputs+ if (didInterruptFromThisMessage) {+ nextCell.debuggerActive = false;+ consoleOutputs = consoleOutputs.map((output) => {+ if (output.channel === "stdin") {+ return { ...output, response: output.response ?? "" };+ }+ return output;+ });+ }+if (message.console !== null) {// The kernel sends an empty array to clear the console; otherwise,// message.console is an output that needs to be appended to the// existing console outputs.consoleOutputs = Array.isArray(message.console)? message.console- : collapseConsoleOutputs([...cell.consoleOutputs, message.console]);+ : collapseConsoleOutputs([...consoleOutputs, message.console]);}nextCell.consoleOutputs = consoleOutputs;// Derive outline from output@@ -103,16 +124,6 @@ export function transitionCell(if (hasPdbOutput && pdbOutputs.some((output) => output.data === "start")) {nextCell.debuggerActive = true;}- // If interrupted, remove the debugger and resolve all stdin- if (nextCell.interrupted || nextCell.errored) {- nextCell.debuggerActive = false;- nextCell.consoleOutputs = nextCell.consoleOutputs.map((output) => {- if (output.channel === "stdin") {- return { ...output, response: output.response ?? "" };- }- return output;- });- }return nextCell;}diff --git a/frontend/src/core/cells/cells.ts b/frontend/src/core/cells/cells.tsindex 70c1e5e529..7bb94a7f19 100644--- a/frontend/src/core/cells/cells.ts+++ b/frontend/src/core/cells/cells.ts@@ -417,6 +417,7 @@ const { reducer, createActions } = createReducer(initialNotebookState, {return {...cell,+ interrupted: false,consoleOutputs,};});diff --git a/frontend/src/core/cells/types.ts b/frontend/src/core/cells/types.tsindex 6db9fc0a23..5f2443c977 100644--- a/frontend/src/core/cells/types.ts+++ b/frontend/src/core/cells/types.ts@@ -4,6 +4,7 @@ import { SerializedEditorState } from "../codemirror/types";import { Outline } from "./outline";import { CellId } from "./ids";import { DEFAULT_CELL_NAME } from "./names";+import { Milliseconds, Seconds } from "@/utils/time";/*** The status of a cell.@@ -97,9 +98,9 @@ export interface CellRuntimeState {*/errored: boolean;/** run start time, as seconds since epoch */- runStartTimestamp: number | null;+ runStartTimestamp: Seconds | null;/** run elapsed time, in milliseconds */- runElapsedTimeMs: number | null;+ runElapsedTimeMs: Milliseconds | null;/** debugger active */debuggerActive: boolean;}diff --git a/frontend/src/core/dom/uiregistry.ts b/frontend/src/core/dom/uiregistry.tsindex 7d40f0c0ab..8ea0d3a137 100644--- a/frontend/src/core/dom/uiregistry.ts+++ b/frontend/src/core/dom/uiregistry.ts@@ -42,6 +42,17 @@ export class UIElementRegistry {return this.entries.has(objectId);}+ set(objectId: UIElementId, value: ValueType): void {+ if (this.entries.has(objectId)) {+ throw new Error(`UIElement ${objectId} already registered`);+ }+ this.entries.set(objectId, {+ objectId: objectId,+ value: value,+ elements: new Set(),+ });+ }+/*** Register an instance of a UIElement*diff --git a/frontend/src/core/errors/state.ts b/frontend/src/core/errors/state.tsindex be9c1cd919..dae31dc8f0 100644--- a/frontend/src/core/errors/state.ts+++ b/frontend/src/core/errors/state.ts@@ -1,11 +1,55 @@/* Copyright 2024 Marimo. All rights reserved. */-import { atom } from "jotai";+import { createReducer } from "@/utils/createReducer";+import { atom, useAtomValue, useSetAtom } from "jotai";+import { useMemo } from "react";-interface BannerState {+interface Banner {+ id: string;title: string;description: string;variant?: "danger";+ action?: "restart";+}++interface BannerState {+ banners: Banner[];}-export const bannerAtom = atom<BannerState | undefined>(undefined);+const { reducer, createActions } = createReducer(+ () => ({ banners: [] } as BannerState),+ {+ addBanner: (state, banner: Banner) => {+ return { ...state, banners: [...state.banners, banner] };+ },+ removeBanner: (state, id: string) => {+ return {+ ...state,+ banners: state.banners.filter((banner) => banner.id !== id),+ };+ },+ clearBanners: (state) => {+ return { ...state, banners: [] };+ },+ }+);++const bannersAtom = atom<BannerState>({ banners: [] });++/**+ * React hook to get the Banner state.+ */+export const useBanners = () => useAtomValue(bannersAtom);++/**+ * React hook to get the Banners actions.+ */+export function useBannersActions() {+ const setState = useSetAtom(bannersAtom);+ return useMemo(() => {+ const actions = createActions((action) => {+ setState((state) => reducer(state, action));+ });+ return actions;+ }, [setState]);+}diff --git a/frontend/src/core/kernel/messages.ts b/frontend/src/core/kernel/messages.tsindex 0c4f346322..ccaee61bba 100644--- a/frontend/src/core/kernel/messages.ts+++ b/frontend/src/core/kernel/messages.ts@@ -2,9 +2,10 @@import { LayoutType } from "@/components/editor/renderers/types";import { CellConfig, CellStatus } from "../cells/types";-import { CellId } from "../cells/ids";+import { CellId, UIElementId } from "../cells/ids";import { VariableName } from "../variables/types";import { RequestId } from "../network/DeferredRequestRegistry";+import { Seconds } from "@/utils/time";export type OutputChannel =| "output"@@ -102,7 +103,7 @@ export interface CellMessage {/*** Timestamp in seconds since epoch, when the message was sent*/- timestamp: number;+ timestamp: Seconds;}export interface CompletionOption {@@ -193,6 +194,19 @@ export type OperationMessage =* The cell configs.*/configs: CellConfig[];+ /**+ * Whether the notebook was resumed from a previous session+ */+ resumed: boolean;+ /**+ * UI element values from the previous session.+ * If the notebook was not resumed, this will be undefined.+ */+ ui_values: Record<UIElementId, unknown> | undefined;+ /**+ * The last executed code+ */+ last_executed_code: Record<CellId, string | undefined> | undefined;};}| {@@ -256,5 +270,6 @@ export type OperationMessage =title: string;description: string;variant?: "danger";+ action?: "restart";};};diff --git a/frontend/src/core/kernel/session.ts b/frontend/src/core/kernel/session.tsnew file mode 100644index 0000000000..355934b70e--- /dev/null+++ b/frontend/src/core/kernel/session.ts@@ -0,0 +1,14 @@+/* Copyright 2024 Marimo. All rights reserved. */+import { generateUUID } from "@/utils/uuid";+import { TypedString } from "@/utils/typed";++export type SessionId = TypedString<"SessionId">;++const sessionId = generateUUID() as SessionId;++/**+ * Resume an existing session or start a new one+ */+export function getSessionId(): SessionId {+ return sessionId;+}diff --git a/frontend/src/core/network/api.ts b/frontend/src/core/network/api.tsindex 84bc6351a2..60491e6473 100644--- a/frontend/src/core/network/api.ts+++ b/frontend/src/core/network/api.ts@@ -1,8 +1,8 @@/* Copyright 2024 Marimo. All rights reserved. */import { once } from "@/utils/once";import { Logger } from "../../utils/Logger";-import { UUID } from "../../utils/uuid";import { getMarimoServerToken } from "../dom/marimo-tag";+import { getSessionId } from "../kernel/session";export function getXsrfCookie(): string {const r = document.cookie.match("\\b_xsrf=([^;]*)\\b");@@ -27,7 +27,7 @@ export const API = {headers: {"Content-Type": "application/json","X-Xsrftoken": getXsrfCookie(),- "Marimo-Session-Id": UUID,+ "Marimo-Session-Id": getSessionId(),"Marimo-Server-Token": getServerTokenOnce(),},body: JSON.stringify(body),diff --git a/frontend/src/core/network/requests.ts b/frontend/src/core/network/requests.tsindex 9546ce2018..33dc0bc16a 100644--- a/frontend/src/core/network/requests.ts+++ b/frontend/src/core/network/requests.ts@@ -44,6 +44,9 @@ function createNetworkRequests(): EditRequests & RunRequests {});},+ sendRestart: () => {+ return API.post("/kernel/restart_session", {});+ },sendRename: (filename: string | null) => {return API.post<RenameRequest>("/kernel/rename", {filename: filename,@@ -51,13 +54,17 @@ function createNetworkRequests(): EditRequests & RunRequests {},sendSave: (request: SaveKernelRequest) => {// Validate same length+ invariant(+ request.cellIds.length === request.codes.length,+ "cell ids and codes must be the same length"+ );invariant(request.codes.length === request.names.length,- "cell codes and names must be the same length"+ "cell ids and names must be the same length");invariant(request.codes.length === request.configs.length,- "cell codes and configs must be the same length"+ "cell ids and configs must be the same length");return API.post<SaveKernelRequest>("/kernel/save", request);@@ -147,6 +154,7 @@ function createNetworkRequests(): EditRequests & RunRequests {export const {sendComponentValues,sendRename,+ sendRestart,sendSave,sendStdin,sendFormat,diff --git a/frontend/src/core/network/static-requests.ts b/frontend/src/core/network/static-requests.tsindex 90c1f0e4d4..28560cd706 100644--- a/frontend/src/core/network/static-requests.ts+++ b/frontend/src/core/network/static-requests.ts@@ -36,6 +36,7 @@ export function createStaticRequests(): EditRequests & RunRequests {Logger.log("Function requests are not supported in static mode");return null;},+ sendRestart: throwNotInEditMode,sendRun: throwNotInEditMode,sendRename: throwNotInEditMode,sendSave: throwNotInEditMode,diff --git a/frontend/src/core/network/types.ts b/frontend/src/core/network/types.tsindex 9f9f497ab4..8211ac23b0 100644--- a/frontend/src/core/network/types.ts+++ b/frontend/src/core/network/types.ts@@ -46,6 +46,7 @@ export interface RunRequest {}export interface SaveKernelRequest {+ cellIds: CellId[];filename: string;codes: string[];names: string[];@@ -146,6 +147,7 @@ export interface EditRequests {saveUserConfig: (request: SaveUserConfigRequest) => Promise<null>;saveAppConfig: (request: SaveAppConfigRequest) => Promise<null>;saveCellConfig: (request: SaveCellConfigRequest) => Promise<null>;+ sendRestart: () => Promise<null>;readCode: () => Promise<{ contents: string }>;// File explorer requestssendListFiles: (request: {diff --git a/frontend/src/core/websocket/useMarimoWebSocket.tsx b/frontend/src/core/websocket/useMarimoWebSocket.tsxindex 9d87f3e273..fb2a25d432 100644--- a/frontend/src/core/websocket/useMarimoWebSocket.tsx+++ b/frontend/src/core/websocket/useMarimoWebSocket.tsx@@ -25,13 +25,16 @@ import { isStaticNotebook } from "../static/static-state";import { useRef } from "react";import { jsonParseWithSpecialChar } from "@/utils/json/json-parser";import { VirtualFileTracker } from "../static/virtual-file-tracker";-import { bannerAtom } from "../errors/state";+import { Objects } from "@/utils/objects";+import { SessionId } from "../kernel/session";+import { useBannersActions } from "../errors/state";+import { generateUUID } from "@/utils/uuid";/*** WebSocket that connects to the Marimo kernel and handles incoming messages.*/export function useMarimoWebSocket(opts: {- sessionId: string;+ sessionId: SessionId;autoInstantiate: boolean;setCells: (cells: CellData[]) => void;}) {@@ -45,30 +48,64 @@ export function useMarimoWebSocket(opts: {const setLayoutView = useSetAtom(layoutViewAtom);const setLayoutData = useSetAtom(layoutDataAtom);const [connStatus, setConnStatus] = useAtom(connectionAtom);- const setBanner = useSetAtom(bannerAtom);+ const { addBanner } = useBannersActions();const handleMessage = (e: MessageEvent<string>) => {const msg = jsonParseWithSpecialChar<OperationMessage>(e.data);switch (msg.op) {case "kernel-ready": {- const { codes, names, layout, configs, cell_ids } = msg.data;+ const {+ codes,+ names,+ layout,+ configs,+ resumed,+ ui_values,+ cell_ids,+ last_executed_code = {},+ } = msg.data;// Set the layout, initial codes, cells- const cells = codes.map((code, i) =>- createCell({- id: cell_ids[i],+ const cells = codes.map((code, i) => {+ const cellId = cell_ids[i];++ // A cell is stale if we did not auto-instantiate (i.e. nothing has run yet)+ // or if the code has changed since the last time it was run.+ let edited = false;+ if (autoInstantiate) {+ const lastCodeRun = last_executed_code[cellId];+ if (lastCodeRun) {+ edited = lastCodeRun !== code;+ }+ } else {+ edited = true;+ }++ return createCell({+ id: cellId,code,- edited: !autoInstantiate,+ edited: edited,name: names[i],+ lastCodeRun: last_executed_code[cellId] ?? null,config: configs[i],- })- );+ });+ });+if (layout) {setLayoutView(layout.type);setLayoutData(deserializeLayout(layout.type, layout.data, cells));}setCells(cells);+ // If resumed, we don't need to instantiate the UI elements,+ // and we should read in th existing values from the kernel.+ if (resumed) {+ for (const [objectId, value] of Objects.entries(ui_values || {})) {+ UI_ELEMENT_REGISTRY.set(objectId, value);+ }+ return;+ }+// Auto-instantiate, in future this can be configurable// or include initial valuesconst objectIds: string[] = [];@@ -157,7 +194,10 @@ export function useMarimoWebSocket(opts: {});return;case "banner":- setBanner(msg.data);+ addBanner({+ ...msg.data,+ id: generateUUID(),+ });return;default:logNever(msg);diff --git a/frontend/src/hooks/useElapsedTime.ts b/frontend/src/hooks/useElapsedTime.tsindex 8906b3df3d..4dd686b9b8 100644--- a/frontend/src/hooks/useElapsedTime.ts+++ b/frontend/src/hooks/useElapsedTime.ts@@ -1,19 +1,20 @@/* Copyright 2024 Marimo. All rights reserved. */+import { Milliseconds, Time } from "@/utils/time";import { useEffect, useRef, useState } from "react";/*** Returns the elapsed time since mount, in milliseconds.*/-export function useElapsedTime() {- const startTime = useRef(Date.now());- const [endTime, setEndTime] = useState(Date.now());+export function useElapsedTime(initialStartTimeMs: Milliseconds) {+ const startTime = useRef(initialStartTimeMs);+ const [endTime, setEndTime] = useState(initialStartTimeMs);useEffect(() => {const step = 17; // 60 FPSconst interval = setInterval(() => {// Need to use Date.now() here because// setInterval could be paused if the tab is inactive.- setEndTime(Date.now());+ setEndTime(Time.now().toMilliseconds());}, step);return () => clearInterval(interval);diff --git a/frontend/src/main.tsx b/frontend/src/main.tsxindex 9868b887d1..4ea195ca56 100644--- a/frontend/src/main.tsx+++ b/frontend/src/main.tsx@@ -1,11 +1,9 @@/* Copyright 2024 Marimo. All rights reserved. */import React from "react";import ReactDOM from "react-dom/client";-import { worker } from "./mocks/browser";import { ThemeProvider } from "./theme/ThemeProvider";import { ErrorBoundary } from "./components/editor/boundary/ErrorBoundary";import { MarimoApp } from "./core/MarimoApp";-import { Logger } from "./utils/Logger";import { reportVitals } from "./utils/vitals";import { Provider } from "jotai";import { store } from "./core/state/jotai";@@ -20,21 +18,8 @@ maybeRegisterVSCodeBindings();* Main entry point for the Marimo app.** Sets up the Marimo app with a theme provider.- * This file will optionally start the MSW worker if enabled.*/-if (import.meta.env.DEV && import.meta.env.VITE_MSW) {- worker.start({- onUnhandledRequest(req) {- if (req.url.href.startsWith("/kernel")) {- Logger.error(- `Found an unhandled ${req.method} request to ${req.url.href}`- );- }- },- });-}-// If we're in static mode, we need to patch fetch to use the virtual fileif (isStaticNotebook()) {patchFetch();diff --git a/frontend/src/mocks/browser.ts b/frontend/src/mocks/browser.tsdeleted file mode 100644index 204668b080..0000000000--- a/frontend/src/mocks/browser.ts+++ /dev/null@@ -1,12 +0,0 @@-/* Copyright 2024 Marimo. All rights reserved. */-import { setupWorker } from "msw";-import { handlers } from "./handlers";-import { createMockServer } from "./socket";--// Create a mock server for the WebSocket connection.-if (import.meta.env.DEV && import.meta.env.VITE_MSW) {- createMockServer();-}--// This configures a Service Worker with the given request handlers.-export const worker = setupWorker(...handlers);diff --git a/frontend/src/mocks/handlers.ts b/frontend/src/mocks/handlers.tsdeleted file mode 100644index 90e6684eee..0000000000--- a/frontend/src/mocks/handlers.ts+++ /dev/null@@ -1,72 +0,0 @@-/* Copyright 2024 Marimo. All rights reserved. */-import { rest } from "msw";-import { SaveKernelRequest } from "../core/network/types";--export const handlers = [- // Run- rest.post("/api/kernel/run/", (req, res, ctx) => {- return res(- ctx.status(200),- ctx.json({- status: "ok",- })- );- }),-- // Save- rest.post<SaveKernelRequest>("/api/kernel/save/", async (req, res, ctx) => {- sessionStorage.setItem(- "merimo:msw:save",- JSON.stringify(await req.json<SaveKernelRequest>())- );-- return res(- ctx.status(200),- ctx.json({- status: "ok",- })- );- }),-- // Instantiate- rest.post("/api/kernel/instantiate/", (req, res, ctx) => {- return res(- ctx.status(200),- ctx.json({- status: "ok",- })- );- }),-- // Directory autocomplete- rest.post("/api/kernel/directory_autocomplete/", (req, res, ctx) => {- return res(- ctx.status(200),- ctx.json({- status: "ok",- matches: [],- files: [],- })- );- }),-- // Rename- rest.post("/api/kernel/rename/", (req, res, ctx) => {- return res(- ctx.status(200),- ctx.json({- status: "ok",- })- );- }),-- // Delete- rest.post("/api/kernel/delete/", (req, res, ctx) => {- return res(- ctx.status(200),- ctx.json({- status: "ok",- })- );- }),-];diff --git a/frontend/src/mocks/socket.ts b/frontend/src/mocks/socket.tsdeleted file mode 100644index ed10080e26..0000000000--- a/frontend/src/mocks/socket.ts+++ /dev/null@@ -1,21 +0,0 @@-/* Copyright 2024 Marimo. All rights reserved. */-import { Server } from "mock-socket";-import { getKernelId } from "../core/kernel/kernel";-import { UUID } from "../utils/uuid";-import { Logger } from "../utils/Logger";--export function createMockServer() {- const fakeURL = `ws://${- window.location.host- }/ws?kernel_id=${getKernelId()}&uuid=${UUID}`;- const mockServer = new Server(fakeURL);-- mockServer.on("connection", (socket) => {- socket.on("message", (data) => {- Logger.log("[mock] message", data);- });- socket.on("close", () => {- Logger.log("[mock] close");- });- });-}diff --git a/frontend/src/stories/cell.stories.tsx b/frontend/src/stories/cell.stories.tsxindex aa0a2dee80..d147fe9dde 100644--- a/frontend/src/stories/cell.stories.tsx+++ b/frontend/src/stories/cell.stories.tsx@@ -4,6 +4,7 @@ import { Cell, CellProps } from "../components/editor/Cell";import { TooltipProvider } from "../components/ui/tooltip";import { CellId } from "../core/cells/ids";import { Logger } from "@/utils/Logger";+import { Milliseconds, Seconds } from "@/utils/time";const meta: Meta<typeof Cell> = {title: "Cell",@@ -28,8 +29,8 @@ const props: CellProps = {stopped: false,updateCellCode: Logger.log,prepareForRun: Logger.log,- runStartTimestamp: 0,- runElapsedTimeMs: 10,+ runStartTimestamp: 0 as Seconds,+ runElapsedTimeMs: 10 as Milliseconds,serializedEditorState: null,mode: "edit",name: "cell_1",@@ -91,7 +92,7 @@ export const WithOutput: Story = {<TooltipProvider><Cell{...props}- runElapsedTimeMs={20}+ runElapsedTimeMs={20 as Milliseconds}output={{channel: "output",data: "<span class='markdown'><h1>Layout</h1>\n<p><code>marimo</code> provides functions to help you lay out your output, such as\nin rows and columns, accordions, tabs, and callouts. This tutorial\nshows some examples.</p></span>",@@ -110,7 +111,7 @@ export const WithLargeOutput: Story = {<TooltipProvider><Cell{...props}- runElapsedTimeMs={20}+ runElapsedTimeMs={20 as Milliseconds}output={{channel: "output",data: "<span class='markdown'><h1>Layout</h1>\n<p><code>marimo</code> provides functions to help you lay out your output, such as\nin rows and columns, accordions, tabs, and callouts. This tutorial\nshows some examples.</p></span>".repeat(@@ -131,7 +132,7 @@ export const UnsavedEditsOutput: Story = {<TooltipProvider><Cell{...props}- runElapsedTimeMs={20}+ runElapsedTimeMs={20 as Milliseconds}edited={true}output={{channel: "output",@@ -151,7 +152,7 @@ export const InterruptedOutput: Story = {<TooltipProvider><Cell{...props}- runElapsedTimeMs={20}+ runElapsedTimeMs={20 as Milliseconds}interrupted={true}output={{channel: "output",@@ -171,7 +172,7 @@ export const WithError: Story = {<TooltipProvider><Cell{...props}- runElapsedTimeMs={20}+ runElapsedTimeMs={20 as Milliseconds}errored={true}output={{channel: "output",@@ -191,7 +192,7 @@ export const Disabled: Story = {<TooltipProvider><Cell{...props}- runElapsedTimeMs={20}+ runElapsedTimeMs={20 as Milliseconds}config={{disabled: true,}}@@ -213,7 +214,7 @@ export const DisabledTransitively: Story = {<TooltipProvider><Cell{...props}- runElapsedTimeMs={20}+ runElapsedTimeMs={20 as Milliseconds}status="disabled-transitively"output={{channel: "output",@@ -233,7 +234,7 @@ export const StaleStatus: Story = {<TooltipProvider><Cell{...props}- runElapsedTimeMs={20}+ runElapsedTimeMs={20 as Milliseconds}status="stale"output={{channel: "output",@@ -253,7 +254,7 @@ export const StaleAndEditedStatus: Story = {<TooltipProvider><Cell{...props}- runElapsedTimeMs={20}+ runElapsedTimeMs={20 as Milliseconds}status="stale"output={{channel: "output",@@ -273,7 +274,7 @@ export const DisabledAndStaleStatus: Story = {<TooltipProvider><Cell{...props}- runElapsedTimeMs={20}+ runElapsedTimeMs={20 as Milliseconds}config={{disabled: true,}}@@ -296,7 +297,7 @@ export const Running: Story = {<TooltipProvider><Cell{...props}- runElapsedTimeMs={20}+ runElapsedTimeMs={20 as Milliseconds}status="running"output={{channel: "output",diff --git a/frontend/src/utils/__tests__/time.test.ts b/frontend/src/utils/__tests__/time.test.tsnew file mode 100644index 0000000000..9b1e3a8383--- /dev/null+++ b/frontend/src/utils/__tests__/time.test.ts@@ -0,0 +1,61 @@+/* Copyright 2024 Marimo. All rights reserved. */+import { expect, describe, it } from "vitest";+import { Milliseconds, Time, Seconds } from "../time";++describe("Time class", () => {+ describe("fromMilliseconds", () => {+ it("should create a Time instance from milliseconds", () => {+ const ms: Milliseconds = 1000 as Milliseconds;+ const time = Time.fromMilliseconds(ms);+ expect(time).toBeInstanceOf(Time);+ expect(time.toMilliseconds()).toBe(ms);+ });++ it("should return null when null is passed", () => {+ const time = Time.fromMilliseconds(null);+ expect(time).toBeNull();+ });+ });++ describe("fromSeconds", () => {+ it("should create a Time instance from seconds", () => {+ const s: Seconds = 1 as Seconds;+ const time = Time.fromSeconds(s);+ expect(time).toBeInstanceOf(Time);+ expect(time.toSeconds()).toBe(s);+ });++ it("should return null when null is passed", () => {+ const time = Time.fromSeconds(null);+ expect(time).toBeNull();+ });+ });++ describe("now", () => {+ it("should create a Time instance representing the current time", () => {+ const before = Date.now();+ const time = Time.now();+ const after = Date.now();+ expect(time.toMilliseconds()).toBeGreaterThanOrEqual(before);+ expect(time.toMilliseconds()).toBeLessThanOrEqual(after);+ });+ });++ describe("toMilliseconds", () => {+ it("should return the time in milliseconds", () => {+ const ms = 1500 as Milliseconds;+ // @ts-expect-error Directly using the private constructor for testing+ const time = new Time(ms);+ expect(time.toMilliseconds()).toBe(ms);+ });+ });++ describe("toSeconds", () => {+ it("should return the time in seconds", () => {+ const ms = 3000 as Milliseconds;+ // @ts-expect-error Directly using the private constructor for testing+ const time = new Time(ms);+ expect(time.toSeconds()).toBe(3);+ });+ });+});diff --git a/frontend/src/utils/createReducer.ts b/frontend/src/utils/createReducer.tsindex 926df1ac43..d268644368 100644--- a/frontend/src/utils/createReducer.ts+++ b/frontend/src/utils/createReducer.ts@@ -46,7 +46,7 @@ export function createReducer<RH extends ReducerHandlers<NoInfer<State>>>(initialState: () => State, reducers: RH): ReducerCreatorResult<State, RH> {return {- reducer: (state, action: ReducerAction<any>) => {+ reducer: (state, action: ReducerAction<RH>) => {state = state || initialState();if (action.type in reducers) {return reducers[action.type](state, action.payload);diff --git a/frontend/src/utils/objects.ts b/frontend/src/utils/objects.tsindex df3e5b42ef..51a86022d2 100644--- a/frontend/src/utils/objects.ts+++ b/frontend/src/utils/objects.ts@@ -2,14 +2,14 @@export const Objects = {mapValues<T, U, K extends string | number>(obj: Record<K, T>,- mapper: (value: T) => U+ mapper: (value: T, key: K) => U): Record<K, U> {if (!obj) {return obj as Record<K, U>;}return Objects.fromEntries(- Objects.entries(obj).map(([key, value]) => [key, mapper(value)])+ Objects.entries(obj).map(([key, value]) => [key, mapper(value, key)]));},/**diff --git a/frontend/src/utils/time.ts b/frontend/src/utils/time.tsnew file mode 100644index 0000000000..db618f5348--- /dev/null+++ b/frontend/src/utils/time.ts@@ -0,0 +1,39 @@+/* Copyright 2024 Marimo. All rights reserved. */++export type Milliseconds = number & { __type__: "milliseconds" };++export type Seconds = number & { __type__: "seconds" };++export class Time {+ static fromMilliseconds(ms: Milliseconds): Time;+ static fromMilliseconds(ms: Milliseconds | null): Time | null;+ static fromMilliseconds(ms: Milliseconds | null): Time | null {+ if (ms == null) {+ return null;+ }+ return new Time(ms);+ }++ static fromSeconds(s: Seconds): Time;+ static fromSeconds(s: Seconds | null): Time | null;+ static fromSeconds(s: Seconds | null): Time | null {+ if (s == null) {+ return null;+ }+ return new Time((s * 1000) as Milliseconds);+ }++ static now(): Time {+ return new Time(Date.now() as Milliseconds);+ }++ private constructor(private readonly ms: Milliseconds) {}++ toMilliseconds(): Milliseconds {+ return this.ms;+ }++ toSeconds(): Seconds {+ return (this.ms / 1000) as Seconds;+ }+}diff --git a/frontend/src/utils/uuid.ts b/frontend/src/utils/uuid.tsindex 6e72a0e833..3373a0c9c3 100644--- a/frontend/src/utils/uuid.ts+++ b/frontend/src/utils/uuid.ts@@ -9,5 +9,3 @@ export function generateUUID() {});}--export const UUID = generateUUID();diff --git a/frontend/tsconfig.json b/frontend/tsconfig.jsonindex 795ada647c..8ca62dd624 100644--- a/frontend/tsconfig.json+++ b/frontend/tsconfig.json@@ -36,8 +36,7 @@// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */// "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */"types": [- "vite/client",- "msw"+ "vite/client"] /* Specify type package names to be included without being referenced in a source file. */,// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */// "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */diff --git a/marimo/_ast/app.py b/marimo/_ast/app.pyindex 5aa23808f5..574284892a 100644--- a/marimo/_ast/app.py+++ b/marimo/_ast/app.py@@ -11,7 +11,6 @@ from typing import (Iterable,Literal,Optional,- OrderedDict,Union,cast,)@@ -54,12 +53,14 @@ class _AppConfig:def asdict(self) -> dict[str, Any]:return asdict(self)- def update(self, updates: dict[str, Any]) -> None:+ def update(self, updates: dict[str, Any]) -> _AppConfig:config_dict = asdict(self)for key in updates:if key in config_dict:self.__setattr__(key, updates[key])+ return self+@dataclassclass CellData:@@ -233,7 +234,6 @@ class CellManager:def __init__(self) -> None:self._cell_data: dict[CellId_t, CellData] = {}- self._cell_data = OrderedDict()self.unparsable = Falseself.random_seed = random.Random(42)@@ -394,3 +394,27 @@ class InternalApp:@propertydef cell_manager(self) -> CellManager:return self._app._cell_manager++ def update_config(self, updates: dict[str, Any]) -> _AppConfig:+ return self.config.update(updates)++ def with_data(+ self,+ *,+ cell_ids: Iterable[CellId_t],+ codes: Iterable[str],+ names: Iterable[str],+ configs: Iterable[CellConfig],+ ) -> InternalApp:+ new_cell_manager = CellManager()+ for cell_id, code, name, config in zip(+ cell_ids, codes, names, configs+ ):+ new_cell_manager.register_cell(+ cell_id=cell_id,+ code=code,+ name=name,+ config=config,+ )+ self._app._cell_manager = new_cell_manager+ return selfdiff --git a/marimo/_messaging/cell_output.py b/marimo/_messaging/cell_output.pyindex 6709f53bba..b1a9017e51 100644--- a/marimo/_messaging/cell_output.py+++ b/marimo/_messaging/cell_output.py@@ -7,15 +7,49 @@ from __future__ import annotationsimport timefrom dataclasses import dataclass, field+from enum import Enumfrom typing import Sequence, Unionfrom marimo._messaging.errors import Error+from marimo._messaging.mimetypes import KnownMimeType+++class CellChannel(str, Enum):+ """The channel of a cell's output."""++ STDOUT = "stdout"+ STDERR = "stderr"+ STDIN = "stdin"+ OUTPUT = "output"+ MARIMO_ERROR = "marimo-error"+ MEDIA = "media"++ def __repr__(self) -> str:+ return self.value@dataclassclass CellOutput:# descriptive name about the kind of output: e.g., stdout, stderr, ...- channel: str- mimetype: str+ channel: CellChannel+ mimetype: KnownMimeTypedata: Union[str, Sequence[Error]]timestamp: float = field(default_factory=lambda: time.time())++ @staticmethod+ def stdout(data: str) -> CellOutput:+ return CellOutput(+ channel=CellChannel.STDOUT, mimetype="text/plain", data=data+ )++ @staticmethod+ def stderr(data: str) -> CellOutput:+ return CellOutput(+ channel=CellChannel.STDERR, mimetype="text/plain", data=data+ )++ @staticmethod+ def stdin(data: str) -> CellOutput:+ return CellOutput(+ channel=CellChannel.STDIN, mimetype="text/plain", data=data+ )diff --git a/marimo/_messaging/console_output_worker.py b/marimo/_messaging/console_output_worker.pyindex 89c55ab9ec..c0ae6478ec 100644--- a/marimo/_messaging/console_output_worker.py+++ b/marimo/_messaging/console_output_worker.py@@ -8,14 +8,14 @@ from threading import Conditionfrom typing import TYPE_CHECKING, Literalfrom marimo._ast.cell import CellId_t-from marimo._messaging.cell_output import CellOutput+from marimo._messaging.cell_output import CellChannel, CellOutputif TYPE_CHECKING:from typing import Optionalfrom marimo._messaging.streams import Stream-StreamT = Literal["stdout", "stderr", "stdin"]+StreamT = Literal[CellChannel.STDERR, CellChannel.STDOUT, CellChannel.STDIN]# Flush console outputs every 10msTIMEOUT_S = 0.01diff --git a/marimo/_messaging/mimetypes.py b/marimo/_messaging/mimetypes.pynew file mode 100644index 0000000000..2552d81721--- /dev/null+++ b/marimo/_messaging/mimetypes.py@@ -0,0 +1,21 @@+# Copyright 2024 Marimo. All rights reserved.+from typing import Literal++# It is convenient to write mimetypes as strings,+# but can lead to typos. This literal type+# helps us avoid typos.+KnownMimeType = Literal[+ "application/json",+ "application/vnd.marimo+error",+ "image/png",+ "image/svg+xml",+ "image/tiff",+ "image/avif",+ "image/bmp",+ "image/gif",+ "image/jpeg",+ "video/mp4",+ "video/mpeg",+ "text/html",+ "text/plain",+]diff --git a/marimo/_messaging/ops.py b/marimo/_messaging/ops.pyindex 48ec315fed..469bc8b7ed 100644--- a/marimo/_messaging/ops.py+++ b/marimo/_messaging/ops.py@@ -14,18 +14,21 @@ from typing import (Any,ClassVar,Dict,+ List,Literal,Optional,Sequence,+ Tuple,Union,cast,)from marimo import _loggers as loggersfrom marimo._ast.cell import CellConfig, CellId_t, CellStatusType-from marimo._messaging.cell_output import CellOutput+from marimo._messaging.cell_output import CellChannel, CellOutputfrom marimo._messaging.completion_option import CompletionOptionfrom marimo._messaging.errors import Error+from marimo._messaging.mimetypes import KnownMimeTypefrom marimo._messaging.streams import OUTPUT_MAX_BYTES, Streamfrom marimo._output.hypertext import Htmlfrom marimo._plugins.core.web_component import JSONType@@ -71,12 +74,14 @@ class CellOp(Op):name: ClassVar[str] = "cell-op"cell_id: CellId_toutput: Optional[CellOutput] = None- console: Optional[Union[CellOutput, list[CellOutput]]] = None+ console: Optional[Union[CellOutput, List[CellOutput]]] = Nonestatus: Optional[CellStatusType] = Nonetimestamp: float = field(default_factory=lambda: time.time())@staticmethod- def maybe_truncate_output(mimetype: str, data: str) -> tuple[str, str]:+ def maybe_truncate_output(+ mimetype: KnownMimeType, data: str+ ) -> tuple[KnownMimeType, str]:if (size := sys.getsizeof(data)) > OUTPUT_MAX_BYTES:from marimo._output.md import mdfrom marimo._plugins.stateless.callout import callout@@ -111,8 +116,8 @@ class CellOp(Op):@staticmethoddef broadcast_output(- channel: str,- mimetype: str,+ channel: CellChannel,+ mimetype: KnownMimeType,data: str,cell_id: Optional[CellId_t],status: Optional[CellStatusType],@@ -144,7 +149,7 @@ class CellOp(Op):CellOp(cell_id=cell_id,output=CellOutput(- channel="output",+ channel=CellChannel.OUTPUT,mimetype="text/plain",data="",),@@ -153,8 +158,8 @@ class CellOp(Op):@staticmethoddef broadcast_console_output(- channel: str,- mimetype: str,+ channel: CellChannel,+ mimetype: KnownMimeType,data: str,cell_id: Optional[CellId_t],status: Optional[CellStatusType],@@ -193,7 +198,7 @@ class CellOp(Op):CellOp(cell_id=cell_id,output=CellOutput(- channel="marimo-error",+ channel=CellChannel.MARIMO_ERROR,mimetype="application/vnd.marimo+error",data=data,),@@ -207,8 +212,8 @@ class HumanReadableStatus(Op):"""Human-readable status."""code: Literal["ok", "error"]- title: str | None = None- message: str | None = None+ title: Union[str, None] = None+ message: Union[str, None] = None@dataclass@@ -249,11 +254,17 @@ class KernelReady(Op):"""Kernel is ready for execution."""name: ClassVar[str] = "kernel-ready"- cell_ids: tuple[CellId_t, ...]- codes: tuple[str, ...]- names: tuple[str, ...]+ cell_ids: Tuple[CellId_t, ...]+ codes: Tuple[str, ...]+ names: Tuple[str, ...]layout: Optional[LayoutConfig]- configs: tuple[CellConfig, ...]+ configs: Tuple[CellConfig, ...]+ # Whether the kernel was resumed from a previous session+ resumed: bool+ # If the kernel was resumed, the values of the UI elements+ ui_values: Optional[Dict[str, JSONType]]+ # If the kernel was resumed, the last executed code for each cell+ last_executed_code: Optional[Dict[CellId_t, str]]@dataclass@@ -263,7 +274,7 @@ class CompletionResult(Op):name: ClassVar[str] = "completion-result"completion_id: strprefix_length: int- options: list[CompletionOption]+ options: List[CompletionOption]@dataclass@@ -275,11 +286,26 @@ class Alert(Op):variant: Optional[Literal["danger"]] = None+@dataclass+class Reconnected(Op):+ name: ClassVar[str] = "reconnected"+++@dataclass+class Banner(Op):+ name: ClassVar[str] = "banner"+ title: str+ # description may be HTML+ description: str+ variant: Optional[Literal["danger"]] = None+ action: Optional[Literal["restart"]] = None++@dataclassclass VariableDeclaration:name: str- declared_by: list[CellId_t]- used_by: list[CellId_t]+ declared_by: List[CellId_t]+ used_by: List[CellId_t]@dataclass@@ -288,7 +314,9 @@ class VariableValue:datatype: Optional[str]value: Optional[str]- def __init__(self, name: str, value: object):+ def __init__(+ self, name: str, value: object, datatype: Optional[str] = None+ ) -> None:self.name = name# Defensively try-catch attribute accesses, which could raise@@ -296,7 +324,7 @@ class VariableValue:try:self.datatype = type(value).__name__ if value is not None else Noneexcept Exception:- self.datatype = None+ self.datatype = datatypetry:self.value = self._format_value(value)@@ -322,7 +350,7 @@ class Variables(Op):"""List of variable declarations."""name: ClassVar[str] = "variables"- variables: list[VariableDeclaration]+ variables: List[VariableDeclaration]@dataclass@@ -330,4 +358,21 @@ class VariableValues(Op):"""List of variables and their types/values."""name: ClassVar[str] = "variable-values"- variables: list[VariableValue]+ variables: List[VariableValue]+++MessageOperation = Union[+ CellOp,+ HumanReadableStatus,+ Reconnected,+ FunctionCallResult,+ RemoveUIElements,+ Interrupted,+ CompletedRun,+ KernelReady,+ CompletionResult,+ Alert,+ Banner,+ Variables,+ VariableValues,+]diff --git a/marimo/_messaging/streams.py b/marimo/_messaging/streams.pyindex 6eada7f12e..4f51623e03 100644--- a/marimo/_messaging/streams.py+++ b/marimo/_messaging/streams.py@@ -7,13 +7,15 @@ import osimport sysimport threadingfrom collections import deque-from multiprocessing.connection import Connectionfrom typing import Any, Iterable, Iterator, Optionalfrom marimo import _loggersfrom marimo._ast.cell import CellId_t+from marimo._messaging.cell_output import CellChannelfrom marimo._messaging.console_output_worker import ConsoleMsg, buffered_writer+from marimo._messaging.types import KernelMessagefrom marimo._server.types import QueueType+from marimo._utils.typed_connection import TypedConnectionLOGGER = _loggers.marimo_logger()@@ -48,7 +50,7 @@ class Stream:def __init__(self,- pipe: Connection,+ pipe: TypedConnection[KernelMessage],input_queue: QueueType[str],cell_id: Optional[CellId_t] = None,):@@ -124,7 +126,11 @@ class Stdout(io.TextIOBase):)data = data[: int(STD_STREAM_MAX_BYTES)] + " ... "self.stream.console_msg_queue.append(- ConsoleMsg(stream="stdout", cell_id=self.stream.cell_id, data=data)+ ConsoleMsg(+ stream=CellChannel.STDOUT,+ cell_id=self.stream.cell_id,+ data=data,+ ))with self.stream.console_msg_cv:self.stream.console_msg_cv.notify()@@ -182,7 +188,9 @@ class Stderr(io.TextIOBase):with self.stream.console_msg_cv:self.stream.console_msg_queue.append(ConsoleMsg(- stream="stderr", cell_id=self.stream.cell_id, data=data+ stream=CellChannel.STDERR,+ cell_id=self.stream.cell_id,+ data=data,))self.stream.console_msg_cv.notify()@@ -232,7 +240,9 @@ class Stdin(io.TextIOBase):# This sends a prompt request to the frontend.self.stream.console_msg_queue.append(ConsoleMsg(- stream="stdin", cell_id=self.stream.cell_id, data=prompt+ stream=CellChannel.STDIN,+ cell_id=self.stream.cell_id,+ data=prompt,))self.stream.console_msg_cv.notify()diff --git a/marimo/_messaging/types.py b/marimo/_messaging/types.pynew file mode 100644index 0000000000..8ed1990e26--- /dev/null+++ b/marimo/_messaging/types.py@@ -0,0 +1,6 @@+# Copyright 2024 Marimo. All rights reserved.+from typing import Any, Tuple++# The message from the kernel is a tuple of message type+# and a json representation of the message+KernelMessage = Tuple[str, Any]diff --git a/marimo/_output/formatters/altair_formatters.py b/marimo/_output/formatters/altair_formatters.pyindex 7207f5de0e..4234d4c945 100644--- a/marimo/_output/formatters/altair_formatters.py+++ b/marimo/_output/formatters/altair_formatters.py@@ -1,6 +1,7 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations+from marimo._messaging.mimetypes import KnownMimeTypefrom marimo._output.formatters.formatter_factory import FormatterFactoryfrom marimo._output.utils import flatten_string@@ -18,7 +19,7 @@ class AltairFormatter(FormatterFactory):from marimo._output import formatting@formatting.formatter(altair.TopLevelMixin)- def _show_chart(chart: altair.Chart) -> tuple[str, str]:+ def _show_chart(chart: altair.Chart) -> tuple[KnownMimeType, str]:# TODO(akshayka): remove the `onload` hack and handle iframe# resizing entirely in the frontend# `__resizeIframe` is a script defined in the frontend that setsdiff --git a/marimo/_output/formatters/leafmap_formatters.py b/marimo/_output/formatters/leafmap_formatters.pyindex d1e07ad6a1..654e1335f9 100644--- a/marimo/_output/formatters/leafmap_formatters.py+++ b/marimo/_output/formatters/leafmap_formatters.py@@ -2,6 +2,7 @@from __future__ import annotationsimport marimo._output.data.data as mo_data+from marimo._messaging.mimetypes import KnownMimeTypefrom marimo._output.formatters.formatter_factory import FormatterFactoryfrom marimo._output.utils import flatten_string@@ -17,7 +18,7 @@ class LeafmapFormatter(FormatterFactory):from marimo._output import formatting@formatting.formatter(leafmap.Map)- def _show_map(lmap: leafmap.Map) -> tuple[str, str]:+ def _show_map(lmap: leafmap.Map) -> tuple[KnownMimeType, str]:# 540px is the pixel height that makes the map fit in the# notebook without scrollingheight = lmap.layout.height or "540px"diff --git a/marimo/_output/formatters/matplotlib_formatters.py b/marimo/_output/formatters/matplotlib_formatters.pyindex eb8984f69c..ddf7b101c8 100644--- a/marimo/_output/formatters/matplotlib_formatters.py+++ b/marimo/_output/formatters/matplotlib_formatters.py@@ -1,6 +1,7 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations+from marimo._messaging.mimetypes import KnownMimeTypefrom marimo._output.formatters.formatter_factory import FormatterFactory@@ -28,10 +29,10 @@ class MatplotlibFormatter(FormatterFactory):from marimo._output import formattingfrom marimo._output.utils import build_data_url- def mime_data_artist(artist: Artist) -> tuple[str, str]:+ def mime_data_artist(artist: Artist) -> tuple[KnownMimeType, str]:buf = io.BytesIO()artist.figure.savefig(buf, format="png")- mimetype = "image/png"+ mimetype: KnownMimeType = "image/png"plot_bytes = base64.b64encode(buf.getvalue())return (mimetype,@@ -45,7 +46,7 @@ class MatplotlibFormatter(FormatterFactory):# use an explicit formatter, no need to try to format subclasses of# BarContainer@formatting.formatter(BarContainer)- def _show_bar_container(bc: BarContainer) -> tuple[str, str]:+ def _show_bar_container(bc: BarContainer) -> tuple[KnownMimeType, str]:if len(bc.patches) > 0:return mime_data_artist(bc.patches[0].figure)else:diff --git a/marimo/_output/formatters/pandas_formatters.py b/marimo/_output/formatters/pandas_formatters.pyindex 1737272008..b1c98699b4 100644--- a/marimo/_output/formatters/pandas_formatters.py+++ b/marimo/_output/formatters/pandas_formatters.py@@ -3,6 +3,7 @@ from __future__ import annotationsfrom typing import Any+from marimo._messaging.mimetypes import KnownMimeTypefrom marimo._output.formatters.formatter_factory import FormatterFactoryfrom marimo._output.utils import flatten_string@@ -22,7 +23,7 @@ class PandasFormatter(FormatterFactory):from marimo._output import formatting@formatting.formatter(pd.DataFrame)- def _show_dataframe(df: pd.DataFrame) -> tuple[str, str]:+ def _show_dataframe(df: pd.DataFrame) -> tuple[KnownMimeType, str]:max_rows = pd.get_option("display.max_rows")max_columns = pd.get_option("display.max_columns")show_dimensions_option = pd.get_option("display.show_dimensions")@@ -58,7 +59,7 @@ class PandasFormatter(FormatterFactory):)@formatting.formatter(pd.Series)- def _show_series(series: pd.Series[Any]) -> tuple[str, str]:+ def _show_series(series: pd.Series[Any]) -> tuple[KnownMimeType, str]:max_rows = pd.get_option("display.max_rows")show_dimensions_option = pd.get_option("display.show_dimensions")if show_dimensions_option == "truncate":diff --git a/marimo/_output/formatters/plotly_formatters.py b/marimo/_output/formatters/plotly_formatters.pyindex 57ce49057b..9ab32e30a4 100644--- a/marimo/_output/formatters/plotly_formatters.py+++ b/marimo/_output/formatters/plotly_formatters.py@@ -3,6 +3,7 @@ from __future__ import annotationsimport json+from marimo._messaging.mimetypes import KnownMimeTypefrom marimo._output.formatters.formatter_factory import FormatterFactoryfrom marimo._output.hypertext import Htmlfrom marimo._plugins.core.web_component import build_stateless_plugin@@ -22,7 +23,7 @@ class PlotlyFormatter(FormatterFactory):@formatting.formatter(plotly.graph_objects.Figure)def _show_plotly_figure(fig: plotly.graph_objects.Figure,- ) -> tuple[str, str]:+ ) -> tuple[KnownMimeType, str]:json_str = plotly.io.to_json(fig)plugin = Html(build_stateless_plugin(diff --git a/marimo/_output/formatters/seaborn_formatters.py b/marimo/_output/formatters/seaborn_formatters.pyindex 25f6c7b656..570ac475be 100644--- a/marimo/_output/formatters/seaborn_formatters.py+++ b/marimo/_output/formatters/seaborn_formatters.py@@ -1,6 +1,7 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations+from marimo._messaging.mimetypes import KnownMimeTypefrom marimo._output.formatters.formatter_factory import FormatterFactory@@ -19,7 +20,7 @@ class SeabornFormatter(FormatterFactory):from marimo._output import formattingfrom marimo._output.mime import MIME- def _show_ax_or_subplots(grid: Any) -> tuple[str, str]:+ def _show_ax_or_subplots(grid: Any) -> tuple[KnownMimeType, str]:# Seaborn uses matplotlib under the hood: figures and axes are# instances of matplotlib's Artist class. (We've monkey pathed# `Artist` to implement the MIME protocol.)@@ -35,15 +36,17 @@ class SeabornFormatter(FormatterFactory):@formatting.formatter(seaborn.axisgrid.FacetGrid)def _show_facet_grid(fg: seaborn.axisgrid.FacetGrid,- ) -> tuple[str, str]:+ ) -> tuple[KnownMimeType, str]:return _show_ax_or_subplots(fg)@formatting.formatter(seaborn.axisgrid.PairGrid)- def _show_pair_grid(pg: seaborn.axisgrid.PairGrid) -> tuple[str, str]:+ def _show_pair_grid(+ pg: seaborn.axisgrid.PairGrid,+ ) -> tuple[KnownMimeType, str]:return _show_ax_or_subplots(pg)@formatting.formatter(seaborn.axisgrid.JointGrid)def _show_joint_grid(jg: seaborn.axisgrid.JointGrid,- ) -> tuple[str, str]:+ ) -> tuple[KnownMimeType, str]:return _show_ax_or_subplots(jg)diff --git a/marimo/_output/formatters/structures.py b/marimo/_output/formatters/structures.pyindex ed22cc8922..5d18e7356a 100644--- a/marimo/_output/formatters/structures.py+++ b/marimo/_output/formatters/structures.py@@ -4,6 +4,7 @@ from __future__ import annotationsimport jsonfrom typing import Any, Union+from marimo._messaging.mimetypes import KnownMimeTypefrom marimo._output import formattingfrom marimo._output.formatters.formatter_factory import FormatterFactoryfrom marimo._utils.flatten import CyclicStructureError, flatten@@ -42,7 +43,7 @@ class StructuresFormatter(FormatterFactory):@formatting.formatter(dict)def _format_structure(t: Union[tuple[Any, ...], list[Any], dict[str, Any]]- ) -> tuple[str, str]:+ ) -> tuple[KnownMimeType, str]:try:formatted_structure = format_structure(t)except CyclicStructureError:diff --git a/marimo/_output/formatting.py b/marimo/_output/formatting.pyindex 06af809d99..b9316f358e 100644--- a/marimo/_output/formatting.py+++ b/marimo/_output/formatting.py@@ -28,6 +28,7 @@ from html import escapefrom typing import Any, Callable, Optional, Tuple, Type, TypeVarfrom marimo import _loggers as loggers+from marimo._messaging.mimetypes import KnownMimeTypefrom marimo._output.hypertext import Htmlfrom marimo._output.rich_help import mddocfrom marimo._output.utils import flatten_string@@ -36,7 +37,7 @@ from marimo._plugins.stateless.json_output import json_outputT = TypeVar("T")# we use Tuple instead of the builtin tuple for py3.8 compatibility-Formatter = Callable[[T], Tuple[str, str]]+Formatter = Callable[[T], Tuple[KnownMimeType, str]]FORMATTERS: dict[Type[Any], Formatter[Any]] = {}LOGGER = loggers.marimo_logger()@@ -92,7 +93,7 @@ def get_formatter(obj: T) -> Optional[Formatter[T]]:return Noneif callable(method):- def f(obj: T) -> tuple[str, str]:+ def f(obj: T) -> tuple[KnownMimeType, str]:return obj._mime_() # type: ignorereturn f@@ -102,7 +103,7 @@ def get_formatter(obj: T) -> Optional[Formatter[T]]:return Noneif callable(method):- def f(obj: T) -> tuple[str, str]:+ def f(obj: T) -> tuple[KnownMimeType, str]:return ("text/html", obj._repr_html_()) # type: ignorereturn f@@ -111,7 +112,7 @@ def get_formatter(obj: T) -> Optional[Formatter[T]]:@dataclassclass FormattedOutput:- mimetype: str+ mimetype: KnownMimeTypedata: strtraceback: Optional[str] = Nonediff --git a/marimo/_output/hypertext.py b/marimo/_output/hypertext.pyindex e5dc81b689..c726dd567d 100644--- a/marimo/_output/hypertext.py+++ b/marimo/_output/hypertext.py@@ -3,6 +3,7 @@ from __future__ import annotationsfrom typing import TYPE_CHECKING, Any, Literal, final+from marimo._messaging.mimetypes import KnownMimeTypefrom marimo._output.mime import MIMEfrom marimo._output.rich_help import mddocfrom marimo._output.utils import flatten_string@@ -110,7 +111,7 @@ class Html(MIME):return self._text@final- def _mime_(self) -> tuple[str, str]:+ def _mime_(self) -> tuple[KnownMimeType, str]:return ("text/html", self.text)def __format__(self, spec: str) -> str:diff --git a/marimo/_output/mime.py b/marimo/_output/mime.pyindex 7b0d6e9b1a..45d312f12d 100644--- a/marimo/_output/mime.py+++ b/marimo/_output/mime.py@@ -3,6 +3,8 @@ from __future__ import annotationsfrom typing import Protocol+from marimo._messaging.mimetypes import KnownMimeType+class MIME(Protocol):"""Protocol for instantiating objects using marimo's media viewer.@@ -13,7 +15,7 @@ class MIME(Protocol):# TODO(akshayka): Single source of truth for supported mimetypes. The# documented types below are copied from the frontend- def _mime_(self) -> tuple[str, str]:+ def _mime_(self) -> tuple[KnownMimeType, str]:"""Return a tuple (mimetype, data)Return a mimetype and the string data to instantiate it in marimo'sdiff --git a/marimo/_output/mpl.py b/marimo/_output/mpl.pyindex 38e24c8b3b..e2e6da5fe5 100644--- a/marimo/_output/mpl.py+++ b/marimo/_output/mpl.py@@ -19,6 +19,8 @@ import matplotlib.pyplot as plt # type: ignorefrom matplotlib.backend_bases import FigureManagerBase, Gcf # type: ignorefrom matplotlib.backends.backend_agg import FigureCanvasAgg # type: ignore+from marimo._messaging.cell_output import CellChannel+from marimo._messaging.mimetypes import KnownMimeTypefrom marimo._messaging.ops import CellOpfrom marimo._output.utils import build_data_url@@ -35,10 +37,10 @@ def _internal_show(canvas: FigureCanvasAgg) -> None:buf.seek(0)canvas.figure.savefig(buf, format="png")plt.close(canvas.figure)- mimetype = "image/png"+ mimetype: KnownMimeType = "image/png"plot_bytes = base64.b64encode(buf.getvalue())CellOp.broadcast_console_output(- channel="media",+ channel=CellChannel.MEDIA,mimetype=mimetype,data=build_data_url(mimetype=mimetype, data=plot_bytes),cell_id=None,diff --git a/marimo/_output/utils.py b/marimo/_output/utils.pyindex f9b964347b..405b148d2e 100644--- a/marimo/_output/utils.py+++ b/marimo/_output/utils.py@@ -3,8 +3,10 @@ from __future__ import annotationsfrom typing import Optional, Union+from marimo._messaging.mimetypes import KnownMimeType-def build_data_url(mimetype: str, data: bytes) -> str:++def build_data_url(mimetype: KnownMimeType, data: bytes) -> str:str_repr = data.decode("utf-8").replace("\n", "")return f"data:{mimetype};base64,{str_repr}"diff --git a/marimo/_runtime/output/_output.py b/marimo/_runtime/output/_output.pyindex 2687765679..3b1b804e4c 100644--- a/marimo/_runtime/output/_output.py+++ b/marimo/_runtime/output/_output.py@@ -2,6 +2,7 @@import sysfrom marimo._ast.cell import CellId_t+from marimo._messaging.cell_output import CellChannelfrom marimo._messaging.ops import CellOpfrom marimo._output import formattingfrom marimo._output.rich_help import mddoc@@ -14,7 +15,7 @@ def write_internal(cell_id: CellId_t, value: object) -> None:if output.traceback is not None:sys.stderr.write(output.traceback)CellOp.broadcast_output(- channel="output",+ channel=CellChannel.OUTPUT,mimetype=output.mimetype,data=output.data,cell_id=cell_id,diff --git a/marimo/_runtime/requests.py b/marimo/_runtime/requests.pyindex 96072c1403..0233ff6d81 100644--- a/marimo/_runtime/requests.py+++ b/marimo/_runtime/requests.py@@ -1,7 +1,6 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations-from collections.abc import Iterablefrom dataclasses import dataclassfrom typing import Any, Optional, Union@@ -22,7 +21,7 @@ class ExecuteMultipleRequest:@dataclassclass SetUIElementValueRequest:# (object id, value) tuples- ids_and_values: Iterable[tuple[str, Any]]+ ids_and_values: list[tuple[str, Any]]@dataclass@@ -75,7 +74,6 @@ class ConfigurationRequest:Request = Union[- ExecutionRequest,ExecuteMultipleRequest,CreationRequest,DeleteRequest,diff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.pyindex d95c8203dd..9a3c19f4c1 100644--- a/marimo/_runtime/runtime.py+++ b/marimo/_runtime/runtime.py@@ -23,6 +23,7 @@ from marimo._ast.cell import CellConfig, CellId_tfrom marimo._ast.compiler import compile_cellfrom marimo._ast.visitor import Name, is_localfrom marimo._config.config import configure+from marimo._messaging.cell_output import CellChannelfrom marimo._messaging.errors import (Error,MarimoAncestorStoppedError,@@ -44,6 +45,7 @@ from marimo._messaging.ops import (VariableValues,)from marimo._messaging.streams import Stderr, Stdin, Stdout, Stream+from marimo._messaging.types import KernelMessagefrom marimo._output import formattingfrom marimo._output.hypertext import Htmlfrom marimo._output.rich_help import mddoc@@ -78,6 +80,7 @@ from marimo._runtime.state import Statefrom marimo._runtime.validate_graph import check_for_errorsfrom marimo._server.types import QueueTypefrom marimo._utils.signals import restore_signals+from marimo._utils.typed_connection import TypedConnectionLOGGER = _loggers.marimo_logger()@@ -511,7 +514,7 @@ class Kernel:for cid in cells_that_no_longer_have_errors:# clear error outputs before runningCellOp.broadcast_output(- channel="output",+ channel=CellChannel.OUTPUT,mimetype="text/plain",data="",cell_id=cid,@@ -683,7 +686,7 @@ class Kernel:with self._install_execution_context(cell_id):sys.stderr.write(formatted_output.traceback)CellOp.broadcast_output(- channel="output",+ channel=CellChannel.OUTPUT,mimetype=formatted_output.mimetype,data=formatted_output.data,cell_id=cell_id,@@ -1084,15 +1087,18 @@ def launch_kernel(restore_signals()n_tries = 0+ pipe: Optional[TypedConnection[KernelMessage]] = Nonewhile n_tries < 100:try:- pipe = mp.connection.Client(socket_addr)+ pipe = TypedConnection[KernelMessage].of(+ mp.connection.Client(socket_addr)+ )breakexcept Exception:n_tries += 1time.sleep(0.01)- if n_tries == 100:+ if n_tries == 100 or pipe is None:LOGGER.debug("Failed to connect to socket.")returndiff --git a/marimo/_server/api/deps.py b/marimo/_server/api/deps.pyindex 2aa360d948..46d7d5aa5a 100644--- a/marimo/_server/api/deps.py+++ b/marimo/_server/api/deps.py@@ -10,7 +10,7 @@ from uvicorn import Serverfrom marimo._ast.app import _AppConfigfrom marimo._config.config import MarimoConfigfrom marimo._server.model import SessionMode-from marimo._server.sessions import Session, SessionManager+from marimo._server.sessions import Session, SessionId, SessionManagerdef app_state(request: Request) -> AppState:@@ -38,18 +38,27 @@ class AppState:self.user_config: MarimoConfig = request.app.state.user_configself._server: Server = request.app.state.server+ def get_current_session_id(self) -> Optional[SessionId]:+ """Get the current session."""+ return self.request.headers.get("Marimo-Session-Id")++ def require_current_session_id(self) -> SessionId:+ """Get the current session or raise an error."""+ session_id = self.get_current_session_id()+ if session_id is None:+ raise ValueError("Missing Marimo-Session-Id header")+ return session_id+def get_current_session(self) -> Optional[Session]:"""Get the current session."""- session_id = self.request.headers.get("Marimo-Session-Id")+ session_id = self.get_current_session_id()if session_id is None:return Nonereturn self.session_manager.get_session(session_id)def require_current_session(self) -> Session:"""Get the current session or raise an error."""- session_id = self.request.headers.get("Marimo-Session-Id")- if session_id is None:- raise ValueError("Missing Marimo-Session-Id header")+ session_id = self.require_current_session_id()session = self.session_manager.get_session(session_id)if session is None:raise ValueError(f"Invalid session id: {session_id}")diff --git a/marimo/_server/api/endpoints/config.py b/marimo/_server/api/endpoints/config.pyindex c6bc6d6175..b84a1f98e9 100644--- a/marimo/_server/api/endpoints/config.py+++ b/marimo/_server/api/endpoints/config.py@@ -64,7 +64,7 @@ async def save_user_config(config = configure(body.config)if config["completion"]["copilot"]:LOGGER.debug("Starting copilot server")- app_state.session_manager.start_lsp_server()+ await app_state.session_manager.start_lsp_server()# Update the kernel's view of the configapp_state.require_current_session().put_request(requests.ConfigurationRequest(str(body.config))diff --git a/marimo/_server/api/endpoints/execution.py b/marimo/_server/api/endpoints/execution.pyindex 075c041007..a04f6cc23f 100644--- a/marimo/_server/api/endpoints/execution.py+++ b/marimo/_server/api/endpoints/execution.py@@ -42,9 +42,11 @@ async def set_ui_element_values(body = await parse_request(request, cls=UpdateComponentValuesRequest)app_state.require_current_session().put_request(SetUIElementValueRequest(- zip(- body.object_ids,- body.values,+ list(+ zip(+ body.object_ids,+ body.values,+ ))))@@ -60,10 +62,9 @@ async def instantiate(Instantiate the kernel."""app_state = AppState(request)- notebook = app_state.session_manager.load_app()+ notebook = app_state.require_current_session().appbody = await parse_request(request, cls=InstantiateRequest)- execution_requests: tuple[ExecutionRequest, ...]execution_requests = tuple(ExecutionRequest(cell_id=cell_data.cell_id, code=cell_data.code)for cell_data in notebook.cell_manager.cell_data()@@ -73,7 +74,7 @@ async def instantiate(CreationRequest(execution_requests=execution_requests,set_ui_element_value_request=SetUIElementValueRequest(- zip(body.object_ids, body.values)+ list(zip(body.object_ids, body.values))),))@@ -141,6 +142,25 @@ async def run_cell(return SuccessResponse()[email protected]("/restart_session")+@requires("edit")+async def restart_session(+ *,+ request: Request,+) -> BaseResponse:+ """+ Restart a session. This does not restart the+ kernel or affect other sessions+ """+ app_state = AppState(request)+ # This just closes the session, and the frontend will+ # do a full reload, which will restart the session.+ session_id = app_state.require_current_session_id()+ app_state.session_manager.close_session(session_id)++ return SuccessResponse()++@router.post("/shutdown")@requires("edit")async def shutdown(diff --git a/marimo/_server/api/endpoints/files.py b/marimo/_server/api/endpoints/files.pyindex 536e1619aa..f05815ba9c 100644--- a/marimo/_server/api/endpoints/files.py+++ b/marimo/_server/api/endpoints/files.py@@ -145,13 +145,23 @@ async def save(app_state = AppState(request)mgr = app_state.session_managerbody = await parse_request(request, cls=SaveRequest)- codes, names, filename, layout = (+ cell_ids, codes, configs, names, filename, layout = (+ body.cell_ids,body.codes,+ body.configs,body.names,body.filename,body.layout,)filename = canonicalize_filename(filename)+ session = app_state.require_current_session()+ session.app.with_data(+ cell_ids=cell_ids,+ codes=codes,+ names=names,+ configs=configs,+ )+if mgr.filename is not None and mgr.filename != filename:raise HTTPException(status_code=HTTPStatus.BAD_REQUEST,@@ -170,6 +180,7 @@ async def save(layout_filename = save_layout_config(app_dir, app_name, LayoutConfig(**layout))+ session.app.update_config({"layout_file": layout_filename})mgr.update_app_config({"layout_file": layout_filename})# try to save the app under the name `filename`@@ -177,7 +188,7 @@ async def save(codes,names,cell_configs=body.configs,- config=mgr.app_config,+ config=session.app.config,)LOGGER.debug("Saving app to %s", filename)try:@@ -204,21 +215,22 @@ async def save_app_config(app_state = AppState(request)body = await parse_request(request, cls=SaveAppConfigurationRequest)mgr = app_state.session_manager- mgr.update_app_config(body.config)# Update the file with the latest app config# TODO(akshayka): Only change the `app = marimo.App` line (at top level# of file), instead of overwriting the whole file.- app = mgr.load_app()+ app = app_state.require_current_session().app- if mgr.filename is not None:- codes = list(app.cell_manager.codes())- names = list(app.cell_manager.names())- configs = list(app.cell_manager.configs())+ new_config = app.update_config(body.config)+ mgr.update_app_config(body.config)+ if mgr.filename is not None:# Try to save the app under the name `mgr.filename`contents = codegen.generate_filecontents(- codes, names, cell_configs=configs, config=mgr.app_config+ codes=list(app.cell_manager.codes()),+ names=list(app.cell_manager.names()),+ cell_configs=list(app.cell_manager.configs()),+ config=new_config,)try:with open(mgr.filename, "w", encoding="utf-8") as f:diff --git a/marimo/_server/api/endpoints/ws.py b/marimo/_server/api/endpoints/ws.pyindex f4bf5c0e67..0960355a00 100644--- a/marimo/_server/api/endpoints/ws.py+++ b/marimo/_server/api/endpoints/ws.py@@ -5,18 +5,30 @@ import asyncioimport jsonimport osfrom enum import IntEnum-from multiprocessing.connection import Connection-from typing import Any, Callable, Optional, Tuple+from typing import Callable, Optionalfrom starlette.websockets import WebSocket, WebSocketDisconnect, WebSocketStatefrom marimo import _loggers-from marimo._ast.cell import CellConfig-from marimo._messaging.ops import KernelReady, serialize+from marimo._ast.cell import CellConfig, CellId_t+from marimo._messaging.ops import (+ Alert,+ Banner,+ KernelReady,+ MessageOperation,+ Reconnected,+ serialize,+)+from marimo._messaging.types import KernelMessagefrom marimo._plugins.core.json_encoder import WebComponentEncoder+from marimo._plugins.core.web_component import JSONTypefrom marimo._server.api.deps import AppStatefrom marimo._server.layout import LayoutConfig, read_layout_config-from marimo._server.model import ConnectionState, SessionHandler, SessionMode+from marimo._server.model import (+ ConnectionState,+ SessionConsumer,+ SessionMode,+)from marimo._server.router import APIRouterfrom marimo._server.sessions import Session, SessionManager@@ -50,7 +62,7 @@ async def websocket_endpoint().start()-class WebsocketHandler(SessionHandler):+class WebsocketHandler(SessionConsumer):"""WebSocket that sessions use to send messages to frontends.Each new socket gets a unique session. At most one session can exist when@@ -73,19 +85,27 @@ class WebsocketHandler(SessionHandler):self.heartbeat_task: Optional[asyncio.Task[None]] = None# Messages from the kernel are put in this queue# to be sent to the frontend- self.message_queue: asyncio.Queue[Tuple[str, Any]]+ self.message_queue: asyncio.Queue[KernelMessage]- async def _write_kernel_ready(self) -> None:+ async def _write_kernel_ready(+ self,+ session: Session,+ resumed: bool,+ ui_values: dict[str, JSONType],+ last_executed_code: dict[CellId_t, str],+ ) -> None:"""Communicates to the client that the kernel is ready.Sends cell code and other metadata to client."""mgr = self.manager+ app = session.app+codes: tuple[str, ...]names: tuple[str, ...]configs: tuple[CellConfig, ...]- app = mgr.load_app()layout: Optional[LayoutConfig] = None+if mgr.should_send_code_to_frontend():codes, names, configs, cell_ids = tuple(zip(@@ -111,6 +131,8 @@ class WebsocketHandler(SessionHandler):))+ last_executed_code = {}+if (appand app.config.layout_file is not None@@ -129,12 +151,17 @@ class WebsocketHandler(SessionHandler):configs=configs,layout=layout,cell_ids=cell_ids,+ resumed=resumed,+ ui_values=ui_values,+ last_executed_code=last_executed_code,)),))- def _reconnect_session(self, session: "Session") -> None:+ async def _reconnect_session(+ self, session: "Session", replay: bool+ ) -> None:"""Reconnect to an existing session (kernel).A websocket can be closed when a user's computer goes to sleep,@@ -144,16 +171,44 @@ class WebsocketHandler(SessionHandler):if self.cancel_close_handle is not None:self.cancel_close_handle.cancel()- assert isinstance(session.session_handler, WebsocketHandler)- assert session.session_handler.status == ConnectionState.CLOSEDself.status = ConnectionState.OPEN- session.session_handler = self- self.on_start(- connection=session.kernel_manager.kernel_connection,- check_alive=session.check_alive,- )+ session.connect_consumer(self)+# Write reconnected message- self.write_operation("reconnected", None)+ await self.write_operation(Reconnected())++ # If not replaying, just send a toast+ if not replay:+ await self.write_operation(+ Alert(+ title="Reconnected",+ description="You have reconnected to an existing session.",+ )+ )+ return++ operations = session.get_current_state().operations+ # Replay the current session view+ LOGGER.debug(+ f"Replaying {len(operations)} operations to the consumer",+ )++ await self._write_kernel_ready(+ session=session,+ resumed=True,+ ui_values=session.get_current_state().ui_values,+ last_executed_code=session.get_current_state().last_executed_code,+ )+ await self.write_operation(+ Banner(+ title="Reconnected",+ description="You have reconnected to an existing session.",+ )+ )++ for op in operations:+ LOGGER.debug("Replaying operation %s", serialize(op))+ await self.write_operation(op)async def start(self) -> None:# Accept the websocket connection@@ -163,7 +218,6 @@ class WebsocketHandler(SessionHandler):session_id = self.session_idmgr = self.manager- session = mgr.get_session(session_id)LOGGER.debug("Websocket open request for session with id %s", session_id)@@ -174,35 +228,55 @@ class WebsocketHandler(SessionHandler):LOGGER.debug("Refusing connection; a frontend is already connected.")- await self.websocket.close(- WebSocketCodes.ALREADY_CONNECTED,- "MARIMO_ALREADY_CONNECTED",- )+ if self.websocket.application_state is WebSocketState.CONNECTED:+ await self.websocket.close(+ WebSocketCodes.ALREADY_CONNECTED,+ "MARIMO_ALREADY_CONNECTED",+ )return- # Handle reconnection- if session is not None:+ async def get_session() -> Session:+ # 1. Handle reconnection+# The session already exists, but it was disconnected.# This can happen in local development when the client# goes to sleep and wakes later. Just replace the session's# socket, but keep its kernel- LOGGER.debug("Reconnecting session %s", session_id)- self._reconnect_session(session)- # Create a new session- else:+ existing_session = mgr.get_session(session_id)+ if existing_session is not None:+ LOGGER.debug("Reconnecting session %s", session_id)+ await self._reconnect_session(existing_session, replay=False)+ return existing_session++ # 2. Handle resume++ # Get resumable possible resumable session+ resumable_session = mgr.maybe_resume_session(session_id)+ if resumable_session is not None:+ LOGGER.debug("Resuming session %s", session_id)+ await self._reconnect_session(resumable_session, replay=True)+ return resumable_session++ # 3. Create a new session+# If the client refreshed their page, there will be one# existing session with a closed socket for a different session# id; that's why we call `close_all_sessions`.if mgr.mode == SessionMode.EDIT:mgr.close_all_sessions()- mgr.create_session(+ new_session = mgr.create_session(session_id=session_id,- session_handler=self,+ session_consumer=self,)self.status = ConnectionState.OPEN# Let the frontend know it can instantiate the app.- await self._write_kernel_ready()+ await self._write_kernel_ready(+ new_session, resumed=False, ui_values={}, last_executed_code={}+ )+ return new_session++ await get_session()async def listen_for_messages() -> None:while True:@@ -229,6 +303,10 @@ class WebsocketHandler(SessionHandler):# Change the statusself.status = ConnectionState.CLOSED+ # Disconnect the consumer+ session = self.manager.get_session(self.session_id)+ if session:+ session.disconnect_consumer()if self.manager.mode == SessionMode.RUN:# When the websocket is closed, we wait TTL_SECONDS before@@ -261,25 +339,19 @@ class WebsocketHandler(SessionHandler):)try:- await asyncio.gather(+ self.future = asyncio.gather(listen_for_messages_task,listen_for_disconnect_task,)+ await self.futureexcept asyncio.CancelledError:LOGGER.debug("Websocket terminated with CancelledError")passdef on_start(self,- connection: Connection,check_alive: Callable[[], None],- ) -> None:- # Add a reader to the connection- asyncio.get_event_loop().add_reader(- connection.fileno(),- lambda: self.message_queue.put_nowait(connection.recv()),- )-+ ) -> Callable[[KernelMessage], None]:# Start a heartbeat taskasync def _heartbeat() -> None:while True:@@ -288,19 +360,23 @@ class WebsocketHandler(SessionHandler):self.heartbeat_task = asyncio.create_task(_heartbeat())- def write_operation(self, op: str, data: Any) -> None:- self.message_queue.put_nowait((op, data))+ def listener(response: KernelMessage) -> None:+ self.message_queue.put_nowait(response)++ return listener- def on_stop(self, connection: Connection) -> None:+ async def write_operation(self, op: MessageOperation) -> None:+ await self.message_queue.put((op.name, serialize(op)))++ def on_stop(self) -> None:# Cancel the heartbeat task, readerif self.heartbeat_task and not self.heartbeat_task.cancelled():self.heartbeat_task.cancel()- asyncio.get_event_loop().remove_reader(connection.fileno())# If the websocket is open, send a close messageif (self.status == ConnectionState.OPEN- and self.websocket.application_state == WebSocketState.CONNECTED+ and self.websocket.application_state is WebSocketState.CONNECTED):asyncio.create_task(self.websocket.close(@@ -308,5 +384,7 @@ class WebsocketHandler(SessionHandler):))+ self.future.cancel()+def connection_state(self) -> ConnectionState:return self.statusdiff --git a/marimo/_server/api/lifespans.py b/marimo/_server/api/lifespans.pyindex b8fbf9c9ab..573905af72 100644--- a/marimo/_server/api/lifespans.py+++ b/marimo/_server/api/lifespans.py@@ -96,7 +96,7 @@ async def lsp(app: Starlette) -> AsyncIterator[None]:run = session_mgr.mode == SessionMode.RUNif not run and user_config["completion"]["copilot"]:LOGGER.debug("GitHub Copilot is enabled")- session_mgr.start_lsp_server()+ await session_mgr.start_lsp_server()yielddiff --git a/marimo/_server/model.py b/marimo/_server/model.pyindex 926b112af2..6d52636dfb 100644--- a/marimo/_server/model.py+++ b/marimo/_server/model.py@@ -1,8 +1,10 @@# Copyright 2024 Marimo. All rights reserved.import abcfrom enum import Enum-from multiprocessing.connection import Connection-from typing import Any, Callable+from typing import Callable++from marimo._messaging.ops import MessageOperation+from marimo._messaging.types import KernelMessageclass ConnectionState(Enum):@@ -10,6 +12,7 @@ class ConnectionState(Enum):OPEN = 0CLOSED = 1+ ORPHANED = 2class SessionMode(Enum):@@ -21,28 +24,31 @@ class SessionMode(Enum):RUN = 1-class SessionHandler(metaclass=abc.ABCMeta):+class SessionConsumer(metaclass=abc.ABCMeta):"""- Handler for a session+ Consumer for a sessionThis allows use to communicate with a session via different- connection types.+ connection types. Currently we consume a session via WebSocket"""@abc.abstractmethoddef on_start(self,- connection: Connection,check_alive: Callable[[], None],- ) -> None:+ ) -> Callable[[KernelMessage], None]:+ """+ Start the session consumer+ and return a subscription function for the session consumer+ """raise NotImplementedError@abc.abstractmethod- def on_stop(self, connection: Connection) -> None:+ def on_stop(self) -> None:raise NotImplementedError@abc.abstractmethod- def write_operation(self, op: str, data: Any) -> None:+ async def write_operation(self, op: MessageOperation) -> None:raise NotImplementedError@abc.abstractmethoddiff --git a/marimo/_server/models/models.py b/marimo/_server/models/models.pyindex 50d2a3a92d..393142f4ed 100644--- a/marimo/_server/models/models.py+++ b/marimo/_server/models/models.py@@ -94,6 +94,8 @@ class RunRequest:@dataclassclass SaveRequest:+ # id of each cell+ cell_ids: List[CellId_t]# code for each cellcodes: List[str]# name of each celldiff --git a/marimo/_server/session/__init__.py b/marimo/_server/session/__init__.pynew file mode 100644index 0000000000..be52407b50--- /dev/null+++ b/marimo/_server/session/__init__.py@@ -0,0 +1 @@+# Copyright 2024 Marimo. All rights reserved.diff --git a/marimo/_server/session/session_view.py b/marimo/_server/session/session_view.pynew file mode 100644index 0000000000..2046fc967d--- /dev/null+++ b/marimo/_server/session/session_view.py@@ -0,0 +1,162 @@+# Copyright 2024 Marimo. All rights reserved.+from __future__ import annotations++from dataclasses import dataclass+from typing import Any, Optional, Union++from marimo._ast.cell import CellId_t+from marimo._messaging.cell_output import CellChannel, CellOutput+from marimo._messaging.ops import (+ CellOp,+ Interrupted,+ MessageOperation,+ Variables,+ VariableValue,+ VariableValues,+)+from marimo._runtime.requests import (+ CreationRequest,+ ExecuteMultipleRequest,+ ExecutionRequest,+ Request,+ SetUIElementValueRequest,+)+from marimo._utils.parse_dataclass import parse_raw+++class SessionView:+ """+ This stores the current view of the session.++ Which are the cell's outputs, status, and console.+ """++ def __init__(self) -> None:+ # List of operations we care about keeping track of.+ self.cell_operations: dict[CellId_t, CellOp] = {}+ # The most recent Variables operation.+ self.variable_operations: Variables = Variables(variables=[])+ # Map of variable name to value.+ self.variable_values: dict[str, VariableValue] = {}+ # Map of object id to value.+ self.ui_values: dict[str, Any] = {}+ # Map of cell id to the last code that was executed in that cell.+ self.last_executed_code: dict[CellId_t, str] = {}++ def _add_ui_value(self, name: str, value: Any) -> None:+ self.ui_values[name] = value++ def _add_last_run_code(self, req: ExecutionRequest) -> None:+ self.last_executed_code[req.cell_id] = req.code++ def add_raw_operation(self, raw_operation: Any) -> None:+ # parse_raw only accepts a dataclass, so we wrap MessageOperation in a+ # dataclass.+ @dataclass+ class _Container:+ operation: MessageOperation++ operation = parse_raw({"operation": raw_operation}, _Container)+ self.add_operation(operation.operation)++ def add_request(self, request: Request) -> None:+ if isinstance(request, SetUIElementValueRequest):+ for object_id, value in request.ids_and_values:+ self._add_ui_value(object_id, value)+ elif isinstance(request, ExecuteMultipleRequest):+ for execution_request in request.execution_requests:+ self._add_last_run_code(execution_request)+ elif isinstance(request, CreationRequest):+ for (+ object_id,+ value,+ ) in request.set_ui_element_value_request.ids_and_values:+ self._add_ui_value(object_id, value)+ for execution_request in request.execution_requests:+ self._add_last_run_code(execution_request)++ def add_stdin(self, stdin: str) -> None:+ """Add a stdin request to the session view."""+ # Find the first cell that is waiting for stdin.+ for cell_op in self.cell_operations.values():+ console_ops: list[CellOutput] = as_list(cell_op.console)+ for cell_output in console_ops:+ if cell_output.channel == CellChannel.STDIN:+ cell_output.channel = CellChannel.STDOUT+ cell_output.data = f"{cell_output.data} {stdin}\n"+ return++ def add_operation(self, operation: MessageOperation) -> None:+ """Add an operation to the session view."""++ if isinstance(operation, CellOp):+ previous = self.cell_operations.get(operation.cell_id)+ self.cell_operations[operation.cell_id] = merge_cell_operation(+ previous, operation+ )+ elif isinstance(operation, Variables):+ self.variable_operations = operation++ # Remove any variable values that are no longer in scope.+ names: set[str] = set(+ [v.name for v in self.variable_operations.variables]+ )+ next_values: dict[str, VariableValue] = {}+ for name, value in self.variable_values.items():+ if name in names:+ next_values[name] = value+ self.variable_values = next_values++ elif isinstance(operation, VariableValues):+ for value in operation.variables:+ self.variable_values[value.name] = value++ elif isinstance(operation, Interrupted):+ # Resolve stdin+ self.add_stdin("")++ @property+ def operations(self) -> list[MessageOperation]:+ all_ops: list[MessageOperation] = [+ self.variable_operations,+ VariableValues(variables=list(self.variable_values.values())),+ ]+ all_ops.extend(self.cell_operations.values())+ return all_ops+++def merge_cell_operation(+ previous: Optional[CellOp],+ next_: CellOp,+) -> CellOp:+ """Merge two cell operations."""+ if previous is None:+ return next_++ assert previous.cell_id == next_.cell_id++ if next_.status is None:+ next_.status = previous.status++ # If we went from queued to running, clear the console.+ if next_.status == "running" and previous.status == "queued":+ next_.console = []+ else:+ combined_console: list[CellOutput] = as_list(previous.console)+ combined_console.extend(as_list(next_.console))+ next_.console = combined_console++ # If we went from running to running, use the previous timestamp.+ if next_.status == "running" and previous.status == "running":+ next_.timestamp = previous.timestamp++ if next_.output is None:+ next_.output = previous.output++ return next_+++def as_list(value: Union[Any, Optional[Any], list[Any]]) -> list[Any]:+ if value is None:+ return []+ return value if isinstance(value, list) else [value]diff --git a/marimo/_server/sessions.py b/marimo/_server/sessions.pyindex 3ca994b9a7..69c181a4c3 100644--- a/marimo/_server/sessions.py+++ b/marimo/_server/sessions.py@@ -28,23 +28,30 @@ from uuid import uuid4from marimo import _loggersfrom marimo._ast import codegen-from marimo._ast.app import App, InternalApp, _AppConfig+from marimo._ast.app import App, InternalAppfrom marimo._ast.cell import CellConfig, CellId_t-from marimo._messaging.ops import Alert, serialize+from marimo._messaging.ops import Alert, MessageOperation+from marimo._messaging.types import KernelMessagefrom marimo._output.formatters.formatters import register_formattersfrom marimo._runtime import requests, runtimefrom marimo._runtime.requests import AppMetadatafrom marimo._server.model import (ConnectionState,- SessionHandler,+ SessionConsumer,SessionMode,)+from marimo._server.session.session_view import SessionViewfrom marimo._server.types import QueueTypefrom marimo._server.utils import import_files, print_tabbed+from marimo._utils.distributor import Distributor+from marimo._utils.repr import format_repr+from marimo._utils.typed_connection import TypedConnectionLOGGER = _loggers.marimo_logger()SESSION_MANAGER: Optional["SessionManager"] = None+SessionId = str+class QueueManager:"""Manages queues for a session."""@@ -94,8 +101,8 @@ class KernelManager:self.queue_manager = queue_managerself.mode = modeself.configs = configs- self._read_conn: Optional[connection.Connection] = Noneself.app_metadata = app_metadata+ self._read_conn: Optional[TypedConnection[KernelMessage]] = Nonedef start_kernel(self) -> None:# Need to use a socket for windows compatibility@@ -130,7 +137,8 @@ class KernelManager:# naturally exit before cleaning up resourcesdef launch_kernel_with_cleanup(*args: Any) -> None:runtime.launch_kernel(*args)- self.kernel_connection.close()+ if not self.kernel_connection.closed:+ self.kernel_connection.close()# install formatter import hooks, which will be shared by all# threads (in edit mode, the single kernel process installs@@ -157,7 +165,7 @@ class KernelManager:self.kernel_task.start() # type: ignore# First thing kernel does is connect to the socket, so it's safe to# call accept- self._read_conn = listener.accept()+ self._read_conn = TypedConnection[KernelMessage].of(listener.accept())def is_alive(self) -> bool:return self.kernel_task is not None and self.kernel_task.is_alive()@@ -184,7 +192,7 @@ class KernelManager:self.queue_manager.control_queue.put(requests.StopRequest())@property- def kernel_connection(self) -> connection.Connection:+ def kernel_connection(self) -> TypedConnection[KernelMessage]:assert self._read_conn is not None, "connection not started"return self._read_conn@@ -201,7 +209,7 @@ class Session:@classmethoddef create(cls,- session_handler: SessionHandler,+ session_consumer: SessionConsumer,mode: SessionMode,app: InternalApp,app_metadata: AppMetadata,@@ -212,49 +220,110 @@ class Session:kernel_manager = KernelManager(queue_manager, mode, configs, app_metadata)- return cls(session_handler, queue_manager, kernel_manager)+ return cls(app, session_consumer, queue_manager, kernel_manager)def __init__(self,- session_handler: SessionHandler,+ app: InternalApp,+ session_consumer: SessionConsumer,queue_manager: QueueManager,kernel_manager: KernelManager,) -> None:"""Initialize kernel and client connection to it."""self._queue_manager: QueueManager- self.session_handler = session_handler+ self.app = app+ # This can be optional in case a consumer gets disconnected,+ # and we want to continue the session without a consumer.+ self.session_consumer: Optional[SessionConsumer] = Noneself._queue_manager = queue_managerself.kernel_manager = kernel_manager- self.kernel_manager.start_kernel()-- def check_alive() -> None:- if not self.kernel_manager.is_alive():- self.close()- print()- print_tabbed(- "\033[31mThe Python kernel died unexpectedly.\033[0m"- )- print()- sys.exit()+ self.session_view = SessionView()- self.check_alive = check_alive- self.session_handler.on_start(- connection=self.kernel_manager.kernel_connection,- check_alive=check_alive,+ self.kernel_manager.start_kernel()+ # Reads from the kernel connection and distributes the+ # messages to each subscriber.+ self.message_distributor = Distributor[KernelMessage](+ self.kernel_manager.kernel_connection+ )+ self.message_distributor.add_consumer(+ lambda msg: self.session_view.add_raw_operation(msg[1]))+ self.connect_consumer(session_consumer)+ self.message_distributor.start()++ def _check_alive(self) -> None:+ if not self.kernel_manager.is_alive():+ LOGGER.debug("Closing session because kernel died")+ self.close()+ print()+ print_tabbed("\033[31mThe Python kernel died unexpectedly.\033[0m")+ print()+ sys.exit()def try_interrupt(self) -> None:self.kernel_manager.interrupt_kernel()def put_request(self, request: requests.Request) -> None:self._queue_manager.control_queue.put(request)+ self.session_view.add_request(request)def put_input(self, text: str) -> None:self._queue_manager.input_queue.put(text)+ self.session_view.add_stdin(text)++ def disconnect_consumer(self) -> None:+ """Stop the session consumer but keep the kernel running"""+ assert (+ self.session_consumer is not None+ ), "Expecting a session consumer to pause"+ LOGGER.debug("Disconnecting session consumer")+ self.session_consumer.on_stop()+ self.unsubscribe_consumer()+ self.session_consumer = None++ def connect_consumer(self, session_consumer: SessionConsumer) -> None:+ """Connect or resume the session with a new consumer"""+ assert (+ self.session_consumer is None+ ), "Expecting no existing session consumer"++ self.session_consumer = session_consumer++ subscribe = self.session_consumer.on_start(self._check_alive)+ self.unsubscribe_consumer = self.message_distributor.add_consumer(+ subscribe+ )++ def get_current_state(self) -> SessionView:+ return self.session_view++ def connection_state(self) -> ConnectionState:+ if self.session_consumer is None:+ return ConnectionState.ORPHANED+ return self.session_consumer.connection_state()++ async def write_operation(self, operation: MessageOperation) -> None:+ self.session_view.add_operation(operation)+ if self.session_consumer is not None:+ await self.session_consumer.write_operation(operation)def close(self) -> None:- self.session_handler.on_stop(self.kernel_manager.kernel_connection)+ # Could be no consumer if we already disconnect, but the session+ # is running in the background+ if self.session_consumer is not None:+ self.session_consumer.on_stop()+ self.message_distributor.stop()self.kernel_manager.close_kernel()+ self.unsubscribe_consumer()++ def __repr__(self) -> str:+ return format_repr(+ self,+ {+ "connection_state": self.connection_state(),+ "consumer": self.session_consumer,+ },+ )class SessionManager:@@ -286,11 +355,10 @@ class SessionManager:self.development_mode = development_modeself.quiet = quietself.sessions: dict[str, Session] = {}- self.app_config: _AppConfigself.include_code = include_code- self.app = self.load_app()- self.app_config = self.app.config+ app = self.load_app()+ self.app_config = app.configself.app_metadata = AppMetadata(filename=self._get_filename(),@@ -305,7 +373,7 @@ class SessionManager:# Because run-mode is read-only, all that matters is that# the frontend's app matches the server's app.self.server_token = str(- hash("".join(code for code in self.app.cell_manager.codes()))+ hash("".join(code for code in app.cell_manager.codes())))def load_app(self) -> InternalApp:@@ -337,21 +405,72 @@ class SessionManager:self.app_metadata.filename = self._get_filename()def create_session(- self, session_id: str, session_handler: SessionHandler+ self, session_id: SessionId, session_consumer: SessionConsumer) -> Session:"""Create a new session"""- LOGGER.debug("creating new session for id %s", session_id)+ LOGGER.debug("Creating new session for id %s", session_id)if session_id not in self.sessions:- s = Session.create(- session_handler=session_handler,+ self.sessions[session_id] = Session.create(+ session_consumer=session_consumer,mode=self.mode,+ # When we create a session,+ # we load the app from the fileapp=self.load_app(),app_metadata=self.app_metadata,)- self.sessions[session_id] = s- return s- else:- return self.sessions[session_id]+ return self.sessions[session_id]++ def get_session(self, session_id: SessionId) -> Optional[Session]:+ return self.sessions.get(session_id)++ def maybe_resume_session(+ self, new_session_id: SessionId+ ) -> Optional[Session]:+ """+ Try to resume a session if one is resumable.+ If it is resumable, return the session and update the session id.+ """++ # If in run mode, only resume the session if it is orphaned and has+ # the same session id, otherwise we want to create a new session+ if self.mode == SessionMode.RUN:+ maybe_session = self.get_session(new_session_id)+ if (+ maybe_session+ and maybe_session.connection_state()+ == ConnectionState.ORPHANED+ ):+ LOGGER.debug(+ "Found a resumable RUN session: prev_id=%s",+ new_session_id,+ )+ return maybe_session+ return None++ if len(self.sessions) == 0:+ return None+ if len(self.sessions) > 1:+ raise Exception("Only one session should exist while editing")++ # Should only return an orphaned session+ (session_id, session) = list(self.sessions.items())[0]+ connection_state = session.connection_state()+ if connection_state == ConnectionState.ORPHANED:+ LOGGER.debug(+ f"Found a resumable EDIT session: prev_id={session_id}"+ )+ # Set new session and remove old session+ self.sessions[new_session_id] = session+ # If the ID is the same, we don't need to delete the old session+ if new_session_id != session_id:+ del self.sessions[session_id]+ return session++ LOGGER.debug(+ "Session is not resumable, current state: %s",+ connection_state,+ )+ return Nonedef _get_filename(self) -> Optional[str]:if self.filename is None:@@ -361,22 +480,14 @@ class SessionManager:except AttributeError:return None- def get_session(self, session_id: str) -> Optional[Session]:- if session_id in self.sessions:- return self.sessions[session_id]- return None-def any_clients_connected(self) -> bool:"""Returns True if at least one client has an open socket."""for session in self.sessions.values():- if (- session.session_handler.connection_state()- == ConnectionState.OPEN- ):+ if session.connection_state() == ConnectionState.OPEN:return Truereturn False- def start_lsp_server(self) -> None:+ async def start_lsp_server(self) -> None:"""Starts the lsp server if it is not already started.Doesn't start in run mode.@@ -389,15 +500,12 @@ class SessionManager:if binpath is None:LOGGER.error("Node.js not found; cannot start LSP server.")for _, session in self.sessions.items():- session.session_handler.write_operation(- Alert.name,- serialize(- Alert(- title="Github Copilot: Connection Error",- description="<span><a class='hyperlink' href='https://docs.marimo.io/getting_started/index.html#github-copilot'>Install Node.js</a> to use copilot.</span>", # noqa: E501- variant="danger",- )- ),+ await session.write_operation(+ Alert(+ title="Github Copilot: Connection Error",+ description="<span><a class='hyperlink' href='https://docs.marimo.io/getting_started/index.html#github-copilot'>Install Node.js</a> to use copilot.</span>", # noqa: E501+ variant="danger",+ ))return@@ -428,8 +536,8 @@ class SessionManager:e,)- def close_session(self, session_id: str) -> None:- LOGGER.debug("closing session %s", session_id)+ def close_session(self, session_id: SessionId) -> None:+ LOGGER.debug("Closing session %s", session_id)session = self.get_session(session_id)if session is not None:session.close()diff --git a/marimo/_utils/disposable.py b/marimo/_utils/disposable.pynew file mode 100644index 0000000000..7ad32569df--- /dev/null+++ b/marimo/_utils/disposable.py@@ -0,0 +1,22 @@+# Copyright 2024 Marimo. All rights reserved.+from typing import Callable+++class Disposable:+ def __init__(self, action: Callable[[], None]) -> None:+ self.action = action+ self._is_disposed = False++ def __call__(self) -> None:+ return self.dispose()++ def dispose(self) -> None:+ self.action()+ self._is_disposed = True++ def is_disposed(self) -> bool:+ return self._is_disposed++ @staticmethod+ def empty() -> "Disposable":+ return Disposable(lambda: None)diff --git a/marimo/_utils/distributor.py b/marimo/_utils/distributor.pynew file mode 100644index 0000000000..77ab5e2c1d--- /dev/null+++ b/marimo/_utils/distributor.py@@ -0,0 +1,70 @@+# Copyright 2024 Marimo. All rights reserved.+from __future__ import annotations++import asyncio+from threading import Thread+from typing import Callable, Generic, TypeVar++from marimo import _loggers+from marimo._utils.disposable import Disposable+from marimo._utils.typed_connection import TypedConnection++LOGGER = _loggers.marimo_logger()++T = TypeVar("T")+++class Distributor(Generic[T]):+ """+ Used to distribute the response of a multiprocessing Connection to multiple+ consumers.++ This also handles adding and removing new consumers.+ """++ def __init__(self, input_connection: TypedConnection[T]) -> None:+ self.consumers: list[Callable[[T], None]] = []+ self.input_connection = input_connection+ self.thread: Thread | None = None++ def add_consumer(self, consumer: Callable[[T], None]) -> Disposable:+ """Add a consumer to the distributor."""+ self.consumers.append(consumer)++ def _remove() -> None:+ if consumer in self.consumers:+ self.consumers.remove(consumer)++ return Disposable(_remove)++ def _on_change(self) -> None:+ """Distribute the response to all consumers."""+ while self.input_connection.poll():+ try:+ response = self.input_connection.recv()+ except (EOFError, StopIteration):+ break+ for consumer in self.consumers:+ consumer(response)++ def start(self) -> Disposable:+ """Start distributing the response."""+ asyncio.get_event_loop().add_reader(+ self.input_connection.fileno(), self._on_change+ )+ return Disposable(self.stop)++ def stop(self) -> None:+ """Stop distributing the response."""+ asyncio.get_event_loop().remove_reader(self.input_connection.fileno())+ if not self.input_connection.closed:+ self.input_connection.close()+ self.consumers.clear()++ def flush(self) -> None:+ """Flush the distributor."""+ while self.input_connection.poll():+ try:+ self.input_connection.recv()+ except EOFError:+ breakdiff --git a/marimo/_utils/repr.py b/marimo/_utils/repr.pynew file mode 100644index 0000000000..3deffa6b9d--- /dev/null+++ b/marimo/_utils/repr.py@@ -0,0 +1,10 @@+# Copyright 2024 Marimo. All rights reserved.+from __future__ import annotations++from typing import Any+++def format_repr(obj: Any, items: dict[str, Any]) -> str:+ """Format a repr string."""+ kvs = [f"{k}={v}" for k, v in items.items()]+ return f"{obj.__class__.__name__}({', '.join(kvs)})"diff --git a/marimo/_utils/typed_connection.py b/marimo/_utils/typed_connection.pynew file mode 100644index 0000000000..ed478b04c9--- /dev/null+++ b/marimo/_utils/typed_connection.py@@ -0,0 +1,25 @@+# Copyright 2024 Marimo. All rights reserved.+from __future__ import annotations++from multiprocessing.connection import Connection+from typing import Generic, TypeVar++T = TypeVar("T")+++class TypedConnection(Generic[T], Connection):+ """Wrapper around a connection with strong typing."""++ @classmethod+ def of(+ cls,+ delegate: Connection,+ ) -> TypedConnection[T]:+ """Create a typed connection from a connection."""+ return delegate # type: ignore[return-value]++ def send(self, obj: T) -> None:+ super().send(obj)++ def recv(self) -> T:+ return super().recv() # type: ignore[no-any-return]diff --git a/tests/_server/api/endpoints/test_execution.py b/tests/_server/api/endpoints/test_execution.pyindex 0554a6fe02..b41e69ea3b 100644--- a/tests/_server/api/endpoints/test_execution.py+++ b/tests/_server/api/endpoints/test_execution.py@@ -68,6 +68,23 @@ class TestExecutionRoutes_EditMode:assert response.headers["content-type"] == "application/json"assert "success" in response.json()+ @staticmethod+ def test_restart_session(client: TestClient) -> None:+ with client.websocket_connect(+ f"/ws?session_id={SESSION_ID}"+ ) as websocket:+ data = websocket.receive_text()+ assert data+ response = client.post("/api/kernel/restart_session", headers=HEADERS)+ assert response.status_code == 200, response.text+ assert response.headers["content-type"] == "application/json"+ assert "success" in response.json()+ server_token: str = client.app.state.session_manager.server_token # type: ignore # noqa: E501+ client.post(+ "/api/kernel/shutdown",+ headers={"Marimo-Server-Token": server_token},+ )+@staticmethod@with_session(SESSION_ID)def test_run_cell(client: TestClient) -> None:@@ -138,6 +155,12 @@ class TestExecutionRoutes_RunMode:response = client.post("/api/kernel/interrupt", headers=HEADERS)assert response.status_code == 403, response.text+ @staticmethod+ @with_read_session(SESSION_ID)+ def test_restart_session(client: TestClient) -> None:+ response = client.post("/api/kernel/restart_session", headers=HEADERS)+ assert response.status_code == 403, response.text+@staticmethod@with_read_session(SESSION_ID)def test_run_cell(client: TestClient) -> None:diff --git a/tests/_server/api/endpoints/test_files.py b/tests/_server/api/endpoints/test_files.pyindex 4c5299f296..83dae8f08d 100644--- a/tests/_server/api/endpoints/test_files.py+++ b/tests/_server/api/endpoints/test_files.py@@ -4,9 +4,12 @@ import randomfrom starlette.testclient import TestClient-from tests._server.mocks import get_mock_session_manager+from tests._server.conftest import get_session_manager+from tests._server.mocks import with_session+SESSION_ID = "session-123"HEADERS = {+ "Marimo-Session-Id": SESSION_ID,"Marimo-Server-Token": "fake-token",}@@ -25,7 +28,7 @@ def test_directory_autocomplete(client: TestClient) -> None:def test_rename(client: TestClient) -> None:- current_filename = get_mock_session_manager().filename+ current_filename = get_session_manager(client).filenameassert current_filenameassert os.path.exists(current_filename)@@ -57,14 +60,16 @@ def test_read_code(client: TestClient) -> None:assert response.json()["contents"].startswith("import marimo")+@with_session(SESSION_ID)def test_save_file(client: TestClient) -> None:- filename = get_mock_session_manager().filename+ filename = get_session_manager(client).filenameassert filenameresponse = client.post("/api/kernel/save",headers=HEADERS,json={+ "cell_ids": ["1"],"filename": filename,"codes": ["import marimo as mo"],"names": ["my_cell"],@@ -88,6 +93,7 @@ def test_save_file(client: TestClient) -> None:"/api/kernel/save",headers=HEADERS,json={+ "cell_ids": ["1"],"filename": filename,"codes": ["import marimo as mo"],"names": ["__"],@@ -100,11 +106,13 @@ def test_save_file(client: TestClient) -> None:)+@with_session(SESSION_ID)def test_save_file_cannot_rename(client: TestClient) -> None:response = client.post("/api/kernel/save",headers=HEADERS,json={+ "cell_ids": ["1"],"filename": "random_filename.py","codes": ["import marimo as mo"],"names": ["my_cell"],@@ -120,8 +128,9 @@ def test_save_file_cannot_rename(client: TestClient) -> None:assert "cannot rename" in response.text+@with_session(SESSION_ID)def test_save_app_config(client: TestClient) -> None:- filename = get_mock_session_manager().filename+ filename = get_session_manager(client).filenameassert filenamefile_contents = open(filename).read()diff --git a/tests/_server/api/endpoints/test_resume_session.py b/tests/_server/api/endpoints/test_resume_session.pynew file mode 100644index 0000000000..7d08db85db--- /dev/null+++ b/tests/_server/api/endpoints/test_resume_session.py@@ -0,0 +1,253 @@+# Copyright 2024 Marimo. All rights reserved.+from __future__ import annotations++from typing import Any, Optional++from starlette.testclient import TestClient++from marimo._messaging.ops import KernelReady+from marimo._server.sessions import Session, SessionManager+from marimo._utils.parse_dataclass import parse_raw+++def create_response(+ partial_response: dict[str, Any],+) -> dict[str, Any]:+ response: dict[str, Any] = {+ "cell_ids": ["Hbol"],+ "codes": ["import marimo as mo"],+ "names": ["__"],+ "layout": None,+ "resumed": False,+ "ui_values": {},+ "last_executed_code": {},+ "configs": [{"disabled": False, "hide_code": False}],+ }+ response.update(partial_response)+ return response+++def headers(session_id: str) -> dict[str, str]:+ return {+ "Marimo-Session-Id": session_id,+ "Marimo-Server-Token": "fake-token",+ }+++HEADERS = {+ "Marimo-Server-Token": "fake-token",+}+++def assert_kernel_ready_response(+ raw_data: dict[str, Any], response: dict[str, Any]+):+ data = parse_raw(raw_data["data"], KernelReady)+ expected = parse_raw(response, KernelReady)+ assert data.cell_ids == expected.cell_ids+ assert data.codes == expected.codes+ assert data.names == expected.names+ assert data.layout == expected.layout+ assert data.resumed == expected.resumed+ assert data.ui_values == expected.ui_values+ assert data.configs == expected.configs+++def get_session(client: TestClient, session_id: str) -> Optional[Session]:+ return get_session_manager(client).get_session(session_id)+++def get_session_manager(client: TestClient) -> SessionManager:+ return client.app.state.session_manager # type: ignore+++def test_refresh_session(client: TestClient) -> None:+ with client.websocket_connect("/ws?session_id=123") as websocket:+ data = websocket.receive_json()+ assert_kernel_ready_response(data, create_response({}))++ # Check the session still exists after closing the websocket+ assert get_session(client, "123")++ # New session with new ID (simulates refresh)+ # We should resume the current session+ with client.websocket_connect("/ws?session_id=456") as websocket:+ # First message is the kernel reconnected+ data = websocket.receive_json()+ assert data == {"op": "reconnected", "data": {}}+ # Resume the session+ data = websocket.receive_json()+ assert_kernel_ready_response(data, create_response({"resumed": True}))+ # Send a value to the kernel+ response = client.post(+ "/api/kernel/set_ui_element_value",+ headers=headers("456"),+ json={+ "object_ids": ["ui-element-1", "ui-element-2"],+ "values": ["value1", "value2"],+ },+ )+ assert response.status_code == 200, response.text++ # Check the session switch IDs+ assert not get_session(client, "123")+ assert get_session(client, "456")++ # New session again+ # We should not resume the current session with the new values+ with client.websocket_connect("/ws?session_id=789") as websocket:+ # First message is the kernel reconnected+ data = websocket.receive_json()+ assert data == {"op": "reconnected", "data": {}}+ # Resume the session+ data = websocket.receive_json()+ assert_kernel_ready_response(+ data,+ create_response(+ {+ "ui_values": {+ "ui-element-1": "value1",+ "ui-element-2": "value2",+ },+ "resumed": True,+ }+ ),+ )+ assert response.status_code == 200, response.text++ # Check the session switch IDs+ assert not get_session(client, "456")+ assert get_session(client, "789")++ # Shutdown the kernel+ client.post("/api/kernel/shutdown", headers=HEADERS)+++def test_save_session(client: TestClient) -> None:+ filename = get_session_manager(client).filename+ with client.websocket_connect("/ws?session_id=123") as websocket:+ data = websocket.receive_json()+ assert_kernel_ready_response(data, create_response({}))+ # Send save request+ client.post(+ "/api/kernel/save",+ headers=headers("123"),+ json={+ "cell_ids": ["2", "1"],+ "filename": filename,+ "codes": [+ "slider = mo.ui.slider(0, 100)",+ "import marimo as mo",+ ],+ "names": ["cell_0", "cell_1"],+ "configs": [+ {+ "hideCode": True,+ "disabled": True,+ },+ {+ "hideCode": False,+ "disabled": False,+ },+ ],+ },+ )++ # Check the session still exists after closing the websocket+ assert get_session(client, "123")++ # New session with new ID (simulates refresh)+ # We should resume the current session+ with client.websocket_connect("/ws?session_id=456") as websocket:+ # First message is the kernel reconnected+ data = websocket.receive_json()+ assert data == {"op": "reconnected", "data": {}}+ # Resume the session+ data = websocket.receive_json()+ assert_kernel_ready_response(+ data,+ create_response(+ {+ # The cell IDs that were saved should be the ones that are+ # resumed+ "cell_ids": ["2", "1"],+ "names": ["cell_0", "cell_1"],+ "codes": [+ "slider = mo.ui.slider(0, 100)",+ "import marimo as mo",+ ],+ "configs": [+ {+ "hideCode": True,+ "disabled": True,+ },+ {+ "hideCode": False,+ "disabled": False,+ },+ ],+ "resumed": True,+ }+ ),+ )++ # Check the session switch IDs+ assert not get_session(client, "123")+ assert get_session(client, "456")++ # Shutdown the kernel+ client.post("/api/kernel/shutdown", headers=HEADERS)+++def test_save_config(client: TestClient) -> None:+ with client.websocket_connect("/ws?session_id=123") as websocket:+ data = websocket.receive_json()+ assert_kernel_ready_response(data, create_response({}))+ # Send save request+ client.post(+ "/api/kernel/save_app_config",+ headers=headers("123"),+ json={+ "config": {"width": "full"},+ },+ )++ # Check the session still exists after closing the websocket+ assert get_session(client, "123").app.config.width == "full"+ assert get_session_manager(client).app_config.width == "full"++ # Loading index page should have the new config+ response = client.get("/")+ assert response.status_code == 200+ assert '"width": "full"' in response.text++ # Shutdown the kernel+ client.post("/api/kernel/shutdown", headers=HEADERS)+++def test_restart_session(client: TestClient) -> None:+ with client.websocket_connect("/ws?session_id=123") as websocket:+ data = websocket.receive_json()+ assert_kernel_ready_response(data, create_response({}))++ # Send save request+ client.post(+ "/api/kernel/restart_session",+ headers=headers("123"),+ )++ # Check the session still exists after closing the websocket+ assert not get_session(client, "123")++ # New session with new ID (simulates refresh)+ # We start a new session+ with client.websocket_connect("/ws?session_id=456") as websocket:+ # First message is the kernel reconnected+ data = websocket.receive_json()+ assert_kernel_ready_response(+ data,+ create_response({}),+ )++ # Shutdown the kernel+ client.post("/api/kernel/shutdown", headers=HEADERS)diff --git a/tests/_server/api/endpoints/test_ws.py b/tests/_server/api/endpoints/test_ws.pyindex 88ccb88e67..e00dc6d775 100644--- a/tests/_server/api/endpoints/test_ws.py+++ b/tests/_server/api/endpoints/test_ws.py@@ -1,34 +1,57 @@# Copyright 2024 Marimo. All rights reserved.-import json+from __future__ import annotations++from typing import Any, Optionalimport pytestfrom starlette.testclient import TestClientfrom starlette.websockets import WebSocketDisconnect-KERNEL_READY_RESPONSE = {- "codes": ["import marimo as mo"],- "names": ["__"],- "layout": None,- "configs": [{"disabled": False, "hide_code": False}],-}+from marimo._messaging.ops import KernelReady+from marimo._utils.parse_dataclass import parse_raw+++def create_response(+ partial_response: dict[str, Any],+) -> dict[str, Any]:+ response: dict[str, Any] = {+ "cell_ids": ["Hbol"],+ "codes": ["import marimo as mo"],+ "names": ["__"],+ "layout": None,+ "resumed": False,+ "ui_values": {},+ "last_executed_code": {},+ "configs": [{"disabled": False, "hide_code": False}],+ }+ response.update(partial_response)+ return response+HEADERS = {"Marimo-Server-Token": "fake-token",}-def assert_kernel_ready_response(data_str: str) -> None:- as_json = json.loads(data_str)- data = as_json["data"]- assert data["cell_ids"]- assert len(data["cell_ids"]) == 1- del data["cell_ids"]- assert data == KERNEL_READY_RESPONSE+def assert_kernel_ready_response(+ raw_data: dict[str, Any], response: Optional[dict[str, Any]] = None+):+ if response is None:+ response = create_response({})+ data = parse_raw(raw_data["data"], KernelReady)+ expected = parse_raw(response, KernelReady)+ assert data.cell_ids == expected.cell_ids+ assert data.codes == expected.codes+ assert data.names == expected.names+ assert data.layout == expected.layout+ assert data.resumed == expected.resumed+ assert data.ui_values == expected.ui_values+ assert data.configs == expected.configsdef test_ws(client: TestClient) -> None:with client.websocket_connect("/ws?session_id=123") as websocket:- data = websocket.receive_text()+ data = websocket.receive_json()assert_kernel_ready_response(data)# shut down after websocket context manager exists, otherwise# the test fails on windows (event loop closed twice)@@ -41,56 +64,55 @@ def test_without_session(client: TestClient) -> None:raise AssertionError()assert exc_info.value.code == 1000assert exc_info.value.reason == "MARIMO_NO_SESSION_ID"---def test_refresh(client: TestClient) -> None:- with client.websocket_connect("/ws?session_id=123") as websocket:- data = websocket.receive_text()- assert_kernel_ready_response(data)- # New session with new ID (simulates refresh)- with client.websocket_connect("/ws?session_id=455") as websocket:- data = websocket.receive_text()- assert_kernel_ready_response(data)+ client.post("/api/kernel/shutdown", headers=HEADERS)def test_disconnect_and_reconnect(client: TestClient) -> None:with client.websocket_connect("/ws?session_id=123") as websocket:- data = websocket.receive_text()+ data = websocket.receive_json()assert_kernel_ready_response(data)- websocket.close()# Connect by the same session idwith client.websocket_connect("/ws?session_id=123") as websocket:- data = websocket.receive_text()- assert data == '{"op": "reconnected", "data": null}' # noqa: E501+ data = websocket.receive_json()+ assert data == {"op": "reconnected", "data": {}}+ data = websocket.receive_json()+ assert data["op"] == "alert"+client.post("/api/kernel/shutdown", headers=HEADERS)def test_disconnect_then_reconnect_then_refresh(client: TestClient) -> None:with client.websocket_connect("/ws?session_id=123") as websocket:- data = websocket.receive_text()+ data = websocket.receive_json()assert_kernel_ready_response(data)websocket.close()# Connect by the same session idwith client.websocket_connect("/ws?session_id=123") as websocket:- data = websocket.receive_text()- assert data == '{"op": "reconnected", "data": null}' # noqa: E501+ data = websocket.receive_json()+ assert data == {"op": "reconnected", "data": {}}+ data = websocket.receive_json()+ assert data["op"] == "alert"# New session with new ID (simulates refresh)- with client.websocket_connect("/ws?session_id=455") as websocket:- data = websocket.receive_text()- assert_kernel_ready_response(data)+ with client.websocket_connect("/ws?session_id=456") as websocket:+ data = websocket.receive_json()+ assert data == {"op": "reconnected", "data": {}}+ data = websocket.receive_json()+ assert_kernel_ready_response(data, create_response({"resumed": True}))++ client.post("/api/kernel/shutdown", headers=HEADERS)def test_fails_on_multiple_connections_with_other_sessions(client: TestClient,) -> None:with client.websocket_connect("/ws?session_id=123") as websocket:- data = websocket.receive_text()+ data = websocket.receive_json()assert_kernel_ready_response(data)with pytest.raises(WebSocketDisconnect) as exc_info:with client.websocket_connect("/ws?session_id=456") as other_websocket:- other_websocket.receive_text()+ other_websocket.receive_json()raise AssertionError()assert exc_info.value.code == 1003assert exc_info.value.reason == "MARIMO_ALREADY_CONNECTED"diff --git a/tests/_server/conftest.py b/tests/_server/conftest.pyindex fa6b15aa9f..e13ccfd7d0 100644--- a/tests/_server/conftest.py+++ b/tests/_server/conftest.py@@ -7,6 +7,7 @@ from starlette.testclient import TestClientfrom marimo._config.config import get_configurationfrom marimo._server.main import app+from marimo._server.sessions import SessionManagerfrom marimo._server.utils import initialize_asynciofrom tests._server.mocks import get_mock_session_manager@@ -22,7 +23,7 @@ def client_with_lifespans() -> Generator[TestClient, None, None]:yield c[email protected](scope="module")[email protected](scope="function")def client() -> TestClient:app.state.session_manager = get_mock_session_manager()app.state.user_config = get_configuration()@@ -34,3 +35,7 @@ def client() -> TestClient:app.state.server = uvicorn_serverreturn client+++def get_session_manager(client: TestClient) -> SessionManager:+ return client.app.state.session_manager # type: ignorediff --git a/tests/_server/mocks.py b/tests/_server/mocks.pyindex 4e6a05fb98..2c1edf663c 100644--- a/tests/_server/mocks.py+++ b/tests/_server/mocks.py@@ -1,5 +1,4 @@# Copyright 2024 Marimo. All rights reserved.-import functoolsimport tempfilefrom typing import Callable@@ -9,7 +8,6 @@ from marimo._server.model import SessionModefrom marimo._server.sessions import SessionManager[email protected]_cache()def get_mock_session_manager() -> SessionManager:temp_file = tempfile.NamedTemporaryFile(suffix=".py", delete=False)diff --git a/tests/_server/session/test_session_view.py b/tests/_server/session/test_session_view.pynew file mode 100644index 0000000000..7be9c8def8--- /dev/null+++ b/tests/_server/session/test_session_view.py@@ -0,0 +1,326 @@+# Copyright 2024 Marimo. All rights reserved.++from typing import Any+from unittest.mock import patch++from marimo._ast.cell import CellId_t, CellStatusType+from marimo._messaging.cell_output import CellChannel, CellOutput+from marimo._messaging.ops import (+ CellOp,+ VariableDeclaration,+ Variables,+ VariableValue,+ VariableValues,+ serialize,+)+from marimo._runtime.requests import (+ CreationRequest,+ ExecuteMultipleRequest,+ ExecutionRequest,+ SetUIElementValueRequest,+)+from marimo._server.session.session_view import SessionView++cell_id: CellId_t = "cell_1"++initial_output = CellOutput(+ channel=CellChannel.OUTPUT,+ data="Initial output",+ mimetype="text/plain",+)+updated_output = CellOutput(+ channel=CellChannel.OUTPUT,+ data="Updated output",+ mimetype="text/plain",+)++initial_status = "running"+updated_status: CellStatusType = "running"+++def test_session_view_cell_op() -> None:+ session_view = SessionView()++ # Create initial CellOp+ initial_cell_op = CellOp(+ cell_id=cell_id, output=initial_output, status=initial_status+ )+ session_view.add_operation(initial_cell_op)++ # Add updated CellOp to SessionView+ updated_cell_op = CellOp(+ cell_id=cell_id, output=updated_output, status=updated_status+ )+ session_view.add_operation(updated_cell_op)++ assert session_view.cell_operations[cell_id].output == updated_output+ assert session_view.cell_operations[cell_id].status == updated_status+++# Test adding Variables to SessionView+def test_session_view_variables() -> None:+ session_view = SessionView()++ # Create Variables operation+ variables_op = Variables(+ variables=[+ VariableDeclaration(name="var1", declared_by=[], used_by=[])+ ]+ )+ session_view.add_operation(variables_op)++ # Check if the Variables operation was added correctly+ assert session_view.variable_operations == variables_op+++# Test adding VariableValues to SessionView+def test_session_view_variable_values() -> None:+ session_view = SessionView()+ # Create Variables operation+ variables_op = Variables(+ variables=[+ VariableDeclaration(+ name="var1", declared_by=[cell_id], used_by=[]+ ),+ VariableDeclaration(+ name="var2", declared_by=[cell_id], used_by=[]+ ),+ ]+ )+ session_view.add_operation(variables_op)++ # Create VariableValues operation+ variable_values_op = VariableValues(+ variables=[+ VariableValue(name="var1", value=1),+ VariableValue(name="var2", value="hello"),+ ]+ )+ session_view.add_operation(variable_values_op)++ variables_names = session_view.variable_values.keys()+ assert list(variables_names) == ["var1", "var2"]++ # Add new Variable operation without the previous variables+ variables_op = Variables(+ variables=[+ VariableDeclaration(+ name="var2", declared_by=[cell_id], used_by=[]+ ),+ VariableDeclaration(+ name="var3", declared_by=[cell_id], used_by=[]+ ),+ ]+ )+ session_view.add_operation(variables_op)++ variables_names = session_view.variable_values.keys()+ # var1 was removed, var2 was not changed, var3 has no value yet+ assert list(variables_names) == ["var2"]+++def test_ui_values():+ session_view = SessionView()+ session_view.add_request(SetUIElementValueRequest([("test_ui", 123)]))+ assert "test_ui" in session_view.ui_values+ assert session_view.ui_values["test_ui"] == 123++ # Can add multiple values+ # and can overwrite values+ session_view.add_request(+ SetUIElementValueRequest([("test_ui2", 456), ("test_ui", 789)])+ )+ assert "test_ui2" in session_view.ui_values+ assert "test_ui" in session_view.ui_values+ assert session_view.ui_values["test_ui2"] == 456+ assert session_view.ui_values["test_ui"] == 789++ # Can add from CreationRequest+ session_view.add_request(+ CreationRequest(+ execution_requests=(),+ set_ui_element_value_request=SetUIElementValueRequest(+ [("test_ui3", 101112)]+ ),+ )+ )+ assert "test_ui3" in session_view.ui_values+++def test_last_run_code():+ session_view = SessionView()+ session_view.add_request(+ ExecuteMultipleRequest(+ execution_requests=(+ ExecutionRequest(cell_id=cell_id, code="print('hello')"),+ )+ )+ )+ assert session_view.last_executed_code[cell_id] == "print('hello')"++ # Can overwrite values and add multiple+ session_view.add_request(+ ExecuteMultipleRequest(+ execution_requests=(+ ExecutionRequest(cell_id=cell_id, code="print('hello world')"),+ ExecutionRequest(+ cell_id="cell_2", code="print('hello world')"+ ),+ )+ )+ )+ assert session_view.last_executed_code[cell_id] == "print('hello world')"+ assert session_view.last_executed_code["cell_2"] == "print('hello world')"++ # Can add from CreationRequest+ session_view.add_request(+ CreationRequest(+ execution_requests=(+ ExecutionRequest(cell_id=cell_id, code="print('hello')"),+ ),+ set_ui_element_value_request=SetUIElementValueRequest([]),+ )+ )+ assert session_view.last_executed_code[cell_id] == "print('hello')"+++def test_add_variables():+ session_view = SessionView()++ session_view.add_raw_operation(+ serialize(+ Variables(+ variables=[+ VariableDeclaration(+ name="var1", declared_by=[cell_id], used_by=[]+ ),+ VariableDeclaration(+ name="var2", declared_by=[cell_id], used_by=[]+ ),+ ]+ )+ )+ )+ session_view.add_raw_operation(+ serialize(+ VariableValues(+ variables=[+ VariableValue(name="var1", value=1),+ VariableValue(name="var2", value="hello"),+ ]+ )+ )+ )++ assert session_view.variable_operations.variables[0].name == "var1"+ assert session_view.variable_operations.variables[1].name == "var2"+ assert session_view.variable_values["var1"].value == "1"+ assert session_view.variable_values["var2"].value == "hello"+++def test_add_cell_op():+ session_view = SessionView()+ session_view.add_raw_operation(+ serialize(+ CellOp(+ cell_id=cell_id, output=initial_output, status=initial_status+ )+ )+ )++ assert session_view.cell_operations[cell_id].output == initial_output+ assert session_view.cell_operations[cell_id].status == initial_status+++# patch time+@patch("time.time", return_value=123)+def test_combine_console_outputs(time_mock: Any) -> None:+ del time_mock+ session_view = SessionView()+ session_view.add_operation(+ CellOp(+ cell_id=cell_id,+ console=CellOutput.stdout("one"),+ status="running",+ )+ )+ session_view.add_operation(+ CellOp(+ cell_id=cell_id,+ console=CellOutput.stdout("two"),+ status="running",+ )+ )++ assert session_view.cell_operations[cell_id].console == [+ CellOutput.stdout("one"),+ CellOutput.stdout("two"),+ ]++ # Moves to queued+ session_view.add_operation(+ CellOp(+ cell_id=cell_id,+ console=None,+ status="queued",+ )+ )++ assert session_view.cell_operations[cell_id].console == [+ CellOutput.stdout("one"),+ CellOutput.stdout("two"),+ ]++ # Moves to running clears console+ session_view.add_operation(+ CellOp(+ cell_id=cell_id,+ console=None,+ status="running",+ )+ )+ assert session_view.cell_operations[cell_id].console == []++ # Write again+ session_view.add_operation(+ CellOp(+ cell_id=cell_id,+ console=CellOutput.stdout("three"),+ status="running",+ )+ )+ assert session_view.cell_operations[cell_id].console == [+ CellOutput.stdout("three")+ ]+++@patch("time.time", return_value=123)+def test_stdin(time_mock: Any) -> None:+ del time_mock+ session_view = SessionView()+ session_view.add_operation(+ CellOp(+ cell_id=cell_id,+ console=CellOutput.stdout("Hello"),+ status="running",+ )+ )+ session_view.add_operation(+ CellOp(+ cell_id=cell_id,+ console=CellOutput.stdin("What is your name?"),+ status="running",+ )+ )++ assert session_view.cell_operations[cell_id].console == [+ CellOutput.stdout("Hello"),+ CellOutput.stdin("What is your name?"),+ ]++ session_view.add_stdin("marimo")++ assert session_view.cell_operations[cell_id].console == [+ CellOutput.stdout("Hello"),+ CellOutput.stdout("What is your name? marimo\n"),+ ]diff --git a/tests/_server/test_session_manager.py b/tests/_server/test_session_manager.pynew file mode 100644index 0000000000..93ba3a95ff--- /dev/null+++ b/tests/_server/test_session_manager.py@@ -0,0 +1,91 @@+from unittest.mock import Mock, patch++import pytest++from marimo._server.model import ConnectionState, SessionConsumer, SessionMode+from marimo._server.sessions import Session, SessionManager+++def mock_session_consumer():+ return Mock(spec=SessionConsumer)+++def mock_session():+ session = Mock(spec=Session)+ session.connection_state.return_value = ConnectionState.OPEN+ return session+++def session_manager():+ return SessionManager(+ filename=None,+ mode=SessionMode.EDIT,+ port=5000,+ development_mode=False,+ quiet=False,+ include_code=True,+ )+++def test_create_session(+ session_manager: SessionManager, mock_session_consumer: SessionConsumer+):+ session_id = "test_session_id"+ session = session_manager.create_session(session_id, mock_session_consumer)+ assert session_id in session_manager.sessions+ assert session_manager.get_session(session_id) is session+ # Close ourselves to finish the test+ session.close()+++def test_rename(session_manager: SessionManager):+ new_filename = "new_test.py"+ session_manager.rename(new_filename)+ assert session_manager.filename == new_filename+++def test_maybe_resume_session(+ session_manager: SessionManager, mock_session: Session+):+ session_id = "test_session_id"+ mock_session.connection_state.return_value = ConnectionState.ORPHANED+ session_manager.sessions[session_id] = mock_session+ resumed_session = session_manager.maybe_resume_session(session_id)+ assert resumed_session is mock_session+++def test_close_session(session_manager: SessionManager, mock_session: Session):+ session_id = "test_session_id"+ session_manager.sessions[session_id] = mock_session+ session_manager.close_session(session_id)+ assert session_id not in session_manager.sessions+ mock_session.close.assert_called_once()+++def test_close_all_sessions(+ session_manager: SessionManager, mock_session: Session+):+ session_manager.sessions = {+ "session1": mock_session,+ "session2": mock_session,+ }+ session_manager.close_all_sessions()+ assert len(session_manager.sessions) == 0+ assert mock_session.close.call_count == 2+++def test_shutdown(session_manager: SessionManager, mock_session: Session):+ session_manager.sessions = {+ "session1": mock_session,+ "session2": mock_session,+ }+ with patch.object(+ session_manager, "lsp_process", create=True+ ) as mock_lsp_process:+ session_manager.shutdown()+ mock_lsp_process.terminate.assert_called_once()+ assert len(session_manager.sessions) == 0+ assert mock_session.close.call_count == 2diff --git a/tests/_server/test_sessions.py b/tests/_server/test_sessions.pyindex 3bfec31de8..27233c6c3c 100644--- a/tests/_server/test_sessions.py+++ b/tests/_server/test_sessions.py@@ -4,8 +4,9 @@ from multiprocessing.queues import Queue as MPQueuefrom typing import Anyfrom unittest.mock import MagicMock+from marimo._ast.app import App, InternalAppfrom marimo._runtime.requests import AppMetadata-from marimo._server.model import SessionMode+from marimo._server.model import ConnectionState, SessionModefrom marimo._server.sessions import KernelManager, QueueManager, Sessionfrom marimo._server.utils import initialize_asyncio@@ -52,23 +53,28 @@ def test_kernel_manager() -> None:def test_session() -> None:- session_handler: Any = MagicMock()+ session_consumer: Any = MagicMock()+ session_consumer.connection_state.return_value = ConnectionState.OPENqueue_manager = QueueManager(use_multiprocessing=False)kernel_manager = KernelManager(queue_manager, SessionMode.RUN, {}, app_metadata)# Instantiate a Session- session = Session(session_handler, queue_manager, kernel_manager)+ session = Session(+ InternalApp(App()), session_consumer, queue_manager, kernel_manager+ )# Assert startup- assert session.session_handler == session_handler+ assert session.session_consumer == session_consumerassert session._queue_manager == queue_managerassert session.kernel_manager == kernel_manager- session_handler.on_start.assert_called_once()- assert session_handler.on_stop.call_count == 0+ session_consumer.on_start.assert_called_once()+ assert session_consumer.on_stop.call_count == 0+ assert session.connection_state() == ConnectionState.OPENsession.close()+ session_consumer.connection_state.return_value = ConnectionState.CLOSED# Assert shutdownassert kernel_manager.kernel_task is not None@@ -76,5 +82,51 @@ def test_session() -> None:assert not kernel_manager.is_alive()assert queue_manager.input_queue.empty()assert queue_manager.control_queue.empty()- session_handler.on_start.assert_called_once()- session_handler.on_stop.assert_called_once()+ session_consumer.on_start.assert_called_once()+ session_consumer.on_stop.assert_called_once()+ assert session.connection_state() == ConnectionState.CLOSED+++def test_session_disconnect_reconnect() -> None:+ session_consumer: Any = MagicMock()+ session_consumer.connection_state.return_value = ConnectionState.OPEN+ queue_manager = QueueManager(use_multiprocessing=False)+ kernel_manager = KernelManager(+ queue_manager, SessionMode.RUN, {}, AppMetadata()+ )++ # Instantiate a Session+ session = Session(+ InternalApp(App()), session_consumer, queue_manager, kernel_manager+ )++ # Assert startup+ assert session.session_consumer == session_consumer+ session_consumer.on_start.assert_called_once()+ assert session_consumer.on_stop.call_count == 0++ session.disconnect_consumer()++ # Assert shutdown of consumer+ assert session.session_consumer is None+ session_consumer.on_start.assert_called_once()+ session_consumer.on_stop.assert_called_once()+ assert session.connection_state() == ConnectionState.ORPHANED++ # Reconnect+ new_session_consumer = MagicMock()+ session.connect_consumer(new_session_consumer)+ assert session.session_consumer == new_session_consumer+ new_session_consumer.on_start.assert_called_once()+ assert new_session_consumer.on_stop.call_count == 0++ session.close()+ new_session_consumer.connection_state.return_value = ConnectionState.CLOSED++ # Assert shutdown+ assert kernel_manager.kernel_task is not None+ kernel_manager.kernel_task.join()+ assert not kernel_manager.is_alive()+ new_session_consumer.on_start.assert_called_once()+ new_session_consumer.on_stop.assert_called_once()+ assert session.connection_state() == ConnectionState.CLOSEDdiff --git a/tests/_utils/test_disposable.py b/tests/_utils/test_disposable.pynew file mode 100644index 0000000000..165816aa4c--- /dev/null+++ b/tests/_utils/test_disposable.py@@ -0,0 +1,22 @@+from marimo._utils.disposable import Disposable+++def test_disposable():+ was_action_called = False++ def action():+ nonlocal was_action_called+ was_action_called = True++ disposable = Disposable(action)+ assert not disposable.is_disposed()+ disposable.dispose()+ assert was_action_called+ assert disposable.is_disposed()+++def test_disposable_empty():+ empty_disposable = Disposable.empty()+ assert not empty_disposable.is_disposed()+ empty_disposable.dispose()+ assert empty_disposable.is_disposed()diff --git a/tests/_utils/test_distributor.py b/tests/_utils/test_distributor.pynew file mode 100644index 0000000000..374c267f1c--- /dev/null+++ b/tests/_utils/test_distributor.py@@ -0,0 +1,51 @@+from typing import Any+from unittest.mock import MagicMock, patch++from marimo._utils.distributor import Distributor+++@patch("asyncio.get_event_loop")+def test_start(mock_get_event_loop: Any) -> None:+ mock_get_event_loop.return_value = MagicMock()++ mock_connection = MagicMock()+ distributor = Distributor[str](mock_connection)++ # Define two mock consumer functions+ mock_consumer1 = MagicMock()+ mock_consumer2 = MagicMock()++ # Add the consumers to the distributor+ distributor.add_consumer(mock_consumer1)+ distributor.add_consumer(mock_consumer2)++ distributor.start()++ # Send+ mock_connection.recv.side_effect = ["test message"]+ mock_connection.poll.return_value = True+ distributor._on_change()++ # Assert both consumers received the message+ mock_consumer1.assert_called_once_with("test message")+ mock_consumer2.assert_called_once_with("test message")++ # Remove one of the consumers+ distributor.consumers.remove(mock_consumer1)++ # Distribute another message+ mock_consumer1.reset_mock()+ mock_consumer2.reset_mock()++ # Send+ mock_connection.recv.side_effect = ["test message"]+ mock_connection.poll.return_value = True+ distributor._on_change()++ # Assert only one consumer received the message+ mock_consumer1.assert_not_called()+ mock_consumer2.assert_called_once_with("test message")++ # Assert the event loop had the reader removed+ distributor.stop()+ assert mock_connection.closed