@marimo-team/islands 0.26.1-dev42 → 0.26.1-dev43

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 (105) hide show
  1. package/dist/{ConnectedDataExplorerComponent-BVMWCBON.js → ConnectedDataExplorerComponent-yQVBQBUW.js} +16 -16
  2. package/dist/{ErrorBoundary-BzyGrUMt.js → ErrorBoundary-jwCXNfZJ.js} +18 -18
  3. package/dist/{abnfDiagram-VCTEODGH-BRj77JhY.js → abnfDiagram-VCTEODGH-Ck_lXwQR.js} +2 -2
  4. package/dist/{any-language-editor-BQ9dhxg5.js → any-language-editor-Cx4idbgX.js} +2 -2
  5. package/dist/{architectureDiagram-5GKGNRK7-CDnAsvE1.js → architectureDiagram-5GKGNRK7-XeVhic7Z.js} +1 -1
  6. package/dist/{assertNever-DeSqnr83.js → assertNever-473SFxLt.js} +2 -2
  7. package/dist/{chat-ui-CXyZb62N.js → chat-ui-D2dBBkxD.js} +870 -870
  8. package/dist/{check-COXd6cXw.js → check-DmTIavbZ.js} +1 -1
  9. package/dist/{chunk-IMKFNOWR-BFtu1O6j.js → chunk-IMKFNOWR-DdQni67K.js} +1 -1
  10. package/dist/{chunk-SHT3W25Y-B9zWo9Da.js → chunk-SHT3W25Y-BdK-vMct.js} +1 -1
  11. package/dist/{chunk-SVP7TREG-kKS-I24p.js → chunk-SVP7TREG-cpFZk4Ca.js} +1 -1
  12. package/dist/{chunk-TICWLB2K-EY3w5-eg.js → chunk-TICWLB2K-DDgQFRgT.js} +1 -1
  13. package/dist/{classDiagram-ZZMXUADV-BR66X7fj.js → classDiagram-ZZMXUADV-DeojX9X4.js} +2 -2
  14. package/dist/{classDiagram-v2-VYDZK3BY-DPcxw_9g.js → classDiagram-v2-VYDZK3BY-DPfTAiQ6.js} +2 -2
  15. package/dist/{code-visibility-DcxCjPS7.js → code-visibility-BWkMC88N.js} +27 -27
  16. package/dist/{common-CA3E-SaD.js → common-DfQQ4A9M.js} +4892 -4900
  17. package/dist/{config-DE3A8m65.js → config-D-lhQq-h.js} +3 -3
  18. package/dist/{copy-icon-gSCLWI50.js → copy-icon-DuxRkh7T.js} +2 -2
  19. package/dist/{createReducer-BFfuVhJG.js → createReducer-D3pBhIVD.js} +5 -5
  20. package/dist/{cynefinDiagram-5FMLGOSQ-B9kG0Adl.js → cynefinDiagram-5FMLGOSQ-DyY9TvuI.js} +1 -1
  21. package/dist/{dagre-GXQ25YYZ-ClnyHQzL.js → dagre-GXQ25YYZ-BPCOgtKg.js} +1 -1
  22. package/dist/{data-grid-overlay-editor-DjSnRyGz.js → data-grid-overlay-editor-BcO56m4p.js} +1 -1
  23. package/dist/{diagram-S7CK7UJ4-afCjSSlp.js → diagram-S7CK7UJ4-KaF-C6kd.js} +1 -1
  24. package/dist/{diagram-UQ7AKVKN-BCHefG5P.js → diagram-UQ7AKVKN-DkeqoSvK.js} +1 -1
  25. package/dist/{diagram-VX7I27RA-9jXA0khj.js → diagram-VX7I27RA-DExolTAf.js} +1 -1
  26. package/dist/{diagram-Z3DM3KII-C8tsbK7Q.js → diagram-Z3DM3KII-BioFuBF3.js} +1 -1
  27. package/dist/{dialog-Dn_UHaEl.js → dialog-CvyFEwby.js} +28 -28
  28. package/dist/{dropdown-menu-D0nePAlm.js → dropdown-menu-BiXHfje7.js} +651 -651
  29. package/dist/{ebnfDiagram-PWID7BFC-It0ZS33j.js → ebnfDiagram-PWID7BFC-BSb9k1ed.js} +2 -2
  30. package/dist/{erDiagram-RLTQ6QDP-Z0Qfo02H.js → erDiagram-RLTQ6QDP-PWA30a_r.js} +1 -1
  31. package/dist/{error-banner-DChjSagB.js → error-banner-B9HQMSaH.js} +70 -70
  32. package/dist/{error-entries-DYoi03MZ.js → error-entries-DJXufUac.js} +812 -697
  33. package/dist/{feedback-button-DeA5LGUm.js → feedback-button-DNzGMlV8.js} +52 -52
  34. package/dist/{flowDiagram-HODETNUW-8DeXLUFK.js → flowDiagram-HODETNUW-BPtD__Zz.js} +2 -2
  35. package/dist/{formats-6QF5hRsy.js → formats-BF95BoCT.js} +1 -1
  36. package/dist/{glide-data-editor-DD03A2zN.js → glide-data-editor-DdyqdPXc.js} +11 -11
  37. package/dist/{glide-utils-B7gy9Her.js → glide-utils-iHKKQPJ8.js} +2 -2
  38. package/dist/{globals-CXh7buzB.js → globals-DNb4-fss.js} +3 -3
  39. package/dist/{html-to-image-CUFNjxtw.js → html-to-image-R7PUQb3h.js} +404 -404
  40. package/dist/{infoDiagram-27XIBGKW-B5wmzeRz.js → infoDiagram-27XIBGKW-SJuilBEE.js} +1 -1
  41. package/dist/{ishikawaDiagram-5VMMS53U-BcbPwik7.js → ishikawaDiagram-5VMMS53U-DjzyxMr8.js} +1 -1
  42. package/dist/{kanban-definition-UXKFOSKX-AfQmkIoH.js → kanban-definition-UXKFOSKX-D2_qopGt.js} +1 -1
  43. package/dist/main.js +5848 -5793
  44. package/dist/{mermaid-az53hfgW.js → mermaid-DcowNmCx.js} +34 -34
  45. package/dist/{mindmap-definition-YA3MSWOX-B7eBrMap.js → mindmap-definition-YA3MSWOX-pEra10M0.js} +1 -1
  46. package/dist/{number-overlay-editor-DJFSx1CC.js → number-overlay-editor-Co2zZ0AQ.js} +1 -1
  47. package/dist/{pegDiagram-XKGWAZYB-BwjpXSLR.js → pegDiagram-XKGWAZYB-CHOPKVOf.js} +2 -2
  48. package/dist/{pencil-pQhLU2Up.js → pencil-FAv6JUvp.js} +1 -1
  49. package/dist/{pieDiagram-E7YTZNPT-D5AyRqAQ.js → pieDiagram-E7YTZNPT-yGDhsyEN.js} +1 -1
  50. package/dist/{process-output-DMMs8Ywh.js → process-output-KUevsERL.js} +4 -4
  51. package/dist/{railroadDiagram-O6MQD6OU-Hhrla0Qq.js → railroadDiagram-O6MQD6OU-CeKEPdyc.js} +2 -2
  52. package/dist/{requirementDiagram-BXWQKSXE-MgDRuFUM.js → requirementDiagram-BXWQKSXE-DSAbAzKe.js} +1 -1
  53. package/dist/{reveal-component-DwB1-KYy.js → reveal-component-B5WBKEMn.js} +7 -7
  54. package/dist/{select-C4rPKgSx.js → select-BszV-bbI.js} +307 -307
  55. package/dist/{sequenceDiagram-WJ2MYXX4-xZYdOGbe.js → sequenceDiagram-WJ2MYXX4-DVhWj_9H.js} +1 -1
  56. package/dist/{spec-BsiCag5K.js → spec-CRfw-lOm.js} +4 -4
  57. package/dist/{stateDiagram-D77RDMKH-DdhE3Yx9.js → stateDiagram-D77RDMKH-CDQ2MltG.js} +2 -2
  58. package/dist/{stateDiagram-v2-MP3YSRHH-DENKYVKr.js → stateDiagram-v2-MP3YSRHH-BQmvwBaz.js} +2 -2
  59. package/dist/{static-state-CNnjDcOR.js → static-state-BtDNJuc2.js} +5 -5
  60. package/dist/{swimlanes-42K2YHIH-Bw7xuGAn.js → swimlanes-42K2YHIH-DLOUTCEL.js} +1 -1
  61. package/dist/{swimlanesDiagram-VR7AAH4N-L91TUeh5.js → swimlanesDiagram-VR7AAH4N-BVKrkNJ6.js} +2 -2
  62. package/dist/{timeline-definition-24CTP7MA-BeGrmws1.js → timeline-definition-24CTP7MA-Cb2JoCSd.js} +1 -1
  63. package/dist/{toast-qyBwbZJ0.js → toast-QsOAIPfq.js} +192 -192
  64. package/dist/{tooltip-COQxCMLx.js → tooltip-BQZ-Bm6h.js} +76 -76
  65. package/dist/{use-restore-focus-D5-Hgr1l.js → use-restore-focus-DT1TZACX.js} +1167 -1167
  66. package/dist/{useDateFormatter-L8edl513.js → useDateFormatter-D3gyMY-g.js} +2 -2
  67. package/dist/{useDeepCompareMemoize-B6yhm6sM.js → useDeepCompareMemoize-CO6rO5Mq.js} +1 -1
  68. package/dist/{useLifecycle-Dnxradbp.js → useLifecycle-C9UTzCY8.js} +1 -1
  69. package/dist/{vega-component-CWKS3tOU.js → vega-component-i5lZ23n7.js} +17 -17
  70. package/dist/{vennDiagram-4TSXK5OY-fknCUyJ2.js → vennDiagram-4TSXK5OY-Cm3EcCcP.js} +1 -1
  71. package/dist/{wardleyDiagram-VM6X3IG4-DvoVMCdj.js → wardleyDiagram-VM6X3IG4-DjlUs2CC.js} +1 -1
  72. package/dist/{xychartDiagram-S5SC5T6Z-0TYtO6UV.js → xychartDiagram-S5SC5T6Z-DxNDul9l.js} +1 -1
  73. package/package.json +1 -1
  74. package/src/__mocks__/animation-frames.ts +31 -0
  75. package/src/__mocks__/executions.ts +6 -1
  76. package/src/components/editor/cell/collapse.tsx +6 -3
  77. package/src/components/editor/header/status.tsx +5 -2
  78. package/src/components/scratchpad/scratchpad.tsx +2 -2
  79. package/src/core/cells/cells.ts +24 -16
  80. package/src/core/cells/execution-console.ts +7 -2
  81. package/src/core/executions/__tests__/atoms.test.ts +204 -1
  82. package/src/core/executions/__tests__/output-lifecycle.test.ts +20 -3
  83. package/src/core/executions/__tests__/select.test.ts +32 -1
  84. package/src/core/executions/atoms.ts +245 -81
  85. package/src/core/executions/hooks.ts +15 -59
  86. package/src/core/executions/index.ts +2 -0
  87. package/src/core/executions/output.ts +34 -14
  88. package/src/core/executions/select.ts +70 -25
  89. package/src/core/islands/bootstrap.ts +7 -2
  90. package/src/core/notebook/replica/__tests__/frame.test.ts +206 -0
  91. package/src/core/notebook/replica/__tests__/once-per-frame.test.ts +95 -0
  92. package/src/core/notebook/replica/frame.ts +54 -0
  93. package/src/core/notebook/replica/index.ts +1 -0
  94. package/src/core/notebook/replica/once-per-frame.ts +60 -0
  95. package/src/core/session/__tests__/useNotebookReplica.hook.test.tsx +53 -7
  96. package/src/core/session/__tests__/useNotebookSession.hook.test.tsx +29 -7
  97. package/src/core/session/active-notebook.ts +4 -1
  98. package/src/core/session/useNotebookReplica.ts +14 -1
  99. package/src/core/state/__tests__/atom-with-selected-inputs.test.ts +48 -0
  100. package/src/core/state/__tests__/create-keyed-selector-hook.test.tsx +16 -7
  101. package/src/core/state/atom-with-selected-inputs.ts +24 -0
  102. package/src/core/state/create-keyed-atom-hook.ts +18 -0
  103. package/src/core/state/create-keyed-selector-hook.ts +5 -9
  104. package/src/core/wasm/__tests__/bridge.test.ts +73 -1
  105. package/src/utils/arrays.ts +4 -1
@@ -183,7 +183,16 @@ export function executionSource(
183
183
  record: Protocol.ExecutionOutput,
184
184
  cells: ReadonlyMap<Protocol.CellId, Protocol.Cell> = NO_CELLS,
185
185
  ): string | undefined {
186
- const cell = record.cell_id === null ? undefined : cells.get(record.cell_id);
186
+ return sourceForCell(
187
+ record,
188
+ record.cell_id === null ? undefined : cells.get(record.cell_id),
189
+ );
190
+ }
191
+
192
+ function sourceForCell(
193
+ record: Protocol.ExecutionOutput,
194
+ cell: Protocol.Cell | undefined,
195
+ ): string | undefined {
187
196
  return cell !== undefined &&
188
197
  cell.code !== null &&
189
198
  cell.code_fingerprint === record.code_fingerprint
@@ -192,15 +201,18 @@ export function executionSource(
192
201
  }
193
202
 
194
203
  /**
195
- * What a result shows, or null for an empty output, with the source it ran
196
- * when `cells` still holds it.
204
+ * What a result shows, with its matching source, unless it is empty or cleared.
197
205
  */
198
206
  export function resultOutput(
199
- result: Result,
200
- cells: ReadonlyMap<Protocol.CellId, Protocol.Cell> = NO_CELLS,
207
+ result: Result | null,
208
+ cell?: Protocol.Cell,
209
+ cleared?: ClearedOutput,
201
210
  ): CellOutput | null {
211
+ if (result === null || stillCleared(cleared, result)) {
212
+ return null;
213
+ }
202
214
  const output = resultDisplay(result);
203
- const code = executionSource(result.record, cells);
215
+ const code = sourceForCell(result.record, cell);
204
216
  return output === null || code === undefined ? output : { ...output, code };
205
217
  }
206
218
 
@@ -240,6 +252,13 @@ export function shownExecution(
240
252
  latestId === undefined
241
253
  ? undefined
242
254
  : inputs.executions.executions.get(latestId);
255
+ return shownCellExecution(latest, inputs.results.get(id) ?? null);
256
+ }
257
+
258
+ export function shownCellExecution(
259
+ latest: Result | undefined,
260
+ result: Result | null,
261
+ ): Result | null {
243
262
  if (
244
263
  latest !== undefined &&
245
264
  shown(latest) !== null &&
@@ -247,7 +266,6 @@ export function shownExecution(
247
266
  ) {
248
267
  return latest;
249
268
  }
250
- const result = inputs.results.get(id) ?? null;
251
269
  if (
252
270
  latest?.record.state.status === "running" &&
253
271
  result !== null &&
@@ -279,11 +297,11 @@ export function cellOutputView(
279
297
  inputs: CellOutputInputs,
280
298
  id: Protocol.CellId,
281
299
  ): CellOutput | null {
282
- const showing = shownExecution(inputs, id);
283
- if (showing === null || stillCleared(inputs.cleared.get(id), showing)) {
284
- return null;
285
- }
286
- return resultOutput(showing, inputs.cells);
300
+ return resultOutput(
301
+ shownExecution(inputs, id),
302
+ inputs.cells.get(id),
303
+ inputs.cleared.get(id),
304
+ );
287
305
  }
288
306
 
289
307
  /**
@@ -312,7 +330,9 @@ export function cellOutputsView(
312
330
  /**
313
331
  * The latest scratch display, retained until a newer execution shows one.
314
332
  */
315
- export function scratchOutputView(executions: Executions): CellOutput | null {
333
+ export function scratchOutputView(
334
+ executions: Pick<Executions, "scratch" | "scratchFailure">,
335
+ ): CellOutput | null {
316
336
  const failure = executions.scratchFailure;
317
337
  // A run that failed before the kernel saw its code has no execution to
318
338
  // show, so its own reason stands in for the result.
@@ -327,5 +347,5 @@ export function scratchOutputView(executions: Executions): CellOutput | null {
327
347
  timestamp: seconds(failure.completedAt),
328
348
  };
329
349
  }
330
- return executions.scratch === null ? null : resultOutput(executions.scratch);
350
+ return resultOutput(executions.scratch);
331
351
  }
@@ -63,8 +63,29 @@ export function outcomeOf(record: Protocol.Execution): CellOutcome | null {
63
63
  return record.state.status === "completed" ? record.state.outcome.kind : null;
64
64
  }
65
65
 
66
- function millis(iso: string | null): Milliseconds | null {
67
- return iso === null ? null : Time.parse(iso).toMilliseconds();
66
+ // Records are immutable and shared across console and output updates.
67
+ const timings = new WeakMap<
68
+ Protocol.Execution,
69
+ { startedAt: Time | null; duration: Milliseconds | null }
70
+ >();
71
+
72
+ function timing(record: Protocol.Execution) {
73
+ const cached = timings.get(record);
74
+ if (cached) {
75
+ return cached;
76
+ }
77
+ const began = startedAtOf(record);
78
+ const ended = completedAt(record);
79
+ const startedAt = began === null ? null : Time.parse(began);
80
+ const value = {
81
+ startedAt,
82
+ duration:
83
+ startedAt === null || ended === null
84
+ ? null
85
+ : Time.parse(ended).since(startedAt),
86
+ };
87
+ timings.set(record, value);
88
+ return value;
68
89
  }
69
90
 
70
91
  function latestOf(
@@ -155,10 +176,20 @@ function awaited(inputs: CellExecutionInputs, id: Protocol.CellId): boolean {
155
176
  if (inputs.requested.has(id)) {
156
177
  return true;
157
178
  }
158
- const planned =
179
+ return awaitingRun(
180
+ inputs.executions.runs,
181
+ id,
159
182
  latestOf(inputs.executions, id)?.record.run_id ??
160
- inputs.results.get(id)?.record.run_id;
161
- for (const run of inputs.executions.runs.values()) {
183
+ inputs.results.get(id)?.record.run_id,
184
+ );
185
+ }
186
+
187
+ export function awaitingRun(
188
+ runs: Executions["runs"],
189
+ id: Protocol.CellId,
190
+ planned: Protocol.RunId | null | undefined,
191
+ ): boolean {
192
+ for (const run of runs.values()) {
162
193
  if (
163
194
  run.state.status !== "completed" &&
164
195
  run.id !== planned &&
@@ -177,35 +208,49 @@ export function cellExecutionView(
177
208
  ): CellExecutionView {
178
209
  const latest = latestOf(inputs.executions, id);
179
210
  const result = inputs.results.get(id)?.record ?? null;
211
+ return executionView({
212
+ latest: latest?.record ?? null,
213
+ result,
214
+ queued: awaited(inputs, id),
215
+ blocked: inputs.blocked.has(id),
216
+ shownBlocked: inputs.shownBlocked.has(id),
217
+ runtimeId: inputs.runtimeId,
218
+ });
219
+ }
220
+
221
+ export function executionView({
222
+ latest,
223
+ result,
224
+ queued,
225
+ blocked,
226
+ shownBlocked,
227
+ runtimeId,
228
+ }: {
229
+ latest: Protocol.ExecutionOutput | null;
230
+ result: Protocol.ExecutionOutput | null;
231
+ queued: boolean;
232
+ blocked: boolean;
233
+ shownBlocked: boolean;
234
+ runtimeId: Protocol.RuntimeId | null;
235
+ }): CellExecutionView {
180
236
  let status: CellRunStatus = "idle";
181
- const began = result === null ? null : startedAtOf(result);
182
- const ended = result === null ? null : completedAt(result);
183
- let startedAt = millis(began);
184
- if (latest !== null && latest.record.state.status !== "completed") {
185
- status = latest.record.state.status;
186
- startedAt = millis(startedAtOf(latest.record)) ?? startedAt;
187
- } else if (awaited(inputs, id)) {
237
+ const resultTiming = result === null ? null : timing(result);
238
+ let startedAt = resultTiming?.startedAt?.toMilliseconds() ?? null;
239
+ if (latest !== null && latest.state.status !== "completed") {
240
+ status = latest.state.status;
241
+ startedAt = timing(latest).startedAt?.toMilliseconds() ?? startedAt;
242
+ } else if (queued) {
188
243
  status = "queued";
189
244
  }
190
245
  const settled = status === "idle";
191
- const duration =
192
- settled && began !== null && ended !== null
193
- ? Time.parse(ended).since(Time.parse(began))
194
- : null;
195
- const blocked = inputs.blocked.has(id);
246
+ const duration = settled ? (resultTiming?.duration ?? null) : null;
196
247
  return {
197
248
  status,
198
249
  blocked,
199
- shownBlock: blocked
200
- ? "current"
201
- : inputs.shownBlocked.has(id)
202
- ? "stale"
203
- : null,
250
+ shownBlock: blocked ? "current" : shownBlocked ? "stale" : null,
204
251
  outcome: settled && result !== null ? outcomeOf(result) : null,
205
252
  live:
206
- result === null ||
207
- inputs.runtimeId === null ||
208
- result.runtime_id === inputs.runtimeId,
253
+ result === null || runtimeId === null || result.runtime_id === runtimeId,
209
254
  startedAt,
210
255
  duration,
211
256
  };
@@ -24,7 +24,7 @@ import { defineCustomElement } from "../dom/defineCustomElement";
24
24
  import { MarimoValueInputEvent } from "../dom/events";
25
25
  import { UI_ELEMENT_REGISTRY } from "../dom/uiregistry";
26
26
  import { FUNCTIONS_REGISTRY } from "../functions/FunctionRegistry";
27
- import { createNotebookReplica } from "../notebook/replica";
27
+ import { createNotebookReplica, createReplicaFrame } from "../notebook/replica";
28
28
  import { consoleObservers } from "../cells/execution-console";
29
29
  import { handleKernelReady, handleRemoveUIElements } from "../kernel/handlers";
30
30
  import type { NotificationMessage } from "../kernel/messages";
@@ -35,6 +35,7 @@ import { requestClientAtom } from "../network/requests";
35
35
  import {
36
36
  activeDocumentModelAtom,
37
37
  activeNotebookReplicaAtom,
38
+ activeNotebookFrameAtom,
38
39
  } from "../session/active-notebook";
39
40
  import { VirtualFileTracker } from "../static/virtual-file-tracker";
40
41
  import { store as defaultStore } from "../state/jotai";
@@ -132,6 +133,11 @@ export async function initializeIslands(
132
133
 
133
134
  // The notebook's cells follow the managed session's host document.
134
135
  const replica = createNotebookReplica(store);
136
+ const lifetime = new AbortController();
137
+ store.set(
138
+ activeNotebookFrameAtom,
139
+ createReplicaFrame(store, replica, { signal: lifetime.signal }),
140
+ );
135
141
  replica.connect(bridge.notebookBackend, {
136
142
  onNotification: Functions.NOOP,
137
143
  ...consoleObservers(actions),
@@ -143,7 +149,6 @@ export async function initializeIslands(
143
149
  shownDocumentAtom: replica.shownDocumentAtom,
144
150
  backendAtom: replica.backendAtom,
145
151
  });
146
- const lifetime = new AbortController();
147
152
  documentModel.start({ signal: lifetime.signal });
148
153
  store.set(activeDocumentModelAtom, documentModel);
149
154
  followDocument({
@@ -0,0 +1,206 @@
1
+ /* Copyright 2026 Marimo. All rights reserved. */
2
+ // @vitest-environment jsdom
3
+
4
+ import type { NotebookTransport } from "@marimo-team/client";
5
+ import { atom, createStore, type Getter } from "jotai/vanilla";
6
+ import { expect, it, onTestFinished, vi } from "vitest";
7
+ import { mockAnimationFrames } from "@/__mocks__/animation-frames";
8
+ import { MockExecutions } from "@/__mocks__/executions";
9
+ import { cellId } from "@/__tests__/branded";
10
+ import {
11
+ cellExecutionAtom,
12
+ cellOutputAtom,
13
+ cellFreshnessForAtom,
14
+ releaseCellOutputAtoms,
15
+ } from "@/core/executions/atoms";
16
+ import {
17
+ activeNotebookFrameAtom,
18
+ activeNotebookReplicaAtom,
19
+ } from "@/core/session/active-notebook";
20
+ import { createReplicaFrame } from "../frame";
21
+ import { createNotebookReplica } from "../replica";
22
+ import { fakeBackend, fixtureMessages } from "./fixtures";
23
+
24
+ async function setup() {
25
+ const advanceFrame = mockAnimationFrames();
26
+ const store = createStore();
27
+ const replica = createNotebookReplica(store);
28
+ const lifetime = new AbortController();
29
+ onTestFinished(() => lifetime.abort());
30
+ const frame = createReplicaFrame(store, replica, { signal: lifetime.signal });
31
+ store.set(activeNotebookReplicaAtom, replica);
32
+ store.set(activeNotebookFrameAtom, frame);
33
+ let receive!: Parameters<NotebookTransport>[1]["message"];
34
+ const onNotification = vi.fn();
35
+ const onExecution = vi.fn();
36
+ onTestFinished(
37
+ replica.connect(
38
+ fakeBackend({
39
+ transport: ({ signal }, handlers) =>
40
+ new Promise<void>((resolve) => {
41
+ receive = handlers.message;
42
+ handlers.open();
43
+ signal.addEventListener("abort", () => resolve(), { once: true });
44
+ }),
45
+ }),
46
+ { onNotification, onExecution },
47
+ ),
48
+ );
49
+ await vi.waitFor(() => expect(receive).toBeDefined());
50
+ fixtureMessages("notebook-events.sse").forEach(receive);
51
+ advanceFrame();
52
+ return {
53
+ store,
54
+ replica,
55
+ frame,
56
+ lifetime,
57
+ receive,
58
+ advanceFrame,
59
+ onNotification,
60
+ onExecution,
61
+ };
62
+ }
63
+
64
+ it("updates commands and observers immediately, publishing a coherent display once per frame", async () => {
65
+ const {
66
+ store,
67
+ replica,
68
+ frame,
69
+ receive,
70
+ advanceFrame,
71
+ onNotification,
72
+ onExecution,
73
+ } = await setup();
74
+ const view = atom((get) => [
75
+ get(frame.executionsAtom),
76
+ get(frame.resultsAtom),
77
+ get(frame.shownDocumentAtom),
78
+ ]);
79
+ const changed = vi.fn();
80
+ onTestFinished(store.sub(view, changed));
81
+ const before = store.get(view);
82
+ onNotification.mockClear();
83
+ onExecution.mockClear();
84
+ fixtureMessages("run-cells.sse").forEach(receive);
85
+ receive({ event: "marimo", data: { marimo: { op: "reload" } } });
86
+ expect(onExecution).toHaveBeenCalled();
87
+ expect(onNotification).toHaveBeenCalledWith({ op: "reload" });
88
+ expect(store.get(replica.executionsAtom)).not.toBe(before[0]);
89
+ expect(store.get(view)).toBe(before);
90
+ expect(changed).not.toHaveBeenCalled();
91
+ advanceFrame();
92
+ expect(changed).toHaveBeenCalledOnce();
93
+ expect(store.get(view)).toEqual([
94
+ store.get(replica.executionsAtom),
95
+ store.get(replica.resultsAtom),
96
+ store.get(replica.shownDocumentAtom),
97
+ ]);
98
+ advanceFrame();
99
+ expect(changed).toHaveBeenCalledOnce();
100
+ });
101
+
102
+ it.each([false, true])(
103
+ "retains an intermediate matching analysis (previous analysis: %s)",
104
+ async (hasPrevious) => {
105
+ const { store, replica, frame, receive, advanceFrame } = await setup();
106
+ const document = store.get(replica.documentAtom)!;
107
+ const base = {
108
+ notebook_id: document.revision.notebook_id,
109
+ document_etag: document.revision.etag,
110
+ cells: {},
111
+ };
112
+ if (hasPrevious) {
113
+ receive({ event: "analysis", data: { analysis: base } });
114
+ advanceFrame();
115
+ }
116
+ const changed = vi.fn();
117
+ onTestFinished(store.sub(frame.analysisAtom, changed));
118
+ const analysis = {
119
+ ...base,
120
+ cells: { c1: { defs: ["x"], refs: [], parents: [], diagnostics: [] } },
121
+ };
122
+ receive({ event: "analysis", data: { analysis } });
123
+ receive({
124
+ event: "document",
125
+ data: {
126
+ document: {
127
+ ...document.revision,
128
+ etag: "next",
129
+ version: document.revision.version + 1,
130
+ },
131
+ },
132
+ });
133
+ const expected = { freshness: "stale", analysis, document };
134
+ expect(store.get(replica.analysisAtom)).toEqual(expected);
135
+ expect(changed).not.toHaveBeenCalled();
136
+ advanceFrame();
137
+ expect(store.get(frame.analysisAtom)).toEqual(expected);
138
+ expect(changed).toHaveBeenCalledOnce();
139
+ },
140
+ );
141
+
142
+ it("unsubscribes and cancels publication on abort, while the replica keeps receiving", async () => {
143
+ const { store, replica, frame, lifetime, receive, advanceFrame } =
144
+ await setup();
145
+ const before = store.get(frame.executionsAtom);
146
+ const changed = vi.fn();
147
+ onTestFinished(store.sub(frame.executionsAtom, changed));
148
+ fixtureMessages("run-cells.sse").forEach(receive);
149
+ lifetime.abort();
150
+ advanceFrame();
151
+ expect(store.get(frame.executionsAtom)).toBe(before);
152
+ expect(store.get(replica.executionsAtom)).not.toBe(before);
153
+ expect(changed).not.toHaveBeenCalled();
154
+ const subscribe = vi.spyOn(store, "sub");
155
+ const stopped = createReplicaFrame(store, replica, {
156
+ signal: lifetime.signal,
157
+ });
158
+ expect(subscribe).not.toHaveBeenCalled();
159
+ expect(store.get(stopped.executionsAtom)).toBe(
160
+ store.get(replica.executionsAtom),
161
+ );
162
+ });
163
+
164
+ it.each([5, 500])(
165
+ "shares one subscription across %s cell views and does no display work between frames",
166
+ (count) => {
167
+ const advanceFrame = mockAnimationFrames();
168
+ const store = createStore();
169
+ const replica = MockExecutions.seed(store, []);
170
+ const lifetime = new AbortController();
171
+ onTestFinished(() => lifetime.abort());
172
+ const subscribe = vi.spyOn(store, "sub");
173
+ const frame = createReplicaFrame(store, replica, {
174
+ signal: lifetime.signal,
175
+ });
176
+ expect(subscribe).toHaveBeenCalledOnce();
177
+ store.set(activeNotebookFrameAtom, frame);
178
+ const changed = vi.fn();
179
+ for (let i = 0; i < count; i++) {
180
+ const id = cellId(`c${i}`);
181
+ for (const view of [
182
+ cellExecutionAtom(id),
183
+ cellOutputAtom(id),
184
+ cellFreshnessForAtom(id),
185
+ ]) {
186
+ onTestFinished(store.sub(view, changed));
187
+ }
188
+ onTestFinished(() => releaseCellOutputAtoms(id));
189
+ }
190
+ const read = vi.fn((get: Getter) => get(frame.executionsAtom));
191
+ const display = atom(read);
192
+ onTestFinished(store.sub(display, () => undefined));
193
+ read.mockClear();
194
+ for (let i = 0; i < 1000; i++) {
195
+ store.set(
196
+ replica.executionsAtom,
197
+ MockExecutions.inputs([MockExecutions.running("c0")]).executions,
198
+ );
199
+ }
200
+ expect(read).not.toHaveBeenCalled();
201
+ expect(changed).not.toHaveBeenCalled();
202
+ advanceFrame();
203
+ expect(read).toHaveBeenCalledOnce();
204
+ expect(changed).toHaveBeenCalledOnce();
205
+ },
206
+ );
@@ -0,0 +1,95 @@
1
+ /* Copyright 2026 Marimo. All rights reserved. */
2
+ // @vitest-environment jsdom
3
+
4
+ import { afterEach, beforeEach, expect, it, vi } from "vitest";
5
+ import { oncePerFrame } from "../once-per-frame";
6
+
7
+ let controller: AbortController;
8
+ beforeEach(() => {
9
+ controller = new AbortController();
10
+ vi.useFakeTimers();
11
+ vi.spyOn(document, "hidden", "get").mockReturnValue(false);
12
+ });
13
+ afterEach(() => {
14
+ controller.abort();
15
+ vi.restoreAllMocks();
16
+ vi.unstubAllGlobals();
17
+ vi.useRealTimers();
18
+ });
19
+
20
+ it.each([false, true])("coalesces invalidations (hidden: %s)", (hidden) => {
21
+ vi.spyOn(document, "hidden", "get").mockReturnValue(hidden);
22
+ const publish = vi.fn();
23
+ const schedule = oncePerFrame(publish, { signal: controller.signal });
24
+ for (let i = 0; i < 1000; i++) {
25
+ schedule();
26
+ }
27
+ expect(publish).not.toHaveBeenCalled();
28
+ vi.advanceTimersByTime(32);
29
+ expect(publish).toHaveBeenCalledOnce();
30
+ });
31
+
32
+ it("publishes pending work when the page becomes hidden and ignores the cancelled frame", () => {
33
+ const frames: FrameRequestCallback[] = [];
34
+ vi.spyOn(globalThis, "requestAnimationFrame").mockImplementation((callback) =>
35
+ frames.push(callback),
36
+ );
37
+ const publish = vi.fn();
38
+ const schedule = oncePerFrame(publish, { signal: controller.signal });
39
+ schedule();
40
+ vi.spyOn(document, "hidden", "get").mockReturnValue(true);
41
+ document.dispatchEvent(new Event("visibilitychange"));
42
+ expect(publish).toHaveBeenCalledOnce();
43
+ schedule();
44
+ frames[0](0);
45
+ expect(publish).toHaveBeenCalledOnce();
46
+ vi.advanceTimersByTime(16);
47
+ expect(publish).toHaveBeenCalledTimes(2);
48
+ });
49
+
50
+ it("puts reentrant work in the next frame", () => {
51
+ const publish = vi.fn().mockImplementationOnce(() => schedule());
52
+ const schedule = oncePerFrame(publish, { signal: controller.signal });
53
+ schedule();
54
+ vi.advanceTimersToNextFrame();
55
+ expect(publish).toHaveBeenCalledOnce();
56
+ vi.advanceTimersToNextFrame();
57
+ expect(publish).toHaveBeenCalledTimes(2);
58
+ });
59
+
60
+ it.each([false, true])(
61
+ "never publishes after abort (already aborted: %s)",
62
+ (alreadyAborted) => {
63
+ if (alreadyAborted) {
64
+ controller.abort();
65
+ }
66
+ const publish = vi.fn();
67
+ const schedule = oncePerFrame(publish, { signal: controller.signal });
68
+ schedule();
69
+ controller.abort();
70
+ schedule();
71
+ document.dispatchEvent(new Event("visibilitychange"));
72
+ vi.runAllTimers();
73
+ expect(publish).not.toHaveBeenCalled();
74
+ },
75
+ );
76
+
77
+ it("can schedule again after publication throws", () => {
78
+ const publish = vi.fn().mockImplementationOnce(() => {
79
+ throw new Error("failed");
80
+ });
81
+ const schedule = oncePerFrame(publish, { signal: controller.signal });
82
+ schedule();
83
+ expect(() => vi.advanceTimersToNextFrame()).toThrow("failed");
84
+ schedule();
85
+ vi.advanceTimersToNextFrame();
86
+ expect(publish).toHaveBeenCalledTimes(2);
87
+ });
88
+
89
+ it("uses a timer without animation frames", () => {
90
+ vi.stubGlobal("requestAnimationFrame", undefined);
91
+ const publish = vi.fn();
92
+ oncePerFrame(publish, { signal: controller.signal })();
93
+ vi.advanceTimersByTime(16);
94
+ expect(publish).toHaveBeenCalledOnce();
95
+ });
@@ -0,0 +1,54 @@
1
+ /* Copyright 2026 Marimo. All rights reserved. */
2
+
3
+ import { atom, type createStore } from "jotai/vanilla";
4
+ import type { NotebookReplica } from "./replica";
5
+ import { oncePerFrame } from "./once-per-frame";
6
+
7
+ export type ReplicaFrame = Pick<
8
+ NotebookReplica,
9
+ | "notebookAtom"
10
+ | "generationAtom"
11
+ | "documentAtom"
12
+ | "shownDocumentAtom"
13
+ | "analysisAtom"
14
+ | "executionsAtom"
15
+ | "resultsAtom"
16
+ | "runtimeAtom"
17
+ >;
18
+
19
+ /** The replica's display atoms, republished together once per frame. */
20
+ export function createReplicaFrame(
21
+ store: ReturnType<typeof createStore>,
22
+ replica: ReplicaFrame,
23
+ { signal }: { signal: AbortSignal },
24
+ ): ReplicaFrame {
25
+ const currentAtom = atom((get) => ({
26
+ notebook: get(replica.notebookAtom),
27
+ generation: get(replica.generationAtom),
28
+ document: get(replica.documentAtom),
29
+ shownDocument: get(replica.shownDocumentAtom),
30
+ analysis: get(replica.analysisAtom),
31
+ executions: get(replica.executionsAtom),
32
+ results: get(replica.resultsAtom),
33
+ runtime: get(replica.runtimeAtom),
34
+ }));
35
+ const frameAtom = atom(store.get(currentAtom));
36
+ const publish = oncePerFrame(
37
+ () => store.set(frameAtom, store.get(currentAtom)),
38
+ { signal },
39
+ );
40
+ if (!signal.aborted) {
41
+ const unsubscribe = store.sub(currentAtom, publish);
42
+ signal.addEventListener("abort", unsubscribe, { once: true });
43
+ }
44
+ return {
45
+ notebookAtom: atom((get) => get(frameAtom).notebook),
46
+ generationAtom: atom((get) => get(frameAtom).generation),
47
+ documentAtom: atom((get) => get(frameAtom).document),
48
+ shownDocumentAtom: atom((get) => get(frameAtom).shownDocument),
49
+ analysisAtom: atom((get) => get(frameAtom).analysis),
50
+ executionsAtom: atom((get) => get(frameAtom).executions),
51
+ resultsAtom: atom((get) => get(frameAtom).results),
52
+ runtimeAtom: atom((get) => get(frameAtom).runtime),
53
+ };
54
+ }
@@ -3,6 +3,7 @@
3
3
  /** Backend-confirmed notebook state, independent of React and transports. */
4
4
 
5
5
  export type { NotebookBackend } from "./backend";
6
+ export { createReplicaFrame, type ReplicaFrame } from "./frame";
6
7
  export {
7
8
  type CloseDecision,
8
9
  ConnectionClosedReason,
@@ -0,0 +1,60 @@
1
+ /* Copyright 2026 Marimo. All rights reserved. */
2
+
3
+ /** Coalesce invalidations without retaining events or delaying their consumers. */
4
+ export function oncePerFrame(
5
+ publish: () => void,
6
+ { signal }: { signal: AbortSignal },
7
+ ): () => void {
8
+ let generation = 0;
9
+ let cancelScheduled: (() => void) | undefined;
10
+
11
+ function clear() {
12
+ generation++;
13
+ cancelScheduled?.();
14
+ cancelScheduled = undefined;
15
+ }
16
+
17
+ function run() {
18
+ const pending = cancelScheduled !== undefined;
19
+ // Reentrant invalidations belong to the next frame.
20
+ clear();
21
+ if (pending && !signal.aborted) {
22
+ publish();
23
+ }
24
+ }
25
+
26
+ if (!signal.aborted) {
27
+ signal.addEventListener("abort", clear, { once: true });
28
+ globalThis.document?.addEventListener(
29
+ "visibilitychange",
30
+ () => {
31
+ if (globalThis.document.hidden) {
32
+ run();
33
+ }
34
+ },
35
+ { signal },
36
+ );
37
+ }
38
+
39
+ return () => {
40
+ if (signal.aborted || cancelScheduled) {
41
+ return;
42
+ }
43
+ const scheduledGeneration = generation;
44
+ const callback = () => {
45
+ if (scheduledGeneration === generation) {
46
+ run();
47
+ }
48
+ };
49
+ if (
50
+ globalThis.document?.hidden ||
51
+ typeof requestAnimationFrame === "undefined"
52
+ ) {
53
+ const timer = setTimeout(callback, 16);
54
+ cancelScheduled = () => clearTimeout(timer);
55
+ } else {
56
+ const frame = requestAnimationFrame(callback);
57
+ cancelScheduled = () => cancelAnimationFrame(frame);
58
+ }
59
+ };
60
+ }