A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
refactor: clean up frontend API and schema conventions (#11449)
Kiran Gadhave3158431af3a1
diff --git a/frontend/src/components/data-table/__tests__/chart-spec-model.test.ts b/frontend/src/components/data-table/__tests__/chart-spec-model.test.tsindex ff4f5c9194..37dd79aaa6 100644--- a/frontend/src/components/data-table/__tests__/chart-spec-model.test.ts+++ b/frontend/src/components/data-table/__tests__/chart-spec-model.test.ts@@ -60,14 +60,14 @@ describe("ColumnChartSpecModel", () => {};it("should create an instance", () => {- const model = new ColumnChartSpecModel(- [],- mockFieldTypes,- mockStats,- mockBinValues,- mockValueCounts,- { includeCharts: true },- );+ const model = new ColumnChartSpecModel({+ data: [],+ fieldTypes: mockFieldTypes,+ stats: mockStats,+ binValues: mockBinValues,+ valueCounts: mockValueCounts,+ opts: { includeCharts: true },+ });expect(model).toBeInstanceOf(ColumnChartSpecModel);});@@ -77,14 +77,14 @@ describe("ColumnChartSpecModel", () => {});it("should return header summary with spec when includeCharts is true", () => {- const model = new ColumnChartSpecModel(- [],- mockFieldTypes,- mockStats,- mockBinValues,- mockValueCounts,- { includeCharts: true },- );+ const model = new ColumnChartSpecModel({+ data: [],+ fieldTypes: mockFieldTypes,+ stats: mockStats,+ binValues: mockBinValues,+ valueCounts: mockValueCounts,+ opts: { includeCharts: true },+ });const dateSummary = model.getHeaderSummary("date");expect(dateSummary.stats).toEqual(mockStats.date);expect(dateSummary.type).toBe("date");@@ -92,14 +92,14 @@ describe("ColumnChartSpecModel", () => {});it("should return header summary without spec when includeCharts is false", () => {- const model = new ColumnChartSpecModel(- [],- mockFieldTypes,- mockStats,- mockBinValues,- mockValueCounts,- { includeCharts: false },- );+ const model = new ColumnChartSpecModel({+ data: [],+ fieldTypes: mockFieldTypes,+ stats: mockStats,+ binValues: mockBinValues,+ valueCounts: mockValueCounts,+ opts: { includeCharts: false },+ });const numberSummary = model.getHeaderSummary("number");expect(numberSummary.stats).toEqual(mockStats.number);expect(numberSummary.type).toBe("number");@@ -107,14 +107,14 @@ describe("ColumnChartSpecModel", () => {});it("should return null spec for unknown types", () => {- const model = new ColumnChartSpecModel(- [],- mockFieldTypes,- mockStats,- mockBinValues,- mockValueCounts,- { includeCharts: true },- );+ const model = new ColumnChartSpecModel({+ data: [],+ fieldTypes: mockFieldTypes,+ stats: mockStats,+ binValues: mockBinValues,+ valueCounts: mockValueCounts,+ opts: { includeCharts: true },+ });const unknownSummary = model.getHeaderSummary("unknown");expect(unknownSummary.spec).toBeNull();});@@ -133,14 +133,14 @@ describe("ColumnChartSpecModel", () => {{ bin_start: "2023-06-01", bin_end: "2023-12-31", count: 20 },],};- const model = new ColumnChartSpecModel(- [],- specialFieldTypes,- specialStats,- specialBinValues,- mockValueCounts,- { includeCharts: true },- );+ const model = new ColumnChartSpecModel({+ data: [],+ fieldTypes: specialFieldTypes,+ stats: specialStats,+ binValues: specialBinValues,+ valueCounts: mockValueCounts,+ opts: { includeCharts: true },+ });const summary = model.getHeaderSummary("column.with[special:chars]");expect(summary.spec).toBeDefined();expect(@@ -150,14 +150,14 @@ describe("ColumnChartSpecModel", () => {});it("should expect bin values to be used for number and integer columns", () => {- const model = new ColumnChartSpecModel(- [],- mockFieldTypes,- mockStats,- mockBinValues,- mockValueCounts,- { includeCharts: true },- );+ const model = new ColumnChartSpecModel({+ data: [],+ fieldTypes: mockFieldTypes,+ stats: mockStats,+ binValues: mockBinValues,+ valueCounts: mockValueCounts,+ opts: { includeCharts: true },+ });const summary = model.getHeaderSummary("number");expect(summary.spec).toBeDefined();// @ts-expect-error data.values should be available@@ -185,14 +185,14 @@ describe("ColumnChartSpecModel", () => {const allNullBins: Record<ColumnName, BinValues> = {number: [],};- const model = new ColumnChartSpecModel(- [],- mockFieldTypes,- allNullStats,- allNullBins,- {},- { includeCharts: true },- );+ const model = new ColumnChartSpecModel({+ data: [],+ fieldTypes: mockFieldTypes,+ stats: allNullStats,+ binValues: allNullBins,+ valueCounts: {},+ opts: { includeCharts: true },+ });const summary = model.getHeaderSummary("number");expect(summary.spec).toBeDefined();// @ts-expect-error hconcat should be available@@ -221,14 +221,14 @@ describe("ColumnChartSpecModel", () => {const stats: Record<ColumnName, Partial<ColumnHeaderStats>> = {number: { nulls: 12, total: 12 },};- const model = new ColumnChartSpecModel(- [],- mockFieldTypes,+ const model = new ColumnChartSpecModel({+ data: [],+ fieldTypes: mockFieldTypes,stats,- nanOnlyBins,- {},- { includeCharts: true },- );+ binValues: nanOnlyBins,+ valueCounts: {},+ opts: { includeCharts: true },+ });const first = model.getHeaderSummary("number");const second = model.getHeaderSummary("number");// All NaN bins are invalid → null-only chart@@ -241,14 +241,14 @@ describe("ColumnChartSpecModel", () => {});it("should render a null bar for all-null temporal columns", () => {- const model = new ColumnChartSpecModel(- [],- mockFieldTypes,- { datetime: { nulls: 12, total: 12 } },- { datetime: [] },- {},- { includeCharts: true },- );+ const model = new ColumnChartSpecModel({+ data: [],+ fieldTypes: mockFieldTypes,+ stats: { datetime: { nulls: 12, total: 12 } },+ binValues: { datetime: [] },+ valueCounts: {},+ opts: { includeCharts: true },+ });const summary = model.getHeaderSummary("datetime");expect(summary.spec).toBeDefined();// @ts-expect-error data.values@@ -265,26 +265,26 @@ describe("ColumnChartSpecModel", () => {});it("should return null when numeric bins are empty and there are no nulls", () => {- const model = new ColumnChartSpecModel(- [],- mockFieldTypes,- { number: { min: 0, max: 1 } },- { number: [] },- {},- { includeCharts: true },- );+ const model = new ColumnChartSpecModel({+ data: [],+ fieldTypes: mockFieldTypes,+ stats: { number: { min: 0, max: 1 } },+ binValues: { number: [] },+ valueCounts: {},+ opts: { includeCharts: true },+ });expect(model.getHeaderSummary("number").spec).toBeNull();});it("should handle datetime bin values", () => {- const model = new ColumnChartSpecModel(- [],- mockFieldTypes,- mockStats,- mockBinValues,- mockValueCounts,- { includeCharts: true },- );+ const model = new ColumnChartSpecModel({+ data: [],+ fieldTypes: mockFieldTypes,+ stats: mockStats,+ binValues: mockBinValues,+ valueCounts: mockValueCounts,+ opts: { includeCharts: true },+ });const summary = model.getHeaderSummary("datetime");expect(summary.spec).toBeDefined();@@ -301,14 +301,14 @@ describe("ColumnChartSpecModel", () => {...mockStats,datetime: { min: "2023-01-01", max: "2023-12-31" },};- const model2 = new ColumnChartSpecModel(- [],- mockFieldTypes,- mockStats2,- mockBinValues,- mockValueCounts,- { includeCharts: true },- );+ const model2 = new ColumnChartSpecModel({+ data: [],+ fieldTypes: mockFieldTypes,+ stats: mockStats2,+ binValues: mockBinValues,+ valueCounts: mockValueCounts,+ opts: { includeCharts: true },+ });const summary2 = model2.getHeaderSummary("datetime");expect(summary2.spec).toBeDefined();@@ -318,14 +318,14 @@ describe("ColumnChartSpecModel", () => {});it("should handle boolean stats", () => {- const model = new ColumnChartSpecModel(- [],- mockFieldTypes,- mockStats,- mockBinValues,- mockValueCounts,- { includeCharts: true },- );+ const model = new ColumnChartSpecModel({+ data: [],+ fieldTypes: mockFieldTypes,+ stats: mockStats,+ binValues: mockBinValues,+ valueCounts: mockValueCounts,+ opts: { includeCharts: true },+ });const summary = model.getHeaderSummary("boolean");expect(summary.spec).toBeDefined();// @ts-expect-error data.values should be available@@ -340,14 +340,14 @@ describe("ColumnChartSpecModel", () => {});it("should handle string value counts", () => {- const model = new ColumnChartSpecModel(- [],- mockFieldTypes,- mockStats,- mockBinValues,- mockValueCounts,- { includeCharts: true },- );+ const model = new ColumnChartSpecModel({+ data: [],+ fieldTypes: mockFieldTypes,+ stats: mockStats,+ binValues: mockBinValues,+ valueCounts: mockValueCounts,+ opts: { includeCharts: true },+ });const summary = model.getHeaderSummary("string");expect(summary.spec).toBeDefined();// @ts-expect-error data.values should be available@@ -374,64 +374,64 @@ describe("ColumnChartSpecModel", () => {]);it("url data", () => {- const model = new ColumnChartSpecModel(- mockData,+ const model = new ColumnChartSpecModel({+ data: mockData,fieldTypes,- mockStats,- mockBinValues,- mockValueCounts,- { includeCharts: true },- );+ stats: mockStats,+ binValues: mockBinValues,+ valueCounts: mockValueCounts,+ opts: { includeCharts: true },+ });expect(model.getHeaderSummary("date").spec).toMatchSnapshot();});it("csv data", () => {- const model = new ColumnChartSpecModel(- `data:text/csv;base64,${btoa("a,b,c\n1,2,3\n4,5,6")}`,+ const model = new ColumnChartSpecModel({+ data: `data:text/csv;base64,${btoa("a,b,c\n1,2,3\n4,5,6")}`,fieldTypes,- mockStats,- mockBinValues,- mockValueCounts,- { includeCharts: true },- );+ stats: mockStats,+ binValues: mockBinValues,+ valueCounts: mockValueCounts,+ opts: { includeCharts: true },+ });expect(model.getHeaderSummary("a").spec).toMatchSnapshot();});it("csv string", () => {- const model = new ColumnChartSpecModel(- "a,b,c\n1,2,3\n4,5,6",+ const model = new ColumnChartSpecModel({+ data: "a,b,c\n1,2,3\n4,5,6",fieldTypes,- mockStats,- mockBinValues,- mockValueCounts,- { includeCharts: true },- );+ stats: mockStats,+ binValues: mockBinValues,+ valueCounts: mockValueCounts,+ opts: { includeCharts: true },+ });expect(model.getHeaderSummary("a").spec).toMatchSnapshot();});it("array", () => {- const model = new ColumnChartSpecModel(- ["a", "b", "c"],+ const model = new ColumnChartSpecModel({+ data: ["a", "b", "c"],fieldTypes,- mockStats,- mockBinValues,- mockValueCounts,- { includeCharts: true },- );+ stats: mockStats,+ binValues: mockBinValues,+ valueCounts: mockValueCounts,+ opts: { includeCharts: true },+ });expect(model.getHeaderSummary("a").spec).toMatchSnapshot();});});describe("file URL handling", () => {it("should handle marimo file URLs with ./@file prefix", () => {- const model = new ColumnChartSpecModel(- "./@file/data.csv",- mockFieldTypes,- mockStats,- mockBinValues,- mockValueCounts,- { includeCharts: true },- );+ const model = new ColumnChartSpecModel({+ data: "./@file/data.csv",+ fieldTypes: mockFieldTypes,+ stats: mockStats,+ binValues: mockBinValues,+ valueCounts: mockValueCounts,+ opts: { includeCharts: true },+ });const summary = model.getHeaderSummary("date");expect(summary.spec).toBeDefined();@@ -440,14 +440,14 @@ describe("ColumnChartSpecModel", () => {});it("should handle marimo file URLs with /@file prefix", () => {- const model = new ColumnChartSpecModel(- "/@file/data.csv",- mockFieldTypes,- mockStats,- mockBinValues,- mockValueCounts,- { includeCharts: true },- );+ const model = new ColumnChartSpecModel({+ data: "/@file/data.csv",+ fieldTypes: mockFieldTypes,+ stats: mockStats,+ binValues: mockBinValues,+ valueCounts: mockValueCounts,+ opts: { includeCharts: true },+ });const summary = model.getHeaderSummary("date");expect(summary.spec).toBeDefined();@@ -456,14 +456,14 @@ describe("ColumnChartSpecModel", () => {});it("should handle absolute HTTP URLs", () => {- const model = new ColumnChartSpecModel(- "https://external.com/data.csv",- mockFieldTypes,- mockStats,- mockBinValues,- mockValueCounts,- { includeCharts: true },- );+ const model = new ColumnChartSpecModel({+ data: "https://external.com/data.csv",+ fieldTypes: mockFieldTypes,+ stats: mockStats,+ binValues: mockBinValues,+ valueCounts: mockValueCounts,+ opts: { includeCharts: true },+ });const summary = model.getHeaderSummary("date");expect(summary.spec).toBeDefined();@@ -473,14 +473,14 @@ describe("ColumnChartSpecModel", () => {it("should handle data URLs", () => {const dataUrl = "data:text/csv;base64,YSxiLGMKMSwyLDMKNCw1LDY=";- const model = new ColumnChartSpecModel(- dataUrl,- mockFieldTypes,- mockStats,- mockBinValues,- mockValueCounts,- { includeCharts: true },- );+ const model = new ColumnChartSpecModel({+ data: dataUrl,+ fieldTypes: mockFieldTypes,+ stats: mockStats,+ binValues: mockBinValues,+ valueCounts: mockValueCounts,+ opts: { includeCharts: true },+ });const summary = model.getHeaderSummary("date");expect(summary.spec).toBeDefined();@@ -491,14 +491,14 @@ describe("ColumnChartSpecModel", () => {it("should handle CSV string data", () => {const csvString = "a,b,c\n1,2,3\n4,5,6";- const model = new ColumnChartSpecModel(- csvString,- mockFieldTypes,- mockStats,- mockBinValues,- mockValueCounts,- { includeCharts: true },- );+ const model = new ColumnChartSpecModel({+ data: csvString,+ fieldTypes: mockFieldTypes,+ stats: mockStats,+ binValues: mockBinValues,+ valueCounts: mockValueCounts,+ opts: { includeCharts: true },+ });const summary = model.getHeaderSummary("date");expect(summary.spec).toBeDefined();@@ -509,14 +509,14 @@ describe("ColumnChartSpecModel", () => {it("should handle arrow data", () => {const arrowData = "ARROW1\n";- const model = new ColumnChartSpecModel(- `data:text/plain;base64,${btoa(arrowData)}`,- mockFieldTypes,- mockStats,- mockBinValues,- mockValueCounts,- { includeCharts: true },- );+ const model = new ColumnChartSpecModel({+ data: `data:text/plain;base64,${btoa(arrowData)}`,+ fieldTypes: mockFieldTypes,+ stats: mockStats,+ binValues: mockBinValues,+ valueCounts: mockValueCounts,+ opts: { includeCharts: true },+ });const spec = model.getHeaderSummary("date").spec;expect(spec).toMatchSnapshot();expect(spec?.data?.format?.type).toBe("arrow");@@ -529,14 +529,14 @@ describe("ColumnChartSpecModel", () => {{ a: 1, b: 2, c: 3 },{ a: 4, b: 5, c: 6 },];- const model = new ColumnChartSpecModel(- arrayData,- mockFieldTypes,- mockStats,- mockBinValues,- mockValueCounts,- { includeCharts: true },- );+ const model = new ColumnChartSpecModel({+ data: arrayData,+ fieldTypes: mockFieldTypes,+ stats: mockStats,+ binValues: mockBinValues,+ valueCounts: mockValueCounts,+ opts: { includeCharts: true },+ });const summary = model.getHeaderSummary("date");expect(summary.spec).toBeDefined();diff --git a/frontend/src/components/data-table/charts/__tests__/spec-snapshot.test.ts b/frontend/src/components/data-table/charts/__tests__/spec-snapshot.test.tsindex da66e827f1..8f12a183b7 100644--- a/frontend/src/components/data-table/charts/__tests__/spec-snapshot.test.ts+++ b/frontend/src/components/data-table/charts/__tests__/spec-snapshot.test.ts@@ -39,13 +39,13 @@ describe("create vega spec", () => {});it("should create and augment a spec", () => {- const spec = createSpecWithoutData(- ChartType.BAR,- createBasicFormValues(),- "light",- 400,- 300,- );+ const spec = createSpecWithoutData({+ chartType: ChartType.BAR,+ formValues: createBasicFormValues(),+ theme: "light",+ width: 400,+ height: 300,+ });expect(spec).toMatchSnapshot();expect(typeof spec !== "string").toBe(true); // Not error messageexpect((spec as TopLevelSpec).data).toEqual({ values: [] });@@ -59,25 +59,25 @@ describe("create vega spec", () => {const formValues = createBasicFormValues();formValues.general!.xColumn!.field = undefined;- const spec = createSpecWithoutData(- ChartType.BAR,+ const spec = createSpecWithoutData({+ chartType: ChartType.BAR,formValues,- "light",- 400,- 300,- );+ theme: "light",+ width: 400,+ height: 300,+ });expect(spec).toEqual(X_AXIS_REQUIRED);// Undefined yColumnconst formValues2 = createBasicFormValues();formValues2.general!.yColumn!.field = undefined;- const spec2 = createSpecWithoutData(- ChartType.BAR,- formValues2,- "light",- 400,- 300,- );+ const spec2 = createSpecWithoutData({+ chartType: ChartType.BAR,+ formValues: formValues2,+ theme: "light",+ width: 400,+ height: 300,+ });expect(spec2).toEqual(Y_AXIS_REQUIRED);});});diff --git a/frontend/src/components/data-table/charts/__tests__/spec.test.ts b/frontend/src/components/data-table/charts/__tests__/spec.test.tsindex 2ff861864c..5a78709cb8 100644--- a/frontend/src/components/data-table/charts/__tests__/spec.test.ts+++ b/frontend/src/components/data-table/charts/__tests__/spec.test.ts@@ -29,10 +29,12 @@ describe("getAxisEncoding", () => {aggregate: "sum",timeUnit: undefined,},- { binned: true, step: 10 },- COUNT_FIELD,- true,- ChartType.BAR,+ {+ binValues: { binned: true, step: 10 },+ label: COUNT_FIELD,+ stack: true,+ chartType: ChartType.BAR,+ },);expect(result).toEqual({@@ -52,10 +54,12 @@ describe("getAxisEncoding", () => {aggregate: "mean",timeUnit: undefined,},- undefined,- "Average Price",- false,- ChartType.BAR,+ {+ binValues: undefined,+ label: "Average Price",+ stack: false,+ chartType: ChartType.BAR,+ },);expect(result).toEqual({@@ -79,10 +83,12 @@ describe("getAxisEncoding", () => {aggregate: NONE_VALUE,timeUnit,},- undefined,- "Date",- undefined,- ChartType.LINE,+ {+ binValues: undefined,+ label: "Date",+ stack: undefined,+ chartType: ChartType.LINE,+ },);expect(result).toEqual({@@ -105,10 +111,12 @@ describe("getAxisEncoding", () => {aggregate: NONE_VALUE,timeUnit: undefined,},- undefined,- "Category",- true,- ChartType.BAR,+ {+ binValues: undefined,+ label: "Category",+ stack: true,+ chartType: ChartType.BAR,+ },);expect(result).toEqual({@@ -129,10 +137,12 @@ describe("getAxisEncoding", () => {aggregate: "sum",timeUnit: undefined,},- undefined,- "Value",- false,- ChartType.BAR,+ {+ binValues: undefined,+ label: "Value",+ stack: false,+ chartType: ChartType.BAR,+ },);expect((result as { bin?: unknown }).bin).toBeUndefined();@@ -146,10 +156,12 @@ describe("getAxisEncoding", () => {aggregate: "sum",timeUnit: undefined,},- undefined,- undefined,- false,- ChartType.BAR,+ {+ binValues: undefined,+ label: undefined,+ stack: false,+ chartType: ChartType.BAR,+ },);expect((result as { title?: string }).title).toBeUndefined();@@ -164,10 +176,12 @@ describe("getAxisEncoding", () => {aggregate: agg,timeUnit: undefined,},- undefined,- "Value",- false,- ChartType.BAR,+ {+ binValues: undefined,+ label: "Value",+ stack: false,+ chartType: ChartType.BAR,+ },);const expectedAggregate = (result as { aggregate?: string }).aggregate;@@ -189,10 +203,12 @@ describe("getAxisEncoding", () => {aggregate: agg,timeUnit: undefined,},- undefined,- "Date",- false,- ChartType.BAR,+ {+ binValues: undefined,+ label: "Date",+ stack: false,+ chartType: ChartType.BAR,+ },);const expectedAggregate = (result as { aggregate?: string }).aggregate;@@ -209,10 +225,12 @@ describe("getAxisEncoding", () => {sort: sort as "ascending" | "descending",aggregate: NONE_VALUE,},- undefined,- "Value",- false,- ChartType.BAR,+ {+ binValues: undefined,+ label: "Value",+ stack: false,+ chartType: ChartType.BAR,+ },);const expectedSort = (result as { sort?: string }).sort;@@ -1009,10 +1027,12 @@ describe("Special character escaping in specs", () => {aggregate: "sum",timeUnit: undefined,},- undefined,- "Value",- false,- ChartType.BAR,+ {+ binValues: undefined,+ label: "Value",+ stack: false,+ chartType: ChartType.BAR,+ },);invariant("field" in result, "field should be defined");@@ -1027,10 +1047,12 @@ describe("Special character escaping in specs", () => {aggregate: "mean",timeUnit: undefined,},- undefined,- "Data",- false,- ChartType.BAR,+ {+ binValues: undefined,+ label: "Data",+ stack: false,+ chartType: ChartType.BAR,+ },);invariant("field" in result, "field should be defined");@@ -1045,10 +1067,12 @@ describe("Special character escaping in specs", () => {aggregate: NONE_VALUE,timeUnit: "yearmonth",},- undefined,- "Timestamp",- false,- ChartType.LINE,+ {+ binValues: undefined,+ label: "Timestamp",+ stack: false,+ chartType: ChartType.LINE,+ },);invariant("field" in result, "field should be defined");@@ -1063,10 +1087,12 @@ describe("Special character escaping in specs", () => {aggregate: "sum",timeUnit: undefined,},- undefined,- "Result",- false,- ChartType.BAR,+ {+ binValues: undefined,+ label: "Result",+ stack: false,+ chartType: ChartType.BAR,+ },);invariant("field" in result, "field should be defined");diff --git a/frontend/src/components/data-table/charts/chart-spec/spec.ts b/frontend/src/components/data-table/charts/chart-spec/spec.tsindex 115c15f8d8..d8d3a9d44d 100644--- a/frontend/src/components/data-table/charts/chart-spec/spec.ts+++ b/frontend/src/components/data-table/charts/chart-spec/spec.ts@@ -51,13 +51,19 @@ export type ErrorMessage = TypedString<"ErrorMessage">;export const X_AXIS_REQUIRED = "X-axis column is required" as ErrorMessage;export const Y_AXIS_REQUIRED = "Y-axis column is required" as ErrorMessage;-export function createSpecWithoutData(- chartType: ChartType,- formValues: ChartSchemaType,- theme: ResolvedTheme,- width: number | "container",- height: number,-): TopLevelSpec | ErrorMessage {+export function createSpecWithoutData({+ chartType,+ formValues,+ theme,+ width,+ height,+}: {+ chartType: ChartType;+ formValues: ChartSchemaType;+ theme: ResolvedTheme;+ width: number | "container";+ height: number;+}): TopLevelSpec | ErrorMessage {const {xColumn,yColumn,@@ -85,27 +91,25 @@ export function createSpecWithoutData(const yEncodingKey = "y";// Create encodings- const xEncoding = getAxisEncoding(- xColumn,- formValues.xAxis?.bin,- getFieldLabel(formValues.xAxis?.label),- colorByColumn?.field && horizontal ? stacking : undefined,+ const xEncoding = getAxisEncoding(xColumn, {+ binValues: formValues.xAxis?.bin,+ label: getFieldLabel(formValues.xAxis?.label),+ stack: colorByColumn?.field && horizontal ? stacking : undefined,chartType,- );+ });let defaultYAggregation: ValidAggregationFn = DEFAULT_AGGREGATION;if (yColumn?.selectedDataType === "string") {defaultYAggregation = "count";}- const yEncoding = getAxisEncoding(- yColumn,- formValues.yAxis?.bin,- getFieldLabel(formValues.yAxis?.label),- colorByColumn?.field && !horizontal ? stacking : undefined,+ const yEncoding = getAxisEncoding(yColumn, {+ binValues: formValues.yAxis?.bin,+ label: getFieldLabel(formValues.yAxis?.label),+ stack: colorByColumn?.field && !horizontal ? stacking : undefined,chartType,- defaultYAggregation,- );+ defaultAggregate: defaultYAggregation,+ });const rowFacet = facet?.row.field? getFacetEncoding(facet.row, chartType)@@ -115,14 +119,14 @@ export function createSpecWithoutData(: undefined;const colorByEncoding = getColorEncoding(chartType, formValues);- const baseSpec = getBaseSpec(+ const baseSpec = getBaseSpec({chartType,formValues,theme,width,height,title,- );+ });const baseEncoding: Encoding<Field> = {[xEncodingKey]: horizontal ? yEncoding : xEncoding,[yEncodingKey]: horizontal ? xEncoding : yEncoding,@@ -160,11 +164,19 @@ export function augmentSpecWithData(export function getAxisEncoding(column: NonNullable<z.infer<typeof AxisSchema>>,- binValues: z.infer<typeof BinSchema> | undefined,- label: string | undefined,- stack: boolean | undefined,- chartType: ChartType,- defaultAggregate?: ValidAggregationFn,+ {+ binValues,+ label,+ stack,+ chartType,+ defaultAggregate,+ }: {+ binValues: z.infer<typeof BinSchema> | undefined;+ label: string | undefined;+ stack: boolean | undefined;+ chartType: ChartType;+ defaultAggregate?: ValidAggregationFn;+ },): PositionDef<string> {const selectedDataType = column.selectedDataType || "string";@@ -236,13 +248,12 @@ function getPieChartSpec(return "Size by column is required" as ErrorMessage;}- const thetaEncoding: PolarDef<string> = getAxisEncoding(- yColumn,- formValues.xAxis?.bin,- getFieldLabel(formValues.xAxis?.label),- undefined,- ChartType.PIE,- );+ const thetaEncoding: PolarDef<string> = getAxisEncoding(yColumn, {+ binValues: formValues.xAxis?.bin,+ label: getFieldLabel(formValues.xAxis?.label),+ stack: undefined,+ chartType: ChartType.PIE,+ });const colorEncoding: ColorDef<string> = {field: escapeFieldName(colorByColumn.field),@@ -252,7 +263,14 @@ function getPieChartSpec(};return {- ...getBaseSpec(ChartType.PIE, formValues, theme, width, height, title),+ ...getBaseSpec({+ chartType: ChartType.PIE,+ formValues,+ theme,+ width,+ height,+ title,+ }),mark: {type: convertChartTypeToMark(ChartType.PIE),innerRadius: formValues.style?.innerRadius,@@ -270,14 +288,21 @@ function getPieChartSpec(};}-function getBaseSpec(- chartType: ChartType,- formValues: ChartSchemaType,- theme: ResolvedTheme,- width: number | "container",- height: number,- title?: string,-): BaseSpec {+function getBaseSpec({+ chartType,+ formValues,+ theme,+ width,+ height,+ title,+}: {+ chartType: ChartType;+ formValues: ChartSchemaType;+ theme: ResolvedTheme;+ width: number | "container";+ height: number;+ title?: string;+}): BaseSpec {let gridLines = formValues.style?.gridLines ?? false;// Scatter charts have grid lines by defaultif (chartType === ChartType.SCATTER) {diff --git a/frontend/src/components/data-table/charts/charts.tsx b/frontend/src/components/data-table/charts/charts.tsxindex c2d239eaea..2a40c43323 100644--- a/frontend/src/components/data-table/charts/charts.tsx+++ b/frontend/src/components/data-table/charts/charts.tsx@@ -387,13 +387,13 @@ export const ChartPanel: React.FC<{// deeply partial, but the form always starts from complete defaults.const formValues = useWatch({ control: form.control }) as ChartSchemaType;- const specWithoutData = createSpecWithoutData(- selectedChartType,+ const specWithoutData = createSpecWithoutData({+ chartType: selectedChartType,formValues,theme,- "container",- CHART_HEIGHT,- );+ width: "container",+ height: CHART_HEIGHT,+ });// Prevent unnecessary re-renders of the chartconst memoizedChart = useMemo(() => {diff --git a/frontend/src/components/data-table/column-summary/chart-spec-model.tsx b/frontend/src/components/data-table/column-summary/chart-spec-model.tsxindex 452d8a1db5..3d318b8a5c 100644--- a/frontend/src/components/data-table/column-summary/chart-spec-model.tsx+++ b/frontend/src/components/data-table/column-summary/chart-spec-model.tsx@@ -119,16 +119,16 @@ export class ColumnChartSpecModel<T> {private columnBinValues = new Map<ColumnName, BinValues>();private columnValueCounts = new Map<ColumnName, ValueCounts>();- public static readonly EMPTY = new ColumnChartSpecModel(- [],- new Map(),- {},- {},- {},- {+ public static readonly EMPTY = new ColumnChartSpecModel({+ data: [],+ fieldTypes: new Map(),+ stats: {},+ binValues: {},+ valueCounts: {},+ opts: {includeCharts: false,},- );+ });private dataSpec: TopLevelSpec["data"];@@ -144,16 +144,23 @@ export class ColumnChartSpecModel<T> {includeCharts: boolean;};- public constructor(- data: T[] | string,- fieldTypes: FieldTypes,- stats: Record<ColumnName, Partial<ColumnHeaderStats>>,- binValues: Record<ColumnName, BinValues>,- valueCounts: Record<ColumnName, ValueCounts>,+ public constructor({+ data,+ fieldTypes,+ stats,+ binValues,+ valueCounts,+ opts,+ }: {+ data: T[] | string;+ fieldTypes: FieldTypes;+ stats: Record<ColumnName, Partial<ColumnHeaderStats>>;+ binValues: Record<ColumnName, BinValues>;+ valueCounts: Record<ColumnName, ValueCounts>;opts: {includeCharts: boolean;- },- ) {+ };+ }) {this.fieldTypes = fieldTypes;this.stats = stats;this.binValues = binValues;diff --git a/frontend/src/components/dependency-graph/dependency-graph-tree.tsx b/frontend/src/components/dependency-graph/dependency-graph-tree.tsxindex eaa313723f..99948abbf8 100644--- a/frontend/src/components/dependency-graph/dependency-graph-tree.tsx+++ b/frontend/src/components/dependency-graph/dependency-graph-tree.tsx@@ -85,13 +85,13 @@ export const DependencyGraphTree: React.FC<PropsWithChildren<Props>> = ({// oxlint-disable-next-line react/hook-use-stateconst [initial] = useState(() => {- const elements = elementsBuilder.createElements(+ const elements = elementsBuilder.createElements({cellIds,cellAtoms,variables,- settings.hidePureMarkdown,- settings.hideReusableFunctions,- );+ hidePureMarkdown: settings.hidePureMarkdown,+ hideReusableFunctions: settings.hideReusableFunctions,+ });return layoutElements({nodes: withExpansion(elements.nodes, expandedIds),edges: elements.edges,@@ -163,13 +163,13 @@ export const DependencyGraphTree: React.FC<PropsWithChildren<Props>> = ({// Rebuild + re-layout when the graph inputs or the expand/collapse set change.useEffect(() => {- const elements = elementsBuilder.createElements(+ const elements = elementsBuilder.createElements({cellIds,cellAtoms,variables,- settings.hidePureMarkdown,- settings.hideReusableFunctions,- );+ hidePureMarkdown: settings.hidePureMarkdown,+ hideReusableFunctions: settings.hideReusableFunctions,+ });syncChanges({nodes: withExpansion(elements.nodes, expandedIds),edges: elements.edges,diff --git a/frontend/src/components/dependency-graph/elements.ts b/frontend/src/components/dependency-graph/elements.tsindex abf457317b..ee371c8d47 100644--- a/frontend/src/components/dependency-graph/elements.ts+++ b/frontend/src/components/dependency-graph/elements.ts@@ -42,6 +42,14 @@ export interface NodeData {}export type CustomNodeProps = NodeProps<NodeData>;+interface CreateElementsOptions {+ cellIds: CellId[];+ cellAtoms: Atom<CellData>[];+ variables: Variables;+ hidePureMarkdown: boolean;+ hideReusableFunctions: boolean;+}+const LINE_HEIGHT = 11; // matches TinyCode.cssexport function getNodeHeight(linesOfCode: number) {@@ -176,13 +184,10 @@ export function computeDefsByCell(}interface ElementsBuilder {- createElements: (- cellIds: CellId[],- cellAtoms: Atom<CellData>[],- variables: Variables,- hidePureMarkdown: boolean,- hideReusableFunctions: boolean,- ) => { nodes: Node<NodeData>[]; edges: Edge[] };+ createElements: (options: CreateElementsOptions) => {+ nodes: Node<NodeData>[];+ edges: Edge[];+ };}export class VerticalElementsBuilder implements ElementsBuilder {@@ -225,13 +230,11 @@ export class VerticalElementsBuilder implements ElementsBuilder {};}- public createElements(- cellIds: CellId[],- cellAtoms: Atom<CellData>[],- variables: Variables,- _hidePureMarkdown: boolean,- _hideReusableFunctions: boolean,- ) {+ public createElements({+ cellIds,+ cellAtoms,+ variables,+ }: CreateElementsOptions) {let prevY = 0;const nodes: Node<NodeData>[] = [];const edges: Edge[] = [];@@ -311,13 +314,13 @@ export class TreeElementsBuilder implements ElementsBuilder {};}- public createElements(- cellIds: CellId[],- cellAtoms: Atom<CellData>[],- variables: Variables,- hidePureMarkdown: boolean,- hideReusableFunctions: boolean,- ) {+ public createElements({+ cellIds,+ cellAtoms,+ variables,+ hidePureMarkdown,+ hideReusableFunctions,+ }: CreateElementsOptions) {const nodes: Node<NodeData>[] = [];const cellRuntime = getNotebook().cellRuntime;diff --git a/frontend/src/components/dependency-graph/utils/__tests__/layout.test.ts b/frontend/src/components/dependency-graph/utils/__tests__/layout.test.tsindex e4733b568d..6866dcc28d 100644--- a/frontend/src/components/dependency-graph/utils/__tests__/layout.test.ts+++ b/frontend/src/components/dependency-graph/utils/__tests__/layout.test.ts@@ -7,10 +7,12 @@ import { boundingBox, placeIslands } from "../layout";function node(id: string,- x: number,- y: number,- width: number,- height: number,+ {+ x,+ y,+ width,+ height,+ }: { x: number; y: number; width: number; height: number },): Node<NodeData> {return {id,@@ -28,8 +30,8 @@ describe("boundingBox", () => {it("spans position + size across nodes", () => {const box = boundingBox([- node("a", 0, 0, 50, 50),- node("b", 10, 20, 100, 40),+ node("a", { x: 0, y: 0, width: 50, height: 50 }),+ node("b", { x: 10, y: 20, width: 100, height: 40 }),]);expect(box).toEqual({ minX: 0, minY: 0, maxX: 110, maxY: 60 });});@@ -52,12 +54,17 @@ describe("boundingBox", () => {describe("placeIslands", () => {it("returns nothing when there are no islands", () => {- expect(placeIslands([], [node("a", 0, 0, 100, 100)])).toEqual([]);+ expect(+ placeIslands([], [node("a", { x: 0, y: 0, width: 100, height: 100 })]),+ ).toEqual([]);});it("stacks islands in a column to the right of the placed graph", () => {- const placed = [node("main", 0, 0, 200, 300)];- const islands = [node("i0", 0, 0, 90, 40), node("i1", 0, 0, 90, 40)];+ const placed = [node("main", { x: 0, y: 0, width: 200, height: 300 })];+ const islands = [+ node("i0", { x: 0, y: 0, width: 90, height: 40 }),+ node("i1", { x: 0, y: 0, width: 90, height: 40 }),+ ];const result = placeIslands(islands, placed);// startX = maxX(200) + margin(40) = 240; startY = minY(0).expect(result[0].position).toEqual({ x: 240, y: 0 });@@ -66,9 +73,9 @@ describe("placeIslands", () => {});it("wraps into a new column when the column gets too tall", () => {- const placed = [node("main", 0, 0, 200, 300)];+ const placed = [node("main", { x: 0, y: 0, width: 200, height: 300 })];const islands = Array.from({ length: 10 }, (_, i) =>- node(`i${i}`, 0, 0, 90, 40),+ node(`i${i}`, { x: 0, y: 0, width: 90, height: 40 }),);const result = placeIslands(islands, placed);const firstColumnX = result[0].position.x;diff --git a/frontend/src/components/editor/output/ansi-reduce.ts b/frontend/src/components/editor/output/ansi-reduce.tsindex b665d61585..6e9bfd2ea8 100644--- a/frontend/src/components/editor/output/ansi-reduce.ts+++ b/frontend/src/components/editor/output/ansi-reduce.ts@@ -381,24 +381,31 @@ export class StatefulOutputMessage implements OutputMessage {public static create(message: StringOutputMessage): StatefulOutputMessage {const ansiReducer = new AnsiReducer();ansiReducer.append(message.data);- return new StatefulOutputMessage(- message.mimetype,- message.channel,- message.timestamp,+ return new StatefulOutputMessage({+ mimetype: message.mimetype,+ channel: message.channel,+ timestamp: message.timestamp,ansiReducer,- message.code,- message.id,- );+ code: message.code,+ id: message.id,+ });}- private constructor(- mimetype: OutputMessage["mimetype"],- channel: OutputMessage["channel"],- timestamp: OutputMessage["timestamp"],- ansiReducer: AnsiReducer,- code: OutputMessage["code"],- id: StringOutputMessage["id"],- ) {+ private constructor({+ mimetype,+ channel,+ timestamp,+ ansiReducer,+ code,+ id,+ }: {+ mimetype: OutputMessage["mimetype"];+ channel: OutputMessage["channel"];+ timestamp: OutputMessage["timestamp"];+ ansiReducer: AnsiReducer;+ code: OutputMessage["code"];+ id: StringOutputMessage["id"];+ }) {this.mimetype = mimetype;this.channel = channel;this.timestamp = timestamp;@@ -410,14 +417,14 @@ export class StatefulOutputMessage implements OutputMessage {public appendData(chunk: string): StatefulOutputMessage {this.ansiReducer.append(chunk);- return new StatefulOutputMessage(- this.mimetype,- this.channel,- this.timestamp,- this.ansiReducer,- this.code,- this.id,- );+ return new StatefulOutputMessage({+ mimetype: this.mimetype,+ channel: this.channel,+ timestamp: this.timestamp,+ ansiReducer: this.ansiReducer,+ code: this.code,+ id: this.id,+ });}public toJSON(): StringOutputMessage {diff --git a/frontend/src/components/editor/renderers/grid-layout/grid-layout.tsx b/frontend/src/components/editor/renderers/grid-layout/grid-layout.tsxindex 733f186e52..f1cd963bed 100644--- a/frontend/src/components/editor/renderers/grid-layout/grid-layout.tsx+++ b/frontend/src/components/editor/renderers/grid-layout/grid-layout.tsx@@ -190,12 +190,18 @@ export const GridLayoutRenderer: React.FC<Props> = ({cells: [...cellLayouts, dropped],});}}- onDragStart={(_layout, _oldItem, _newItem, _placeholder, event) => {- dragProps.onDragStart(event);- }}- onDrag={(_layout, _oldItem, _newItem, _placeholder, event) => {- dragProps.onDragMove(event);- }}+ onDragStart={+ // oxlint-disable-next-line marimo/prefer-object-params -- React Grid Layout supplies the event as the fifth argument.+ (_layout, _oldItem, _newItem, _placeholder, event) => {+ dragProps.onDragStart(event);+ }+ }+ onDrag={+ // oxlint-disable-next-line marimo/prefer-object-params -- React Grid Layout supplies the event as the fifth argument.+ (_layout, _oldItem, _newItem, _placeholder, event) => {+ dragProps.onDragMove(event);+ }+ }onDragStop={() => {dragProps.onDragStop();}}diff --git a/frontend/src/core/ai/tools/base.ts b/frontend/src/core/ai/tools/base.tsindex ab5e73f089..840ba89e00 100644--- a/frontend/src/core/ai/tools/base.ts+++ b/frontend/src/core/ai/tools/base.ts@@ -20,9 +20,11 @@ export type StatusValue = "success" | "error" | "warning";* @example* throw new ToolExecutionError(* "Failed to fetch data",- * "FETCH_ERROR",- * true,- * "Check your network connection"+ * {+ * code: "FETCH_ERROR",+ * isRetryable: true,+ * suggestedFix: "Check your network connection",+ * }* );*/export class ToolExecutionError extends Error {@@ -33,10 +35,17 @@ export class ToolExecutionError extends Error {public constructor(message: string,- code = "TOOL_ERROR",- isRetryable = false,- suggestedFix?: string,- meta?: Record<string, unknown>,+ {+ code = "TOOL_ERROR",+ isRetryable = false,+ suggestedFix,+ meta,+ }: {+ code?: string;+ isRetryable?: boolean;+ suggestedFix?: string;+ meta?: Record<string, unknown>;+ } = {},) {super(message);this.name = "ToolExecutionError";diff --git a/frontend/src/core/ai/tools/edit-notebook-tool.ts b/frontend/src/core/ai/tools/edit-notebook-tool.tsindex 4093b9f345..76f76df594 100644--- a/frontend/src/core/ai/tools/edit-notebook-tool.ts+++ b/frontend/src/core/ai/tools/edit-notebook-tool.ts@@ -94,19 +94,17 @@ export class EditNotebookTool implements AiTool<const cellId = position.cellId as CellId | undefined;if (!cellId) {- throw new ToolExecutionError(- "Cell ID is required for update_cell",- "CELL_ID_REQUIRED_FOR_UPDATE_CELL",- true,- "Provide a cell ID to update",- );+ throw new ToolExecutionError("Cell ID is required for update_cell", {+ code: "CELL_ID_REQUIRED_FOR_UPDATE_CELL",+ isRetryable: true,+ suggestedFix: "Provide a cell ID to update",+ });} else if (!code) {- throw new ToolExecutionError(- "Code is required for update_cell",- "CODE_REQUIRED_FOR_UPDATE_CELL",- true,- "Provide the new code to update the cell",- );+ throw new ToolExecutionError("Code is required for update_cell", {+ code: "CODE_REQUIRED_FOR_UPDATE_CELL",+ isRetryable: true,+ suggestedFix: "Provide the new code to update the cell",+ });}const notebook = store.get(notebookAtom);@@ -157,18 +155,22 @@ export class EditNotebookTool implements AiTool<if (!cellId) {throw new ToolExecutionError("Cell ID is required for add_cell with relative position",- "TOOL_ERROR",- true,- "Provide a cell ID to add the cell before",+ {+ code: "TOOL_ERROR",+ isRetryable: true,+ suggestedFix: "Provide a cell ID to add the cell before",+ },);}if (position.before === undefined) {throw new ToolExecutionError("Before is required for add_cell with relative position",- "TOOL_ERROR",- true,- `Provide a boolean value for before, true to add before cell ${cellId}, false to add after the cell`,+ {+ code: "TOOL_ERROR",+ isRetryable: true,+ suggestedFix: `Provide a boolean value for before, true to add before cell ${cellId}, false to add after the cell`,+ },);}@@ -181,9 +183,12 @@ export class EditNotebookTool implements AiTool<if (!position.columnIndex) {throw new ToolExecutionError("Column index is required for add_cell with column_end position",- "TOOL_ERROR",- true,- "Provide a column index to add the cell at the end of",+ {+ code: "TOOL_ERROR",+ isRetryable: true,+ suggestedFix:+ "Provide a column index to add the cell at the end of",+ },);}@@ -218,12 +223,11 @@ export class EditNotebookTool implements AiTool<const cellId = position.cellId as CellId | undefined;if (!cellId) {- throw new ToolExecutionError(- "Cell ID is required for delete_cell",- "CELL_ID_REQUIRED_FOR_DELETE_CELL",- true,- "Provide a cell ID to delete",- );+ throw new ToolExecutionError("Cell ID is required for delete_cell", {+ code: "CELL_ID_REQUIRED_FOR_DELETE_CELL",+ isRetryable: true,+ suggestedFix: "Provide a cell ID to delete",+ });}const notebook = store.get(notebookAtom);@@ -255,12 +259,11 @@ export class EditNotebookTool implements AiTool<private validateCellIdExists(cellId: CellId, notebook: NotebookState) {const cellIds = notebook.cellIds;if (!cellIds.getColumns().some((column) => column.idSet.has(cellId))) {- throw new ToolExecutionError(- "Cell not found",- "CELL_NOT_FOUND",- false,- "Check which cells exist in the notebook",- );+ throw new ToolExecutionError("Cell not found", {+ code: "CELL_NOT_FOUND",+ isRetryable: false,+ suggestedFix: "Check which cells exist in the notebook",+ });}}@@ -272,12 +275,12 @@ export class EditNotebookTool implements AiTool<const columns = cellIds.getColumns();if (columnIndex < 0 || columnIndex >= columns.length) {- throw new ToolExecutionError(- "Column index is out of range",- "COLUMN_INDEX_OUT_OF_RANGE",- true,- "Choose a column index between 0 and the number of columns in the notebook (0-based)",- );+ throw new ToolExecutionError("Column index is out of range", {+ code: "COLUMN_INDEX_OUT_OF_RANGE",+ isRetryable: true,+ suggestedFix:+ "Choose a column index between 0 and the number of columns in the notebook (0-based)",+ });}return columns[columnIndex].id;}@@ -289,12 +292,11 @@ export class EditNotebookTool implements AiTool<const cellHandles = notebook.cellHandles;const cellHandle = cellHandles[cellId].current;if (!cellHandle?.editorView) {- throw new ToolExecutionError(- "Cell editor not found",- "CELL_EDITOR_NOT_FOUND",- false,- "Internal error, ask the user to report this error",- );+ throw new ToolExecutionError("Cell editor not found", {+ code: "CELL_EDITOR_NOT_FOUND",+ isRetryable: false,+ suggestedFix: "Internal error, ask the user to report this error",+ });}return cellHandle.editorView;}diff --git a/frontend/src/core/ai/tools/registry.ts b/frontend/src/core/ai/tools/registry.tsindex 1e8e5be054..d856cdf64f 100644--- a/frontend/src/core/ai/tools/registry.ts+++ b/frontend/src/core/ai/tools/registry.ts@@ -73,9 +73,11 @@ export class FrontendToolRegistry {const strError = z.prettifyError(inputResponse.error);throw new ToolExecutionError(`Tool ${toolName} returned invalid input: ${strError}`,- "INVALID_ARGUMENTS",- true,- "Please check the arguments and try again.",+ {+ code: "INVALID_ARGUMENTS",+ isRetryable: true,+ suggestedFix: "Please check the arguments and try again.",+ },);}const args = inputResponse.data;@@ -110,12 +112,15 @@ export class FrontendToolRegistry {// Handle unknown/generic errorsconst genericError = new ToolExecutionError(error instanceof Error ? error.message : String(error),- "TOOL_ERROR",- false,- "Check the error message and try again with valid arguments.",{- args: rawArgs,- errorType: error?.constructor?.name ?? typeof error,+ code: "TOOL_ERROR",+ isRetryable: false,+ suggestedFix:+ "Check the error message and try again with valid arguments.",+ meta: {+ args: rawArgs,+ errorType: error?.constructor?.name ?? typeof error,+ },},);return {diff --git a/frontend/src/core/ai/tools/sample-tool.ts b/frontend/src/core/ai/tools/sample-tool.tsindex 1b7965c042..e9a4b8bf07 100644--- a/frontend/src/core/ai/tools/sample-tool.ts+++ b/frontend/src/core/ai/tools/sample-tool.ts@@ -50,13 +50,12 @@ export class TestFrontendTool implements AiTool<Input, Output> {public async handler({ name }: Input): Promise<Output> {// Example: Validate input and throw ToolExecutionError on invalid dataif (!name.trim()) {- throw new ToolExecutionError(- "Name cannot be empty",- "INVALID_INPUT",- false,- "Please provide a non-empty name",- { field: "name", received: name },- );+ throw new ToolExecutionError("Name cannot be empty", {+ code: "INVALID_INPUT",+ isRetryable: false,+ suggestedFix: "Please provide a non-empty name",+ meta: { field: "name", received: name },+ });}return {diff --git a/frontend/src/core/cells/__tests__/session.test.ts b/frontend/src/core/cells/__tests__/session.test.tsindex 1e0ac4658b..cc78b837aa 100644--- a/frontend/src/core/cells/__tests__/session.test.ts+++ b/frontend/src/core/cells/__tests__/session.test.ts@@ -46,10 +46,17 @@ describe("notebookStateFromSession", () => {const createNotebookCell = (id: string,- code: string | null = null,- name: string | null = null,- config: NotebookCell["config"] | null = null,- code_hash: string | null = null,+ {+ code = null,+ name = null,+ config = null,+ code_hash = null,+ }: {+ code?: string | null;+ name?: string | null;+ config?: NotebookCell["config"] | null;+ code_hash?: string | null;+ } = {},): NotebookCell => ({id,code,@@ -87,7 +94,7 @@ describe("notebookStateFromSession", () => {it("logs error when session and notebook have different cells", () => {const session = createSession([createSessionCell("cell-1")]);- const notebook = createNotebook([createNotebookCell("cell-2")]);+ const notebook = createNotebook([createNotebookCell("cell-2", {})]);const result = notebookStateFromSession(session, notebook);@@ -328,7 +335,10 @@ describe("notebookStateFromSession", () => {describe("notebook only scenarios", () => {it("creates state from notebook with single cell", () => {const notebook = createNotebook([- createNotebookCell("cell-1", "print('hello')", "my_cell"),+ createNotebookCell("cell-1", {+ code: "print('hello')",+ name: "my_cell",+ }),]);const result = notebookStateFromSession(null, notebook);@@ -356,11 +366,15 @@ describe("notebookStateFromSession", () => {it("creates state from notebook with custom config", () => {const notebook = createNotebook([- createNotebookCell("cell-1", "code", "name", {- hide_code: true,- disabled: true,- column: 1,- expand_output: true,+ createNotebookCell("cell-1", {+ code: "code",+ name: "name",+ config: {+ hide_code: true,+ disabled: true,+ column: 1,+ expand_output: true,+ },}),]);const result = notebookStateFromSession(null, notebook);@@ -464,7 +478,10 @@ describe("notebookStateFromSession", () => {),]);const notebook = createNotebook([- createNotebookCell("cell-1", "print('hello')", "my_cell"),+ createNotebookCell("cell-1", {+ code: "print('hello')",+ name: "my_cell",+ }),]);const result = notebookStateFromSession(session, notebook);@@ -495,8 +512,8 @@ describe("notebookStateFromSession", () => {createSessionCell("cell-2"),]);const notebook = createNotebook([- createNotebookCell("cell-2"),- createNotebookCell("cell-1"),+ createNotebookCell("cell-2", {}),+ createNotebookCell("cell-1", {}),]);const result = notebookStateFromSession(session, notebook);@@ -514,8 +531,8 @@ describe("notebookStateFromSession", () => {createSessionCell("cell-2"),]);const notebook = createNotebook([- createNotebookCell("cell-1"),- createNotebookCell("cell-2"),+ createNotebookCell("cell-1", {}),+ createNotebookCell("cell-2", {}),]);const result = notebookStateFromSession(session, notebook);@@ -669,12 +686,42 @@ describe("notebookStateFromSession", () => {};// Create notebook cells with code values 'a' through 'f'const notebookCells = [- createNotebookCell("cell-a", "a", null, null, hashes.a),- createNotebookCell("cell-b", "b", null, null, hashes.b),- createNotebookCell("cell-c", "c", null, null, hashes.c),- createNotebookCell("cell-d", "d", null, null, hashes.d),- createNotebookCell("cell-e", "e", null, null, hashes.e),- createNotebookCell("cell-f", "f", null, null, hashes.f),+ createNotebookCell("cell-a", {+ code: "a",+ name: null,+ config: null,+ code_hash: hashes.a,+ }),+ createNotebookCell("cell-b", {+ code: "b",+ name: null,+ config: null,+ code_hash: hashes.b,+ }),+ createNotebookCell("cell-c", {+ code: "c",+ name: null,+ config: null,+ code_hash: hashes.c,+ }),+ createNotebookCell("cell-d", {+ code: "d",+ name: null,+ config: null,+ code_hash: hashes.d,+ }),+ createNotebookCell("cell-e", {+ code: "e",+ name: null,+ config: null,+ code_hash: hashes.e,+ }),+ createNotebookCell("cell-f", {+ code: "f",+ name: null,+ config: null,+ code_hash: hashes.f,+ }),];// Create session cells with matching code_hashesconst sessionCells = [@@ -787,11 +834,36 @@ describe("notebookStateFromSession", () => {// Notebook has cells with code 'a', 'c', 'z', 'e', 'g'const notebookCells = [- createNotebookCell("cell-a", "a", null, null, hashes.a),- createNotebookCell("cell-c", "c", null, null, hashes.c),- createNotebookCell("cell-z", "z", null, null, hashes.z),- createNotebookCell("cell-e", "e", null, null, hashes.e),- createNotebookCell("cell-g", "g", null, null, hashes.g),+ createNotebookCell("cell-a", {+ code: "a",+ name: null,+ config: null,+ code_hash: hashes.a,+ }),+ createNotebookCell("cell-c", {+ code: "c",+ name: null,+ config: null,+ code_hash: hashes.c,+ }),+ createNotebookCell("cell-z", {+ code: "z",+ name: null,+ config: null,+ code_hash: hashes.z,+ }),+ createNotebookCell("cell-e", {+ code: "e",+ name: null,+ config: null,+ code_hash: hashes.e,+ }),+ createNotebookCell("cell-g", {+ code: "g",+ name: null,+ config: null,+ code_hash: hashes.g,+ }),];const session = createSession(sessionCells);@@ -908,15 +980,24 @@ describe("notebookStateFromSession", () => {// Notebook has cells: cell-1 (1 / 0, no hash), cell-2 (mo.md("Hello"), hash=moMd), cell-3 (slider, hash=slider)const notebookCells = [- createNotebookCell("cell-1", "1 / 0", null, null, null), // no hash- createNotebookCell("cell-2", 'mo.md("Hello")', null, null, hashes.moMd),- createNotebookCell(- "cell-3",- "x = mo.ui.slider(0, 10)",- null,- null,- hashes.slider,- ),+ createNotebookCell("cell-1", {+ code: "1 / 0",+ name: null,+ config: null,+ code_hash: null,+ }), // no hash+ createNotebookCell("cell-2", {+ code: 'mo.md("Hello")',+ name: null,+ config: null,+ code_hash: hashes.moMd,+ }),+ createNotebookCell("cell-3", {+ code: "x = mo.ui.slider(0, 10)",+ name: null,+ config: null,+ code_hash: hashes.slider,+ }),];const session = createSession(sessionCells);diff --git a/frontend/src/core/codemirror/__tests__/setup.test.ts b/frontend/src/core/codemirror/__tests__/setup.test.tsindex d4533a28cd..a0146b5f71 100644--- a/frontend/src/core/codemirror/__tests__/setup.test.ts+++ b/frontend/src/core/codemirror/__tests__/setup.test.ts@@ -198,22 +198,22 @@ test("go to definition falls through to lower-priority LSP keymap", () => {test("placeholder adds another extension", () => {const opts = getOpts();const withAI = new PythonLanguageAdapter()- .getExtension(- opts.cellId,- opts.completionConfig,- opts.hotkeys,- "marimo-import",- opts.lspConfig,- )+ .getExtension({+ cellId: opts.cellId,+ completionConfig: opts.completionConfig,+ hotkeys: opts.hotkeys,+ placeholderType: "marimo-import",+ lspConfig: opts.lspConfig,+ }).flat();const withoutAI = new PythonLanguageAdapter()- .getExtension(- opts.cellId,- opts.completionConfig,- opts.hotkeys,- "none",- opts.lspConfig,- )+ .getExtension({+ cellId: opts.cellId,+ completionConfig: opts.completionConfig,+ hotkeys: opts.hotkeys,+ placeholderType: "none",+ lspConfig: opts.lspConfig,+ }).flat();expect(withAI.length - 1).toBe(withoutAI.length);});@@ -221,22 +221,22 @@ test("placeholder adds another extension", () => {test("ai adds more extensions", () => {const opts = getOpts();const withAI = new PythonLanguageAdapter()- .getExtension(- opts.cellId,- opts.completionConfig,- opts.hotkeys,- "ai",- opts.lspConfig,- )+ .getExtension({+ cellId: opts.cellId,+ completionConfig: opts.completionConfig,+ hotkeys: opts.hotkeys,+ placeholderType: "ai",+ lspConfig: opts.lspConfig,+ }).flat();const withoutAI = new PythonLanguageAdapter()- .getExtension(- opts.cellId,- opts.completionConfig,- opts.hotkeys,- "none",- opts.lspConfig,- )+ .getExtension({+ cellId: opts.cellId,+ completionConfig: opts.completionConfig,+ hotkeys: opts.hotkeys,+ placeholderType: "none",+ lspConfig: opts.lspConfig,+ }).flat();expect(withAI.length - 2).toBe(withoutAI.length);});diff --git a/frontend/src/core/codemirror/language/__tests__/sql.test.ts b/frontend/src/core/codemirror/language/__tests__/sql.test.tsindex a7e9be0f69..4ea7cc68e5 100644--- a/frontend/src/core/codemirror/language/__tests__/sql.test.ts+++ b/frontend/src/core/codemirror/language/__tests__/sql.test.ts@@ -42,12 +42,14 @@ const adapter = new SQLLanguageAdapter();const TEST_ENGINE = "test_engine" as ConnectionName;const TEST_EXTENSION_ARGS = [- {} as CellId,- {} as CompletionConfig,- {} as HotkeyProvider,- {} as PlaceholderType,- {} as LSPConfig & {- diagnostics: DiagnosticsConfig;+ {+ cellId: {} as CellId,+ completionConfig: {} as CompletionConfig,+ hotkeys: {} as HotkeyProvider,+ placeholderType: {} as PlaceholderType,+ lspConfig: {} as LSPConfig & {+ diagnostics: DiagnosticsConfig;+ },},] as const;@@ -930,15 +932,15 @@ describe("SQL analysis features", () => {it("reports semantic diagnostics as warnings", async () => {const adapter = new SQLLanguageAdapter();- const extensions = adapter.getExtension(- {} as CellId,- {} as CompletionConfig,- {} as HotkeyProvider,- {} as PlaceholderType,- {+ const extensions = adapter.getExtension({+ cellId: {} as CellId,+ completionConfig: {} as CompletionConfig,+ hotkeys: {} as HotkeyProvider,+ placeholderType: {} as PlaceholderType,+ lspConfig: {diagnostics: { sql_linter: true },} as LSPConfig & { diagnostics: DiagnosticsConfig },- );+ });const state = EditorState.create({doc: "SELECT missing FROM users",extensions: [languageMetadataField.init(() => metadata), ...extensions],@@ -963,15 +965,15 @@ describe("SQL analysis features", () => {it("does not report unknown tables", async () => {const adapter = new SQLLanguageAdapter();- const extensions = adapter.getExtension(- {} as CellId,- {} as CompletionConfig,- {} as HotkeyProvider,- {} as PlaceholderType,- {+ const extensions = adapter.getExtension({+ cellId: {} as CellId,+ completionConfig: {} as CompletionConfig,+ hotkeys: {} as HotkeyProvider,+ placeholderType: {} as PlaceholderType,+ lspConfig: {diagnostics: { sql_linter: true },} as LSPConfig & { diagnostics: DiagnosticsConfig },- );+ });const state = EditorState.create({doc: "SELECT missing FROM users; SELECT * FROM unknown_table",extensions: [languageMetadataField.init(() => metadata), ...extensions],diff --git a/frontend/src/core/codemirror/language/extension.ts b/frontend/src/core/codemirror/language/extension.tsindex 8c556186a2..54ee67a94e 100644--- a/frontend/src/core/codemirror/language/extension.ts+++ b/frontend/src/core/codemirror/language/extension.ts@@ -167,13 +167,13 @@ function updateLanguageAdapterAndCode({setLanguageAdapter.of(nextLanguage),setLanguageMetadata.of(metadata),languageCompartment.reconfigure(- nextLanguage.getExtension(+ nextLanguage.getExtension({cellId,completionConfig,- hotkeysProvider,+ hotkeys: hotkeysProvider,placeholderType,lspConfig,- ),+ }),),// Clear historyhistoryCompartment.reconfigure([]),@@ -218,13 +218,13 @@ export function adaptiveLanguageConfiguration(opts: {// Language adapterlanguageToggleKeymaps(),languageCompartment.of(- LanguageAdapters.python.getExtension(+ LanguageAdapters.python.getExtension({cellId,completionConfig,hotkeys,placeholderType,lspConfig,- ),+ }),),languageAdapterState,languageMetadataField,@@ -323,12 +323,12 @@ export function reconfigureLanguageEffect(}return languageCompartment.reconfigure(- language.getExtension(+ language.getExtension({cellId,completionConfig,- hotkeysProvider,+ hotkeys: hotkeysProvider,placeholderType,lspConfig,- ),+ }),);}diff --git a/frontend/src/core/codemirror/language/languages/markdown.ts b/frontend/src/core/codemirror/language/languages/markdown.tsindex 0e3596be3f..9a3eaf3509 100644--- a/frontend/src/core/codemirror/language/languages/markdown.ts+++ b/frontend/src/core/codemirror/language/languages/markdown.ts@@ -69,12 +69,14 @@ export class MarkdownLanguageAdapter implements LanguageAdapter<MarkdownLanguagereturn this.parser.isSupported(pythonCode);}- public getExtension(- _cellId: CellId,- _completionConfig: CompletionConfig,- hotkeys: HotkeyProvider,- _placeholderType: PlaceholderType,- ): Extension[] {+ public getExtension({+ hotkeys,+ }: {+ cellId: CellId;+ completionConfig: CompletionConfig;+ hotkeys: HotkeyProvider;+ placeholderType: PlaceholderType;+ }): Extension[] {const markdownLanguageData = markdown().language.data;let view: EditorView | undefined;diff --git a/frontend/src/core/codemirror/language/languages/python.ts b/frontend/src/core/codemirror/language/languages/python.tsindex 4c1368cb17..f7a9dcb02c 100644--- a/frontend/src/core/codemirror/language/languages/python.ts+++ b/frontend/src/core/codemirror/language/languages/python.ts@@ -279,13 +279,19 @@ export class PythonLanguageAdapter implements LanguageAdapter<{}> {return this.parser.isSupported(code);}- public getExtension(- cellId: CellId,- completionConfig: CompletionConfig,- hotkeys: HotkeyProvider,- placeholderType: PlaceholderType,- lspConfig: LSPConfig & { diagnostics: DiagnosticsConfig },- ): Extension[] {+ public getExtension({+ cellId,+ completionConfig,+ hotkeys,+ placeholderType,+ lspConfig,+ }: {+ cellId: CellId;+ completionConfig: CompletionConfig;+ hotkeys: HotkeyProvider;+ placeholderType: PlaceholderType;+ lspConfig: LSPConfig & { diagnostics: DiagnosticsConfig };+ }): Extension[] {const getCompletionsExtension = () => {const autocompleteOptions = {// We remove the default keymap because we use our own whichdiff --git a/frontend/src/core/codemirror/language/languages/sql/sql.ts b/frontend/src/core/codemirror/language/languages/sql/sql.tsindex 602e032edc..c215fbafee 100644--- a/frontend/src/core/codemirror/language/languages/sql/sql.ts+++ b/frontend/src/core/codemirror/language/languages/sql/sql.ts@@ -155,13 +155,15 @@ export class SQLLanguageAdapter implements LanguageAdapter<SQLLanguageAdapterMetreturn this.parser.isSupported(pythonCode);}- public getExtension(- _cellId: CellId,- _completionConfig: CompletionConfig,- _hotkeys: HotkeyProvider,- _placeholderType: PlaceholderType,- lspConfig: LSPConfig & { diagnostics: DiagnosticsConfig },- ): Extension[] {+ public getExtension({+ lspConfig,+ }: {+ cellId: CellId;+ completionConfig: CompletionConfig;+ hotkeys: HotkeyProvider;+ placeholderType: PlaceholderType;+ lspConfig: LSPConfig & { diagnostics: DiagnosticsConfig };+ }): Extension[] {const analysis = createSQLAnalysis();const extensions = [// This can be updated with a dispatch effectdiff --git a/frontend/src/core/codemirror/language/types.ts b/frontend/src/core/codemirror/language/types.tsindex f54145cd5a..ed2c328d95 100644--- a/frontend/src/core/codemirror/language/types.ts+++ b/frontend/src/core/codemirror/language/types.ts@@ -26,13 +26,13 @@ export interface LanguageAdapter<M = Record<string, any>> {transformIn(code: string): [string, number, M];transformOut(code: string, metadata: M): [string, number];isSupported(code: string): boolean;- getExtension(- cellId: CellId,- completionConfig: CompletionConfig,- hotkeys: HotkeyProvider,- placeholderType: PlaceholderType,- lspConfig: LSPConfig & { diagnostics?: DiagnosticsConfig },- ): Extension[];+ getExtension(options: {+ cellId: CellId;+ completionConfig: CompletionConfig;+ hotkeys: HotkeyProvider;+ placeholderType: PlaceholderType;+ lspConfig: LSPConfig & { diagnostics?: DiagnosticsConfig };+ }): Extension[];}export type LanguageMetadataOf<T extends LanguageAdapter> =diff --git a/frontend/src/core/codemirror/rtc/extension.ts b/frontend/src/core/codemirror/rtc/extension.tsindex 59085f2870..257acae3ce 100644--- a/frontend/src/core/codemirror/rtc/extension.ts+++ b/frontend/src/core/codemirror/rtc/extension.ts@@ -207,7 +207,13 @@ export function realTimeCollaboration(extension: [languageObserverExtension(cellId),languageListenerExtension(cellId),- loroAwarenessPlugin(doc, awareness, userState, () => loroText, cellId),+ loroAwarenessPlugin({+ doc,+ awareness,+ user: userState,+ getTextFromDoc: () => loroText,+ cellId,+ }),loroSyncPlugin(doc, ["codes", cellId], () => {return loroText;}),@@ -419,14 +425,21 @@ function languageListenerExtension(cellId: CellId) {/*** Create a plugin to observe awareness changes*/-function loroAwarenessPlugin(- doc: LoroDoc,- awareness: Awareness<AwarenessState>,- user: UserState,- getTextFromDoc: (doc: LoroDoc) => LoroText,- cellId: CellId,- getUserId?: () => Uid,-): Extension[] {+function loroAwarenessPlugin({+ doc,+ awareness,+ user,+ getTextFromDoc,+ cellId,+ getUserId,+}: {+ doc: LoroDoc;+ awareness: Awareness<AwarenessState>;+ user: UserState;+ getTextFromDoc: (doc: LoroDoc) => LoroText;+ cellId: CellId;+ getUserId?: () => Uid;+}): Extension[] {const scopeId = `loro:cell:${cellId}` as ScopeId;return [@@ -435,15 +448,14 @@ function loroAwarenessPlugin(createSelectionLayer(),ViewPlugin.define((view) =>- new AwarenessPlugin(- view,+ new AwarenessPlugin(view, {doc,user,awareness,getTextFromDoc,scopeId,getUserId,- ),+ }),),ViewPlugin.define((view) => new RemoteAwarenessPlugin(view, doc, awareness, scopeId),diff --git a/frontend/src/core/codemirror/rtc/loro/awareness.ts b/frontend/src/core/codemirror/rtc/loro/awareness.tsindex 86da62825f..ec8f4ac140 100644--- a/frontend/src/core/codemirror/rtc/loro/awareness.ts+++ b/frontend/src/core/codemirror/rtc/loro/awareness.ts@@ -208,13 +208,19 @@ export class RemoteCursorMarker implements LayerMarker {private name: string;private colorClassName: string;- public constructor(- left: number,- top: number,- height: number,- name: string,- colorClassName: string,- ) {+ public constructor({+ left,+ top,+ height,+ name,+ colorClassName,+ }: {+ left: number;+ top: number;+ height: number;+ name: string;+ colorClassName: string;+ }) {this.left = left;this.top = top;this.height = height;@@ -271,13 +277,13 @@ export class RemoteCursorMarker implements LayerMarker {const baseLeft = left - view.scrollDOM.scrollLeft;const baseTop = rect.top - view.scrollDOM.scrollTop;return [- new RemoteCursorMarker(- absolutePosition.left - baseLeft,- absolutePosition.top - baseTop,- absolutePosition.bottom - absolutePosition.top,- displayName,+ new RemoteCursorMarker({+ left: absolutePosition.left - baseLeft,+ top: absolutePosition.top - baseTop,+ height: absolutePosition.bottom - absolutePosition.top,+ name: displayName,colorClassName,- ),+ }),];}@@ -375,12 +381,21 @@ export class AwarenessPlugin implements PluginValue {public constructor(view: EditorView,- doc: LoroDoc,- user: UserState,- awareness: Awareness<AwarenessState>,- getTextFromDoc: (doc: LoroDoc) => LoroText,- scopeId: ScopeId,- getUserId?: () => Uid,+ {+ doc,+ user,+ awareness,+ getTextFromDoc,+ scopeId,+ getUserId,+ }: {+ doc: LoroDoc;+ user: UserState;+ awareness: Awareness<AwarenessState>;+ getTextFromDoc: (doc: LoroDoc) => LoroText;+ scopeId: ScopeId;+ getUserId?: () => Uid;+ },) {this.view = view;this.doc = doc;diff --git a/frontend/src/core/codemirror/rtc/loro/sync.ts b/frontend/src/core/codemirror/rtc/loro/sync.tsindex e16b3a5e97..b550ed528a 100644--- a/frontend/src/core/codemirror/rtc/loro/sync.ts+++ b/frontend/src/core/codemirror/rtc/loro/sync.ts@@ -148,6 +148,7 @@ export class LoroSyncPluginValue implements PluginValue {return;}let adj = 0;+ // oxlint-disable-next-line marimo/prefer-object-params -- CodeMirror supplies positional change ranges and inserted text.update.changes.iterChanges((fromA, toA, fromB, toB, insert) => {const insertText = insert.sliceString(0, insert.length, "\n");if (fromA !== toA) {diff --git a/frontend/src/core/codemirror/utils.ts b/frontend/src/core/codemirror/utils.tsindex 3c34b5f2b7..1b9f3af542 100644--- a/frontend/src/core/codemirror/utils.ts+++ b/frontend/src/core/codemirror/utils.ts@@ -122,6 +122,7 @@ export function hasNewLines(tr: Transaction | ViewUpdate): boolean {let hasNewLines = false;// Iterate through all changes in the transaction+ // oxlint-disable-next-line marimo/prefer-object-params -- CodeMirror supplies positional change ranges and inserted text.tr.changes.iterChanges((fromA, toA, fromB, toB, inserted) => {// Check if the inserted text contains line breaksif (inserted.toString().includes("\n")) {diff --git a/frontend/src/core/islands/components/__tests__/IslandControls.test.tsx b/frontend/src/core/islands/components/__tests__/IslandControls.test.tsxindex 59c200c282..38b9a8fdfc 100644--- a/frontend/src/core/islands/components/__tests__/IslandControls.test.tsx+++ b/frontend/src/core/islands/components/__tests__/IslandControls.test.tsx@@ -2,6 +2,7 @@import { fireEvent, render, screen } from "@testing-library/react";import { beforeEach, describe, expect, it, vi } from "vitest";+import { MockRequestClient } from "@/__mocks__/requests";import { TooltipProvider } from "@/components/ui/tooltip";import type { CellId } from "@/core/cells/ids";import * as requestsModule from "@/core/network/requests";@@ -18,7 +19,8 @@ vi.mock("@/utils/copy", () => ({}));describe("IslandControls", () => {- const mockSendRun = vi.fn();+ const mockSendRun =+ vi.fn<ReturnType<typeof requestsModule.useRequestClient>["sendRun"]>();const mockCopyToClipboard = vi.fn();const mockCodeCallback = vi.fn(() => "print('test code')");const cellId = "test-cell-id" as CellId;@@ -30,11 +32,11 @@ describe("IslandControls", () => {beforeEach(() => {vi.clearAllMocks();- mockSendRun.mockResolvedValue(undefined);+ mockSendRun.mockResolvedValue(null);- vi.spyOn(requestsModule, "useRequestClient").mockReturnValue({- sendRun: mockSendRun,- } as any);+ vi.spyOn(requestsModule, "useRequestClient").mockReturnValue(+ MockRequestClient.create({ sendRun: mockSendRun }),+ );vi.spyOn(copyModule, "copyToClipboard").mockImplementation(mockCopyToClipboard,diff --git a/frontend/src/core/static/__tests__/files.test.ts b/frontend/src/core/static/__tests__/files.test.tsindex f1282b46ab..f9fc74c34b 100644--- a/frontend/src/core/static/__tests__/files.test.ts+++ b/frontend/src/core/static/__tests__/files.test.ts@@ -654,19 +654,47 @@ describe("error handling and edge cases", () => {unpatch();});- it("should handle malformed URLs gracefully", async () => {- const virtualFiles = {};- const unpatch = patchFetch(virtualFiles);+ it("forwards relative URLs and options to the original fetch", async () => {+ const response = new Response("relative content");+ const originalFetch = vi.spyOn(window, "fetch").mockResolvedValue(response);+ const unpatch = patchFetch({});+ const options = { headers: { Accept: "text/plain" } };++ try {+ expect(await window.fetch("relative-file.txt", options)).toBe(response);+ expect(originalFetch).toHaveBeenCalledExactlyOnceWith(+ "relative-file.txt",+ options,+ );+ } finally {+ unpatch();+ originalFetch.mockRestore();+ }+ });- // Mock Logger.error to avoid test output+ it("preserves the original fetch rejection for malformed URLs", async () => {+ const error = new TypeError("Invalid URL");+ const originalFetch = vi.spyOn(window, "fetch").mockRejectedValue(error);const loggerSpy = vi.spyOn(console, "error").mockImplementation(Functions.NOOP);-- // This should catch the error and fallback to original fetch- await window.fetch("not-a-valid-url").catch(() => undefined);-- unpatch();- loggerSpy.mockRestore();+ const unpatch = patchFetch({});+ const options = { headers: { Accept: "text/plain" } };++ try {+ await expect(window.fetch("http://[", options)).rejects.toBe(error);+ expect(originalFetch).toHaveBeenCalledExactlyOnceWith(+ "http://[",+ options,+ );+ expect(loggerSpy).toHaveBeenCalledWith(+ "Error parsing URL",+ expect.any(TypeError),+ );+ } finally {+ unpatch();+ originalFetch.mockRestore();+ loggerSpy.mockRestore();+ }});});diff --git a/frontend/src/plugins/__tests__/plugin-object-schemas.test.ts b/frontend/src/plugins/__tests__/plugin-object-schemas.test.tsnew file mode 100644index 0000000000..6de7162906--- /dev/null+++ b/frontend/src/plugins/__tests__/plugin-object-schemas.test.ts@@ -0,0 +1,104 @@+/* Copyright 2026 Marimo. All rights reserved. */++import { describe, expect, it } from "vitest";+import { DataEditorPlugin } from "../impl/DataEditorPlugin";+import { DataTablePlugin } from "../impl/DataTablePlugin";+import { DataFramePlugin } from "../impl/data-frames/DataFramePlugin";+import { PlotlyPlugin } from "../impl/plotly/PlotlyPlugin";+import { VegaPlugin } from "../impl/vega/VegaPlugin";++describe("plugin object schemas", () => {+ const rows = [{ value: 1, extra: { nested: true } }];+ const styles = { "0": { value: { color: "red", customProperty: 1 } } };+ const tableData = {+ initialValue: [],+ label: null,+ data: rows,+ totalRows: 1,+ totalColumns: 1,+ rowHeaders: [],+ cellStyles: styles,+ };++ it("preserves table rows and arbitrary cell style fields", () => {+ expect(DataTablePlugin.validator.parse(tableData)).toMatchObject({+ data: rows,+ cellStyles: styles,+ pageSize: 10,+ });+ });++ it("preserves data editor row fields", () => {+ expect(+ DataEditorPlugin.validator.parse({+ initialValue: { edits: [] },+ label: null,+ data: rows,+ editableColumns: "all",+ }),+ ).toMatchObject({ data: rows, columnNames: [] });+ });++ it("preserves table RPC payload fields", () => {+ const functions = DataTablePlugin.functions!;+ const searchResult = {+ data: rows,+ total_rows: 1,+ cell_styles: styles,+ cell_hover_texts: null,+ };+ expect(functions.search.output.parse(searchResult)).toEqual(searchResult);+ expect(functions.get_row_ids!.input.parse({ custom: true })).toEqual({+ custom: true,+ });+ expect(functions.get_data_url!.input.parse({ custom: true })).toEqual({+ custom: true,+ });+ expect(+ functions.get_data_url!.output.parse({ data_url: rows, format: "json" }),+ ).toEqual({ data_url: rows, format: "json" });+ });++ it("preserves dataframe search row fields", () => {+ const result = { data: rows, total_rows: 1 };+ expect(DataFramePlugin.functions!.search.output.parse(result)).toEqual(+ result,+ );+ });++ it("preserves Plotly figure and config fields", () => {+ const data = {+ figure: { data: [], layout: { title: "Chart" } },+ config: { responsive: true },+ };+ expect(new PlotlyPlugin().validator.parse(data)).toEqual(data);+ });++ it("preserves Vega spec and embed options fields and defaults", () => {+ const spec = { mark: "bar", encoding: { x: { field: "value" } } };+ const validator = new VegaPlugin().validator;+ expect(validator.parse({ spec })).toEqual({+ spec,+ chartSelection: true,+ fieldSelection: true,+ embedOptions: {},+ });+ expect(+ validator.parse({ spec, embedOptions: { actions: false } }).embedOptions,+ ).toEqual({ actions: false });+ });++ it("rejects scalar values where plugin objects are required", () => {+ expect(+ DataTablePlugin.validator.safeParse({ ...tableData, data: [42] }).success,+ ).toBe(false);+ expect(+ new PlotlyPlugin().validator.safeParse({ figure: 42, config: {} })+ .success,+ ).toBe(false);+ expect(+ new VegaPlugin().validator.safeParse({ spec: {}, embedOptions: 42 })+ .success,+ ).toBe(false);+ });+});diff --git a/frontend/src/plugins/impl/DataEditorPlugin.tsx b/frontend/src/plugins/impl/DataEditorPlugin.tsxindex ee96000e74..ed2868d603 100644--- a/frontend/src/plugins/impl/DataEditorPlugin.tsx+++ b/frontend/src/plugins/impl/DataEditorPlugin.tsx@@ -44,7 +44,7 @@ export const DataEditorPlugin = createPlugin<Edits>("marimo-data-editor", {),}),label: z.string().nullable(),- data: z.union([z.string(), z.array(z.object({}).passthrough())]),+ data: z.union([z.string(), z.array(z.looseObject({}))]),fieldTypes: columnToFieldTypesSchema.nullish(),columnNames: z.array(z.string()).default([]),editableColumns: z.union([z.array(z.string()), z.literal("all")]),diff --git a/frontend/src/plugins/impl/DataTablePlugin.tsx b/frontend/src/plugins/impl/DataTablePlugin.tsxindex 612263ff9c..94000a89e3 100644--- a/frontend/src/plugins/impl/DataTablePlugin.tsx+++ b/frontend/src/plugins/impl/DataTablePlugin.tsx@@ -258,7 +258,7 @@ export const DataTablePlugin = createPlugin<S>("marimo-table")z.array(z.object({ rowId: z.string(), columnName: z.string() })),]),label: z.string().nullable(),- data: z.union([z.string(), z.array(z.object({}).passthrough())]),+ data: z.union([z.string(), z.array(z.looseObject({}))]),rawData: z.union([z.string(), z.array(z.looseObject({}))]).nullish(),totalRows: z.union([z.number(), z.literal(TOO_MANY_ROWS)]),pagination: z.boolean().default(false),@@ -296,7 +296,7 @@ export const DataTablePlugin = createPlugin<S>("marimo-table")hasStableRowId: z.boolean().default(false),maxHeight: z.number().optional(),cellStyles: z- .record(z.string(), z.record(z.string(), z.object({}).passthrough()))+ .record(z.string(), z.record(z.string(), z.looseObject({}))).optional(),hoverTemplate: z.string().optional(),cellHoverTexts: cellHoverTextSchema,@@ -341,28 +341,25 @@ export const DataTablePlugin = createPlugin<S>("marimo-table")).output(z.object({- data: z.union([z.string(), z.array(z.object({}).passthrough())]),+ data: z.union([z.string(), z.array(z.looseObject({}))]),total_rows: z.union([z.number(), z.literal(TOO_MANY_ROWS)]),cell_styles: z- .record(- z.string(),- z.record(z.string(), z.object({}).passthrough()),- )+ .record(z.string(), z.record(z.string(), z.looseObject({}))).nullable(),cell_hover_texts: cellHoverTextSchema.nullable(),raw_data: z.union([z.string(), z.array(z.looseObject({}))]).nullish(),}),),- get_row_ids: rpc.input(z.object({}).passthrough()).output(+ get_row_ids: rpc.input(z.looseObject({})).output(z.object({row_ids: z.array(z.number()),all_rows: z.boolean(),error: z.string().nullable(),}),),- get_data_url: rpc.input(z.object({}).passthrough()).output(+ get_data_url: rpc.input(z.looseObject({})).output(z.object({- data_url: z.union([z.string(), z.array(z.object({}).passthrough())]),+ data_url: z.union([z.string(), z.array(z.looseObject({}))]),format: z.enum(["csv", "json", "arrow"]),}),),@@ -919,16 +916,16 @@ const DataTableComponent = ({}const fieldTypesWithoutExternalTypes = toFieldTypes(fieldTypes);- return new ColumnChartSpecModel(- columnSummaries.data || [],- fieldTypesWithoutExternalTypes,- columnSummaries.stats,- columnSummaries.bin_values,- columnSummaries.value_counts,- {+ return new ColumnChartSpecModel({+ data: columnSummaries.data || [],+ fieldTypes: fieldTypesWithoutExternalTypes,+ stats: columnSummaries.stats,+ binValues: columnSummaries.bin_values,+ valueCounts: columnSummaries.value_counts,+ opts: {includeCharts: columnSummaries.show_charts,},- );+ });}, [fieldTypes, columnSummaries]);const rowHeaderNames = new Set(rowHeaders.map(([name]) => name));diff --git a/frontend/src/plugins/impl/data-frames/DataFramePlugin.tsx b/frontend/src/plugins/impl/data-frames/DataFramePlugin.tsxindex 7a8ea0dcca..572b3cd7b3 100644--- a/frontend/src/plugins/impl/data-frames/DataFramePlugin.tsx+++ b/frontend/src/plugins/impl/data-frames/DataFramePlugin.tsx@@ -154,7 +154,7 @@ export const DataFramePlugin = createPlugin<S>("marimo-dataframe")).output(z.object({- data: z.union([z.string(), z.array(z.object({}).passthrough())]),+ data: z.union([z.string(), z.array(z.looseObject({}))]),total_rows: z.number(),}),),diff --git a/frontend/src/plugins/impl/plotly/PlotlyPlugin.tsx b/frontend/src/plugins/impl/plotly/PlotlyPlugin.tsxindex 8f6c106bc2..2af70ea521 100644--- a/frontend/src/plugins/impl/plotly/PlotlyPlugin.tsx+++ b/frontend/src/plugins/impl/plotly/PlotlyPlugin.tsx@@ -58,11 +58,8 @@ export class PlotlyPlugin implements IPlugin<T, Data> {public tagName = "marimo-plotly";public validator = z.object({- figure: z- .object({})- .passthrough()- .transform((spec) => spec as unknown as Figure),- config: z.object({}).passthrough(),+ figure: z.looseObject({}).transform((spec) => spec as unknown as Figure),+ config: z.looseObject({}),});public render(props: IPluginProps<T, Data>): JSX.Element {diff --git a/frontend/src/plugins/impl/plotly/selection.ts b/frontend/src/plugins/impl/plotly/selection.tsindex 21838ffd7f..2998813380 100644--- a/frontend/src/plugins/impl/plotly/selection.ts+++ b/frontend/src/plugins/impl/plotly/selection.ts@@ -208,13 +208,19 @@ export function hasAreaTrace(});}-function createDragmodeButton(- name: string,- title: string,- svg: string,- dragmode: Plotly.Layout["dragmode"],- setDragmode: (dragmode: Plotly.Layout["dragmode"]) => void,-): ModeBarButton {+function createDragmodeButton({+ name,+ title,+ svg,+ dragmode,+ setDragmode,+}: {+ name: string;+ title: string;+ svg: string;+ dragmode: Plotly.Layout["dragmode"];+ setDragmode: (dragmode: Plotly.Layout["dragmode"]) => void;+}): ModeBarButton {return {name,title,@@ -227,27 +233,27 @@ export function lineSelectionButtons(setDragmode: (dragmode: Plotly.Layout["dragmode"]) => void,): ModeBarButton[] {return [- createDragmodeButton(- "line-box-select",- "Box select",- `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor"+ createDragmodeButton({+ name: "line-box-select",+ title: "Box select",+ svg: `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor"stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="4" y="4" width="16" height="16" stroke-dasharray="2 2" /></svg>`,- "select",+ dragmode: "select",setDragmode,- ),- createDragmodeButton(- "line-lasso-select",- "Lasso select",- `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor"+ }),+ createDragmodeButton({+ name: "line-lasso-select",+ title: "Lasso select",+ svg: `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor"stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M6 8c0-2.2 2.2-4 5-4s5 1.8 5 4-2.2 4-5 4-5 1.8-5 4 2.2 4 5 4" /><circle cx="17.5" cy="16.5" r="1.5" /></svg>`,- "lasso",+ dragmode: "lasso",setDragmode,- ),+ }),];}diff --git a/frontend/src/plugins/impl/vega/VegaPlugin.tsx b/frontend/src/plugins/impl/vega/VegaPlugin.tsxindex 2b19142c3d..2967be66a8 100644--- a/frontend/src/plugins/impl/vega/VegaPlugin.tsx+++ b/frontend/src/plugins/impl/vega/VegaPlugin.tsx@@ -16,14 +16,13 @@ export class VegaPlugin implements IPlugin<VegaComponentState, Data> {public validator = z.object({spec: z- .object({})- .passthrough()+ .looseObject({}).transform((spec) => spec as unknown as VegaLiteSpec),chartSelection: z.union([z.boolean(), z.literal("point"), z.literal("interval")]).default(true),fieldSelection: z.union([z.boolean(), z.array(z.string())]).default(true),- embedOptions: z.object({}).passthrough().default({}),+ embedOptions: z.looseObject({}).default({}),});public render(props: IPluginProps<VegaComponentState, Data>): JSX.Element {