@marimo-team/islands 0.26.1-dev108 → 0.26.1-dev118

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 (65) hide show
  1. package/dist/{ErrorBoundary-BW4TciqU.js → ErrorBoundary-Gr2Kt5kj.js} +1 -1
  2. package/dist/{chat-ui-Be9X-W22.js → chat-ui-CMKYvKUz.js} +3 -3
  3. package/dist/{code-visibility-BKmktPMd.js → code-visibility-BFFe0rT7.js} +2 -2
  4. package/dist/{common-CSJAjJGa.js → common-7eNIhSN-.js} +4766 -4747
  5. package/dist/{data-grid-overlay-editor-DTibdR4H.js → data-grid-overlay-editor-B37-1-8n.js} +1 -1
  6. package/dist/{error-entries-23Z_1oDM.js → error-entries-B4LgfizR.js} +772 -751
  7. package/dist/{feedback-button-CPu5SV3b.js → feedback-button-CpQcgVuz.js} +3 -3
  8. package/dist/{formats-Y52bg800.js → formats-CeuXJ_1f.js} +32 -25
  9. package/dist/{glide-data-editor-CC9_NDNi.js → glide-data-editor-BxTlDHV5.js} +3 -3
  10. package/dist/{globals-BFlYTNoR.js → globals-ljOLdTJr.js} +1 -1
  11. package/dist/{html-to-image-Cw7o1IbE.js → html-to-image-CIkwg7mv.js} +1 -1
  12. package/dist/main.js +69 -66
  13. package/dist/{number-overlay-editor-qDcRKPE0.js → number-overlay-editor-DGKTstav.js} +1 -1
  14. package/dist/{process-output-DdBM0lmd.js → process-output-PS9YSLNu.js} +2 -2
  15. package/dist/{reveal-component-BE1xhtNc.js → reveal-component-BLJMkx2N.js} +2 -2
  16. package/dist/{useDeepCompareMemoize-Dn-ZJVTd.js → semaphore-8KhQouXt.js} +5 -15
  17. package/dist/style.css +1 -1
  18. package/dist/{vega-component-BIq0qzhQ.js → vega-component-CoJiBCaS.js} +11 -11
  19. package/package.json +1 -1
  20. package/src/__mocks__/executions.ts +1 -1
  21. package/src/__mocks__/intersection-observer.ts +5 -5
  22. package/src/components/editor/Output.tsx +3 -21
  23. package/src/components/editor/__tests__/cell-renders.test.tsx +327 -1
  24. package/src/components/editor/actions/__tests__/pair-with-agent-modal.test.tsx +27 -0
  25. package/src/components/editor/actions/pair-with-agent-modal.tsx +8 -1
  26. package/src/components/editor/ai/__tests__/completion-utils.test.ts +12 -20
  27. package/src/components/editor/ai/ai-completion-editor.tsx +391 -289
  28. package/src/components/editor/ai/completion-utils.ts +9 -7
  29. package/src/components/editor/cell/CellDeleteShoulder.tsx +82 -0
  30. package/src/components/editor/cell/DeleteButton.tsx +11 -2
  31. package/src/components/editor/cell/__tests__/CellDeleteShoulder.test.tsx +181 -0
  32. package/src/components/editor/cell/code/cell-editor.tsx +15 -25
  33. package/src/components/editor/chrome/panels/__tests__/logs-panel.test.tsx +26 -2
  34. package/src/components/editor/chrome/panels/logs-panel.tsx +27 -11
  35. package/src/components/editor/notebook-cell.tsx +20 -40
  36. package/src/components/editor/output/VegaOutput.tsx +35 -0
  37. package/src/components/find-replace/find-replace.tsx +1 -7
  38. package/src/core/ai/state.ts +6 -0
  39. package/src/core/cells/__tests__/cell-errors.test.tsx +179 -0
  40. package/src/core/cells/__tests__/cells.test.ts +34 -20
  41. package/src/core/cells/cell-log-chunks.ts +31 -0
  42. package/src/core/cells/cells.ts +34 -33
  43. package/src/core/codemirror/find-replace/__tests__/navigate.test.ts +18 -15
  44. package/src/core/codemirror/find-replace/__tests__/search-highlight.test.ts +90 -2
  45. package/src/core/codemirror/find-replace/__tests__/unmounted-cells.test.ts +44 -10
  46. package/src/core/codemirror/find-replace/navigate.ts +4 -1
  47. package/src/core/codemirror/find-replace/search-highlight.ts +54 -58
  48. package/src/core/codemirror/lsp/__tests__/log-messages.test.ts +1 -1
  49. package/src/core/codemirror/lsp/__tests__/transports.test.ts +1 -1
  50. package/src/core/executions/__tests__/atoms.test.ts +0 -2
  51. package/src/core/executions/__tests__/output-lifecycle.test.ts +16 -0
  52. package/src/core/executions/atoms.ts +33 -36
  53. package/src/core/export/__tests__/output-snapshot.test.tsx +240 -0
  54. package/src/core/export/__tests__/output-subscription.test.tsx +79 -0
  55. package/src/core/export/hooks.ts +29 -13
  56. package/src/core/islands/__tests__/bridge.test.ts +2 -5
  57. package/src/core/notebook/replica/frame.ts +8 -2
  58. package/src/core/notebook/replica/index.ts +5 -1
  59. package/src/core/notebook/replica/once-per-frame.ts +4 -3
  60. package/src/core/notebook/replica/resources/executions.ts +16 -1
  61. package/src/core/session/__tests__/useNotebookSession.hook.test.tsx +10 -1
  62. package/src/css/common.css +11 -0
  63. package/src/hooks/useFinePointer.ts +30 -0
  64. package/src/stories/log-viewer.stories.tsx +48 -44
  65. package/src/utils/shared-intersection-observer.ts +2 -1
@@ -11,10 +11,10 @@ import { t as f } from "./debounce-DrhhziJv.js";
11
11
  import { t as p } from "./objects-DCmMvZtn.js";
12
12
  import { t as ee } from "./useEvent-BoN7U38T.js";
13
13
  import { a as m, t as te } from "./arrays-DoQ-AILx.js";
14
- import { a as h, i as ne, n as re, t as ie } from "./formats-Y52bg800.js";
14
+ import { a as ne, n as re, o as h, r as ie, t as ae } from "./formats-CeuXJ_1f.js";
15
15
  import { a as g } from "./export-context-B1jdxzHF.js";
16
- import { t as ae } from "./useAsyncData-P5-Oovhq.js";
17
- import { n as _, t as oe } from "./useDeepCompareMemoize-Dn-ZJVTd.js";
16
+ import { t as oe } from "./useAsyncData-P5-Oovhq.js";
17
+ import { t as _ } from "./semaphore-8KhQouXt.js";
18
18
  import { o as se, r as ce, t as le } from "./loader-C9-qRO3m.js";
19
19
  import { W as ue, n as v } from "./vega-loader.browser-Co9gYE8Z.js";
20
20
  import { t as de } from "./react-vega-CGgQEf0O.js";
@@ -505,11 +505,11 @@ async function W(e) {
505
505
  //#endregion
506
506
  //#region src/plugins/impl/vega/vega-component.tsx
507
507
  var G = l();
508
- v("arrow", ie);
508
+ v("arrow", ae);
509
509
  var K = (e) => {
510
510
  let t = (0, pe.c)(12), { value: n, setValue: r, chartSelection: i, fieldSelection: a, spec: o, embedOptions: s } = e, c, l;
511
511
  t[0] === o ? (c = t[1], l = t[2]) : (c = async () => W(o), l = [o], t[0] = o, t[1] = c, t[2] = l);
512
- let { data: u, error: f } = ae(c, l);
512
+ let { data: u, error: f } = oe(c, l);
513
513
  if (f) {
514
514
  let e;
515
515
  return t[3] === f ? e = t[4] : (e = /* @__PURE__ */ (0, G.jsx)(d, { error: f }), t[3] = f, t[4] = e), e;
@@ -525,7 +525,7 @@ var K = (e) => {
525
525
  embedOptions: s
526
526
  }), t[5] = i, t[6] = s, t[7] = a, t[8] = u, t[9] = r, t[10] = n, t[11] = p) : p = t[11], p;
527
527
  }, q = (e) => {
528
- let a = (0, pe.c)(53), { value: o, setValue: l, chartSelection: d, fieldSelection: m, spec: te, embedOptions: h } = e, { theme: ie } = u(), g = (0, y.useRef)(null), ae = (0, y.useRef)(void 0), [_, ce] = (0, y.useState)(), v;
528
+ let a = (0, pe.c)(53), { value: o, setValue: l, chartSelection: d, fieldSelection: m, spec: te, embedOptions: h } = e, { theme: ae } = u(), g = (0, y.useRef)(null), oe = (0, y.useRef)(void 0), [_, ce] = (0, y.useState)(), v;
529
529
  bb0: {
530
530
  if (h && "actions" in h) {
531
531
  v = h.actions;
@@ -537,7 +537,7 @@ var K = (e) => {
537
537
  compiled: !1
538
538
  }, a[0] = e) : e = a[0], v = e;
539
539
  }
540
- let b = v, x = oe(te), S;
540
+ let b = v, x = re(te), S;
541
541
  a[1] !== d || a[2] !== m || a[3] !== x ? (S = ge(me(x), {
542
542
  chartSelection: d,
543
543
  fieldSelection: m
@@ -559,7 +559,7 @@ var K = (e) => {
559
559
  let r = p.mapValues(n, ve);
560
560
  r = p.mapValues(r, _e), he({ [e]: r });
561
561
  }, 100), a[12] = he, a[13] = j);
562
- let M = j, N = oe(k), P;
562
+ let M = j, N = re(k), P;
563
563
  if (a[14] !== M || a[15] !== N) {
564
564
  let e;
565
565
  a[17] === M ? e = a[18] : (e = (e, t) => (C.PAN_ZOOM === t || C.isBinColoring(t) || e.push({
@@ -573,7 +573,7 @@ var K = (e) => {
573
573
  }, a[19] = w, a[20] = I);
574
574
  let L = ee(I), R;
575
575
  a[21] === Symbol.for("react.memo_cache_sentinel") ? (R = (e) => {
576
- t.debug("[Vega view] created", e), ae.current = e, ce(void 0);
576
+ t.debug("[Vega view] created", e), oe.current = e, ce(void 0);
577
577
  }, a[21] = R) : R = a[21];
578
578
  let z = ee(R), B;
579
579
  a[22] === k ? B = a[23] : (B = () => {
@@ -592,7 +592,7 @@ var K = (e) => {
592
592
  children: /* @__PURE__ */ (0, G.jsx)(c, { className: "absolute bottom-1 right-0 m-2 h-4 w-4 cursor-help text-muted-foreground hover:text-foreground" })
593
593
  });
594
594
  }, a[22] = k, a[23] = B);
595
- let V = B, H = ie === "dark" ? "dark" : void 0, U;
595
+ let V = B, H = ae === "dark" ? "dark" : void 0, U;
596
596
  a[24] !== b || a[25] !== E || a[26] !== H ? (U = {
597
597
  theme: H,
598
598
  actions: b,
@@ -634,7 +634,7 @@ var K = (e) => {
634
634
  });
635
635
  }), xe = [K, F], a[35] = K, a[36] = F, a[37] = be, a[38] = xe) : (be = a[37], xe = a[38]), (0, y.useEffect)(be, xe);
636
636
  let Y;
637
- a[39] === _ ? Y = a[40] : (Y = _ && /* @__PURE__ */ (0, G.jsxs)(re, {
637
+ a[39] === _ ? Y = a[40] : (Y = _ && /* @__PURE__ */ (0, G.jsxs)(ie, {
638
638
  variant: "destructive",
639
639
  children: [/* @__PURE__ */ (0, G.jsx)(ne, { children: _.message }), /* @__PURE__ */ (0, G.jsx)("div", {
640
640
  className: "text-md",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@marimo-team/islands",
3
- "version": "0.26.1-dev108",
3
+ "version": "0.26.1-dev118",
4
4
  "main": "dist/main.js",
5
5
  "types": "dist/index.d.ts",
6
6
  "type": "module",
@@ -323,7 +323,7 @@ export const MockExecutions = {
323
323
  } satisfies NotebookReplica;
324
324
  store.set(activeNotebookReplicaAtom, replica);
325
325
  // Selector tests share current inputs; frame scheduling is tested separately.
326
- store.set(activeNotebookFrameAtom, replica);
326
+ store.set(activeNotebookFrameAtom, { ...replica, flush: () => undefined });
327
327
  return replica;
328
328
  },
329
329
  };
@@ -13,16 +13,16 @@ export function mockIntersectionObservers() {
13
13
  unobserve: vi.fn(),
14
14
  disconnect: vi.fn(),
15
15
  takeRecords: () => [],
16
- emit(target: Element, visible: boolean) {
17
- observer.emitBatch([[target, visible]]);
16
+ emit(target: Element, visible: boolean, intersectionRatio?: number) {
17
+ observer.emitBatch([[target, visible, intersectionRatio]]);
18
18
  },
19
- emitBatch(changes: [Element, boolean][]) {
19
+ emitBatch(changes: [Element, boolean, number?][]) {
20
20
  const rect = new DOMRect();
21
21
  callback(
22
- changes.map(([target, isIntersecting]) => ({
22
+ changes.map(([target, isIntersecting, ratio]) => ({
23
23
  target,
24
24
  isIntersecting,
25
- intersectionRatio: isIntersecting ? 1 : 0,
25
+ intersectionRatio: ratio ?? (isIntersecting ? 1 : 0),
26
26
  time: 0,
27
27
  boundingClientRect: rect,
28
28
  intersectionRect: rect,
@@ -1,5 +1,5 @@
1
1
  /* Copyright 2026 Marimo. All rights reserved. */
2
- import React, { memo, Suspense, useMemo, useRef } from "react";
2
+ import React, { memo, useMemo, useRef } from "react";
3
3
  import { type CellId, CellOutputId } from "@/core/cells/ids";
4
4
  import type { CellOutput } from "@/core/executions";
5
5
  import type { OutputMessage } from "@/core/kernel/messages";
@@ -21,7 +21,6 @@ import {
21
21
  ExpandIcon,
22
22
  ShrinkIcon,
23
23
  } from "lucide-react";
24
- import { tooltipHandler } from "@/components/charts/tooltip";
25
24
  import { useExpandedOutput } from "@/core/cells/outputs";
26
25
  import { viewStateAtom } from "@/core/mode";
27
26
  import { useEventListener } from "@/hooks/useEventListener";
@@ -30,15 +29,12 @@ import { useOverflowDetection } from "@/hooks/useOverflowDetection";
30
29
  import { renderHTML } from "@/plugins/core/RenderHTML";
31
30
  import { Banner } from "@/plugins/impl/common/error-banner";
32
31
  import type { TopLevelFacetedUnitSpec } from "@/plugins/impl/data-explorer/queries/types";
33
- import { getContainerWidth } from "@/plugins/impl/vega/utils";
34
- import { useTheme } from "@/theme/useTheme";
35
32
  import { Events } from "@/utils/events";
36
33
  import { invariant } from "@/utils/invariant";
37
34
  import { Logger } from "@/utils/Logger";
38
35
  import { processMimeBundle } from "@/utils/mime-types";
39
36
  import { Objects } from "@/utils/objects";
40
- import { LazyVegaEmbed } from "../charts/lazy";
41
- import { ChartLoadingState } from "../data-table/charts/components/chart-states";
37
+ import { VegaOutput } from "./output/VegaOutput";
42
38
  import { Button } from "../ui/button";
43
39
  import { useIsFullScreen } from "../ui/fullscreen";
44
40
  import { Tabs, TabsContent, TabsList, TabsTrigger } from "../ui/tabs";
@@ -85,7 +81,6 @@ export const OutputRenderer: React.FC<{
85
81
  metadata,
86
82
  renderFallback,
87
83
  } = props;
88
- const { theme } = useTheme();
89
84
 
90
85
  // Memoize parsing the json data
91
86
  const parsedJsonData = useMemo(() => {
@@ -214,20 +209,7 @@ export const OutputRenderer: React.FC<{
214
209
  case "application/vnd.vega.v5+json":
215
210
  case "application/vnd.vegalite.v6+json":
216
211
  case "application/vnd.vega.v6+json":
217
- return (
218
- <Suspense fallback={<ChartLoadingState />}>
219
- <LazyVegaEmbed
220
- spec={parsedJsonData as TopLevelFacetedUnitSpec}
221
- data-container-width={getContainerWidth(parsedJsonData)}
222
- options={{
223
- theme: theme === "dark" ? "dark" : undefined,
224
- mode: "vega-lite",
225
- tooltip: tooltipHandler.call,
226
- renderer: "canvas",
227
- }}
228
- />
229
- </Suspense>
230
- );
212
+ return <VegaOutput spec={parsedJsonData as TopLevelFacetedUnitSpec} />;
231
213
  case "application/vnd.marimo+mimebundle":
232
214
  return (
233
215
  <MimeBundleOutputRenderer
@@ -1,4 +1,6 @@
1
1
  /* Copyright 2026 Marimo. All rights reserved. */
2
+ import { Chat, useChat } from "@ai-sdk/react";
3
+ import { EditorView } from "@codemirror/view";
2
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";
@@ -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,7 +73,33 @@ 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;
81
+ }
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
+ });
67
103
  }
68
104
 
69
105
  it("shares the tooltip hover delay across cells", async () => {
@@ -83,6 +119,51 @@ it("shares the tooltip hover delay across cells", async () => {
83
119
  });
84
120
 
85
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
+
86
167
  it("does not re-render other cells on a keystroke", async () => {
87
168
  const { store, model, renders } = await setup(count);
88
169
  await act(async () => {
@@ -130,3 +211,248 @@ describe.each([2, 25])("cell render isolation with %i cells", (count) => {
130
211
  }
131
212
  });
132
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
+ );
@@ -378,6 +378,33 @@ describe("PairWithAgentModal", () => {
378
378
  expect(screen.getByRole("button", { name: "Copy command" })).toBeDisabled();
379
379
  });
380
380
 
381
+ it("cancels the copy confirmation reset when the modal unmounts", async () => {
382
+ vi.useFakeTimers();
383
+ const schedule = vi.spyOn(globalThis, "setTimeout");
384
+ const cancel = vi.spyOn(globalThis, "clearTimeout");
385
+ try {
386
+ const { unmount } = await act(async () =>
387
+ render(<PairWithAgentModal onClose={vi.fn()} />, { wrapper }),
388
+ );
389
+ await act(async () => {
390
+ fireEvent.click(screen.getByRole("button", { name: "Copy command" }));
391
+ });
392
+ expect(copyToClipboard).toHaveBeenCalledOnce();
393
+ const resetIndex = schedule.mock.calls.findIndex(
394
+ ([, delay]) => delay === 2000,
395
+ );
396
+ expect(resetIndex).toBeGreaterThanOrEqual(0);
397
+ const reset = schedule.mock.results[resetIndex].value;
398
+
399
+ unmount();
400
+ expect(cancel).toHaveBeenCalledWith(reset);
401
+ } finally {
402
+ schedule.mockRestore();
403
+ cancel.mockRestore();
404
+ vi.useRealTimers();
405
+ }
406
+ });
407
+
381
408
  it("copies a host mode terminal command without the token and lets the user copy the token separately", async () => {
382
409
  vi.mocked(fetch).mockImplementation((url) =>
383
410
  responseFor(url, "secret-token"),
@@ -252,6 +252,14 @@ const CommandBlock: React.FC<{
252
252
  }) => {
253
253
  const [copied, setCopied] = useState(false);
254
254
 
255
+ useEffect(() => {
256
+ if (!copied) {
257
+ return;
258
+ }
259
+ const timeout = setTimeout(() => setCopied(false), 2000);
260
+ return () => clearTimeout(timeout);
261
+ }, [copied]);
262
+
255
263
  const copy = Events.stopPropagation(async (e) => {
256
264
  e.preventDefault();
257
265
  if (disabled) {
@@ -259,7 +267,6 @@ const CommandBlock: React.FC<{
259
267
  }
260
268
  await copyToClipboard(command);
261
269
  setCopied(true);
262
- setTimeout(() => setCopied(false), 2000);
263
270
  });
264
271
 
265
272
  if (multiline) {