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.

Thread Python `NewType` branding through to TypeScript (#8823)

Trevor Manz283789c134cf
diff --git a/frontend/src/__mocks__/notebook.ts b/frontend/src/__mocks__/notebook.ts
index 8bc3513d4a..3c3263ebf2 100644
--- a/frontend/src/__mocks__/notebook.ts
+++ b/frontend/src/__mocks__/notebook.ts
@@ -22,16 +22,16 @@ export const MockNotebook = {
},
notebookState: (opts?: {
- cellData: Record<string, Partial<CellData>>;
- cellRuntime?: Record<string, Partial<CellRuntimeState>>;
+ cellData: Record<CellId, Partial<CellData>>;
+ cellRuntime?: Record<CellId, Partial<CellRuntimeState>>;
}): NotebookState => {
- const cellData = opts?.cellData || {};
- const cellRuntime = opts?.cellRuntime || {};
+ const cellData = opts?.cellData ?? {};
+ const cellRuntime = opts?.cellRuntime ?? {};
return {
- cellData: Objects.mapValues(cellData, (data, cellId) => ({
- id: cellId as CellId,
+ cellData: Objects.mapValues(cellData, (data, cid) => ({
+ id: cid,
code: "",
- name: `cell-${cellId}`,
+ name: `cell-${cid}`,
config: {
hide_code: false,
disabled: false,
@@ -45,8 +45,8 @@ export const MockNotebook = {
...data,
})),
cellIds: MultiColumn.from([Object.keys(cellData) as CellId[]]),
- cellRuntime: Objects.mapValues(cellData, (_data, cellId) =>
- createCellRuntimeState({ ...cellRuntime[cellId] }),
+ cellRuntime: Objects.mapValues(cellData, (_data, cid) =>
+ createCellRuntimeState({ ...cellRuntime[cid] }),
),
cellHandles: Objects.mapValues(cellData, (_data) => createRef()),
cellLogs: [],
diff --git a/frontend/src/__tests__/branded.ts b/frontend/src/__tests__/branded.ts
new file mode 100644
index 0000000000..566447aefb
--- /dev/null
+++ b/frontend/src/__tests__/branded.ts
@@ -0,0 +1,20 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+/**
+ * Test-only helpers for constructing branded ID types from plain strings.
+ *
+ * In production code, branded types flow from the API (via codegen) or
+ * from designated creation points (e.g. CellId.create()). Tests need to
+ * construct these from string literals, which requires a cast. These
+ * helpers centralise that cast so test files don't scatter `as CellId`
+ * everywhere.
+ */
+
+import type { CellId, UIElementId } from "@/core/cells/ids";
+import type { RequestId } from "@/core/network/DeferredRequestRegistry";
+import type { VariableName } from "@/core/variables/types";
+
+export const cellId = (s: string) => s as CellId;
+export const variableName = (s: string) => s as VariableName;
+export const requestId = (s: string) => s as RequestId;
+export const uiElementId = (s: string) => s as UIElementId;
diff --git a/frontend/src/components/data-table/charts/__tests__/storage.test.ts b/frontend/src/components/data-table/charts/__tests__/storage.test.ts
index feb5f41a0b..429dfd94eb 100644
--- a/frontend/src/components/data-table/charts/__tests__/storage.test.ts
+++ b/frontend/src/components/data-table/charts/__tests__/storage.test.ts
@@ -12,7 +12,7 @@ vi.mock("@/utils/storage/storage", () => ({
},
}));
-import type { CellId } from "@/core/cells/ids";
+import { cellId } from "@/__tests__/branded";
import { availableStorage } from "@/utils/storage/storage";
import { ChartSchema } from "../schemas";
import type { TabName } from "../storage";
@@ -37,7 +37,7 @@ describe("Chart Transforms Storage", () => {
it("should store and retrieve tab data", () => {
const store = getDefaultStore();
- const cellId = "cell-1" as CellId;
+ const cid = cellId("cell-1");
const tabData = {
tabName: "Tab 1" as TabName,
chartType: ChartType.LINE,
@@ -51,17 +51,17 @@ describe("Chart Transforms Storage", () => {
// Set the atom value
const newMap = new Map();
- newMap.set(cellId, [tabData]);
+ newMap.set(cid, [tabData]);
store.set(tabsStorageAtom, newMap);
// Verify the value was set
const retrievedValue = store.get(tabsStorageAtom);
- expect(retrievedValue.get(cellId)).toEqual([tabData]);
+ expect(retrievedValue.get(cid)).toEqual([tabData]);
});
it("should handle multiple tabs for the same cell", () => {
const store = getDefaultStore();
- const cellId = "cell-1" as CellId;
+ const cid = cellId("cell-1");
const tabData1 = {
tabName: "Tab 1" as TabName,
chartType: ChartType.LINE,
@@ -85,12 +85,12 @@ describe("Chart Transforms Storage", () => {
// Set the atom value
const newMap = new Map();
- newMap.set(cellId, [tabData1, tabData2]);
+ newMap.set(cid, [tabData1, tabData2]);
store.set(tabsStorageAtom, newMap);
// Verify the value was set
const retrievedValue = store.get(tabsStorageAtom);
- expect(retrievedValue.get(cellId)).toEqual([tabData1, tabData2]);
+ expect(retrievedValue.get(cid)).toEqual([tabData1, tabData2]);
});
});
diff --git a/frontend/src/components/editor/__tests__/data-attributes.test.tsx b/frontend/src/components/editor/__tests__/data-attributes.test.tsx
index 751ca4b4f1..1bc28d8ac0 100644
--- a/frontend/src/components/editor/__tests__/data-attributes.test.tsx
+++ b/frontend/src/components/editor/__tests__/data-attributes.test.tsx
@@ -5,9 +5,9 @@ import { beforeAll, describe, expect, it } from "vitest";
import { SetupMocks } from "@/__mocks__/common";
import { MockNotebook } from "@/__mocks__/notebook";
import { MockRequestClient } from "@/__mocks__/requests";
+import { cellId } from "@/__tests__/branded";
import { TooltipProvider } from "@/components/ui/tooltip";
import { notebookAtom } from "@/core/cells/cells";
-import type { CellId } from "@/core/cells/ids";
import { createCellRuntimeState } from "@/core/cells/types";
import type { UserConfig } from "@/core/config/config-schema";
import type { OutputMessage } from "@/core/kernel/messages";
@@ -39,7 +39,7 @@ describe("Cell data attributes", () => {
"present",
])("should render cell with data-cell-id and data-cell-name in %s mode", (mode) => {
const { store, wrapper } = createTestWrapper();
- const cellId = "test" as CellId;
+ const cid = cellId("test");
const cellName = "test_cell";
const userConfig: UserConfig = {
@@ -83,7 +83,7 @@ describe("Cell data attributes", () => {
const notebook = MockNotebook.notebookState({
cellData: {
- [cellId]: {
+ [cid]: {
code: "",
name: cellName,
edited: false,
@@ -97,7 +97,7 @@ describe("Cell data attributes", () => {
},
});
- notebook.cellRuntime[cellId] = createCellRuntimeState({
+ notebook.cellRuntime[cid] = createCellRuntimeState({
status: "idle",
output: null,
consoleOutputs: [],
@@ -117,7 +117,7 @@ describe("Cell data attributes", () => {
const { container } = render(
<TooltipProvider>
<Cell
- cellId={cellId}
+ cellId={cid}
mode={mode as AppMode}
canDelete={true}
userConfig={userConfig}
@@ -131,7 +131,7 @@ describe("Cell data attributes", () => {
{ wrapper },
);
- const cellElement = container.querySelector(`[data-cell-id="${cellId}"]`);
+ const cellElement = container.querySelector(`[data-cell-id="${cid}"]`);
expect(cellElement).toBeTruthy();
expect(cellElement?.getAttribute("data-cell-name")).toBe(cellName);
});
@@ -139,7 +139,7 @@ describe("Cell data attributes", () => {
describe("Output data attributes", () => {
it("should render output with data-cell-role", () => {
- const cellId = "test" as CellId;
+ const cid = cellId("test");
const output: OutputMessage = {
channel: "output",
mimetype: "text/plain",
@@ -151,7 +151,7 @@ describe("Output data attributes", () => {
<TooltipProvider>
<OutputArea
output={output}
- cellId={cellId}
+ cellId={cid}
stale={false}
loading={false}
allowExpand={true}
diff --git a/frontend/src/components/editor/ai/__tests__/completion-utils.test.ts b/frontend/src/components/editor/ai/__tests__/completion-utils.test.ts
index 806ebfdab2..0e8d5814bd 100644
--- a/frontend/src/components/editor/ai/__tests__/completion-utils.test.ts
+++ b/frontend/src/components/editor/ai/__tests__/completion-utils.test.ts
@@ -1,5 +1,6 @@
/* Copyright 2026 Marimo. All rights reserved. */
import { beforeEach, describe, expect, it, type Mock, vi } from "vitest";
+import { variableName } from "@/__tests__/branded";
import { getCodes } from "@/core/codemirror/copilot/getCodes";
import { dataSourceConnectionsAtom } from "@/core/datasets/data-source-connections";
import { DUCKDB_ENGINE } from "@/core/datasets/engines";
@@ -7,7 +8,6 @@ import { datasetsAtom } from "@/core/datasets/state";
import type { DatasetsState } from "@/core/datasets/types";
import { store } from "@/core/state/jotai";
import { variablesAtom } from "@/core/variables/state";
-import type { Variable, VariableName } from "@/core/variables/types";
import { codeToCells, getAICompletionBody } from "../completion-utils";
// Mock getCodes function
@@ -205,16 +205,16 @@ describe("getAICompletionBody", () => {
it("should return the correct completion body with mentioned variables", () => {
// Set up test data in the Jotai store
- const testVariables: Record<VariableName, Variable> = {
- ["var1" as VariableName]: {
- name: "var1" as VariableName,
+ const testVariables = {
+ [variableName("var1")]: {
+ name: variableName("var1"),
value: "string value",
dataType: "string",
declaredBy: [],
usedBy: [],
},
- ["var2" as VariableName]: {
- name: "var2" as VariableName,
+ [variableName("var2")]: {
+ name: variableName("var2"),
value: "42",
dataType: "number",
declaredBy: [],
@@ -253,9 +253,9 @@ describe("getAICompletionBody", () => {
];
store.set(datasetsAtom, { tables: testDatasets } as DatasetsState);
- const testVariables: Record<VariableName, Variable> = {
- ["var1" as VariableName]: {
- name: "var1" as VariableName,
+ const testVariables = {
+ [variableName("var1")]: {
+ name: variableName("var1"),
value: "string value",
dataType: "string",
declaredBy: [],
@@ -285,9 +285,9 @@ describe("getAICompletionBody", () => {
it("should handle non-existent variables", () => {
// Set up test data in the Jotai store
- const testVariables: Record<VariableName, Variable> = {
- ["existingVar" as VariableName]: {
- name: "existingVar" as VariableName,
+ const testVariables = {
+ [variableName("existingVar")]: {
+ name: variableName("existingVar"),
value: "string value",
dataType: "string",
declaredBy: [],
@@ -322,9 +322,9 @@ describe("getAICompletionBody", () => {
];
store.set(datasetsAtom, { tables: testDatasets } as DatasetsState);
- const testVariables: Record<VariableName, Variable> = {
- ["conflict" as VariableName]: {
- name: "conflict" as VariableName,
+ const testVariables = {
+ [variableName("conflict")]: {
+ name: variableName("conflict"),
value: "string value",
dataType: "string",
declaredBy: [],
diff --git a/frontend/src/components/editor/navigation/__tests__/clipboard.test.ts b/frontend/src/components/editor/navigation/__tests__/clipboard.test.ts
index e77ca7b862..560f7f7cbd 100644
--- a/frontend/src/components/editor/navigation/__tests__/clipboard.test.ts
+++ b/frontend/src/components/editor/navigation/__tests__/clipboard.test.ts
@@ -4,8 +4,8 @@
import { act, renderHook } from "@testing-library/react";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { asMock, MockModules, Mocks, SetupMocks } from "@/__mocks__/common";
+import { cellId } from "@/__tests__/branded";
import type { CellActions, NotebookState } from "@/core/cells/cells";
-import type { CellId } from "@/core/cells/ids";
import { useCellClipboard } from "../clipboard";
// Mock dependencies
@@ -179,7 +179,7 @@ describe("useCellClipboard", () => {
});
it("should filter out non-existent cells", async () => {
- const nonExistentCellId = "non-existent" as CellId;
+ const nonExistentCellId = cellId("non-existent");
const { result } = renderHook(() => useCellClipboard());
diff --git a/frontend/src/components/editor/navigation/__tests__/selection.test.ts b/frontend/src/components/editor/navigation/__tests__/selection.test.ts
index 09bdad1cb3..e8e2602676 100644
--- a/frontend/src/components/editor/navigation/__tests__/selection.test.ts
+++ b/frontend/src/components/editor/navigation/__tests__/selection.test.ts
@@ -1,6 +1,7 @@
/* Copyright 2026 Marimo. All rights reserved. */
+
import { beforeEach, describe, expect, it } from "vitest";
-import type { CellId } from "@/core/cells/ids";
+import { cellId } from "@/__tests__/branded";
import { MultiColumn } from "@/utils/id-tree";
import type { CellSelectionState } from "../selection";
import { exportedForTesting } from "../selection";
@@ -8,11 +9,11 @@ import { exportedForTesting } from "../selection";
const { initialState, reducer, createActions } = exportedForTesting;
const CellIds = {
- a: "a" as CellId,
- b: "b" as CellId,
- c: "c" as CellId,
- d: "d" as CellId,
- e: "e" as CellId,
+ a: cellId("a"),
+ b: cellId("b"),
+ c: cellId("c"),
+ d: cellId("d"),
+ e: cellId("e"),
};
describe("cell selection reducer", () => {
diff --git a/frontend/src/components/editor/navigation/__tests__/state.test.ts b/frontend/src/components/editor/navigation/__tests__/state.test.ts
index 6ce33646a7..06042d9ff7 100644
--- a/frontend/src/components/editor/navigation/__tests__/state.test.ts
+++ b/frontend/src/components/editor/navigation/__tests__/state.test.ts
@@ -1,6 +1,7 @@
/* Copyright 2026 Marimo. All rights reserved. */
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { cellId } from "@/__tests__/branded";
import { type CellId, HTMLCellId } from "@/core/cells/ids";
const mockScrollCellIntoView = vi.fn();
@@ -14,12 +15,12 @@ vi.mock("../focus-utils", () => ({
type TemporarilyShownCodeState = Set<CellId>;
describe("temporarilyShownCodeActions", () => {
- const cellId = "cell-1" as CellId;
+ const cid = cellId("cell-1");
let cellElement: HTMLElement;
beforeEach(() => {
cellElement = document.createElement("div");
- cellElement.id = HTMLCellId.create(cellId);
+ cellElement.id = HTMLCellId.create(cid);
document.body.append(cellElement);
cellElement.focus();
@@ -37,17 +38,17 @@ describe("temporarilyShownCodeActions", () => {
});
it("should scroll cell into view when removing cell causes layout shift", () => {
- const state = new Set<CellId>([cellId]);
- removeCell(state, cellId);
+ const state = new Set<CellId>([cid]);
+ removeCell(state, cid);
- expect(mockScrollCellIntoView).toHaveBeenCalledWith(cellId);
+ expect(mockScrollCellIntoView).toHaveBeenCalledWith(cid);
});
it("should not scroll when focused cell is not found", () => {
vi.spyOn(HTMLCellId, "findElementThroughShadowDOMs").mockReturnValue(null);
- const state = new Set<CellId>([cellId]);
- removeCell(state, cellId);
+ const state = new Set<CellId>([cid]);
+ removeCell(state, cid);
expect(mockScrollCellIntoView).not.toHaveBeenCalled();
});
diff --git a/frontend/src/components/editor/output/MarimoErrorOutput.tsx b/frontend/src/components/editor/output/MarimoErrorOutput.tsx
index 0637918c51..c1770406db 100644
--- a/frontend/src/components/editor/output/MarimoErrorOutput.tsx
+++ b/frontend/src/components/editor/output/MarimoErrorOutput.tsx
@@ -316,7 +316,7 @@ export const MarimoErrorOutput = ({
<ul className="list-disc">
{error.cells.map((cid, cidIdx) => (
<li className={liStyle} key={`cell-${cidIdx}`}>
- <CellLinkError cellId={cid as CellId} />
+ <CellLinkError cellId={cid} />
</li>
))}
</ul>
@@ -491,7 +491,7 @@ export const MarimoErrorOutput = ({
) : (
<div>
{processTextForUrls(error.msg, `exception-${idx}`)}
- <CellLinkError cellId={error.raising_cell as CellId} />
+ <CellLinkError cellId={error.raising_cell} />
</div>
)}
</li>
@@ -518,7 +518,7 @@ export const MarimoErrorOutput = ({
) : (
<div>
{error.msg}
- <CellLinkError cellId={error.blamed_cell as CellId} />
+ <CellLinkError cellId={error.blamed_cell} />
</div>
)}
</li>
@@ -554,13 +554,13 @@ export const MarimoErrorOutput = ({
{error.msg}
{error.blamed_cell == null ? (
<span>
- (<CellLinkError cellId={error.raising_cell as CellId} />)
+ (<CellLinkError cellId={error.raising_cell} />)
</span>
) : (
<span>
- (<CellLinkError cellId={error.raising_cell as CellId} />
+ (<CellLinkError cellId={error.raising_cell} />
&nbsp;blames&nbsp;
- <CellLinkError cellId={error.blamed_cell as CellId} />)
+ <CellLinkError cellId={error.blamed_cell} />)
</span>
)}
</div>
@@ -578,7 +578,7 @@ export const MarimoErrorOutput = ({
{ancestorStoppedErrors.map((error, idx) => (
<div key={`ancestor-stopped-${idx}`}>
{error.msg}
- <CellLinkError cellId={error.raising_cell as CellId} />
+ <CellLinkError cellId={error.raising_cell} />
</div>
))}
{cellId && (
diff --git a/frontend/src/components/editor/output/__tests__/traceback.test.tsx b/frontend/src/components/editor/output/__tests__/traceback.test.tsx
index 4e03d9699b..b38d597a4c 100644
--- a/frontend/src/components/editor/output/__tests__/traceback.test.tsx
+++ b/frontend/src/components/editor/output/__tests__/traceback.test.tsx
@@ -3,8 +3,8 @@
import { render } from "@testing-library/react";
import { beforeAll, beforeEach, describe, expect, test, vi } from "vitest";
import { Tracebacks } from "@/__mocks__/tracebacks";
+import { cellId } from "@/__tests__/branded";
import { TooltipProvider } from "@/components/ui/tooltip";
-import type { CellId } from "@/core/cells/ids";
import { initialModeAtom } from "@/core/mode";
import { store } from "@/core/state/jotai";
import { renderHTML } from "@/plugins/core/RenderHTML";
@@ -14,7 +14,7 @@ import {
replaceTracebackPrefix,
} from "../MarimoTracebackOutput";
-const cellId = "1" as CellId;
+const cid = cellId("1");
describe("traceback component", () => {
beforeEach(() => {
@@ -25,7 +25,7 @@ describe("traceback component", () => {
test("extracts cell-link", () => {
const traceback = (
<TooltipProvider>
- <MarimoTracebackOutput traceback={Tracebacks.raw} cellId={cellId} />
+ <MarimoTracebackOutput traceback={Tracebacks.raw} cellId={cid} />
</TooltipProvider>
);
const { unmount, getAllByRole } = render(traceback);
@@ -45,7 +45,7 @@ describe("traceback component", () => {
test("renames File to Cell for relevant lines", () => {
const traceback = (
<TooltipProvider>
- <MarimoTracebackOutput traceback={Tracebacks.raw} cellId={cellId} />
+ <MarimoTracebackOutput traceback={Tracebacks.raw} cellId={cid} />
</TooltipProvider>
);
const { unmount, container } = render(traceback);
diff --git a/frontend/src/components/editor/output/console/__tests__/ConsoleOutput.test.tsx b/frontend/src/components/editor/output/console/__tests__/ConsoleOutput.test.tsx
index c83895240b..7ed85f951a 100644
--- a/frontend/src/components/editor/output/console/__tests__/ConsoleOutput.test.tsx
+++ b/frontend/src/components/editor/output/console/__tests__/ConsoleOutput.test.tsx
@@ -3,8 +3,8 @@
import { act, fireEvent, render, screen } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { SetupMocks } from "@/__mocks__/common";
+import { cellId } from "@/__tests__/branded";
import { TooltipProvider } from "@/components/ui/tooltip";
-import type { CellId } from "@/core/cells/ids";
import type { WithResponse } from "@/core/cells/types";
import type { OutputMessage } from "@/core/kernel/messages";
import { CONSOLE_CLEAR_DEBOUNCE_MS, ConsoleOutput } from "../ConsoleOutput";
@@ -24,7 +24,7 @@ describe("ConsoleOutput integration", () => {
});
const defaultProps = {
- cellId: "cell-1" as CellId,
+ cellId: cellId("cell-1"),
cellName: "test_cell",
consoleOutputs: [] as WithResponse<OutputMessage>[],
stale: false,
@@ -55,7 +55,7 @@ describe("ConsoleOutput integration", () => {
describe("ConsoleOutput pdb history", () => {
const defaultProps = {
- cellId: "cell-1" as CellId,
+ cellId: cellId("cell-1"),
cellName: "test_cell",
consoleOutputs: [] as WithResponse<OutputMessage>[],
stale: false,
@@ -215,7 +215,7 @@ describe("ConsoleOutput debounced clearing", () => {
});
const defaultProps = {
- cellId: "cell-1" as CellId,
+ cellId: cellId("cell-1"),
cellName: "test_cell",
consoleOutputs: [] as WithResponse<OutputMessage>[],
stale: false,
diff --git a/frontend/src/components/editor/renderers/vertical-layout/useFocusFirstEditor.ts b/frontend/src/components/editor/renderers/vertical-layout/useFocusFirstEditor.ts
index 4c8fe1332d..79865070bd 100644
--- a/frontend/src/components/editor/renderers/vertical-layout/useFocusFirstEditor.ts
+++ b/frontend/src/components/editor/renderers/vertical-layout/useFocusFirstEditor.ts
@@ -91,7 +91,7 @@ function focusCellByName(cellName: string) {
// Look for an editor to focus
const { cellHandles } = getNotebook();
- const cellId = cellElement.dataset.cellId as CellId | undefined;
+ const cellId = extractCellIdFromDomElement(cellElement);
if (!cellId) {
Logger.error(`Missing cellId for cell with name ${cellName}`);
@@ -111,3 +111,10 @@ function focusCellByName(cellName: string) {
focusFirstEditor();
}
}
+
+function extractCellIdFromDomElement(
+ cellElement: HTMLElement,
+): CellId | undefined {
+ const cellIdStr = cellElement.dataset.cellId ?? undefined;
+ return cellIdStr as CellId | undefined;
+}
diff --git a/frontend/src/components/storage/storage-inspector.tsx b/frontend/src/components/storage/storage-inspector.tsx
index 0f0f2dee18..3607d73c89 100644
--- a/frontend/src/components/storage/storage-inspector.tsx
+++ b/frontend/src/components/storage/storage-inspector.tsx
@@ -50,7 +50,6 @@ import type {
StoragePathKey,
} from "@/core/storage/types";
import { storagePathKey } from "@/core/storage/types";
-import type { VariableName } from "@/core/variables/types";
import { cn } from "@/utils/cn";
import { copyToClipboard } from "@/utils/copy";
import { downloadByURL } from "@/utils/download";
@@ -474,7 +473,7 @@ const StorageNamespaceSection: React.FC<{
<span>{namespace.displayName}</span>
{namespace.name && (
<span className="text-xs text-muted-foreground font-normal">
- (<EngineVariable variableName={namespace.name as VariableName} />)
+ (<EngineVariable variableName={namespace.name} />)
</span>
)}
<RefreshIconButton
diff --git a/frontend/src/components/tracing/tracing.tsx b/frontend/src/components/tracing/tracing.tsx
index 0b65ef9a1a..f742c847c6 100644
--- a/frontend/src/components/tracing/tracing.tsx
+++ b/frontend/src/components/tracing/tracing.tsx
@@ -243,7 +243,9 @@ const TraceBlockBody: React.FC<{
signalName: VEGA_HOVER_SIGNAL,
handler: (_name: string, value: unknown) => {
const signalValue = value as VegaHoverCellSignal;
- const hoveredCell = signalValue.cell?.[0] as CellId | undefined;
+ const hoveredCell = (signalValue.cell?.[0] ?? undefined) as
+ | CellId
+ | undefined;
setHoveredCellId(hoveredCell ?? null);
},
},
diff --git a/frontend/src/core/ai/__tests__/staged-cells.test.ts b/frontend/src/core/ai/__tests__/staged-cells.test.ts
index 996bbec7a1..fcd7acb984 100644
--- a/frontend/src/core/ai/__tests__/staged-cells.test.ts
+++ b/frontend/src/core/ai/__tests__/staged-cells.test.ts
@@ -3,6 +3,7 @@
import { renderHook } from "@testing-library/react";
import { getDefaultStore } from "jotai";
import { beforeEach, describe, expect, it, vi } from "vitest";
+import { cellId } from "@/__tests__/branded";
import { CellId } from "@/core/cells/ids";
import { updateEditorCodeFromPython } from "../../codemirror/language/utils";
import {
@@ -61,8 +62,8 @@ describe("staged-cells", () => {
beforeEach(() => {
store = getDefaultStore();
- cellId1 = "cell-1" as CellId;
- cellId2 = "cell-2" as CellId;
+ cellId1 = cellId("cell-1");
+ cellId2 = cellId("cell-2");
// Reset mocks
vi.clearAllMocks();
@@ -213,7 +214,7 @@ describe("staged-cells", () => {
const testCode = "print('hello world')";
// Mock CellId.create to return a predictable ID
- const mockCellId = "mock-cell-id" as CellId;
+ const mockCellId = cellId("mock-cell-id");
vi.mocked(CellId.create).mockReturnValue(mockCellId);
const returnedCellId = result.current.createStagedCell(testCode);
@@ -229,7 +230,7 @@ describe("staged-cells", () => {
it("should delete a staged cell", () => {
const { result } = renderHook(() => useStagedCells(store));
- const testCellId = "test-cell-id" as CellId;
+ const testCellId = cellId("test-cell-id");
result.current.deleteStagedCell(testCellId);
@@ -330,7 +331,7 @@ describe("staged-cells", () => {
const { result } = renderHook(() => useStagedCells(store));
// Create a staged cell
- const mockCellId = "mock-cell-id" as CellId;
+ const mockCellId = cellId("mock-cell-id");
vi.mocked(CellId.create).mockReturnValue(mockCellId);
const createdCellId = result.current.createStagedCell("test code");
@@ -341,7 +342,7 @@ describe("staged-cells", () => {
let state = store.get(stagedAICellsAtom);
expect(state.has(mockCellId)).toBe(true);
- expect(state.get(mockCellId)).toEqual({ type: "add_cell" });
+ expect(state.get(mockCellId)).toEqual({ type: cellId("add_cell") });
// Delete the staged cell
result.current.deleteStagedCell(mockCellId);
@@ -423,7 +424,7 @@ describe("onStream", () => {
result.current.onStream({ type: "text-start", id: "test-id" });
// Mock CellId.create to return a predictable ID
- const mockCellId = "mock-cell-id" as CellId;
+ const mockCellId = cellId("mock-cell-id");
vi.mocked(CellId.create).mockReturnValue(mockCellId);
result.current.onStream({
@@ -444,7 +445,7 @@ describe("onStream", () => {
const { result } = renderHook(() => useStagedCells(store));
result.current.onStream({ type: "text-start", id: "test-id" });
- const mockCellId = "mock-cell-id" as CellId;
+ const mockCellId = cellId("mock-cell-id");
vi.mocked(CellId.create).mockReturnValue(mockCellId);
result.current.onStream({
diff --git a/frontend/src/core/ai/context/providers/__tests__/cell-output.test.ts b/frontend/src/core/ai/context/providers/__tests__/cell-output.test.ts
index 8c85774d7c..50d4b42101 100644
--- a/frontend/src/core/ai/context/providers/__tests__/cell-output.test.ts
+++ b/frontend/src/core/ai/context/providers/__tests__/cell-output.test.ts
@@ -2,6 +2,7 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { Mocks } from "@/__mocks__/common";
+import { cellId } from "@/__tests__/branded";
// Mock the external dependencies
vi.mock("html-to-image", () => ({
@@ -13,7 +14,6 @@ vi.mock("@/utils/Logger", () => ({
}));
import type { NotebookState } from "@/core/cells/cells";
-import type { CellId } from "@/core/cells/ids";
import type { OutputMessage } from "@/core/kernel/messages";
import type { JotaiStore } from "@/core/state/jotai";
import { CellOutputContextProvider, getCellContextData } from "../cell-output";
@@ -35,21 +35,21 @@ describe("CellOutputContextProvider", () => {
// Create a basic mock notebook state
mockNotebook = {
cellIds: {
- inOrderIds: ["cell1" as CellId, "cell2" as CellId, "cell3" as CellId],
+ inOrderIds: ["cell1", "cell2", "cell3"],
},
cellData: {
cell1: {
- id: "cell1" as CellId,
+ id: "cell1",
name: "My Cell",
code: "print('hello world')",
},
cell2: {
- id: "cell2" as CellId,
+ id: "cell2",
name: "",
code: "import matplotlib.pyplot as plt\nplt.plot([1,2,3])",
},
cell3: {
- id: "cell3" as CellId,
+ id: "cell3",
name: "Empty Cell",
code: "# no output",
},
@@ -226,9 +226,9 @@ describe("Cell output utility functions", () => {
for (const testCase of testCases) {
mockStore = createMockStore({
- cellIds: { inOrderIds: ["test" as CellId] },
+ cellIds: { inOrderIds: ["test"] },
cellData: {
- test: { id: "test" as CellId, name: "", code: "" },
+ test: { id: "test", name: "", code: "" },
},
cellRuntime: {
test: {
@@ -261,9 +261,9 @@ describe("Cell output utility functions", () => {
for (const testCase of testCases) {
mockStore = createMockStore({
- cellIds: { inOrderIds: ["test" as CellId] },
+ cellIds: { inOrderIds: ["test"] },
cellData: {
- test: { id: "test" as CellId, name: "", code: "" },
+ test: { id: "test", name: "", code: "" },
},
cellRuntime: {
test: {
@@ -295,9 +295,9 @@ describe("Cell output utility functions", () => {
for (const testCase of testCases) {
mockStore = createMockStore({
- cellIds: { inOrderIds: ["test" as CellId] },
+ cellIds: { inOrderIds: ["test"] },
cellData: {
- test: { id: "test" as CellId, name: "", code: "" },
+ test: { id: "test", name: "", code: "" },
},
cellRuntime: {
test: {
@@ -369,9 +369,9 @@ describe("Cell output utility functions", () => {
).mockReturnValue(mockDiv);
mockStore = createMockStore({
- cellIds: { inOrderIds: ["test" as CellId] },
+ cellIds: { inOrderIds: ["test"] },
cellData: {
- test: { id: "test" as CellId, name: "", code: "" },
+ test: { id: "test", name: "", code: "" },
},
cellRuntime: {
test: {
@@ -396,16 +396,16 @@ describe("Cell output utility functions", () => {
beforeEach(() => {
mockNotebook = {
cellIds: {
- inOrderIds: ["cell1" as CellId, "cell2" as CellId],
+ inOrderIds: ["cell1", "cell2"],
},
cellData: {
cell1: {
- id: "cell1" as CellId,
+ id: "cell1",
name: "My Named Cell",
code: "x = 42",
},
cell2: {
- id: "cell2" as CellId,
+ id: "cell2",
name: "",
code: "y = x * 2",
},
@@ -432,7 +432,7 @@ describe("Cell output utility functions", () => {
});
it("should extract basic cell data", () => {
- const result = getCellContextData("cell1" as CellId, mockNotebook);
+ const result = getCellContextData(cellId("cell1"), mockNotebook);
expect(result.cellId).toBe("cell1");
expect(result.cellName).toBe("My Named Cell");
@@ -440,13 +440,13 @@ describe("Cell output utility functions", () => {
});
it("should generate cell name for unnamed cells", () => {
- const result = getCellContextData("cell2" as CellId, mockNotebook);
+ const result = getCellContextData(cellId("cell2"), mockNotebook);
expect(result.cellName).toBe("cell-1"); // 0-indexed, so cell2 is at index 1
});
it("should include cell output when present", () => {
- const result = getCellContextData("cell1" as CellId, mockNotebook);
+ const result = getCellContextData(cellId("cell1"), mockNotebook);
expect(result.cellOutput).toBeDefined();
expect(result.cellOutput?.outputType).toBe("text");
@@ -454,19 +454,19 @@ describe("Cell output utility functions", () => {
});
it("should not include cell output when not present", () => {
- const result = getCellContextData("cell2" as CellId, mockNotebook);
+ const result = getCellContextData(cellId("cell2"), mockNotebook);
expect(result.cellOutput).toBeUndefined();
});
it("should not include console outputs by default", () => {
- const result = getCellContextData("cell2" as CellId, mockNotebook);
+ const result = getCellContextData(cellId("cell2"), mockNotebook);
expect(result.consoleOutputs).toBeUndefined();
});
it("should include console outputs when opted in", () => {
- const result = getCellContextData("cell2" as CellId, mockNotebook, {
+ const result = getCellContextData(cellId("cell2"), mockNotebook, {
includeConsoleOutput: true,
});
@@ -478,7 +478,7 @@ describe("Cell output utility functions", () => {
});
it("should filter out empty console outputs", () => {
- const cell2Runtime = mockNotebook.cellRuntime["cell2" as CellId];
+ const cell2Runtime = mockNotebook.cellRuntime[cellId("cell2")];
if (cell2Runtime) {
(cell2Runtime as { consoleOutputs: OutputMessage[] }).consoleOutputs = [
{
@@ -492,7 +492,7 @@ describe("Cell output utility functions", () => {
];
}
- const result = getCellContextData("cell2" as CellId, mockNotebook, {
+ const result = getCellContextData(cellId("cell2"), mockNotebook, {
includeConsoleOutput: true,
});
@@ -501,7 +501,7 @@ describe("Cell output utility functions", () => {
});
it("should handle cells with both cell output and console outputs", () => {
- const cell1Runtime = mockNotebook.cellRuntime["cell1" as CellId];
+ const cell1Runtime = mockNotebook.cellRuntime[cellId("cell1")];
if (cell1Runtime) {
(cell1Runtime as { consoleOutputs: OutputMessage[] }).consoleOutputs = [
{
@@ -511,7 +511,7 @@ describe("Cell output utility functions", () => {
];
}
- const result = getCellContextData("cell1" as CellId, mockNotebook, {
+ const result = getCellContextData(cellId("cell1"), mockNotebook, {
includeConsoleOutput: true,
});
@@ -524,7 +524,7 @@ describe("Cell output utility functions", () => {
});
it("should handle empty console outputs array", () => {
- const result = getCellContextData("cell1" as CellId, mockNotebook, {
+ const result = getCellContextData(cellId("cell1"), mockNotebook, {
includeConsoleOutput: true,
});
@@ -532,7 +532,7 @@ describe("Cell output utility functions", () => {
});
it("should handle media outputs in cell output", () => {
- const cell1Runtime = mockNotebook.cellRuntime["cell1" as CellId];
+ const cell1Runtime = mockNotebook.cellRuntime[cellId("cell1")];
if (cell1Runtime) {
(cell1Runtime as { output: OutputMessage | null }).output = {
mimetype: "image/png",
@@ -540,7 +540,7 @@ describe("Cell output utility functions", () => {
} as OutputMessage;
}
- const result = getCellContextData("cell1" as CellId, mockNotebook);
+ const result = getCellContextData(cellId("cell1"), mockNotebook);
expect(result.cellOutput).toBeDefined();
expect(result.cellOutput?.outputType).toBe("media");
@@ -548,7 +548,7 @@ describe("Cell output utility functions", () => {
});
it("should handle media outputs in console outputs", () => {
- const cell2Runtime = mockNotebook.cellRuntime["cell2" as CellId];
+ const cell2Runtime = mockNotebook.cellRuntime[cellId("cell2")];
if (cell2Runtime) {
(cell2Runtime as { consoleOutputs: OutputMessage[] }).consoleOutputs = [
{
@@ -558,7 +558,7 @@ describe("Cell output utility functions", () => {
];
}
- const result = getCellContextData("cell2" as CellId, mockNotebook, {
+ const result = getCellContextData(cellId("cell2"), mockNotebook, {
includeConsoleOutput: true,
});
diff --git a/frontend/src/core/ai/context/providers/__tests__/datasource.test.ts b/frontend/src/core/ai/context/providers/__tests__/datasource.test.ts
index a8dc9ad1b6..e32b3021a6 100644
--- a/frontend/src/core/ai/context/providers/__tests__/datasource.test.ts
+++ b/frontend/src/core/ai/context/providers/__tests__/datasource.test.ts
@@ -2,7 +2,7 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import { beforeEach, describe, expect, it } from "vitest";
-import type { CellId } from "@/core/cells/ids";
+import { cellId, variableName } from "@/__tests__/branded";
import type {
ConnectionsMap,
DatasetTablesMap,
@@ -88,7 +88,7 @@ const createMockDataTable = (
source_type: "local",
num_rows: 100,
num_columns: 3,
- variable_name: name, // This makes it a dataframe
+ variable_name: variableName(name), // This makes it a dataframe
columns: [
{
name: "id",
@@ -634,7 +634,7 @@ describe("DatasourceContextProvider", () => {
describe("getDatasourceContext", () => {
it("should return null if no cell ID is found", () => {
- const context = getDatasourceContext("1" as CellId);
+ const context = getDatasourceContext(cellId("1"));
expect(context).toBeNull();
});
});
diff --git a/frontend/src/core/ai/context/providers/__tests__/tables.test.ts b/frontend/src/core/ai/context/providers/__tests__/tables.test.ts
index de017da497..d5ddc9ce22 100644
--- a/frontend/src/core/ai/context/providers/__tests__/tables.test.ts
+++ b/frontend/src/core/ai/context/providers/__tests__/tables.test.ts
@@ -1,6 +1,7 @@
/* Copyright 2026 Marimo. All rights reserved. */
import { describe, expect, it } from "vitest";
+import { variableName } from "@/__tests__/branded";
import type { DatasetTablesMap } from "@/core/datasets/data-source-connections";
import type { DataTable, DataTableColumn } from "@/core/kernel/messages";
import { type TableContextItem, TableContextProvider } from "../tables";
@@ -86,7 +87,7 @@ describe("TableContextProvider", () => {
it("should handle dataframe tables with variable names", () => {
const dfTable = createMockTable("df_analysis", {
- variable_name: "df_analysis",
+ variable_name: variableName("df_analysis"),
source: "pandas",
source_type: "local",
columns: [
@@ -180,7 +181,7 @@ describe("TableContextProvider", () => {
const table = createMockTable("remote_table", {
source: "postgresql://localhost:5432/mydb",
source_type: "connection",
- engine: "postgresql",
+ engine: variableName("postgresql"),
columns: [
createMockColumn("uuid", "string", "uuid"),
createMockColumn("created_at", "string", "timestamp with time zone"),
diff --git a/frontend/src/core/ai/context/providers/__tests__/variable.test.ts b/frontend/src/core/ai/context/providers/__tests__/variable.test.ts
index 2396374da8..85c9a29abe 100644
--- a/frontend/src/core/ai/context/providers/__tests__/variable.test.ts
+++ b/frontend/src/core/ai/context/providers/__tests__/variable.test.ts
@@ -2,9 +2,9 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import { describe, expect, it, vi } from "vitest";
-import type { CellId } from "@/core/cells/ids";
+import { cellId, variableName } from "@/__tests__/branded";
import type { DatasetTablesMap } from "@/core/datasets/data-source-connections";
-import type { Variable, VariableName, Variables } from "@/core/variables/types";
+import type { Variable, Variables } from "@/core/variables/types";
import { type VariableContextItem, VariableContextProvider } from "../variable";
// Mock the variable completions module
@@ -17,7 +17,7 @@ vi.mock("@/core/codemirror/completion/variable-completions", () => ({
prefix: string,
) => {
return Object.entries(variables).map(([name, variable]) => ({
- name: `${prefix}${name}`,
+ name: variableName(`${prefix}${name}`),
displayname: name,
detail: variable.dataType || "unknown",
boost,
@@ -34,9 +34,9 @@ const createMockVariable = (
name: string,
options: Partial<Variable> = {},
): Variable => ({
- name: name as VariableName,
- declaredBy: ["cell1" as CellId],
- usedBy: ["cell2" as CellId],
+ name: variableName(name),
+ declaredBy: [cellId("cell1")],
+ usedBy: [cellId("cell2")],
value: `value_of_${name}`,
dataType: "str",
...options,
@@ -55,10 +55,13 @@ describe("VariableContextProvider", () => {
it("should return variable items for single variable", () => {
const variables: Variables = {
- ["user_name" as VariableName]: createMockVariable("user_name", {
- value: '"John Doe"',
- dataType: "str",
- }),
+ [variableName("user_name")]: createMockVariable(
+ variableName("user_name"),
+ {
+ value: '"John Doe"',
+ dataType: "str",
+ },
+ ),
};
const tablesMap: DatasetTablesMap = new Map();
const provider = new VariableContextProvider(variables, tablesMap);
@@ -69,29 +72,32 @@ describe("VariableContextProvider", () => {
it("should return variable items for multiple variables with different types", () => {
const variables: Variables = {
- ["user_id" as VariableName]: createMockVariable("user_id", {
+ [variableName("user_id")]: createMockVariable(variableName("user_id"), {
value: "123",
dataType: "int",
- declaredBy: ["cell1" as CellId],
- usedBy: ["cell2" as CellId, "cell3" as CellId],
- }),
- ["is_active" as VariableName]: createMockVariable("is_active", {
- value: "True",
- dataType: "bool",
- declaredBy: ["cell2" as CellId],
- usedBy: [],
+ declaredBy: [cellId("cell1")],
+ usedBy: [cellId("cell2"), cellId("cell3")],
}),
- ["scores" as VariableName]: createMockVariable("scores", {
+ [variableName("is_active")]: createMockVariable(
+ variableName("is_active"),
+ {
+ value: "True",
+ dataType: "bool",
+ declaredBy: [cellId("cell2")],
+ usedBy: [],
+ },
+ ),
+ [variableName("scores")]: createMockVariable(variableName("scores"), {
value: "[1, 2, 3, 4, 5]",
dataType: "list",
- declaredBy: ["cell3" as CellId],
- usedBy: ["cell4" as CellId],
+ declaredBy: [cellId("cell3")],
+ usedBy: [cellId("cell4")],
}),
- ["config" as VariableName]: createMockVariable("config", {
+ [variableName("config")]: createMockVariable(variableName("config"), {
value: '{"debug": true, "timeout": 30}',
dataType: "dict",
- declaredBy: ["cell1" as CellId],
- usedBy: ["cell2" as CellId, "cell4" as CellId],
+ declaredBy: [cellId("cell1")],
+ usedBy: [cellId("cell2"), cellId("cell4")],
}),
};
const tablesMap: DatasetTablesMap = new Map();
@@ -103,18 +109,27 @@ describe("VariableContextProvider", () => {
it("should handle variables with null/undefined values", () => {
const variables: Variables = {
- ["null_var" as VariableName]: createMockVariable("null_var", {
- value: null,
- dataType: "NoneType",
- }),
- ["undefined_var" as VariableName]: createMockVariable("undefined_var", {
- value: undefined,
- dataType: null,
- }),
- ["empty_string" as VariableName]: createMockVariable("empty_string", {
- value: '""',
- dataType: "str",
- }),
+ [variableName("null_var")]: createMockVariable(
+ variableName("null_var"),
+ {
+ value: null,
+ dataType: "NoneType",
+ },
+ ),
+ [variableName("undefined_var")]: createMockVariable(
+ variableName("undefined_var"),
+ {
+ value: undefined,
+ dataType: null,
+ },
+ ),
+ [variableName("empty_string")]: createMockVariable(
+ variableName("empty_string"),
+ {
+ value: '""',
+ dataType: "str",
+ },
+ ),
};
const tablesMap: DatasetTablesMap = new Map();
const provider = new VariableContextProvider(variables, tablesMap);
@@ -125,23 +140,23 @@ describe("VariableContextProvider", () => {
it("should handle complex data types", () => {
const variables: Variables = {
- ["df" as VariableName]: createMockVariable("df", {
+ [variableName("df")]: createMockVariable(variableName("df"), {
value: "<DataFrame shape: (100, 5)>",
dataType: "pandas.DataFrame",
- declaredBy: ["cell1" as CellId],
- usedBy: ["cell2" as CellId, "cell3" as CellId],
+ declaredBy: [cellId("cell1")],
+ usedBy: [cellId("cell2"), cellId("cell3")],
}),
- ["model" as VariableName]: createMockVariable("model", {
+ [variableName("model")]: createMockVariable(variableName("model"), {
value: "<sklearn.linear_model.LinearRegression>",
dataType: "sklearn.linear_model._base.LinearRegression",
- declaredBy: ["cell4" as CellId],
- usedBy: ["cell5" as CellId],
+ declaredBy: [cellId("cell4")],
+ usedBy: [cellId("cell5")],
}),
- ["array" as VariableName]: createMockVariable("array", {
+ [variableName("array")]: createMockVariable(variableName("array"), {
value: "array([1, 2, 3, 4, 5])",
dataType: "numpy.ndarray",
- declaredBy: ["cell2" as CellId],
- usedBy: ["cell3" as CellId],
+ declaredBy: [cellId("cell2")],
+ usedBy: [cellId("cell3")],
}),
};
const tablesMap: DatasetTablesMap = new Map();
@@ -153,21 +168,27 @@ describe("VariableContextProvider", () => {
it("should handle variables with special characters in names", () => {
const variables: Variables = {
- ["_private_var" as VariableName]: createMockVariable("_private_var", {
- value: "42",
- dataType: "int",
- }),
- ["var_with_numbers123" as VariableName]: createMockVariable(
- "var_with_numbers123",
+ [variableName("_private_var")]: createMockVariable(
+ variableName("_private_var"),
+ {
+ value: "42",
+ dataType: "int",
+ },
+ ),
+ [variableName("var_with_numbers123")]: createMockVariable(
+ variableName("var_with_numbers123"),
{
value: '"test"',
dataType: "str",
},
),
- ["CONSTANT_VAR" as VariableName]: createMockVariable("CONSTANT_VAR", {
- value: "3.14159",
- dataType: "float",
- }),
+ [variableName("CONSTANT_VAR")]: createMockVariable(
+ variableName("CONSTANT_VAR"),
+ {
+ value: "3.14159",
+ dataType: "float",
+ },
+ ),
};
const tablesMap: DatasetTablesMap = new Map();
const provider = new VariableContextProvider(variables, tablesMap);
@@ -191,7 +212,7 @@ describe("VariableContextProvider", () => {
data: { variable },
};
- const variables: Variables = { ["username" as VariableName]: variable };
+ const variables: Variables = { [variableName("username")]: variable };
const tablesMap: DatasetTablesMap = new Map();
const provider = new VariableContextProvider(variables, tablesMap);
@@ -213,7 +234,7 @@ describe("VariableContextProvider", () => {
};
const variables: Variables = {
- ["mystery_var" as VariableName]: variable,
+ [variableName("mystery_var")]: variable,
};
const tablesMap: DatasetTablesMap = new Map();
const provider = new VariableContextProvider(variables, tablesMap);
@@ -237,7 +258,7 @@ describe("VariableContextProvider", () => {
};
const variables: Variables = {
- ["complex_data" as VariableName]: variable,
+ [variableName("complex_data")]: variable,
};
const tablesMap: DatasetTablesMap = new Map();
const provider = new VariableContextProvider(variables, tablesMap);
@@ -260,7 +281,7 @@ describe("VariableContextProvider", () => {
data: { variable },
};
- const variables: Variables = { ["sales_df" as VariableName]: variable };
+ const variables: Variables = { [variableName("sales_df")]: variable };
const tablesMap: DatasetTablesMap = new Map();
const provider = new VariableContextProvider(variables, tablesMap);
@@ -284,12 +305,12 @@ describe("VariableContextProvider", () => {
describe("integration with tables", () => {
it("should work with both variables and tables", () => {
const variables: Variables = {
- ["df" as VariableName]: createMockVariable("df", {
+ [variableName("df")]: createMockVariable(variableName("df"), {
dataType: "pandas.DataFrame",
value: "<DataFrame shape: (50, 3)>",
}),
- ["connection_string" as VariableName]: createMockVariable(
- "connection_string",
+ [variableName("connection_string")]: createMockVariable(
+ variableName("connection_string"),
{
dataType: "str",
value: '"postgresql://localhost:5432/mydb"',
diff --git a/frontend/src/core/ai/tools/__tests__/edit-notebook-tool.test.ts b/frontend/src/core/ai/tools/__tests__/edit-notebook-tool.test.ts
index 29da0f39b6..11533e4e72 100644
--- a/frontend/src/core/ai/tools/__tests__/edit-notebook-tool.test.ts
+++ b/frontend/src/core/ai/tools/__tests__/edit-notebook-tool.test.ts
@@ -5,6 +5,7 @@ import { EditorView } from "@codemirror/view";
import { getDefaultStore } from "jotai";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { MockNotebook } from "@/__mocks__/notebook";
+import { cellId } from "@/__tests__/branded";
import { notebookAtom } from "@/core/cells/cells";
import type { CellId } from "@/core/cells/ids";
import { updateEditorCodeFromPython } from "@/core/codemirror/language/utils";
@@ -32,7 +33,7 @@ function createMockEditorView(code: string): EditorView {
doc: code,
extensions: [
adaptiveLanguageConfiguration({
- cellId: "cell1" as CellId,
+ cellId: cellId("cell1"),
completionConfig: {
copilot: false,
activate_on_typing: true,
@@ -44,7 +45,7 @@ function createMockEditorView(code: string): EditorView {
lspConfig: {},
}),
cellConfigExtension({
- cellId: "cell1" as CellId,
+ cellId: cellId("cell1"),
completionConfig: {
copilot: false,
activate_on_typing: true,
@@ -93,9 +94,9 @@ describe("EditNotebookTool", () => {
};
tool = new EditNotebookTool();
- cellId1 = "cell-1" as CellId;
- cellId2 = "cell-2" as CellId;
- cellId3 = "cell-3" as CellId;
+ cellId1 = cellId("cell-1");
+ cellId2 = cellId("cell-2");
+ cellId3 = cellId("cell-3");
// Reset mocks
vi.clearAllMocks();
@@ -270,7 +271,7 @@ describe("EditNotebookTool", () => {
{
edit: {
type: "update_cell",
- position: { cellId: "nonexistent" as CellId },
+ position: { cellId: cellId("nonexistent") },
code: "x = 2",
},
},
@@ -283,7 +284,7 @@ describe("EditNotebookTool", () => {
{
edit: {
type: "update_cell",
- position: { cellId: "nonexistent" as CellId },
+ position: { cellId: cellId("nonexistent") },
code: "x = 2",
},
},
@@ -496,7 +497,7 @@ describe("EditNotebookTool", () => {
type: "add_cell",
position: {
type: "relative",
- cellId: "nonexistent" as CellId,
+ cellId: cellId("nonexistent"),
before: true,
},
code: "y = 2",
@@ -660,7 +661,7 @@ describe("EditNotebookTool", () => {
{
edit: {
type: "delete_cell",
- position: { cellId: "nonexistent" as CellId },
+ position: { cellId: cellId("nonexistent") },
},
},
toolContext as never,
diff --git a/frontend/src/core/ai/tools/__tests__/run-cells-tool.test.ts b/frontend/src/core/ai/tools/__tests__/run-cells-tool.test.ts
index 6097bd457a..014d107df2 100644
--- a/frontend/src/core/ai/tools/__tests__/run-cells-tool.test.ts
+++ b/frontend/src/core/ai/tools/__tests__/run-cells-tool.test.ts
@@ -3,6 +3,7 @@
import { getDefaultStore } from "jotai";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { MockNotebook } from "@/__mocks__/notebook";
+import { cellId } from "@/__tests__/branded";
import { notebookAtom } from "@/core/cells/cells";
import type { CellId } from "@/core/cells/ids";
import { RunStaleCellsTool } from "../run-cells-tool";
@@ -46,9 +47,9 @@ describe("RunStaleCellsTool", () => {
tool = new RunStaleCellsTool({ postExecutionDelay: 0 });
- cellId1 = "cell-1" as CellId;
- cellId2 = "cell-2" as CellId;
- cellId3 = "cell-3" as CellId;
+ cellId1 = cellId("cell-1");
+ cellId2 = cellId("cell-2");
+ cellId3 = cellId("cell-3");
// Reset mocks
vi.clearAllMocks();
@@ -490,9 +491,8 @@ describe("RunStaleCellsTool", () => {
});
it("should omit output for cells that exceed total output budget", async () => {
- const cellIds = Array.from(
- { length: 25 },
- (_, i) => `budget-cell-${i}` as CellId,
+ const cellIds = Array.from({ length: 25 }, (_, i) =>
+ cellId(`budget-cell-${i}`),
);
const cellData: Record<string, { code: string; edited: boolean }> = {};
for (const id of cellIds) {
diff --git a/frontend/src/core/ai/tools/edit-notebook-tool.ts b/frontend/src/core/ai/tools/edit-notebook-tool.ts
index 0e2a6ba205..fd205d8d4a 100644
--- a/frontend/src/core/ai/tools/edit-notebook-tool.ts
+++ b/frontend/src/core/ai/tools/edit-notebook-tool.ts
@@ -90,7 +90,7 @@ export class EditNotebookTool
switch (edit.type) {
case "update_cell": {
const { position, code } = edit;
- const cellId = position.cellId as CellId;
+ const cellId = position.cellId as CellId | undefined;
if (!cellId) {
throw new ToolExecutionError(
@@ -152,7 +152,7 @@ export class EditNotebookTool
switch (position.type) {
case "relative": {
- const cellId = position.cellId as CellId;
+ const cellId = position.cellId as CellId | undefined;
if (!cellId) {
throw new ToolExecutionError(
"Cell ID is required for add_cell with relative position",
@@ -214,7 +214,7 @@ export class EditNotebookTool
}
case "delete_cell": {
const { position } = edit;
- const cellId = position.cellId as CellId;
+ const cellId = position.cellId as CellId | undefined;
if (!cellId) {
throw new ToolExecutionError(
diff --git a/frontend/src/core/cells/__tests__/add-missing-import.test.ts b/frontend/src/core/cells/__tests__/add-missing-import.test.ts
index dbe08a792d..69db7cc8e6 100644
--- a/frontend/src/core/cells/__tests__/add-missing-import.test.ts
+++ b/frontend/src/core/cells/__tests__/add-missing-import.test.ts
@@ -4,6 +4,7 @@ import { createStore } from "jotai";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { MockNotebook } from "@/__mocks__/notebook";
import { MockRequestClient } from "@/__mocks__/requests";
+import { cellId } from "@/__tests__/branded";
import { store } from "@/core/state/jotai";
import { variablesAtom } from "@/core/variables/state";
import type { Variables } from "@/core/variables/types";
@@ -13,7 +14,6 @@ import {
maybeAddMissingImport,
} from "../add-missing-import";
import { notebookAtom } from "../cells";
-import type { CellId } from "../ids";
// Mock the getRequestClient function
const mockRequestClient = MockRequestClient.create();
@@ -21,8 +21,8 @@ vi.mock("@/core/network/requests", () => ({
getRequestClient: () => mockRequestClient,
}));
-const Cell1 = "1" as CellId;
-const Cell2 = "2" as CellId;
+const Cell1 = cellId("1");
+const Cell2 = cellId("2");
describe("maybeAddMissingImport", () => {
beforeEach(() => {
diff --git a/frontend/src/core/cells/__tests__/cells.test.ts b/frontend/src/core/cells/__tests__/cells.test.ts
index 413e7f7227..6f69e45e29 100644
--- a/frontend/src/core/cells/__tests__/cells.test.ts
+++ b/frontend/src/core/cells/__tests__/cells.test.ts
@@ -14,8 +14,9 @@ import {
vi,
} from "vitest";
import { MockNotebook } from "@/__mocks__/notebook";
+import { cellId } from "@/__tests__/branded";
import type { CellHandle } from "@/components/editor/notebook-cell";
-import { CellId, SETUP_CELL_ID } from "@/core/cells/ids";
+import { CellId, SCRATCH_CELL_ID, SETUP_CELL_ID } from "@/core/cells/ids";
import { foldAllBulk, unfoldAllBulk } from "@/core/codemirror/editing/commands";
import { adaptiveLanguageConfiguration } from "@/core/codemirror/language/extension";
import { OverridingHotkeyProvider } from "@/core/hotkeys/hotkeys";
@@ -84,7 +85,7 @@ function createEditor(content: string) {
extensions: [
python(),
adaptiveLanguageConfiguration({
- cellId: "cell1" as CellId,
+ cellId: cellId("cell1"),
completionConfig: {
activate_on_typing: true,
signature_hint_on_typing: false,
@@ -113,14 +114,16 @@ describe("cell reducer", () => {
const actions = createActions((action) => {
state = reducer(state, action);
- for (const [cellId, handle] of Object.entries(state.cellHandles)) {
+ for (const [cellIdString, handle] of Object.entries(state.cellHandles)) {
+ // @ts-expect-error - Typescript Object.entries doesn't know that keys are CellId
+ const cid: CellId = cellIdString;
if (!handle.current) {
- const view = createEditor(state.cellData[cellId as CellId].code);
+ const view = createEditor(state.cellData[cid].code);
const handle: CellHandle = {
editorView: view,
editorViewOrNull: view,
};
- state.cellHandles[cellId as CellId] = { current: handle };
+ state.cellHandles[cid] = { current: handle };
}
}
cells = flattenTopLevelNotebookCells(state);
@@ -131,7 +134,7 @@ describe("cell reducer", () => {
beforeAll(() => {
CellId.create = () => {
- return `${i++}` as CellId;
+ return cellId(`${i++}`);
};
});
@@ -221,7 +224,7 @@ describe("cell reducer", () => {
`);
// Verify scrollKey is set to the restored cell
- expect(state.scrollKey).toBe("2" as CellId);
+ expect(state.scrollKey).toBe("2");
});
it("can delete a SQL cell and undo delete", () => {
@@ -362,7 +365,7 @@ describe("cell reducer", () => {
`);
// Add a column breakpoint to test left/right movement
- actions.addColumnBreakpoint({ cellId: "1" as CellId });
+ actions.addColumnBreakpoint({ cellId: cellId("1") });
expect(formatCells(state)).toMatchInlineSnapshot(`
"
> col 0
@@ -422,7 +425,7 @@ describe("cell reducer", () => {
// Try to move cell right when it's already in rightmost column (should noop)
actions.moveCell({
- cellId: "1" as CellId,
+ cellId: cellId("1"),
direction: "right",
});
expect(formatCells(state)).toMatchInlineSnapshot(`
@@ -442,7 +445,7 @@ describe("cell reducer", () => {
before: false,
});
actions.createNewCell({
- cellId: "1" as CellId,
+ cellId: cellId("1"),
before: false,
});
expect(formatCells(state)).toMatchInlineSnapshot(`
@@ -458,7 +461,7 @@ describe("cell reducer", () => {
// drag first cell to the end
actions.dropCellOverCell({
cellId: firstCellId,
- overCellId: "2" as CellId,
+ overCellId: cellId("2"),
});
expect(formatCells(state)).toMatchInlineSnapshot(`
"
@@ -473,7 +476,7 @@ describe("cell reducer", () => {
// drag it back to the middle
actions.dropCellOverCell({
cellId: firstCellId,
- overCellId: "2" as CellId,
+ overCellId: cellId("2"),
});
expect(formatCells(state)).toMatchInlineSnapshot(`
"
@@ -1001,7 +1004,7 @@ describe("cell reducer", () => {
data: [
{
msg: "This cell wasn't run because an ancestor was stopped with `mo.stop`: ",
- raising_cell: "2" as CellId,
+ raising_cell: "2",
type: "ancestor-stopped",
},
],
@@ -1284,8 +1287,8 @@ describe("cell reducer", () => {
it("can send a cell to the top", () => {
actions.createNewCell({ cellId: firstCellId, before: false });
- actions.createNewCell({ cellId: "1" as CellId, before: false });
- actions.sendToTop({ cellId: "2" as CellId });
+ actions.createNewCell({ cellId: cellId("1"), before: false });
+ actions.sendToTop({ cellId: cellId("2") });
expect(formatCells(state)).toMatchInlineSnapshot(`
"
[2] ''
@@ -1299,7 +1302,7 @@ describe("cell reducer", () => {
it("can send a cell to the bottom", () => {
actions.createNewCell({ cellId: firstCellId, before: false });
- actions.createNewCell({ cellId: "1" as CellId, before: false });
+ actions.createNewCell({ cellId: cellId("1"), before: false });
actions.sendToBottom({ cellId: firstCellId });
expect(formatCells(state)).toMatchInlineSnapshot(`
"
@@ -1314,12 +1317,12 @@ describe("cell reducer", () => {
it("can focus cells", () => {
actions.createNewCell({ cellId: firstCellId, before: false });
- actions.createNewCell({ cellId: "1" as CellId, before: false });
+ actions.createNewCell({ cellId: cellId("1"), before: false });
- actions.focusCell({ cellId: "1" as CellId, where: "before" });
+ actions.focusCell({ cellId: cellId("1"), where: "before" });
expect(focusAndScrollCellIntoView).toHaveBeenCalledWith(
expect.objectContaining({
- cellId: "0" as CellId,
+ cellId: cellId("0"),
}),
);
@@ -1336,7 +1339,7 @@ describe("cell reducer", () => {
});
it("can set cell IDs and codes", () => {
- const newIds = ["3", "4", "5"] as CellId[];
+ const newIds = [cellId("3"), cellId("4"), cellId("5")];
const newCodes = ["code1", "code2", "code3"];
actions.setCellIds({ cellIds: newIds });
@@ -1371,76 +1374,91 @@ describe("cell reducer", () => {
it("can can add a new cell with/without stale code", () => {
actions.setCellCodes({
codes: ["new code"],
- ids: ["2"] as CellId[],
+ ids: [cellId("2")],
codeIsStale: false,
});
- expect(state.cellData["2" as CellId].code).toBe("new code");
- expect(state.cellData["2" as CellId].edited).toBe(false);
- expect(state.cellData["2" as CellId].lastCodeRun).toBe("new code");
+ expect(state.cellData[cellId("2")].code).toBe("new code");
+ expect(state.cellData[cellId("2")].edited).toBe(false);
+ expect(state.cellData[cellId("2")].lastCodeRun).toBe("new code");
actions.setCellCodes({
codes: ["new code 2"],
- ids: ["9"] as CellId[],
+ ids: [cellId("9")],
codeIsStale: true,
});
- expect(state.cellData["9" as CellId].code).toBe("new code 2");
- expect(state.cellData["9" as CellId].edited).toBe(true);
- expect(state.cellData["9" as CellId].lastCodeRun).toBe(null);
+ expect(state.cellData[cellId("9")].code).toBe("new code 2");
+ expect(state.cellData[cellId("9")].edited).toBe(true);
+ expect(state.cellData[cellId("9")].lastCodeRun).toBe(null);
});
it("can partial update cell codes", () => {
actions.createNewCell({ cellId: firstCellId, before: false });
- actions.createNewCell({ cellId: "1" as CellId, before: false });
+ actions.createNewCell({ cellId: cellId("1"), before: false });
- expect(state.cellIds.inOrderIds).toEqual(["0", "1", "2"]);
- expect(state.cellData["0" as CellId].code).toBe("");
- expect(state.cellData["1" as CellId].code).toBe("");
- expect(state.cellData["2" as CellId].code).toBe("");
+ expect(state.cellIds.inOrderIds).toEqual([
+ cellId("0"),
+ cellId("1"),
+ cellId("2"),
+ ]);
+ expect(state.cellData[cellId("0")].code).toBe("");
+ expect(state.cellData[cellId("1")].code).toBe("");
+ expect(state.cellData[cellId("2")].code).toBe("");
// Update cell 1
actions.setCellCodes({
codes: ["new code 2"],
- ids: ["1"] as CellId[],
+ ids: [cellId("1")],
codeIsStale: false,
});
- expect(state.cellIds.inOrderIds).toEqual(["0", "1", "2"]);
- expect(state.cellData["0" as CellId].code).toBe("");
- expect(state.cellData["1" as CellId].code).toBe("new code 2");
- expect(state.cellData["1" as CellId].edited).toBe(false);
- expect(state.cellData["2" as CellId].code).toBe("");
+ expect(state.cellIds.inOrderIds).toEqual([
+ cellId("0"),
+ cellId("1"),
+ cellId("2"),
+ ]);
+ expect(state.cellData[cellId("0")].code).toBe("");
+ expect(state.cellData[cellId("1")].code).toBe("new code 2");
+ expect(state.cellData[cellId("1")].edited).toBe(false);
+ expect(state.cellData[cellId("2")].code).toBe("");
});
it("can set cell codes with new cell ids, while preserving the old cell data", () => {
actions.setCellCodes({
codes: ["code1", "code2", "code3"],
- ids: ["3", "4", "5"] as CellId[],
+ ids: [cellId("3"), cellId("4"), cellId("5")],
codeIsStale: false,
});
- expect(state.cellData["3" as CellId].code).toBe("code1");
- expect(state.cellData["4" as CellId].code).toBe("code2");
- expect(state.cellData["5" as CellId].code).toBe("code3");
+ expect(state.cellData[cellId("3")].code).toBe("code1");
+ expect(state.cellData[cellId("4")].code).toBe("code2");
+ expect(state.cellData[cellId("5")].code).toBe("code3");
// Update with some new cell ids and some old cell ids
- actions.setCellIds({ cellIds: ["1", "2", "3", "4"] as CellId[] });
+ actions.setCellIds({
+ cellIds: [cellId("1"), cellId("2"), cellId("3"), cellId("4")],
+ });
actions.setCellCodes({
codes: ["new1", "new2", "code1", "code2"],
- ids: ["1", "2", "3", "4"] as CellId[],
+ ids: [cellId("1"), cellId("2"), cellId("3"), cellId("4")],
codeIsStale: false,
});
- expect(state.cellData["1" as CellId].code).toBe("new1");
- expect(state.cellData["2" as CellId].code).toBe("new2");
- expect(state.cellData["3" as CellId].code).toBe("code1");
- expect(state.cellData["4" as CellId].code).toBe("code2");
- expect(state.cellIds.inOrderIds).toEqual(["1", "2", "3", "4"]);
+ expect(state.cellData[cellId("1")].code).toBe("new1");
+ expect(state.cellData[cellId("2")].code).toBe("new2");
+ expect(state.cellData[cellId("3")].code).toBe("code1");
+ expect(state.cellData[cellId("4")].code).toBe("code2");
+ expect(state.cellIds.inOrderIds).toEqual([
+ cellId("1"),
+ cellId("2"),
+ cellId("3"),
+ cellId("4"),
+ ]);
// Cell 5 data is preserved (possibly used for tracing), but it's not in the cellIds
- expect(state.cellData["5" as CellId]).not.toBeUndefined();
+ expect(state.cellData[cellId("5")]).not.toBeUndefined();
});
it("can set cell codes with names and configs", () => {
- const newIds = ["3", "4"] as CellId[];
+ const newIds = [cellId("3"), cellId("4")];
actions.setCellIds({ cellIds: newIds });
actions.setCellCodes({
codes: ["code1", "code2"],
@@ -1453,17 +1471,17 @@ describe("cell reducer", () => {
],
});
- expect(state.cellData["3" as CellId].name).toBe("setup_cell");
- expect(state.cellData["3" as CellId].config.hide_code).toBe(true);
- expect(state.cellData["3" as CellId].config.disabled).toBe(false);
+ expect(state.cellData[cellId("3")].name).toBe("setup_cell");
+ expect(state.cellData[cellId("3")].config.hide_code).toBe(true);
+ expect(state.cellData[cellId("3")].config.disabled).toBe(false);
- expect(state.cellData["4" as CellId].name).toBe("analysis");
- expect(state.cellData["4" as CellId].config.hide_code).toBe(false);
- expect(state.cellData["4" as CellId].config.disabled).toBe(true);
+ expect(state.cellData[cellId("4")].name).toBe("analysis");
+ expect(state.cellData[cellId("4")].config.hide_code).toBe(false);
+ expect(state.cellData[cellId("4")].config.disabled).toBe(true);
});
it("can set cell codes without names/configs (backward compat)", () => {
- const newIds = ["3"] as CellId[];
+ const newIds = [cellId("3")];
actions.setCellIds({ cellIds: newIds });
actions.setCellCodes({
codes: ["code1"],
@@ -1472,9 +1490,9 @@ describe("cell reducer", () => {
});
// Should use defaults when names/configs not provided
- expect(state.cellData["3" as CellId].code).toBe("code1");
- expect(state.cellData["3" as CellId].config.hide_code).toBe(false);
- expect(state.cellData["3" as CellId].config.disabled).toBe(false);
+ expect(state.cellData[cellId("3")].code).toBe("code1");
+ expect(state.cellData[cellId("3")].config.hide_code).toBe(false);
+ expect(state.cellData[cellId("3")].config.disabled).toBe(false);
});
it("can update names and configs on existing cells via setCellCodes", () => {
@@ -1521,12 +1539,12 @@ describe("cell reducer", () => {
it("can collapse and expand cells", () => {
actions.createNewCell({ cellId: firstCellId, before: false });
actions.createNewCell({
- cellId: "1" as CellId,
+ cellId: cellId("1"),
before: false,
code: "# Header",
});
actions.createNewCell({
- cellId: "2" as CellId,
+ cellId: cellId("2"),
before: false,
code: "## Subheader",
});
@@ -1549,25 +1567,25 @@ describe("cell reducer", () => {
it("can collapse and expand all cells in multiple columns", () => {
actions.createNewCell({ cellId: firstCellId, before: false });
actions.createNewCell({
- cellId: "1" as CellId,
+ cellId: cellId("1"),
before: false,
code: "# First Column Header",
});
actions.createNewCell({
- cellId: "2" as CellId,
+ cellId: cellId("2"),
before: false,
code: "## First Column Subheader",
});
- actions.addColumnBreakpoint({ cellId: "2" as CellId });
+ actions.addColumnBreakpoint({ cellId: cellId("2") });
actions.createNewCell({
- cellId: "3" as CellId,
+ cellId: cellId("3"),
before: false,
code: "# Second Column Header",
});
actions.createNewCell({
- cellId: "4" as CellId,
+ cellId: cellId("4"),
before: false,
code: "## Second Column Subheader",
});
@@ -1616,17 +1634,17 @@ describe("cell reducer", () => {
it("can collapse and expand nested cells in one call", () => {
actions.createNewCell({ cellId: firstCellId, before: false });
actions.createNewCell({
- cellId: "1" as CellId,
+ cellId: cellId("1"),
before: false,
code: "# Header",
});
actions.createNewCell({
- cellId: "2" as CellId,
+ cellId: cellId("2"),
before: false,
code: "## Subheader",
});
actions.createNewCell({
- cellId: "3" as CellId,
+ cellId: cellId("3"),
before: false,
code: "### Subsubheader",
});
@@ -1670,10 +1688,10 @@ describe("cell reducer", () => {
it("can show hidden cells", () => {
actions.createNewCell({ cellId: firstCellId, before: false });
- actions.createNewCell({ cellId: "1" as CellId, before: false });
+ actions.createNewCell({ cellId: cellId("1"), before: false });
actions.collapseCell({ cellId: firstCellId });
- actions.showCellIfHidden({ cellId: "1" as CellId });
+ actions.showCellIfHidden({ cellId: cellId("1") });
expect(state.cellIds.atOrThrow(FIRST_COLUMN).isCollapsed(firstCellId)).toBe(
false,
);
@@ -1748,8 +1766,8 @@ describe("cell reducer", () => {
it("can add a column breakpoint", () => {
actions.createNewCell({ cellId: firstCellId, before: false });
- actions.createNewCell({ cellId: "1" as CellId, before: false });
- actions.createNewCell({ cellId: "2" as CellId, before: false });
+ actions.createNewCell({ cellId: cellId("1"), before: false });
+ actions.createNewCell({ cellId: cellId("2"), before: false });
expect(state.cellIds.getColumns().length).toBe(1);
expect(formatCells(state)).toMatchInlineSnapshot(`
@@ -1764,7 +1782,7 @@ describe("cell reducer", () => {
"
`);
- actions.addColumnBreakpoint({ cellId: "2" as CellId });
+ actions.addColumnBreakpoint({ cellId: cellId("2") });
expect(state.cellIds.getColumns().length).toBe(2);
expect(formatCells(state)).toMatchInlineSnapshot(`
@@ -1782,23 +1800,29 @@ describe("cell reducer", () => {
`);
// Check that the cells are in the correct columns
- expect(state.cellIds.getColumns()[0].topLevelIds).toEqual(["0", "1"]);
- expect(state.cellIds.getColumns()[1].topLevelIds).toEqual(["2", "3"]);
+ expect(state.cellIds.getColumns()[0].topLevelIds).toEqual([
+ cellId("0"),
+ cellId("1"),
+ ]);
+ expect(state.cellIds.getColumns()[1].topLevelIds).toEqual([
+ cellId("2"),
+ cellId("3"),
+ ]);
});
it("cannot add a column breakpoint before the first cell", () => {
expect(state.cellIds.getColumns().length).toBe(1);
actions.createNewCell({ cellId: firstCellId, before: false });
- actions.createNewCell({ cellId: "1" as CellId, before: false });
+ actions.createNewCell({ cellId: cellId("1"), before: false });
actions.addColumnBreakpoint({ cellId: firstCellId });
expect(state.cellIds.getColumns().length).toBe(1);
});
it("can delete a column", () => {
actions.createNewCell({ cellId: firstCellId, before: false });
- actions.createNewCell({ cellId: "1" as CellId, before: false });
- actions.createNewCell({ cellId: "2" as CellId, before: false });
- actions.addColumnBreakpoint({ cellId: "2" as CellId });
+ actions.createNewCell({ cellId: cellId("1"), before: false });
+ actions.createNewCell({ cellId: cellId("2"), before: false });
+ actions.addColumnBreakpoint({ cellId: cellId("2") });
expect(state.cellIds.getColumns().length).toBe(2);
expect(formatCells(state)).toMatchInlineSnapshot(`
@@ -1842,7 +1866,7 @@ describe("cell reducer", () => {
it("deleting the last column does nothing", () => {
actions.createNewCell({ cellId: firstCellId, before: false });
- actions.createNewCell({ cellId: "1" as CellId, before: false });
+ actions.createNewCell({ cellId: cellId("1"), before: false });
const initialState = { ...state };
@@ -1854,8 +1878,8 @@ describe("cell reducer", () => {
it("can drop a cell over another cell", () => {
actions.createNewCell({ cellId: firstCellId, before: false });
- actions.createNewCell({ cellId: "1" as CellId, before: false });
- actions.createNewCell({ cellId: "2" as CellId, before: false });
+ actions.createNewCell({ cellId: cellId("1"), before: false });
+ actions.createNewCell({ cellId: cellId("2"), before: false });
expect(formatCells(state)).toMatchInlineSnapshot(`
"
@@ -1870,8 +1894,8 @@ describe("cell reducer", () => {
`);
actions.dropCellOverCell({
- cellId: "0" as CellId,
- overCellId: "3" as CellId,
+ cellId: cellId("0"),
+ overCellId: cellId("3"),
});
expect(formatCells(state)).toMatchInlineSnapshot(`
@@ -1889,7 +1913,7 @@ describe("cell reducer", () => {
it("can drop a cell over a new column", () => {
actions.createNewCell({ cellId: firstCellId, before: false });
- actions.createNewCell({ cellId: "1" as CellId, before: false });
+ actions.createNewCell({ cellId: cellId("1"), before: false });
expect(state.cellIds.getColumns().length).toBe(1);
expect(formatCells(state)).toMatchInlineSnapshot(`
@@ -1902,7 +1926,7 @@ describe("cell reducer", () => {
"
`);
- actions.dropOverNewColumn({ cellId: "1" as CellId });
+ actions.dropOverNewColumn({ cellId: cellId("1") });
expect(state.cellIds.getColumns().length).toBe(2);
expect(formatCells(state)).toMatchInlineSnapshot(`
@@ -1918,15 +1942,18 @@ describe("cell reducer", () => {
`);
// Check that the cells are in the correct columns
- expect(state.cellIds.getColumns()[0].topLevelIds).toEqual(["0", "2"]);
- expect(state.cellIds.getColumns()[1].topLevelIds).toEqual(["1"]);
+ expect(state.cellIds.getColumns()[0].topLevelIds).toEqual([
+ cellId("0"),
+ cellId("2"),
+ ]);
+ expect(state.cellIds.getColumns()[1].topLevelIds).toEqual([cellId("1")]);
});
it("can drop a column over another column", () => {
actions.createNewCell({ cellId: firstCellId, before: false });
- actions.createNewCell({ cellId: "1" as CellId, before: false });
- actions.createNewCell({ cellId: "2" as CellId, before: false });
- actions.addColumnBreakpoint({ cellId: "2" as CellId });
+ actions.createNewCell({ cellId: cellId("1"), before: false });
+ actions.createNewCell({ cellId: cellId("2"), before: false });
+ actions.addColumnBreakpoint({ cellId: cellId("2") });
expect(state.cellIds.getColumns().length).toBe(2);
expect(formatCells(state)).toMatchInlineSnapshot(`
@@ -1964,17 +1991,23 @@ describe("cell reducer", () => {
`);
// Check that the columns have swapped positions
- expect(state.cellIds.getColumns()[0].topLevelIds).toEqual(["2", "3"]);
- expect(state.cellIds.getColumns()[1].topLevelIds).toEqual(["0", "1"]);
+ expect(state.cellIds.getColumns()[0].topLevelIds).toEqual([
+ cellId("2"),
+ cellId("3"),
+ ]);
+ expect(state.cellIds.getColumns()[1].topLevelIds).toEqual([
+ cellId("0"),
+ cellId("1"),
+ ]);
});
it("can compact columns", () => {
// Create initial state with 3 columns, including an empty one
actions.createNewCell({ cellId: firstCellId, before: false });
- actions.createNewCell({ cellId: "1" as CellId, before: false });
- actions.addColumnBreakpoint({ cellId: "1" as CellId });
- actions.addColumnBreakpoint({ cellId: "2" as CellId });
- actions.dropOverNewColumn({ cellId: "2" as CellId });
+ actions.createNewCell({ cellId: cellId("1"), before: false });
+ actions.addColumnBreakpoint({ cellId: cellId("1") });
+ actions.addColumnBreakpoint({ cellId: cellId("2") });
+ actions.dropOverNewColumn({ cellId: cellId("2") });
expect(state.cellIds.getColumns().length).toBe(4);
expect(formatCells(state)).toMatchInlineSnapshot(`
@@ -1994,10 +2027,10 @@ describe("cell reducer", () => {
`);
// Check initial column structure
- expect(state.cellIds.getColumns()[0].topLevelIds).toEqual(["0"]);
- expect(state.cellIds.getColumns()[1].topLevelIds).toEqual(["1"]);
+ expect(state.cellIds.getColumns()[0].topLevelIds).toEqual([cellId("0")]);
+ expect(state.cellIds.getColumns()[1].topLevelIds).toEqual([cellId("1")]);
expect(state.cellIds.getColumns()[2].topLevelIds).toEqual([]);
- expect(state.cellIds.getColumns()[3].topLevelIds).toEqual(["2"]);
+ expect(state.cellIds.getColumns()[3].topLevelIds).toEqual([cellId("2")]);
// Compact columns
actions.compactColumns();
@@ -2017,9 +2050,9 @@ describe("cell reducer", () => {
`);
// Check compacted column structure
- expect(state.cellIds.getColumns()[0].topLevelIds).toEqual(["0"]);
- expect(state.cellIds.getColumns()[1].topLevelIds).toEqual(["1"]);
- expect(state.cellIds.getColumns()[2].topLevelIds).toEqual(["2"]);
+ expect(state.cellIds.getColumns()[0].topLevelIds).toEqual([cellId("0")]);
+ expect(state.cellIds.getColumns()[1].topLevelIds).toEqual([cellId("1")]);
+ expect(state.cellIds.getColumns()[2].topLevelIds).toEqual([cellId("2")]);
});
it("can clear output of a single cell", () => {
@@ -2406,7 +2439,7 @@ describe("cell reducer", () => {
const initialState = { ...state };
actions.moveToNextCell({
- cellId: "__scratch__" as CellId,
+ cellId: SCRATCH_CELL_ID,
before: false,
noCreate: false,
});
@@ -2498,7 +2531,7 @@ describe("cell reducer", () => {
});
it("can mark a non-existent cell as touched without error", () => {
- const nonExistentCellId = "non-existent" as CellId;
+ const nonExistentCellId = cellId("non-existent");
expect(() => {
actions.markTouched({ cellId: nonExistentCellId });
@@ -2829,7 +2862,7 @@ describe("isCellCodeHidden", () => {
const firstCellId = state.cellIds.inOrderIds[0];
it("returns false when hide_code is false and cell is not untouched", () => {
- const testCellId = "test-cell" as CellId;
+ const testCellId = cellId("test-cell");
const testState: NotebookState = {
...state,
cellData: {
@@ -2849,7 +2882,7 @@ describe("isCellCodeHidden", () => {
});
it("returns true when hide_code is true and cell is not untouched", () => {
- const testCellId = "test-cell" as CellId;
+ const testCellId = cellId("test-cell");
const testState: NotebookState = {
...state,
cellData: {
@@ -2869,7 +2902,7 @@ describe("isCellCodeHidden", () => {
});
it("returns false when hide_code is true but cell is untouched", () => {
- const testCellId = "test-cell" as CellId;
+ const testCellId = cellId("test-cell");
const testState: NotebookState = {
...state,
cellData: {
@@ -2889,7 +2922,7 @@ describe("isCellCodeHidden", () => {
});
it("returns false when hide_code is false and cell is untouched", () => {
- const testCellId = "test-cell" as CellId;
+ const testCellId = cellId("test-cell");
const testState: NotebookState = {
...state,
cellData: {
@@ -2917,8 +2950,8 @@ describe("createTracebackInfoAtom", () => {
notebookAtom,
MockNotebook.notebookState({
cellData: {
- cell1: {
- id: "cell1" as CellId,
+ [cellId("cell1")]: {
+ id: cellId("cell1"),
name: "cell1",
code: "",
},
@@ -2927,7 +2960,7 @@ describe("createTracebackInfoAtom", () => {
);
const tracebackAtom = exportedForTesting.createTracebackInfoAtom(
- "cell1" as CellId,
+ cellId("cell1"),
);
const traceback = store.get(tracebackAtom);
@@ -2939,10 +2972,14 @@ describe("createTracebackInfoAtom", () => {
notebookAtom,
MockNotebook.notebookState({
cellData: {
- cell1: { id: "cell1" as CellId, name: "cell1", code: "x = 1" },
+ [cellId("cell1")]: {
+ id: cellId("cell1"),
+ name: "cell1",
+ code: "x = 1",
+ },
},
cellRuntime: {
- cell1: {
+ [cellId("cell1")]: {
output: {
channel: "marimo-error",
data: [{ type: "syntax", msg: "Syntax error", lineno: 5 }],
@@ -2954,7 +2991,7 @@ describe("createTracebackInfoAtom", () => {
);
const tracebackAtom = exportedForTesting.createTracebackInfoAtom(
- "cell1" as CellId,
+ cellId("cell1"),
);
const traceback = store.get(tracebackAtom);
@@ -2962,7 +2999,7 @@ describe("createTracebackInfoAtom", () => {
expect(traceback).toHaveLength(1);
expect(traceback![0]).toEqual({
kind: "cell",
- cellId: "cell1",
+ cellId: cellId("cell1"),
lineNumber: 5,
});
});
@@ -2972,10 +3009,14 @@ describe("createTracebackInfoAtom", () => {
notebookAtom,
MockNotebook.notebookState({
cellData: {
- cell1: { id: "cell1" as CellId, name: "cell1", code: "x = 1" },
+ [cellId("cell1")]: {
+ id: cellId("cell1"),
+ name: "cell1",
+ code: "x = 1",
+ },
},
cellRuntime: {
- cell1: {
+ [cellId("cell1")]: {
output: {
channel: "marimo-error",
data: [{ type: "syntax", msg: "Syntax error", lineno: 0 }],
@@ -2987,7 +3028,7 @@ describe("createTracebackInfoAtom", () => {
);
const tracebackAtom = exportedForTesting.createTracebackInfoAtom(
- "cell1" as CellId,
+ cellId("cell1"),
);
const traceback = store.get(tracebackAtom);
expect(traceback).toBeDefined();
@@ -3000,10 +3041,14 @@ describe("createTracebackInfoAtom", () => {
notebookAtom,
MockNotebook.notebookState({
cellData: {
- cell1: { id: "cell1" as CellId, name: "cell1", code: "x = 1" },
+ [cellId("cell1")]: {
+ id: cellId("cell1"),
+ name: "cell1",
+ code: "x = 1",
+ },
},
cellRuntime: {
- cell1: {
+ [cellId("cell1")]: {
output: {
channel: "marimo-error",
data: [{ type: "syntax", msg: "Syntax error", lineno: null }],
@@ -3015,7 +3060,7 @@ describe("createTracebackInfoAtom", () => {
);
const tracebackAtom = exportedForTesting.createTracebackInfoAtom(
- "cell1" as CellId,
+ cellId("cell1"),
);
const traceback = store.get(tracebackAtom);
@@ -3027,10 +3072,14 @@ describe("createTracebackInfoAtom", () => {
notebookAtom,
MockNotebook.notebookState({
cellData: {
- cell1: { id: "cell1" as CellId, name: "cell1", code: "x = 1" },
+ [cellId("cell1")]: {
+ id: cellId("cell1"),
+ name: "cell1",
+ code: "x = 1",
+ },
},
cellRuntime: {
- cell1: {
+ [cellId("cell1")]: {
output: {
channel: "marimo-error",
data: [
@@ -3045,7 +3094,7 @@ describe("createTracebackInfoAtom", () => {
);
const tracebackAtom = exportedForTesting.createTracebackInfoAtom(
- "cell1" as CellId,
+ cellId("cell1"),
);
const traceback = store.get(tracebackAtom);
expect(traceback).toBeDefined();
@@ -3059,10 +3108,14 @@ describe("createTracebackInfoAtom", () => {
notebookAtom,
MockNotebook.notebookState({
cellData: {
- cell1: { id: "cell1" as CellId, name: "cell1", code: "x = 1" },
+ [cellId("cell1")]: {
+ id: cellId("cell1"),
+ name: "cell1",
+ code: "x = 1",
+ },
},
cellRuntime: {
- cell1: {
+ [cellId("cell1")]: {
output: {
channel: "marimo-error",
data: [{ type: "syntax", msg: "Syntax error", lineno: 1 }],
@@ -3075,7 +3128,7 @@ describe("createTracebackInfoAtom", () => {
);
const tracebackAtom = exportedForTesting.createTracebackInfoAtom(
- "cell1" as CellId,
+ cellId("cell1"),
);
const traceback = store.get(tracebackAtom);
@@ -3087,10 +3140,14 @@ describe("createTracebackInfoAtom", () => {
notebookAtom,
MockNotebook.notebookState({
cellData: {
- cell1: { id: "cell1" as CellId, name: "cell1", code: "x = 1" },
+ [cellId("cell1")]: {
+ id: cellId("cell1"),
+ name: "cell1",
+ code: "x = 1",
+ },
},
cellRuntime: {
- cell1: {
+ [cellId("cell1")]: {
output: {
channel: "marimo-error",
data: [{ type: "syntax", msg: "Syntax error", lineno: 1 }],
@@ -3103,7 +3160,7 @@ describe("createTracebackInfoAtom", () => {
);
const tracebackAtom = exportedForTesting.createTracebackInfoAtom(
- "cell1" as CellId,
+ cellId("cell1"),
);
const traceback = store.get(tracebackAtom);
diff --git a/frontend/src/core/cells/__tests__/focus.test.ts b/frontend/src/core/cells/__tests__/focus.test.ts
index 46590fed84..daa6f9a9c9 100644
--- a/frontend/src/core/cells/__tests__/focus.test.ts
+++ b/frontend/src/core/cells/__tests__/focus.test.ts
@@ -1,15 +1,16 @@
/* Copyright 2026 Marimo. All rights reserved. */
+
import { beforeEach, describe, expect, it } from "vitest";
-import type { CellId } from "@/core/cells/ids";
+import { cellId } from "@/__tests__/branded";
import type { CellFocusState } from "../focus";
import { exportedForTesting } from "../focus";
const { initialState, reducer, createActions } = exportedForTesting;
const CellIds = {
- a: "a" as CellId,
- b: "b" as CellId,
- c: "c" as CellId,
+ a: cellId("a"),
+ b: cellId("b"),
+ c: cellId("c"),
};
describe("cell focus reducer", () => {
diff --git a/frontend/src/core/cells/__tests__/logs.test.ts b/frontend/src/core/cells/__tests__/logs.test.ts
index d32cb349b2..ce7903d7b2 100644
--- a/frontend/src/core/cells/__tests__/logs.test.ts
+++ b/frontend/src/core/cells/__tests__/logs.test.ts
@@ -1,6 +1,7 @@
/* Copyright 2026 Marimo. All rights reserved. */
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
+import { cellId } from "@/__tests__/branded";
import type { CellMessage } from "../../kernel/messages";
import { formatLogTimestamp, getCellLogsForMessage } from "../logs";
@@ -18,7 +19,7 @@ describe("getCellLogsForMessage", () => {
test("handles text/plain MIME type on stdout", () => {
const cellMessage: CellMessage = {
- cell_id: "cell-1",
+ cell_id: cellId("cell-1"),
console: [
{
mimetype: "text/plain",
@@ -46,7 +47,7 @@ describe("getCellLogsForMessage", () => {
test("handles text/plain MIME type on stderr", () => {
const cellMessage: CellMessage = {
- cell_id: "cell-2",
+ cell_id: cellId("cell-2"),
console: [
{
mimetype: "text/plain",
@@ -74,7 +75,7 @@ describe("getCellLogsForMessage", () => {
test("handles text/html MIME type and strips HTML tags", () => {
const cellMessage: CellMessage = {
- cell_id: "cell-3",
+ cell_id: cellId("cell-3"),
console: [
{
mimetype: "text/html",
@@ -102,7 +103,7 @@ describe("getCellLogsForMessage", () => {
test("handles text/html MIME type on stderr", () => {
const cellMessage: CellMessage = {
- cell_id: "cell-4",
+ cell_id: cellId("cell-4"),
console: [
{
mimetype: "text/html",
@@ -130,7 +131,7 @@ describe("getCellLogsForMessage", () => {
test("handles application/vnd.marimo+traceback MIME type and strips HTML", () => {
const cellMessage: CellMessage = {
- cell_id: "cell-5",
+ cell_id: cellId("cell-5"),
console: [
{
mimetype: "application/vnd.marimo+traceback",
@@ -156,7 +157,7 @@ describe("getCellLogsForMessage", () => {
test("handles multiple console outputs with different MIME types", () => {
const cellMessage: CellMessage = {
- cell_id: "cell-7",
+ cell_id: cellId("cell-7"),
console: [
{
mimetype: "text/plain",
@@ -196,7 +197,7 @@ describe("getCellLogsForMessage", () => {
vi.spyOn(Date, "now").mockReturnValue(now);
const cellMessage: CellMessage = {
- cell_id: "cell-8",
+ cell_id: cellId("cell-8"),
console: [
{
mimetype: "text/plain",
@@ -219,7 +220,7 @@ describe("getCellLogsForMessage", () => {
test("ignores unsupported MIME types", () => {
const cellMessage: CellMessage = {
- cell_id: "cell-9",
+ cell_id: cellId("cell-9"),
console: [
{
mimetype: "application/json",
@@ -241,7 +242,7 @@ describe("getCellLogsForMessage", () => {
test("ignores non-logging channels", () => {
const cellMessage: CellMessage = {
- cell_id: "cell-10",
+ cell_id: cellId("cell-10"),
console: [
{
mimetype: "text/plain",
@@ -263,7 +264,7 @@ describe("getCellLogsForMessage", () => {
test("returns empty array when console is null", () => {
const cellMessage: CellMessage = {
- cell_id: "cell-11",
+ cell_id: cellId("cell-11"),
console: null as unknown as CellMessage["console"],
output: null,
status: "idle",
@@ -278,7 +279,7 @@ describe("getCellLogsForMessage", () => {
test("handles complex HTML with nested elements in text/html", () => {
const cellMessage: CellMessage = {
- cell_id: "cell-12",
+ cell_id: cellId("cell-12"),
console: [
{
mimetype: "text/html",
@@ -301,7 +302,7 @@ describe("getCellLogsForMessage", () => {
test("handles marimo-error channel as stderr level", () => {
const cellMessage: CellMessage = {
- cell_id: "cell-13",
+ cell_id: cellId("cell-13"),
console: [
{
mimetype: "text/plain",
diff --git a/frontend/src/core/cells/__tests__/pending-delete-service.test.tsx b/frontend/src/core/cells/__tests__/pending-delete-service.test.tsx
index 45c3b37c41..c62d4d336b 100644
--- a/frontend/src/core/cells/__tests__/pending-delete-service.test.tsx
+++ b/frontend/src/core/cells/__tests__/pending-delete-service.test.tsx
@@ -4,11 +4,11 @@ import { act, renderHook, waitFor } from "@testing-library/react";
import { createStore, Provider } from "jotai";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { MockNotebook } from "@/__mocks__/notebook";
+import { variableName } from "@/__tests__/branded";
import { notebookAtom } from "@/core/cells/cells";
import { CellId } from "@/core/cells/ids";
import { createCellRuntimeState } from "@/core/cells/types";
import { variablesAtom } from "@/core/variables/state";
-import type { VariableName } from "@/core/variables/types";
import type { Milliseconds } from "@/utils/time";
import {
usePendingDelete,
@@ -138,8 +138,8 @@ describe("pending-delete-service", () => {
store.set(notebookAtom, notebook);
store.set(variablesAtom, {
- ["x" as VariableName]: {
- name: "x" as VariableName,
+ [variableName("x")]: {
+ name: variableName("x"),
declaredBy: [cell1Id],
usedBy: [cell2Id],
},
diff --git a/frontend/src/core/cells/__tests__/runs.test.ts b/frontend/src/core/cells/__tests__/runs.test.ts
index 0d61b1fd14..493aa8a85a 100644
--- a/frontend/src/core/cells/__tests__/runs.test.ts
+++ b/frontend/src/core/cells/__tests__/runs.test.ts
@@ -1,6 +1,7 @@
/* Copyright 2026 Marimo. All rights reserved. */
import { beforeEach, describe, expect, it } from "vitest";
+import { cellId } from "@/__tests__/branded";
import type { CellMessage } from "@/core/kernel/messages";
import { invariant } from "@/utils/invariant";
import {
@@ -22,13 +23,13 @@ describe("RunsState Reducer", () => {
let state: RunsState;
const runId = "run1" as RunId;
- const cellId = "cell1";
+ const testCellId = cellId("cell1");
const timestamp = Date.now();
const code = "print('Hello World')";
const cellNotification: CellMessage = {
run_id: runId,
- cell_id: cellId,
+ cell_id: testCellId,
timestamp,
status: "queued",
};
@@ -61,9 +62,9 @@ describe("RunsState Reducer", () => {
runStartTime: timestamp,
cellRuns: new Map([
[
- cellId,
+ testCellId,
{
- cellId,
+ cellId: testCellId,
code: code.slice(0, MAX_CODE_LENGTH),
elapsedTime: 0,
startTime: timestamp,
@@ -98,7 +99,7 @@ describe("RunsState Reducer", () => {
payload: {
cellNotification: {
run_id: runId2,
- cell_id: "cell2",
+ cell_id: cellId("cell2"),
timestamp,
status: "queued",
},
@@ -124,7 +125,7 @@ describe("RunsState Reducer", () => {
payload: {
cellNotification: {
run_id: runId,
- cell_id: cellId,
+ cell_id: testCellId,
timestamp: timestamp + 1000,
status: "running",
},
@@ -145,7 +146,7 @@ describe("RunsState Reducer", () => {
payload: {
cellNotification: {
run_id: runId,
- cell_id: cellId,
+ cell_id: testCellId,
timestamp: runStartTimestamp + 5000,
status: "success",
},
@@ -171,8 +172,8 @@ describe("RunsState Reducer", () => {
type: "addCellNotification",
payload: {
cellNotification: {
- run_id: `run${i}`,
- cell_id: `cell${i}`,
+ run_id: `run${i}` as RunId,
+ cell_id: cellId(`cell${i}`),
timestamp: timestamp,
status: "queued",
},
@@ -198,7 +199,7 @@ describe("RunsState Reducer", () => {
payload: {
cellNotification: {
run_id: runId,
- cell_id: cellId,
+ cell_id: testCellId,
timestamp,
status: "queued",
},
@@ -220,7 +221,7 @@ describe("RunsState Reducer", () => {
payload: {
cellNotification: {
run_id: runId,
- cell_id: cellId,
+ cell_id: testCellId,
timestamp: errorTimestamp,
status: "running",
output: {
@@ -248,7 +249,7 @@ describe("RunsState Reducer", () => {
payload: {
cellNotification: {
run_id: runId,
- cell_id: cellId,
+ cell_id: testCellId,
timestamp: errorTimestamp,
status: "running",
output: {
@@ -273,7 +274,7 @@ describe("RunsState Reducer", () => {
payload: {
cellNotification: {
run_id: runId,
- cell_id: cellId,
+ cell_id: testCellId,
timestamp,
output: {
channel: "marimo-error",
@@ -288,7 +289,7 @@ describe("RunsState Reducer", () => {
payload: {
cellNotification: {
run_id: runId,
- cell_id: cellId,
+ cell_id: testCellId,
timestamp: timestamp + 2000,
status: "running", // shouldn't happen
},
@@ -312,7 +313,7 @@ describe("RunsState Reducer", () => {
payload: {
cellNotification: {
run_id: runId2,
- cell_id: "cell2",
+ cell_id: cellId("cell2"),
timestamp: timestamp + 1000,
status: "queued",
},
@@ -325,7 +326,7 @@ describe("RunsState Reducer", () => {
payload: {
cellNotification: {
run_id: runId3,
- cell_id: "cell3",
+ cell_id: cellId("cell3"),
timestamp: timestamp + 2000,
status: "queued",
},
@@ -345,7 +346,7 @@ describe("RunsState Reducer", () => {
payload: {
cellNotification: {
run_id: runId,
- cell_id: "cell2",
+ cell_id: cellId("cell2"),
timestamp: timestamp + 1000,
status: "queued",
},
@@ -367,7 +368,7 @@ describe("RunsState Reducer", () => {
payload: {
cellNotification: {
run_id: runId,
- cell_id: cellId,
+ cell_id: testCellId,
timestamp: timestamp + 1000,
status: "running",
},
@@ -386,7 +387,7 @@ describe("RunsState Reducer", () => {
payload: {
cellNotification: {
run_id: runId,
- cell_id: cellId,
+ cell_id: testCellId,
timestamp,
status: "queued",
},
@@ -405,7 +406,7 @@ describe("RunsState Reducer", () => {
payload: {
cellNotification: {
run_id: runId,
- cell_id: cellId,
+ cell_id: testCellId,
timestamp,
status: "queued",
},
@@ -419,7 +420,7 @@ describe("RunsState Reducer", () => {
payload: {
cellNotification: {
run_id: runId,
- cell_id: "cell2",
+ cell_id: cellId("cell2"),
timestamp: timestamp + 1000,
status: "queued",
},
diff --git a/frontend/src/core/cells/__tests__/scrollCellIntoView.test.ts b/frontend/src/core/cells/__tests__/scrollCellIntoView.test.ts
index 0339602db5..6e16534b24 100644
--- a/frontend/src/core/cells/__tests__/scrollCellIntoView.test.ts
+++ b/frontend/src/core/cells/__tests__/scrollCellIntoView.test.ts
@@ -1,7 +1,8 @@
/* Copyright 2026 Marimo. All rights reserved. */
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { type CellId, HTMLCellId } from "@/core/cells/ids";
+import { cellId } from "@/__tests__/branded";
+import { HTMLCellId } from "@/core/cells/ids";
import { Logger } from "@/utils/Logger";
// Mock the getCellEditorView function
@@ -20,12 +21,12 @@ vi.mock("@/core/codemirror/extensions", () => ({
const { scrollCellIntoView } = await import("@/core/cells/scrollCellIntoView");
describe("scrollCellIntoView", () => {
- const cellId = "test-cell-id" as CellId;
+ const cid = cellId("test-cell-id");
let cellElement: HTMLElement;
beforeEach(() => {
cellElement = document.createElement("div");
- cellElement.id = HTMLCellId.create(cellId);
+ cellElement.id = HTMLCellId.create(cid);
cellElement.scrollIntoView = vi.fn();
document.body.append(cellElement);
@@ -42,7 +43,7 @@ describe("scrollCellIntoView", () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
mockGetCellEditorView.mockReturnValue(mockEditor as any);
- scrollCellIntoView(cellId);
+ scrollCellIntoView(cid);
expect(mockScrollActiveLineIntoView).toHaveBeenCalledWith(mockEditor, {
behavior: "instant",
@@ -51,7 +52,7 @@ describe("scrollCellIntoView", () => {
});
it("should scroll cell element when editor is not focused", () => {
- scrollCellIntoView(cellId);
+ scrollCellIntoView(cid);
expect(mockScrollActiveLineIntoView).not.toHaveBeenCalled();
expect(cellElement.scrollIntoView).toHaveBeenCalledWith({
@@ -64,10 +65,10 @@ describe("scrollCellIntoView", () => {
const warnSpy = vi.spyOn(Logger, "warn").mockImplementation(vi.fn());
cellElement.remove();
- scrollCellIntoView(cellId);
+ scrollCellIntoView(cid);
expect(warnSpy).toHaveBeenCalledWith(
- `[CellFocusManager] scrollCellIntoView: element not found: ${cellId}`,
+ `[CellFocusManager] scrollCellIntoView: element not found: ${cid}`,
);
warnSpy.mockRestore();
});
diff --git a/frontend/src/core/cells/__tests__/session.test.ts b/frontend/src/core/cells/__tests__/session.test.ts
index f9a3df59bf..fbd6f98232 100644
--- a/frontend/src/core/cells/__tests__/session.test.ts
+++ b/frontend/src/core/cells/__tests__/session.test.ts
@@ -4,11 +4,12 @@ import type * as api from "@marimo-team/marimo-api";
/* eslint-disable @typescript-eslint/no-explicit-any */
import { beforeEach, describe, expect, it, vi } from "vitest";
import { Mocks } from "@/__mocks__/common";
+import { cellId } from "@/__tests__/branded";
import { parseOutline } from "@/core/dom/outline";
import { MultiColumn, visibleForTesting } from "@/utils/id-tree";
import { invariant } from "@/utils/invariant";
import { Logger } from "@/utils/Logger";
-import { type CellId, SETUP_CELL_ID } from "../ids";
+import { SETUP_CELL_ID } from "../ids";
import { notebookStateFromSession } from "../session";
// Mock dependencies
@@ -22,7 +23,7 @@ type SessionCell = api.Session["NotebookSessionV1"]["cells"][0];
type NotebookCell = api.Notebook["NotebookV1"]["cells"][0];
// Test constants
-const CELL_1 = "cell-1" as CellId;
+const CELL_1 = cellId("cell-1");
describe("notebookStateFromSession", () => {
beforeEach(() => {
@@ -671,9 +672,9 @@ describe("notebookStateFromSession", () => {
);
// Should have correct code and output for each cell
for (const code of ["a", "b", "c", "d", "e", "f"]) {
- const cellId = `cell-${code}` as CellId;
- expect(result.cellData[cellId].code).toBe(code);
- expect(result.cellRuntime[cellId].output).toEqual({
+ const cid = cellId(`cell-${code}`);
+ expect(result.cellData[cid].code).toBe(code);
+ expect(result.cellRuntime[cid].output).toEqual({
channel: "output",
data: `${code.toUpperCase()}!`,
mimetype: "text/plain",
@@ -751,26 +752,26 @@ describe("notebookStateFromSession", () => {
);
// Should have correct code for each cell
- expect(result.cellData["cell-a" as CellId].code).toBe("a");
- expect(result.cellData["cell-c" as CellId].code).toBe("c");
- expect(result.cellData["cell-z" as CellId].code).toBe("z");
- expect(result.cellData["cell-e" as CellId].code).toBe("e");
- expect(result.cellData["cell-g" as CellId].code).toBe("g");
+ expect(result.cellData[cellId("cell-a")].code).toBe("a");
+ expect(result.cellData[cellId("cell-c")].code).toBe("c");
+ expect(result.cellData[cellId("cell-z")].code).toBe("z");
+ expect(result.cellData[cellId("cell-e")].code).toBe("e");
+ expect(result.cellData[cellId("cell-g")].code).toBe("g");
// Should have session outputs for matching cells (a, c, e)
- expect(result.cellRuntime["cell-a" as CellId].output).toEqual({
+ expect(result.cellRuntime[cellId("cell-a")].output).toEqual({
channel: "output",
data: "A!",
mimetype: "text/plain",
timestamp: 0,
});
- expect(result.cellRuntime["cell-c" as CellId].output).toEqual({
+ expect(result.cellRuntime[cellId("cell-c")].output).toEqual({
channel: "output",
data: "C!",
mimetype: "text/plain",
timestamp: 0,
});
- expect(result.cellRuntime["cell-e" as CellId].output).toEqual({
+ expect(result.cellRuntime[cellId("cell-e")].output).toEqual({
channel: "output",
data: "E!",
mimetype: "text/plain",
@@ -778,8 +779,8 @@ describe("notebookStateFromSession", () => {
});
// Should have no output for new cells (z, g) - they get stub session cells
- expect(result.cellRuntime["cell-z" as CellId].output).toBeNull();
- expect(result.cellRuntime["cell-g" as CellId].output).toBeNull();
+ expect(result.cellRuntime[cellId("cell-z")].output).toBeNull();
+ expect(result.cellRuntime[cellId("cell-g")].output).toBeNull();
// Should log warning about different cells
expect(Logger.warn).toHaveBeenCalledWith(
@@ -875,18 +876,18 @@ describe("notebookStateFromSession", () => {
);
// Should have correct code from notebook
- expect(result.cellData["cell-1" as CellId].code).toBe("1 / 0");
- expect(result.cellData["cell-2" as CellId].code).toBe('mo.md("Hello")');
- expect(result.cellData["cell-3" as CellId].code).toBe(
+ expect(result.cellData[cellId("cell-1")].code).toBe("1 / 0");
+ expect(result.cellData[cellId("cell-2")].code).toBe('mo.md("Hello")');
+ expect(result.cellData[cellId("cell-3")].code).toBe(
"x = mo.ui.slider(0, 10)",
);
// cell-1: No matching session cell (hash is null), gets stub session cell
- expect(result.cellRuntime["cell-1" as CellId].output).toBeNull();
- expect(result.cellRuntime["cell-1" as CellId].consoleOutputs).toEqual([]);
+ expect(result.cellRuntime[cellId("cell-1")].output).toBeNull();
+ expect(result.cellRuntime[cellId("cell-1")].consoleOutputs).toEqual([]);
// cell-2: Matches session cell-1 by hash (moMd), gets its output
- expect(result.cellRuntime["cell-2" as CellId].output).toEqual({
+ expect(result.cellRuntime[cellId("cell-2")].output).toEqual({
channel: "output",
data: "Welcome to marimo!",
mimetype: "text/markdown",
@@ -894,7 +895,7 @@ describe("notebookStateFromSession", () => {
});
// cell-3: Matches session cell-2 by hash (slider), gets its output
- expect(result.cellRuntime["cell-3" as CellId].output).toEqual({
+ expect(result.cellRuntime[cellId("cell-3")].output).toEqual({
channel: "output",
data: "",
mimetype: "text/plain",
diff --git a/frontend/src/core/cells/cells.ts b/frontend/src/core/cells/cells.ts
index 4919f10052..8bb90475b9 100644
--- a/frontend/src/core/cells/cells.ts
+++ b/frontend/src/core/cells/cells.ts
@@ -755,7 +755,7 @@ const {
});
},
handleCellMessage: (state, message: CellMessage) => {
- const cellId = message.cell_id as CellId;
+ const cellId = message.cell_id;
const nextState = updateCellRuntimeState({
state,
cellId,
diff --git a/frontend/src/core/cells/ids.ts b/frontend/src/core/cells/ids.ts
index fb6bcb91c6..090c37ce14 100644
--- a/frontend/src/core/cells/ids.ts
+++ b/frontend/src/core/cells/ids.ts
@@ -1,9 +1,9 @@
/* Copyright 2026 Marimo. All rights reserved. */
/* eslint-disable @typescript-eslint/no-redeclare */
+import type { components } from "@marimo-team/marimo-api";
import { OBJECT_ID_ATTR } from "@/core/dom/ui-element-constants";
import { invariant } from "@/utils/invariant";
-import type { TypedString } from "../../utils/typed";
const lowercase = "abcdefghijklmnopqrstuvwxyz";
const uppercase = lowercase.toUpperCase();
@@ -14,9 +14,9 @@ export const SCRATCH_CELL_ID = "__scratch__" as CellId;
export const SETUP_CELL_ID = "setup" as CellId;
/**
- * A typed CellId
+ * A typed CellId — derived from the generated OpenAPI schema.
*/
-export type CellId = TypedString<"CellId">;
+export type CellId = components["schemas"]["CellId"];
export const CellId = {
/**
* Create a new CellId, a random 4 letter string.
@@ -106,9 +106,9 @@ export function findCellId(element: HTMLElement): CellId | null {
}
/**
- * A typed UIElementId
+ * A typed UIElementId — derived from the generated OpenAPI schema.
*/
-export type UIElementId = `${CellId}-${string}`;
+export type UIElementId = components["schemas"]["UIElementId"];
export const UIElementId = {
parse(element: Element): UIElementId | null {
return element.getAttribute(OBJECT_ID_ATTR) as UIElementId | null;
diff --git a/frontend/src/core/cells/logs.ts b/frontend/src/core/cells/logs.ts
index 5569683cfc..d80f007c9d 100644
--- a/frontend/src/core/cells/logs.ts
+++ b/frontend/src/core/cells/logs.ts
@@ -43,7 +43,7 @@ export function getCellLogsForMessage(cell: CellMessage): CellLog[] {
timestamp: output.timestamp || Date.now(),
level: isError ? "stderr" : "stdout",
message: message,
- cellId: cell.cell_id as CellId,
+ cellId: cell.cell_id,
});
break;
}
@@ -66,7 +66,7 @@ export function getCellLogsForMessage(cell: CellMessage): CellLog[] {
cell.output.data.forEach((error) => {
CellLogLogger.log({
level: "stderr",
- cellId: cell.cell_id as CellId,
+ cellId: cell.cell_id,
timestamp: cell.timestamp ?? 0,
message: JSON.stringify(error),
});
diff --git a/frontend/src/core/cells/runs.ts b/frontend/src/core/cells/runs.ts
index 2c6d10643b..395c9b7b6c 100644
--- a/frontend/src/core/cells/runs.ts
+++ b/frontend/src/core/cells/runs.ts
@@ -79,9 +79,9 @@ const {
runId,
cellRuns: new Map([
[
- cellNotification.cell_id as CellId,
+ cellNotification.cell_id,
{
- cellId: cellNotification.cell_id as CellId,
+ cellId: cellNotification.cell_id,
code: code.slice(0, MAX_CODE_LENGTH),
elapsedTime: 0,
status: status,
@@ -111,9 +111,7 @@ const {
// Update existing run
const nextCellRuns = new Map(existingRun.cellRuns);
- const existingCellRun = nextCellRuns.get(
- cellNotification.cell_id as CellId,
- );
+ const existingCellRun = nextCellRuns.get(cellNotification.cell_id);
// Early return if nothing changed
if (
@@ -140,15 +138,15 @@ const {
? timestamp - existingCellRun.startTime
: undefined;
- nextCellRuns.set(cellNotification.cell_id as CellId, {
+ nextCellRuns.set(cellNotification.cell_id, {
...existingCellRun,
startTime,
elapsedTime,
status,
});
} else {
- nextCellRuns.set(cellNotification.cell_id as CellId, {
- cellId: cellNotification.cell_id as CellId,
+ nextCellRuns.set(cellNotification.cell_id, {
+ cellId: cellNotification.cell_id,
code: code.slice(0, MAX_CODE_LENGTH),
elapsedTime: 0,
status: status,
diff --git a/frontend/src/core/codemirror/__tests__/format.test.ts b/frontend/src/core/codemirror/__tests__/format.test.ts
index 2028298873..42a7846b26 100644
--- a/frontend/src/core/codemirror/__tests__/format.test.ts
+++ b/frontend/src/core/codemirror/__tests__/format.test.ts
@@ -6,6 +6,7 @@ import { EditorView } from "@codemirror/view";
import { atom } from "jotai";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { MockRequestClient } from "@/__mocks__/requests";
+import { cellId } from "@/__tests__/branded";
import type { NotebookState } from "@/core/cells/cells";
import { getNotebook } from "@/core/cells/cells";
import type { CellId } from "@/core/cells/ids";
@@ -99,11 +100,11 @@ afterEach(() => {
describe("format", () => {
describe("formatEditorViews", () => {
it("should format code in editor views", async () => {
- const cellId1 = "1" as CellId;
- const cellId2 = "2" as CellId;
+ const cid1 = cellId("1");
+ const cid2 = cellId("2");
const views = {
- [cellId1]: createEditor("import numpy as np", cellId1),
- [cellId2]: createEditor("import pandas as pd", cellId2),
+ [cid1]: createEditor("import numpy as np", cid1),
+ [cid2]: createEditor("import pandas as pd", cid2),
};
const formattedCode1 = "import numpy as np";
@@ -111,8 +112,8 @@ describe("format", () => {
mockRequestClient.sendFormat.mockResolvedValueOnce({
codes: {
- [cellId1]: formattedCode1,
- [cellId2]: formattedCode2,
+ [cid1]: formattedCode1,
+ [cid2]: formattedCode2,
},
});
@@ -122,36 +123,36 @@ describe("format", () => {
expect(mockRequestClient.sendFormat).toHaveBeenCalledWith({
codes: {
- [cellId1]: "import numpy as np",
- [cellId2]: "import pandas as pd",
+ [cid1]: "import numpy as np",
+ [cid2]: "import pandas as pd",
},
lineLength: 88,
});
- expect(views[cellId1].state.doc.toString()).toBe(formattedCode1);
- expect(views[cellId2].state.doc.toString()).toBe(formattedCode2);
+ expect(views[cid1].state.doc.toString()).toBe(formattedCode1);
+ expect(views[cid2].state.doc.toString()).toBe(formattedCode2);
expect(updateCellCode).toHaveBeenCalledWith({
- cellId: cellId1,
+ cellId: cid1,
code: formattedCode1,
formattingChange: true,
});
expect(updateCellCode).toHaveBeenCalledWith({
- cellId: cellId2,
+ cellId: cid2,
code: formattedCode2,
formattingChange: true,
});
});
it("should not update editor if formatted code is same as original", async () => {
- const cellId = "1" as CellId;
+ const cid = cellId("1");
const originalCode = "import numpy as np";
const views = {
- [cellId]: createEditor(originalCode, cellId),
+ [cid]: createEditor(originalCode, cid),
};
mockRequestClient.sendFormat.mockResolvedValueOnce({
codes: {
- [cellId]: originalCode,
+ [cid]: originalCode,
},
});
@@ -159,26 +160,26 @@ describe("format", () => {
await formatEditorViews(views);
- expect(views[cellId].state.doc.toString()).toBe(originalCode);
+ expect(views[cid].state.doc.toString()).toBe(originalCode);
expect(updateCellCode).not.toHaveBeenCalled();
});
});
describe("formatAll", () => {
it("should format all cells in notebook", async () => {
- const cellId1 = "1" as CellId;
- const cellId2 = "2" as CellId;
+ const cid1 = cellId("1");
+ const cid2 = cellId("2");
const views = {
- [cellId1]: createEditor("import numpy as np", cellId1),
- [cellId2]: createEditor("import pandas as pd", cellId2),
+ [cid1]: createEditor("import numpy as np", cid1),
+ [cid2]: createEditor("import pandas as pd", cid2),
};
vi.mocked(getNotebook).mockReturnValueOnce({} as NotebookState);
vi.mocked(notebookCellEditorViews).mockReturnValueOnce(views);
mockRequestClient.sendFormat.mockResolvedValueOnce({
codes: {
- [cellId1]: "import numpy as np",
- [cellId2]: "import pandas as pd",
+ [cid1]: "import numpy as np",
+ [cid2]: "import pandas as pd",
},
});
@@ -188,14 +189,14 @@ describe("format", () => {
expect(mockRequestClient.sendFormat).toHaveBeenCalledWith({
codes: {
- [cellId1]: "import numpy as np",
- [cellId2]: "import pandas as pd",
+ [cid1]: "import numpy as np",
+ [cid2]: "import pandas as pd",
},
lineLength: 88,
});
expect(updateCellCode).toHaveBeenCalledWith({
- cellId: cellId1,
+ cellId: cid1,
code: "import numpy as np",
formattingChange: true,
});
@@ -204,8 +205,8 @@ describe("format", () => {
describe("formatSQL", () => {
it("should format SQL code", async () => {
- const cellId = "1" as CellId;
- const editor = createEditor("SELECT * FROM table WHERE id = 1", cellId);
+ const cid = cellId("1");
+ const editor = createEditor("SELECT * FROM table WHERE id = 1", cid);
switchLanguage(editor, { language: "sql" });
await formatSQL(editor, "duckdb" as ConnectionName);
@@ -220,15 +221,15 @@ describe("format", () => {
id = 1"
`);
expect(updateCellCode).toHaveBeenCalledWith({
- cellId: cellId,
+ cellId: cid,
code: editor.state.doc.toString(),
formattingChange: true,
});
});
it("should not format if language adapter is not SQL", async () => {
- const cellId = "1" as CellId;
- const editor = createEditor("SELECT * FROM table WHERE id = 1", cellId);
+ const cid = cellId("1");
+ const editor = createEditor("SELECT * FROM table WHERE id = 1", cid);
switchLanguage(editor, { language: "python" });
await formatSQL(editor, "duckdb" as ConnectionName);
@@ -242,11 +243,8 @@ describe("format", () => {
});
it("should format SQL code with different dialect", async () => {
- const cellId = "1" as CellId;
- const editor = createEditor(
- "SELECT * FROM `table.dot` WHERE id = 1",
- cellId,
- );
+ const cid = cellId("1");
+ const editor = createEditor("SELECT * FROM `table.dot` WHERE id = 1", cid);
switchLanguage(editor, { language: "sql" });
await formatSQL(editor, "mysql" as ConnectionName); // mysql uses backticks for identifiers
@@ -260,7 +258,7 @@ describe("format", () => {
id = 1"
`);
expect(updateCellCode).toHaveBeenCalledWith({
- cellId: cellId,
+ cellId: cid,
code: editor.state.doc.toString(),
formattingChange: true,
});
diff --git a/frontend/src/core/codemirror/__tests__/setup.test.ts b/frontend/src/core/codemirror/__tests__/setup.test.ts
index 12b712a0de..e7b3b98608 100644
--- a/frontend/src/core/codemirror/__tests__/setup.test.ts
+++ b/frontend/src/core/codemirror/__tests__/setup.test.ts
@@ -3,7 +3,7 @@
import { EditorState, type Extension } from "@codemirror/state";
import { keymap } from "@codemirror/view";
import { describe, expect, test, vi } from "vitest";
-import type { CellId } from "@/core/cells/ids";
+import { cellId } from "@/__tests__/branded";
import { OverridingHotkeyProvider } from "@/core/hotkeys/hotkeys";
import { Objects } from "@/utils/objects";
import type { CodemirrorCellActions } from "../cells/state";
@@ -35,7 +35,7 @@ function namedFunction(name: string) {
function getOpts() {
return {
- cellId: "0" as CellId,
+ cellId: cellId("0"),
showPlaceholder: false,
enableAI: false,
cellActions: {
diff --git a/frontend/src/core/codemirror/cells/__tests__/traceback-decorations.test.ts b/frontend/src/core/codemirror/cells/__tests__/traceback-decorations.test.ts
index 0fc1d068c7..6e9c774323 100644
--- a/frontend/src/core/codemirror/cells/__tests__/traceback-decorations.test.ts
+++ b/frontend/src/core/codemirror/cells/__tests__/traceback-decorations.test.ts
@@ -5,6 +5,7 @@ import { foldCode, foldedRanges, foldGutter } from "@codemirror/language";
import { EditorState } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { afterEach, describe, expect, it } from "vitest";
+import { cellId } from "@/__tests__/branded";
import type { CellId } from "@/core/cells/ids";
import { createMockObservable } from "@/core/state/__mocks__/mocks";
import type { Observable } from "@/core/state/observable";
@@ -48,7 +49,7 @@ describe("traceback-decorations", () => {
describe("unfoldErrorLines", () => {
it("should unfold folded regions containing error lines", () => {
- const cellId = "cell1" as CellId;
+ const cid = cellId("cell1");
const code = `def my_function():
x = 1
y = 2
@@ -60,7 +61,7 @@ result = my_function()`;
const errorsObservable = createMockObservable<
TracebackInfo[] | undefined
>(undefined);
- view = createEditor(code, cellId, errorsObservable);
+ view = createEditor(code, cid, errorsObservable);
// Fold the function body (lines 2-5)
// @ts-expect-error - foldCode accepts position as second arg at runtime
@@ -82,7 +83,7 @@ result = my_function()`;
mockObservable.set([
{
kind: "cell",
- cellId,
+ cellId: cid,
lineNumber: 3,
},
]);
@@ -100,7 +101,7 @@ result = my_function()`;
});
it("should not unfold folded regions when error is outside the region", () => {
- const cellId = "cell1" as CellId;
+ const cid = cellId("cell1");
const code = `def my_function():
x = 1
y = 2
@@ -111,7 +112,7 @@ result = my_function()`;
const errorsObservable = createMockObservable<
TracebackInfo[] | undefined
>(undefined);
- view = createEditor(code, cellId, errorsObservable);
+ view = createEditor(code, cid, errorsObservable);
// Fold the function body (lines 2-4)
// @ts-expect-error - foldCode accepts position as second arg at runtime
@@ -133,7 +134,7 @@ result = my_function()`;
mockObservable.set([
{
kind: "cell",
- cellId,
+ cellId: cid,
lineNumber: 6,
},
]);
@@ -151,8 +152,8 @@ result = my_function()`;
});
it("should not unfold regions for errors in different cells", () => {
- const cellId1 = "cell1" as CellId;
- const cellId2 = "cell2" as CellId;
+ const cellId1 = cellId("cell1");
+ const cellId2 = cellId("cell2");
const code = `def my_function():
x = 1
y = 2
@@ -201,7 +202,7 @@ result = my_function()`;
});
it("should handle multiple errors in the same folded region", () => {
- const cellId = "cell1" as CellId;
+ const cid = cellId("cell1");
const code = `def my_function():
x = 1
y = 2
@@ -213,7 +214,7 @@ result = my_function()`;
const errorsObservable = createMockObservable<
TracebackInfo[] | undefined
>(undefined);
- view = createEditor(code, cellId, errorsObservable);
+ view = createEditor(code, cid, errorsObservable);
// Fold the function body
// @ts-expect-error - foldCode accepts position as second arg at runtime
@@ -235,12 +236,12 @@ result = my_function()`;
mockObservable.set([
{
kind: "cell",
- cellId,
+ cellId: cid,
lineNumber: 2, // Inside folded region
},
{
kind: "cell",
- cellId,
+ cellId: cid,
lineNumber: 4, // Also inside folded region
},
]);
@@ -258,7 +259,7 @@ result = my_function()`;
});
it("should handle invalid line numbers gracefully in unfoldErrorLines", () => {
- const cellId = "cell1" as CellId;
+ const cid = cellId("cell1");
const code = `def my_function():
x = 1
return x`;
@@ -266,7 +267,7 @@ result = my_function()`;
const errorsObservable = createMockObservable<
TracebackInfo[] | undefined
>(undefined);
- view = createEditor(code, cellId, errorsObservable);
+ view = createEditor(code, cid, errorsObservable);
// Fold the function
// @ts-expect-error - foldCode accepts position as second arg at runtime
@@ -284,7 +285,7 @@ result = my_function()`;
mockObservable.set([
{
kind: "cell",
- cellId,
+ cellId: cid,
lineNumber: 2, // Valid line number inside folded region
},
]);
@@ -310,7 +311,7 @@ result = my_function()`;
});
it("should handle file errors (not cell errors)", () => {
- const cellId = "cell1" as CellId;
+ const cid = cellId("cell1");
const code = `def my_function():
x = 1
return x`;
@@ -318,7 +319,7 @@ result = my_function()`;
const errorsObservable = createMockObservable<
TracebackInfo[] | undefined
>(undefined);
- view = createEditor(code, cellId, errorsObservable);
+ view = createEditor(code, cid, errorsObservable);
// Fold the function
// @ts-expect-error - foldCode accepts position as second arg at runtime
@@ -350,7 +351,7 @@ result = my_function()`;
});
it("should handle empty or undefined errors", () => {
- const cellId = "cell1" as CellId;
+ const cid = cellId("cell1");
const code = `def my_function():
x = 1
return x`;
@@ -358,7 +359,7 @@ result = my_function()`;
const errorsObservable = createMockObservable<
TracebackInfo[] | undefined
>(undefined);
- view = createEditor(code, cellId, errorsObservable);
+ view = createEditor(code, cid, errorsObservable);
// Fold the function
// @ts-expect-error - foldCode accepts position as second arg at runtime
@@ -392,7 +393,7 @@ result = my_function()`;
});
it("should handle invalid line numbers gracefully", () => {
- const cellId = "cell1" as CellId;
+ const cid = cellId("cell1");
const code = `def my_function():
x = 1
return x`;
@@ -400,7 +401,7 @@ result = my_function()`;
const errorsObservable = createMockObservable<
TracebackInfo[] | undefined
>(undefined);
- view = createEditor(code, cellId, errorsObservable);
+ view = createEditor(code, cid, errorsObservable);
// Fold the function
// @ts-expect-error - foldCode accepts position as second arg at runtime
@@ -415,7 +416,7 @@ result = my_function()`;
mockObservable.set([
{
kind: "cell",
- cellId,
+ cellId: cid,
lineNumber: maxLine + 100, // Invalid line number
},
]);
@@ -438,7 +439,7 @@ result = my_function()`;
});
it("should unfold nested structures when error is inside", () => {
- const cellId = "cell1" as CellId;
+ const cid = cellId("cell1");
const code = `def outer_function():
def inner_function():
x = 1
@@ -452,7 +453,7 @@ final = outer_function()`;
const errorsObservable = createMockObservable<
TracebackInfo[] | undefined
>(undefined);
- view = createEditor(code, cellId, errorsObservable);
+ view = createEditor(code, cid, errorsObservable);
// Fold the outer function (which contains the inner function)
// @ts-expect-error - foldCode accepts position as second arg at runtime
@@ -474,7 +475,7 @@ final = outer_function()`;
mockObservable.set([
{
kind: "cell",
- cellId,
+ cellId: cid,
lineNumber: 4,
},
]);
@@ -492,7 +493,7 @@ final = outer_function()`;
});
it("should handle errors being cleared and then re-added", () => {
- const cellId = "cell1" as CellId;
+ const cid = cellId("cell1");
const code = `def my_function():
x = 1
y = 2
@@ -503,7 +504,7 @@ result = my_function()`;
const errorsObservable = createMockObservable<
TracebackInfo[] | undefined
>(undefined);
- view = createEditor(code, cellId, errorsObservable);
+ view = createEditor(code, cid, errorsObservable);
// Fold the function
// @ts-expect-error - foldCode accepts position as second arg at runtime
@@ -517,7 +518,7 @@ result = my_function()`;
mockObservable.set([
{
kind: "cell",
- cellId,
+ cellId: cid,
lineNumber: 2,
},
]);
@@ -545,7 +546,7 @@ result = my_function()`;
mockObservable.set([
{
kind: "cell",
- cellId,
+ cellId: cid,
lineNumber: 3,
},
]);
@@ -562,7 +563,7 @@ result = my_function()`;
});
it("should unfold immediately when errors are set", () => {
- const cellId = "cell1" as CellId;
+ const cid = cellId("cell1");
const code = `def my_function():
x = 1
y = 2
@@ -573,7 +574,7 @@ result = my_function()`;
const errorsObservable = createMockObservable<
TracebackInfo[] | undefined
>(undefined);
- view = createEditor(code, cellId, errorsObservable);
+ view = createEditor(code, cid, errorsObservable);
// Fold the function
// @ts-expect-error - foldCode accepts position as second arg at runtime
@@ -595,7 +596,7 @@ result = my_function()`;
mockObservable.set([
{
kind: "cell",
- cellId,
+ cellId: cid,
lineNumber: 2,
},
]);
diff --git a/frontend/src/core/codemirror/copilot/__tests__/getCodes.test.ts b/frontend/src/core/codemirror/copilot/__tests__/getCodes.test.ts
index 67fd9d7869..deedd2bb59 100644
--- a/frontend/src/core/codemirror/copilot/__tests__/getCodes.test.ts
+++ b/frontend/src/core/codemirror/copilot/__tests__/getCodes.test.ts
@@ -3,28 +3,27 @@
import { EditorState } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { describe, expect, it } from "vitest";
+import { cellId, variableName } from "@/__tests__/branded";
import { initialNotebookState, notebookAtom } from "@/core/cells/cells";
-import type { CellId } from "@/core/cells/ids";
import { OverridingHotkeyProvider } from "@/core/hotkeys/hotkeys";
import { store } from "@/core/state/jotai";
import { variablesAtom } from "@/core/variables/state";
-import type { VariableName, Variables } from "@/core/variables/types";
import { MultiColumn } from "@/utils/id-tree";
import { cellConfigExtension } from "../../config/extension";
import { adaptiveLanguageConfiguration } from "../../language/extension";
import { getCodes, getTopologicalCellIds } from "../getCodes";
const Cells = {
- cell1: "cell1" as CellId,
- cell2: "cell2" as CellId,
- cell3: "cell3" as CellId,
- cell4: "cell4" as CellId,
+ cell1: cellId("cell1"),
+ cell2: cellId("cell2"),
+ cell3: cellId("cell3"),
+ cell4: cellId("cell4"),
};
const Variables = {
- var1: "var1" as VariableName,
- var2: "var2" as VariableName,
- var3: "var3" as VariableName,
+ var1: variableName("var1"),
+ var2: variableName("var2"),
+ var3: variableName("var3"),
};
function createMockEditorView(code: string) {
@@ -33,7 +32,7 @@ function createMockEditorView(code: string) {
doc: code,
extensions: [
adaptiveLanguageConfiguration({
- cellId: "cell1" as CellId,
+ cellId: cellId("cell1"),
completionConfig: {
copilot: false,
activate_on_typing: true,
@@ -45,7 +44,7 @@ function createMockEditorView(code: string) {
lspConfig: {},
}),
cellConfigExtension({
- cellId: "cell1" as CellId,
+ cellId: cellId("cell1"),
completionConfig: {
copilot: false,
activate_on_typing: true,
@@ -71,7 +70,7 @@ describe("getTopologicalCellIds", () => {
it("should return topologically sorted cell IDs", () => {
// Setup mock data
const cellIds = [Cells.cell1, Cells.cell2, Cells.cell3, Cells.cell4];
- const variables: Variables = {
+ const variables = {
[Variables.var1]: {
name: Variables.var1,
declaredBy: [Cells.cell1],
@@ -125,7 +124,7 @@ describe("getTopologicalCellIds", () => {
it("should put new cells (with no dependencies) at the end", () => {
const cellIds = [Cells.cell1, Cells.cell2, Cells.cell3, Cells.cell4];
- const variables: Variables = {
+ const variables = {
[Variables.var1]: {
name: Variables.var1,
declaredBy: [Cells.cell2],
diff --git a/frontend/src/core/codemirror/language/__tests__/utils.test.ts b/frontend/src/core/codemirror/language/__tests__/utils.test.ts
index 7aae643cf0..f88d21957b 100644
--- a/frontend/src/core/codemirror/language/__tests__/utils.test.ts
+++ b/frontend/src/core/codemirror/language/__tests__/utils.test.ts
@@ -3,7 +3,7 @@
import { EditorState } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { describe, expect, it } from "vitest";
-import type { CellId } from "@/core/cells/ids";
+import { cellId } from "@/__tests__/branded";
import { OverridingHotkeyProvider } from "@/core/hotkeys/hotkeys";
import { cellConfigExtension } from "../../config/extension";
import { adaptiveLanguageConfiguration, switchLanguage } from "../extension";
@@ -26,12 +26,12 @@ function createEditor(doc: string) {
codeium_api_key: null,
},
hotkeys: new OverridingHotkeyProvider({}),
- cellId: "cell1" as CellId,
+ cellId: cellId("cell1"),
placeholderType: "marimo-import",
lspConfig: {},
}),
cellConfigExtension({
- cellId: "cell1" as CellId,
+ cellId: cellId("cell1"),
completionConfig: {
activate_on_typing: true,
signature_hint_on_typing: false,
diff --git a/frontend/src/core/codemirror/language/embedded/__tests__/embedded-python.test.ts b/frontend/src/core/codemirror/language/embedded/__tests__/embedded-python.test.ts
index 30a045697d..c9bf44b495 100644
--- a/frontend/src/core/codemirror/language/embedded/__tests__/embedded-python.test.ts
+++ b/frontend/src/core/codemirror/language/embedded/__tests__/embedded-python.test.ts
@@ -5,10 +5,9 @@ import { python } from "@codemirror/lang-python";
import { EditorState } from "@codemirror/state";
import type { InlineContext } from "@lezer/markdown";
import { beforeEach, describe, expect, it } from "vitest";
-import type { CellId } from "@/core/cells/ids";
+import { cellId, variableName } from "@/__tests__/branded";
import { store } from "@/core/state/jotai";
import { variablesAtom } from "@/core/variables/state";
-import type { VariableName, Variables } from "@/core/variables/types";
import { parsePython, variableCompletionSource } from "../embedded-python";
const IS_ACTIVE = () => true;
@@ -51,16 +50,16 @@ describe("parsePython", () => {
describe("variableCompletionSource", () => {
beforeEach(() => {
- const mockCellId = "cell-1" as CellId;
- const mockVariables: Variables = {
- ["var1" as VariableName]: {
- name: "var1" as VariableName,
+ const mockCellId = cellId("cell-1");
+ const mockVariables = {
+ [variableName("var1")]: {
+ name: variableName("var1"),
dataType: "int",
declaredBy: [mockCellId],
usedBy: [mockCellId],
},
- ["var2" as VariableName]: {
- name: "var2" as VariableName,
+ [variableName("var2")]: {
+ name: variableName("var2"),
dataType: "str",
declaredBy: [mockCellId],
usedBy: [mockCellId],
diff --git a/frontend/src/core/codemirror/lsp/__tests__/notebook-lsp.test.ts b/frontend/src/core/codemirror/lsp/__tests__/notebook-lsp.test.ts
index 1dd9d55991..4a131a9f3f 100644
--- a/frontend/src/core/codemirror/lsp/__tests__/notebook-lsp.test.ts
+++ b/frontend/src/core/codemirror/lsp/__tests__/notebook-lsp.test.ts
@@ -8,6 +8,7 @@ import {
} from "@marimo-team/codemirror-languageserver";
import { beforeEach, describe, expect, it, type Mocked, vi } from "vitest";
import * as LSP from "vscode-languageserver-protocol";
+import { cellId } from "@/__tests__/branded";
import type { CellId } from "@/core/cells/ids";
import { store } from "@/core/state/jotai";
import { topologicalCodesAtom } from "../../copilot/getCodes";
@@ -19,9 +20,9 @@ import { NotebookLanguageServerClient } from "../notebook-lsp";
import { CellDocumentUri, type ILanguageServerClient } from "../types";
const Cells = {
- cell1: "cell1" as CellId,
- cell2: "cell2" as CellId,
- cell3: "cell3" as CellId,
+ cell1: cellId("cell1"),
+ cell2: cellId("cell2"),
+ cell3: cellId("cell3"),
};
describe("createNotebookLens", () => {
diff --git a/frontend/src/core/codemirror/reactive-references/__tests__/analyzer.test.ts b/frontend/src/core/codemirror/reactive-references/__tests__/analyzer.test.ts
index a3974b6e1c..d801cd8165 100644
--- a/frontend/src/core/codemirror/reactive-references/__tests__/analyzer.test.ts
+++ b/frontend/src/core/codemirror/reactive-references/__tests__/analyzer.test.ts
@@ -3,8 +3,8 @@
import { python } from "@codemirror/lang-python";
import { EditorState } from "@codemirror/state";
import { describe, expect, test } from "vitest";
-import type { CellId } from "@/core/cells/ids";
-import type { VariableName, Variables } from "@/core/variables/types";
+import { cellId, variableName } from "@/__tests__/branded";
+import type { Variables } from "@/core/variables/types";
import { findReactiveVariables, type ReactiveVariableRange } from "../analyzer";
describe("findReactiveVariables - Lexical Scoping", () => {
@@ -1199,16 +1199,17 @@ class Foo:
function runHighlight(variableNames: string[], code: string): string {
const variables: Variables = {};
for (const name of variableNames) {
- variables[name as VariableName] = {
- name: name as VariableName,
- declaredBy: ["other-cell" as CellId],
+ const varName = variableName(name);
+ variables[varName] = {
+ name: varName,
+ declaredBy: [cellId("other-cell")],
usedBy: [],
value: "test-value",
dataType: "str",
};
}
const ranges = findReactiveVariables({
- cellId: "current-cell" as CellId,
+ cellId: cellId("current-cell"),
state: EditorState.create({
doc: code,
extensions: [python()],
diff --git a/frontend/src/core/codemirror/reactive-references/analyzer.ts b/frontend/src/core/codemirror/reactive-references/analyzer.ts
index 14679806be..64aecb2a83 100644
--- a/frontend/src/core/codemirror/reactive-references/analyzer.ts
+++ b/frontend/src/core/codemirror/reactive-references/analyzer.ts
@@ -3,7 +3,7 @@
import { syntaxTree } from "@codemirror/language";
import type { EditorState } from "@codemirror/state";
import type { SyntaxNode, Tree, TreeCursor } from "@lezer/common";
-import type { CellId } from "@/core/cells/ids";
+import { type CellId, SETUP_CELL_ID } from "@/core/cells/ids";
import type { VariableName, Variables } from "@/core/variables/types";
export interface ReactiveVariableRange {
@@ -52,7 +52,7 @@ export function findReactiveVariables(options: {
const variable = options.variables[name as VariableName];
return (
variable.dataType !== "module" &&
- !variable.declaredBy.includes("setup" as CellId) &&
+ !variable.declaredBy.includes(SETUP_CELL_ID) &&
!variable.declaredBy.includes(options.cellId)
);
}),
diff --git a/frontend/src/core/datasets/__tests__/data-source.test.ts b/frontend/src/core/datasets/__tests__/data-source.test.ts
index a5ff8dadb0..87b2aaff92 100644
--- a/frontend/src/core/datasets/__tests__/data-source.test.ts
+++ b/frontend/src/core/datasets/__tests__/data-source.test.ts
@@ -1,5 +1,6 @@
/* Copyright 2026 Marimo. All rights reserved. */
import { beforeEach, describe, expect, it } from "vitest";
+import { variableName } from "@/__tests__/branded";
import type { DataTable } from "@/core/kernel/messages";
import type { VariableName } from "@/core/variables/types";
import {
@@ -182,7 +183,7 @@ describe("filtering data sources", () => {
});
it("keeps matching variables and internal engines", () => {
- const filtered = filterDataSources(["conn1" as unknown as VariableName]);
+ const filtered = filterDataSources([variableName("conn1")]);
expect(filtered.connectionsMap.size).toBe(defaultConnSize + 1);
expect(filtered.connectionsMap.has("conn1" as ConnectionName)).toBe(true);
for (const engine of INTERNAL_SQL_ENGINES) {
@@ -191,16 +192,14 @@ describe("filtering data sources", () => {
});
it("filters out non-matching variables", () => {
- const filtered = filterDataSources([
- "non_existent" as unknown as VariableName,
- ]);
+ const filtered = filterDataSources([variableName("non_existent")]);
expect(filtered.connectionsMap.size).toBe(defaultConnSize);
});
it("handles mix of matching and non-matching variables", () => {
const filtered = filterDataSources([
- "conn1" as unknown as VariableName,
- "non_existent" as unknown as VariableName,
+ variableName("conn1"),
+ variableName("non_existent"),
]);
expect(filtered.connectionsMap.size).toBe(defaultConnSize + 1);
expect(filtered.connectionsMap.has("conn1" as ConnectionName)).toBe(true);
diff --git a/frontend/src/core/datasets/state.ts b/frontend/src/core/datasets/state.ts
index 94a16df9db..547ef32e6e 100644
--- a/frontend/src/core/datasets/state.ts
+++ b/frontend/src/core/datasets/state.ts
@@ -83,7 +83,7 @@ const {
if (!table.variable_name) {
return true;
}
- return names.has(table.variable_name as VariableName);
+ return names.has(table.variable_name);
});
return { ...state, tables };
},
diff --git a/frontend/src/core/errors/__tests__/errors.test.ts b/frontend/src/core/errors/__tests__/errors.test.ts
index 8edd7dc377..0fbc5eda76 100644
--- a/frontend/src/core/errors/__tests__/errors.test.ts
+++ b/frontend/src/core/errors/__tests__/errors.test.ts
@@ -1,5 +1,6 @@
/* Copyright 2026 Marimo. All rights reserved. */
import { describe, expect, it } from "vitest";
+import { cellId } from "@/__tests__/branded";
import type { MarimoError } from "@/core/kernel/messages";
import { getAutoFixes, getImportCode } from "../errors";
@@ -25,7 +26,7 @@ describe("getAutoFixes", () => {
const error: MarimoError = {
type: "multiple-defs",
name: "foo",
- cells: ["foo"],
+ cells: [cellId("foo")],
};
const fixes = getAutoFixes(error, opts);
diff --git a/frontend/src/core/export/__tests__/hooks.test.ts b/frontend/src/core/export/__tests__/hooks.test.ts
index b12b4fb888..2f6d2dea89 100644
--- a/frontend/src/core/export/__tests__/hooks.test.ts
+++ b/frontend/src/core/export/__tests__/hooks.test.ts
@@ -6,6 +6,7 @@ import type { ReactNode } from "react";
import * as React from "react";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { MockModules, Mocks } from "@/__mocks__/common";
+import { cellId } from "@/__tests__/branded";
import type { CellId } from "@/core/cells/ids";
import { CellOutputId } from "@/core/cells/ids";
import type { CellRuntimeState } from "@/core/cells/types";
@@ -63,7 +64,7 @@ describe("useEnrichCellOutputs", () => {
): Record<CellId, CellRuntimeState> => {
return Object.fromEntries(
Object.entries(cells).map(([cellId, cell]) => [
- cellId as CellId,
+ cellId,
{
output: cell.output || null,
status: cell.status || "idle",
@@ -106,7 +107,7 @@ describe("useEnrichCellOutputs", () => {
});
it("should capture screenshots for cells with text/html output", async () => {
- const cellId = "cell-1" as CellId;
+ const cid = cellId("cell-1");
const mockElement = document.createElement("div");
const mockDataUrl = "data:image/png;base64,mockImageData";
@@ -116,7 +117,7 @@ describe("useEnrichCellOutputs", () => {
setCellsRuntime(
createMockCellRuntimes({
- [cellId]: {
+ [cid]: {
output: {
channel: "output",
mimetype: "text/html",
@@ -133,7 +134,7 @@ describe("useEnrichCellOutputs", () => {
const output = await takeScreenshots({ progress });
expect(document.getElementById).toHaveBeenCalledWith(
- CellOutputId.create(cellId),
+ CellOutputId.create(cid),
);
expect(toPng).toHaveBeenCalledWith(
mockElement,
@@ -143,12 +144,12 @@ describe("useEnrichCellOutputs", () => {
}),
);
expect(output).toEqual({
- [cellId]: ["image/png", mockDataUrl],
+ [cid]: ["image/png", mockDataUrl],
});
});
it("should skip cells where output has not changed", async () => {
- const cellId = "cell-1" as CellId;
+ const cid = cellId("cell-1");
const mockElement = document.createElement("div");
const mockDataUrl = "data:image/png;base64,mockImageData";
const htmlData = "<div>Chart</div>";
@@ -158,7 +159,7 @@ describe("useEnrichCellOutputs", () => {
setCellsRuntime(
createMockCellRuntimes({
- [cellId]: {
+ [cid]: {
output: {
channel: "output",
mimetype: "text/html",
@@ -176,7 +177,7 @@ describe("useEnrichCellOutputs", () => {
// First call - should capture
let takeScreenshots = result.current;
let output = await takeScreenshots({ progress });
- expect(output).toEqual({ [cellId]: ["image/png", mockDataUrl] });
+ expect(output).toEqual({ [cid]: ["image/png", mockDataUrl] });
expect(toPng).toHaveBeenCalledTimes(1);
// Rerender to get updated atom state
@@ -190,7 +191,7 @@ describe("useEnrichCellOutputs", () => {
});
it("should handle screenshot errors gracefully", async () => {
- const cellId = "cell-1" as CellId;
+ const cid = cellId("cell-1");
const mockElement = document.createElement("div");
const error = new Error("Screenshot failed");
@@ -199,7 +200,7 @@ describe("useEnrichCellOutputs", () => {
setCellsRuntime(
createMockCellRuntimes({
- [cellId]: {
+ [cid]: {
output: {
channel: "output",
mimetype: "text/html",
@@ -217,13 +218,13 @@ describe("useEnrichCellOutputs", () => {
expect(output).toEqual({}); // Failed screenshot should be filtered out
expect(Logger.error).toHaveBeenCalledWith(
- `Error screenshotting cell ${cellId}:`,
+ `Error screenshotting cell ${cid}:`,
error,
);
});
it("should retry failed screenshots on next call", async () => {
- const cellId = "cell-1" as CellId;
+ const cid = cellId("cell-1");
const mockElement = document.createElement("div");
const error = new Error("Screenshot failed");
const mockDataUrl = "data:image/png;base64,retrySuccess";
@@ -236,7 +237,7 @@ describe("useEnrichCellOutputs", () => {
setCellsRuntime(
createMockCellRuntimes({
- [cellId]: {
+ [cid]: {
output: {
channel: "output",
mimetype: "text/html",
@@ -262,18 +263,18 @@ describe("useEnrichCellOutputs", () => {
// Second call - should retry since the first one failed
takeScreenshots = result.current;
output = await takeScreenshots({ progress });
- expect(output).toEqual({ [cellId]: ["image/png", mockDataUrl] });
+ expect(output).toEqual({ [cid]: ["image/png", mockDataUrl] });
expect(toPng).toHaveBeenCalledTimes(2);
});
it("should handle missing DOM elements", async () => {
- const cellId = "cell-1" as CellId;
+ const cid = cellId("cell-1");
vi.spyOn(document, "getElementById").mockReturnValue(null);
setCellsRuntime(
createMockCellRuntimes({
- [cellId]: {
+ [cid]: {
output: {
channel: "output",
mimetype: "text/html",
@@ -291,14 +292,14 @@ describe("useEnrichCellOutputs", () => {
expect(output).toEqual({});
expect(Logger.error).toHaveBeenCalledWith(
- `Output element not found for cell ${cellId}`,
+ `Output element not found for cell ${cid}`,
);
expect(toPng).not.toHaveBeenCalled();
});
it("should process multiple cells in parallel", async () => {
- const cell1 = "cell-1" as CellId;
- const cell2 = "cell-2" as CellId;
+ const cell1 = "cell-1";
+ const cell2 = "cell-2";
const mockElement1 = document.createElement("div");
const mockElement2 = document.createElement("div");
const mockDataUrl1 = "data:image/png;base64,image1";
@@ -347,8 +348,8 @@ describe("useEnrichCellOutputs", () => {
it("should filter out null results from failed screenshots", async () => {
// Setup: one successful, one failed screenshot
- const cell1 = "cell-1" as CellId;
- const cell2 = "cell-2" as CellId;
+ const cell1 = "cell-1";
+ const cell2 = "cell-2";
const mockElement1 = document.createElement("div");
const mockDataUrl = "data:image/png;base64,image1";
@@ -394,7 +395,7 @@ describe("useEnrichCellOutputs", () => {
});
it("should only capture screenshots for cells with changed output", async () => {
- const cellId = "cell-1" as CellId;
+ const cid = cellId("cell-1");
const mockElement = document.createElement("div");
const mockDataUrl1 = "data:image/png;base64,image1";
const mockDataUrl2 = "data:image/png;base64,image2";
@@ -407,7 +408,7 @@ describe("useEnrichCellOutputs", () => {
// First call - cell should be captured
setCellsRuntime(
createMockCellRuntimes({
- [cellId]: {
+ [cid]: {
output: {
channel: "output",
mimetype: "text/html",
@@ -425,7 +426,7 @@ describe("useEnrichCellOutputs", () => {
// First screenshot
let takeScreenshots = result.current;
let output = await takeScreenshots({ progress });
- expect(output).toEqual({ [cellId]: ["image/png", mockDataUrl1] });
+ expect(output).toEqual({ [cid]: ["image/png", mockDataUrl1] });
// Second call - same output, should not be captured
rerender();
@@ -436,7 +437,7 @@ describe("useEnrichCellOutputs", () => {
// Third call - output changed, should be captured
setCellsRuntime(
createMockCellRuntimes({
- [cellId]: {
+ [cid]: {
output: {
channel: "output",
mimetype: "text/html",
@@ -450,7 +451,7 @@ describe("useEnrichCellOutputs", () => {
rerender();
takeScreenshots = result.current;
output = await takeScreenshots({ progress });
- expect(output).toEqual({ [cellId]: ["image/png", mockDataUrl2] });
+ expect(output).toEqual({ [cid]: ["image/png", mockDataUrl2] });
expect(toPng).toHaveBeenCalledTimes(2);
});
@@ -523,7 +524,7 @@ describe("useEnrichCellOutputs", () => {
it("should return correctly formatted result with CellId and tuple", async () => {
// Expected format: Record<CellId, ["image/png", string]>
- const cellId = "test-cell" as CellId;
+ const cid = cellId("test-cell");
const mockElement = document.createElement("div");
const mockDataUrl = "data:image/png;base64,testData";
@@ -532,7 +533,7 @@ describe("useEnrichCellOutputs", () => {
setCellsRuntime(
createMockCellRuntimes({
- [cellId]: {
+ [cid]: {
output: {
channel: "output",
mimetype: "text/html",
@@ -549,8 +550,8 @@ describe("useEnrichCellOutputs", () => {
const output = await takeScreenshots({ progress });
// Verify the exact return type structure
- expect(output).toHaveProperty(cellId);
- const cellOutput = output[cellId];
+ expect(output).toHaveProperty(cid);
+ const cellOutput = output[cid];
expect(cellOutput).toBeDefined();
expect(Array.isArray(cellOutput)).toBe(true);
if (cellOutput) {
@@ -566,9 +567,9 @@ describe("updateCellOutputsWithScreenshots", () => {
});
it("should call updateCellOutputs when there are screenshots", async () => {
- const cellId = "cell-1" as CellId;
+ const cid = cellId("cell-1");
const mockScreenshots = {
- [cellId]: ["image/png", "data:image/png;base64,test"] as [
+ [cid]: ["image/png", "data:image/png;base64,test"] as [
"image/png",
string,
],
@@ -603,8 +604,8 @@ describe("updateCellOutputsWithScreenshots", () => {
});
it("should handle multiple cell screenshots", async () => {
- const cell1 = "cell-1" as CellId;
- const cell2 = "cell-2" as CellId;
+ const cell1 = "cell-1";
+ const cell2 = "cell-2";
const mockScreenshots = {
[cell1]: ["image/png", "data:image/png;base64,image1"] as [
"image/png",
@@ -654,9 +655,9 @@ describe("updateCellOutputsWithScreenshots", () => {
});
it("should catch errors from updateCellOutputs and show toast", async () => {
- const cellId = "cell-1" as CellId;
+ const cid = cellId("cell-1");
const mockScreenshots = {
- [cellId]: ["image/png", "data:image/png;base64,test"] as [
+ [cid]: ["image/png", "data:image/png;base64,test"] as [
"image/png",
string,
],
diff --git a/frontend/src/core/islands/main.ts b/frontend/src/core/islands/main.ts
index 1729cd2f8b..d8c2b92550 100644
--- a/frontend/src/core/islands/main.ts
+++ b/frontend/src/core/islands/main.ts
@@ -28,7 +28,6 @@ import {
notebookAtom,
notebookReducer,
} from "../cells/cells";
-import type { UIElementId } from "../cells/ids";
import { defineCustomElement } from "../dom/defineCustomElement";
import { MarimoValueInputEvent } from "../dom/events";
import { UI_ELEMENT_REGISTRY } from "../dom/uiregistry";
@@ -41,7 +40,6 @@ import {
import { queryParamHandlers } from "../kernel/queryParamHandlers";
import { RuntimeState } from "../kernel/RuntimeState";
import { initialModeAtom } from "../mode";
-import type { RequestId } from "../network/DeferredRequestRegistry";
import { requestClientAtom } from "../network/requests";
import { store } from "../state/jotai";
import { IslandsPyodideBridge } from "./bridge";
@@ -153,7 +151,7 @@ export async function initialize() {
return;
case "send-ui-element-message":
UI_ELEMENT_REGISTRY.broadcastMessage(
- msg.data.ui_element as UIElementId,
+ msg.data.ui_element,
msg.data.message,
safeExtractSetUIElementMessageBuffers(msg.data),
);
@@ -163,10 +161,7 @@ export async function initialize() {
handleRemoveUIElements(msg.data);
return;
case "function-call-result":
- FUNCTIONS_REGISTRY.resolve(
- msg.data.function_call_id as RequestId,
- msg.data,
- );
+ FUNCTIONS_REGISTRY.resolve(msg.data.function_call_id, msg.data);
return;
case "cell-op":
handleCellNotificationeration(msg.data, actions.handleCellMessage);
diff --git a/frontend/src/core/kernel/__tests__/handlers.test.ts b/frontend/src/core/kernel/__tests__/handlers.test.ts
index a43e70d8e6..7048cfa2da 100644
--- a/frontend/src/core/kernel/__tests__/handlers.test.ts
+++ b/frontend/src/core/kernel/__tests__/handlers.test.ts
@@ -1,5 +1,6 @@
/* Copyright 2026 Marimo. All rights reserved. */
import { describe, expect, it, vi } from "vitest";
+import { cellId } from "@/__tests__/branded";
import { buildCellData, buildLayoutState } from "../handlers";
import type { NotificationMessageData } from "../messages";
import { queryParamHandlers } from "../queryParamHandlers";
@@ -65,7 +66,7 @@ describe("queryParamHandlers", () => {
describe("buildCellData", () => {
it("should build cell data from kernel-ready data", () => {
const kernelReadyData: NotificationMessageData<"kernel-ready"> = {
- cell_ids: ["cell1", "cell2"],
+ cell_ids: [cellId("cell1"), cellId("cell2")],
codes: ["x = 1", "y = 2"],
names: ["__", "__"],
configs: [
@@ -127,7 +128,7 @@ describe("buildCellData", () => {
it("should mark cells as edited when code differs from last executed code", () => {
const kernelReadyData: NotificationMessageData<"kernel-ready"> = {
- cell_ids: ["cell1", "cell2"],
+ cell_ids: [cellId("cell1"), cellId("cell2")],
codes: ["x = 1", "y = 3"],
names: ["__", "__"],
configs: [
@@ -201,7 +202,7 @@ describe("buildCellData", () => {
describe("buildLayoutState", () => {
it("should build default layout state when no layout is provided", () => {
const kernelReadyData: NotificationMessageData<"kernel-ready"> = {
- cell_ids: ["cell1"],
+ cell_ids: [cellId("cell1")],
codes: ["x = 1"],
names: ["__"],
configs: [{ disabled: false, hide_code: false }],
@@ -243,7 +244,7 @@ describe("buildLayoutState", () => {
it("should build layout state with vertical layout", () => {
const kernelReadyData: NotificationMessageData<"kernel-ready"> = {
- cell_ids: ["cell1", "cell2"],
+ cell_ids: [cellId("cell1"), cellId("cell2")],
codes: ["x = 1", "y = 2"],
names: ["__", "__"],
configs: [
diff --git a/frontend/src/core/kernel/handlers.ts b/frontend/src/core/kernel/handlers.ts
index 354b9bd965..04bc225df5 100644
--- a/frontend/src/core/kernel/handlers.ts
+++ b/frontend/src/core/kernel/handlers.ts
@@ -3,7 +3,7 @@ import { deserializeLayout } from "@/components/editor/renderers/plugins";
import type { LayoutType } from "@/components/editor/renderers/types";
import { Logger } from "@/utils/Logger";
import { Objects } from "@/utils/objects";
-import type { CellId, UIElementId } from "../cells/ids";
+import type { UIElementId } from "../cells/ids";
import { type CellData, createCell } from "../cells/types";
import { type AppConfig, AppConfigSchema } from "../config/config-schema";
import { UI_ELEMENT_REGISTRY } from "../dom/uiregistry";
@@ -47,7 +47,7 @@ export function buildCellData(data: KernelReadyData): CellData[] {
const edited = lastCodeRun ? lastCodeRun !== code : false;
return createCell({
- id: cellId as CellId,
+ id: cellId,
code,
edited,
name: names[i],
@@ -160,7 +160,10 @@ export function handleKernelReady(
// If resumed, restore UI element values from kernel and we're done
if (resumed) {
for (const [objectId, value] of Objects.entries(ui_values || {})) {
- UI_ELEMENT_REGISTRY.set(objectId as UIElementId, value);
+ // @ts-expect-error - TODO: We need to fix the types for KernelReadyNotification["ui_values"]
+ // It is currently typed as Record<string, any> and should be Record<UIElementId, unknown>
+ const uiObjectId: UIElementId = objectId;
+ UI_ELEMENT_REGISTRY.set(uiObjectId, value);
}
return;
}
@@ -196,7 +199,7 @@ export function handleRemoveUIElements(
// This removes the element from the registry to (1) clean-up
// memory and (2) make sure that the old value doesn't get re-used
// if the same cell-id is later reused for another element.
- const cellId = data.cell_id as CellId;
+ const cellId = data.cell_id;
UI_ELEMENT_REGISTRY.removeElementsByCell(cellId);
VirtualFileTracker.INSTANCE.removeForCellId(cellId);
}
diff --git a/frontend/src/core/network/DeferredRequestRegistry.ts b/frontend/src/core/network/DeferredRequestRegistry.ts
index 56ef69d152..7cb51c5ebb 100644
--- a/frontend/src/core/network/DeferredRequestRegistry.ts
+++ b/frontend/src/core/network/DeferredRequestRegistry.ts
@@ -1,10 +1,10 @@
/* Copyright 2026 Marimo. All rights reserved. */
/* eslint-disable @typescript-eslint/no-redeclare */
+import type { components } from "@marimo-team/marimo-api";
import { Deferred } from "@/utils/Deferred";
import { generateUUID } from "@/utils/uuid";
-import type { TypedString } from "../../utils/typed";
-export type RequestId = TypedString<"RequestId">;
+export type RequestId = components["schemas"]["RequestId"];
export const RequestId = {
create(): RequestId {
return generateUUID() as RequestId;
diff --git a/frontend/src/core/network/__tests__/CachingRequestRegistry.test.ts b/frontend/src/core/network/__tests__/CachingRequestRegistry.test.ts
index 168d56d2c8..6278686de0 100644
--- a/frontend/src/core/network/__tests__/CachingRequestRegistry.test.ts
+++ b/frontend/src/core/network/__tests__/CachingRequestRegistry.test.ts
@@ -1,17 +1,16 @@
/* Copyright 2026 Marimo. All rights reserved. */
+
import { beforeEach, describe, expect, it, vi } from "vitest";
+import { requestId } from "@/__tests__/branded";
import { CachingRequestRegistry } from "../CachingRequestRegistry";
-import {
- DeferredRequestRegistry,
- type RequestId,
-} from "../DeferredRequestRegistry";
+import { DeferredRequestRegistry } from "../DeferredRequestRegistry";
vi.mock("@/utils/uuid", () => ({
generateUUID: vi.fn().mockReturnValue("uuid"),
}));
describe("CachingRequestRegistry", () => {
- const REQUEST_ID = "uuid" as RequestId;
+ const REQUEST_ID = requestId("uuid");
let makeRequestMock = vi.fn();
let delegate: DeferredRequestRegistry<unknown, unknown>;
let caching: CachingRequestRegistry<unknown, unknown>;
@@ -31,7 +30,7 @@ describe("CachingRequestRegistry", () => {
// Resolve first request
delegate.resolve(REQUEST_ID, "response");
- await expect(p1).resolves.toBe("response");
+ await expect(p1).resolves.toBe(requestId("response"));
// Second call with equivalent request gets served from cache
const p2 = caching.request({ a: 1 });
@@ -50,8 +49,8 @@ describe("CachingRequestRegistry", () => {
expect(p1).toStrictEqual(p2);
// Resolve and ensure both resolve to same result
- delegate.resolve(REQUEST_ID, "ok");
- await expect(p1).resolves.toBe("ok");
+ delegate.resolve(REQUEST_ID, requestId("ok"));
+ await expect(p1).resolves.toBe(requestId("ok"));
await expect(p2).resolves.toBe("ok");
});
@@ -67,7 +66,7 @@ describe("CachingRequestRegistry", () => {
expect(makeRequestMock).toHaveBeenCalledTimes(2);
// Resolve the second request
- delegate.resolve(REQUEST_ID, "ok");
- await expect(p2).resolves.toBe("ok");
+ delegate.resolve(REQUEST_ID, requestId("ok"));
+ await expect(p2).resolves.toBe(requestId("ok"));
});
});
diff --git a/frontend/src/core/network/__tests__/DeferredRequestRegistry.test.ts b/frontend/src/core/network/__tests__/DeferredRequestRegistry.test.ts
index 6def9a7ef7..596ec170f8 100644
--- a/frontend/src/core/network/__tests__/DeferredRequestRegistry.test.ts
+++ b/frontend/src/core/network/__tests__/DeferredRequestRegistry.test.ts
@@ -1,16 +1,14 @@
/* Copyright 2026 Marimo. All rights reserved. */
import { beforeEach, describe, expect, it, vi } from "vitest";
-import {
- DeferredRequestRegistry,
- type RequestId,
-} from "../DeferredRequestRegistry";
+import { requestId } from "@/__tests__/branded";
+import { DeferredRequestRegistry } from "../DeferredRequestRegistry";
vi.mock("@/utils/uuid", () => ({
generateUUID: vi.fn().mockReturnValue("uuid"),
}));
describe("DeferredRequestRegistry", () => {
- const REQUEST_ID = "uuid" as RequestId;
+ const REQUEST_ID = requestId("uuid");
let makeRequestMock = vi.fn();
let registry: DeferredRequestRegistry<unknown, unknown>;
@@ -26,7 +24,7 @@ describe("DeferredRequestRegistry", () => {
// resolve
registry.resolve(REQUEST_ID, "response");
- await expect(promise).resolves.toBe("response");
+ await expect(promise).resolves.toBe(requestId("response"));
});
it("should handle request failure", async () => {
diff --git a/frontend/src/core/static/__tests__/virtual-file-tracker.test.ts b/frontend/src/core/static/__tests__/virtual-file-tracker.test.ts
index 9f480fc5a5..8837719eed 100644
--- a/frontend/src/core/static/__tests__/virtual-file-tracker.test.ts
+++ b/frontend/src/core/static/__tests__/virtual-file-tracker.test.ts
@@ -1,6 +1,6 @@
/* Copyright 2026 Marimo. All rights reserved. */
import { describe, expect, it } from "vitest";
-import type { CellId } from "@/core/cells/ids";
+import { cellId } from "@/__tests__/branded";
import type { OutputMessage } from "@/core/kernel/messages";
import { findVirtualFiles, VirtualFileTracker } from "../virtual-file-tracker";
@@ -103,32 +103,32 @@ describe("findVirtualFiles", () => {
describe("VirtualFileTracker", () => {
it("should track virtual files, append, clear", () => {
const tracker = VirtualFileTracker.INSTANCE;
- const cellId = "test-cell-id" as CellId;
+ const cid = cellId("test-cell-id");
tracker.track({
- cell_id: cellId,
+ cell_id: cid,
output: {
mimetype: "text/html",
data: "Some text /@file/test-file.js more text",
} as OutputMessage,
});
- expect(tracker.virtualFiles.get(cellId)).toEqual(
+ expect(tracker.virtualFiles.get(cid)).toEqual(
new Set(["/@file/test-file.js"]),
);
// can append
tracker.track({
- cell_id: cellId,
+ cell_id: cid,
output: {
mimetype: "text/html",
data: "Some text /@file/another-file.txt more text",
} as OutputMessage,
});
- expect(tracker.virtualFiles.get(cellId)).toEqual(
+ expect(tracker.virtualFiles.get(cid)).toEqual(
new Set(["/@file/test-file.js", "/@file/another-file.txt"]),
);
// can clear
- tracker.removeForCellId(cellId);
- expect(tracker.virtualFiles.get(cellId)).toEqual(undefined);
+ tracker.removeForCellId(cid);
+ expect(tracker.virtualFiles.get(cid)).toEqual(undefined);
});
});
diff --git a/frontend/src/core/static/virtual-file-tracker.ts b/frontend/src/core/static/virtual-file-tracker.ts
index dfb0352d1a..3a41553bc1 100644
--- a/frontend/src/core/static/virtual-file-tracker.ts
+++ b/frontend/src/core/static/virtual-file-tracker.ts
@@ -29,7 +29,7 @@ export class VirtualFileTracker {
track(message: Pick<CellMessage, "cell_id" | "output">): void {
const output = message.output;
- const cellId = message.cell_id as CellId;
+ const cellId = message.cell_id;
if (!output) {
return;
}
diff --git a/frontend/src/core/storage/__tests__/state.test.ts b/frontend/src/core/storage/__tests__/state.test.ts
index 2def07fcc2..997e316789 100644
--- a/frontend/src/core/storage/__tests__/state.test.ts
+++ b/frontend/src/core/storage/__tests__/state.test.ts
@@ -1,5 +1,6 @@
/* Copyright 2026 Marimo. All rights reserved. */
import { beforeEach, describe, expect, it } from "vitest";
+import { variableName } from "@/__tests__/branded";
import type { VariableName } from "../../variables/types";
import { exportedForTesting } from "../state";
import type { StorageEntry, StorageNamespace, StorageState } from "../types";
@@ -7,7 +8,7 @@ import type { StorageEntry, StorageNamespace, StorageState } from "../types";
const { initialState, reducer, createActions } = exportedForTesting;
function makeNamespace(
- overrides: Partial<StorageNamespace> & { name: string },
+ overrides: Partial<StorageNamespace> & { name: VariableName },
): StorageNamespace {
return {
backendType: overrides.backendType ?? "obstore",
@@ -53,8 +54,14 @@ describe("storage state", () => {
describe("setNamespaces", () => {
it("should add namespaces from an empty state", () => {
- const ns1 = makeNamespace({ name: "my_s3", protocol: "s3" });
- const ns2 = makeNamespace({ name: "my_gcs", protocol: "gcs" });
+ const ns1 = makeNamespace({
+ name: variableName("my_s3"),
+ protocol: "s3",
+ });
+ const ns2 = makeNamespace({
+ name: variableName("my_gcs"),
+ protocol: "gcs",
+ });
actions.setNamespaces({ namespaces: [ns1, ns2] });
@@ -63,15 +70,18 @@ describe("storage state", () => {
it("should merge namespaces by name, replacing existing ones", () => {
const nsOld = makeNamespace({
- name: "my_s3",
+ name: variableName("my_s3"),
protocol: "s3",
rootPath: "/old",
});
- const nsOther = makeNamespace({ name: "my_gcs", protocol: "gcs" });
+ const nsOther = makeNamespace({
+ name: variableName("my_gcs"),
+ protocol: "gcs",
+ });
actions.setNamespaces({ namespaces: [nsOld, nsOther] });
const nsUpdated = makeNamespace({
- name: "my_s3",
+ name: variableName("my_s3"),
protocol: "s3",
rootPath: "/new",
});
@@ -82,10 +92,10 @@ describe("storage state", () => {
});
it("should add new namespaces alongside existing ones", () => {
- const ns1 = makeNamespace({ name: "ns1" });
+ const ns1 = makeNamespace({ name: variableName("ns1") });
actions.setNamespaces({ namespaces: [ns1] });
- const ns2 = makeNamespace({ name: "ns2" });
+ const ns2 = makeNamespace({ name: variableName("ns2") });
actions.setNamespaces({ namespaces: [ns2] });
expect(state.namespaces).toHaveLength(2);
@@ -101,7 +111,7 @@ describe("storage state", () => {
});
actions.setNamespaces({
- namespaces: [makeNamespace({ name: "ns" })],
+ namespaces: [makeNamespace({ name: variableName("ns") })],
});
expect(state.entriesByPath.get("ns::")).toEqual([entry]);
@@ -205,7 +215,7 @@ describe("storage state", () => {
});
it("should not affect namespaces", () => {
- const ns = makeNamespace({ name: "ns" });
+ const ns = makeNamespace({ name: variableName("ns") });
actions.setNamespaces({ namespaces: [ns] });
actions.setEntries({
@@ -263,7 +273,7 @@ describe("storage state", () => {
});
it("should not affect namespaces", () => {
- const ns = makeNamespace({ name: "my_s3" });
+ const ns = makeNamespace({ name: variableName("my_s3") });
actions.setNamespaces({ namespaces: [ns] });
actions.setEntries({
namespace: "my_s3",
@@ -293,31 +303,31 @@ describe("storage state", () => {
describe("filterFromVariables", () => {
it("should keep namespaces whose variable is still in scope", () => {
- const ns1 = makeNamespace({ name: "var_a" });
- const ns2 = makeNamespace({ name: "var_b" });
+ const ns1 = makeNamespace({ name: variableName("var_a") });
+ const ns2 = makeNamespace({ name: variableName("var_b") });
actions.setNamespaces({ namespaces: [ns1, ns2] });
actions.filterFromVariables([
- "var_a" as VariableName,
- "var_b" as VariableName,
+ variableName("var_a"),
+ variableName("var_b"),
]);
expect(state.namespaces).toEqual([ns1, ns2]);
});
it("should remove namespaces whose variable is no longer in scope", () => {
- const ns1 = makeNamespace({ name: "var_a" });
- const ns2 = makeNamespace({ name: "var_b" });
+ const ns1 = makeNamespace({ name: variableName("var_a") });
+ const ns2 = makeNamespace({ name: variableName("var_b") });
actions.setNamespaces({ namespaces: [ns1, ns2] });
- actions.filterFromVariables(["var_a" as VariableName]);
+ actions.filterFromVariables([variableName("var_a")]);
expect(state.namespaces).toEqual([ns1]);
});
it("should remove all named namespaces when given an empty variable list", () => {
- const ns1 = makeNamespace({ name: "var_a" });
- const ns2 = makeNamespace({ name: "var_b" });
+ const ns1 = makeNamespace({ name: variableName("var_a") });
+ const ns2 = makeNamespace({ name: variableName("var_b") });
actions.setNamespaces({ namespaces: [ns1, ns2] });
actions.filterFromVariables([]);
@@ -326,7 +336,7 @@ describe("storage state", () => {
});
it("should not affect entriesByPath", () => {
- const ns = makeNamespace({ name: "ns" });
+ const ns = makeNamespace({ name: variableName("ns") });
actions.setNamespaces({ namespaces: [ns] });
const entry = makeEntry({ path: "file.txt" });
diff --git a/frontend/src/core/storage/state.ts b/frontend/src/core/storage/state.ts
index 240f309f8b..1a49431b3d 100644
--- a/frontend/src/core/storage/state.ts
+++ b/frontend/src/core/storage/state.ts
@@ -71,7 +71,7 @@ const {
const names = new Set(variableNames);
// Filter out namespaces whose backing variable is no longer in scope
const namespaces = state.namespaces.filter((ns) => {
- return names.has(ns.name as VariableName);
+ return names.has(ns.name);
});
return { ...state, namespaces };
},
diff --git a/frontend/src/core/variables/__tests__/state.test.ts b/frontend/src/core/variables/__tests__/state.test.ts
index 9a22781597..61f7ecb25f 100644
--- a/frontend/src/core/variables/__tests__/state.test.ts
+++ b/frontend/src/core/variables/__tests__/state.test.ts
@@ -1,19 +1,19 @@
/* Copyright 2026 Marimo. All rights reserved. */
import { beforeEach, describe, expect, it } from "vitest";
-import type { CellId } from "@/core/cells/ids";
+import { cellId, variableName } from "@/__tests__/branded";
import { exportedForTesting } from "../state";
-import type { VariableName, Variables } from "../types";
+import type { Variables } from "../types";
const { initialState, reducer, createActions } = exportedForTesting;
const CellIds = {
- a: "a" as CellId,
- b: "b" as CellId,
+ a: cellId("a"),
+ b: cellId("b"),
};
const Names = {
- x: "x" as VariableName,
- y: "y" as VariableName,
+ x: variableName("x"),
+ y: variableName("y"),
};
describe("cell reducer", () => {
diff --git a/frontend/src/core/variables/types.ts b/frontend/src/core/variables/types.ts
index 049a04168b..dbaa92f926 100644
--- a/frontend/src/core/variables/types.ts
+++ b/frontend/src/core/variables/types.ts
@@ -1,9 +1,9 @@
/* Copyright 2026 Marimo. All rights reserved. */
-import type { TypedString } from "../../utils/typed";
+import type { components } from "@marimo-team/marimo-api";
import type { CellId } from "../cells/ids";
-export type VariableName = TypedString<"VariableName">;
+export type VariableName = components["schemas"]["VariableName"];
export interface Variable {
name: VariableName;
diff --git a/frontend/src/core/wasm/__tests__/state.test.ts b/frontend/src/core/wasm/__tests__/state.test.ts
index fd1f3659d8..3cb0f0919f 100644
--- a/frontend/src/core/wasm/__tests__/state.test.ts
+++ b/frontend/src/core/wasm/__tests__/state.test.ts
@@ -2,9 +2,9 @@
import { createRef } from "react";
import { describe, expect, it } from "vitest";
+import { cellId } from "@/__tests__/branded";
import type { NotebookState } from "@/core/cells/cells";
import { initialNotebookState, notebookAtom } from "@/core/cells/cells";
-import type { CellId } from "@/core/cells/ids";
import { createCell, createCellRuntimeState } from "@/core/cells/types";
import type { OutputMessage } from "@/core/kernel/messages";
import { store } from "@/core/state/jotai";
@@ -17,17 +17,17 @@ describe("hasAnyOutputAtom", () => {
): NotebookState => ({
...initialNotebookState(),
cellIds: new MultiColumn([
- CollapsibleTree.from(outputs.map((_, i) => `${i}` as CellId)),
+ CollapsibleTree.from(outputs.map((_, i) => cellId(`${i}`))),
]),
cellData: Object.fromEntries(
outputs.map((_, i) => [
- `${i}` as CellId,
- createCell({ id: `${i}` as CellId }),
+ cellId(`${i}`),
+ createCell({ id: cellId(`${i}`) }),
]),
),
cellRuntime: Object.fromEntries(
outputs.map((output, i) => [
- `${i}` as CellId,
+ `${i}`,
createCellRuntimeState({
output,
status: "queued",
@@ -36,7 +36,7 @@ describe("hasAnyOutputAtom", () => {
]),
),
cellHandles: Object.fromEntries(
- outputs.map((_, i) => [`${i}` as CellId, createRef()]),
+ outputs.map((_, i) => [cellId(`${i}`), createRef()]),
),
});
@@ -90,8 +90,8 @@ describe("hasAnyOutputAtom", () => {
it("should return true when all outputs are idle", () => {
const notebookState = createNotebookState([null, null]);
- const cellId0 = "0" as CellId;
- const cellId1 = "1" as CellId;
+ const cellId0 = cellId("0");
+ const cellId1 = cellId("1");
// Some idle cell, so returns false
store.set(notebookAtom, {
...notebookState,
diff --git a/frontend/src/core/websocket/useMarimoKernelConnection.tsx b/frontend/src/core/websocket/useMarimoKernelConnection.tsx
index c43c172fc7..d6ce36ac66 100644
--- a/frontend/src/core/websocket/useMarimoKernelConnection.tsx
+++ b/frontend/src/core/websocket/useMarimoKernelConnection.tsx
@@ -24,7 +24,7 @@ import { Logger } from "@/utils/Logger";
import { reloadSafe } from "@/utils/reload-safe";
import { useAlertActions } from "../alerts/state";
import { cacheInfoAtom } from "../cache/requests";
-import { type CellId, SCRATCH_CELL_ID, type UIElementId } from "../cells/ids";
+import { SCRATCH_CELL_ID } from "../cells/ids";
import { useRunsActions } from "../cells/runs";
import { focusAndScrollCellOutputIntoView } from "../cells/scrollCellIntoView";
import type { CellData } from "../cells/types";
@@ -153,7 +153,7 @@ export function useMarimoKernelConnection(opts: {
if (uiElement) {
const buffers = safeExtractSetUIElementMessageBuffers(msg.data);
UI_ELEMENT_REGISTRY.broadcastMessage(
- uiElement as UIElementId,
+ uiElement,
msg.data.message,
buffers,
);
@@ -173,14 +173,11 @@ export function useMarimoKernelConnection(opts: {
AUTOCOMPLETER.resolve(msg.data.completion_id as RequestId, msg.data);
return;
case "function-call-result":
- FUNCTIONS_REGISTRY.resolve(
- msg.data.function_call_id as RequestId,
- msg.data,
- );
+ FUNCTIONS_REGISTRY.resolve(msg.data.function_call_id, msg.data);
return;
case "cell-op": {
handleCellNotificationeration(msg.data, handleCellMessage);
- const cellData = getNotebook().cellData[msg.data.cell_id as CellId];
+ const cellData = getNotebook().cellData[msg.data.cell_id];
if (!cellData) {
return;
}
@@ -195,8 +192,8 @@ export function useMarimoKernelConnection(opts: {
setVariables(
msg.data.variables.map((v) => ({
name: v.name as VariableName,
- declaredBy: v.declared_by as CellId[],
- usedBy: v.used_by as CellId[],
+ declaredBy: v.declared_by,
+ usedBy: v.used_by,
})),
);
filterDatasetsFromVariables(
@@ -271,16 +268,16 @@ export function useMarimoKernelConnection(opts: {
addColumnPreview(msg.data);
return;
case "sql-table-preview":
- PreviewSQLTable.resolve(msg.data.request_id as RequestId, msg.data);
+ PreviewSQLTable.resolve(msg.data.request_id, msg.data);
return;
case "sql-table-list-preview":
- PreviewSQLTableList.resolve(msg.data.request_id as RequestId, msg.data);
+ PreviewSQLTableList.resolve(msg.data.request_id, msg.data);
return;
case "validate-sql-result":
ValidateSQL.resolve(msg.data.request_id as RequestId, msg.data);
return;
case "secret-keys-result":
- SECRETS_REGISTRY.resolve(msg.data.request_id as RequestId, msg.data);
+ SECRETS_REGISTRY.resolve(msg.data.request_id, msg.data);
return;
case "cache-info":
setCacheInfo(msg.data);
@@ -310,19 +307,19 @@ export function useMarimoKernelConnection(opts: {
return;
case "focus-cell":
- focusAndScrollCellOutputIntoView(msg.data.cell_id as CellId);
+ focusAndScrollCellOutputIntoView(msg.data.cell_id);
return;
case "update-cell-codes":
setCellCodes({
codes: msg.data.codes,
- ids: msg.data.cell_ids as CellId[],
+ ids: msg.data.cell_ids,
codeIsStale: msg.data.code_is_stale,
names: msg.data.names,
configs: msg.data.configs,
});
return;
case "update-cell-ids":
- setCellIds({ cellIds: msg.data.cell_ids as CellId[] });
+ setCellIds({ cellIds: msg.data.cell_ids });
return;
default:
logNever(msg.data);
diff --git a/frontend/src/plugins/impl/anywidget/model.ts b/frontend/src/plugins/impl/anywidget/model.ts
index dd92efc0e3..9be88fd0af 100644
--- a/frontend/src/plugins/impl/anywidget/model.ts
+++ b/frontend/src/plugins/impl/anywidget/model.ts
@@ -323,8 +323,7 @@ export async function handleWidgetMessage(
const msg = notification.message;
// Decode base64 buffers to DataViews (present in open/update/custom messages)
- const base64Buffers: Base64String[] =
- "buffers" in msg ? (msg.buffers as Base64String[]) : [];
+ const base64Buffers: Base64String[] = "buffers" in msg ? msg.buffers : [];
const buffers = base64Buffers.map(base64ToDataView);
switch (msg.method) {
diff --git a/frontend/src/stories/cell.stories.tsx b/frontend/src/stories/cell.stories.tsx
index 4152822683..945cbbc17d 100644
--- a/frontend/src/stories/cell.stories.tsx
+++ b/frontend/src/stories/cell.stories.tsx
@@ -3,6 +3,7 @@
import type { Meta, StoryObj } from "@storybook/react-vite";
import { createStore, Provider } from "jotai";
import { createRef } from "react";
+import { cellId } from "@/__tests__/branded";
import { type NotebookState, notebookAtom } from "@/core/cells/cells";
import {
type CellRuntimeState,
@@ -18,7 +19,6 @@ import { MultiColumn } from "@/utils/id-tree";
import type { Milliseconds, Seconds } from "@/utils/time";
import { Cell as EditorCell } from "../components/editor/notebook-cell";
import { TooltipProvider } from "../components/ui/tooltip";
-import type { CellId } from "../core/cells/ids";
type Story = StoryObj<typeof Cell>;
@@ -34,11 +34,11 @@ const Cell: React.FC<{
config?: CellConfig;
};
}> = ({ overrides = {} }) => {
- const cellId = "1" as CellId;
+ const cid = cellId("1");
const notebook: NotebookState = {
cellData: {
- [cellId]: {
- id: cellId,
+ [cid]: {
+ id: cid,
name: "cell_1",
code: "import marimo as mo",
edited: overrides.edited ?? false,
@@ -52,9 +52,9 @@ const Cell: React.FC<{
lastExecutionTime: null,
},
},
- cellIds: MultiColumn.from([[cellId]]),
+ cellIds: MultiColumn.from([[cid]]),
cellRuntime: {
- [cellId]: createCellRuntimeState({
+ [cid]: createCellRuntimeState({
output: overrides.output ?? null,
runElapsedTimeMs: overrides.runElapsedTimeMs ?? (10 as Milliseconds),
status: overrides.status ?? "idle",
@@ -70,7 +70,7 @@ const Cell: React.FC<{
}),
},
cellHandles: {
- [cellId]: createRef(),
+ [cid]: createRef(),
},
cellLogs: [],
history: [],
@@ -86,7 +86,7 @@ const Cell: React.FC<{
<Provider store={store}>
<TooltipProvider>
<EditorCell
- cellId={cellId}
+ cellId={cid}
theme={"light"}
showPlaceholder={false}
mode={"edit"}
diff --git a/frontend/src/stories/layout/vertical/one-column.stories.tsx b/frontend/src/stories/layout/vertical/one-column.stories.tsx
index 912444a33f..2757bea578 100644
--- a/frontend/src/stories/layout/vertical/one-column.stories.tsx
+++ b/frontend/src/stories/layout/vertical/one-column.stories.tsx
@@ -3,6 +3,7 @@
import type { Meta } from "@storybook/react-vite";
import { createStore, Provider } from "jotai";
import { createRef } from "react";
+import { cellId } from "@/__tests__/branded";
import { type NotebookState, notebookAtom } from "@/core/cells/cells";
import { createCellRuntimeState } from "@/core/cells/types";
import { defaultUserConfig, parseAppConfig } from "@/core/config/config-schema";
@@ -99,8 +100,8 @@ export default {
type W = Window & { __MARIMO_STATIC__?: { files: Record<string, unknown> } };
const EditModeCodeShown = () => {
- const cellId = "Hbol" as CellId;
- const notebook = createLongReprNotebook(cellId);
+ const cid = cellId("Hbol");
+ const notebook = createLongReprNotebook(cid);
const store = createStore();
store.set(notebookAtom, notebook);
@@ -124,8 +125,8 @@ const EditModeCodeShown = () => {
};
const EditModeCodeHidden = () => {
- const cellId = "Hbol" as CellId;
- const notebook = createLongReprNotebook(cellId, true);
+ const cid = cellId("Hbol");
+ const notebook = createLongReprNotebook(cid, true);
const store = createStore();
store.set(notebookAtom, notebook);
@@ -149,8 +150,8 @@ const EditModeCodeHidden = () => {
};
const ReadModeCodeShown = () => {
- const cellId = "Hbol" as CellId;
- const notebook = createLongReprNotebook(cellId);
+ const cid = cellId("Hbol");
+ const notebook = createLongReprNotebook(cid);
const store = createStore();
store.set(notebookAtom, notebook);
@@ -168,8 +169,8 @@ const ReadModeCodeShown = () => {
};
const ReadModeCodeHidden = () => {
- const cellId = "Hbol" as CellId;
- const notebook = createLongReprNotebook(cellId);
+ const cid = cellId("Hbol");
+ const notebook = createLongReprNotebook(cid);
const store = createStore();
store.set(notebookAtom, notebook);
diff --git a/frontend/src/stories/log-viewer.stories.tsx b/frontend/src/stories/log-viewer.stories.tsx
index 0dbd44bc1c..b770462dc8 100644
--- a/frontend/src/stories/log-viewer.stories.tsx
+++ b/frontend/src/stories/log-viewer.stories.tsx
@@ -1,7 +1,7 @@
/* Copyright 2026 Marimo. All rights reserved. */
import type { Meta, StoryObj } from "@storybook/react-vite";
+import { cellId } from "@/__tests__/branded";
import { LogViewer } from "@/components/editor/chrome/panels/logs-panel";
-import type { CellId } from "@/core/cells/ids";
import { Dialog } from "../components/ui/dialog";
import { TooltipProvider } from "../components/ui/tooltip";
@@ -23,37 +23,37 @@ export const Primary: Story = {
{
timestamp: Date.now(),
level: "stdout",
- cellId: "cell1" as CellId,
+ cellId: cellId("cell1"),
message: "Hello world!",
},
{
timestamp: Date.now(),
level: "stdout",
- cellId: "cell1" as CellId,
+ cellId: cellId("cell1"),
message: "Running cell...",
},
{
timestamp: Date.now(),
level: "stdout",
- cellId: "cell1" as CellId,
+ cellId: cellId("cell1"),
message: "Done!",
},
{
timestamp: Date.now(),
level: "stderr",
- cellId: "cell2" as CellId,
+ cellId: cellId("cell2"),
message: "Output is too large!",
},
{
timestamp: Date.now(),
level: "stderr",
- cellId: "cell2" as CellId,
+ cellId: cellId("cell2"),
message: "String length is too short.".repeat(100),
},
- ...Array.from({ length: 100 }).map((_, index) => ({
+ ...Array.from({ length: 100 }).map(() => ({
timestamp: Date.now(),
level: "stdout" as const,
- cellId: "cell1" as CellId,
+ cellId: cellId("cell1"),
message: "Running cell...",
})),
]}
diff --git a/frontend/src/stories/variables.stories.tsx b/frontend/src/stories/variables.stories.tsx
index 5b7624d609..025ff07989 100644
--- a/frontend/src/stories/variables.stories.tsx
+++ b/frontend/src/stories/variables.stories.tsx
@@ -1,7 +1,7 @@
/* Copyright 2026 Marimo. All rights reserved. */
import type { Meta, StoryObj } from "@storybook/react-vite";
+import { cellId } from "@/__tests__/branded";
import { VariableTable } from "@/components/variables/variables-table";
-import type { CellId } from "@/core/cells/ids";
const meta: Meta<typeof VariableTable> = {
title: "VariableTable",
@@ -51,7 +51,7 @@ export const Primary: Story = {
<div className="max-w-4xl">
<VariableTable
variables={variables}
- cellIds={["2", "1", "3"] as CellId[]}
+ cellIds={[cellId("2"), cellId("1"), cellId("3")]}
/>
</div>
),
diff --git a/frontend/src/utils/__tests__/download.test.tsx b/frontend/src/utils/__tests__/download.test.tsx
index 618472bff0..f33a5fc6a5 100644
--- a/frontend/src/utils/__tests__/download.test.tsx
+++ b/frontend/src/utils/__tests__/download.test.tsx
@@ -1,7 +1,8 @@
/* Copyright 2026 Marimo. All rights reserved. */
+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { Mocks } from "@/__mocks__/common";
-import type { CellId } from "@/core/cells/ids";
+import { cellId } from "@/__tests__/branded";
import { CellOutputId } from "@/core/cells/ids";
import {
downloadAsPDF,
@@ -218,7 +219,7 @@ describe("getImageDataUrlForCell", () => {
beforeEach(() => {
vi.clearAllMocks();
mockElement = document.createElement("div");
- mockElement.id = CellOutputId.create("cell-1" as CellId);
+ mockElement.id = CellOutputId.create(cellId("cell-1"));
document.body.append(mockElement);
});
@@ -227,7 +228,7 @@ describe("getImageDataUrlForCell", () => {
});
it("should return undefined if element is not found", async () => {
- const result = await getImageDataUrlForCell("nonexistent" as CellId);
+ const result = await getImageDataUrlForCell(cellId("nonexistent"));
expect(result).toBeUndefined();
expect(Logger.error).toHaveBeenCalledWith(
@@ -238,7 +239,7 @@ describe("getImageDataUrlForCell", () => {
it("should capture screenshot and return data URL", async () => {
vi.mocked(toPng).mockResolvedValue(mockDataUrl);
- const result = await getImageDataUrlForCell("cell-1" as CellId);
+ const result = await getImageDataUrlForCell(cellId("cell-1"));
expect(result).toBe(mockDataUrl);
expect(toPng).toHaveBeenCalledWith(
@@ -253,7 +254,7 @@ describe("getImageDataUrlForCell", () => {
it("should pass style options to prevent clipping", async () => {
vi.mocked(toPng).mockResolvedValue(mockDataUrl);
- await getImageDataUrlForCell("cell-1" as CellId);
+ await getImageDataUrlForCell(cellId("cell-1"));
expect(toPng).toHaveBeenCalledWith(
mockElement,
@@ -274,7 +275,7 @@ describe("getImageDataUrlForCell", () => {
});
vi.mocked(toPng).mockResolvedValue(mockDataUrl);
- await getImageDataUrlForCell("cell-1" as CellId);
+ await getImageDataUrlForCell(cellId("cell-1"));
expect(toPng).toHaveBeenCalledWith(
mockElement,
@@ -287,7 +288,7 @@ describe("getImageDataUrlForCell", () => {
it("should pass scrollbar hiding styles via extraStyleContent", async () => {
vi.mocked(toPng).mockResolvedValue(mockDataUrl);
- await getImageDataUrlForCell("cell-1" as CellId);
+ await getImageDataUrlForCell(cellId("cell-1"));
expect(toPng).toHaveBeenCalledWith(
mockElement,
@@ -302,7 +303,7 @@ describe("getImageDataUrlForCell", () => {
mockElement.style.maxHeight = "100px";
vi.mocked(toPng).mockResolvedValue(mockDataUrl);
- await getImageDataUrlForCell("cell-1" as CellId);
+ await getImageDataUrlForCell(cellId("cell-1"));
// DOM should remain unchanged
expect(mockElement.style.overflow).toBe("hidden");
@@ -312,7 +313,7 @@ describe("getImageDataUrlForCell", () => {
it("should throw error on failure", async () => {
vi.mocked(toPng).mockRejectedValue(new Error("Capture failed"));
- await expect(getImageDataUrlForCell("cell-1" as CellId)).rejects.toThrow(
+ await expect(getImageDataUrlForCell(cellId("cell-1"))).rejects.toThrow(
"Capture failed",
);
});
@@ -320,13 +321,13 @@ describe("getImageDataUrlForCell", () => {
it("should handle concurrent captures correctly", async () => {
// Create a second element
const mockElement2 = document.createElement("div");
- mockElement2.id = CellOutputId.create("cell-2" as CellId);
+ mockElement2.id = CellOutputId.create(cellId("cell-2"));
document.body.append(mockElement2);
vi.mocked(toPng).mockResolvedValue(mockDataUrl);
- const capture1 = getImageDataUrlForCell("cell-1" as CellId);
- const capture2 = getImageDataUrlForCell("cell-2" as CellId);
+ const capture1 = getImageDataUrlForCell(cellId("cell-1"));
+ const capture2 = getImageDataUrlForCell(cellId("cell-2"));
await Promise.all([capture1, capture2]);
@@ -461,7 +462,7 @@ describe("downloadCellOutputAsImage", () => {
beforeEach(() => {
vi.clearAllMocks();
mockElement = document.createElement("div");
- mockElement.id = CellOutputId.create("cell-1" as CellId);
+ mockElement.id = CellOutputId.create(cellId("cell-1"));
mockAppEl = document.createElement("div");
mockAppEl.id = "App";
// Mock scrollTo since jsdom doesn't implement it
@@ -486,7 +487,7 @@ describe("downloadCellOutputAsImage", () => {
});
it("should show error toast if element not found", async () => {
- await downloadCellOutputAsImage("nonexistent" as CellId, "test");
+ await downloadCellOutputAsImage(cellId("nonexistent"), "test");
expect(toPng).not.toHaveBeenCalled();
expect(Logger.error).toHaveBeenCalledWith(
@@ -502,7 +503,7 @@ describe("downloadCellOutputAsImage", () => {
it("should show error toast if toPng fails", async () => {
vi.mocked(toPng).mockRejectedValue(new Error("Screenshot failed"));
- await downloadCellOutputAsImage("cell-1" as CellId, "result");
+ await downloadCellOutputAsImage(cellId("cell-1"), "result");
expect(toast).toHaveBeenCalledWith({
title: "Failed to download PNG",
@@ -514,7 +515,7 @@ describe("downloadCellOutputAsImage", () => {
it("should download cell output as image", async () => {
vi.mocked(toPng).mockResolvedValue(mockDataUrl);
- await downloadCellOutputAsImage("cell-1" as CellId, "result");
+ await downloadCellOutputAsImage(cellId("cell-1"), "result");
expect(toPng).toHaveBeenCalledWith(
mockElement,
@@ -529,7 +530,7 @@ describe("downloadCellOutputAsImage", () => {
it("should pass style options to toPng for full content capture", async () => {
vi.mocked(toPng).mockResolvedValue(mockDataUrl);
- await downloadCellOutputAsImage("cell-1" as CellId, "result");
+ await downloadCellOutputAsImage(cellId("cell-1"), "result");
expect(toPng).toHaveBeenCalledWith(
mockElement,
@@ -547,7 +548,7 @@ describe("downloadCellOutputAsImage", () => {
mockElement.style.maxHeight = "100px";
vi.mocked(toPng).mockResolvedValue(mockDataUrl);
- await downloadCellOutputAsImage("cell-1" as CellId, "result");
+ await downloadCellOutputAsImage(cellId("cell-1"), "result");
// DOM should remain unchanged
expect(mockElement.style.overflow).toBe("hidden");
diff --git a/frontend/src/utils/json/base64.ts b/frontend/src/utils/json/base64.ts
index 0329b6e221..fae9a31103 100644
--- a/frontend/src/utils/json/base64.ts
+++ b/frontend/src/utils/json/base64.ts
@@ -1,5 +1,6 @@
/* Copyright 2026 Marimo. All rights reserved. */
+import type { components } from "@marimo-team/marimo-api";
import type { NotificationMessageData } from "@/core/kernel/messages";
import type { TypedString } from "../typed";
@@ -11,9 +12,9 @@ export type JsonString<T = unknown> = TypedString<"Json"> & {
};
/**
- * A base64-encoded string.
+ * A base64-encoded string — derived from the generated OpenAPI schema.
*/
-export type Base64String = TypedString<"Base64">;
+export type Base64String = components["schemas"]["Base64String"];
/**
* A data URL string.
@@ -120,7 +121,6 @@ export function dataViewToBase64(dataView: DataView): Base64String {
export function safeExtractSetUIElementMessageBuffers(
notification: NotificationMessageData<"send-ui-element-message">,
): readonly DataView[] {
- // @ts-expect-error - TypeScript doesn't know that these strings are actually base64 strings
const strs: Base64String[] = notification.buffers ?? [];
return strs.map(base64ToDataView);
}
diff --git a/frontend/src/utils/traceback.ts b/frontend/src/utils/traceback.ts
index fb06dd6191..3661b80a1d 100644
--- a/frontend/src/utils/traceback.ts
+++ b/frontend/src/utils/traceback.ts
@@ -98,10 +98,12 @@ export function getTracebackInfo(domNode: DOMNode): TracebackInfo | null {
10,
);
if (domNode.firstChild.nodeValue?.includes("__marimo__")) {
- const cellId = /__marimo__cell_(\w+)_/.exec(
+ const maybeCellId = /__marimo__cell_(\w+)_/.exec(
domNode.firstChild.nodeValue,
- )?.[1] as CellId;
- if (cellId && lineNumber) {
+ )?.[1];
+ if (maybeCellId && lineNumber) {
+ // @ts-expect-error - Custom parser above will return valid cell ids
+ const cellId: CellId = maybeCellId;
return { kind: "cell", cellId, lineNumber };
}
} else {
diff --git a/marimo/_cli/development/commands.py b/marimo/_cli/development/commands.py
index c571b11e69..a5488d041f 100644
--- a/marimo/_cli/development/commands.py
+++ b/marimo/_cli/development/commands.py
@@ -24,6 +24,183 @@ if TYPE_CHECKING:
import psutil
+def _enrich_branded_types(
+ component_schemas: dict[str, Any],
+ models: list[object],
+) -> None:
+ """Post-process schemas to replace NewType string fields with $ref
+ branded types.
+
+ msgspec.json.schema_components() strips NewType wrappers, emitting plain
+ ``{type: string}`` for fields like ``CellId_t``. This function:
+
+ 1. Adds named schemas for each branded type (e.g. ``CellId: {type: string}``).
+ 2. Walks every model struct's type hints and replaces inline schemas with
+ ``$ref`` pointers wherever a field's annotation is (or contains) a
+ registered NewType.
+ """
+ import types as _types
+ import typing
+ from typing import Union
+
+ import msgspec
+
+ from marimo._types.ids import (
+ CellId_t,
+ RequestId,
+ SessionId,
+ UIElementId,
+ VariableName,
+ WidgetModelId,
+ )
+
+ branded: dict[Any, str] = {
+ CellId_t: "CellId",
+ UIElementId: "UIElementId",
+ SessionId: "SessionId",
+ VariableName: "VariableName",
+ RequestId: "RequestId",
+ WidgetModelId: "WidgetModelId",
+ }
+
+ # Step 1 — add named schemas for each branded type
+ for schema_name in branded.values():
+ component_schemas[schema_name] = {"type": "string"}
+
+ def make_ref(name: str) -> dict[str, str]:
+ return {"$ref": f"#/components/schemas/{name}"}
+
+ def _is_union(origin: Any) -> bool:
+ return origin is Union or origin is getattr(_types, "UnionType", None)
+
+ def resolve(ty: Any) -> dict[str, Any] | None:
+ """Produce a branded schema for *ty*, or ``None``."""
+ if ty in branded:
+ return make_ref(branded[ty])
+
+ origin = typing.get_origin(ty)
+ args = typing.get_args(ty)
+
+ # Union / Optional
+ if _is_union(origin):
+ non_none = [a for a in args if a is not type(None)]
+ has_none = len(non_none) < len(args)
+ if len(non_none) == 1:
+ inner = resolve(non_none[0])
+ if inner is not None:
+ if has_none:
+ return {"anyOf": [inner, {"type": "null"}]}
+ return inner
+ return None
+
+ # list[T]
+ if origin is list:
+ if args:
+ inner = resolve(args[0])
+ if inner is not None:
+ return {"type": "array", "items": inner}
+ return None
+
+ # tuple[T, ...]
+ if origin is tuple:
+ if len(args) == 2 and args[1] is Ellipsis:
+ inner = resolve(args[0])
+ if inner is not None:
+ return {"type": "array", "items": inner}
+ return None
+
+ # dict[K, V] — brand the value type (keys are always strings in JSON)
+ if origin is dict and len(args) == 2:
+ val = resolve(args[1])
+ if val is not None:
+ return {"type": "object", "additionalProperties": val}
+
+ return None
+
+ # Step 2 — collect *all* reachable struct types (not just MODELS,
+ # since msgspec pulls in transitively-referenced structs too).
+ all_structs: dict[str, type] = {}
+
+ def _visit_type(ty: Any) -> None:
+ if isinstance(ty, type) and issubclass(ty, msgspec.Struct):
+ if ty.__name__ in all_structs:
+ return
+ all_structs[ty.__name__] = ty
+ try:
+ for hint in typing.get_type_hints(ty).values():
+ _visit_annotation(hint)
+ except Exception:
+ pass
+
+ def _visit_annotation(ty: Any) -> None:
+ if isinstance(ty, type):
+ _visit_type(ty)
+ return
+ for arg in typing.get_args(ty):
+ if arg is not Ellipsis and arg is not type(None):
+ _visit_annotation(arg)
+
+ for model in models:
+ _visit_type(model)
+
+ # Step 3 — walk collected structs and replace inline schemas with $refs
+ for schema_name, struct_cls in all_structs.items():
+ schema = component_schemas.get(schema_name)
+ if schema is None:
+ continue
+
+ properties = schema.get("properties", {})
+
+ try:
+ hints = typing.get_type_hints(struct_cls)
+ except Exception:
+ continue
+
+ for field_name, field_type in hints.items():
+ if field_name not in properties:
+ continue
+
+ replacement = resolve(field_type)
+ if replacement is not None:
+ # Preserve default value from the original schema
+ existing = properties[field_name]
+ if isinstance(existing, dict) and "default" in existing:
+ replacement["default"] = existing["default"]
+ properties[field_name] = replacement
+
+ # Step 4 — replace inline {type: string, contentEncoding: base64}
+ # with a named $ref. msgspec already emits contentEncoding for
+ # bytes fields; we just need to give it a name so the TS codegen
+ # can brand it.
+ component_schemas["Base64String"] = {
+ "type": "string",
+ "contentEncoding": "base64",
+ }
+
+ def _make_base64_ref() -> dict[str, str]:
+ # Fresh dict each time to avoid YAML anchor deduplication
+ return {"$ref": "#/components/schemas/Base64String"}
+
+ def _replace_base64(obj: Any) -> Any:
+ if isinstance(obj, dict):
+ if (
+ obj.get("type") == "string"
+ and obj.get("contentEncoding") == "base64"
+ ):
+ return _make_base64_ref()
+ return {k: _replace_base64(v) for k, v in obj.items()}
+ if isinstance(obj, list):
+ return [_replace_base64(item) for item in obj]
+ return obj
+
+ for schema_name in list(component_schemas):
+ if schema_name == "Base64String":
+ continue
+ component_schemas[schema_name] = _replace_base64(
+ component_schemas[schema_name]
+ )
+
+
def _generate_server_api_schema() -> dict[str, Any]:
import msgspec
import msgspec.json
@@ -275,6 +452,8 @@ def _generate_server_api_schema() -> dict[str, Any]:
ref_template="#/components/schemas/{name}",
)
+ _enrich_branded_types(component_schemas, MODELS)
+
schemas_generator = SchemaGenerator(
{
"openapi": "3.1.0",
diff --git a/packages/openapi/api.yaml b/packages/openapi/api.yaml
index 5f0df4d840..221df796e7 100644
--- a/packages/openapi/api.yaml
+++ b/packages/openapi/api.yaml
@@ -256,6 +256,9 @@ components:
- description
title: BannerNotification
type: object
+ Base64String:
+ contentEncoding: base64
+ type: string
BaseResponse:
properties:
success:
@@ -366,6 +369,8 @@ components:
required: []
title: CellConfig
type: object
+ CellId:
+ type: string
CellNotification:
description: "Updates a cell's state in the frontend.\n\n Only fields that\
\ are set (not None) will update the cell state.\n Omitting a field leaves\
@@ -379,7 +384,7 @@ components:
\ Creation timestamp, auto-set."
properties:
cell_id:
- type: string
+ $ref: '#/components/schemas/CellId'
console:
anyOf:
- items:
@@ -619,7 +624,7 @@ components:
document:
type: string
id:
- type: string
+ $ref: '#/components/schemas/RequestId'
type:
enum:
- code-completion
@@ -637,7 +642,7 @@ components:
document:
type: string
id:
- type: string
+ $ref: '#/components/schemas/RequestId'
required:
- id
- document
@@ -1022,7 +1027,7 @@ components:
type: array
engine:
anyOf:
- - type: string
+ - $ref: '#/components/schemas/VariableName'
- type: 'null'
default: null
indexes:
@@ -1064,7 +1069,7 @@ components:
- view
variable_name:
anyOf:
- - type: string
+ - $ref: '#/components/schemas/VariableName'
- type: 'null'
required:
- source_type
@@ -1115,7 +1120,7 @@ components:
type: string
engine:
anyOf:
- - type: string
+ - $ref: '#/components/schemas/VariableName'
- type: 'null'
default: null
name:
@@ -1825,7 +1830,7 @@ components:
\ Cell to focus."
properties:
cell_id:
- type: string
+ $ref: '#/components/schemas/CellId'
op:
enum:
- focus-cell
@@ -1882,7 +1887,7 @@ components:
\ status."
properties:
function_call_id:
- type: string
+ $ref: '#/components/schemas/RequestId'
op:
enum:
- function-call-result
@@ -2262,7 +2267,7 @@ components:
$ref: '#/components/schemas/KernelCapabilitiesNotification'
cell_ids:
items:
- type: string
+ $ref: '#/components/schemas/CellId'
type: array
codes:
items:
@@ -2843,12 +2848,12 @@ components:
properties:
blamed_cell:
anyOf:
- - type: string
+ - $ref: '#/components/schemas/CellId'
- type: 'null'
msg:
type: string
raising_cell:
- type: string
+ $ref: '#/components/schemas/CellId'
type:
enum:
- ancestor-prevented
@@ -2864,7 +2869,7 @@ components:
msg:
type: string
raising_cell:
- type: string
+ $ref: '#/components/schemas/CellId'
type:
enum:
- ancestor-stopped
@@ -2930,7 +2935,7 @@ components:
type: string
raising_cell:
anyOf:
- - type: string
+ - $ref: '#/components/schemas/CellId'
- type: 'null'
type:
enum:
@@ -3041,7 +3046,7 @@ components:
properties:
blamed_cell:
anyOf:
- - type: string
+ - $ref: '#/components/schemas/CellId'
- type: 'null'
msg:
type: string
@@ -3121,8 +3126,7 @@ components:
properties:
buffers:
items:
- contentEncoding: base64
- type: string
+ $ref: '#/components/schemas/Base64String'
type: array
message:
anyOf:
@@ -3152,8 +3156,7 @@ components:
properties:
buffers:
items:
- contentEncoding: base64
- type: string
+ $ref: '#/components/schemas/Base64String'
type: array
content: {}
method:
@@ -3221,8 +3224,7 @@ components:
type: array
buffers:
items:
- contentEncoding: base64
- type: string
+ $ref: '#/components/schemas/Base64String'
type: array
method:
enum:
@@ -3240,8 +3242,7 @@ components:
properties:
buffers:
items:
- contentEncoding: base64
- type: string
+ $ref: '#/components/schemas/Base64String'
type: array
message:
anyOf:
@@ -3275,8 +3276,7 @@ components:
type: array
buffers:
items:
- contentEncoding: base64
- type: string
+ $ref: '#/components/schemas/Base64String'
type: array
method:
enum:
@@ -3318,7 +3318,7 @@ components:
properties:
cells:
items:
- type: string
+ $ref: '#/components/schemas/CellId'
type: array
name:
type: string
@@ -3729,7 +3729,7 @@ components:
\ UI elements should be removed."
properties:
cell_id:
- type: string
+ $ref: '#/components/schemas/CellId'
op:
enum:
- remove-ui-elements
@@ -3761,6 +3761,8 @@ components:
- filename
title: RenameNotebookRequest
type: object
+ RequestId:
+ type: string
RunningNotebooksResponse:
properties:
files:
@@ -3902,7 +3904,7 @@ components:
enum:
- sql-table-list-preview
request_id:
- type: string
+ $ref: '#/components/schemas/RequestId'
tables:
default: []
items:
@@ -3931,7 +3933,7 @@ components:
enum:
- sql-table-preview
request_id:
- type: string
+ $ref: '#/components/schemas/RequestId'
table:
anyOf:
- type: 'null'
@@ -4064,7 +4066,7 @@ components:
enum:
- secret-keys-result
request_id:
- type: string
+ $ref: '#/components/schemas/RequestId'
secrets:
items:
$ref: '#/components/schemas/SecretKeysWithProvider'
@@ -4115,6 +4117,8 @@ components:
- follow_symlink
title: ServerConfig
type: object
+ SessionId:
+ type: string
SetupRootError:
properties:
edges_with_vars:
@@ -4526,7 +4530,7 @@ components:
displayName:
type: string
name:
- type: string
+ $ref: '#/components/schemas/VariableName'
protocol:
type: string
rootPath:
@@ -4657,6 +4661,8 @@ components:
required: []
title: TyLanguageServerConfig
type: object
+ UIElementId:
+ type: string
UIElementMessageNotification:
description: "Sends a message to a UI element/widget.\n\n Attributes:\n \
\ ui_element: UI element identifier.\n message: Message payload\
@@ -4665,8 +4671,7 @@ components:
buffers:
anyOf:
- items:
- contentEncoding: base64
- type: string
+ $ref: '#/components/schemas/Base64String'
type: array
- type: 'null'
default: null
@@ -4676,7 +4681,7 @@ components:
enum:
- send-ui-element-message
ui_element:
- type: string
+ $ref: '#/components/schemas/UIElementId'
required:
- op
- ui_element
@@ -4710,7 +4715,7 @@ components:
properties:
cell_ids:
items:
- type: string
+ $ref: '#/components/schemas/CellId'
type: array
code_is_stale:
type: boolean
@@ -4772,7 +4777,7 @@ components:
properties:
cell_ids:
items:
- type: string
+ $ref: '#/components/schemas/CellId'
type: array
op:
enum:
@@ -5028,13 +5033,13 @@ components:
properties:
declared_by:
items:
- type: string
+ $ref: '#/components/schemas/CellId'
type: array
name:
type: string
used_by:
items:
- type: string
+ $ref: '#/components/schemas/CellId'
type: array
required:
- name
@@ -5042,6 +5047,8 @@ components:
- used_by
title: VariableDeclarationNotification
type: object
+ VariableName:
+ type: string
VariableValue:
description: "Variable value and type for variables panel.\n\n Attributes:\n\
\ name: Variable name.\n value: String representation of value.\n\
@@ -5110,6 +5117,8 @@ components:
required: []
title: VenvConfig
type: object
+ WidgetModelId:
+ type: string
WorkspaceFilesRequest:
properties:
includeMarkdown:
diff --git a/packages/openapi/convert_types.js b/packages/openapi/convert_types.js
index d1e7132da2..7d0252523c 100644
--- a/packages/openapi/convert_types.js
+++ b/packages/openapi/convert_types.js
@@ -2,52 +2,73 @@
/** biome-ignore-all lint/suspicious/noConsole: for debugging */
// @ts-check
import * as fs from "node:fs";
-import * as process from "node:process";
+import openapiTS, { astToString, COMMENT_HEADER } from "openapi-typescript";
/**
- * Make an assertion.
+ * Branded NewType schemas generated by the Python codegen post-processor.
+ * Each key is the OpenAPI schema name; the value is the TypeScript brand tag.
*
- * @param {unknown} expression - The expression to test.
- * @param {string=} msg - The optional message to display if the assertion fails.
- * @returns {asserts expression}
- * @throws an {@link Error} if `expression` is not truthy.
+ * When a new NewType is added to marimo/_types/ids.py *and* registered in
+ * _enrich_branded_types (commands.py), add a corresponding entry here so
+ * the generated TypeScript carries the branded type.
*/
-function assert(expression, msg = "") {
- if (!expression) {
- console.error(msg);
- process.exit(1);
- }
-}
+const BRANDED_TYPES = {
+ Base64String: "Base64String",
+ CellId: "CellId",
+ SessionId: "SessionId",
+ VariableName: "VariableName",
+ RequestId: "RequestId",
+ WidgetModelId: "WidgetModelId",
+};
-function main() {
- const paths = process.argv.slice(2);
+/**
+ * Injected at the top of the generated file so branded schemas can reference it.
+ */
+const TYPED_STRING_HELPER =
+ "/** Branded string type — compile-time only. */\ntype TypedString<T extends string> = string & { __type__: T };\n";
- if (paths.length === 0) {
- console.error("Usage: node convert_types.js file1.ts [file2.ts ...]");
- process.exit(1);
- }
+/**
+ * Apply post-generation transforms to the TypeScript output.
+ *
+ * @param {string} content
+ * @returns {string}
+ */
+function transform(content) {
+ let result = content;
+
+ // 1. Record<string, never> → Record<string, any>
+ result = result.replace(/Record<string, never>/g, "Record<string, any>");
- for (const filePath of paths) {
- assert(fs.existsSync(filePath), `Expected ${filePath} to exist`);
- assert(
- filePath.endsWith(".ts"),
- `Expected ${filePath} to have .ts extension`,
- );
- const stats = fs.statSync(filePath);
- assert(stats.isFile(), `Expected ${filePath} to be a file`);
-
- const content = fs.readFileSync(filePath, "utf8");
- const newContent = content.replace(
- /Record<string, never>/g,
- "Record<string, any>",
- );
- if (content !== newContent) {
- fs.writeFileSync(filePath, newContent);
- console.log(`Updated: ${filePath}`);
- } else {
- console.log(`No changes made to: ${filePath}`);
- }
+ // 2. Inject TypedString helper before the first export
+ result = result.replace(/^(export )/m, `${TYPED_STRING_HELPER}\n$1`);
+
+ // 3. Brand named type schemas.
+ // openapi-typescript emits these as top-level schema entries:
+ // SchemaName: string;
+ // We replace with:
+ // SchemaName: TypedString<"SchemaName">;
+ for (const [schemaName, brand] of Object.entries(BRANDED_TYPES)) {
+ const pattern = new RegExp(`(\\b${schemaName}): string;`);
+ const replacement = `$1: TypedString<"${brand}">;`;
+ result = result.replace(pattern, replacement);
}
+
+ // 4. UIElementId is a template literal, not a simple branded string.
+ result = result.replace(
+ /\bUIElementId: string;/,
+ 'UIElementId: `${components["schemas"]["CellId"]}-${string}`;',
+ );
+
+ return result;
+}
+
+async function main() {
+ const source = new URL("./api.yaml", import.meta.url);
+ const dest = new URL("./src/api.ts", import.meta.url);
+ const nodes = await openapiTS(source, { defaultNonNullable: false });
+ const content = transform(COMMENT_HEADER + astToString(nodes));
+ fs.writeFileSync(dest, content);
+ console.log("api.yaml → src/api.ts");
}
main();
diff --git a/packages/openapi/package.json b/packages/openapi/package.json
index d9532166ec..93b98a832c 100644
--- a/packages/openapi/package.json
+++ b/packages/openapi/package.json
@@ -12,7 +12,7 @@
],
"scripts": {
"codegen": "pnpm run \"/^codegen:.*/\" && pnpm biome format --write src/",
- "codegen:api": "openapi-typescript ./api.yaml --default-non-nullable=false -o ./src/api.ts && node ./convert_types.js ./src/api.ts",
+ "codegen:api": "node ./convert_types.js",
"codegen:session": "openapi-typescript ../../marimo/_schemas/generated/session.yaml -o ./src/session.ts",
"codegen:notebook": "openapi-typescript ../../marimo/_schemas/generated/notebook.yaml -o ./src/notebook.ts"
},
diff --git a/packages/openapi/src/api.ts b/packages/openapi/src/api.ts
index 1a8c73239e..42495a7b53 100644
--- a/packages/openapi/src/api.ts
+++ b/packages/openapi/src/api.ts
@@ -3,6 +3,9 @@
* Do not make direct changes to the file.
*/
+/** Branded string type — compile-time only. */
+type TypedString<T extends string> = string & { __type__: T };
+
export interface paths {
"/@file/{filename_and_length}": {
parameters: {
@@ -3388,6 +3391,7 @@ export interface components {
/** @default null */
variant?: "danger" | null;
};
+ Base64String: TypedString<"Base64String">;
/** BaseResponse */
BaseResponse: {
success: boolean;
@@ -3477,6 +3481,7 @@ export interface components {
/** @default false */
hide_code?: boolean;
};
+ CellId: TypedString<"CellId">;
/**
* CellNotification
* @description Updates a cell's state in the frontend.
@@ -3495,7 +3500,7 @@ export interface components {
* timestamp: Creation timestamp, auto-set.
*/
CellNotification: {
- cell_id: string;
+ cell_id: components["schemas"]["CellId"];
/** @default null */
console?:
| components["schemas"]["CellOutput"][]
@@ -3633,7 +3638,7 @@ export interface components {
CodeCompletionCommand: {
cellId: string;
document: string;
- id: string;
+ id: components["schemas"]["RequestId"];
/** @enum {unknown} */
type: "code-completion";
};
@@ -3641,7 +3646,7 @@ export interface components {
CodeCompletionRequest: {
cellId: string;
document: string;
- id: string;
+ id: components["schemas"]["RequestId"];
};
/**
* ColumnStats
@@ -3855,7 +3860,7 @@ export interface components {
DataTable: {
columns: components["schemas"]["DataTableColumn"][];
/** @default null */
- engine?: string | null;
+ engine?: components["schemas"]["VariableName"] | null;
/** @default null */
indexes?: string[] | null;
name: string;
@@ -3871,7 +3876,7 @@ export interface components {
* @enum {unknown}
*/
type?: "table" | "view";
- variable_name: string | null;
+ variable_name: components["schemas"]["VariableName"] | null;
};
/**
* DataTableColumn
@@ -3911,7 +3916,7 @@ export interface components {
Database: {
dialect: string;
/** @default null */
- engine?: string | null;
+ engine?: components["schemas"]["VariableName"] | null;
name: string;
schemas: components["schemas"]["Schema"][];
};
@@ -4307,7 +4312,7 @@ export interface components {
* cell_id: Cell to focus.
*/
FocusCellNotification: {
- cell_id: string;
+ cell_id: components["schemas"]["CellId"];
/** @enum {unknown} */
op: "focus-cell";
};
@@ -4349,7 +4354,7 @@ export interface components {
* status: Human-readable success/failure status.
*/
FunctionCallResultNotification: {
- function_call_id: string;
+ function_call_id: components["schemas"]["RequestId"];
/** @enum {unknown} */
op: "function-call-result";
return_value: unknown;
@@ -4623,7 +4628,7 @@ export interface components {
/** @default false */
auto_instantiated?: boolean;
capabilities: components["schemas"]["KernelCapabilitiesNotification"];
- cell_ids: string[];
+ cell_ids: components["schemas"]["CellId"][];
codes: string[];
configs: components["schemas"]["CellConfig"][];
kiosk: boolean;
@@ -4948,16 +4953,16 @@ export interface components {
};
/** MarimoAncestorPreventedError */
MarimoAncestorPreventedError: {
- blamed_cell: string | null;
+ blamed_cell: components["schemas"]["CellId"] | null;
msg: string;
- raising_cell: string;
+ raising_cell: components["schemas"]["CellId"];
/** @enum {unknown} */
type: "ancestor-prevented";
};
/** MarimoAncestorStoppedError */
MarimoAncestorStoppedError: {
msg: string;
- raising_cell: string;
+ raising_cell: components["schemas"]["CellId"];
/** @enum {unknown} */
type: "ancestor-stopped";
};
@@ -4988,7 +4993,7 @@ export interface components {
MarimoExceptionRaisedError: {
exception_type: string;
msg: string;
- raising_cell: string | null;
+ raising_cell: components["schemas"]["CellId"] | null;
/** @enum {unknown} */
type: "exception";
};
@@ -5045,7 +5050,7 @@ export interface components {
};
/** MarimoStrictExecutionError */
MarimoStrictExecutionError: {
- blamed_cell: string | null;
+ blamed_cell: components["schemas"]["CellId"] | null;
msg: string;
ref: string;
/** @enum {unknown} */
@@ -5102,7 +5107,7 @@ export interface components {
* token: Unique identifier for deduplication across dual queues.
*/
ModelCommand: {
- buffers: string[];
+ buffers: components["schemas"]["Base64String"][];
message:
| components["schemas"]["ModelUpdateMessage"]
| components["schemas"]["ModelCustomMessage"];
@@ -5116,7 +5121,7 @@ export interface components {
* @description Custom application message.
*/
ModelCustom: {
- buffers: string[];
+ buffers: components["schemas"]["Base64String"][];
content: unknown;
/** @enum {unknown} */
method: "custom";
@@ -5159,14 +5164,14 @@ export interface components {
*/
ModelOpen: {
buffer_paths: (string | number)[][];
- buffers: string[];
+ buffers: components["schemas"]["Base64String"][];
/** @enum {unknown} */
method: "open";
state: Record<string, any>;
};
/** ModelRequest */
ModelRequest: {
- buffers: string[];
+ buffers: components["schemas"]["Base64String"][];
message:
| components["schemas"]["ModelUpdateMessage"]
| components["schemas"]["ModelCustomMessage"];
@@ -5179,7 +5184,7 @@ export interface components {
*/
ModelUpdate: {
buffer_paths: (string | number)[][];
- buffers: string[];
+ buffers: components["schemas"]["Base64String"][];
/** @enum {unknown} */
method: "update";
state: Record<string, any>;
@@ -5200,7 +5205,7 @@ export interface components {
};
/** MultipleDefinitionError */
MultipleDefinitionError: {
- cells: string[];
+ cells: components["schemas"]["CellId"][];
name: string;
/** @enum {unknown} */
type: "multiple-defs";
@@ -5476,7 +5481,7 @@ export interface components {
* cell_id: Cell whose UI elements should be removed.
*/
RemoveUIElementsNotification: {
- cell_id: string;
+ cell_id: components["schemas"]["CellId"];
/** @enum {unknown} */
op: "remove-ui-elements";
};
@@ -5498,6 +5503,7 @@ export interface components {
RenameNotebookRequest: {
filename: string;
};
+ RequestId: TypedString<"RequestId">;
/** RunningNotebooksResponse */
RunningNotebooksResponse: {
files: components["schemas"]["MarimoFile"][];
@@ -5603,7 +5609,7 @@ export interface components {
metadata: components["schemas"]["SQLMetadata"];
/** @enum {unknown} */
op: "sql-table-list-preview";
- request_id: string;
+ request_id: components["schemas"]["RequestId"];
/** @default [] */
tables?: components["schemas"]["DataTable"][];
};
@@ -5623,7 +5629,7 @@ export interface components {
metadata: components["schemas"]["SQLMetadata"];
/** @enum {unknown} */
op: "sql-table-preview";
- request_id: string;
+ request_id: components["schemas"]["RequestId"];
table: null | components["schemas"]["DataTable"];
};
/** SaveAppConfigurationRequest */
@@ -5689,7 +5695,7 @@ export interface components {
SecretKeysResultNotification: {
/** @enum {unknown} */
op: "secret-keys-result";
- request_id: string;
+ request_id: components["schemas"]["RequestId"];
secrets: components["schemas"]["SecretKeysWithProvider"][];
};
/** SecretKeysWithProvider */
@@ -5717,6 +5723,7 @@ export interface components {
disable_file_downloads?: boolean;
follow_symlink: boolean;
};
+ SessionId: TypedString<"SessionId">;
/** SetupRootError */
SetupRootError: {
edges_with_vars: [string, string[], string][];
@@ -5985,7 +5992,7 @@ export interface components {
/** @enum {unknown} */
backendType: "fsspec" | "obstore";
displayName: string;
- name: string;
+ name: components["schemas"]["VariableName"];
protocol: string;
rootPath: string;
storageEntries: components["schemas"]["StorageEntry"][];
@@ -6061,6 +6068,7 @@ export interface components {
TyLanguageServerConfig: {
enabled?: boolean;
};
+ UIElementId: `${components["schemas"]["CellId"]}-${string}`;
/**
* UIElementMessageNotification
* @description Sends a message to a UI element/widget.
@@ -6072,11 +6080,11 @@ export interface components {
*/
UIElementMessageNotification: {
/** @default null */
- buffers?: string[] | null;
+ buffers?: components["schemas"]["Base64String"][] | null;
message: Record<string, any>;
/** @enum {unknown} */
op: "send-ui-element-message";
- ui_element: string;
+ ui_element: components["schemas"]["UIElementId"];
};
/** UnknownError */
UnknownError: {
@@ -6098,7 +6106,7 @@ export interface components {
* configs: Cell configs for each cell (optional, for file reload).
*/
UpdateCellCodesNotification: {
- cell_ids: string[];
+ cell_ids: components["schemas"]["CellId"][];
code_is_stale: boolean;
codes: string[];
/** @default [] */
@@ -6139,7 +6147,7 @@ export interface components {
* cell_ids: Complete ordered list of cell IDs.
*/
UpdateCellIdsNotification: {
- cell_ids: string[];
+ cell_ids: components["schemas"]["CellId"][];
/** @enum {unknown} */
op: "update-cell-ids";
};
@@ -6306,10 +6314,11 @@ export interface components {
* used_by: Cell IDs that use this variable.
*/
VariableDeclarationNotification: {
- declared_by: string[];
+ declared_by: components["schemas"]["CellId"][];
name: string;
- used_by: string[];
+ used_by: components["schemas"]["CellId"][];
};
+ VariableName: TypedString<"VariableName">;
/**
* VariableValue
* @description Variable value and type for variables panel.
@@ -6366,6 +6375,7 @@ export interface components {
path?: string;
writable?: boolean;
};
+ WidgetModelId: TypedString<"WidgetModelId">;
/** WorkspaceFilesRequest */
WorkspaceFilesRequest: {
/** @default false */