Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

fix: home-page followups (#1128)

Myles Scolnickd5a2f2bdb621
diff --git a/frontend/package.json b/frontend/package.json
index bb841e134a..348b98af0a 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -34,6 +34,7 @@
"@lezer/highlight": "^1.2.0",
"@lezer/lr": "^1.4.0",
"@open-rpc/client-js": "^1.8.1",
+ "@paralleldrive/cuid2": "^2.2.2",
"@radix-ui/colors": "^3.0.0",
"@radix-ui/primitive": "^1.0.1",
"@radix-ui/react-accordion": "^1.1.2",
diff --git a/frontend/pnpm-lock.yaml b/frontend/pnpm-lock.yaml
index 62451dda13..6b447dc02e 100644
--- a/frontend/pnpm-lock.yaml
+++ b/frontend/pnpm-lock.yaml
@@ -71,6 +71,9 @@ dependencies:
'@open-rpc/client-js':
specifier: ^1.8.1
version: 1.8.1
+ '@paralleldrive/cuid2':
+ specifier: ^2.2.2
+ version: 2.2.2
'@radix-ui/colors':
specifier: ^3.0.0
version: 3.0.0
@@ -3299,6 +3302,11 @@ packages:
'@lezer/lr': 1.4.0
dev: false
+ resolution: {integrity: sha512-V1JJ1WTRUqHHrOSh597hURcMqVKVGL/ea3kv0gSnEdsEZ0/+VyPghM1lMNGc00z7CIQorSvbKpuJkxvuHbvdbg==}
+ engines: {node: '>= 16'}
+ dev: false
+
/@nodelib/[email protected]:
resolution: {integrity: sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==}
engines: {node: '>= 8'}
@@ -3330,6 +3338,12 @@ packages:
- utf-8-validate
dev: false
+ /@paralleldrive/[email protected]:
+ resolution: {integrity: sha512-ZOBkgDwEdoYVlSeRbYYXs0S9MejQofiVYoTbKzy/6GQa39/q5tQU2IX46+shYnUkpEl3wc+J6wRlar7r2EK2xA==}
+ dependencies:
+ '@noble/hashes': 1.4.0
+ dev: false
+
resolution: {integrity: sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg==}
engines: {node: '>=14'}
diff --git a/frontend/src/components/home/home-page.tsx b/frontend/src/components/home/home-page.tsx
index 5a927ce859..e8412dd298 100644
--- a/frontend/src/components/home/home-page.tsx
+++ b/frontend/src/components/home/home-page.tsx
@@ -10,7 +10,12 @@ import React, { Suspense, useState } from "react";
import { Spinner } from "../icons/spinner";
import { ExternalLinkIcon, PowerOffIcon } from "lucide-react";
import { ShutdownButton } from "../editor/controls/shutdown-button";
-import { SessionId, getSessionId } from "@/core/kernel/session";
+import {
+ SessionId,
+ generateSessionId,
+ getSessionId,
+ isSessionId,
+} from "@/core/kernel/session";
import { useInterval } from "@/hooks/useInterval";
import { cn } from "@/utils/cn";
import { useImperativeModal } from "@/components/modal/ImperativeModal";
@@ -62,7 +67,17 @@ export const HomePage: React.FC = () => {
const runningNotebooks = new Map(
running.files.flatMap((file) =>
- file.sessionId ? [[file.path, file.sessionId]] : [],
+ file.initializationId && file.sessionId
+ ? [
+ [
+ file.path,
+ {
+ sessionId: file.sessionId,
+ initializationId: file.initializationId,
+ },
+ ],
+ ]
+ : [],
),
);
@@ -103,8 +118,19 @@ export const HomePage: React.FC = () => {
const NotebookList: React.FC<{
header: string;
- files: Array<{ name: string; path: string; sessionId?: string }>;
- runningNotebooks: Map<string, SessionId>;
+ files: Array<{
+ name: string;
+ path: string;
+ sessionId?: string;
+ initializationId?: string;
+ }>;
+ runningNotebooks: Map<
+ string,
+ {
+ sessionId: SessionId;
+ initializationId: string;
+ }
+ >;
setRunningNotebooks: (data: RunningNotebooksResponse) => void;
}> = ({ header, files, runningNotebooks, setRunningNotebooks }) => {
const { openConfirm, closeModal } = useImperativeModal();
@@ -119,81 +145,90 @@ const NotebookList: React.FC<{
<div
className="flex flex-col divide-y divide-[var(--slate-3)] border rounded overflow-hidden
max-h-[48rem] overflow-y-auto shadow-sm bg-background
- "
+ "
>
- {files.map((file) => (
- <a
- className="py-2 px-4 hover:bg-[var(--blue-2)] hover:text-primary transition-all duration-300 cursor-pointer group relative"
- key={file.path}
- href={`/?file=${file.path}`}
- target={tabTarget(file.path)}
- >
- <div className="flex flex-col justify-between">
- <span>{file.name}</span>
- <p
- title={file.path}
- className="text-sm text-muted-foreground
+ {files.map((file) => {
+ // If path is a sessionId, then it has not been saved yet
+ // We want to keep the sessionId in this case
+ const isNewNotebook = isSessionId(file.path);
+ const href = isNewNotebook
+ ? `/?file=${file.initializationId}&session_id=${file.path}`
+ : `/?file=${file.path}`;
+
+ return (
+ <a
+ className="py-2 px-4 hover:bg-[var(--blue-2)] hover:text-primary transition-all duration-300 cursor-pointer group relative"
+ key={file.path}
+ href={href}
+ target={tabTarget(file.initializationId || file.path)}
+ >
+ <div className="flex flex-col justify-between">
+ <span>{file.name}</span>
+ <p
+ title={file.path}
+ className="text-sm text-muted-foreground
overflow-hidden whitespace-nowrap overflow-ellipsis
"
- >
- {file.path}
- </p>
- </div>
- <div className="absolute right-16 top-0 bottom-0 flex items-center">
- {runningNotebooks.has(file.path) && (
- <Tooltip content="Shutdown">
- <Button
- size={"xs"}
- variant="outline"
- className="m-0 opacity-80 hover:opacity-100 hover:bg-accent text-destructive border-destructive hover:border-destructive hover:text-destructive bg-background hover:bg-[var(--red-1)]"
- onClick={(e) => {
- e.stopPropagation();
- e.preventDefault();
- 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) => {
- const sessionId = runningNotebooks.get(file.path);
- assertExists(sessionId);
- shutdownSession({ sessionId }).then(
- (response) => {
+ >
+ {file.path}
+ </p>
+ </div>
+ <div className="absolute right-16 top-0 bottom-0 flex items-center">
+ {runningNotebooks.has(file.path) && (
+ <Tooltip content="Shutdown">
+ <Button
+ size={"xs"}
+ variant="outline"
+ className="m-0 opacity-80 hover:opacity-100 hover:bg-accent text-destructive border-destructive hover:border-destructive hover:text-destructive bg-background hover:bg-[var(--red-1)]"
+ onClick={(e) => {
+ e.stopPropagation();
+ e.preventDefault();
+ 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) => {
+ const ids = runningNotebooks.get(file.path);
+ assertExists(ids);
+ shutdownSession({
+ sessionId: ids.sessionId,
+ }).then((response) => {
setRunningNotebooks(response);
- },
- );
- closeModal();
- toast({
- description: "Notebook has been shutdown.",
- });
- }}
- aria-label="Confirm Shutdown"
- >
- Shutdown
- </AlertDialogDestructiveAction>
- ),
- });
- }}
- >
- <PowerOffIcon size={16} />
- </Button>
- </Tooltip>
- )}
- </div>
- <div
- className={cn(
- "absolute right-8 top-0 bottom-0 rounded-lg flex items-center justify-center text-muted-foreground text-primary",
- )}
- >
- <ExternalLinkIcon
- size={24}
- className="absolute group-hover:opacity-100 opacity-0 transition-all duration-300"
- />
- </div>
- </a>
- ))}
+ });
+ closeModal();
+ toast({
+ description: "Notebook has been shutdown.",
+ });
+ }}
+ aria-label="Confirm Shutdown"
+ >
+ Shutdown
+ </AlertDialogDestructiveAction>
+ ),
+ });
+ }}
+ >
+ <PowerOffIcon size={16} />
+ </Button>
+ </Tooltip>
+ )}
+ </div>
+ <div
+ className={cn(
+ "absolute right-8 top-0 bottom-0 rounded-lg flex items-center justify-center text-muted-foreground text-primary",
+ )}
+ >
+ <ExternalLinkIcon
+ size={24}
+ className="absolute group-hover:opacity-100 opacity-0 transition-all duration-300"
+ />
+ </div>
+ </a>
+ );
+ })}
</div>
</div>
);
@@ -206,15 +241,16 @@ const Header: React.FC<{ children: React.ReactNode }> = ({ children }) => {
};
const CreateNewNotebook: React.FC = () => {
+ const sessionId = generateSessionId();
+ const initializationId = `__new__${sessionId}`;
return (
<a
className="relative rounded-lg p-6 group
- text-primary hover:bg-[var(--blue-2)] shadow-smAccent border
+ text-primary hover:bg-[var(--blue-2)] shadow-smAccent border
transition-all duration-300 cursor-pointer
"
- href={`/?file=__new__`}
- target="_blank"
- rel="noreferrer"
+ href={`/?file=${initializationId}`}
+ target={tabTarget(initializationId)}
>
<h2 className="text-lg font-semibold">Create a new notebook</h2>
<div className="group-hover:opacity-100 opacity-0 absolute right-5 top-0 bottom-0 rounded-lg flex items-center justify-center transition-all duration-300">
diff --git a/frontend/src/components/ui/toast.tsx b/frontend/src/components/ui/toast.tsx
index f451267f69..1edd966298 100644
--- a/frontend/src/components/ui/toast.tsx
+++ b/frontend/src/components/ui/toast.tsx
@@ -47,7 +47,10 @@ const Toast = React.forwardRef<
return (
<ToastPrimitives.Root
ref={ref}
- className={cn(toastVariants({ variant }), className)}
+ className={cn(
+ toastVariants({ variant: variant || "default" }),
+ className,
+ )}
{...props}
/>
);
diff --git a/frontend/src/core/kernel/__tests__/session.test.ts b/frontend/src/core/kernel/__tests__/session.test.ts
new file mode 100644
index 0000000000..bfa6a894e6
--- /dev/null
+++ b/frontend/src/core/kernel/__tests__/session.test.ts
@@ -0,0 +1,10 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import { describe, expect, it } from "vitest";
+import { generateSessionId, isSessionId } from "../session";
+
+describe("Session", () => {
+ it("should create a session", () => {
+ const id = generateSessionId();
+ expect(isSessionId(id)).toBe(true);
+ });
+});
diff --git a/frontend/src/core/kernel/session.ts b/frontend/src/core/kernel/session.ts
index 355934b70e..384829370d 100644
--- a/frontend/src/core/kernel/session.ts
+++ b/frontend/src/core/kernel/session.ts
@@ -1,10 +1,35 @@
/* Copyright 2024 Marimo. All rights reserved. */
-import { generateUUID } from "@/utils/uuid";
+import { init } from "@paralleldrive/cuid2";
import { TypedString } from "@/utils/typed";
+import { updateQueryParams } from "@/utils/urls";
export type SessionId = TypedString<"SessionId">;
-const sessionId = generateUUID() as SessionId;
+const createId = init({ length: 6 });
+
+export function generateSessionId(): SessionId {
+ return `s_${createId()}` as SessionId;
+}
+
+export function isSessionId(value: string | null): value is SessionId {
+ if (!value) {
+ return false;
+ }
+ return /^s_[\da-z]{6}$/.test(value);
+}
+
+const sessionId = (() => {
+ const url = new URL(window.location.href);
+ const id = url.searchParams.get("session_id") as SessionId | null;
+ if (isSessionId(id)) {
+ // Remove the session_id from the URL
+ updateQueryParams((params) => {
+ params.delete("session_id");
+ });
+ return id;
+ }
+ return generateSessionId();
+})();
/**
* Resume an existing session or start a new one
diff --git a/frontend/src/core/network/types.ts b/frontend/src/core/network/types.ts
index a3d8a28557..80f7c2bf8f 100644
--- a/frontend/src/core/network/types.ts
+++ b/frontend/src/core/network/types.ts
@@ -177,6 +177,7 @@ interface MarimoNotebook {
path: string;
lastModified?: number;
sessionId?: SessionId;
+ initializationId?: string;
}
export interface RecentFilesResponse {
diff --git a/marimo/_server/api/endpoints/home.py b/marimo/_server/api/endpoints/home.py
index 861747a2b1..9832966ecb 100644
--- a/marimo/_server/api/endpoints/home.py
+++ b/marimo/_server/api/endpoints/home.py
@@ -65,9 +65,11 @@ def _get_active_sessions(app_state: AppState) -> List[MarimoFile]:
path=(pretty_path(filename) if filename else session_id),
last_modified=0,
session_id=session_id,
+ initialization_id=session.initialization_id,
)
)
- return files
+ # These are better in reverse
+ return files[::-1]
@router.post("/running_notebooks")
diff --git a/marimo/_server/file_router.py b/marimo/_server/file_router.py
index 48eb0b7819..16f32735c7 100644
--- a/marimo/_server/file_router.py
+++ b/marimo/_server/file_router.py
@@ -68,7 +68,7 @@ class AppFileRouter(abc.ABC):
"""
Given a key, return an AppFileManager.
"""
- if key == AppFileRouter.NEW_FILE:
+ if key.startswith(AppFileRouter.NEW_FILE):
return AppFileManager(None)
for file in self.files:
diff --git a/marimo/_server/models/home.py b/marimo/_server/models/home.py
index fe2f957abb..646200010c 100644
--- a/marimo/_server/models/home.py
+++ b/marimo/_server/models/home.py
@@ -15,6 +15,9 @@ class MarimoFile:
last_modified: float
# Session id
session_id: Optional[SessionId] = None
+ # Session initialization id
+ # This is the ID for when the session was initialized
+ initialization_id: Optional[str] = None
@dataclass
diff --git a/marimo/_server/sessions.py b/marimo/_server/sessions.py
index 754dd00642..3e44809c88 100644
--- a/marimo/_server/sessions.py
+++ b/marimo/_server/sessions.py
@@ -242,6 +242,7 @@ class Session:
@classmethod
def create(
cls,
+ initialization_id: str,
session_consumer: SessionConsumer,
mode: SessionMode,
app_metadata: AppMetadata,
@@ -255,6 +256,7 @@ class Session:
queue_manager, mode, configs, app_metadata, user_config_manager
)
return cls(
+ initialization_id,
session_consumer,
queue_manager,
kernel_manager,
@@ -263,12 +265,17 @@ class Session:
def __init__(
self,
+ initialization_id: str,
session_consumer: SessionConsumer,
queue_manager: QueueManager,
kernel_manager: KernelManager,
app_file_manager: AppFileManager,
) -> None:
"""Initialize kernel and client connection to it."""
+ # This is some unique ID that we can use to identify the session
+ # We don't use the session_id because this can change if the
+ # session is resumed
+ self.initialization_id = initialization_id
self._queue_manager: QueueManager
self.app_file_manager = app_file_manager
# This can be optional in case a consumer gets disconnected,
@@ -454,6 +461,7 @@ class SessionManager:
self.recents.touch(app_file_manager.path)
self.sessions[session_id] = Session.create(
+ initialization_id=file_key,
session_consumer=session_consumer,
mode=self.mode,
app_metadata=AppMetadata(
@@ -526,7 +534,7 @@ class SessionManager:
def any_clients_connected(self, key: MarimoFileKey) -> bool:
"""Returns True if at least one client has an open socket."""
- if key == AppFileRouter.NEW_FILE:
+ if key.startswith(AppFileRouter.NEW_FILE):
return False
for session in self.sessions.values():
diff --git a/tests/_server/test_sessions.py b/tests/_server/test_sessions.py
index b0f1ce51f0..e2d2783c6f 100644
--- a/tests/_server/test_sessions.py
+++ b/tests/_server/test_sessions.py
@@ -89,6 +89,7 @@ def test_session() -> None:
# Instantiate a Session
session = Session(
+ "test",
session_consumer,
queue_manager,
kernel_manager,
@@ -132,6 +133,7 @@ def test_session_disconnect_reconnect() -> None:
# Instantiate a Session
session = Session(
+ "test",
session_consumer,
queue_manager,
kernel_manager,