The best way to control Claude Code, Codex and more from any computer or phone

main
tsx 1,146 lines 42.3 KB
Raw
1 import type { ComposerFileAttachment } from "../composerDraftStore";
2 import { formatInlineContextReference } from "../lib/composerContextReferences";
3 import { fileContextReference } from "../lib/composerContextRecords";
4 import {
5 reconcileAttachmentContextReferences,
6 type RetainedContextPayloads,
7 useRetainedContextPayloads,
8 } from "./chat/composerContextUndo";
9
10 import {
11 ComposerContextId,
12 type ComposerContextRecord,
13 EnvironmentId,
14 type ServerProviderSkill,
15 } from "@t3tools/contracts";
16 import {
17 COMPOSER_CONTEXT_CLIPBOARD_MIME,
18 encodeComposerContextFragment,
19 } from "@t3tools/shared/composerContextClipboard";
20 import { formatComposerContextReference } from "@t3tools/shared/composerContextReferences";
21 import type { Editor } from "@tiptap/core";
22 import { redoDepth, undoDepth } from "@tiptap/pm/history";
23 import { NodeSelection } from "@tiptap/pm/state";
24 import { createElement, createRef, useEffect, useState } from "react";
25 import { describe, expect, it, vi } from "vite-plus/test";
26 import { userEvent } from "vite-plus/test/browser";
27
28 import { act, fakeTimers, render } from "../../test/render";
29
30 import { flatToMarkdown, pmToFlat, serializeEditorDoc } from "~/composer-rich-text-doc";
31 import { isMacPlatform } from "~/lib/utils";
32 import { registerCommands } from "~/shortcuts/dispatcher";
33 import {
34 ComposerPromptEditorTiptap as ComposerPromptEditor,
35 type ComposerPromptEditorHandle,
36 type ComposerPromptEditorProps,
37 } from "./ComposerPromptEditorTiptap";
38
39 vi.mock(import("../state/server"), async (original) => {
40 const { Atom } = await import("effect/reactivity");
41 const { compileResolvedKeybindingsConfig, DEFAULT_KEYBINDINGS } =
42 await import("@t3tools/shared/keybindings");
43 return {
44 ...(await original()),
45 primaryServerKeybindingsAtom: Atom.make(
46 compileResolvedKeybindingsConfig([
47 ...DEFAULT_KEYBINDINGS,
48 { key: "mod+arrowup", command: "thread.previous" },
49 { key: "mod+arrowdown", command: "thread.next" },
50 ]),
51 ),
52 };
53 });
54
55 const babysit: ServerProviderSkill = {
56 name: "babysit",
57 path: "/skills/babysit/SKILL.md",
58 enabled: true,
59 };
60
61 function Composer({
62 value,
63 richTextEnabled,
64 skills,
65 onChange,
66 onCommandKeyDown = () => false,
67 importContextFragment,
68 literalText = false,
69 disabled = false,
70 }: {
71 value: string;
72 richTextEnabled: boolean;
73 skills: ReadonlyArray<ServerProviderSkill>;
74 onChange?: ComposerPromptEditorProps["onChange"] | undefined;
75 onCommandKeyDown?: ComposerPromptEditorProps["onCommandKeyDown"] | undefined;
76 importContextFragment?: ComposerPromptEditorProps["importContextFragment"];
77 literalText?: boolean;
78 disabled?: boolean;
79 }) {
80 const [prompt, setPrompt] = useState({ value, cursor: value.length });
81 return (
82 <ComposerPromptEditor
83 editorRef={createRef<ComposerPromptEditorHandle>()}
84 value={prompt.value}
85 cursor={prompt.cursor}
86 richTextEnabled={richTextEnabled}
87 contextRecords={new Map()}
88 skills={skills}
89 disabled={disabled}
90 placeholder=""
91 onChange={(...args) => {
92 setPrompt({ value: args[0], cursor: args[1] });
93 onChange?.(...args);
94 }}
95 onPaste={() => {}}
96 onCommandKeyDown={onCommandKeyDown}
97 importContextFragment={importContextFragment}
98 literalText={literalText}
99 />
100 );
101 }
102
103 function composer(
104 value: string,
105 richTextEnabled = true,
106 skills: ReadonlyArray<ServerProviderSkill> = [],
107 onChange?: ComposerPromptEditorProps["onChange"],
108 onCommandKeyDown?: ComposerPromptEditorProps["onCommandKeyDown"],
109 ) {
110 return (
111 <Composer
112 value={value}
113 richTextEnabled={richTextEnabled}
114 skills={skills}
115 onChange={onChange}
116 onCommandKeyDown={onCommandKeyDown}
117 />
118 );
119 }
120
121 function editorIn(container: HTMLElement) {
122 const element = container.querySelector<HTMLElement & { editor: Editor }>(".tiptap");
123 if (!element) throw new Error("Composer did not mount");
124 return element.editor;
125 }
126
127 async function mountEditor(...props: Parameters<typeof composer>) {
128 await using stack = new AsyncDisposableStack();
129 const screen = stack.use(await render(composer(...props)));
130 const editor = editorIn(screen.container);
131 const environment = stack.move();
132 return Object.assign(screen, {
133 [Symbol.asyncDispose]: () => environment.disposeAsync(),
134 editor,
135 /** Rerenders the same composer with new props, as a parent would. */
136 update: async (...next: Parameters<typeof composer>) => {
137 await screen.rerender(composer(...next));
138 return editorIn(screen.container);
139 },
140 });
141 }
142
143 async function replaceDomText(editor: Editor, text: string, isComposing = false) {
144 await act(async () => {
145 const node = editor.view.dom.querySelector("p")?.firstChild;
146 if (!(node instanceof Text)) throw new Error("Composition text is missing");
147 node.data = text;
148 window.getSelection()?.collapse(node, text.length);
149 if (isComposing) {
150 editor.view.dom.dispatchEvent(new CompositionEvent("compositionupdate", { data: text }));
151 }
152 editor.view.dom.dispatchEvent(
153 new InputEvent("input", {
154 inputType: isComposing ? "insertCompositionText" : "insertText",
155 data: text,
156 isComposing,
157 }),
158 );
159 });
160 }
161
162 function typeText(editor: Editor, from: number, to: number, text: string) {
163 const insert = () => editor.state.tr.insertText(text, from, to);
164 if (
165 !editor.view.someProp("handleTextInput", (handler) =>
166 handler(editor.view, from, to, text, insert),
167 )
168 ) {
169 editor.view.dispatch(insert());
170 }
171 }
172
173 function textWithMark(editor: Editor, name: string) {
174 const text: string[] = [];
175 editor.state.doc.descendants((node) => {
176 if (node.isText && node.marks.some((mark) => mark.type.name === name)) {
177 text.push(node.textContent);
178 }
179 });
180 return text;
181 }
182
183 it.each([
184 { value: "clean _build and node", code: [] },
185 { value: "clean `_build` and `node", code: ["_build"] },
186 ])("keeps a typed underscore literal after $value", async ({ value, code }) => {
187 await using screen = await mountEditor(value);
188 const { editor } = screen;
189 await act(async () => {
190 editor.commands.focus("end");
191 const { from, to } = editor.state.selection;
192 typeText(editor, from, to, "_");
193 });
194 expect(serializeEditorDoc(editor.state.doc).value).toBe(`${value}_`);
195 expect(textWithMark(editor, "italic")).toEqual([]);
196 expect(textWithMark(editor, "code")).toEqual(code);
197 });
198
199 it.each([
200 { mark: "bold", key: "b", marker: "**" },
201 { mark: "italic", key: "i", marker: "*" },
202 ])("toggles $mark with Mod+$key at a collapsed cursor", async ({ mark, key, marker }) => {
203 await using screen = await mountEditor("ship it");
204 const { editor } = screen;
205 const mod = isMacPlatform(navigator.platform) ? "Meta" : "Control";
206 const chord = `{${mod}>}${key}{/${mod}}`;
207 await act(async () => {
208 editor.commands.focus("end");
209 });
210 await vi.waitFor(() => expect(document.activeElement).toBe(editor.view.dom));
211 await userEvent.keyboard(" ");
212 await userEvent.keyboard(chord);
213 await userEvent.keyboard("now");
214 await userEvent.keyboard(chord);
215 await userEvent.keyboard(" done");
216 await vi.waitFor(() =>
217 expect(serializeEditorDoc(editor.state.doc).value).toBe(`ship it ${marker}now${marker} done`),
218 );
219 expect(textWithMark(editor, mark)).toEqual(["now"]);
220 });
221
222 it.each([
223 { key: "i", caret: 10, expected: "ship it **n*X*ow** done" },
224 { key: "i", caret: 9, expected: "ship it *X***now** done" },
225 { key: "e", caret: "{ArrowLeft>5/}", expected: "ship it **now**`X` done" },
226 ])(
227 "Mod+$key at $caret in a bold word styles the next typed text",
228 async ({ key, caret, expected }) => {
229 await using screen = await mountEditor("ship it **now** done");
230 const { editor } = screen;
231 const mod = isMacPlatform(navigator.platform) ? "Meta" : "Control";
232 // ProseMirror rewrites the DOM caret 20ms after focus. Run that now, or it
233 // can undo the first arrow key before ProseMirror reads the native move.
234 {
235 using _timers = fakeTimers();
236 await act(async () => {
237 if (typeof caret === "number") editor.commands.focus(caret);
238 else editor.commands.focus("end");
239 });
240 await vi.waitFor(() => expect(document.activeElement).toBe(editor.view.dom));
241 vi.runOnlyPendingTimers();
242 }
243 if (typeof caret === "string") await userEvent.keyboard(caret);
244 await userEvent.keyboard(`{${mod}>}${key}{/${mod}}`);
245 await userEvent.keyboard("X");
246 await vi.waitFor(() => expect(serializeEditorDoc(editor.state.doc).value).toBe(expected));
247 },
248 );
249
250 it.each([
251 { word: "ship", prefix: "", source: ["**ship**"] },
252 { word: "path\\", prefix: "", source: [] },
253 { word: "2*3", prefix: "", source: [] },
254 { word: "b", prefix: "*", source: [] },
255 { word: "word", prefix: "\\\\*", source: [] },
256 { word: "word", prefix: "\\\\**", source: [] },
257 { word: "word", prefix: "\\", source: [] },
258 { word: "word", prefix: "\\\\", source: ["**word**"] },
259 { word: "word", prefix: "\\\\\\", source: [] },
260 {
261 word: "word",
262 prefix: "`path\\`",
263 prefixText: "path\\",
264 source: ["**word**"],
265 code: ["path\\"],
266 },
267 ])(
268 "bolds $word after '$prefix' with Mod+B over a selection",
269 async ({ word, prefix, prefixText = prefix, source, code = [] }) => {
270 const value = `${prefix}${word} it`;
271 await using screen = await mountEditor(value);
272 const { editor } = screen;
273 const modB = isMacPlatform(navigator.platform) ? "{Meta>}b{/Meta}" : "{Control>}b{/Control}";
274 await act(async () => {
275 editor.commands.focus("end");
276 });
277 await vi.waitFor(() => expect(document.activeElement).toBe(editor.view.dom));
278 await act(async () => {
279 editor.commands.setTextSelection({
280 from: prefixText.length + 1,
281 to: prefixText.length + word.length + 1,
282 });
283 });
284 await userEvent.keyboard(modB);
285 await vi.waitFor(() =>
286 expect(serializeEditorDoc(editor.state.doc).value).toBe(`${prefix}**${word}** it`),
287 );
288 expect(textWithMark(editor, "markdownSource")).toEqual(source);
289 const depth = undoDepth(editor.state);
290 await userEvent.keyboard("{End}");
291 expect(serializeEditorDoc(editor.state.doc).value).toBe(`${prefix}**${word}** it`);
292 expect(textWithMark(editor, "bold")).toEqual([word]);
293 expect(textWithMark(editor, "code")).toEqual(code);
294 expect(undoDepth(editor.state)).toBe(depth);
295 await act(async () => {
296 editor.commands.setTextSelection({
297 from: prefixText.length + 1,
298 to: prefixText.length + word.length + 1,
299 });
300 });
301
302 // Whether the selection spans shown markers or not, Mod+B removes the bold.
303 await userEvent.keyboard(modB);
304 await vi.waitFor(() => expect(serializeEditorDoc(editor.state.doc).value).toBe(value));
305 },
306 );
307
308 it("distinguishes text edits from caret moves in change notifications", async () => {
309 const onChange = vi.fn<ComposerPromptEditorProps["onChange"]>();
310 await using screen = await mountEditor("", true, [], onChange);
311 await act(async () => {
312 screen.editor.commands.focus("end");
313 });
314 await vi.waitFor(() => expect(document.activeElement).toBe(screen.editor.view.dom));
315 await userEvent.keyboard("/mod ab");
316 expect(onChange.mock.lastCall?.[0]).toBe("/mod ab");
317 expect(onChange.mock.lastCall?.[5]).toBe(true);
318
319 await userEvent.keyboard("{ArrowLeft}");
320 expect(onChange.mock.lastCall?.[0]).toBe("/mod ab");
321 expect(onChange.mock.lastCall?.[5]).toBe(false);
322 });
323
324 // The mocked server keybindings bind Command-Up and Command-Down to thread navigation.
325 it("leaves Command-arrow thread navigation bindings to the app on macOS", async () => {
326 using _platform = vi.spyOn(navigator, "platform", "get").mockReturnValue("MacIntel");
327 await using screen = await mountEditor("first\nsecond");
328 const { editor } = screen;
329 await act(async () => {
330 editor.commands.focus("end");
331 });
332 await vi.waitFor(() => expect(document.activeElement).toBe(editor.view.dom));
333 const reachedApp: string[] = [];
334 const onWindowKeyDown = (event: KeyboardEvent) => {
335 if (!event.defaultPrevented && event.key.startsWith("Arrow")) reachedApp.push(event.key);
336 };
337 window.addEventListener("keydown", onWindowKeyDown);
338 using _listener = {
339 [Symbol.dispose]: () => window.removeEventListener("keydown", onWindowKeyDown),
340 };
341
342 await userEvent.keyboard("{Meta>}{ArrowUp}{ArrowDown}{/Meta}");
343
344 expect(reachedApp).toEqual(["ArrowUp", "ArrowDown"]);
345 });
346
347 it.each([
348 ["e", false, false],
349 ["i", false, false],
350 ["e", true, false],
351 ["e", false, true],
352 ])(
353 "leaves Mod+%s to an app command bound to it instead of formatting (composer command: %s, declined capture command: %s)",
354 async (key, composerClaimsKey, declinedCapture) => {
355 const openUsage = vi.fn((event: KeyboardEvent) => {
356 if (declinedCapture) return false;
357 event.preventDefault();
358 });
359 using _commands = {
360 [Symbol.dispose]: registerCommands(
361 { "usage.open": openUsage },
362 {
363 keybindings: () => [
364 {
365 command: "usage.open",
366 shortcut: {
367 key,
368 metaKey: false,
369 ctrlKey: false,
370 shiftKey: false,
371 altKey: false,
372 modKey: true,
373 },
374 },
375 ],
376 capture: declinedCapture,
377 },
378 ),
379 };
380 const composerCommand = vi.fn(() => composerClaimsKey);
381 await using screen = await mountEditor("word", true, [], undefined, composerCommand);
382 const { editor } = screen;
383 await act(async () => {
384 editor.commands.focus();
385 editor.commands.setTextSelection({ from: 1, to: 5 });
386 });
387 await vi.waitFor(() => expect(document.activeElement).toBe(editor.view.dom));
388 const modifier = isMacPlatform(navigator.platform) ? "Meta" : "Control";
389 await userEvent.keyboard(`{${modifier}>}${key}{/${modifier}}`);
390 expect(composerCommand).toHaveBeenCalled();
391 expect(openUsage).toHaveBeenCalledTimes(composerClaimsKey ? 0 : 1);
392 expect(serializeEditorDoc(editor.state.doc).value).toBe(declinedCapture ? "`word`" : "word");
393 },
394 );
395
396 it.each([false, true])(
397 "composes an umlaut without wrapping the preedit text (rich text: %s)",
398 async (richTextEnabled) => {
399 // The middle dot stands in for the provisional text shown by the Compose key.
400 await using screen = await mountEditor("·", richTextEnabled);
401 const { editor } = screen;
402 await act(async () => {
403 editor.view.focus();
404 editor.view.dom.dispatchEvent(new CompositionEvent("compositionstart"));
405 });
406 await replaceDomText(editor, '"', true);
407 expect(serializeEditorDoc(editor.state.doc).value).toBe('"');
408 await replaceDomText(editor, "ö", true);
409 await act(async () => {
410 editor.view.dom.dispatchEvent(new CompositionEvent("compositionend", { data: "ö" }));
411 });
412 expect(serializeEditorDoc(editor.state.doc).value).toBe("ö");
413 },
414 );
415
416 it("lets composition replace selected text without surrounding it", async () => {
417 await using screen = await mountEditor("word");
418 const { editor } = screen;
419 await act(async () => {
420 editor.commands.setTextSelection({ from: 1, to: 5 });
421 editor.view.dom.dispatchEvent(new CompositionEvent("compositionstart"));
422 typeText(editor, 1, 5, '"');
423 });
424 expect(serializeEditorDoc(editor.state.doc).value).toBe('"');
425 });
426
427 it.each([
428 { at: "inside bold", selection: 5, composed: "**bo漢ld** after", bold: ["bo漢ld"] },
429 {
430 at: "over the opening markers",
431 selection: { from: 1, to: 3 },
432 composed: "漢bold** after",
433 bold: [],
434 },
435 { at: "after the closing markers", selection: 9, composed: "**bold**漢 after", bold: ["bold"] },
436 ])("undoes composition $at in revealed Markdown through the earlier paste", async (row) => {
437 await using screen = await mountEditor("");
438 const { editor } = screen;
439 const value = () => serializeEditorDoc(editor.state.doc).value;
440 await act(async () => {
441 editor.view.focus();
442 const clipboardData = new DataTransfer();
443 clipboardData.setData("text/plain", "**bold** after");
444 editor.view.dom.dispatchEvent(new ClipboardEvent("paste", { clipboardData, cancelable: true }));
445 editor.commands.insertContent("!");
446 editor.commands.undo();
447 editor.commands.setTextSelection(3);
448 });
449 expect(value()).toBe("**bold** after");
450 expect(textWithMark(editor, "markdownSource")).toEqual(["**bold**"]);
451 await act(async () => {
452 editor.commands.setTextSelection(row.selection);
453 // A composition canceled before it edits anything keeps the redo and adds no undo.
454 editor.view.dom.dispatchEvent(new CompositionEvent("compositionstart"));
455 editor.view.dom.dispatchEvent(new CompositionEvent("compositionend", { data: "" }));
456 });
457 expect([undoDepth(editor.state), redoDepth(editor.state)]).toEqual([1, 1]);
458 await act(async () => {
459 editor.view.dom.dispatchEvent(new CompositionEvent("compositionstart"));
460 // ProseMirror numbers each composition; the canceled one was 1.
461 editor.view.dispatch(editor.state.tr.insertText("漢").setMeta("composition", 2));
462 editor.view.dom.dispatchEvent(new CompositionEvent("compositionend", { data: "漢" }));
463 editor.commands.setTextSelection(editor.state.doc.content.size - 1);
464 });
465 expect(value()).toBe(row.composed);
466 await act(async () => {
467 editor.commands.undo();
468 });
469 expect(value()).toBe("**bold** after");
470 await act(async () => {
471 editor.commands.undo();
472 });
473 expect(value()).toBe("");
474 await act(async () => {
475 editor.commands.redo();
476 editor.commands.redo();
477 editor.commands.setTextSelection(editor.state.doc.content.size - 1);
478 });
479 expect(value()).toBe(row.composed);
480 expect(textWithMark(editor, "bold")).toEqual(row.bold);
481 });
482
483 it("keeps unknown dollar names editable when restoring and pasting a draft", async () => {
484 const value = "echo $HOME $PATH $anything $notaskill $20 $20k $babysit ";
485 await using screen = await mountEditor(value, true, [babysit]);
486 const { editor } = screen;
487 expect(editor.state.doc.textContent).toBe(value.replace("$babysit", ""));
488 expect(serializeEditorDoc(editor.state.doc).value).toBe(value);
489 await act(async () => {
490 editor.commands.setTextSelection("echo $HO".length + 1);
491 editor.commands.insertContent("X");
492 });
493 expect(serializeEditorDoc(editor.state.doc).value).toBe(value.replace("$HOME", "$HOXME"));
494 await act(async () => {
495 editor.commands.selectAll();
496 const clipboardData = new DataTransfer();
497 clipboardData.setData("text/plain", value);
498 editor.view.dom.dispatchEvent(new ClipboardEvent("paste", { clipboardData, cancelable: true }));
499 });
500 expect(editor.state.doc.textContent).toBe(value.replace("$babysit", ""));
501 expect(serializeEditorDoc(editor.state.doc).value).toBe(value);
502 });
503
504 // regression: #25180 Tiptap's paste rules styled the pasted text a second time
505 it.each([
506 "Read https://example.com/_handle_/status/1 and open src/__test__.tsx",
507 "see `**x**` now",
508 ])("sends pasted %s as pasted", async (pasted) => {
509 await using screen = await mountEditor("");
510 const { editor } = screen;
511 await act(async () => {
512 const clipboardData = new DataTransfer();
513 clipboardData.setData("text/plain", pasted);
514 editor.view.dom.dispatchEvent(new ClipboardEvent("paste", { clipboardData, cancelable: true }));
515 });
516 expect(serializeEditorDoc(editor.state.doc).value).toBe(pasted);
517 });
518
519 it.each([
520 { literalText: false, imports: 1 },
521 { literalText: true, imports: 0 },
522 ])(
523 "imports a copied snapshot's context over its image file: %o",
524 async ({ literalText, imports }) => {
525 const record = {
526 version: 1,
527 kind: "image",
528 contextId: ComposerContextId.make("image_snapshot"),
529 label: "shot.png",
530 attachmentId: "snapshot",
531 name: "shot.png",
532 mimeType: "image/png",
533 sizeBytes: 3,
534 } satisfies ComposerContextRecord;
535 const importContextFragment = vi.fn(() => new Map([[record.contextId, record.contextId]]));
536 await using screen = await render(
537 <Composer
538 value=""
539 richTextEnabled
540 skills={[]}
541 literalText={literalText}
542 importContextFragment={importContextFragment}
543 />,
544 );
545 const editor = editorIn(screen.container);
546 await act(async () => {
547 const clipboardData = new DataTransfer();
548 clipboardData.items.add(
549 new File([new Uint8Array([1, 2, 3])], "shot.png", { type: "image/png" }),
550 );
551 clipboardData.setData("text/plain", formatComposerContextReference(record));
552 clipboardData.setData(
553 COMPOSER_CONTEXT_CLIPBOARD_MIME,
554 encodeComposerContextFragment({
555 version: 1,
556 source: { environmentId: EnvironmentId.make("snapshot-source") },
557 records: [record],
558 })!,
559 );
560 editor.view.dom.dispatchEvent(
561 new ClipboardEvent("paste", { clipboardData, cancelable: true }),
562 );
563 });
564 expect(importContextFragment).toHaveBeenCalledTimes(imports);
565 },
566 );
567
568 it.each(["x\r\n\r\ny", "x\r\ry"])(
569 "pastes %j with the same blank line as x\\n\\ny",
570 async (text) => {
571 await using screen = await mountEditor("");
572 const { editor } = screen;
573 await act(async () => {
574 editor.commands.focus("end");
575 const clipboardData = new DataTransfer();
576 clipboardData.setData("text/plain", text);
577 editor.view.dom.dispatchEvent(
578 new ClipboardEvent("paste", { clipboardData, cancelable: true }),
579 );
580 });
581 const paragraphs: string[] = [];
582 editor.state.doc.forEach((node) => paragraphs.push(node.textContent));
583 expect(paragraphs).toEqual(["x", "", "y"]);
584 expect(serializeEditorDoc(editor.state.doc).value).toBe("x\n\ny");
585 },
586 );
587
588 it("keeps the caret inside unknown dollar text across rich and plain remounts", async () => {
589 const value = "echo $HOME now";
590 await using screen = await mountEditor(value);
591 let { editor } = screen;
592 await act(async () => {
593 editor.commands.setTextSelection("echo $HO".length + 1);
594 });
595 editor = await screen.update(value, false);
596 await act(async () => {
597 editor.commands.insertContent("X");
598 });
599 expect(serializeEditorDoc(editor.state.doc).value).toBe("echo $HOXME now");
600 editor = await screen.update(value, true);
601 await act(async () => {
602 editor.commands.insertContent("Y");
603 });
604 expect(serializeEditorDoc(editor.state.doc).value).toBe("echo $HOXYME now");
605 });
606
607 async function focusAt(editor: Editor, position: number | "end") {
608 // ProseMirror rewrites the DOM caret 20ms after focus. Run that now, or it
609 // can undo the first key before ProseMirror reads the native move.
610 using _timers = fakeTimers();
611 await act(async () => {
612 editor.commands.focus(position);
613 });
614 await vi.waitFor(() => expect(document.activeElement).toBe(editor.view.dom));
615 vi.runOnlyPendingTimers();
616 }
617
618 it("reopens a long draft scrolled to its caret without taking focus", async () => {
619 // App CSS is not loaded here; give the editor its own scroll box.
620 const style = document.head.appendChild(document.createElement("style"));
621 // The bottom padding stands in for space reserved under overlaid controls.
622 style.textContent =
623 ".composer-tiptap { max-height: 120px; overflow-y: auto; padding-bottom: 48px; }";
624 using _style = { [Symbol.dispose]: () => style.remove() };
625 const value = Array.from({ length: 40 }, (_, line) => `line ${line + 1}`).join("\n");
626 await using screen = await mountEditor(value);
627 const { editor } = screen;
628 const scroller = editor.view.dom;
629 await vi.waitFor(() => expect(scroller.scrollTop).toBeGreaterThan(0));
630 expect(document.activeElement).not.toBe(scroller);
631 const caret = editor.view.coordsAtPos(editor.state.selection.head);
632 expect(caret.bottom).toBeLessThanOrEqual(scroller.getBoundingClientRect().bottom - 48 + 1);
633 });
634
635 describe("Markdown markers around styled text", () => {
636 it.each([
637 { keys: "{Backspace}", expected: "**** after" },
638 { keys: "X", expected: "**X** after" },
639 ])("keeps a styled chip selected for $keys when showing source", async ({ keys, expected }) => {
640 await using screen = await mountEditor("$babysit after", true, [babysit]);
641 const { editor } = screen;
642 await focusAt(editor, "end");
643 await act(async () => {
644 editor.view.dispatch(editor.state.tr.addMark(1, 2, editor.schema.marks.bold!.create()));
645 });
646 expect(editor.state.doc.nodeAt(1)?.type.name).toBe("composer-skill");
647 await act(async () => {
648 editor.commands.setNodeSelection(1);
649 });
650 expect(editor.state.selection).toBeInstanceOf(NodeSelection);
651 expect((editor.state.selection as NodeSelection).node.type.name).toBe("composer-skill");
652 await userEvent.keyboard(keys);
653 await userEvent.keyboard("{End}");
654 await vi.waitFor(() => expect(serializeEditorDoc(editor.state.doc).value).toBe(expected));
655 });
656
657 it.each([
658 {
659 name: "deleting the opening markers removes bold",
660 value: "**bold** after",
661 caret: 1,
662 keys: "{Delete}{Delete}",
663 expected: "bold** after",
664 marks: {},
665 },
666 {
667 name: "turning ** into * makes it italic",
668 value: "**bold** after",
669 caret: 1,
670 keys: "{Delete}{ArrowRight}{ArrowRight}{ArrowRight}{ArrowRight}{ArrowRight}{Delete}",
671 expected: "*bold* after",
672 marks: { italic: ["bold"] },
673 },
674 {
675 name: "backspacing from the closing edge keeps italic",
676 value: "**bold** after",
677 caret: 1,
678 keys: async (editor: Editor) => {
679 await userEvent.keyboard("{Delete}");
680 await vi.waitFor(() => expect(editor.state.doc.textContent).toBe("*bold** after"));
681 for (let position = 2; position <= 8; position += 1) {
682 await userEvent.keyboard("{ArrowRight}");
683 await vi.waitFor(() => expect(editor.state.selection.from).toBe(position));
684 }
685 await userEvent.keyboard("{Backspace}");
686 await vi.waitFor(() =>
687 expect(serializeEditorDoc(editor.state.doc).value).toBe("*bold* after"),
688 );
689 },
690 expected: "*bold* after",
691 marks: { italic: ["bold"] },
692 },
693 {
694 name: "retyping deleted closing markers restores bold",
695 value: "**bold** after",
696 caret: 3,
697 keys: "{ArrowRight}{ArrowRight}{Delete}{Delete}**",
698 expected: "**bold** after",
699 marks: { bold: ["bold"] },
700 },
701 {
702 name: "deleting a backtick removes inline code",
703 value: "`code` after",
704 caret: 1,
705 keys: "{Delete}",
706 expected: "code` after",
707 marks: {},
708 },
709 {
710 name: "a line break inside bold keeps both halves bold",
711 value: "**bold** after",
712 caret: 3,
713 keys: "{Shift>}{Enter}{/Shift}",
714 expected: "**bo**\n**ld** after",
715 marks: { bold: ["bo", "ld"] },
716 },
717 {
718 name: "a line break after typed inline code leaves the next line plain",
719 value: "",
720 caret: 1,
721 keys: "`Test`{Shift>}{Enter}{/Shift}f",
722 expected: "`Test`\nf",
723 marks: { code: ["Test"] },
724 },
725 {
726 name: "a line break after typed bold leaves the next line plain",
727 value: "",
728 caret: 1,
729 keys: "**Test**{Shift>}{Enter}{/Shift}f",
730 expected: "**Test**\nf",
731 marks: { bold: ["Test"] },
732 },
733 {
734 name: "bold turned on after typed bold carries across a line break",
735 value: "",
736 caret: 1,
737 keys: `**Test**${isMacPlatform(navigator.platform) ? "{Meta>}b{/Meta}" : "{Control>}b{/Control}"}{Shift>}{Enter}{/Shift}f`,
738 expected: "**Test**\n**f**",
739 // The caret beside f shows it as source.
740 marks: { bold: ["Test"] },
741 },
742 {
743 name: "splitting a list item inside bold keeps both halves bold",
744 value: "- **bold** after",
745 caret: 5,
746 keys: "{Enter}",
747 expected: "- **bo**\n- **ld** after",
748 marks: { bold: ["bo", "ld"] },
749 },
750 ])("edits the markers as text: $name", async ({ value, caret, keys, expected, marks }) => {
751 await using screen = await mountEditor(value);
752 const { editor } = screen;
753 // Position 1 is the start of the styled word; 3 is two characters into it (5 in a list item).
754 await focusAt(editor, caret);
755 if (typeof keys === "string") await userEvent.keyboard(keys);
756 else await keys(editor);
757 await userEvent.keyboard("{End}");
758 await vi.waitFor(() => expect(serializeEditorDoc(editor.state.doc).value).toBe(expected));
759 for (const name of ["bold", "italic", "code"] as const) {
760 expect(textWithMark(editor, name)).toEqual(marks[name as keyof typeof marks] ?? []);
761 }
762 });
763
764 it("shows nested formatting as Markdown and restores it when the caret leaves", async () => {
765 const value = "**a *b* c** d";
766 await using screen = await mountEditor(value);
767 const { editor } = screen;
768 await focusAt(editor, "a b".length + 1);
769 expect(editor.state.doc.textContent).toBe(value);
770 expect(textWithMark(editor, "bold")).toEqual([]);
771 await userEvent.keyboard("{End}");
772 await vi.waitFor(() => expect(editor.state.doc.textContent).toBe("a b c d"));
773 expect(textWithMark(editor, "bold")).toEqual(["a ", "b", " c"]);
774 expect(textWithMark(editor, "italic")).toEqual(["b"]);
775 expect(serializeEditorDoc(editor.state.doc).value).toBe(value);
776 });
777
778 it("undoes a marker edit in one step without an extra step for showing markers", async () => {
779 await using screen = await mountEditor("**bold** after");
780 const { editor } = screen;
781 await focusAt(editor, "end");
782 await userEvent.keyboard("!");
783 await act(async () => {
784 editor.commands.setTextSelection(1);
785 });
786 await userEvent.keyboard("{Delete}{Delete}{End}");
787 const value = () => serializeEditorDoc(editor.state.doc).value;
788 await vi.waitFor(() => expect(value()).toBe("bold** after!"));
789 await act(async () => {
790 editor.commands.undo();
791 });
792 expect(value()).toBe("**bold** after!");
793 expect(textWithMark(editor, "markdownSource")).toEqual(["**bold**"]);
794 const end = () => editor.state.doc.content.size - 1;
795 // Undo restored the markers as text; leaving hides them without touching the text undo needs.
796 await act(async () => {
797 editor.commands.setTextSelection(end());
798 });
799 expect(value()).toBe("**bold** after!");
800 const hidden = editor.view.dom.querySelectorAll(".composer-rich-marker-hidden");
801 expect(Array.from(hidden, (marker) => marker.textContent)).toEqual(["**", "**"]);
802 await act(async () => {
803 editor.commands.undo();
804 });
805 expect(value()).toBe("**bold** after");
806 // Moving the caret into styled text keeps redo, and adds no undo step after it.
807 await act(async () => {
808 editor.commands.setTextSelection(3);
809 });
810 expect(editor.state.doc.textContent).toBe("**bold** after");
811 expect(textWithMark(editor, "markdownSource")).toEqual(["**bold**"]);
812 await act(async () => {
813 editor.commands.redo();
814 });
815 expect(value()).toBe("**bold** after!");
816 await act(async () => {
817 editor.commands.setTextSelection(1);
818 });
819 await act(async () => {
820 editor.commands.redo();
821 });
822 expect(value()).toBe("bold** after!");
823 expect(textWithMark(editor, "bold")).toEqual([]);
824 await act(async () => {
825 editor.commands.undo();
826 editor.commands.undo();
827 });
828 await act(async () => {
829 editor.commands.redo();
830 });
831 await act(async () => {
832 editor.commands.setTextSelection(editor.state.doc.content.size - 1);
833 });
834 await act(async () => {
835 editor.commands.undo();
836 });
837 // Undo puts the caret back inside the styled text.
838 expect(editor.state.doc.textContent).toBe("**bold** after");
839 await act(async () => {
840 editor.commands.setTextSelection(end());
841 });
842 expect(editor.state.doc.textContent).toBe("bold after");
843 expect(textWithMark(editor, "bold")).toEqual(["bold"]);
844 // After a completed redo, markers still follow the caret, and Delete edits the opening one.
845 await userEvent.keyboard("?");
846 await act(async () => {
847 editor.commands.undo();
848 });
849 await act(async () => {
850 editor.commands.redo();
851 });
852 expect(editor.state.doc.textContent).toBe("bold after?");
853 await act(async () => {
854 editor.commands.setTextSelection(1);
855 });
856 expect(editor.state.doc.textContent).toBe("**bold** after?");
857 expect(textWithMark(editor, "markdownSource")).toEqual(["**bold**"]);
858 await act(async () => {
859 editor.commands.setTextSelection(end());
860 });
861 expect(editor.state.doc.textContent).toBe("bold after?");
862 expect(textWithMark(editor, "bold")).toEqual(["bold"]);
863 await act(async () => {
864 editor.commands.setTextSelection(1);
865 });
866 await userEvent.keyboard("{Delete}");
867 expect(value()).toBe("*bold** after?");
868 await act(async () => {
869 editor.commands.undo();
870 });
871 expect(value()).toBe("**bold** after?");
872 expect(textWithMark(editor, "markdownSource")).toEqual(["**bold**"]);
873 await act(async () => {
874 editor.commands.setTextSelection(end());
875 });
876 expect(editor.state.doc.textContent).toBe("bold after?");
877 expect(textWithMark(editor, "bold")).toEqual(["bold"]);
878 });
879
880 it("keeps bold around a skill pasted inside it", async () => {
881 await using screen = await mountEditor("**helloworld** after", true, [babysit]);
882 const { editor } = screen;
883 await focusAt(editor, "hello".length + 1);
884 await act(async () => {
885 const clipboardData = new DataTransfer();
886 clipboardData.setData("text/plain", "$babysit");
887 editor.view.dom.dispatchEvent(
888 new ClipboardEvent("paste", { clipboardData, cancelable: true }),
889 );
890 });
891 await userEvent.keyboard("{End}");
892 await vi.waitFor(() =>
893 expect(serializeEditorDoc(editor.state.doc).value).toBe("**hello** $babysit **world** after"),
894 );
895 expect(textWithMark(editor, "bold")).toEqual(["hello", "world"]);
896 });
897 });
898
899 const file = {
900 type: "file",
901 id: "file-1",
902 name: "notes.txt",
903 mimeType: "text/plain",
904 sizeBytes: 5,
905 file: new File(["notes"], "notes.txt", { type: "text/plain" }),
906 } satisfies ComposerFileAttachment;
907
908 describe("composer context undo lifetime", () => {
909 async function mountComposer(destinationValue = "") {
910 const initialValue = `Draft A ${formatInlineContextReference(fileContextReference(file))}`;
911 const editorRef = createRef<ComposerPromptEditorHandle>();
912 let current: { value: string; files: ComposerFileAttachment[] };
913 let retained: RetainedContextPayloads;
914
915 function Composer({ targetKey }: { targetKey: string }) {
916 const [drafts, setDrafts] = useState<
917 Record<string, { value: string; files: ComposerFileAttachment[] }>
918 >({
919 a: { value: initialValue, files: [file] },
920 b: { value: destinationValue, files: [] },
921 });
922 const payloads = useRetainedContextPayloads(targetKey);
923 const draft = drafts[targetKey]!;
924 useEffect(() => {
925 current = draft;
926 retained = payloads;
927 });
928 const editorProps = {
929 draftKey: targetKey,
930 editorRef,
931 value: draft.value,
932 cursor: 0,
933 contextRecords: new Map(
934 draft.files.map((entry) => [
935 fileContextReference(entry).contextId,
936 { kind: "file" as const, record: entry },
937 ]),
938 ),
939 skills: [],
940 disabled: false,
941 placeholder: "",
942 onChange: (value, _cursor, _expandedCursor, _adjacent, contextIds) => {
943 const changes = reconcileAttachmentContextReferences({
944 referencedContextIds: new Set(contextIds),
945 files: draft.files,
946 images: [],
947 previewAnnotations: [],
948 retained: payloads,
949 });
950 setDrafts({
951 ...drafts,
952 [targetKey]: {
953 value,
954 files: [
955 ...draft.files.filter((entry) => !changes.filesToRemove.includes(entry.id)),
956 ...changes.filesToRestore,
957 ],
958 },
959 });
960 },
961 onPaste: () => {},
962 } satisfies ComposerPromptEditorProps;
963 return createElement(ComposerPromptEditor, editorProps);
964 }
965
966 await using stack = new AsyncDisposableStack();
967 const screen = stack.use(await render(createElement(Composer, { targetKey: "a" })));
968 const editor = () => editorIn(screen.container);
969 const environment = stack.move();
970 return Object.assign(screen, {
971 [Symbol.asyncDispose]: () => environment.disposeAsync(),
972 initialValue,
973 show: (targetKey: string) => screen.rerender(createElement(Composer, { targetKey })),
974 editor,
975 draft: () => current,
976 retained: () => retained,
977 deleteDraft: async () => {
978 await act(async () => {
979 const currentEditor = editor();
980 currentEditor.view.dispatch(
981 currentEditor.state.tr.delete(1, currentEditor.state.doc.content.size - 1),
982 );
983 });
984 },
985 undo: async () => {
986 await act(async () => {
987 editor().commands.undo();
988 });
989 },
990 });
991 }
992
993 it("restores a deleted chip and its file bytes on same-draft undo, then releases them on unmount", async () => {
994 await using composer = await mountComposer();
995 await composer.deleteDraft();
996 expect(composer.draft()).toEqual({ value: "", files: [] });
997 const retained = composer.retained();
998 expect(retained.files.get(fileContextReference(file).contextId)?.file).toBe(file.file);
999
1000 await composer.show("a");
1001 await composer.undo();
1002 expect(serializeEditorDoc(composer.editor().state.doc).value).toBe(composer.initialValue);
1003 expect(composer.draft()).toEqual({ value: composer.initialValue, files: [file] });
1004 expect(composer.draft().files[0]?.file).toBe(file.file);
1005
1006 await composer.deleteDraft();
1007 await composer.unmount();
1008 expect(retained.files.size).toBe(0);
1009 });
1010
1011 it.each(["", "Draft B"])(
1012 "releases deleted payloads and prevents undo into the previous draft when switching to %j",
1013 async (destinationValue) => {
1014 await using composer = await mountComposer(destinationValue);
1015 await composer.deleteDraft();
1016 expect(composer.draft()).toEqual({ value: "", files: [] });
1017 const retained = composer.retained();
1018 expect(retained.files.get(fileContextReference(file).contextId)?.file).toBe(file.file);
1019
1020 await composer.show("b");
1021 expect(retained.files.size).toBe(0);
1022 await composer.undo();
1023 expect(serializeEditorDoc(composer.editor().state.doc).value).toBe(destinationValue);
1024 expect(composer.draft()).toEqual({ value: destinationValue, files: [] });
1025
1026 await composer.show("a");
1027 await composer.undo();
1028 expect(serializeEditorDoc(composer.editor().state.doc).value).toBe("");
1029 expect(composer.draft()).toEqual({ value: "", files: [] });
1030 },
1031 );
1032 });
1033
1034 describe("an Arabic line", () => {
1035 async function focusEnd(editor: Editor) {
1036 // ProseMirror rewrites the DOM caret 20ms after focus. Run that now, or it
1037 // can undo the first arrow key before ProseMirror reads the native move.
1038 using _timers = fakeTimers();
1039 await act(async () => {
1040 editor.commands.focus("end");
1041 });
1042 await vi.waitFor(() => expect(document.activeElement).toBe(editor.view.dom));
1043 vi.runOnlyPendingTimers();
1044 }
1045
1046 it("walks back through inline code and its backticks with ArrowRight", async () => {
1047 const value = "اكتب `sumBy` الان";
1048 await using screen = await mountEditor(value);
1049 const { editor } = screen;
1050 await focusEnd(editor);
1051 const offset = () => {
1052 const map = serializeEditorDoc(editor.state.doc);
1053 return flatToMarkdown(map, pmToFlat(map, editor.state.selection.head));
1054 };
1055 const visited = [offset()];
1056 let sawSource = false;
1057 while (visited.at(-1)! > "اكتب".length) {
1058 const before = visited.at(-1)!;
1059 await userEvent.keyboard("{ArrowRight}");
1060 await vi.waitFor(() => expect(offset()).toBe(before - 1));
1061 sawSource ||= editor.state.doc.textContent === value;
1062 visited.push(offset());
1063 }
1064 expect(sawSource).toBe(true);
1065 expect(textWithMark(editor, "code")).toEqual(["sumBy"]);
1066 });
1067
1068 it("shows the backticks on either side of inline code it is editing", async () => {
1069 await using screen = await mountEditor("اكتب `sumBy` الان");
1070 const { editor } = screen;
1071 await act(async () => {
1072 editor.commands.setTextSelection("اكتب su".length + 1);
1073 });
1074 const code = editor.view.dom.querySelector("code")!;
1075 const text = [...code.childNodes].find((node) => node instanceof Text)!;
1076 expect(text.data).toBe("`sumBy`");
1077 const rect = (from: number, to: number) => {
1078 const range = document.createRange();
1079 range.setStart(text, from);
1080 range.setEnd(text, to);
1081 return range.getBoundingClientRect();
1082 };
1083 const [open, word, close] = [rect(0, 1), rect(1, 6), rect(6, 7)];
1084 expect(open.right).toBeLessThanOrEqual(word.left + 1);
1085 expect(close.left).toBeGreaterThanOrEqual(word.right - 1);
1086 });
1087
1088 it("starts the next line on the right", async () => {
1089 await using screen = await mountEditor("اكتب الدالة");
1090 const { editor } = screen;
1091 await focusEnd(editor);
1092 await userEvent.keyboard("{Shift>}{Enter}{/Shift}");
1093 await vi.waitFor(() => expect(editor.state.doc.childCount).toBe(2));
1094 const box = editor.view.dom.getBoundingClientRect();
1095 expect(editor.view.coordsAtPos(editor.state.selection.head).left).toBeGreaterThan(
1096 box.left + box.width / 2,
1097 );
1098 });
1099 });
1100
1101 it.each([true, false])(
1102 "restores the caret after dictation unlocks the editor (rich text: %s)",
1103 async (richTextEnabled) => {
1104 const ui = (disabled: boolean) => (
1105 <Composer value="Draft" richTextEnabled={richTextEnabled} skills={[]} disabled={disabled} />
1106 );
1107 await using screen = await render(ui(false));
1108 const editor = editorIn(screen.container);
1109 await act(() => {
1110 editor.commands.setTextSelection(3);
1111 editor.view.focus();
1112 });
1113 await screen.rerender(ui(true));
1114 await screen.rerender(ui(false));
1115 await vi.waitFor(() => {
1116 expect(editor.view.hasFocus()).toBe(true);
1117 expect(editor.view.dom.contains(window.getSelection()?.anchorNode ?? null)).toBe(true);
1118 });
1119 await userEvent.keyboard("X");
1120 await vi.waitFor(() => expect(editor.getText()).toBe("DrXaft"));
1121 },
1122 );
1123
1124 it.each(["other field", "document body"])(
1125 "does not reclaim focus when it moves away during dictation and ends on the %s",
1126 async (focusTarget) => {
1127 const ui = (disabled: boolean) => (
1128 <>
1129 <Composer value="Draft" richTextEnabled skills={[]} disabled={disabled} />
1130 <input aria-label="Other field" />
1131 </>
1132 );
1133 await using screen = await render(ui(false));
1134 const editor = editorIn(screen.container);
1135 await act(() => editor.view.focus());
1136 await screen.rerender(ui(true));
1137 const other = screen.container.querySelector("input")!;
1138 other.focus();
1139 await vi.waitFor(() => expect(document.activeElement).toBe(other));
1140 if (focusTarget === "document body") other.blur();
1141 await screen.rerender(ui(false));
1142 await vi.waitFor(() =>
1143 expect(document.activeElement).toBe(focusTarget === "document body" ? document.body : other),
1144 );
1145 },
1146 );