@marimo-team/islands 0.26.1-dev21 → 0.26.1-dev25

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 (106) hide show
  1. package/dist/{ConnectedDataExplorerComponent-CR9WyiEc.js → ConnectedDataExplorerComponent-jtTaDisw.js} +16 -16
  2. package/dist/{ErrorBoundary-C5X_T831.js → ErrorBoundary-Bs2ehxEI.js} +6 -6
  3. package/dist/{abnfDiagram-VCTEODGH-DGAbsdXT.js → abnfDiagram-VCTEODGH-cUj3Gnnh.js} +2 -2
  4. package/dist/{any-language-editor-DzGF1ll-.js → any-language-editor-BHgkY7jY.js} +2 -2
  5. package/dist/{architectureDiagram-5GKGNRK7-D4DnIo7R.js → architectureDiagram-5GKGNRK7-CIAZgn9d.js} +1 -1
  6. package/dist/{assertNever-CqwxSD_2.js → assertNever-BHnIohkX.js} +13 -13
  7. package/dist/{chat-ui-qZdDDrzU.js → chat-ui-DOvIzlMA.js} +46 -46
  8. package/dist/{check-D9vf6LYF.js → check-LtjuWmNn.js} +1 -1
  9. package/dist/{chunk-IMKFNOWR-Bc_i6jWx.js → chunk-IMKFNOWR-CB9N3qYR.js} +1 -1
  10. package/dist/{chunk-SHT3W25Y-CGML5pnF.js → chunk-SHT3W25Y-D9njV7TI.js} +1 -1
  11. package/dist/{chunk-SVP7TREG-ZpeFKfFT.js → chunk-SVP7TREG-CUCE0BFm.js} +1 -1
  12. package/dist/{chunk-TICWLB2K-C6cLmcg8.js → chunk-TICWLB2K-iQB6ttkI.js} +1 -1
  13. package/dist/{classDiagram-ZZMXUADV--q40NTXr.js → classDiagram-ZZMXUADV-BI1VBNIo.js} +2 -2
  14. package/dist/{classDiagram-v2-VYDZK3BY-Dt_Pp94L.js → classDiagram-v2-VYDZK3BY-BYL3asWh.js} +2 -2
  15. package/dist/{code-visibility-7FxdzbDq.js → code-visibility-BnMkbydx.js} +19 -19
  16. package/dist/{common-D-iTRwaQ.js → common-CQur5dRA.js} +156 -156
  17. package/dist/{config-B8JCQMby.js → config-DL9e-OWE.js} +3 -3
  18. package/dist/{copy-icon-BLig0ZKb.js → copy-icon-rYV2znAe.js} +2 -2
  19. package/dist/{createReducer-BIUQ3TbG.js → createReducer-BdiSrxHu.js} +5 -5
  20. package/dist/{cynefinDiagram-5FMLGOSQ-2FtF_-cc.js → cynefinDiagram-5FMLGOSQ-DpGtYvnZ.js} +1 -1
  21. package/dist/{dagre-GXQ25YYZ-Cymu2SPS.js → dagre-GXQ25YYZ-B5GDC2kN.js} +1 -1
  22. package/dist/{data-grid-overlay-editor-DoWUW2oW.js → data-grid-overlay-editor-BXEY35Xl.js} +1 -1
  23. package/dist/{diagram-S7CK7UJ4-OwDa8kAa.js → diagram-S7CK7UJ4-B2T25t1t.js} +1 -1
  24. package/dist/{diagram-UQ7AKVKN-CzRDwZwd.js → diagram-UQ7AKVKN-Dy3B5L_z.js} +1 -1
  25. package/dist/{diagram-VX7I27RA-XRIcgMDs.js → diagram-VX7I27RA-tOptWvNh.js} +1 -1
  26. package/dist/{diagram-Z3DM3KII-DdRDYAs6.js → diagram-Z3DM3KII-DsgZAokO.js} +1 -1
  27. package/dist/{dialog-DGh2HNAO.js → dialog-vs6x3On9.js} +19 -19
  28. package/dist/{dropdown-menu-ChH3oiqI.js → dropdown-menu-DYN2RV5d.js} +193 -193
  29. package/dist/{ebnfDiagram-PWID7BFC-CZMNMGNP.js → ebnfDiagram-PWID7BFC-CGWECzS1.js} +2 -2
  30. package/dist/{erDiagram-RLTQ6QDP-ByxHAN4b.js → erDiagram-RLTQ6QDP-CZLi87y3.js} +1 -1
  31. package/dist/{error-banner-BvRaQnGH.js → error-banner-D-AC7pQx.js} +70 -70
  32. package/dist/{error-entries-DhI0hGvj.js → error-entries-CncQR572.js} +443 -436
  33. package/dist/{feedback-button-OUiV15AL.js → feedback-button-BAOp7zqu.js} +120 -120
  34. package/dist/{flowDiagram-HODETNUW-BQpzWx5O.js → flowDiagram-HODETNUW-CS86WYbX.js} +2 -2
  35. package/dist/{formats-BxP8k8Un.js → formats-BUFLQJXY.js} +1 -1
  36. package/dist/{glide-data-editor-CFouYM6e.js → glide-data-editor-Ce94qTW7.js} +11 -11
  37. package/dist/{glide-utils-bKdvDwwo.js → glide-utils-CZ-O-CB_.js} +2 -2
  38. package/dist/{globals-B_U6Frqj.js → globals-Uqg4j5z5.js} +3 -3
  39. package/dist/{html-to-image-B803aaWE.js → html-to-image-BU7H-AM1.js} +4323 -4318
  40. package/dist/{infoDiagram-27XIBGKW-C9EWHkak.js → infoDiagram-27XIBGKW-C9JBFfpC.js} +1 -1
  41. package/dist/{ishikawaDiagram-5VMMS53U-D67SGFvp.js → ishikawaDiagram-5VMMS53U-Eh3iuw2D.js} +1 -1
  42. package/dist/{kanban-definition-UXKFOSKX-CTMTiazR.js → kanban-definition-UXKFOSKX-DYtuVwYD.js} +1 -1
  43. package/dist/main.js +399 -398
  44. package/dist/{mermaid-DE_tvTGF.js → mermaid--k1o49nH.js} +34 -34
  45. package/dist/{mindmap-definition-YA3MSWOX-LzNgDy8O.js → mindmap-definition-YA3MSWOX-Dn1Cnqys.js} +1 -1
  46. package/dist/{number-overlay-editor-CiQQjf9m.js → number-overlay-editor-Br_Vp3Ws.js} +1 -1
  47. package/dist/{pegDiagram-XKGWAZYB-DFMS6feI.js → pegDiagram-XKGWAZYB-DiY7rITR.js} +2 -2
  48. package/dist/{pencil-CHkdsX07.js → pencil-AWgwbH4D.js} +1 -1
  49. package/dist/{pieDiagram-E7YTZNPT-C0MSBop-.js → pieDiagram-E7YTZNPT-BL6InbDs.js} +1 -1
  50. package/dist/{process-output-CnCLfvnL.js → process-output-xJm8T5-E.js} +4 -4
  51. package/dist/{railroadDiagram-O6MQD6OU-mbdav2pV.js → railroadDiagram-O6MQD6OU-DterenMu.js} +2 -2
  52. package/dist/{requirementDiagram-BXWQKSXE-C1HNBBO6.js → requirementDiagram-BXWQKSXE-Vb5_9LHC.js} +1 -1
  53. package/dist/{reveal-component-B73BObRc.js → reveal-component-B7TgfbYJ.js} +1008 -1008
  54. package/dist/{select-CvorIE3l.js → select-CKLRKIzB.js} +298 -298
  55. package/dist/{sequenceDiagram-WJ2MYXX4-D6gBHifq.js → sequenceDiagram-WJ2MYXX4-BWsq8hMt.js} +1 -1
  56. package/dist/{spec-ayzaXGVq.js → spec-C4uOz0Em.js} +4 -4
  57. package/dist/{stateDiagram-D77RDMKH-Bx-fTtRZ.js → stateDiagram-D77RDMKH-nfKKy6aQ.js} +2 -2
  58. package/dist/{stateDiagram-v2-MP3YSRHH-Cec8T2yO.js → stateDiagram-v2-MP3YSRHH-DMUHA_9A.js} +2 -2
  59. package/dist/{static-state-CqwW3B_X.js → static-state-DZ1nSa6e.js} +9 -9
  60. package/dist/{swimlanes-42K2YHIH-C2bAgnov.js → swimlanes-42K2YHIH-N4qHIMoc.js} +1 -1
  61. package/dist/{swimlanesDiagram-VR7AAH4N-CzeG-Mnb.js → swimlanesDiagram-VR7AAH4N-DQpDDjQb.js} +2 -2
  62. package/dist/{timeline-definition-24CTP7MA-DTJ0Rx8X.js → timeline-definition-24CTP7MA-Od8dY9F5.js} +1 -1
  63. package/dist/{toast-6V8Og7d5.js → toast-bhZHUEal.js} +187 -187
  64. package/dist/{tooltip-D0h-ZJ6j.js → tooltip-DSWC_Td_.js} +40 -40
  65. package/dist/{use-restore-focus-BFvwj2Hj.js → use-restore-focus-ocw7t85i.js} +1371 -1373
  66. package/dist/{useDateFormatter-D6o9PsWt.js → useDateFormatter-BiDS8uXQ.js} +2 -2
  67. package/dist/{useDeepCompareMemoize-D-Pbv7dN.js → useDeepCompareMemoize-BsaXfZ8C.js} +1 -1
  68. package/dist/{useLifecycle-CE0yGTMF.js → useLifecycle-CCV7yZ-v.js} +1 -1
  69. package/dist/{vega-component-DTf7GHQe.js → vega-component-DpTyTrz3.js} +6 -6
  70. package/dist/{vennDiagram-4TSXK5OY-lIM3SAjl.js → vennDiagram-4TSXK5OY-Di3T2YMb.js} +1 -1
  71. package/dist/{wardleyDiagram-VM6X3IG4-Bw_t7uvA.js → wardleyDiagram-VM6X3IG4-CKOF5DTi.js} +1 -1
  72. package/dist/{xychartDiagram-S5SC5T6Z-BXwkLYKj.js → xychartDiagram-S5SC5T6Z-GYLPWSeb.js} +1 -1
  73. package/package.json +1 -1
  74. package/src/__mocks__/executions.ts +25 -3
  75. package/src/__tests__/notebook-analysis.ts +48 -0
  76. package/src/components/editor/ai/__tests__/completion-utils.test.ts +28 -61
  77. package/src/components/editor/navigation/__tests__/navigation.test.ts +0 -4
  78. package/src/core/cells/__tests__/add-missing-import.test.ts +14 -9
  79. package/src/core/cells/__tests__/pending-delete-service.test.tsx +4 -11
  80. package/src/core/cells/add-missing-import.ts +2 -3
  81. package/src/core/codemirror/code-lens/__tests__/entities.test.ts +7 -11
  82. package/src/core/codemirror/code-lens/__tests__/extension.test.ts +8 -13
  83. package/src/core/codemirror/code-lens/__tests__/perf.test.ts +7 -9
  84. package/src/core/codemirror/copilot/__tests__/getCodes.test.ts +9 -13
  85. package/src/core/codemirror/go-to-definition/__tests__/utils.test.ts +16 -35
  86. package/src/core/codemirror/language/embedded/__tests__/embedded-python.test.ts +2 -18
  87. package/src/core/codemirror/reactive-references/__tests__/extension.test.ts +8 -14
  88. package/src/core/datasets/__tests__/data-source.test.ts +15 -17
  89. package/src/core/datasets/data-source-connections.ts +8 -11
  90. package/src/core/datasets/state.ts +7 -12
  91. package/src/core/executions/__tests__/freshness.test.ts +8 -3
  92. package/src/core/executions/__tests__/interrupt.test.ts +1 -0
  93. package/src/core/executions/__tests__/select.test.ts +1 -1
  94. package/src/core/executions/atoms.ts +1 -0
  95. package/src/core/executions/freshness.ts +2 -2
  96. package/src/core/islands/bootstrap.ts +0 -2
  97. package/src/core/notebook/replica/__tests__/executions.test.ts +4 -2
  98. package/src/core/notebook/replica/replica.ts +11 -2
  99. package/src/core/notebook/replica/resources/executions.ts +29 -20
  100. package/src/core/session/__tests__/useNotebookSession.hook.test.tsx +192 -1
  101. package/src/core/session/useNotebookSession.tsx +37 -37
  102. package/src/core/storage/__tests__/state.test.ts +6 -9
  103. package/src/core/storage/state.ts +5 -8
  104. package/src/core/variables/state.ts +73 -68
  105. package/src/core/variables/types.ts +2 -2
  106. package/src/core/variables/__tests__/state.test.ts +0 -148
@@ -18,15 +18,13 @@ type ProducedItem =
18
18
  /** Time the host published the item, when included in a live event. */
19
19
  export type Item = ProducedItem & { readonly time?: string };
20
20
 
21
- /** An execution on the stream, with the items and variables it has produced. */
21
+ /** An execution on the stream, with the items it has produced. */
22
22
  export interface Execution extends Result {
23
23
  /** Items by id. `itemsInOrder` sorts them by `seq`. */
24
24
  readonly lastSeq?: number;
25
25
  /** Fast path for a reader displaying exactly the version before an append. */
26
26
  readonly append?: { before: WeakRef<Execution["items"]>; item: Item };
27
27
  readonly items: ReadonlyMap<Protocol.ItemId, Item>;
28
- /** The variables the execution bound, by item id. */
29
- readonly variables: ReadonlyMap<Protocol.ItemId, Protocol.Variable>;
30
28
  }
31
29
 
32
30
  /**
@@ -41,6 +39,11 @@ export interface Executions {
41
39
  readonly executions: ReadonlyMap<Protocol.ExecutionId, Execution>;
42
40
  /** The execution on the stream for each cell that has one. */
43
41
  readonly latest: ReadonlyMap<Protocol.CellId, Protocol.ExecutionId>;
42
+ /** Bindings by defining cell and item id, shared across unrelated stream updates. */
43
+ readonly variables: ReadonlyMap<
44
+ Protocol.CellId,
45
+ ReadonlyMap<Protocol.ItemId, Protocol.Variable>
46
+ >;
44
47
  readonly results: Results;
45
48
  readonly scratch: Result | null;
46
49
  /** The latest scratch execution to start, including one that printed nothing. */
@@ -135,15 +138,14 @@ function remove(state: Executions, id: Protocol.ExecutionId): Executions {
135
138
  return state;
136
139
  }
137
140
  const cellId = execution.record.cell_id;
141
+ const isLatest = cellId !== null && state.latest.get(cellId) === id;
138
142
  return {
139
143
  ...state,
140
144
  executions: without(state.executions, id),
145
+ variables: isLatest ? without(state.variables, cellId) : state.variables,
141
146
  scratchConsole:
142
147
  state.scratchConsole?.record.id === id ? undefined : state.scratchConsole,
143
- latest:
144
- cellId !== null && state.latest.get(cellId) === id
145
- ? without(state.latest, cellId)
146
- : state.latest,
148
+ latest: isLatest ? without(state.latest, cellId) : state.latest,
147
149
  };
148
150
  }
149
151
 
@@ -182,23 +184,30 @@ function detach(state: Executions, itemId: Protocol.ItemId): Executions {
182
184
  }
183
185
 
184
186
  function bind(state: Executions, variable: Protocol.Variable): Executions {
185
- const execution = state.executions.get(variable.execution_id);
186
- if (execution === undefined) {
187
+ const cellId = state.executions.get(variable.execution_id)?.record.cell_id;
188
+ if (cellId == null) {
187
189
  return state;
188
190
  }
189
- return set(state, {
190
- ...execution,
191
- variables: new Map(execution.variables).set(variable.id, variable),
192
- });
191
+ const bindings = new Map(state.variables.get(cellId)).set(
192
+ variable.id,
193
+ variable,
194
+ );
195
+ return {
196
+ ...state,
197
+ variables: new Map(state.variables).set(cellId, bindings),
198
+ };
193
199
  }
194
200
 
195
201
  function unbind(state: Executions, itemId: Protocol.ItemId): Executions {
196
- for (const execution of state.executions.values()) {
197
- if (execution.variables.has(itemId)) {
198
- return set(state, {
199
- ...execution,
200
- variables: without(execution.variables, itemId),
201
- });
202
+ for (const [cellId, bindings] of state.variables) {
203
+ if (bindings.has(itemId)) {
204
+ const variables = new Map(state.variables);
205
+ if (bindings.size === 1) {
206
+ variables.delete(cellId);
207
+ } else {
208
+ variables.set(cellId, without(bindings, itemId));
209
+ }
210
+ return { ...state, variables };
202
211
  }
203
212
  }
204
213
  return state;
@@ -282,6 +291,7 @@ export const executions: NotebookResource<Executions, Kind> = {
282
291
  runs: new Map(),
283
292
  executions: new Map(),
284
293
  latest: new Map(),
294
+ variables: new Map(),
285
295
  results: new Map(),
286
296
  scratch: null,
287
297
  },
@@ -319,7 +329,6 @@ export const executions: NotebookResource<Executions, Kind> = {
319
329
  append: previous?.append,
320
330
  lastSeq: previous?.lastSeq,
321
331
  items: previous?.items ?? new Map(),
322
- variables: previous?.variables ?? new Map(),
323
332
  });
324
333
  },
325
334
  "execution.removed": (state, { data }) => remove(state, data.id),
@@ -37,7 +37,7 @@ vi.mock("@/core/runtime/config", async () => {
37
37
 
38
38
  import { MockNotebook } from "@/__mocks__/notebook";
39
39
  import { Deferred } from "@/utils/Deferred";
40
- import { cellId } from "@/__tests__/branded";
40
+ import { cellId, variableName } from "@/__tests__/branded";
41
41
  import { alertAtom, getPackageAlert } from "@/core/alerts/state";
42
42
  import { stagedAICellsAtom } from "@/core/ai/staged-cells";
43
43
  import { cellRuntimeAtom } from "@/core/cells/cells";
@@ -59,7 +59,10 @@ import {
59
59
  cell,
60
60
  CONFIG,
61
61
  document as documentOf,
62
+ withCells,
62
63
  } from "@/core/notebook/document/__tests__/fixtures";
64
+ import { variablesAtom } from "@/core/variables/state";
65
+ import { storageNamespacesAtom } from "@/core/storage/state";
63
66
  import { initialRunCompletedAtom } from "../../kernel/state";
64
67
  import { connectionAtom, startupProgressAtom } from "../../network/connection";
65
68
  import { generateSessionId } from "../../kernel/session";
@@ -75,6 +78,7 @@ import {
75
78
  import { MockExecutions } from "@/__mocks__/executions";
76
79
  import { VirtualFileTracker } from "@/core/static/virtual-file-tracker";
77
80
  import { useNotebookSession } from "../useNotebookSession";
81
+ import type { CellAnalysis } from "@marimo-team/client/protocol";
78
82
  import { type NotebookTransport, StreamStopped } from "@marimo-team/client";
79
83
 
80
84
  const C1 = cellId("c1");
@@ -442,6 +446,193 @@ describe("useNotebookSession messages", () => {
442
446
  expect(blocked().size).toBe(0);
443
447
  });
444
448
 
449
+ function publishDocument(document: ReturnType<typeof documentOf>) {
450
+ for (const cell of document.cells.values()) {
451
+ receive({ event: "cell", data: { cell } });
452
+ }
453
+ receive({ event: "document", data: { document: document.revision } });
454
+ }
455
+
456
+ function analyzeVariables(
457
+ document: ReturnType<typeof documentOf>,
458
+ cells: Record<string, CellAnalysis>,
459
+ ) {
460
+ receive({
461
+ event: "analysis",
462
+ data: {
463
+ analysis: {
464
+ notebook_id: document.revision.notebook_id,
465
+ document_etag: document.revision.etag,
466
+ cells,
467
+ },
468
+ },
469
+ });
470
+ }
471
+
472
+ it("joins analysis to its defining cell's binding across updates, removal, and edits", () => {
473
+ const document = documentOf();
474
+ receive({
475
+ event: "notebook",
476
+ data: { notebook: MockExecutions.notebook() },
477
+ });
478
+ publishDocument(document);
479
+ const execution = MockExecutions.completed("c1");
480
+ const variable = {
481
+ id: "bound-x",
482
+ execution_id: execution.id,
483
+ name: "x",
484
+ type: "int",
485
+ preview: "1",
486
+ revision: { execution_id: execution.id, update: 0 },
487
+ };
488
+ receive({ event: "execution", data: { execution } });
489
+ receive({ event: "variable", data: { variable } });
490
+ expect(store.get(variablesAtom)).toEqual({});
491
+ receive({ event: "ready", data: {}, id: "1" });
492
+ const x = { name: "x", declaredBy: ["c1"], usedBy: [] };
493
+ expect(store.get(variablesAtom)).toEqual({
494
+ x: { ...x, dataType: "int", value: "1" },
495
+ });
496
+
497
+ analyzeVariables(document, {
498
+ c2: { defs: ["pending"], refs: ["x"], diagnostics: [] },
499
+ c1: { defs: ["x", "pending"], refs: [], diagnostics: [] },
500
+ });
501
+ const declarations = {
502
+ x: { ...x, usedBy: ["c2"] },
503
+ pending: { name: "pending", declaredBy: ["c2", "c1"], usedBy: [] },
504
+ };
505
+ expect(store.get(variablesAtom)).toEqual({
506
+ ...declarations,
507
+ x: { ...declarations.x, dataType: "int", value: "1" },
508
+ });
509
+
510
+ const updated = {
511
+ ...variable,
512
+ preview: "2",
513
+ revision: { ...variable.revision, update: 1 },
514
+ };
515
+ receive({ event: "variable", data: { variable: updated } });
516
+ const variables = store.get(variablesAtom);
517
+ expect(variables).toEqual({
518
+ ...declarations,
519
+ x: { ...declarations.x, dataType: "int", value: "2" },
520
+ });
521
+ receive({ event: "execution", data: { execution } });
522
+ expect(store.get(variablesAtom)).toBe(variables);
523
+ receive({ event: "variable.removed", data: { id: variable.id } });
524
+ expect(store.get(variablesAtom)).toEqual(declarations);
525
+
526
+ receive({ event: "variable", data: { variable } });
527
+ const moved = withCells(document, {
528
+ c1: cell("c1", ""),
529
+ c2: cell("c2", "x = 3"),
530
+ });
531
+ publishDocument(moved);
532
+ const duringEdit = { ...variable, name: "new_name", id: "bound-new" };
533
+ receive({ event: "variable", data: { variable: duringEdit } });
534
+ expect(store.get(variablesAtom)[variableName("new_name")]).toEqual({
535
+ name: "new_name",
536
+ declaredBy: ["c1"],
537
+ usedBy: [],
538
+ dataType: "int",
539
+ value: "1",
540
+ });
541
+ analyzeVariables(moved, {
542
+ c1: { defs: [], refs: [], diagnostics: [] },
543
+ c2: { defs: ["x"], refs: [], diagnostics: [] },
544
+ });
545
+ expect(store.get(variablesAtom)[variableName("new_name")]).toEqual({
546
+ name: "new_name",
547
+ declaredBy: [],
548
+ usedBy: [],
549
+ dataType: "int",
550
+ value: "1",
551
+ });
552
+ receive({ event: "variable.removed", data: { id: duringEdit.id } });
553
+ expect(store.get(variablesAtom)).toEqual({
554
+ x: { name: "x", declaredBy: ["c2"], usedBy: [] },
555
+ });
556
+ const beforeReset = store.get(variablesAtom);
557
+ receive({ event: "reset", data: {} });
558
+ expect(store.get(variablesAtom)).toEqual(beforeReset);
559
+ receive({
560
+ event: "notebook",
561
+ data: { notebook: MockExecutions.notebook("n2") },
562
+ });
563
+ publishDocument(documentOf("n2"));
564
+ receive({ event: "ready", data: {}, id: "2" });
565
+ expect(store.get(variablesAtom)).toEqual({});
566
+ });
567
+
568
+ it("keeps a live variable and its namespace through an incomplete edit", () => {
569
+ const document = documentOf();
570
+ const discover = () =>
571
+ act(() =>
572
+ connection(fake).send({
573
+ op: "storage-namespaces",
574
+ namespaces: ["x", "z"].map((name) => ({
575
+ name: variableName(name),
576
+ displayName: name,
577
+ protocol: "s3",
578
+ rootPath: "",
579
+ backendType: "obstore",
580
+ storageEntries: [],
581
+ })),
582
+ } satisfies NotificationPayload["data"]),
583
+ );
584
+ const namespaces = () =>
585
+ store.get(storageNamespacesAtom).map((ns) => ns.name);
586
+ receive({
587
+ event: "notebook",
588
+ data: { notebook: MockExecutions.notebook() },
589
+ });
590
+ publishDocument(document);
591
+ receive({ event: "ready", data: {}, id: "1" });
592
+ // Discovery can precede the binding from the same execution.
593
+ discover();
594
+ const execution = MockExecutions.completed("c1");
595
+ const variable = {
596
+ id: "bound-x",
597
+ execution_id: execution.id,
598
+ name: "x",
599
+ type: "S3Store",
600
+ preview: "s3://bucket",
601
+ revision: { execution_id: execution.id, update: 0 },
602
+ };
603
+ receive({ event: "execution", data: { execution } });
604
+ receive({ event: "variable", data: { variable } });
605
+ analyzeVariables(document, {
606
+ c1: { defs: ["x"], refs: [], diagnostics: [] },
607
+ });
608
+ const beforeEdit = store.get(variablesAtom);
609
+ const edited = withCells(document, { c1: cell("c1", "x = (") });
610
+ publishDocument(edited);
611
+ analyzeVariables(edited, { c1: { defs: [], refs: [], diagnostics: [] } });
612
+ expect(namespaces()).toEqual(["x", "z"]);
613
+ expect(store.get(variablesAtom)).toEqual({
614
+ x: {
615
+ name: "x",
616
+ declaredBy: [],
617
+ usedBy: [],
618
+ dataType: "S3Store",
619
+ value: "s3://bucket",
620
+ },
621
+ });
622
+
623
+ publishDocument(document);
624
+ analyzeVariables(document, {
625
+ c1: { defs: ["x"], refs: [], diagnostics: [] },
626
+ });
627
+ expect(namespaces()).toEqual(["x", "z"]);
628
+ expect(store.get(variablesAtom)).toEqual(beforeEdit);
629
+ receive({ event: "variable.removed", data: { id: variable.id } });
630
+ expect(namespaces()).toEqual(["z"]);
631
+ expect(store.get(variablesAtom)).toEqual({
632
+ x: { name: "x", declaredBy: ["c1"], usedBy: [] },
633
+ });
634
+ });
635
+
445
636
  it("records completion of the initial run", () => {
446
637
  const notification = {
447
638
  op: "completed-run",
@@ -73,8 +73,7 @@ import {
73
73
  ListStorageEntries,
74
74
  } from "../storage/request-registry";
75
75
  import { useStorageActions } from "../storage/state";
76
- import { useVariablesActions } from "../variables/state";
77
- import type { VariableName } from "../variables/types";
76
+ import { variableBindingsAtom } from "../variables/state";
78
77
  import {
79
78
  activeDocumentModelAtom,
80
79
  confirmedDocumentAtom,
@@ -99,10 +98,9 @@ export function useNotebookSession(opts: { sessionId: SessionId }) {
99
98
  const { reconcileStagedCells } = useStagedAICellsActions();
100
99
  const { addExecution } = useRunsActions();
101
100
  const setInitialRunCompleted = useSetAtom(initialRunCompletedAtom);
102
- const { setVariables, setMetadata } = useVariablesActions();
103
- const { addColumnPreview } = useDatasetsActions();
104
- const { addDatasets, filterDatasetsFromVariables } = useDatasetsActions();
105
- const { addDataSourceConnection, filterDataSourcesFromVariables } =
101
+ const { addColumnPreview, addDatasets, removeDatasetsForVariables } =
102
+ useDatasetsActions();
103
+ const { addDataSourceConnection, removeConnectionsForVariables } =
106
104
  useDataSourceActions();
107
105
  const { setLayoutData } = useLayoutActions();
108
106
  const [connection, setConnection] = useAtom(connectionAtom);
@@ -121,10 +119,8 @@ export function useNotebookSession(opts: { sessionId: SessionId }) {
121
119
  const transportType = useAtomValue(connectionTransportTypeAtom);
122
120
  const setCacheInfo = useSetAtom(cacheInfoAtom);
123
121
  const setKernelStartupError = useSetAtom(kernelStartupErrorAtom);
124
- const {
125
- setNamespaces: setStorageNamespaces,
126
- filterFromVariables: filterStorageFromVariables,
127
- } = useStorageActions();
122
+ const { setNamespaces: setStorageNamespaces, removeNamespacesForVariables } =
123
+ useStorageActions();
128
124
 
129
125
  const handleNotification = (msg: NotificationPayload) => {
130
126
  switch (msg.data.op) {
@@ -227,33 +223,6 @@ export function useNotebookSession(opts: { sessionId: SessionId }) {
227
223
  case "pdb-output":
228
224
  showCommandOutput(msg.data);
229
225
  return;
230
- case "variables":
231
- const variableNames = msg.data.variables.map((v) => v.name);
232
- setVariables(
233
- msg.data.variables.map((v) => ({
234
- name: v.name,
235
- declaredBy: v.declared_by,
236
- usedBy: v.used_by,
237
- })),
238
- );
239
- filterDatasetsFromVariables(variableNames);
240
- filterDataSourcesFromVariables(variableNames);
241
- filterStorageFromVariables(variableNames);
242
- return;
243
- case "variable-values":
244
- setMetadata([
245
- ...(msg.data.removed ?? []).map((v) => ({
246
- name: v.name as VariableName,
247
- dataType: undefined,
248
- value: undefined,
249
- })),
250
- ...msg.data.variables.map((v) => ({
251
- name: v.name as VariableName,
252
- dataType: v.datatype,
253
- value: v.value,
254
- })),
255
- ]);
256
- return;
257
226
  case "alert":
258
227
  toast({
259
228
  title: msg.data.title,
@@ -447,6 +416,37 @@ export function useNotebookSession(opts: { sessionId: SessionId }) {
447
416
  },
448
417
  });
449
418
 
419
+ // Discovery can precede a binding. Remove only resources whose binding disappeared.
420
+ useLayoutEffect(() => {
421
+ let previous = store.get(variableBindingsAtom);
422
+ return store.sub(variableBindingsAtom, () => {
423
+ const current = store.get(variableBindingsAtom);
424
+ const removed = new Set<string>();
425
+ for (const [cellId, bindings] of previous ?? []) {
426
+ const next = current?.get(cellId);
427
+ if (bindings === next) {
428
+ continue;
429
+ }
430
+ for (const [id, binding] of bindings) {
431
+ if (!next?.has(id)) {
432
+ removed.add(binding.name);
433
+ }
434
+ }
435
+ }
436
+ previous = current;
437
+ if (removed.size > 0) {
438
+ removeDatasetsForVariables(removed);
439
+ removeConnectionsForVariables(removed);
440
+ removeNamespacesForVariables(removed);
441
+ }
442
+ });
443
+ }, [
444
+ store,
445
+ removeDatasetsForVariables,
446
+ removeConnectionsForVariables,
447
+ removeNamespacesForVariables,
448
+ ]);
449
+
450
450
  const documentModel = useMemo(
451
451
  () =>
452
452
  createDocumentModel({
@@ -350,16 +350,13 @@ describe("storage state", () => {
350
350
  });
351
351
  });
352
352
 
353
- describe("filterFromVariables", () => {
353
+ describe("removeNamespacesForVariables", () => {
354
354
  it("should keep namespaces whose variable is still in scope", () => {
355
355
  const ns1 = makeNamespace({ name: variableName("var_a") });
356
356
  const ns2 = makeNamespace({ name: variableName("var_b") });
357
357
  actions.setNamespaces({ namespaces: [ns1, ns2] });
358
358
 
359
- actions.filterFromVariables([
360
- variableName("var_a"),
361
- variableName("var_b"),
362
- ]);
359
+ actions.removeNamespacesForVariables(new Set(["unrelated"]));
363
360
 
364
361
  expect(state.namespaces).toEqual([ns1, ns2]);
365
362
  });
@@ -369,17 +366,17 @@ describe("storage state", () => {
369
366
  const ns2 = makeNamespace({ name: variableName("var_b") });
370
367
  actions.setNamespaces({ namespaces: [ns1, ns2] });
371
368
 
372
- actions.filterFromVariables([variableName("var_a")]);
369
+ actions.removeNamespacesForVariables(new Set(["var_b"]));
373
370
 
374
371
  expect(state.namespaces).toEqual([ns1]);
375
372
  });
376
373
 
377
- it("should remove all named namespaces when given an empty variable list", () => {
374
+ it("should remove namespaces for each removed binding", () => {
378
375
  const ns1 = makeNamespace({ name: variableName("var_a") });
379
376
  const ns2 = makeNamespace({ name: variableName("var_b") });
380
377
  actions.setNamespaces({ namespaces: [ns1, ns2] });
381
378
 
382
- actions.filterFromVariables([]);
379
+ actions.removeNamespacesForVariables(new Set(["var_a", "var_b"]));
383
380
 
384
381
  expect(state.namespaces).toEqual([]);
385
382
  });
@@ -395,7 +392,7 @@ describe("storage state", () => {
395
392
  entries: [entry],
396
393
  });
397
394
 
398
- actions.filterFromVariables([]);
395
+ actions.removeNamespacesForVariables(new Set(["ns"]));
399
396
 
400
397
  // Namespace removed, but entries remain (they are keyed independently)
401
398
  expect(state.namespaces).toEqual([]);
@@ -5,7 +5,6 @@ import { useCallback, useRef, useState } from "react";
5
5
  import { useAsyncData } from "@/hooks/useAsyncData";
6
6
  import { createReducerAndAtoms } from "@/utils/createReducer";
7
7
  import type { NotificationMessageData } from "../kernel/messages";
8
- import type { VariableName } from "../variables/types";
9
8
  import {
10
9
  ListStorageEntries,
11
10
  type StorageEntriesResult,
@@ -97,13 +96,11 @@ const {
97
96
  };
98
97
  },
99
98
 
100
- filterFromVariables: (state, variableNames: VariableName[]) => {
101
- const names = new Set(variableNames);
102
- // Filter out namespaces whose backing variable is no longer in scope
103
- const namespaces = state.namespaces.filter((ns) => {
104
- return names.has(ns.name);
105
- });
106
- return { ...state, namespaces };
99
+ removeNamespacesForVariables: (state, removed: ReadonlySet<string>) => {
100
+ const namespaces = state.namespaces.filter((ns) => !removed.has(ns.name));
101
+ return namespaces.length === state.namespaces.length
102
+ ? state
103
+ : { ...state, namespaces };
107
104
  },
108
105
  });
109
106
 
@@ -1,81 +1,86 @@
1
1
  /* Copyright 2026 Marimo. All rights reserved. */
2
2
 
3
- import { useAtomValue } from "jotai";
4
- import { createReducerAndAtoms } from "@/utils/createReducer";
5
- import type { Variable, VariableName, Variables } from "./types";
3
+ import type { CellAnalysis } from "@marimo-team/client/protocol";
4
+ import { atom, useAtomValue } from "jotai";
5
+ import type { CellId } from "../cells/ids";
6
+ import {
7
+ activeNotebookReplicaAtom,
8
+ confirmedDocumentAtom,
9
+ notebookAnalysisAtom,
10
+ } from "../session/active-notebook";
11
+ import { Objects } from "@/utils/objects";
12
+ import type { VariableName, Variables } from "./types";
6
13
 
7
- function initialState(): Variables {
8
- return {};
9
- }
14
+ /** Null until the host has analyzed a revision of this notebook. */
15
+ const declaredVariablesAtom = atom((get): Variables | null => {
16
+ const analysis = get(notebookAnalysisAtom);
17
+ if (analysis === null) {
18
+ return null;
19
+ }
10
20
 
11
- const {
12
- reducer,
13
- createActions,
14
- valueAtom: variablesAtom,
15
- useActions,
16
- } = createReducerAndAtoms(initialState, {
17
- setVariables: (state, variables: Variable[]) => {
18
- // start with empty state, but keep the old state's metadata
19
- const oldVariables = { ...state };
20
- const newVariables: Variables = {};
21
- for (const variable of variables) {
22
- newVariables[variable.name] = {
23
- ...oldVariables[variable.name],
24
- ...variable,
25
- };
21
+ const declarations: Variables = Object.create(null);
22
+ const cells = Objects.entries<CellId, CellAnalysis>(analysis.cells);
23
+ for (const [cellId, cell] of cells) {
24
+ for (const name of cell.defs as VariableName[]) {
25
+ const variable = (declarations[name] ??= {
26
+ name,
27
+ declaredBy: [],
28
+ usedBy: [],
29
+ });
30
+ variable.declaredBy.push(cellId);
26
31
  }
27
- return newVariables;
28
- },
29
- addVariables: (state, variables: Variable[]) => {
30
- const newVariables = { ...state };
31
- for (const variable of variables) {
32
- newVariables[variable.name] = {
33
- ...newVariables[variable.name],
34
- ...variable,
35
- };
32
+ }
33
+ for (const [cellId, cell] of cells) {
34
+ for (const name of cell.refs as VariableName[]) {
35
+ declarations[name]?.usedBy.push(cellId);
36
36
  }
37
- return newVariables;
38
- },
39
- setMetadata: (
40
- state,
41
- metadata: {
42
- name: VariableName;
43
- value?: string | null;
44
- dataType?: string | null;
45
- }[],
46
- ) => {
47
- const newVariables = { ...state };
48
- for (const { name, value, dataType } of metadata) {
49
- if (!newVariables[name]) {
37
+ }
38
+ return declarations;
39
+ });
40
+
41
+ export const variableBindingsAtom = atom((get) => {
42
+ const replica = get(activeNotebookReplicaAtom);
43
+ return replica && get(replica.shownDocumentAtom)
44
+ ? get(replica.executionsAtom).variables
45
+ : null;
46
+ });
47
+
48
+ const analysisMatchesDocumentAtom = atom((get) => {
49
+ const document = get(confirmedDocumentAtom);
50
+ return (
51
+ document !== null &&
52
+ get(notebookAnalysisAtom)?.document_etag === document.revision.etag
53
+ );
54
+ });
55
+
56
+ const EMPTY: Variables = Object.freeze(Object.create(null));
57
+
58
+ export const variablesAtom = atom((get): Variables => {
59
+ const declarations = get(declaredVariablesAtom);
60
+ const bindings = get(variableBindingsAtom);
61
+ if (!bindings?.size) {
62
+ return declarations ?? EMPTY;
63
+ }
64
+ const current = get(analysisMatchesDocumentAtom);
65
+ const variables: Variables = Object.assign(Object.create(null), declarations);
66
+ for (const [cellId, items] of bindings) {
67
+ for (const item of items.values()) {
68
+ const name = item.name as VariableName;
69
+ const declaration = declarations?.[name];
70
+ const owner = declaration?.declaredBy.includes(cellId)
71
+ ? declaration
72
+ : undefined;
73
+ if (current && declaration && !owner) {
50
74
  continue;
51
75
  }
52
-
53
- newVariables[name] = {
54
- ...newVariables[name],
55
- value,
56
- dataType: dataType,
76
+ variables[name] = {
77
+ ...(owner ?? { name, declaredBy: current ? [] : [cellId], usedBy: [] }),
78
+ dataType: item.type,
79
+ value: item.preview,
57
80
  };
58
81
  }
59
- return newVariables;
60
- },
82
+ }
83
+ return variables;
61
84
  });
62
85
 
63
- /**
64
- * React hook to get the variables state.
65
- */
66
86
  export const useVariables = () => useAtomValue(variablesAtom);
67
-
68
- /**
69
- * React hook to get the variables actions.
70
- */
71
- export function useVariablesActions() {
72
- return useActions();
73
- }
74
-
75
- export { variablesAtom };
76
-
77
- export const exportedForTesting = {
78
- reducer,
79
- createActions,
80
- initialState,
81
- };
@@ -1,9 +1,9 @@
1
1
  /* Copyright 2026 Marimo. All rights reserved. */
2
2
 
3
- import type { components } from "@marimo-team/marimo-api";
3
+ import type { TypedString } from "@/utils/typed";
4
4
  import type { CellId } from "../cells/ids";
5
5
 
6
- export type VariableName = components["schemas"]["VariableName"];
6
+ export type VariableName = TypedString<"VariableName">;
7
7
 
8
8
  export interface Variable {
9
9
  name: VariableName;