Skip to content

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

fix: use stable keys for dynamic frontend lists (#11450)

Kiran Gadhavee8028eb4f40f
diff --git a/frontend/src/components/chat/acp/blocks.tsx b/frontend/src/components/chat/acp/blocks.tsx
index 0857f2cc9d..3e9d8a5f45 100644
--- a/frontend/src/components/chat/acp/blocks.tsx
+++ b/frontend/src/components/chat/acp/blocks.tsx
@@ -328,9 +328,9 @@ export const PlansBlock = (props: { data: PlanNotificationEvent[] }) => {
</span>
</div>
<ul className="flex flex-col gap-1">
- {plans.map((item, index) => (
+ {plans.map((item) => (
<li
- key={`${item.status}-${index}`}
+ key={item.content}
className={`
flex items-center gap-2 px-2 py-1 rounded
`}
diff --git a/frontend/src/components/data-table/charts/__tests__/chart-panel.test.tsx b/frontend/src/components/data-table/charts/__tests__/chart-panel.test.tsx
index 32ac53d446..9068f0cad8 100644
--- a/frontend/src/components/data-table/charts/__tests__/chart-panel.test.tsx
+++ b/frontend/src/components/data-table/charts/__tests__/chart-panel.test.tsx
@@ -10,13 +10,27 @@ import { cellId } from "@/__tests__/branded";
import { LazyVegaEmbed } from "@/components/charts/lazy";
import { vegaLoader } from "@/plugins/impl/vega/loader";
import { ChartPanel, TablePanel, type TablePanelProps } from "../charts";
-import { getChartTabName, tabsStorageAtom } from "../storage";
+import { createTabId, getChartTabName, tabsStorageAtom } from "../storage";
import { ChartType, NONE_VALUE } from "../types";
+import { TOO_MANY_ROWS } from "../../types";
vi.mock("@/components/charts/lazy", () => ({
LazyVegaEmbed: vi.fn(() => null),
}));
+vi.mock("../components/chart-items", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("../components/chart-items")>()),
+ ChartTypeSelect: ({
+ onValueChange,
+ }: {
+ onValueChange: (value: string) => void;
+ }) => (
+ <button type="button" onClick={() => onValueChange("line")}>
+ Change chart type
+ </button>
+ ),
+}));
+
beforeAll(() => {
SetupMocks.resizeObserver();
});
@@ -38,6 +52,7 @@ describe("ChartPanel", () => {
id,
[
{
+ id: createTabId(),
tabName,
chartType: ChartType.BAR,
config: {
@@ -283,4 +298,62 @@ describe("ChartPanel", () => {
});
},
);
+ it("keeps panel state when a chart type change renames the tab", async () => {
+ const store = createStore();
+ const id = cellId("rename-keeps-state");
+ const tabName = getChartTabName(0, ChartType.BAR);
+ store.set(
+ tabsStorageAtom,
+ new Map([
+ [
+ id,
+ [
+ {
+ id: createTabId(),
+ tabName,
+ chartType: ChartType.BAR,
+ config: {
+ general: {
+ xColumn: { field: "value", type: "number" },
+ yColumn: {
+ field: "value",
+ type: "integer",
+ aggregate: NONE_VALUE,
+ },
+ },
+ },
+ },
+ ],
+ ],
+ ]),
+ );
+ const sample = [{ value: 1 }];
+ const props: TablePanelProps = {
+ cellId: id,
+ data: sample,
+ dataTable: <div />,
+ totalRows: TOO_MANY_ROWS,
+ columns: 1,
+ displayHeader: true,
+ fieldTypes: [["value", ["number", "float64"]]],
+ };
+ const { getByRole, findByRole, queryByRole } = render(
+ <Provider store={store}>
+ <Tooltip.Provider>
+ <TablePanel {...props} />
+ </Tooltip.Provider>
+ </Provider>,
+ );
+ fireEvent.click(getByRole("tab", { name: tabName }));
+ fireEvent.click(await findByRole("button", { name: "Proceed" }));
+ await waitFor(() => {
+ expect(queryByRole("button", { name: "Proceed" })).toBeNull();
+ });
+
+ fireEvent.click(getByRole("button", { name: "Change chart type" }));
+
+ const renamed = getChartTabName(0, ChartType.LINE);
+ await findByRole("tab", { name: renamed });
+ expect(queryByRole("button", { name: "Proceed" })).toBeNull();
+ });
});
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 429dfd94eb..4d34339306 100644
--- a/frontend/src/components/data-table/charts/__tests__/storage.test.ts
+++ b/frontend/src/components/data-table/charts/__tests__/storage.test.ts
@@ -16,7 +16,7 @@ import { cellId } from "@/__tests__/branded";
import { availableStorage } from "@/utils/storage/storage";
import { ChartSchema } from "../schemas";
import type { TabName } from "../storage";
-import { KEY, tabsStorageAtom } from "../storage";
+import { createTabId, KEY, tabsStorageAtom } from "../storage";
import { ChartType } from "../types";
describe("Chart Transforms Storage", () => {
@@ -39,6 +39,7 @@ describe("Chart Transforms Storage", () => {
const store = getDefaultStore();
const cid = cellId("cell-1");
const tabData = {
+ id: createTabId(),
tabName: "Tab 1" as TabName,
chartType: ChartType.LINE,
config: ChartSchema.parse({
@@ -63,6 +64,7 @@ describe("Chart Transforms Storage", () => {
const store = getDefaultStore();
const cid = cellId("cell-1");
const tabData1 = {
+ id: createTabId(),
tabName: "Tab 1" as TabName,
chartType: ChartType.LINE,
config: ChartSchema.parse({
@@ -73,6 +75,7 @@ describe("Chart Transforms Storage", () => {
}),
};
const tabData2 = {
+ id: createTabId(),
tabName: "Tab 2" as TabName,
chartType: ChartType.BAR,
config: ChartSchema.parse({
diff --git a/frontend/src/components/data-table/charts/charts.tsx b/frontend/src/components/data-table/charts/charts.tsx
index a23ef9e25d..c2d239eaea 100644
--- a/frontend/src/components/data-table/charts/charts.tsx
+++ b/frontend/src/components/data-table/charts/charts.tsx
@@ -48,7 +48,12 @@ import { HeatmapForm } from "./forms/heatmap";
import { PieForm } from "./forms/pie";
import { LazyChart } from "./lazy-chart";
import { ChartSchema, type ChartSchemaType, getChartDefaults } from "./schemas";
-import { getChartTabName, type TabName, tabsStorageAtom } from "./storage";
+import {
+ createTabId,
+ getChartTabName,
+ type TabName,
+ tabsStorageAtom,
+} from "./storage";
import { ChartType } from "./types";
const NEW_CHART_TYPE = "bar" as ChartType;
@@ -114,7 +119,12 @@ export const TablePanel: React.FC<TablePanelProps> = ({
const tabName = getChartTabName(0, NEW_CHART_TYPE);
const newTabs = new Map(tabsMap);
newTabs.set(cellId, [
- { tabName, chartType: NEW_CHART_TYPE, config: getChartDefaults() },
+ {
+ id: createTabId(),
+ tabName,
+ chartType: NEW_CHART_TYPE,
+ config: getChartDefaults(),
+ },
]);
saveTabsMap(newTabs);
setTabCounter(1);
@@ -135,6 +145,7 @@ export const TablePanel: React.FC<TablePanelProps> = ({
newTabs.set(cellId, [
...tabs,
{
+ id: createTabId(),
tabName,
chartType: NEW_CHART_TYPE,
config: getChartDefaults(),
@@ -233,9 +244,9 @@ export const TablePanel: React.FC<TablePanelProps> = ({
>
Table
</TabsTrigger>
- {tabs.map((tab, idx) => (
+ {tabs.map((tab) => (
<TabsTrigger
- key={idx}
+ key={tab.id}
className="text-xs"
value={tab.tabName}
onClick={() => setSelectedTab(tab.tabName)}
@@ -263,7 +274,7 @@ export const TablePanel: React.FC<TablePanelProps> = ({
<TabsContent className="mt-1 overflow-hidden" value={DEFAULT_TAB_NAME}>
{dataTable}
</TabsContent>
- {tabs.map((tab, idx) => {
+ {tabs.map((tab) => {
const saveChart = (formValues: ChartSchemaType) => {
saveTabChart({
tabName: tab.tabName,
@@ -275,7 +286,11 @@ export const TablePanel: React.FC<TablePanelProps> = ({
saveTabChartType(tab.tabName, chartType);
};
return (
- <TabsContent key={idx} value={tab.tabName} className="h-[400px] mt-0">
+ <TabsContent
+ key={tab.id}
+ value={tab.tabName}
+ className="h-[400px] mt-0"
+ >
<ChartPanel
tableData={data}
chartConfig={tab.config}
diff --git a/frontend/src/components/data-table/charts/storage.ts b/frontend/src/components/data-table/charts/storage.ts
index 1fe3e5336b..d60aeb3442 100644
--- a/frontend/src/components/data-table/charts/storage.ts
+++ b/frontend/src/components/data-table/charts/storage.ts
@@ -7,13 +7,16 @@ import { Logger } from "@/utils/Logger";
import { NotebookScopedLocalStorage } from "@/utils/storage/typed";
import { capitalize } from "@/utils/strings";
import type { TypedString } from "@/utils/typed";
+import { generateUUID } from "@/utils/uuid";
import { ChartSchema, type ChartSchemaType } from "./schemas";
import type { ChartType } from "./types";
export type TabName = TypedString<"TabName">;
+export type TabId = TypedString<"TabId">;
export const KEY = "marimo:charts:v2";
interface TabStorage {
+ id: TabId;
tabName: TabName; // unique within cell
chartType: ChartType;
config: ChartSchemaType;
@@ -21,11 +24,15 @@ interface TabStorage {
type TabStorageMap = Map<CellId, TabStorage[]>;
-const TabStorageSchema = z.object({
- tabName: z.string().transform((name) => name as TabName),
- chartType: z.string().transform((type) => type as ChartType),
- config: ChartSchema,
-});
+const TabStorageSchema = z
+ .object({
+ id: z.string().optional(),
+ tabName: z.string().transform((name) => name as TabName),
+ chartType: z.string().transform((type) => type as ChartType),
+ config: ChartSchema,
+ })
+ // Stored tabs without an id use their name, which is unique within a cell.
+ .transform((tab) => ({ ...tab, id: (tab.id ?? tab.tabName) as TabId }));
const TabStorageEntriesSchema = z.array(
z.tuple([
z.string().transform((name) => name as CellId),
@@ -64,6 +71,10 @@ export const tabsStorageAtom = atomWithStorage<TabStorageMap>(
mapStorage,
);
+export function createTabId(): TabId {
+ return generateUUID() as TabId;
+}
+
/**
* Convenience function to get the tab name for a given tab number and chart type
*/
diff --git a/frontend/src/components/editor/output/ansi-reduce.ts b/frontend/src/components/editor/output/ansi-reduce.ts
index d1175a7b62..b665d61585 100644
--- a/frontend/src/components/editor/output/ansi-reduce.ts
+++ b/frontend/src/components/editor/output/ansi-reduce.ts
@@ -358,6 +358,7 @@ export class AnsiReducer {
export type StringOutputMessage = Omit<OutputMessage, "data"> & {
data: string;
+ id?: number;
};
/**
@@ -369,6 +370,7 @@ export class StatefulOutputMessage implements OutputMessage {
public readonly channel: OutputMessage["channel"];
public readonly timestamp: OutputMessage["timestamp"];
public readonly code: OutputMessage["code"];
+ public readonly id: StringOutputMessage["id"];
private ansiReducer = new AnsiReducer();
private _data: string;
@@ -385,6 +387,7 @@ export class StatefulOutputMessage implements OutputMessage {
message.timestamp,
ansiReducer,
message.code,
+ message.id,
);
}
@@ -394,11 +397,13 @@ export class StatefulOutputMessage implements OutputMessage {
timestamp: OutputMessage["timestamp"],
ansiReducer: AnsiReducer,
code: OutputMessage["code"],
+ id: StringOutputMessage["id"],
) {
this.mimetype = mimetype;
this.channel = channel;
this.timestamp = timestamp;
this.code = code;
+ this.id = id;
this.ansiReducer = ansiReducer;
this._data = this.ansiReducer.render();
}
@@ -411,6 +416,7 @@ export class StatefulOutputMessage implements OutputMessage {
this.timestamp,
this.ansiReducer,
this.code,
+ this.id,
);
}
diff --git a/frontend/src/components/editor/output/console/ConsoleOutput.tsx b/frontend/src/components/editor/output/console/ConsoleOutput.tsx
index 2ded6720f9..6bc9c53ccc 100644
--- a/frontend/src/components/editor/output/console/ConsoleOutput.tsx
+++ b/frontend/src/components/editor/output/console/ConsoleOutput.tsx
@@ -16,8 +16,7 @@ import { Tooltip } from "@/components/ui/tooltip";
import type { CellId } from "@/core/cells/ids";
import { isInternalCellName } from "@/core/cells/names";
import { useExpandedConsoleOutput } from "@/core/cells/outputs";
-import type { WithResponse } from "@/core/cells/types";
-import type { OutputMessage } from "@/core/kernel/messages";
+import type { ConsoleOutputMessage } from "@/core/cells/types";
import {
type UseInputHistoryReturn,
useInputHistory,
@@ -73,7 +72,7 @@ interface Props {
cellId: CellId;
cellName: string;
className?: string;
- consoleOutputs: WithResponse<OutputMessage>[];
+ consoleOutputs: ConsoleOutputMessage[];
stale: boolean;
interrupted: boolean;
debuggerActive: boolean;
@@ -241,19 +240,24 @@ const ConsoleOutputInternal = (props: Props): React.ReactNode => {
return null;
}
+ const originalIdx = consoleOutputs.length - idx - 1;
+ // Outputs render in reverse, so the reversed index shifts on every
+ // new line. The assigned id survives collapse and truncation. The
+ // original position is the fallback for outputs without one.
+ const key = output.id ?? `position-${originalIdx}`;
+
if (output.channel === "stdin") {
invariant(
typeof output.data === "string",
"Expected data to be a string",
);
- const originalIdx = consoleOutputs.length - idx - 1;
const isPassword = output.mimetype === "text/password";
if (output.response == null && lastStdInputIdx === idx) {
return (
<StdInput
- key={idx}
+ key={key}
output={output.data}
isPdb={isPdb}
isPassword={isPassword}
@@ -268,7 +272,7 @@ const ConsoleOutputInternal = (props: Props): React.ReactNode => {
return (
<StdInputWithResponse
- key={idx}
+ key={key}
output={output.data}
response={output.response}
isPassword={isPassword}
@@ -278,7 +282,7 @@ const ConsoleOutputInternal = (props: Props): React.ReactNode => {
}
return (
- <React.Fragment key={idx}>
+ <React.Fragment key={key}>
<OutputRenderer
cellId={cellId}
onRefactorWithAI={onRefactorWithAI}
diff --git a/frontend/src/components/editor/package-alert.tsx b/frontend/src/components/editor/package-alert.tsx
index bd447ba408..e4c88bd9d1 100644
--- a/frontend/src/components/editor/package-alert.tsx
+++ b/frontend/src/components/editor/package-alert.tsx
@@ -172,12 +172,12 @@ export const PackageAlert: React.FC = () => {
<p>The following packages were not found:</p>
<table className="list-disc ml-2 mt-1">
<tbody>
- {packageAlert.packages.map((pkg, index) => {
+ {packageAlert.packages.map((pkg) => {
const parsed = parsePackageSpecifier(pkg);
const currentExtras = selectedExtras[pkg] || parsed.extras;
return (
- <tr className="font-mono text-sm" key={index}>
+ <tr className="font-mono text-sm" key={pkg}>
<td className="pr-2 py-1 align-middle">
<BoxIcon size="1rem" />
</td>
@@ -296,7 +296,7 @@ export const PackageAlert: React.FC = () => {
</>
)}
<ul className="list-disc ml-2 mt-1">
- {Object.entries(packageAlert.packages).map(([pkg, st], index) => (
+ {Object.entries(packageAlert.packages).map(([pkg, st]) => (
<li
className={cn(
"flex items-center gap-1 font-mono text-sm",
@@ -307,7 +307,7 @@ export const PackageAlert: React.FC = () => {
status === "failed" &&
"text-muted-foreground",
)}
- key={index}
+ key={pkg}
>
<ProgressIcon status={st} />
{pkg}
diff --git a/frontend/src/components/scratchpad/scratchpad.tsx b/frontend/src/components/scratchpad/scratchpad.tsx
index e9ab5ddf58..2dfd9208d8 100644
--- a/frontend/src/components/scratchpad/scratchpad.tsx
+++ b/frontend/src/components/scratchpad/scratchpad.tsx
@@ -135,9 +135,9 @@ export const ScratchPad: React.FC = () => {
return (
<div className="absolute inset-0 z-100 bg-background p-3 border-none overflow-auto">
<div className="overflow-auto flex flex-col gap-3">
- {history.map((item, index) => (
+ {history.map((item) => (
<div
- key={index}
+ key={item}
className="border rounded-md hover:shadow-sm cursor-pointer hover:border-input overflow-hidden"
onClick={() => handleSelectHistoryItem(item)}
>
diff --git a/frontend/src/components/slides/reveal-component.tsx b/frontend/src/components/slides/reveal-component.tsx
index 7672fc88af..5a3c283f54 100644
--- a/frontend/src/components/slides/reveal-component.tsx
+++ b/frontend/src/components/slides/reveal-component.tsx
@@ -404,13 +404,15 @@ const SubslideView = ({
if (block.isFragment) {
const cumulative = cumulativeByBlock.get(i);
return (
- <Fragment key={i} as="div">
+ <Fragment key={block.cells[0].id} as="div">
{rendered}
{cumulative && <NotesAside text={cumulative} />}
</Fragment>
);
}
- return <ReactFragment key={i}>{rendered}</ReactFragment>;
+ return (
+ <ReactFragment key={block.cells[0].id}>{rendered}</ReactFragment>
+ );
})}
</div>
</SlideScrollContainer>
diff --git a/frontend/src/core/cells/__tests__/__snapshots__/cells.test.ts.snap b/frontend/src/core/cells/__tests__/__snapshots__/cells.test.ts.snap
index 6ea1cec1f7..027b977dd9 100644
--- a/frontend/src/core/cells/__tests__/__snapshots__/cells.test.ts.snap
+++ b/frontend/src/core/cells/__tests__/__snapshots__/cells.test.ts.snap
@@ -139,6 +139,7 @@ exports[`cell reducer > can initialize stdin > second stdin requested 1`] = `
{
"channel": "stdin",
"data": "what is your name?",
+ "id": 2,
"mimetype": "text/plain",
"response": "Marimo!",
"timestamp": 2,
@@ -146,6 +147,7 @@ exports[`cell reducer > can initialize stdin > second stdin requested 1`] = `
{
"channel": "stdin",
"data": "how old are you?",
+ "id": 3,
"mimetype": "text/plain",
"timestamp": 3,
},
@@ -189,6 +191,7 @@ exports[`cell reducer > can initialize stdin > stdin answered 1`] = `
{
"channel": "stdin",
"data": "what is your name?",
+ "id": 2,
"mimetype": "text/plain",
"response": "Marimo!",
"timestamp": 2,
@@ -233,6 +236,7 @@ exports[`cell reducer > can initialize stdin > stdin requested 1`] = `
{
"channel": "stdin",
"data": "what is your name?",
+ "id": 2,
"mimetype": "text/plain",
"timestamp": 2,
},
diff --git a/frontend/src/core/cells/__tests__/cell.test.ts b/frontend/src/core/cells/__tests__/cell.test.ts
index a0a7c2ea54..d4330bd059 100644
--- a/frontend/src/core/cells/__tests__/cell.test.ts
+++ b/frontend/src/core/cells/__tests__/cell.test.ts
@@ -219,6 +219,45 @@ describe("transitionCell serialization", () => {
});
});
+describe("transitionCell console output ids", () => {
+ const output = (
+ data: string,
+ channel: OutputMessage["channel"] = "stdout",
+ ): OutputMessage => ({
+ channel,
+ mimetype: "text/plain",
+ data,
+ timestamp: 0,
+ });
+
+ it("assigns increasing ids to appended outputs", () => {
+ let cell = createCellRuntimeState({ status: "running" });
+ cell = transitionCell(cell, { console: output("a") } as CellMessage);
+ cell = transitionCell(cell, {
+ console: output("b", "stderr"),
+ } as CellMessage);
+ expect(cell.consoleOutputs.map((o) => o.id)).toEqual([1, 2]);
+ });
+
+ it("continues from the surviving maximum after a collapse", () => {
+ let cell = createCellRuntimeState({ status: "running" });
+ cell = transitionCell(cell, { console: output("a") } as CellMessage);
+ cell = transitionCell(cell, { console: output("b") } as CellMessage);
+ expect(cell.consoleOutputs.map((o) => o.id)).toEqual([1]);
+ cell = transitionCell(cell, {
+ console: output("c", "stderr"),
+ } as CellMessage);
+ expect(cell.consoleOutputs.map((o) => o.id)).toEqual([1, 2]);
+ });
+
+ it("assigns ids when the kernel replaces the whole console", () => {
+ const cell = transitionCell(createCellRuntimeState({ status: "running" }), {
+ console: [output("a"), output("b", "stderr")],
+ } as CellMessage);
+ expect(cell.consoleOutputs.map((o) => o.id)).toEqual([1, 2]);
+ });
+});
+
describe("transitionCell stdin resolution", () => {
describe.each([
{
diff --git a/frontend/src/core/cells/__tests__/cells.test.ts b/frontend/src/core/cells/__tests__/cells.test.ts
index 01fcf601a7..e21487f05f 100644
--- a/frontend/src/core/cells/__tests__/cells.test.ts
+++ b/frontend/src/core/cells/__tests__/cells.test.ts
@@ -1579,7 +1579,9 @@ describe("cell reducer", () => {
response: secret,
});
- expect(cells[0].consoleOutputs).toEqual([{ ...prompt, response: "" }]);
+ expect(cells[0].consoleOutputs).toEqual([
+ { ...prompt, id: 1, response: "" },
+ ]);
expect(JSON.stringify(cells[0].consoleOutputs)).not.toContain(secret);
});
diff --git a/frontend/src/core/cells/__tests__/collapseConsoleOutputs.test.ts b/frontend/src/core/cells/__tests__/collapseConsoleOutputs.test.ts
index 1362329ada..2d28fed09b 100644
--- a/frontend/src/core/cells/__tests__/collapseConsoleOutputs.test.ts
+++ b/frontend/src/core/cells/__tests__/collapseConsoleOutputs.test.ts
@@ -2,6 +2,7 @@
import { describe, expect, it } from "vitest";
import { StatefulOutputMessage } from "@/components/editor/output/ansi-reduce";
+import type { ConsoleOutputMessage } from "@/core/cells/types";
import type { OutputMessage } from "@/core/kernel/messages";
import {
collapseConsoleOutputs,
@@ -279,6 +280,59 @@ describe("collapseConsoleOutputs", () => {
expect(result[0].data).toContain("Streaming output truncated");
});
+ it("keeps the first id when collapsing outputs", () => {
+ const consoleOutputs = [
+ {
+ mimetype: "text/plain",
+ channel: "output",
+ data: "Hello ",
+ timestamp: 0,
+ id: 7,
+ },
+ {
+ mimetype: "text/plain",
+ channel: "output",
+ data: "World",
+ timestamp: 0,
+ id: 8,
+ },
+ ] satisfies ConsoleOutputMessage[];
+ const result = collapseConsoleOutputs(consoleOutputs);
+ expect(result).toHaveLength(1);
+ expect(result[0].data).toBe("Hello World");
+ expect((result[0] as ConsoleOutputMessage).id).toBe(7);
+ });
+
+ it("keeps ids on outputs that survive truncation", () => {
+ const consoleOutputs = [
+ {
+ mimetype: "text/plain",
+ channel: "output",
+ data: "one\ntwo",
+ timestamp: 0,
+ id: 1,
+ },
+ {
+ mimetype: "text/plain",
+ channel: "stderr",
+ data: "three\nfour",
+ timestamp: 0,
+ id: 2,
+ },
+ {
+ mimetype: "text/plain",
+ channel: "output",
+ data: "five",
+ timestamp: 0,
+ id: 3,
+ },
+ ] satisfies ConsoleOutputMessage[];
+ const result = collapseConsoleOutputs(consoleOutputs, 3);
+ const ids = result.map((output) => (output as ConsoleOutputMessage).id);
+ expect(result[0].data).toContain("Streaming output truncated");
+ expect(ids).toEqual([undefined, 2, 3]);
+ });
+
describe("ANSI escape sequences", () => {
it("should handle cursor movement with collapse", () => {
const consoleOutputs: OutputMessage[] = [
diff --git a/frontend/src/core/cells/cell.ts b/frontend/src/core/cells/cell.ts
index cf980c29f5..cfd4591a35 100644
--- a/frontend/src/core/cells/cell.ts
+++ b/frontend/src/core/cells/cell.ts
@@ -7,7 +7,12 @@ import { parseOutline } from "../dom/outline";
import type { CellMessage, OutputMessage } from "../kernel/messages";
import type { RuntimeState } from "../network/types";
import { collapseConsoleOutputs } from "./collapseConsoleOutputs";
-import type { CellRuntimeState } from "./types";
+import type { CellRuntimeState, ConsoleOutputMessage } from "./types";
+
+// Ids increase with position, so the last output holds the maximum.
+function nextConsoleOutputId(outputs: ConsoleOutputMessage[]): number {
+ return (outputs.at(-1)?.id ?? 0) + 1;
+}
export function transitionCell(
cell: CellRuntimeState,
@@ -133,6 +138,7 @@ export function transitionCell(
mimetype: output.mimetype,
data: output.data,
timestamp: output.timestamp,
+ id: output.id,
response: output.response ?? "",
};
}
@@ -146,8 +152,13 @@ export function transitionCell(
// messageConsole is an output that needs to be appended to the
// existing console outputs.
consoleOutputs = Array.isArray(messageConsole)
- ? collapseConsoleOutputs(messageConsole)
- : collapseConsoleOutputs([...consoleOutputs, messageConsole]);
+ ? collapseConsoleOutputs(
+ messageConsole.map((output, i) => ({ ...output, id: i + 1 })),
+ )
+ : collapseConsoleOutputs([
+ ...consoleOutputs,
+ { ...messageConsole, id: nextConsoleOutputId(consoleOutputs) },
+ ]);
}
nextCell.consoleOutputs = consoleOutputs;
// Derive outline from output
diff --git a/frontend/src/core/cells/cells.ts b/frontend/src/core/cells/cells.ts
index 51e83dfb93..428d8c2fed 100644
--- a/frontend/src/core/cells/cells.ts
+++ b/frontend/src/core/cells/cells.ts
@@ -1114,6 +1114,7 @@ const {
mimetype: stdinOutput.mimetype,
data: stdinOutput.data,
timestamp: stdinOutput.timestamp,
+ id: stdinOutput.id,
// An empty response resolves the prompt without retaining the secret.
response: stdinOutput.mimetype === "text/password" ? "" : response,
};
diff --git a/frontend/src/core/cells/types.ts b/frontend/src/core/cells/types.ts
index bb7420d4c7..0193ddf41c 100644
--- a/frontend/src/core/cells/types.ts
+++ b/frontend/src/core/cells/types.ts
@@ -95,7 +95,7 @@ export interface CellRuntimeState {
/** TOC outline */
outline: Outline | null;
/** messages encoding the cell's console outputs. */
- consoleOutputs: WithResponse<OutputMessage>[];
+ consoleOutputs: ConsoleOutputMessage[];
/** current status of the cell */
status: RuntimeState;
/** whether the cell has stale inputs*/
@@ -130,3 +130,12 @@ export type WithResponse<T> = T & {
*/
response?: string;
};
+
+/**
+ * A console output as held by the frontend. The id is assigned when the
+ * output arrives and never changes, so it can identify the output while
+ * neighboring outputs collapse, truncate, or receive a stdin response.
+ */
+export type ConsoleOutputMessage = WithResponse<OutputMessage> & {
+ id?: number;
+};
diff --git a/frontend/src/plugins/impl/chat/chat-ui.tsx b/frontend/src/plugins/impl/chat/chat-ui.tsx
index d6c27cb603..322e99fa2f 100644
--- a/frontend/src/plugins/impl/chat/chat-ui.tsx
+++ b/frontend/src/plugins/impl/chat/chat-ui.tsx
@@ -472,7 +472,7 @@ export const Chatbot: React.FC<Props> = (props) => {
return (
<div
- key={`${message.id}-${index}`}
+ key={message.id}
className={cn(
"flex flex-col group gap-2",
message.role === "user" ? "items-end" : "items-start",