@marimo-team/islands 0.25.3-dev446 → 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-CBvdOZsh.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-BVsBD2bm.js → code-visibility-BQE60zOk.js} +7 -7
  6. package/dist/{common-Cz5kXzjw.js → common-DfUux6zJ.js} +4902 -4893
  7. package/dist/{data-grid-overlay-editor-B-PHwg_F.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-DKfgWMh1.js → feedback-button-BEUh4iQQ.js} +129 -129
  10. package/dist/{glide-data-editor-BMrcgCud.js → glide-data-editor-CbdIXPTZ.js} +3 -3
  11. package/dist/{globals-vjja83iL.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-CQvIdVeX.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-DF7VRfN2.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
@@ -1,14 +1,24 @@
1
1
  /* Copyright 2026 Marimo. All rights reserved. */
2
2
  /* oxlint-disable typescript/no-explicit-any */
3
3
 
4
- import { NotebookClient, type NotebookTransport } from "@marimo-team/client";
4
+ import {
5
+ NotebookClient,
6
+ type NotebookEvent,
7
+ type NotebookTransport,
8
+ } from "@marimo-team/client";
5
9
  import { getWorkerRPC } from "@/core/wasm/rpc";
6
10
  import { Deferred } from "@/utils/Deferred";
7
11
  import { throwNotImplemented } from "@/utils/functions";
8
12
  import { Logger } from "@/utils/Logger";
9
13
  import { jsonParseWithSpecialChar } from "@/utils/json/json-parser";
10
14
  import { generateUUID } from "@/utils/uuid";
11
- import { initialNotebookState, notebookAtom } from "../cells/cells";
15
+ import {
16
+ initialNotebookState,
17
+ notebookAtom,
18
+ notebookReducer,
19
+ } from "../cells/cells";
20
+ import type { CellId } from "../cells/ids";
21
+ import { getCellLogsForMessage } from "../cells/logs";
12
22
  import type { NotebookBackend } from "../notebook/replica";
13
23
  import type { ClientCommand, NotificationMessage } from "../kernel/messages";
14
24
  import type { EditRequests, RunRequests } from "../network/types";
@@ -69,7 +79,8 @@ export class IslandsPyodideBridge implements RunRequests, EditRequests {
69
79
  private session: AppSession | undefined;
70
80
  private sessionReady = new Deferred<AppSession>();
71
81
  private nextSessionGeneration = 0;
72
- private readonly activeSessionGenerations = new Set<number>();
82
+ /** The host retains one execution per cell and removes it before its replacement. */
83
+ private readonly activeSessions = new Map<number, Map<string, CellId>>();
73
84
  private appTransition = Promise.resolve();
74
85
  private workerReady = new Deferred<void>();
75
86
  /** Where the managed session's host events go while a replica follows them. */
@@ -159,13 +170,13 @@ export class IslandsPyodideBridge implements RunRequests, EditRequests {
159
170
  ({ event, sessionGeneration }) => {
160
171
  // A stopped session can still have events in transit after the next
161
172
  // app takes ownership of the shared frontend state.
162
- if (!this.activeSessionGenerations.has(sessionGeneration)) {
173
+ const cells = this.activeSessions.get(sessionGeneration);
174
+ if (!cells) {
163
175
  return;
164
176
  }
165
- const frame = jsonParseWithSpecialChar(event) as {
166
- event: string;
167
- data: { marimo?: NotificationMessage };
168
- };
177
+ const frame = jsonParseWithSpecialChar(event) as
178
+ | NotebookEvent
179
+ | { event: "marimo"; data: { marimo?: NotificationMessage } };
169
180
  if (frame.event === "marimo") {
170
181
  if (frame.data.marimo) {
171
182
  this.notificationConsumer?.(frame.data.marimo, sessionGeneration);
@@ -175,11 +186,53 @@ export class IslandsPyodideBridge implements RunRequests, EditRequests {
175
186
  // The replica follows the managed session's host document.
176
187
  if (sessionGeneration === this.session?.sessionGeneration) {
177
188
  this.stream?.message(frame);
189
+ } else {
190
+ this.logIslandConsole(cells, frame);
178
191
  }
179
192
  },
180
193
  );
181
194
  }
182
195
 
196
+ private logIslandConsole(cells: Map<string, CellId>, frame: NotebookEvent) {
197
+ switch (frame.event) {
198
+ case "reset":
199
+ cells.clear();
200
+ break;
201
+ case "execution": {
202
+ const { id, cell_id } = frame.data.execution;
203
+ if (cell_id !== null) {
204
+ cells.set(id, cell_id as CellId);
205
+ }
206
+ break;
207
+ }
208
+ case "execution.removed":
209
+ cells.delete(frame.data.id);
210
+ break;
211
+ case "console": {
212
+ const entry = frame.data.console;
213
+ const cellId = cells.get(entry.execution_id);
214
+ // Snapshot rows have no cursor. Only live writes belong in the logs.
215
+ if (frame.id !== undefined && cellId !== undefined) {
216
+ const logs = getCellLogsForMessage({
217
+ cell_id: cellId,
218
+ console: {
219
+ channel: entry.name,
220
+ mimetype: "text/plain",
221
+ data: entry.text,
222
+ timestamp: frame.data.time
223
+ ? Date.parse(frame.data.time) / 1000
224
+ : Date.now() / 1000,
225
+ },
226
+ });
227
+ this.store.set(notebookAtom, (state) =>
228
+ notebookReducer(state, { type: "addLogs", payload: { logs } }),
229
+ );
230
+ }
231
+ break;
232
+ }
233
+ }
234
+ }
235
+
183
236
  /** The managed session is gone, so its stream starts over. */
184
237
  private resetNotebookStream(): void {
185
238
  this.stream?.message({ event: "reset", data: {} });
@@ -220,7 +273,7 @@ export class IslandsPyodideBridge implements RunRequests, EditRequests {
220
273
  return;
221
274
  }
222
275
  if (apps.length > 0) {
223
- this.activeSessionGenerations.clear();
276
+ this.activeSessions.clear();
224
277
  this.store.set(
225
278
  islandsPendingInitialRunsAtom,
226
279
  new Set(apps.map((_, index) => this.nextSessionGeneration + index + 1)),
@@ -237,7 +290,7 @@ export class IslandsPyodideBridge implements RunRequests, EditRequests {
237
290
  };
238
291
  const previousSession = this.session;
239
292
  const replacesSession = managesSingleApp && previousSession !== undefined;
240
- this.activeSessionGenerations.add(request.sessionGeneration);
293
+ this.activeSessions.set(request.sessionGeneration, new Map());
241
294
  if (replacesSession) {
242
295
  this.resetNotebookStream();
243
296
  this.store.set(notebookAtom, initialNotebookState());
@@ -260,12 +313,13 @@ export class IslandsPyodideBridge implements RunRequests, EditRequests {
260
313
  this.sessionReady.resolve(this.session);
261
314
  }
262
315
  } catch (error) {
263
- this.activeSessionGenerations.delete(request.sessionGeneration);
316
+ this.activeSessions.delete(request.sessionGeneration);
264
317
  if (this.session?.sessionGeneration === request.sessionGeneration) {
265
318
  this.session = previousSession;
266
319
  if (previousSession) {
267
- this.activeSessionGenerations.add(
320
+ this.activeSessions.set(
268
321
  previousSession.sessionGeneration,
322
+ new Map(),
269
323
  );
270
324
  }
271
325
  }
@@ -283,7 +337,7 @@ export class IslandsPyodideBridge implements RunRequests, EditRequests {
283
337
  if (session?.code === undefined || (appId && session.appId !== appId)) {
284
338
  return;
285
339
  }
286
- this.activeSessionGenerations.delete(session.sessionGeneration);
340
+ this.activeSessions.delete(session.sessionGeneration);
287
341
  await this.rpc.proxy.request.stopSession({
288
342
  appId: session.appId,
289
343
  sessionGeneration: session.sessionGeneration,
@@ -8,11 +8,7 @@ import { UI_ELEMENT_REGISTRY } from "../dom/uiregistry";
8
8
  import { deserializeLayoutState } from "../layout/layout";
9
9
  import type { LayoutData, LayoutState } from "../layout/state";
10
10
  import { VirtualFileTracker } from "../static/virtual-file-tracker";
11
- import type {
12
- Capabilities,
13
- CellMessage,
14
- NotificationMessageData,
15
- } from "./messages";
11
+ import type { Capabilities, NotificationMessageData } from "./messages";
16
12
 
17
13
  type KernelReadyData = NotificationMessageData<"kernel-ready">;
18
14
 
@@ -56,7 +52,7 @@ export function handleKernelReady(
56
52
  const { cells, resetCellRuntimes, setLayoutData, setCapabilities } = opts;
57
53
  const { resumed, ui_values, capabilities } = data;
58
54
 
59
- resetCellRuntimes();
55
+ resetCellRuntimes(resumed);
60
56
  const layoutState = buildLayoutState(data, cells, setLayoutData);
61
57
 
62
58
  setCapabilities(capabilities);
@@ -84,18 +80,3 @@ export function handleRemoveUIElements(
84
80
  UI_ELEMENT_REGISTRY.removeElementsByCell(cellId);
85
81
  VirtualFileTracker.INSTANCE.removeForCellId(cellId);
86
82
  }
87
-
88
- export function handleCellNotificationeration(
89
- data: NotificationMessageData<"cell-op">,
90
- handleCellMessage: (message: CellMessage) => void,
91
- ) {
92
- /* Register a state transition for a cell.
93
- *
94
- * The cell may have a new output, a new console output,
95
- * it may have been queued, it may have started running, or
96
- * it may have stopped running. Each of these things
97
- * affects how the cell should be rendered.
98
- */
99
- handleCellMessage(data);
100
- VirtualFileTracker.INSTANCE.track(data);
101
- }
@@ -46,7 +46,6 @@ export type DataSourceDiscoveryResult =
46
46
  NotificationMessageData<"data-source-discovery-result">;
47
47
  export type SecretKeysResult = NotificationMessageData<"secret-keys-result">;
48
48
  export type StartupLogs = NotificationMessageData<"startup-logs">;
49
- export type CellMessage = NotificationMessageData<"cell-op">;
50
49
  export type Capabilities =
51
50
  NotificationMessageData<"kernel-ready">["capabilities"];
52
51
  export type CacheInfoFetched = NotificationMessageData<"cache-info">;
@@ -13,7 +13,6 @@ export type CellConfig = schemas["CellConfig"];
13
13
  * idle: not running.
14
14
  * disabled-transitively: disabled because an ancestor was disabled.
15
15
  */
16
- export type RuntimeState = schemas["CellNotification"]["status"];
17
16
  export type CodeCompletionRequest = schemas["CodeCompletionRequest"];
18
17
  export type AutoExportAsIPYNBRequest = schemas["AutoExportAsIPYNBRequest"];
19
18
  export type AutoExportAsMarkdownRequest =
@@ -83,6 +83,7 @@ function languages(id: CellId) {
83
83
  collapseAllCells: vi.fn(),
84
84
  expandAllCells: vi.fn(),
85
85
  clearCellOutput: vi.fn(),
86
+ clearCellConsoleOutput: vi.fn(),
86
87
  clearAllCellOutputs: vi.fn(),
87
88
  showCellIfHidden: vi.fn(),
88
89
  moveCell: vi.fn(),
@@ -159,6 +159,7 @@ describe("executions resource", () => {
159
159
  ["console", "o-input-2", 2],
160
160
  ["input", "i2", "cancelled"],
161
161
  ]);
162
+ expect(execution!.items.get("i1")?.time).toBe("2026-11-03T14:00:03Z");
162
163
  expect(prompted.latest.size).toBe(0);
163
164
  const gone = resource(replay(inputs, start));
164
165
  expect(gone.executions.has("e-input")).toBe(false);
@@ -152,6 +152,34 @@ describe("NotebookReplica lifetime", () => {
152
152
  expect(store.get(client.notebookAtom)).toBeNull();
153
153
  });
154
154
 
155
+ it.each(["r1", "new-runtime", null])(
156
+ "restores completed scratch output only for its runtime (snapshot runtime %s)",
157
+ async (runtimeId) => {
158
+ const { connect, opened, client, store } = setup();
159
+ connect(lifetime().signal);
160
+ const { receive } = await opened();
161
+ const events = fixtureEvents("notebook-events.sse");
162
+ events.forEach(receive);
163
+ const previous = store.get(client.executionsAtom).scratchConsole;
164
+ expect(previous?.items.get("o3")).toMatchObject({ text: "2\n" });
165
+
166
+ receive({ event: "reset", data: {} });
167
+ for (const event of events) {
168
+ if (event.event === "notebook" || event.event === "ready") {
169
+ receive(event);
170
+ } else if (event.event === "runtime" && runtimeId !== null) {
171
+ receive({
172
+ ...event,
173
+ data: { runtime: { ...event.data.runtime, id: runtimeId } },
174
+ });
175
+ }
176
+ }
177
+ expect(store.get(client.executionsAtom).scratchConsole).toBe(
178
+ runtimeId === "r1" ? previous : undefined,
179
+ );
180
+ },
181
+ );
182
+
155
183
  it("rebuilds the replica after a reconnect reset selects a new notebook", async () => {
156
184
  vi.useFakeTimers();
157
185
  const { connect, opened, client, store } = setup();
@@ -482,6 +510,91 @@ describe("NotebookReplica lifetime", () => {
482
510
  data: { op: "interrupted" },
483
511
  });
484
512
  });
513
+
514
+ it("delivers startup notifications immediately and snapshot notifications after the document", async () => {
515
+ const { connect, opened, onNotification, client, store } = setup();
516
+ connect(lifetime().signal);
517
+ const { receive } = await opened();
518
+ const startup = { op: "startup-progress", phase: "starting-kernel" };
519
+ receive({ event: "marimo", data: { marimo: startup } });
520
+ expect(onNotification).toHaveBeenCalledExactlyOnceWith({ data: startup });
521
+ onNotification.mockClear();
522
+
523
+ const snapshot = fixtureMessages("notebook-events.sse");
524
+ const readyIndex = snapshot.findIndex((event) => event.event === "ready");
525
+ snapshot.slice(0, readyIndex).forEach(receive);
526
+ const cellOutput = { op: "pdb-output", cell_id: "c1", entries: [] };
527
+ receive(kernelReady);
528
+ receive({ event: "marimo", data: { marimo: cellOutput } });
529
+ expect(onNotification).not.toHaveBeenCalled();
530
+ onNotification.mockImplementation(() => {
531
+ expect(store.get(client.documentAtom)?.revision.order).toContain("c1");
532
+ });
533
+
534
+ receive(snapshot[readyIndex]);
535
+ expect(onNotification.mock.calls).toEqual([
536
+ [{ data: kernelReady.data.marimo }],
537
+ [{ data: cellOutput }],
538
+ ]);
539
+ });
540
+
541
+ it("discards notifications from a snapshot interrupted by a dropped connection", async () => {
542
+ vi.useFakeTimers();
543
+ const { connect, opened, onNotification } = setup();
544
+ connect(lifetime().signal);
545
+ const first = await opened();
546
+ first.receive({ event: "notebook", data: { notebook } });
547
+ first.receive(kernelReady);
548
+ expect(onNotification).not.toHaveBeenCalled();
549
+ first.drop();
550
+ await backoff();
551
+
552
+ const next = await opened();
553
+ fixtureMessages("notebook-events.sse").forEach(next.receive);
554
+ expect(onNotification).not.toHaveBeenCalled();
555
+ });
556
+
557
+ it("stops delivering snapshot notifications when a callback disconnects", async () => {
558
+ const { connect, opened, onNotification } = setup();
559
+ const current = lifetime();
560
+ connect(current.signal);
561
+ const { receive } = await opened();
562
+ receive({ event: "notebook", data: { notebook } });
563
+ receive(kernelReady);
564
+ receive({ event: "marimo", data: { marimo: { op: "interrupted" } } });
565
+ onNotification.mockImplementationOnce(() => current.abort());
566
+
567
+ receive({ event: "ready", id: "1", data: {} });
568
+ expect(onNotification).toHaveBeenCalledExactlyOnceWith({
569
+ data: kernelReady.data.marimo,
570
+ });
571
+ });
572
+
573
+ it("delivers the rest of a snapshot when a notification callback throws", async () => {
574
+ const { connect, opened, onNotification } = setup();
575
+ connect(lifetime().signal);
576
+ const { receive } = await opened();
577
+ receive({ event: "notebook", data: { notebook } });
578
+ receive(kernelReady);
579
+ const interrupted = { op: "interrupted" };
580
+ receive({ event: "marimo", data: { marimo: interrupted } });
581
+ const error = new Error("notification failed");
582
+ onNotification.mockImplementationOnce(() => {
583
+ throw error;
584
+ });
585
+ const report = vi
586
+ .spyOn(globalThis, "queueMicrotask")
587
+ .mockImplementation(vi.fn());
588
+ onTestFinished(() => report.mockRestore());
589
+
590
+ receive({ event: "ready", id: "1", data: {} });
591
+ expect(onNotification.mock.calls).toEqual([
592
+ [{ data: kernelReady.data.marimo }],
593
+ [{ data: interrupted }],
594
+ ]);
595
+ expect(report).toHaveBeenCalledOnce();
596
+ expect(report.mock.calls[0][0]).toThrow(error);
597
+ });
485
598
  });
486
599
 
487
600
  describe("NotebookReplica attachments", () => {
@@ -26,6 +26,7 @@ import {
26
26
  import { attachments } from "./resources/attachments";
27
27
  import { type Document, document } from "./resources/document";
28
28
  import {
29
+ type Item,
29
30
  type Executions,
30
31
  executions,
31
32
  resumeResults,
@@ -36,7 +37,7 @@ import { runtime } from "./resources/runtime";
36
37
  /**
37
38
  * The kinds the editor reads, with marimo's own notifications.
38
39
  *
39
- * Console, display and stdin still render from the native console (MO-8405).
40
+ * Execution items provide the console, side-effect displays and input prompts.
40
41
  */
41
42
  export const EDITOR_EVENT_TYPES = [
42
43
  "notebook",
@@ -46,6 +47,9 @@ export const EDITOR_EVENT_TYPES = [
46
47
  "runtime",
47
48
  "run",
48
49
  "execution",
50
+ "console",
51
+ "display",
52
+ "input",
49
53
  "variable",
50
54
  "marimo",
51
55
  ] as const;
@@ -115,8 +119,14 @@ export interface NotebookReplica {
115
119
  options: {
116
120
  /** Handle a native marimo notification. Its payload has not been validated. */
117
121
  onNotification: (notification: unknown) => void;
118
- /** Observe execution records as they arrive, including retained values on reconnect. */
119
- onExecution?: (record: HostExecution) => void;
122
+ /** Observe an item for live logs and virtual files in an export. */
123
+ onItem?: (record: HostExecution, item: Item, live: boolean) => void;
124
+ /**
125
+ * Export tracks file references from each execution as it arrives, including
126
+ * restored results and updates to completed values. Execution history uses
127
+ * `lifecycleChanged` to record restored executions and live status changes.
128
+ */
129
+ onExecution?: (record: HostExecution, lifecycleChanged: boolean) => void;
120
130
  },
121
131
  ): () => void;
122
132
  /** Restore the current connection after its stream closed, if the host is healthy. */
@@ -233,6 +243,7 @@ export function createNotebookReplica(
233
243
  executions: resumeResults(
234
244
  next.resources.executions,
235
245
  retained.resources.executions,
246
+ next.resources.runtime?.id,
236
247
  ),
237
248
  },
238
249
  };
@@ -276,7 +287,11 @@ export function createNotebookReplica(
276
287
 
277
288
  function connect(
278
289
  connected: NotebookBackend,
279
- { onNotification, onExecution }: Parameters<NotebookReplica["connect"]>[1],
290
+ {
291
+ onNotification,
292
+ onExecution,
293
+ onItem,
294
+ }: Parameters<NotebookReplica["connect"]>[1],
280
295
  ) {
281
296
  current?.end();
282
297
  const lifetime = new AbortController();
@@ -286,10 +301,11 @@ export function createNotebookReplica(
286
301
  const { transport } = connected;
287
302
  let events: NotebookEvents<(typeof EDITOR_EVENT_TYPES)[number]> | undefined;
288
303
  let checkingHealth = false;
289
-
304
+ let pendingNotifications: unknown[] = [];
290
305
  /** Mirror one stream into the atoms until it closes. */
291
306
  function follow(cursor?: string) {
292
307
  if (cursor === undefined) {
308
+ pendingNotifications = [];
293
309
  setStream(reducer.initial);
294
310
  }
295
311
  const current = new NotebookEvents(transport, {
@@ -327,23 +343,48 @@ export function createNotebookReplica(
327
343
 
328
344
  function stopMalformed(source: NotebookEvents<string>) {
329
345
  source.close();
346
+ pendingNotifications = [];
330
347
  // The cursor can already include an event the replica rejected.
331
348
  clear(malformed);
332
349
  }
333
350
 
351
+ function observeExecution(
352
+ record: HostExecution,
353
+ lifecycleChanged: boolean,
354
+ ) {
355
+ try {
356
+ onExecution?.(record, lifecycleChanged);
357
+ } catch (error) {
358
+ Logger.error("Failed to handle execution update", error);
359
+ }
360
+ }
361
+
334
362
  function apply(source: NotebookEvents<string>, event: EditorEvent) {
335
363
  if (event.event === "marimo") {
336
364
  const message = MarimoMessage.safeParse(event.data);
337
365
  if (message.success) {
338
- onNotification(message.data.marimo);
366
+ const stream = store.get(streamAtom);
367
+ if (stream.phase === "snapshot" && stream.notebook !== null) {
368
+ pendingNotifications.push(message.data.marimo);
369
+ } else {
370
+ onNotification(message.data.marimo);
371
+ }
339
372
  } else {
340
373
  Logger.error("Failed to decode notebook message", event);
341
374
  stopMalformed(source);
342
375
  }
343
376
  return;
344
377
  }
378
+ if (event.event === "reset" || event.event === "notebook.removed") {
379
+ pendingNotifications = [];
380
+ }
381
+ const before = store.get(streamAtom);
382
+ const previous =
383
+ event.event === "execution"
384
+ ? before.resources.executions.executions.get(event.data.execution.id)
385
+ : undefined;
345
386
  try {
346
- setStream(reducer.reduce(store.get(streamAtom), event));
387
+ setStream(reducer.reduce(before, event));
347
388
  if (event.event === "reset") {
348
389
  store.set(generationAtom, (generation) => generation + 1);
349
390
  }
@@ -353,11 +394,64 @@ export function createNotebookReplica(
353
394
  stopMalformed(source);
354
395
  return;
355
396
  }
356
- if (event.event === "execution" && onExecution) {
357
- try {
358
- onExecution(event.data.execution);
359
- } catch (error) {
360
- Logger.error("Failed to handle execution update", error);
397
+ const after = store.get(streamAtom);
398
+ if (event.event === "ready" && before.phase === "snapshot") {
399
+ for (const execution of after.resources.executions.executions.values()) {
400
+ observeExecution(execution.record, true);
401
+ if (onItem) {
402
+ for (const item of execution.items.values()) {
403
+ if (item.kind === "display") {
404
+ onItem(execution.record, item, false);
405
+ }
406
+ }
407
+ }
408
+ }
409
+ const notifications = pendingNotifications;
410
+ pendingNotifications = [];
411
+ for (const notification of notifications) {
412
+ if (signal.aborted) {
413
+ break;
414
+ }
415
+ try {
416
+ onNotification(notification);
417
+ } catch (error) {
418
+ queueMicrotask(() => {
419
+ throw error;
420
+ });
421
+ }
422
+ }
423
+ return;
424
+ }
425
+ if (after.phase !== "live") {
426
+ return;
427
+ }
428
+ const executions = after.resources.executions.executions;
429
+ switch (event.event) {
430
+ case "execution": {
431
+ const record = event.data.execution;
432
+ const changed = previous?.record.status !== record.status;
433
+ observeExecution(record, changed);
434
+ return;
435
+ }
436
+ case "console":
437
+ case "display":
438
+ case "input": {
439
+ const item =
440
+ event.event === "console"
441
+ ? event.data.console
442
+ : event.event === "display"
443
+ ? event.data.display
444
+ : event.data.input;
445
+ const execution = executions.get(item.execution_id);
446
+ if (execution && onItem) {
447
+ const received = execution.items.get(item.id);
448
+ if (received) {
449
+ const live = !before.resources.executions.executions
450
+ .get(item.execution_id)
451
+ ?.items.has(item.id);
452
+ onItem(execution.record, received, live);
453
+ }
454
+ }
361
455
  }
362
456
  }
363
457
  }