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

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 (108) hide show
  1. package/dist/{ConnectedDataExplorerComponent-BVMWCBON.js → ConnectedDataExplorerComponent-yQVBQBUW.js} +16 -16
  2. package/dist/{ErrorBoundary-BzyGrUMt.js → ErrorBoundary-i7VCVA53.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-6qTQeEIx.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-DNUnnMY_.js} +27 -27
  16. package/dist/{common-CA3E-SaD.js → common-CXvbAyqO.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-_B2yWrZg.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-8CPw0aYH.js} +812 -698
  33. package/dist/{feedback-button-DeA5LGUm.js → feedback-button-BOJ6pfBP.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-oQ3lCfvU.js} +11 -11
  37. package/dist/{glide-utils-B7gy9Her.js → glide-utils-iHKKQPJ8.js} +2 -2
  38. package/dist/{globals-CXh7buzB.js → globals-a3k2q2j7.js} +3 -3
  39. package/dist/{html-to-image-CUFNjxtw.js → html-to-image-BIom70fW.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 +5811 -5766
  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-CUwIpUt4.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-ns7N5ovS.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-BAhQeB3o.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__/executions.test.ts +8 -12
  91. package/src/core/notebook/replica/__tests__/frame.test.ts +206 -0
  92. package/src/core/notebook/replica/__tests__/once-per-frame.test.ts +95 -0
  93. package/src/core/notebook/replica/__tests__/results.test.ts +3 -9
  94. package/src/core/notebook/replica/frame.ts +54 -0
  95. package/src/core/notebook/replica/index.ts +1 -0
  96. package/src/core/notebook/replica/once-per-frame.ts +60 -0
  97. package/src/core/notebook/replica/resources/executions.ts +0 -2
  98. package/src/core/session/__tests__/useNotebookReplica.hook.test.tsx +53 -7
  99. package/src/core/session/__tests__/useNotebookSession.hook.test.tsx +29 -7
  100. package/src/core/session/active-notebook.ts +4 -1
  101. package/src/core/session/useNotebookReplica.ts +14 -1
  102. package/src/core/state/__tests__/atom-with-selected-inputs.test.ts +48 -0
  103. package/src/core/state/__tests__/create-keyed-selector-hook.test.tsx +16 -7
  104. package/src/core/state/atom-with-selected-inputs.ts +24 -0
  105. package/src/core/state/create-keyed-atom-hook.ts +18 -0
  106. package/src/core/state/create-keyed-selector-hook.ts +5 -9
  107. package/src/core/wasm/__tests__/bridge.test.ts +73 -1
  108. package/src/utils/arrays.ts +4 -1
@@ -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
+ }
@@ -344,8 +344,6 @@ export const executions: NotebookResource<Executions, Kind> = {
344
344
  execution.outputVersion + (sameShown(execution, next) ? 0 : 1),
345
345
  });
346
346
  },
347
- // The output leaves with its execution, and a retained result keeps its copy.
348
- "output.removed": (state) => state,
349
347
  console: (state, { data }) =>
350
348
  attach(state, { ...data.console, kind: "console", time: data.time }),
351
349
  "console.removed": (state, { data }) => detach(state, data.id),
@@ -4,7 +4,7 @@
4
4
  import { act, renderHook } from "@testing-library/react";
5
5
  import { createStore, Provider } from "jotai";
6
6
  import type { PropsWithChildren } from "react";
7
- import { beforeEach, describe, expect, it, vi } from "vitest";
7
+ import { beforeEach, describe, expect, it, vi, onTestFinished } from "vitest";
8
8
  import type { NotebookTransport } from "@marimo-team/client";
9
9
  import type { AttachmentOutput } from "@marimo-team/client/protocol";
10
10
  import { ConnectionState } from "../types";
@@ -14,8 +14,12 @@ import {
14
14
  fakeBackend,
15
15
  fixtureMessages,
16
16
  } from "../../notebook/replica/__tests__/fixtures";
17
+ import { mockAnimationFrames } from "@/__mocks__/animation-frames";
17
18
  import { useNotebookAttachments } from "@/core/notebook";
18
- import { activeNotebookReplicaAtom } from "../active-notebook";
19
+ import {
20
+ activeNotebookReplicaAtom,
21
+ activeNotebookFrameAtom,
22
+ } from "../active-notebook";
19
23
 
20
24
  vi.mock("../backend", () => ({ createEditorBackend: vi.fn() }));
21
25
 
@@ -95,9 +99,12 @@ describe("useNotebookReplica", () => {
95
99
  await act(async () => Promise.resolve());
96
100
  expect(store.get(activeNotebookReplicaAtom)).toBe(result.current);
97
101
  const [connection] = fake.opened;
102
+ const receive = (message: unknown) => {
103
+ connection.receive(message);
104
+ };
98
105
  act(() => {
99
106
  connection.open();
100
- fixtureMessages("notebook-events.sse").forEach(connection.receive);
107
+ fixtureMessages("notebook-events.sse").forEach(receive);
101
108
  });
102
109
  expect(attachments.result.current.agents).toEqual([
103
110
  {
@@ -120,7 +127,7 @@ describe("useNotebookReplica", () => {
120
127
  (attachment) => attachment.kind === "browser",
121
128
  )!;
122
129
  act(() =>
123
- connection.receive({
130
+ receive({
124
131
  event: "attachment",
125
132
  data: { attachment: { ...browser, name: "Firefox" } },
126
133
  }),
@@ -129,7 +136,7 @@ describe("useNotebookReplica", () => {
129
136
 
130
137
  const renamedAgent = { ...agents[0], name: "Renamed agent" };
131
138
  act(() =>
132
- connection.receive({
139
+ receive({
133
140
  event: "attachment",
134
141
  data: { attachment: renamedAgent },
135
142
  }),
@@ -151,7 +158,9 @@ describe("useNotebookReplica", () => {
151
158
  await act(async () => Promise.resolve());
152
159
  const onNotification = vi.fn();
153
160
  rerender({ ...options, onNotification, url: () => "ws://redirected/ws" });
154
- act(() => fake.notify());
161
+ act(() => {
162
+ fake.notify();
163
+ });
155
164
  expect(options.onNotification).not.toHaveBeenCalled();
156
165
  expect(onNotification).toHaveBeenCalledExactlyOnceWith({
157
166
  data: { op: "reload" },
@@ -176,7 +185,9 @@ describe("useNotebookReplica", () => {
176
185
  expect(store.get(result.current.connectionAtom)).toEqual({
177
186
  state: ConnectionState.OPEN,
178
187
  });
179
- act(() => fake.opened.forEach((attempt) => attempt.receive(notification)));
188
+ act(() => {
189
+ fake.opened.forEach((attempt) => attempt.receive(notification));
190
+ });
180
191
  expect(options.onNotification).toHaveBeenCalledOnce();
181
192
  unmount();
182
193
  expect(active.signal.aborted).toBe(true);
@@ -185,3 +196,38 @@ describe("useNotebookReplica", () => {
185
196
  expect(fake.opened).toHaveLength(attempts);
186
197
  });
187
198
  });
199
+
200
+ it("publishes views once per frame while delivering notifications immediately", async () => {
201
+ const advanceFrame = mockAnimationFrames();
202
+ const fake = makeTransport();
203
+ vi.mocked(createEditorBackend).mockReturnValue(
204
+ fakeBackend({ transport: fake.transport }),
205
+ );
206
+ const { result, options, store, unmount } = setup();
207
+ onTestFinished(unmount);
208
+ await act(async () => Promise.resolve());
209
+ const [connection] = fake.opened;
210
+ act(() => {
211
+ connection.open();
212
+ fixtureMessages("notebook-events.sse").forEach(connection.receive);
213
+ });
214
+ act(advanceFrame);
215
+ const changed = vi.fn();
216
+ const frame = store.get(activeNotebookFrameAtom)!;
217
+ onTestFinished(store.sub(frame.executionsAtom, changed));
218
+ options.onNotification.mockClear();
219
+ act(() => {
220
+ fixtureMessages("run-cells.sse").forEach(connection.receive);
221
+ connection.receive(notification);
222
+ });
223
+ expect(changed).not.toHaveBeenCalled();
224
+ expect(options.onNotification).toHaveBeenCalledOnce();
225
+ expect(store.get(result.current.executionsAtom)).not.toBe(
226
+ store.get(frame.executionsAtom),
227
+ );
228
+ act(advanceFrame);
229
+ expect(changed).toHaveBeenCalledTimes(1);
230
+ expect(options.onNotification).toHaveBeenCalledExactlyOnceWith({
231
+ data: { op: "reload" },
232
+ });
233
+ });
@@ -77,10 +77,17 @@ import {
77
77
  } from "../../notebook/replica/__tests__/fixtures";
78
78
  import { MockExecutions } from "@/__mocks__/executions";
79
79
  import { VirtualFileTracker } from "@/core/static/virtual-file-tracker";
80
+ import { mockAnimationFrames } from "@/__mocks__/animation-frames";
81
+
80
82
  import { useNotebookSession } from "../useNotebookSession";
81
83
  import type { CellAnalysis } from "@marimo-team/client/protocol";
82
84
  import { type NotebookTransport, StreamStopped } from "@marimo-team/client";
83
85
 
86
+ let advanceFrame: () => void;
87
+ beforeEach(() => {
88
+ advanceFrame = mockAnimationFrames();
89
+ });
90
+
84
91
  const C1 = cellId("c1");
85
92
 
86
93
  const SESSION_ID = generateSessionId();
@@ -131,12 +138,18 @@ function connection(fake: FakeTransport) {
131
138
  }
132
139
  return attempt;
133
140
  };
141
+ // Each delivery represents a complete frame. Tests can group events explicitly.
142
+ const frame = (...messages: unknown[]) => {
143
+ messages.forEach((message) => current().receive(message));
144
+ advanceFrame();
145
+ };
134
146
  return {
147
+ frame,
135
148
  open: () => current().open(),
136
- receive: (message: unknown) => current().receive(message),
149
+ receive: (message: unknown) => frame(message),
137
150
  /** Deliver a notification as the session routes frame it. */
138
151
  send: (notification: unknown) =>
139
- current().receive({ event: "marimo", data: { marimo: notification } }),
152
+ frame({ event: "marimo", data: { marimo: notification } }),
140
153
  /** Deliver a snapshot of the notebook, ending in the stream's `ready`. */
141
154
  ready: () => {
142
155
  for (const message of fixtureMessages("notebook-events.sse")) {
@@ -145,6 +158,7 @@ function connection(fake: FakeTransport) {
145
158
  break;
146
159
  }
147
160
  }
161
+ advanceFrame();
148
162
  },
149
163
  /** End the connection so the stream reconnects. */
150
164
  drop: () => current().drop(),
@@ -1013,7 +1027,7 @@ it.each(["callback-output", "pdb-output"] as const)(
1013
1027
  },
1014
1028
  );
1015
1029
 
1016
- it.each(["live", "replay"])(
1030
+ it.each(["live", "replay", "batched"])(
1017
1031
  "interleaves %s command output with untimed execution items",
1018
1032
  async (mode) => {
1019
1033
  const store = createStore();
@@ -1051,7 +1065,7 @@ it.each(["live", "replay"])(
1051
1065
  }
1052
1066
  conn.receive(event);
1053
1067
  }
1054
- conn.send({
1068
+ const callback = {
1055
1069
  op: "callback-output",
1056
1070
  cell_id: id,
1057
1071
  replace: mode === "replay",
@@ -1064,9 +1078,17 @@ it.each(["live", "replay"])(
1064
1078
  },
1065
1079
  ],
1066
1080
  after_seq: [0],
1067
- });
1068
- if (mode === "live") {
1069
- conn.receive(line(1, "C"));
1081
+ };
1082
+ if (mode === "batched") {
1083
+ conn.frame(
1084
+ { event: "marimo", data: { marimo: callback } },
1085
+ line(1, "C"),
1086
+ );
1087
+ } else {
1088
+ conn.send(callback);
1089
+ if (mode === "live") {
1090
+ conn.receive(line(1, "C"));
1091
+ }
1070
1092
  }
1071
1093
  });
1072
1094
  expect(rows()).toEqual(["ABC"]);
@@ -2,11 +2,14 @@
2
2
 
3
3
  import { atom } from "jotai";
4
4
  import type { DocumentModel } from "../notebook/document";
5
- import type { NotebookReplica } from "../notebook/replica";
5
+ import type { NotebookReplica, ReplicaFrame } from "../notebook/replica";
6
6
 
7
7
  /** The replica owned by the mounted notebook session. */
8
8
  export const activeNotebookReplicaAtom = atom<NotebookReplica | null>(null);
9
9
 
10
+ /** Display state published once per frame by the mounted session. */
11
+ export const activeNotebookFrameAtom = atom<ReplicaFrame | null>(null);
12
+
10
13
  /** The last analysis, kept while the host analyzes a newer revision. */
11
14
  export const notebookAnalysisAtom = atom((get) => {
12
15
  const replica = get(activeNotebookReplicaAtom);
@@ -14,9 +14,13 @@ import type {
14
14
  } from "../kernel/messages";
15
15
  import {
16
16
  createNotebookReplica,
17
+ createReplicaFrame,
17
18
  type NotebookReplica,
18
19
  } from "../notebook/replica";
19
- import { activeNotebookReplicaAtom } from "./active-notebook";
20
+ import {
21
+ activeNotebookReplicaAtom,
22
+ activeNotebookFrameAtom,
23
+ } from "./active-notebook";
20
24
  import { createEditorBackend, type EditorBackendOptions } from "./backend";
21
25
 
22
26
  type Options = EditorBackendOptions & {
@@ -62,6 +66,11 @@ export function useNotebookReplica(options: Options): NotebookReplica {
62
66
  );
63
67
 
64
68
  useEffect(() => {
69
+ const lifetime = new AbortController();
70
+ const frame = createReplicaFrame(store, replica, {
71
+ signal: lifetime.signal,
72
+ });
73
+ store.set(activeNotebookFrameAtom, frame);
65
74
  store.set(activeNotebookReplicaAtom, replica);
66
75
  const disconnect = replica.connect(backend, {
67
76
  ...consoleObservers({ addLogs, startCellConsole }, onExecution),
@@ -72,7 +81,11 @@ export function useNotebookReplica(options: Options): NotebookReplica {
72
81
  },
73
82
  });
74
83
  return () => {
84
+ lifetime.abort();
75
85
  disconnect();
86
+ if (store.get(activeNotebookFrameAtom) === frame) {
87
+ store.set(activeNotebookFrameAtom, null);
88
+ }
76
89
  if (store.get(activeNotebookReplicaAtom) === replica) {
77
90
  store.set(activeNotebookReplicaAtom, null);
78
91
  }
@@ -0,0 +1,48 @@
1
+ /* Copyright 2026 Marimo. All rights reserved. */
2
+
3
+ import { atom, createStore } from "jotai/vanilla";
4
+ import { expect, it, vi } from "vitest";
5
+ import { atomWithSelectedInputs } from "../atom-with-selected-inputs";
6
+
7
+ it("skips derivation and notification for unrelated updates, including after remount", () => {
8
+ const source = atom({ selected: { count: 1 }, unrelated: 0 });
9
+ const derive = vi.fn(
10
+ ([value]: readonly [{ count: number }]) => value.count * 2,
11
+ );
12
+ const view = atomWithSelectedInputs(
13
+ source,
14
+ (state) => [state.selected],
15
+ derive,
16
+ );
17
+ const store = createStore();
18
+ const notify = vi.fn();
19
+ let release = store.sub(view, notify);
20
+ expect(store.get(view)).toBe(2);
21
+ derive.mockClear();
22
+ store.set(source, (state) => ({ ...state, unrelated: 1 }));
23
+ expect(derive).not.toHaveBeenCalled();
24
+ expect(notify).not.toHaveBeenCalled();
25
+ store.set(source, (state) => ({ ...state, selected: { count: 2 } }));
26
+ expect(derive).toHaveBeenCalledTimes(1);
27
+ expect(notify).toHaveBeenCalledTimes(1);
28
+ release();
29
+ store.set(source, (state) => ({ ...state, selected: { count: 3 } }));
30
+ release = store.sub(view, notify);
31
+ expect(store.get(view)).toBe(6);
32
+ release();
33
+ });
34
+
35
+ it("keeps memoization local to each store", () => {
36
+ const source = atom({ count: 1 });
37
+ const view = atomWithSelectedInputs(
38
+ source,
39
+ (state) => [state.count],
40
+ ([count]) => ({ count }),
41
+ );
42
+ const first = createStore();
43
+ const second = createStore();
44
+ const original = second.get(view);
45
+ first.set(source, { count: 2 });
46
+ expect(first.get(view)).toEqual({ count: 2 });
47
+ expect(second.get(view)).toBe(original);
48
+ });
@@ -4,9 +4,11 @@ import { act, renderHook } from "@testing-library/react";
4
4
  import { atom, createStore, Provider } from "jotai";
5
5
  import type { ReactNode } from "react";
6
6
  import { describe, expect, it, vi } from "vitest";
7
+ import { atomFamily, selectAtom } from "jotai/utils";
8
+ import { createKeyedAtomHook } from "../create-keyed-atom-hook";
7
9
  import { createKeyedSelectorHook } from "../create-keyed-selector-hook";
8
10
 
9
- function setup() {
11
+ function setup(kind: "selector" | "family") {
10
12
  const source = atom(
11
13
  new Map([
12
14
  ["a", 1],
@@ -20,13 +22,20 @@ function setup() {
20
22
  const select = vi.fn((state: Map<string, number>, key: string) =>
21
23
  state.get(key),
22
24
  );
23
- const useEntry = createKeyedSelectorHook(source, select);
25
+ const useEntry =
26
+ kind === "selector"
27
+ ? createKeyedSelectorHook(source, select)
28
+ : createKeyedAtomHook(
29
+ atomFamily((key: string) =>
30
+ selectAtom(source, (state) => select(state, key)),
31
+ ),
32
+ );
24
33
  return { source, store, wrapper, select, useEntry };
25
34
  }
26
35
 
27
- describe("createKeyedSelectorHook", () => {
36
+ describe.each(["selector", "family"] as const)("keyed hooks (%s)", (kind) => {
28
37
  it("isolates renders while observing changes and removal of its own entry", () => {
29
- const { source, store, wrapper, useEntry } = setup();
38
+ const { source, store, wrapper, useEntry } = setup(kind);
30
39
  const renders = vi.fn();
31
40
  const { result } = renderHook(
32
41
  () => {
@@ -67,7 +76,7 @@ describe("createKeyedSelectorHook", () => {
67
76
  });
68
77
 
69
78
  it("keeps the selector stable on rerender and switches keys without stale reads", () => {
70
- const { source, store, wrapper, select, useEntry } = setup();
79
+ const { source, store, wrapper, select, useEntry } = setup(kind);
71
80
  const renders = vi.fn();
72
81
  const { result, rerender } = renderHook(
73
82
  ({ id }) => {
@@ -98,7 +107,7 @@ describe("createKeyedSelectorHook", () => {
98
107
  });
99
108
 
100
109
  it("releases the source subscription and stops selecting after unmount", () => {
101
- const { source, store, wrapper, select, useEntry } = setup();
110
+ const { source, store, wrapper, select, useEntry } = setup(kind);
102
111
  const dispose = vi.fn();
103
112
  source.onMount = () => dispose;
104
113
  const { unmount } = renderHook(() => useEntry("a"), { wrapper });
@@ -110,7 +119,7 @@ describe("createKeyedSelectorHook", () => {
110
119
  });
111
120
 
112
121
  it("uses the current Provider store without sharing values between stores", () => {
113
- const { source, store, wrapper, useEntry } = setup();
122
+ const { source, store, wrapper, useEntry } = setup(kind);
114
123
  const otherStore = createStore();
115
124
  otherStore.set(source, new Map([["a", 7]]));
116
125
  const first = renderHook(() => useEntry("a"), { wrapper });
@@ -0,0 +1,24 @@
1
+ /* Copyright 2026 Marimo. All rights reserved. */
2
+
3
+ import { type Atom, atom } from "jotai/vanilla";
4
+ import { selectAtom } from "jotai/utils";
5
+ import { arrayShallowEquals } from "@/utils/arrays";
6
+
7
+ /**
8
+ * Select cheap, immutable inputs before computing a view. Selectors still run
9
+ * when the source changes; derive runs only when a selected input changes.
10
+ * Return primitives or shared references, not newly allocated objects, in the
11
+ * tuple. Create once (or inside an atomFamily), never during render.
12
+ */
13
+ export function atomWithSelectedInputs<
14
+ State,
15
+ const Inputs extends readonly unknown[],
16
+ View,
17
+ >(
18
+ source: Atom<State>,
19
+ select: (state: State) => Inputs,
20
+ derive: (inputs: Inputs) => View,
21
+ ): Atom<View> {
22
+ const inputs = selectAtom(source, select, arrayShallowEquals);
23
+ return atom((get) => derive(get(inputs)));
24
+ }
@@ -0,0 +1,18 @@
1
+ /* Copyright 2026 Marimo. All rights reserved. */
2
+
3
+ import { type Atom, useAtomValue } from "jotai";
4
+ import { useMemo } from "react";
5
+
6
+ /**
7
+ * Define at module scope. Each mount keeps its atom until the key changes;
8
+ * React owns subscription cleanup. Accepts atom families or atom factories.
9
+ * Family cache eviction remains the owner's responsibility.
10
+ */
11
+ export function createKeyedAtomHook<Key, Value>(
12
+ createAtom: (key: Key) => Atom<Value>,
13
+ ) {
14
+ return function useKeyedAtom(key: Key): Value {
15
+ const selected = useMemo(() => createAtom(key), [key]);
16
+ return useAtomValue(selected);
17
+ };
18
+ }
@@ -1,8 +1,8 @@
1
1
  /* Copyright 2026 Marimo. All rights reserved. */
2
2
 
3
- import { type Atom, useAtomValue } from "jotai";
3
+ import type { Atom } from "jotai";
4
4
  import { selectAtom } from "jotai/utils";
5
- import { useMemo } from "react";
5
+ import { createKeyedAtomHook } from "./create-keyed-atom-hook";
6
6
 
7
7
  /**
8
8
  * Define at module scope to subscribe to one keyed slice of immutable state.
@@ -16,11 +16,7 @@ export function createKeyedSelectorHook<State, Key, Slice>(
16
16
  source: Atom<State>,
17
17
  select: (state: State, key: Key) => Slice,
18
18
  ) {
19
- return function useKeyedSelector(key: Key): Slice {
20
- const selected = useMemo(
21
- () => selectAtom(source, (state) => select(state, key)),
22
- [key],
23
- );
24
- return useAtomValue(selected);
25
- };
19
+ return createKeyedAtomHook((key: Key) =>
20
+ selectAtom(source, (state) => select(state, key)),
21
+ );
26
22
  }
@@ -107,7 +107,15 @@ vi.mock("@/core/wasm/store", () => ({
107
107
  // Import after all mocks are set up
108
108
  import { store } from "@/core/state/jotai";
109
109
  import { initialModeAtom } from "@/core/mode";
110
- import type { NotebookReplica } from "@/core/notebook/replica";
110
+ import {
111
+ createNotebookReplica,
112
+ createReplicaFrame,
113
+ type NotebookReplica,
114
+ } from "@/core/notebook/replica";
115
+ import { MockExecutions } from "@/__mocks__/executions";
116
+ import { mockAnimationFrames } from "@/__mocks__/animation-frames";
117
+ import { fixtureMessages } from "@/core/notebook/replica/__tests__/fixtures";
118
+ import { notebookIsRunningAtom } from "@/core/executions";
111
119
  import { activeNotebookReplicaAtom } from "@/core/session/active-notebook";
112
120
  import { fallbackFileStore, notebookFileStore } from "../store";
113
121
  import { getWasmWorkerName, PyodideBridge } from "../bridge";
@@ -524,3 +532,67 @@ it("signals an interrupt once across pending, completed, and lost-reply retries"
524
532
  store.set(initialModeAtom, undefined);
525
533
  }
526
534
  });
535
+
536
+ it("cancels a received running event before the display frame catches up", async () => {
537
+ vi.clearAllMocks();
538
+ const advanceFrame = mockAnimationFrames();
539
+ store.set(initialModeAtom, "read");
540
+ rpcListeners.initialized();
541
+ mockNotebookSubscribe.mockResolvedValue(undefined);
542
+ mockNotebookUnsubscribe.mockResolvedValue(undefined);
543
+ const backend = await PyodideBridge.INSTANCE.createNotebookBackend();
544
+ const replica = createNotebookReplica(store);
545
+ store.set(activeNotebookReplicaAtom, replica);
546
+ const lifetime = new AbortController();
547
+ const frame = createReplicaFrame(store, replica, { signal: lifetime.signal });
548
+ const disconnect = replica.connect(backend, { onNotification: vi.fn() });
549
+ const buffer = workerState.interruptBuffer!;
550
+ buffer[0] = 0;
551
+ try {
552
+ await vi.waitFor(() =>
553
+ expect(mockNotebookSubscribe).toHaveBeenCalledOnce(),
554
+ );
555
+ const [{ id }] = mockNotebookSubscribe.mock.calls[0];
556
+ const receive = (event: unknown) =>
557
+ rpcListeners.notebookEvent({ id, event: JSON.stringify(event) });
558
+ fixtureMessages("notebook-events.sse").forEach(receive);
559
+ advanceFrame();
560
+ const before = store.get(frame.executionsAtom);
561
+ const run = {
562
+ id: "run-cancel-before-frame",
563
+ notebook_id: "n1",
564
+ runtime_id: "r1",
565
+ origin: { kind: "code", code: "pass" },
566
+ created_at: "2026-10-01T09:20:00Z",
567
+ state: { status: "running", started_at: "2026-10-01T09:20:11Z" },
568
+ };
569
+ receive({ event: "run", id: "1000", data: { run } });
570
+ receive({
571
+ event: "execution",
572
+ id: "1001",
573
+ data: { execution: { ...MockExecutions.running("c1"), run_id: run.id } },
574
+ });
575
+ expect(store.get(notebookIsRunningAtom)).toBe(true);
576
+ expect(store.get(frame.executionsAtom)).toBe(before);
577
+ expect(buffer[0]).toBe(0);
578
+ mockNotebookCall.mockImplementationOnce(async () => {
579
+ expect(buffer[0]).toBe(2);
580
+ return { status: 202, body: run };
581
+ });
582
+ expect((await backend.notebook("n1").cancel({ runId: run.id })).ok).toBe(
583
+ true,
584
+ );
585
+ expect(buffer[0]).toBe(2);
586
+ expect(store.get(frame.executionsAtom)).toBe(before);
587
+ advanceFrame();
588
+ expect(store.get(frame.executionsAtom)).toBe(
589
+ store.get(replica.executionsAtom),
590
+ );
591
+ } finally {
592
+ lifetime.abort();
593
+ disconnect();
594
+ buffer[0] = 0;
595
+ store.set(activeNotebookReplicaAtom, null);
596
+ store.set(initialModeAtom, undefined);
597
+ }
598
+ });
@@ -37,7 +37,10 @@ export function arrayInsertMany<T>(
37
37
  return result;
38
38
  }
39
39
 
40
- export function arrayShallowEquals<T>(a: T[], b: T[]): boolean {
40
+ export function arrayShallowEquals<T>(
41
+ a: readonly T[],
42
+ b: readonly T[],
43
+ ): boolean {
41
44
  if (a === b) {
42
45
  return true;
43
46
  }