@marimo-team/islands 0.25.3-dev447 → 0.25.3-dev453

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (88) hide show
  1. package/dist/{ErrorBoundary-DVbdKroW.js → ErrorBoundary-CIYMOu2p.js} +1 -1
  2. package/dist/assets/__vite-browser-external-D2z_TiUO.js +1 -0
  3. package/dist/assets/{worker-BUqfWMtI.js → worker-DLJ9P24O.js} +2 -2
  4. package/dist/{chat-ui-9oyUBL6M.js → chat-ui-DEHpKH2l.js} +17 -19
  5. package/dist/{code-visibility-DmsDqWUx.js → code-visibility-BQE60zOk.js} +7 -7
  6. package/dist/{common-BDo_Jwoz.js → common-DfUux6zJ.js} +4902 -4893
  7. package/dist/{data-grid-overlay-editor-CpHB_knU.js → data-grid-overlay-editor-B9zW4oN1.js} +1 -1
  8. package/dist/{error-entries-CWdDf7iZ.js → error-entries-BG7ifiDg.js} +1368 -996
  9. package/dist/{feedback-button-B_Wmi4to.js → feedback-button-BEUh4iQQ.js} +129 -129
  10. package/dist/{glide-data-editor-CMiIW5WP.js → glide-data-editor-CbdIXPTZ.js} +3 -3
  11. package/dist/{globals-DaC3pk9F.js → globals-BkxG-Y8L.js} +1 -1
  12. package/dist/{html-to-image-CexRSGAZ.js → html-to-image-9HLBGrIx.js} +4115 -4103
  13. package/dist/main.js +6562 -6671
  14. package/dist/{number-overlay-editor-Dd4cOJ5I.js → number-overlay-editor-BFzdth50.js} +1 -1
  15. package/dist/{process-output-hcyVRJCC.js → process-output-B8HPq5iZ.js} +2 -2
  16. package/dist/{reveal-component-CTmvBdvu.js → reveal-component-DK_-9fAX.js} +166 -167
  17. package/package.json +1 -1
  18. package/src/__mocks__/executions.ts +7 -4
  19. package/src/__mocks__/notebook.ts +20 -4
  20. package/src/components/editor/cell/DeleteButton.tsx +2 -2
  21. package/src/components/editor/cell/StopButton.tsx +2 -2
  22. package/src/components/editor/cell/useRunCells.ts +0 -3
  23. package/src/components/editor/errors/__tests__/send-error-report-button.test.tsx +1 -1
  24. package/src/components/editor/notebook-cell.tsx +4 -35
  25. package/src/components/editor/output/ansi-reduce.ts +124 -61
  26. package/src/components/editor/output/console/ConsoleOutput.tsx +7 -25
  27. package/src/components/editor/output/console/__tests__/ConsoleOutput.test.tsx +15 -44
  28. package/src/components/editor/renderers/cells-renderer.tsx +2 -5
  29. package/src/components/editor/renderers/grid-layout/__tests__/grid-layout.test.tsx +1 -1
  30. package/src/components/editor/renderers/vertical-layout/vertical-layout.tsx +3 -6
  31. package/src/components/editor/stdin-blocking-alert.tsx +14 -18
  32. package/src/components/scratchpad/scratchpad.test.tsx +1 -1
  33. package/src/components/scratchpad/scratchpad.tsx +5 -6
  34. package/src/components/slides/__tests__/cell-output-block.test.tsx +2 -2
  35. package/src/components/slides/__tests__/slide-cell-view.test.tsx +2 -2
  36. package/src/components/tracing/tracing-spec.ts +11 -1
  37. package/src/components/tracing/tracing.tsx +4 -0
  38. package/src/core/ai/context/providers/__tests__/cell-output.test.ts +10 -20
  39. package/src/core/ai/context/providers/__tests__/error.test.ts +5 -27
  40. package/src/core/ai/context/providers/cell-output.ts +4 -12
  41. package/src/core/cells/__tests__/cell.test.ts +1 -169
  42. package/src/core/cells/__tests__/cells.test.ts +32 -709
  43. package/src/core/cells/__tests__/clear-outputs.test.ts +21 -14
  44. package/src/core/cells/__tests__/collapseConsoleOutputs.test.ts +71 -2
  45. package/src/core/cells/__tests__/logs.test.ts +18 -29
  46. package/src/core/cells/__tests__/runs.test.ts +128 -431
  47. package/src/core/cells/__tests__/session.test.ts +9 -9
  48. package/src/core/cells/actions.ts +29 -7
  49. package/src/core/cells/cell.ts +1 -96
  50. package/src/core/cells/cells.ts +147 -117
  51. package/src/core/cells/collapseConsoleOutputs.tsx +71 -40
  52. package/src/core/cells/command-console.ts +46 -0
  53. package/src/core/cells/execution-console.ts +230 -0
  54. package/src/core/cells/focus.ts +9 -29
  55. package/src/core/cells/logs.ts +10 -2
  56. package/src/core/cells/runs.ts +62 -118
  57. package/src/core/cells/session.ts +2 -2
  58. package/src/core/cells/types.ts +30 -23
  59. package/src/core/cells/useAnswerPrompt.ts +29 -0
  60. package/src/core/errors/error-entries.ts +3 -4
  61. package/src/core/executions/__tests__/atoms.test.ts +6 -20
  62. package/src/core/executions/__tests__/input.test.ts +3 -3
  63. package/src/core/executions/__tests__/output-lifecycle.test.ts +2 -8
  64. package/src/core/executions/atoms.ts +2 -21
  65. package/src/core/executions/index.ts +2 -1
  66. package/src/core/executions/input.ts +4 -3
  67. package/src/core/executions/output.ts +3 -3
  68. package/src/core/islands/__tests__/bridge.test.ts +59 -0
  69. package/src/core/islands/bootstrap.ts +29 -12
  70. package/src/core/islands/bridge.ts +67 -13
  71. package/src/core/kernel/handlers.ts +2 -21
  72. package/src/core/kernel/messages.ts +0 -1
  73. package/src/core/network/types.ts +0 -1
  74. package/src/core/notebook/document/__tests__/codemirror.test.ts +1 -0
  75. package/src/core/notebook/replica/__tests__/executions.test.ts +1 -0
  76. package/src/core/notebook/replica/__tests__/replica.test.ts +113 -0
  77. package/src/core/notebook/replica/replica.ts +106 -12
  78. package/src/core/notebook/replica/resources/executions.ts +57 -4
  79. package/src/core/session/__tests__/backend.test.ts +2 -4
  80. package/src/core/session/__tests__/useNotebookReplica.hook.test.tsx +1 -0
  81. package/src/core/session/__tests__/useNotebookSession.hook.test.tsx +601 -35
  82. package/src/core/session/useNotebookReplica.ts +20 -6
  83. package/src/core/session/useNotebookSession.tsx +63 -33
  84. package/src/core/static/virtual-file-tracker.ts +26 -8
  85. package/src/stories/layout/vertical/one-column.stories.tsx +18 -12
  86. package/dist/assets/__vite-browser-external-CpRgw4M_.js +0 -1
  87. package/src/components/editor/alerts/stdin-blocking-alert.tsx +0 -68
  88. package/src/core/cells/__tests__/__snapshots__/cells.test.ts.snap +0 -703
@@ -45,6 +45,7 @@ import {
45
45
  useReducerActions,
46
46
  } from "./cells";
47
47
  import { resolveColumns } from "./columns";
48
+ import { consoleExecution } from "./execution-console";
48
49
  import { documentOf, focusWhenMounted, modelOf } from "./edit";
49
50
  import {
50
51
  isCodeHidden,
@@ -252,14 +253,33 @@ function clearOutputs(
252
253
  cellIds: readonly CellId[],
253
254
  ): void {
254
255
  clearCellOutputs(store, cellIds);
255
- store.set(notebookAtom, (state) =>
256
- notebookReducer(state, {
257
- type: "clearCellConsoleOutputs",
258
- payload: { cellIds },
259
- }),
260
- );
256
+ for (const cellId of cellIds) {
257
+ store.set(clearCellConsoleOutputAtom, { cellId });
258
+ }
261
259
  }
262
260
 
261
+ export const clearCellConsoleOutputAtom = atom(
262
+ null,
263
+ (get, set, { cellId }: { cellId: CellId }) => {
264
+ const execution = consoleExecution(get, cellId);
265
+ const clearedConsole = execution && {
266
+ executionId: execution.record.id,
267
+ seq: execution.lastSeq ?? -1,
268
+ prompts: new Set(
269
+ [...execution.items.values()]
270
+ .filter((item) => item.kind === "input" && item.status === "pending")
271
+ .map((item) => item.id),
272
+ ),
273
+ };
274
+ set(notebookAtom, (state) =>
275
+ notebookReducer(state, {
276
+ type: "clearCellConsole",
277
+ payload: { cellId, clearedConsole },
278
+ }),
279
+ );
280
+ },
281
+ );
282
+
263
283
  /** Clear one cell's output. */
264
284
  export const clearCellOutputAtom = atom(
265
285
  null,
@@ -636,7 +656,7 @@ export function useCellActions() {
636
656
  // The session feeds the kernel's messages and the document into the
637
657
  // notebook through `useReducerActions`; components get the operations.
638
658
  const {
639
- handleCellMessage: _handleCellMessage,
659
+ setCellReusability: _setCellReusability,
640
660
  addLogs: _addLogs,
641
661
  reconcileDocument: _reconcileDocument,
642
662
  resetCellRuntimes: _resetCellRuntimes,
@@ -656,6 +676,7 @@ export function useCellActions() {
656
676
  const collapseAllCells = useSetAtom(collapseAllCellsAtom);
657
677
  const expandAllCells = useSetAtom(expandAllCellsAtom);
658
678
  const clearCellOutput = useSetAtom(clearCellOutputAtom);
679
+ const clearCellConsoleOutput = useSetAtom(clearCellConsoleOutputAtom);
659
680
  const clearAllCellOutputs = useSetAtom(clearAllCellOutputsAtom);
660
681
  const showCellIfHidden = useSetAtom(showCellIfHiddenAtom);
661
682
  const moveCell = useSetAtom(moveCellAtom);
@@ -707,6 +728,7 @@ export function useCellActions() {
707
728
  collapseAllCells,
708
729
  expandAllCells,
709
730
  clearCellOutput,
731
+ clearCellConsoleOutput,
710
732
  clearAllCellOutputs,
711
733
  showCellIfHidden,
712
734
  }),
@@ -5,102 +5,7 @@ import type {
5
5
  CellRunStatus,
6
6
  } from "@/core/executions";
7
7
  import { extractAllTracebackInfo, type TracebackInfo } from "@/utils/traceback";
8
- import type { CellMessage, OutputMessage } from "../kernel/messages";
9
- import { collapseConsoleOutputs } from "./collapseConsoleOutputs";
10
- import type { CellRuntimeState, ConsoleOutputMessage } from "./types";
11
-
12
- // Ids increase with position, so the last output holds the maximum.
13
- function nextConsoleOutputId(outputs: ConsoleOutputMessage[]): number {
14
- return (outputs.at(-1)?.id ?? 0) + 1;
15
- }
16
-
17
- function errorTypes(output: OutputMessage | null | undefined): string[] {
18
- if (
19
- output == null ||
20
- output.mimetype !== "application/vnd.marimo+error" ||
21
- !Array.isArray(output.data)
22
- ) {
23
- return [];
24
- }
25
- return output.data.map((error) => error.type);
26
- }
27
-
28
- export function transitionCell(
29
- cell: CellRuntimeState,
30
- message: CellMessage,
31
- ): CellRuntimeState {
32
- const nextCell = { ...cell };
33
-
34
- if (message.status === "running" && nextCell.pdbOutput) {
35
- delete nextCell.pdbOutput;
36
- }
37
- if (message.status === "queued") {
38
- nextCell.debuggerActive = false;
39
- }
40
- // Tri-state partial update: an omitted field (undefined) leaves the hint
41
- // unchanged; null explicitly clears it; a string sets it.
42
- if (message.serialization !== undefined) {
43
- nextCell.serialization = message.serialization;
44
- }
45
-
46
- const interrupted = errorTypes(message.output).includes("interruption");
47
-
48
- // Coalesce console outputs, which are streamed during execution.
49
- let consoleOutputs = cell.consoleOutputs;
50
-
51
- // When the cell is interrupted or finishes (idle), there is no live
52
- // stdin/pdb session, so resolve any dangling stdin prompt. This removes the
53
- // debugger box — e.g. after quitting pdb with `q`, which stops the cell
54
- // (idle) rather than interrupting it.
55
- if (interrupted || message.status === "idle") {
56
- nextCell.debuggerActive = false;
57
- consoleOutputs = consoleOutputs.map((output) => {
58
- if (output.channel === "stdin") {
59
- // StatefulOutputMessage exposes data through a getter, which object
60
- // spread would omit.
61
- return {
62
- channel: output.channel,
63
- mimetype: output.mimetype,
64
- data: output.data,
65
- timestamp: output.timestamp,
66
- id: output.id,
67
- input_id: output.input_id,
68
- response: output.response ?? "",
69
- };
70
- }
71
- return output;
72
- });
73
- }
74
-
75
- const messageConsole = message.console;
76
- if (messageConsole != null) {
77
- // The kernel sends an empty array to clear the console; otherwise,
78
- // messageConsole is an output that needs to be appended to the
79
- // existing console outputs.
80
- consoleOutputs = Array.isArray(messageConsole)
81
- ? collapseConsoleOutputs(
82
- messageConsole.map((output, i) => ({ ...output, id: i + 1 })),
83
- )
84
- : collapseConsoleOutputs([
85
- ...consoleOutputs,
86
- { ...messageConsole, id: nextConsoleOutputId(consoleOutputs) },
87
- ]);
88
- }
89
- nextCell.consoleOutputs = consoleOutputs;
90
-
91
- // Transition PDB
92
- const newConsoleOutputs = [message.console].flat().filter(Boolean);
93
- const pdbOutputs = newConsoleOutputs.filter(
94
- (output) => output.channel === "pdb",
95
- );
96
- const hasPdbOutput = pdbOutputs.length > 0;
97
- if (hasPdbOutput && pdbOutputs.some((output) => output.data === "start")) {
98
- nextCell.debuggerActive = true;
99
- }
100
-
101
- return nextCell;
102
- }
103
-
8
+ import type { OutputMessage } from "../kernel/messages";
104
9
  /**
105
10
  * A cell's output is loading if it is running or queued.
106
11
  */
@@ -7,9 +7,9 @@ import { createRef, type ReducerWithoutAction } from "react";
7
7
  import type { CellHandle } from "@/components/editor/notebook-cell";
8
8
  import type { EditableDocument, Placement } from "@/core/notebook/document";
9
9
  import {
10
- type CellOutput,
11
10
  cellExecutionInputsAtom,
12
11
  cellExecutionView,
12
+ executionSource,
13
13
  cellFreshnessAtom,
14
14
  cellOutlineAtom,
15
15
  cellOutputAtom,
@@ -25,12 +25,15 @@ import { foldAllBulk, unfoldAllBulk } from "../codemirror/editing/commands";
25
25
  import { editorMountScheduler } from "../codemirror/editor-mount-scheduler";
26
26
  import type { SerializedEditorState } from "../codemirror/types";
27
27
  import { mergeOutlines } from "../dom/outline";
28
- import { collapseConsoleOutputs } from "./collapseConsoleOutputs";
29
- import type { NotificationMessage, CellMessage } from "../kernel/messages";
28
+ import { confirmedDocumentAtom } from "../session/active-notebook";
30
29
  import { isErrorMime } from "../mime";
31
30
  import { createDeepEqualAtom, store } from "../state/jotai";
32
31
  import { isWasm } from "../wasm/utils";
33
- import { transitionCell } from "./cell";
32
+ import {
33
+ type CommandOutputMessage,
34
+ updateCommandConsole,
35
+ } from "./command-console";
36
+ import { consoleExecution, consoleView } from "./execution-console";
34
37
  import { applyDocument } from "./document";
35
38
  import { isCodeHidden, shownHiddenCodeAtom } from "./editor";
36
39
  import { type CellId, SCRATCH_CELL_ID } from "./ids";
@@ -38,8 +41,6 @@ import { type CellLog, getCellLogsForMessage } from "./logs";
38
41
  import type { Outline } from "./outline";
39
42
  import { focusAndScrollCellIntoView } from "./scrollCellIntoView";
40
43
  import {
41
- withPdbOutput,
42
- type ConsoleOutputMessage,
43
44
  type CellData,
44
45
  type CellRuntimeState,
45
46
  createCell,
@@ -167,61 +168,95 @@ const {
167
168
  useActions,
168
169
  valueAtom: notebookAtom,
169
170
  } = createReducerAndAtoms(initialNotebookState, {
170
- prepareForRun: (state, action: { cellId: CellId }) =>
171
+ setCellReusability: (
172
+ state,
173
+ message: { cell_id: CellId; serialization: string | null },
174
+ ) =>
171
175
  updateCellRuntimeState({
172
176
  state,
173
- cellId: action.cellId,
174
- cellReducer: (cell) => ({ ...cell, debuggerActive: false }),
177
+ cellId: message.cell_id,
178
+ cellReducer: (cell) => ({
179
+ ...cell,
180
+ serialization: message.serialization,
181
+ }),
175
182
  }),
176
- showPdbOutput: (
183
+ startCellConsole: (state, { cellId }: { cellId: CellId }) =>
184
+ updateCellRuntimeState({
185
+ state,
186
+ cellId,
187
+ cellReducer: (cell) => ({
188
+ ...cell,
189
+ embeddedConsole: [],
190
+ commandConsole: undefined,
191
+ answers: undefined,
192
+ clearedConsoleInputs: undefined,
193
+ }),
194
+ }),
195
+ showCommandOutput: (state, message: CommandOutputMessage) => {
196
+ const { cell_id, entries, replace } = message;
197
+ const next = updateCellRuntimeState({
198
+ state,
199
+ cellId: cell_id,
200
+ cellReducer: (cell) => ({
201
+ ...cell,
202
+ commandConsole: updateCommandConsole(
203
+ cell.commandConsole,
204
+ message,
205
+ cell.clearedCommandIds?.[message.op],
206
+ ),
207
+ }),
208
+ });
209
+ // The debugger transcript belongs only to the editor that can see it.
210
+ return replace || message.op === "pdb-output"
211
+ ? next
212
+ : {
213
+ ...next,
214
+ cellLogs: [
215
+ ...next.cellLogs,
216
+ ...getCellLogsForMessage({ cell_id, console: entries }),
217
+ ],
218
+ };
219
+ },
220
+ hideConsoleInputs: (
177
221
  state,
178
222
  {
179
- cell_id,
180
- entries,
181
- replace,
182
- }: Extract<NotificationMessage, { op: "pdb-output" }>,
223
+ cellId,
224
+ executionId,
225
+ inputIds,
226
+ }: { cellId: CellId; executionId: string; inputIds: string[] },
183
227
  ) => {
228
+ const ids = new Set(inputIds);
184
229
  return updateCellRuntimeState({
185
230
  state,
186
- cellId: cell_id,
187
- cellReducer: (cell) => {
188
- let transcript =
189
- replace || entries.length === 0 ? [] : (cell.pdbOutput ?? []);
190
- for (const entry of entries) {
191
- // Execution entries have positive keys.
192
- const output: ConsoleOutputMessage = {
193
- ...entry,
194
- id: (transcript.at(-1)?.id ?? 0) - 1,
195
- };
196
- transcript = collapseConsoleOutputs([...transcript, output]);
197
- }
198
- return { ...cell, pdbOutput: transcript };
199
- },
231
+ cellId,
232
+ cellReducer: (cell) => ({
233
+ ...cell,
234
+ clearedConsoleInputs: { executionId, ids },
235
+ }),
200
236
  });
201
237
  },
202
238
  clearDebuggerOutput: (state) => {
203
239
  const cellRuntime = { ...state.cellRuntime };
204
240
  for (const cellId of Object.keys(cellRuntime) as CellId[]) {
205
- if (cellRuntime[cellId].pdbOutput) {
206
- cellRuntime[cellId] = { ...cellRuntime[cellId], pdbOutput: undefined };
241
+ const cell = cellRuntime[cellId];
242
+ if (
243
+ cell.commandConsole?.entries.some(
244
+ (entry) => entry.source === "pdb-output",
245
+ )
246
+ ) {
247
+ cellRuntime[cellId] = {
248
+ ...cell,
249
+ commandConsole: updateCommandConsole(cell.commandConsole, {
250
+ op: "pdb-output",
251
+ cell_id: cellId,
252
+ entries: [],
253
+ replace: true,
254
+ }),
255
+ };
207
256
  }
208
257
  }
209
258
  return { ...state, cellRuntime };
210
259
  },
211
- handleCellMessage: (state, message: CellMessage) => {
212
- const cellId = message.cell_id;
213
- const nextState = updateCellRuntimeState({
214
- state,
215
- cellId,
216
- cellReducer: (cell) => {
217
- return transitionCell(cell, message);
218
- },
219
- });
220
- return {
221
- ...nextState,
222
- cellLogs: [...nextState.cellLogs, ...getCellLogsForMessage(message)],
223
- };
224
- },
225
260
  addLogs: (state, action: { logs: CellLog[] }) => {
226
261
  return {
227
262
  ...state,
@@ -240,43 +275,23 @@ const {
240
275
  },
241
276
  setStdinResponse: (
242
277
  state,
243
- action: { cellId: CellId; response: string; outputIndex: number },
278
+ action: { cellId: CellId; response: string; inputId: string },
244
279
  ) => {
245
- const { cellId, response, outputIndex } = action;
280
+ const { cellId, response, inputId } = action;
246
281
  return updateCellRuntimeState({
247
282
  state,
248
283
  cellId,
249
- cellReducer: (cell) => {
250
- const consoleOutputs = [...cell.consoleOutputs];
251
- const stdinOutput = consoleOutputs[outputIndex];
252
- if (stdinOutput == null || stdinOutput.channel !== "stdin") {
253
- Logger.warn("Expected stdin output");
254
- return cell;
255
- }
256
-
257
- consoleOutputs[outputIndex] = {
258
- channel: "stdin",
259
- mimetype: stdinOutput.mimetype,
260
- data: stdinOutput.data,
261
- timestamp: stdinOutput.timestamp,
262
- id: stdinOutput.id,
263
- input_id: stdinOutput.input_id,
264
- // An empty response resolves the prompt without retaining the secret.
265
- response: stdinOutput.mimetype === "text/password" ? "" : response,
266
- };
267
-
268
- return {
269
- ...cell,
270
- consoleOutputs,
271
- };
272
- },
284
+ cellReducer: (cell) => ({
285
+ ...cell,
286
+ answers: new Map(cell.answers).set(inputId, response),
287
+ }),
273
288
  });
274
289
  },
275
290
  /**
276
- * Start each cell's runtime over for a new kernel. WASM keeps the console
277
- * output its mount-time snapshot gave it.
291
+ * WASM keeps its mount-time snapshot. A resumed kernel replays execution
292
+ * items, so the browser also keeps the watermark for rows it hid.
278
293
  */
279
- resetCellRuntimes: (state) => {
294
+ resetCellRuntimes: (state, resumed?: boolean) => {
280
295
  const preserveSnapshot = isWasm();
281
296
  const cellRuntime = { ...state.cellRuntime };
282
297
  for (const cellId of [...state.cellIds, SCRATCH_CELL_ID]) {
@@ -284,8 +299,15 @@ const {
284
299
  const hasSnapshot =
285
300
  preserveSnapshot &&
286
301
  previous !== undefined &&
287
- previous.consoleOutputs.length > 0;
288
- cellRuntime[cellId] = hasSnapshot ? previous : createCellRuntimeState();
302
+ previous.embeddedConsole.length > 0;
303
+ cellRuntime[cellId] = hasSnapshot
304
+ ? previous
305
+ : createCellRuntimeState({
306
+ clearedConsole: resumed ? previous?.clearedConsole : undefined,
307
+ clearedCommandIds: resumed
308
+ ? previous?.clearedCommandIds
309
+ : undefined,
310
+ });
289
311
  }
290
312
  return { ...state, cellRuntime };
291
313
  },
@@ -334,36 +356,37 @@ const {
334
356
  cellLogs: [],
335
357
  };
336
358
  },
337
- clearCellConsoleOutput: (state, action: { cellId: CellId }) => {
338
- return clearConsoleOutputs(state, [action.cellId]);
339
- },
340
- clearCellConsoleOutputs: (state, action: { cellIds: readonly CellId[] }) => {
341
- return clearConsoleOutputs(state, action.cellIds);
342
- },
359
+ clearCellConsole: (
360
+ state,
361
+ action: {
362
+ cellId: CellId;
363
+ clearedConsole?: CellRuntimeState["clearedConsole"];
364
+ },
365
+ ) =>
366
+ updateCellRuntimeState({
367
+ state,
368
+ cellId: action.cellId,
369
+ cellReducer: (cell) => {
370
+ const clearedCommandIds = { ...cell.clearedCommandIds };
371
+ for (const entry of cell.commandConsole?.entries ?? []) {
372
+ if (entry.command_id !== undefined) {
373
+ clearedCommandIds[entry.source] = entry.command_id;
374
+ }
375
+ }
376
+ return {
377
+ ...cell,
378
+ commandConsole: undefined,
379
+ clearedCommandIds,
380
+ clearedConsole: action.clearedConsole,
381
+ embeddedConsole: cell.embeddedConsole.filter(
382
+ (output) =>
383
+ output.channel === "stdin" && output.response === undefined,
384
+ ),
385
+ };
386
+ },
387
+ }),
343
388
  });
344
389
 
345
- function clearConsoleOutputs(
346
- state: NotebookState,
347
- cellIds: readonly CellId[],
348
- ): NotebookState {
349
- const cellRuntime = { ...state.cellRuntime };
350
- for (const cellId of cellIds) {
351
- const cell = cellRuntime[cellId];
352
- if (cell === undefined) {
353
- Logger.warn(`Cell ${cellId} not found in state`);
354
- continue;
355
- }
356
- cellRuntime[cellId] = {
357
- ...cell,
358
- pdbOutput: undefined,
359
- consoleOutputs: cell.consoleOutputs.filter(
360
- (output) => output.channel === "stdin" && output.response == null,
361
- ),
362
- };
363
- }
364
- return { ...state, cellRuntime };
365
- }
366
-
367
390
  // Helper function to update a cell in the array
368
391
  function updateCellRuntimeState({
369
392
  state,
@@ -558,9 +581,20 @@ export const hasCellsAtom = atom((get) => get(notebookAtom).cellIds.length > 0);
558
581
  export const cellDataAtom = atomFamily((cellId: CellId) =>
559
582
  atom((get) => get(notebookAtom).cellData[cellId]),
560
583
  );
561
- const cellRuntimeAtom = atomFamily((cellId: CellId) =>
562
- atom((get) => withPdbOutput(get(notebookAtom).cellRuntime[cellId])),
563
- );
584
+ const EMPTY_RUNTIME = createCellRuntimeState();
585
+ export const cellRuntimeAtom = atomFamily((cellId: CellId) => {
586
+ const inputs = atom((get) => {
587
+ const execution = consoleExecution(get, cellId);
588
+ const cells = get(confirmedDocumentAtom)?.cells;
589
+ return {
590
+ local: get(notebookAtom).cellRuntime[cellId] ?? EMPTY_RUNTIME,
591
+ execution,
592
+ code: execution && executionSource(execution.record, cells),
593
+ };
594
+ });
595
+ const view = selectAtom(inputs, consoleView);
596
+ return atom((get) => get(view).rendered);
597
+ });
564
598
  export const cellHandleAtom = atomFamily((cellId: CellId) =>
565
599
  atom((get) => get(notebookAtom).cellHandles[cellId]),
566
600
  );
@@ -617,17 +651,13 @@ export const ensureCellEditorView = (cellId: CellId) => {
617
651
  };
618
652
 
619
653
  /** The document's cells with their runtime state and what each shows. */
620
- export function flattenTopLevelNotebookCells(
621
- state: NotebookState,
622
- outputs: ReadonlyMap<CellId, CellOutput>,
623
- ): RuntimeCell[] {
624
- const { cellIds, cellData, cellRuntime } = state;
625
- return cellIds.map((cellId) => ({
626
- ...cellData[cellId],
627
- ...withPdbOutput(cellRuntime[cellId]),
628
- output: outputs.get(cellId) ?? null,
629
- }));
630
- }
654
+ export const renderedNotebookCellsAtom = atom((get): RuntimeCell[] =>
655
+ get(cellIdsAtom).map((cellId) => ({
656
+ ...get(cellDataAtom(cellId)),
657
+ ...get(cellRuntimeAtom(cellId)),
658
+ output: get(cellOutputAtom(cellId)),
659
+ })),
660
+ );
631
661
 
632
662
  export function createTracebackInfoAtom(
633
663
  cellId: CellId,
@@ -3,41 +3,60 @@ import {
3
3
  StatefulOutputMessage,
4
4
  type StringOutputMessage,
5
5
  } from "@/components/editor/output/ansi-reduce";
6
- import type { OutputMessage } from "@/core/kernel/messages";
6
+ import type { ConsoleOutputMessage as OutputMessage } from "./types";
7
7
  import { invariant } from "@/utils/invariant";
8
8
 
9
- /**
10
- * Collapses the last text/plain cells with the preceding one on the same
11
- * channel (if any), and handles bare carriage returns ("\r").
12
- */
9
+ const MAX_CONSOLE_LINES = 5000;
10
+
11
+ /** Merge the last write with the preceding row when both use the same text channel. */
13
12
  export function collapseConsoleOutputs(
14
13
  consoleOutputs: OutputMessage[],
15
- maxLines = 5000,
14
+ maxLines = MAX_CONSOLE_LINES,
16
15
  ): OutputMessage[] {
17
- const newConsoleOutputs = [...consoleOutputs];
18
-
19
- if (newConsoleOutputs.length < 2) {
20
- return truncateHead(
21
- newConsoleOutputs.map(maybeMakeOutputStateful),
22
- maxLines,
23
- );
16
+ const outputs = consoleOutputs.slice(0, -1);
17
+ const last = consoleOutputs.at(-1);
18
+ if (last) {
19
+ appendOutput(outputs, last);
24
20
  }
21
+ return truncateHead(outputs, maxLines);
22
+ }
25
23
 
26
- const lastOutput = newConsoleOutputs[newConsoleOutputs.length - 1];
27
- const secondLastOutput = newConsoleOutputs[newConsoleOutputs.length - 2];
28
-
29
- if (shouldCollapse(lastOutput, secondLastOutput)) {
30
- assertStringOutputMessage(lastOutput);
31
- assertStringOutputMessage(secondLastOutput);
32
-
33
- newConsoleOutputs[newConsoleOutputs.length - 2] = mergeLeft(
34
- secondLastOutput,
35
- lastOutput,
36
- );
37
- newConsoleOutputs.pop();
24
+ /** Rebuild the visible rows from a replay, carrying ANSI state across adjacent writes. */
25
+ export function collapseConsoleBatch(
26
+ entries: OutputMessage[],
27
+ ): OutputMessage[] {
28
+ const rows: OutputMessage[] = [];
29
+ for (let start = 0; start < entries.length;) {
30
+ const first = entries[start];
31
+ let end = start + 1;
32
+ while (end < entries.length && shouldCollapse(first, entries[end])) {
33
+ end++;
34
+ }
35
+ if (end === start + 1) {
36
+ appendOutput(rows, first);
37
+ } else {
38
+ const text = entries.slice(start, end).map((entry) => {
39
+ assertStringOutputMessage(entry);
40
+ return entry.data;
41
+ });
42
+ rows.push(
43
+ StatefulOutputMessage.create({ ...first, data: text.join("") }),
44
+ );
45
+ }
46
+ start = end;
38
47
  }
48
+ return truncateHead(rows, MAX_CONSOLE_LINES);
49
+ }
39
50
 
40
- return truncateHead(newConsoleOutputs, maxLines);
51
+ function appendOutput(outputs: OutputMessage[], entry: OutputMessage): void {
52
+ const last = outputs.at(-1);
53
+ if (last && shouldCollapse(last, entry)) {
54
+ assertStringOutputMessage(last);
55
+ assertStringOutputMessage(entry);
56
+ outputs[outputs.length - 1] = mergeLeft(last, entry);
57
+ } else {
58
+ outputs.push(maybeMakeOutputStateful(entry));
59
+ }
41
60
  }
42
61
 
43
62
  function shouldCollapse(
@@ -60,7 +79,11 @@ export function maybeMakeOutputStateful(output: OutputMessage): OutputMessage {
60
79
  if (output instanceof StatefulOutputMessage) {
61
80
  return output;
62
81
  }
63
- if (typeof output.data === "string") {
82
+ if (
83
+ output.mimetype === "text/plain" &&
84
+ output.channel !== "stdin" &&
85
+ typeof output.data === "string"
86
+ ) {
64
87
  return StatefulOutputMessage.create(output as StringOutputMessage);
65
88
  }
66
89
  return output;
@@ -90,7 +113,10 @@ function truncateHead(consoleOutputs: OutputMessage[], limit: number) {
90
113
  const output: OutputMessage = consoleOutputs[i];
91
114
  if (output.mimetype === "text/plain") {
92
115
  invariant(typeof output.data === "string", "expected string");
93
- nLines += output.data.split("\n").length;
116
+ nLines +=
117
+ output instanceof StatefulOutputMessage
118
+ ? output.lineCount
119
+ : output.data.split("\n").length;
94
120
  } else {
95
121
  nLines++;
96
122
  }
@@ -107,20 +133,25 @@ function truncateHead(consoleOutputs: OutputMessage[], limit: number) {
107
133
  data: `<pre>Streaming output truncated to last ${limit} lines.\n</pre>`,
108
134
  timestamp: -1,
109
135
  };
136
+ const pending = consoleOutputs
137
+ .slice(0, cutoff)
138
+ .filter((row) => row.channel === "stdin" && row.response === undefined);
139
+ const retained = [warningOutput, ...pending];
110
140
  const output = consoleOutputs[cutoff];
111
- if (output == null) {
112
- return [warningOutput, ...consoleOutputs.slice(cutoff + 1)];
141
+ if (output?.channel === "stdin" && output.response === undefined) {
142
+ return [...retained, ...consoleOutputs.slice(cutoff)];
113
143
  }
114
- if (output.mimetype === "text/plain") {
144
+ if (output?.mimetype === "text/plain") {
115
145
  invariant(typeof output.data === "string", "expected string");
116
- const outputLines = output.data.split("\n");
117
- const nLinesAfterOutput = nLines - outputLines.length;
118
- const nLinesToKeep = limit - nLinesAfterOutput;
119
- return [
120
- warningOutput,
121
- { ...output, data: outputLines.slice(-nLinesToKeep).join("\n") },
122
- ...consoleOutputs.slice(cutoff + 1),
123
- ];
146
+ const dropLines = nLines - limit;
147
+ const tail =
148
+ output instanceof StatefulOutputMessage
149
+ ? output.dropFirstLines(dropLines)
150
+ : {
151
+ ...output,
152
+ data: output.data.split("\n").slice(dropLines).join("\n"),
153
+ };
154
+ return [...retained, tail, ...consoleOutputs.slice(cutoff + 1)];
124
155
  }
125
- return [warningOutput, ...consoleOutputs.slice(cutoff + 1)];
156
+ return [...retained, ...consoleOutputs.slice(cutoff + 1)];
126
157
  }