@marimo-team/islands 0.26.1-dev105 → 0.26.1-dev112

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 (117) hide show
  1. package/dist/{ConnectedDataExplorerComponent-C6dY5fiI.js → ConnectedDataExplorerComponent-DQaiOY7w.js} +15 -15
  2. package/dist/{ErrorBoundary-Bn664FZa.js → ErrorBoundary-pNKOBKXw.js} +19 -19
  3. package/dist/{abnfDiagram-VCTEODGH-Ba0MYVW8.js → abnfDiagram-VCTEODGH-Df80tEYq.js} +2 -2
  4. package/dist/{any-language-editor-BNe8do3C.js → any-language-editor-BW-gNmbk.js} +2 -2
  5. package/dist/{architectureDiagram-5GKGNRK7-7MqAehef.js → architectureDiagram-5GKGNRK7-DNNMvKkY.js} +1 -1
  6. package/dist/{assertNever-5vhHGKOK.js → assertNever-B9_7z-dW.js} +13 -13
  7. package/dist/{chat-ui-zGgiq5zN.js → chat-ui-C9NZA-bk.js} +49 -49
  8. package/dist/{check-DUIc04aK.js → check-BqF09bSG.js} +1 -1
  9. package/dist/{chunk-IMKFNOWR-CAWA0HGB.js → chunk-IMKFNOWR-pXqnQ_fj.js} +1 -1
  10. package/dist/{chunk-SHT3W25Y-BIwVQjG5.js → chunk-SHT3W25Y-BWrxB3I2.js} +1 -1
  11. package/dist/{chunk-SVP7TREG-Cux251TB.js → chunk-SVP7TREG-CPdQP8_U.js} +1 -1
  12. package/dist/{chunk-TICWLB2K-DJVQ6khO.js → chunk-TICWLB2K-C5MYCwBz.js} +1 -1
  13. package/dist/{circle-question-mark-evCnVIut.js → circle-question-mark-YmLYXyvS.js} +1 -1
  14. package/dist/{classDiagram-ZZMXUADV-Cwve77ev.js → classDiagram-ZZMXUADV-Ba0SRm01.js} +2 -2
  15. package/dist/{classDiagram-v2-VYDZK3BY-BAeHKXmD.js → classDiagram-v2-VYDZK3BY-DSSzL_Dk.js} +2 -2
  16. package/dist/{code-visibility-CMgSFUs7.js → code-visibility-B9s3Hl8z.js} +18 -18
  17. package/dist/{common-DWnR77Qk.js → common-Bn3jx0X6.js} +170 -168
  18. package/dist/{copy-icon-CmNLxT5_.js → copy-icon-zP4__HPI.js} +2 -2
  19. package/dist/{createReducer-m7yAXmDu.js → createReducer-CArOwUaJ.js} +1 -1
  20. package/dist/{cynefinDiagram-5FMLGOSQ-t4eEkPJh.js → cynefinDiagram-5FMLGOSQ-BOtNvA04.js} +1 -1
  21. package/dist/{dagre-GXQ25YYZ-IuZuI28B.js → dagre-GXQ25YYZ-FpCEOTxX.js} +1 -1
  22. package/dist/{data-grid-overlay-editor-zS1h3iMI.js → data-grid-overlay-editor-mxwwRaQy.js} +1 -1
  23. package/dist/{diagram-S7CK7UJ4-D8R5Q_ok.js → diagram-S7CK7UJ4-Cm1HaBuu.js} +1 -1
  24. package/dist/{diagram-UQ7AKVKN-BGuMPsr-.js → diagram-UQ7AKVKN-D1lA7Ggu.js} +1 -1
  25. package/dist/{diagram-VX7I27RA-BkTtpO8P.js → diagram-VX7I27RA-BX3e-Rue.js} +1 -1
  26. package/dist/{diagram-Z3DM3KII-C0__Mxfm.js → diagram-Z3DM3KII-Dgoj7bPf.js} +1 -1
  27. package/dist/{dialog-BvjfalZ9.js → dialog-DfKgafXJ.js} +30 -30
  28. package/dist/{dropdown-menu-D0DeN-aL.js → dropdown-menu-Dge_SmqE.js} +168 -168
  29. package/dist/{ebnfDiagram-PWID7BFC-CSESPZoz.js → ebnfDiagram-PWID7BFC-B0xWiXrz.js} +2 -2
  30. package/dist/{erDiagram-RLTQ6QDP-DsDTtabH.js → erDiagram-RLTQ6QDP-Cm-GO31-.js} +1 -1
  31. package/dist/{error-banner-CXLjTW24.js → error-banner-CfYrJaIb.js} +91 -91
  32. package/dist/{error-entries-DVclFjaE.js → error-entries-1DC4BiYB.js} +661 -656
  33. package/dist/{export-context-CkgZeARR.js → export-context-B1jdxzHF.js} +21 -21
  34. package/dist/{feedback-button-BMGqp8Ff.js → feedback-button-BrzbnRTT.js} +72 -72
  35. package/dist/{flowDiagram-HODETNUW-qxDPYbfV.js → flowDiagram-HODETNUW-CH6xMlW_.js} +2 -2
  36. package/dist/{formats-CcQrzFo8.js → formats-Y52bg800.js} +1 -1
  37. package/dist/{glide-data-editor-Bra6h4KB.js → glide-data-editor-Cnsv3NcI.js} +11 -11
  38. package/dist/{glide-utils-CD8BaFTm.js → glide-utils-BRcuSTCx.js} +2 -2
  39. package/dist/{globals-_bXqC0R8.js → globals-BGqfFPx8.js} +3 -3
  40. package/dist/{html-to-image-Cst4BlIm.js → html-to-image-CsvAOgd3.js} +5073 -5076
  41. package/dist/{infoDiagram-27XIBGKW-B5hq8RM_.js → infoDiagram-27XIBGKW-DbUO63CX.js} +1 -1
  42. package/dist/{ishikawaDiagram-5VMMS53U-DkHc_9ET.js → ishikawaDiagram-5VMMS53U-CfQrrELH.js} +1 -1
  43. package/dist/{kanban-definition-UXKFOSKX-CqkTFXmU.js → kanban-definition-UXKFOSKX-C5SJcu1W.js} +1 -1
  44. package/dist/{loader-CGrYn73j.js → loader-C9-qRO3m.js} +2 -2
  45. package/dist/main.js +6696 -6602
  46. package/dist/{mermaid-pmVHDUQA.js → mermaid-C2alqcd8.js} +34 -34
  47. package/dist/{mindmap-definition-YA3MSWOX-D6cNa__z.js → mindmap-definition-YA3MSWOX-ByVHE0Ax.js} +1 -1
  48. package/dist/{number-overlay-editor-XLUhOVa7.js → number-overlay-editor-DuSCOMTK.js} +1 -1
  49. package/dist/{pegDiagram-XKGWAZYB-CmWJX_s1.js → pegDiagram-XKGWAZYB-DF5FBKZi.js} +2 -2
  50. package/dist/{pencil-CxMgOe04.js → pencil-D7jyZPnP.js} +1 -1
  51. package/dist/{pieDiagram-E7YTZNPT-CAQAxHah.js → pieDiagram-E7YTZNPT-B5n9nBQN.js} +1 -1
  52. package/dist/{process-output-DizFa5IE.js → process-output-CtfJ_Gbp.js} +4 -4
  53. package/dist/{railroadDiagram-O6MQD6OU-jlSsiQg3.js → railroadDiagram-O6MQD6OU-r5t7OYNE.js} +2 -2
  54. package/dist/{requirementDiagram-BXWQKSXE-DkDjfPhn.js → requirementDiagram-BXWQKSXE-D4QtEyZQ.js} +1 -1
  55. package/dist/{reveal-component-llpC324_.js → reveal-component-DzmiQyN9.js} +1008 -1008
  56. package/dist/{select-CEnB18uc.js → select-Buk3aXi1.js} +341 -341
  57. package/dist/{sequenceDiagram-WJ2MYXX4-DLywsGCW.js → sequenceDiagram-WJ2MYXX4-CK3Atn-z.js} +1 -1
  58. package/dist/{spec-Dz-Avv1m.js → spec-BEp9O9dy.js} +4 -4
  59. package/dist/{stateDiagram-D77RDMKH-DUmlKwYU.js → stateDiagram-D77RDMKH-C1SxRI8V.js} +2 -2
  60. package/dist/{stateDiagram-v2-MP3YSRHH-D646KiXs.js → stateDiagram-v2-MP3YSRHH-DK5X6bsr.js} +2 -2
  61. package/dist/{static-state-iw0PrHK4.js → static-state-D-aT9dOr.js} +9 -9
  62. package/dist/style.css +1 -1
  63. package/dist/{swimlanes-42K2YHIH-L7B1GphF.js → swimlanes-42K2YHIH-DdH5TZdu.js} +1 -1
  64. package/dist/{swimlanesDiagram-VR7AAH4N-DEu2wxtC.js → swimlanesDiagram-VR7AAH4N-CWBIvzgR.js} +2 -2
  65. package/dist/{timeline-definition-24CTP7MA-DDPyx1yG.js → timeline-definition-24CTP7MA-DE7-o2zU.js} +1 -1
  66. package/dist/{toast-BTjH6fIf.js → toast-b3k4YxaT.js} +54 -54
  67. package/dist/{tooltip-DyLdBIM4.js → tooltip-D-9pDheN.js} +62 -62
  68. package/dist/{use-restore-focus-DJ_-uSn_.js → use-restore-focus-CCfk-ey2.js} +1 -1
  69. package/dist/{useDateFormatter-HpKD0jEC.js → useDateFormatter-DH0uFwfL.js} +2 -2
  70. package/dist/{useDeepCompareMemoize-CHx-NxMl.js → useDeepCompareMemoize-Dn-ZJVTd.js} +1 -1
  71. package/dist/{useLifecycle-tPpAt-OE.js → useLifecycle-yjK7JsRL.js} +1 -1
  72. package/dist/{vega-component-BzNDFvQf.js → vega-component-BIq0qzhQ.js} +8 -8
  73. package/dist/{vennDiagram-4TSXK5OY-CRwWeb7g.js → vennDiagram-4TSXK5OY-D7yfNz0d.js} +1 -1
  74. package/dist/{wardleyDiagram-VM6X3IG4-DVlG9eoq.js → wardleyDiagram-VM6X3IG4-m5Jcz26Z.js} +1 -1
  75. package/dist/{xychartDiagram-S5SC5T6Z-CM32AISp.js → xychartDiagram-S5SC5T6Z-CA3zV3RW.js} +1 -1
  76. package/package.json +1 -1
  77. package/src/__mocks__/intersection-observer.ts +13 -12
  78. package/src/components/editor/Output.tsx +1 -1
  79. package/src/components/editor/__tests__/cell-renders.test.tsx +344 -2
  80. package/src/components/editor/ai/__tests__/completion-utils.test.ts +12 -20
  81. package/src/components/editor/ai/ai-completion-editor.tsx +391 -289
  82. package/src/components/editor/ai/completion-utils.ts +9 -7
  83. package/src/components/editor/cell/CellDeleteShoulder.tsx +82 -0
  84. package/src/components/editor/cell/DeleteButton.tsx +11 -2
  85. package/src/components/editor/cell/__tests__/CellDeleteShoulder.test.tsx +181 -0
  86. package/src/components/editor/cell/code/cell-editor.tsx +15 -25
  87. package/src/components/editor/chrome/panels/__tests__/logs-panel.test.tsx +26 -2
  88. package/src/components/editor/chrome/panels/logs-panel.tsx +27 -11
  89. package/src/components/editor/chrome/panels/outline/__tests__/outline-keyboard.test.tsx +517 -68
  90. package/src/components/editor/chrome/panels/outline/__tests__/useActiveOutline.test.ts +17 -5
  91. package/src/components/editor/chrome/panels/outline/floating-outline.tsx +29 -59
  92. package/src/components/editor/chrome/panels/outline/useActiveOutline.tsx +333 -133
  93. package/src/components/editor/chrome/panels/outline-panel.tsx +5 -19
  94. package/src/components/editor/notebook-cell.tsx +250 -274
  95. package/src/core/ai/state.ts +6 -0
  96. package/src/core/cells/__tests__/cells.test.ts +34 -20
  97. package/src/core/cells/__tests__/layout.test.ts +1 -1
  98. package/src/core/cells/__tests__/notebook-outline.test.ts +31 -3
  99. package/src/core/cells/cell-log-chunks.ts +31 -0
  100. package/src/core/cells/cells.ts +31 -20
  101. package/src/core/cells/outline.ts +8 -8
  102. package/src/core/codemirror/language/extension.ts +6 -3
  103. package/src/core/codemirror/language/panel/panel.test.tsx +144 -0
  104. package/src/core/codemirror/language/panel/panel.tsx +9 -6
  105. package/src/core/codemirror/lsp/__tests__/log-messages.test.ts +1 -1
  106. package/src/core/codemirror/lsp/__tests__/transports.test.ts +1 -1
  107. package/src/core/codemirror/react-dom/createPanel.tsx +15 -15
  108. package/src/core/dom/__tests__/outline.test.ts +29 -170
  109. package/src/core/dom/outline.ts +21 -61
  110. package/src/core/executions/atoms.ts +12 -4
  111. package/src/core/islands/__tests__/bridge.test.ts +2 -5
  112. package/src/core/islands/components/output-wrapper.tsx +7 -2
  113. package/src/core/session/__tests__/useNotebookSession.hook.test.tsx +10 -1
  114. package/src/css/common.css +11 -0
  115. package/src/hooks/useFinePointer.ts +30 -0
  116. package/src/plugins/layout/OutlinePlugin.tsx +5 -17
  117. package/src/stories/log-viewer.stories.tsx +48 -44
@@ -1,5 +1,7 @@
1
1
  /* Copyright 2026 Marimo. All rights reserved. */
2
- import { act, render } from "@testing-library/react";
2
+ import { Chat, useChat } from "@ai-sdk/react";
3
+ import { EditorView } from "@codemirror/view";
4
+ import { act, fireEvent, render, screen, within } from "@testing-library/react";
3
5
  import { Profiler } from "react";
4
6
  import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
5
7
  import { DocumentWrapper } from "@/__mocks__/document";
@@ -9,18 +11,26 @@ import { createRenderTracker } from "@/__tests__/render-tracker";
9
11
  import { cell } from "@/core/notebook/document/__tests__/fixtures";
10
12
  import { cellId } from "@/__tests__/branded";
11
13
  import { TooltipProvider } from "@/components/ui/tooltip";
14
+ import { stagedAICellsAtom } from "@/core/ai/staged-cells";
15
+ import { aiCompletionCellAtom } from "@/core/ai/state";
12
16
  import { notebookAtom } from "@/core/cells/cells";
17
+ import { HTMLCellId } from "@/core/cells/ids";
18
+ import * as notebookCode from "@/core/codemirror/copilot/getCodes";
13
19
  import { editorMountScheduler } from "@/core/codemirror/editor-mount-scheduler";
14
20
  import { setupNotebook } from "@/core/cells/__tests__/harness";
15
21
  import { defaultUserConfig } from "@/core/config/config-schema";
22
+ import { isPlatformMac } from "@/core/hotkeys/shortcuts";
16
23
  import { requestClientAtom } from "@/core/network/requests";
17
24
  import { invariant } from "@/utils/invariant";
18
25
  import { Cell } from "../notebook-cell";
19
26
 
27
+ vi.mock("@ai-sdk/react", { spy: true });
28
+
20
29
  const stops: Array<() => void> = [];
21
30
  beforeEach(() => vi.useFakeTimers());
22
31
  afterEach(() => {
23
32
  act(() => stops.splice(0).forEach((stop) => stop()));
33
+ vi.restoreAllMocks();
24
34
  vi.useRealTimers();
25
35
  });
26
36
 
@@ -63,10 +73,97 @@ async function setup(count: number) {
63
73
  });
64
74
  expect(Object.keys(renders.counts())).toEqual(ids);
65
75
  renders.reset();
66
- return { ...notebook, replica, renders };
76
+ return { ...notebook, replica, renders, container: mounted.container };
77
+ }
78
+
79
+ function editor(store: Awaited<ReturnType<typeof setup>>["store"], id: string) {
80
+ return store.get(notebookAtom).cellHandles[cellId(id)].current?.editorView;
67
81
  }
68
82
 
83
+ function prompt() {
84
+ const editor = document.querySelector<HTMLElement>(
85
+ ".mo-ai-prompt .cm-editor",
86
+ );
87
+ invariant(editor, "The AI prompt must be mounted");
88
+ const view = EditorView.findFromDOM(editor);
89
+ invariant(view, "The AI prompt must have an editor view");
90
+ return view;
91
+ }
92
+
93
+ const streamChunk = (value: object) => `data: ${JSON.stringify(value)}\n\n`;
94
+ const completionChunk = (code: string) =>
95
+ streamChunk({ type: "data-cell-completion", data: { code } });
96
+ const finishStream = `${streamChunk({ type: "finish", finishReason: "stop" })}data: [DONE]\n\n`;
97
+ const streamHeaders = { "Content-Type": "text/event-stream" };
98
+
99
+ function completionResponse(code: string) {
100
+ return new Response(completionChunk(code) + finishStream, {
101
+ headers: streamHeaders,
102
+ });
103
+ }
104
+
105
+ it("shares the tooltip hover delay across cells", async () => {
106
+ await setup(2);
107
+ const [first, second] = screen
108
+ .getAllByTestId("cell-tray")
109
+ .map((tray) => within(tray).getByRole("button", { name: "Delete cell" }));
110
+
111
+ fireEvent.pointerMove(first, { pointerType: "mouse" });
112
+ expect(first).toHaveAttribute("data-state", "closed");
113
+ await act(async () => vi.advanceTimersByTimeAsync(400));
114
+ expect(first).toHaveAttribute("data-state", "delayed-open");
115
+
116
+ fireEvent.pointerLeave(first, { pointerType: "mouse" });
117
+ fireEvent.pointerMove(second, { pointerType: "mouse" });
118
+ expect(second).toHaveAttribute("data-state", "instant-open");
119
+ });
120
+
69
121
  describe.each([2, 25])("cell render isolation with %i cells", (count) => {
122
+ it("opens, switches, and closes AI completion without work in unrelated cells", async () => {
123
+ const { store, renders } = await setup(count);
124
+ const a = cellId("c1");
125
+ const b = cellId("c2");
126
+ expect(editor(store, a)).toBeNull();
127
+ expect(editor(store, b)).toBeNull();
128
+
129
+ await act(async () => store.set(aiCompletionCellAtom, { cellId: a }));
130
+ expect(Object.keys(renders.counts())).toEqual([a]);
131
+ const viewA = editor(store, a);
132
+ invariant(viewA, "Opening AI completion must promote a dormant editor");
133
+ const parent = viewA.dom.parentElement;
134
+ const initialPrompt = "Rename this variable";
135
+
136
+ renders.reset();
137
+ await act(async () =>
138
+ store.set(aiCompletionCellAtom, { cellId: b, initialPrompt }),
139
+ );
140
+ expect(Object.keys(renders.counts()).toSorted()).toEqual([a, b]);
141
+ expect(editor(store, a)).toBe(viewA);
142
+ expect(viewA.dom.parentElement).toBe(parent);
143
+ const viewB = editor(store, b);
144
+ invariant(viewB, "Switching AI completion must promote the new editor");
145
+ await act(async () => vi.advanceTimersByTimeAsync(100));
146
+ const promptView = prompt();
147
+ expect(promptView.hasFocus).toBe(true);
148
+ expect(
149
+ promptView.state.sliceDoc(
150
+ promptView.state.selection.main.from,
151
+ promptView.state.selection.main.to,
152
+ ),
153
+ ).toBe(initialPrompt);
154
+ expect(Object.keys(renders.counts()).toSorted()).toEqual([a, b]);
155
+
156
+ renders.reset();
157
+ fireEvent.click(
158
+ screen.getByRole("button", { name: "Discard AI completion" }),
159
+ );
160
+ expect(Object.keys(renders.counts())).toEqual([b]);
161
+ expect(store.get(aiCompletionCellAtom)).toBeNull();
162
+ expect(viewB.hasFocus).toBe(true);
163
+ expect(useChat).not.toHaveBeenCalled();
164
+ expect(Chat).not.toHaveBeenCalled();
165
+ });
166
+
70
167
  it("does not re-render other cells on a keystroke", async () => {
71
168
  const { store, model, renders } = await setup(count);
72
169
  await act(async () => {
@@ -114,3 +211,248 @@ describe.each([2, 25])("cell render isolation with %i cells", (count) => {
114
211
  }
115
212
  });
116
213
  });
214
+
215
+ it("preserves a streaming proposal across target switches and applies changes to the same editor", async () => {
216
+ const { store, container } = await setup(2);
217
+ const a = cellId("c1");
218
+ const b = cellId("c2");
219
+ const first = new TransformStream<Uint8Array>();
220
+ const writer = first.writable.getWriter();
221
+ const encoder = new TextEncoder();
222
+ const fetch = vi
223
+ .spyOn(globalThis, "fetch")
224
+ .mockResolvedValueOnce(
225
+ new Response(first.readable, { headers: streamHeaders }),
226
+ )
227
+ .mockResolvedValueOnce(completionResponse("x = 100"));
228
+ const suggestion = () =>
229
+ container.querySelector(".cm-mergeView .cm-merge-b .cm-content");
230
+
231
+ await act(async () => {
232
+ store.set(aiCompletionCellAtom, {
233
+ cellId: a,
234
+ initialPrompt: "Fix",
235
+ triggerImmediately: true,
236
+ });
237
+ });
238
+ await act(async () => vi.advanceTimersByTimeAsync(100));
239
+ expect(fetch).toHaveBeenCalledTimes(1);
240
+ expect(fetch.mock.calls[0][1]?.body).toEqual(
241
+ expect.stringContaining('"code":"x = 1"'),
242
+ );
243
+ expect(Chat).toHaveBeenCalledTimes(1);
244
+
245
+ const view = editor(store, a);
246
+ invariant(view, "AI completion must promote the editor");
247
+ act(() => view.dispatch({ selection: { anchor: 0, head: 1 } }));
248
+ const parent = view.dom.parentElement;
249
+ const selection = view.state.selection;
250
+ await act(async () => writer.write(encoder.encode(completionChunk("x = 9"))));
251
+ expect(suggestion()).toHaveTextContent("x = 9");
252
+ expect(view.dom).not.toBeVisible();
253
+ expect(view.dom.parentElement).toBe(parent);
254
+
255
+ await act(async () => store.set(aiCompletionCellAtom, { cellId: b }));
256
+ expect(suggestion()).toBeNull();
257
+ expect(view.dom).toBeVisible();
258
+ await act(async () => {
259
+ await writer.write(
260
+ encoder.encode(completionChunk("x = 99") + finishStream),
261
+ );
262
+ await writer.close();
263
+ });
264
+ expect(suggestion()).toBeNull();
265
+ await act(async () => store.set(aiCompletionCellAtom, { cellId: a }));
266
+ expect(suggestion()).toHaveTextContent("x = 99");
267
+ fireEvent.click(screen.getByRole("button", { name: /Revert change/ }));
268
+ expect(suggestion()).toBeNull();
269
+ expect(view.state.doc.toString()).toBe("x = 1");
270
+ expect(view.state.selection.eq(selection)).toBe(true);
271
+ expect(prompt().hasFocus).toBe(true);
272
+
273
+ const input = prompt();
274
+ act(() => input.dispatch({ changes: { from: 0, insert: "Try again" } }));
275
+ await act(async () => fireEvent.keyDown(input.contentDOM, { key: "Enter" }));
276
+ expect(suggestion()).toHaveTextContent("x = 100");
277
+ expect(useChat).not.toHaveBeenCalled();
278
+ expect(Chat).toHaveBeenCalledTimes(2);
279
+ fireEvent.click(screen.getByRole("button", { name: /^Keep change/ }));
280
+ expect(store.get(aiCompletionCellAtom)).toBeNull();
281
+ expect(view.state.doc.toString()).toBe("x = 100");
282
+ expect(view.dom.parentElement).toBe(parent);
283
+ expect(view.hasFocus).toBe(true);
284
+ });
285
+
286
+ it("shows staged edits without allocating a chat", async () => {
287
+ const { store, container } = await setup(2);
288
+ const a = cellId("c1");
289
+ act(() => editorMountScheduler.promote(a));
290
+ const view = editor(store, a);
291
+ invariant(view, "The cell editor must be mounted");
292
+ const parent = view.dom.parentElement;
293
+
294
+ act(() =>
295
+ store.set(
296
+ stagedAICellsAtom,
297
+ new Map([[a, { type: "update_cell", previousCode: "" }]]),
298
+ ),
299
+ );
300
+ const diff = container.querySelector(".cm-mergeView");
301
+ expect(diff).toBeVisible();
302
+ expect(diff?.querySelector(".cm-merge-a .cm-content")).toHaveAttribute(
303
+ "contenteditable",
304
+ "false",
305
+ );
306
+ expect(view.dom).not.toBeVisible();
307
+
308
+ await act(async () =>
309
+ store.set(aiCompletionCellAtom, { cellId: cellId("c2") }),
310
+ );
311
+ expect(container.querySelector(".cm-mergeView")).toBe(diff);
312
+ await act(async () => store.set(aiCompletionCellAtom, { cellId: a }));
313
+ fireEvent.click(
314
+ screen.getByRole("button", { name: "Discard AI completion" }),
315
+ );
316
+ expect(document.getElementById(HTMLCellId.create(a))).toHaveFocus();
317
+ act(() => store.set(stagedAICellsAtom, new Map()));
318
+ expect(view.dom).toBeVisible();
319
+ expect(view.dom.parentElement).toBe(parent);
320
+ expect(useChat).not.toHaveBeenCalled();
321
+ expect(Chat).not.toHaveBeenCalled();
322
+ });
323
+
324
+ it("aborts a stopped request and can submit again", async () => {
325
+ const { store } = await setup(2);
326
+ const getCodes = vi.spyOn(notebookCode, "getCodes").mockReturnValue("y = 2");
327
+ const fetch = vi
328
+ .spyOn(globalThis, "fetch")
329
+ .mockImplementationOnce((_url, options) => {
330
+ const signal = options?.signal;
331
+ invariant(signal, "A completion request must be abortable");
332
+ return new Promise((_resolve, reject) => {
333
+ signal.addEventListener("abort", () => reject(signal.reason), {
334
+ once: true,
335
+ });
336
+ });
337
+ })
338
+ .mockResolvedValueOnce(completionResponse("x = 42"));
339
+ await act(async () =>
340
+ store.set(aiCompletionCellAtom, {
341
+ cellId: cellId("c1"),
342
+ initialPrompt: "Update the value",
343
+ }),
344
+ );
345
+
346
+ const submit = () => screen.getByRole("button", { name: "Submit" });
347
+ const allCode = screen.getByRole("checkbox", { name: "All code" });
348
+ expect(allCode).toBeChecked();
349
+ fireEvent.click(allCode);
350
+ await act(async () => fireEvent.click(submit()));
351
+ expect(getCodes).not.toHaveBeenCalled();
352
+ expect(fetch.mock.calls[0][1]?.body).toEqual(
353
+ expect.stringContaining('"includeOtherCode":""'),
354
+ );
355
+ const signal = fetch.mock.calls[0][1]?.signal;
356
+ expect(signal?.aborted).toBe(false);
357
+ fireEvent.click(screen.getByRole("button", { name: "Stop" }));
358
+ expect(signal?.aborted).toBe(true);
359
+ fireEvent.click(allCode);
360
+ await act(async () => fireEvent.click(submit()));
361
+ expect(fetch).toHaveBeenCalledTimes(2);
362
+ expect(getCodes).toHaveBeenCalledExactlyOnceWith("x = 1");
363
+ expect(fetch.mock.calls[1][1]?.body).toEqual(
364
+ expect.stringContaining('"includeOtherCode":"y = 2"'),
365
+ );
366
+ expect(screen.getByRole("button", { name: /^Keep change/ })).toBeEnabled();
367
+ });
368
+
369
+ it("preserves focus and selection when the user types and leaves the prompt before autofocus", async () => {
370
+ const { store } = await setup(1);
371
+ await act(async () =>
372
+ store.set(aiCompletionCellAtom, { cellId: cellId("c1") }),
373
+ );
374
+ const input = prompt();
375
+ act(() => {
376
+ input.focus();
377
+ input.dispatch({
378
+ changes: { from: 0, insert: "Fix" },
379
+ selection: { anchor: 3 },
380
+ });
381
+ });
382
+ const selection = input.state.selection;
383
+ const submit = screen.getByRole("button", { name: "Submit" });
384
+ act(() => submit.focus());
385
+ await act(async () => vi.advanceTimersByTimeAsync(100));
386
+ expect(submit).toHaveFocus();
387
+ expect(input.state.selection.eq(selection)).toBe(true);
388
+ });
389
+
390
+ it("resets a draft when the same cell receives a fresh prompt", async () => {
391
+ const { store } = await setup(1);
392
+ const target = { cellId: cellId("c1") };
393
+ await act(async () => store.set(aiCompletionCellAtom, target));
394
+ const input = prompt();
395
+ const submit = screen.getByRole("button", { name: "Submit" });
396
+ act(() => input.dispatch({ changes: { from: 0, insert: "Fix this line" } }));
397
+ expect(submit).toBeEnabled();
398
+
399
+ await act(async () => store.set(aiCompletionCellAtom, { ...target }));
400
+ expect(prompt()).toBe(input);
401
+ expect(submit).toBeDisabled();
402
+ });
403
+
404
+ it("focuses the visible prompt after a banner rejection", async () => {
405
+ const { store } = await setup(1);
406
+ vi.spyOn(globalThis, "fetch").mockResolvedValueOnce(
407
+ completionResponse("x = 2"),
408
+ );
409
+ await act(async () =>
410
+ store.set(aiCompletionCellAtom, {
411
+ cellId: cellId("c1"),
412
+ initialPrompt: "Fix",
413
+ triggerImmediately: true,
414
+ }),
415
+ );
416
+ await act(async () => vi.advanceTimersByTimeAsync(100));
417
+ fireEvent.click(screen.getByRole("switch"));
418
+ await act(async () => vi.advanceTimersByTimeAsync(100));
419
+ const reject = screen.getByRole("button", { name: "Revert change" });
420
+ act(() => reject.focus());
421
+ fireEvent.click(reject);
422
+ expect(prompt().hasFocus).toBe(true);
423
+ });
424
+
425
+ it.each([
426
+ { proposal: "", cursor: 0 },
427
+ { proposal: "x = 1", cursor: 2 },
428
+ ])(
429
+ "can keep a proposal of '$proposal' without disturbing the cursor",
430
+ async ({ proposal, cursor }) => {
431
+ const { store, container } = await setup(1);
432
+ const a = cellId("c1");
433
+ vi.spyOn(globalThis, "fetch").mockResolvedValueOnce(
434
+ completionResponse(proposal),
435
+ );
436
+ await act(async () =>
437
+ store.set(aiCompletionCellAtom, {
438
+ cellId: a,
439
+ initialPrompt: "Edit this cell",
440
+ }),
441
+ );
442
+ const view = editor(store, a);
443
+ invariant(view, "Opening the prompt must promote the editor");
444
+ act(() => view.dispatch({ selection: { anchor: 2 } }));
445
+ await act(async () =>
446
+ fireEvent.click(screen.getByRole("button", { name: "Submit" })),
447
+ );
448
+ expect(container.querySelector(".cm-mergeView")).toBeVisible();
449
+ expect(screen.getByRole("button", { name: /^Keep change/ })).toBeEnabled();
450
+ fireEvent.keyDown(prompt().contentDOM, {
451
+ key: "Enter",
452
+ [isPlatformMac() ? "metaKey" : "ctrlKey"]: true,
453
+ });
454
+ expect(store.get(aiCompletionCellAtom)).toBeNull();
455
+ expect(view.state.doc.toString()).toBe(proposal);
456
+ expect(view.state.selection.main.head).toBe(cursor);
457
+ },
458
+ );
@@ -1,18 +1,9 @@
1
1
  /* Copyright 2026 Marimo. All rights reserved. */
2
2
  import type { Variable } from "@marimo-team/client/protocol";
3
3
  import type { FileUIPart, UIMessage } from "ai";
4
- import {
5
- afterEach,
6
- beforeEach,
7
- describe,
8
- expect,
9
- it,
10
- type Mock,
11
- vi,
12
- } from "vitest";
4
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
13
5
  import { MockExecutions } from "@/__mocks__/executions";
14
6
  import * as aiContext from "@/core/ai/context/context";
15
- import { getCodes } from "@/core/codemirror/copilot/getCodes";
16
7
  import { dataSourceConnectionsAtom } from "@/core/datasets/data-source-connections";
17
8
  import { DUCKDB_ENGINE } from "@/core/datasets/engines";
18
9
  import { datasetsAtom } from "@/core/datasets/state";
@@ -43,6 +34,8 @@ function setBindings(bindings: Pick<Variable, "name" | "type" | "preview">[]) {
43
34
  }
44
35
 
45
36
  describe("getAICompletionBody", () => {
37
+ const includeOtherCode = "// Some other code";
38
+
46
39
  beforeEach(() => {
47
40
  // Reset the Jotai store before each test
48
41
  store.set(datasetsAtom, {
@@ -53,7 +46,6 @@ describe("getAICompletionBody", () => {
53
46
  connectionsMap: new Map(),
54
47
  });
55
48
  store.set(activeNotebookReplicaAtom, null);
56
- (getCodes as Mock).mockReturnValue("// Some other code");
57
49
  });
58
50
 
59
51
  it("should return the correct completion body with mentioned datasets", () => {
@@ -77,7 +69,7 @@ describe("getAICompletionBody", () => {
77
69
  store.set(datasetsAtom, { tables: testDatasets } as DatasetsState);
78
70
 
79
71
  const input = "Use @data://dataset1 and @data://dataset2 for analysis";
80
- const result = getAICompletionBody({ input });
72
+ const result = getAICompletionBody({ input, includeOtherCode });
81
73
 
82
74
  expect(result).toMatchInlineSnapshot(`
83
75
  {
@@ -99,7 +91,7 @@ describe("getAICompletionBody", () => {
99
91
 
100
92
  it("should handle input with no mentioned datasets", () => {
101
93
  const input = "Perform some analysis without mentioning @data://datasets";
102
- const result = getAICompletionBody({ input });
94
+ const result = getAICompletionBody({ input, includeOtherCode });
103
95
 
104
96
  expect(result).toMatchInlineSnapshot(`
105
97
  {
@@ -128,7 +120,7 @@ describe("getAICompletionBody", () => {
128
120
 
129
121
  const input =
130
122
  "Use @data://existingDataset and @data://nonExistentDataset for analysis";
131
- const result = getAICompletionBody({ input });
123
+ const result = getAICompletionBody({ input, includeOtherCode });
132
124
 
133
125
  expect(result).toMatchInlineSnapshot(`
134
126
  {
@@ -163,7 +155,7 @@ describe("getAICompletionBody", () => {
163
155
 
164
156
  const input =
165
157
  "Use @data://dataset.with.dots and @data://regular_dataset for analysis";
166
- const result = getAICompletionBody({ input });
158
+ const result = getAICompletionBody({ input, includeOtherCode });
167
159
 
168
160
  expect(result).toMatchInlineSnapshot(`
169
161
  {
@@ -215,7 +207,7 @@ describe("getAICompletionBody", () => {
215
207
  });
216
208
 
217
209
  const input = "Use @data://table1 for analysis";
218
- const result = getAICompletionBody({ input });
210
+ const result = getAICompletionBody({ input, includeOtherCode });
219
211
 
220
212
  expect(result).toMatchInlineSnapshot(`
221
213
  {
@@ -238,7 +230,7 @@ describe("getAICompletionBody", () => {
238
230
  ]);
239
231
 
240
232
  const input = "Use @variable://var1 and @variable://var2 for analysis";
241
- const result = getAICompletionBody({ input });
233
+ const result = getAICompletionBody({ input, includeOtherCode });
242
234
 
243
235
  expect(result).toMatchInlineSnapshot(`
244
236
  {
@@ -270,7 +262,7 @@ describe("getAICompletionBody", () => {
270
262
  setBindings([{ name: "var1", type: "string", preview: "string value" }]);
271
263
 
272
264
  const input = "Use @data://dataset1 and @variable://var1 for analysis";
273
- const result = getAICompletionBody({ input });
265
+ const result = getAICompletionBody({ input, includeOtherCode });
274
266
 
275
267
  expect(result).toMatchInlineSnapshot(`
276
268
  {
@@ -296,7 +288,7 @@ describe("getAICompletionBody", () => {
296
288
 
297
289
  const input =
298
290
  "Use @variable://existingVar and @variable://nonExistentVar for analysis";
299
- const result = getAICompletionBody({ input });
291
+ const result = getAICompletionBody({ input, includeOtherCode });
300
292
 
301
293
  expect(result).toMatchInlineSnapshot(`
302
294
  {
@@ -325,7 +317,7 @@ describe("getAICompletionBody", () => {
325
317
  ]);
326
318
 
327
319
  const input = "Use @data://conflict for analysis";
328
- const result = getAICompletionBody({ input });
320
+ const result = getAICompletionBody({ input, includeOtherCode });
329
321
 
330
322
  expect(result).toMatchInlineSnapshot(`
331
323
  {