Skip to content

Commit bb03435

Browse files
fix(web): keep composer undo history scoped without losing focus
1 parent c6d4d65 commit bb03435

12 files changed

Lines changed: 383 additions & 99 deletions
Lines changed: 198 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,198 @@
1+
// @vitest-environment jsdom
2+
import type { Editor } from "@tiptap/core";
3+
import { closeHistory } from "@tiptap/pm/history";
4+
import { act, createRef, useImperativeHandle, useState } from "react";
5+
import { createRoot, type Root } from "react-dom/client";
6+
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
7+
8+
import { editableOwnsUndo } from "../lib/editableFocus";
9+
import { formatInlineContextReference } from "../lib/composerContextReferences";
10+
import { ComposerPromptEditor, type ComposerPromptEditorHandle } from "./ComposerPromptEditor";
11+
12+
let root: Root;
13+
let container: HTMLDivElement;
14+
const controls = createRef<{ setDraft: (value: string, thread?: string) => void }>();
15+
function setDraft(value: string, thread?: string) {
16+
if (!controls.current) throw new Error("Controlled composer missing");
17+
controls.current.setDraft(value, thread);
18+
}
19+
const editorRef = createRef<ComposerPromptEditorHandle>();
20+
21+
beforeEach(() => {
22+
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
23+
container = document.createElement("div");
24+
document.body.append(container);
25+
root = createRoot(container);
26+
});
27+
28+
afterEach(async () => {
29+
await act(async () => root.unmount());
30+
container.remove();
31+
vi.unstubAllGlobals();
32+
});
33+
34+
function ControlledComposer() {
35+
const [draft, updateDraft] = useState({ value: "", thread: "a" });
36+
useImperativeHandle(
37+
controls,
38+
() => ({
39+
setDraft: (value, thread) =>
40+
updateDraft((current) => ({ value, thread: thread ?? current.thread })),
41+
}),
42+
[],
43+
);
44+
return (
45+
<ComposerPromptEditor
46+
historyScopeKey={draft.thread}
47+
value={draft.value}
48+
cursor={draft.value.length}
49+
contextRecords={new Map()}
50+
skills={[]}
51+
disabled={false}
52+
placeholder="Prompt"
53+
onChange={(value) => updateDraft((current) => ({ ...current, value }))}
54+
onPaste={() => {}}
55+
editorRef={editorRef}
56+
/>
57+
);
58+
}
59+
60+
function editor() {
61+
const element = container.querySelector<HTMLElement>('[data-testid="composer-editor"]');
62+
if (!element) throw new Error("Composer editor missing");
63+
// Tiptap attaches the live instance to its editable DOM element.
64+
return (element as HTMLElement & { editor: Editor }).editor;
65+
}
66+
67+
async function mount() {
68+
await act(async () => root.render(<ControlledComposer />));
69+
// jsdom has no layout; keep focus/selection real without measuring its caret.
70+
editor().setOptions({
71+
editorProps: { ...editor().options.editorProps, handleScrollToSelection: () => true },
72+
});
73+
}
74+
75+
async function edit(run: (editor: Editor) => void) {
76+
await act(async () => run(editor()));
77+
}
78+
79+
function ownsUndo() {
80+
return editableOwnsUndo(editor().view.dom);
81+
}
82+
83+
describe("controlled composer undo ownership", () => {
84+
it("lets the empty composer yield after sending, without restoring sent text", async () => {
85+
await mount();
86+
await edit((current) => current.commands.insertContent("sent prompt"));
87+
await edit((current) => current.view.dispatch(closeHistory(current.state.tr)));
88+
await act(async () => setDraft(""));
89+
expect(editorRef.current?.readSnapshot().value).toBe("");
90+
expect(ownsUndo()).toBe(false);
91+
expect(editor().commands.undo()).toBe(false);
92+
expect(editorRef.current?.readSnapshot().value).toBe("");
93+
});
94+
95+
it("resets an already empty editor when an attachment-only send clears the draft", async () => {
96+
await mount();
97+
await edit((current) => current.commands.insertContent("deleted draft"));
98+
await edit((current) => current.view.dispatch(closeHistory(current.state.tr)));
99+
await edit((current) => current.commands.selectAll());
100+
await edit((current) => current.commands.deleteSelection());
101+
expect(ownsUndo()).toBe(true);
102+
// ChatComposer.resetCursorState uses this when send clears an already
103+
// empty prompt, which causes no controlled value change.
104+
await act(async () => {
105+
setDraft("");
106+
editorRef.current?.resetUndoHistory();
107+
});
108+
expect(ownsUndo()).toBe(false);
109+
expect(editor().commands.undo()).toBe(false);
110+
expect(editorRef.current?.readSnapshot().value).toBe("");
111+
});
112+
113+
it("preserves user deletion and yields after undo history is exhausted", async () => {
114+
await mount();
115+
await edit((current) => current.commands.insertContent("draft"));
116+
await edit((current) => current.view.dispatch(closeHistory(current.state.tr)));
117+
await edit((current) => current.commands.selectAll());
118+
await edit((current) => current.commands.deleteSelection());
119+
expect(editorRef.current?.readSnapshot().value).toBe("");
120+
expect(ownsUndo()).toBe(true);
121+
await edit((current) => current.commands.undo());
122+
expect(editorRef.current?.readSnapshot().value).toBe("draft");
123+
await edit((current) => current.commands.undo());
124+
expect(editorRef.current?.readSnapshot().value).toBe("");
125+
expect(ownsUndo()).toBe(false);
126+
});
127+
128+
it("keeps a new thread's draft separate from the old thread's history", async () => {
129+
await mount();
130+
await edit((current) => current.commands.insertContent("thread a draft"));
131+
await act(async () => setDraft("thread b draft", "b"));
132+
await edit((current) => current.view.dispatch(closeHistory(current.state.tr)));
133+
await edit((current) => current.commands.selectAll());
134+
await edit((current) => current.commands.deleteSelection());
135+
expect(ownsUndo()).toBe(true);
136+
await edit((current) => current.commands.undo());
137+
expect(editorRef.current?.readSnapshot().value).toBe("thread b draft");
138+
expect(editor().commands.undo()).toBe(false);
139+
await act(async () => setDraft("", "a"));
140+
expect(ownsUndo()).toBe(false);
141+
expect(editor().commands.undo()).toBe(false);
142+
expect(editorRef.current?.readSnapshot().value).toBe("");
143+
});
144+
145+
it("restores a chip-only draft after its editor deletion", async () => {
146+
await mount();
147+
const chip = formatInlineContextReference({
148+
kind: "file",
149+
contextId: "file_one",
150+
label: "one.ts",
151+
});
152+
await act(async () => setDraft(chip));
153+
expect(editorRef.current?.readSnapshot().contextIds).toEqual(["file_one"]);
154+
await edit((current) => current.view.dispatch(closeHistory(current.state.tr)));
155+
await edit((current) => current.commands.selectAll());
156+
await edit((current) => current.commands.deleteSelection());
157+
expect(editorRef.current?.readSnapshot().value).toBe("");
158+
expect(ownsUndo()).toBe(true);
159+
await edit((current) => current.commands.undo());
160+
expect(editorRef.current?.readSnapshot().contextIds).toEqual(["file_one"]);
161+
});
162+
163+
it.each(["same draft", ""])(
164+
"keeps composer focus while isolating equal-text thread scopes (%j)",
165+
async (value) => {
166+
await mount();
167+
await edit((current) => current.commands.insertContent("same draft"));
168+
if (value === "") {
169+
await edit((current) => current.commands.selectAll());
170+
await edit((current) => current.commands.deleteSelection());
171+
}
172+
const focusedEditor = editor().view.dom;
173+
await act(async () => focusedEditor.focus());
174+
expect(document.activeElement).toBe(focusedEditor);
175+
await act(async () => setDraft(value, "b"));
176+
expect(document.activeElement).toBe(focusedEditor);
177+
expect(editorRef.current?.readSnapshot().value).toBe(value);
178+
expect(editor().commands.undo()).toBe(false);
179+
},
180+
);
181+
182+
it("keeps new user history undoable after a send-clear", async () => {
183+
await mount();
184+
await edit((current) => current.commands.insertContent("sent prompt"));
185+
await act(async () => setDraft(""));
186+
await edit((current) => current.commands.insertContent("new draft"));
187+
await edit((current) => current.view.dispatch(closeHistory(current.state.tr)));
188+
await edit((current) => current.commands.selectAll());
189+
await edit((current) => current.commands.deleteSelection());
190+
expect(ownsUndo()).toBe(true);
191+
await edit((current) => current.commands.undo());
192+
expect(editorRef.current?.readSnapshot().value).toBe("new draft");
193+
await edit((current) => current.commands.undo());
194+
expect(editorRef.current?.readSnapshot().value).toBe("");
195+
expect(ownsUndo()).toBe(false);
196+
expect(editor().commands.undo()).toBe(false);
197+
});
198+
});

‎apps/web/src/components/ComposerPromptEditorTiptap.tsx‎

Lines changed: 34 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import { ReactNodeViewRenderer, NodeViewWrapper, type NodeViewProps } from "@tip
44
import StarterKit from "@tiptap/starter-kit";
55
import { type Node as ProseMirrorNode } from "@tiptap/pm/model";
66
import { splitBlockKeepMarks } from "@tiptap/pm/commands";
7+
import { history, undoDepth } from "@tiptap/pm/history";
78
import { Plugin, PluginKey, TextSelection } from "@tiptap/pm/state";
89
import { Decoration, DecorationSet } from "@tiptap/pm/view";
910
import type {
@@ -58,6 +59,7 @@ import {
5859
} from "~/composer-rich-text-doc";
5960
import { collectInlineContextIds } from "~/lib/composerContextReferences";
6061
import { cn, isMacPlatform } from "~/lib/utils";
62+
import { registerEditableUndoHistory } from "~/lib/editableFocus";
6163
import { basenameOfPath } from "~/pierre-icons";
6264
import { FileTagChipContent } from "./chat/FileTagChip";
6365
import { SkillChipIcon } from "./chat/SkillInlineText";
@@ -79,6 +81,7 @@ import { didComposerSelectionChangeVisibly } from "./composerSelection";
7981
import type { ComposerDraftContextRecords } from "./composerContextPresentation";
8082

8183
export interface ComposerPromptEditorHandle {
84+
resetUndoHistory: () => void;
8285
focus: () => void;
8386
focusAt: (cursor: number) => void;
8487
focusAtEnd: () => void;
@@ -100,6 +103,8 @@ export interface ComposerPromptEditorHandle {
100103
}
101104

102105
export interface ComposerPromptEditorProps {
106+
/** Draft identity: editor undo must never cross thread or draft boundaries. */
107+
historyScopeKey: string;
103108
value: string;
104109
cursor: number;
105110
/**
@@ -572,17 +577,22 @@ const ComposerMarkersExtension = Extension.create({
572577

573578
type TiptapEditor = NonNullable<ReturnType<typeof useEditor>>;
574579

580+
function resetComposerUndoHistory(editor: TiptapEditor) {
581+
editor.unregisterPlugin("history");
582+
editor.registerPlugin(history());
583+
}
584+
575585
export function ComposerPromptEditorTiptap(props: ComposerPromptEditorProps) {
576-
// Extensions are creation-time: flipping the setting remounts the editor.
577-
// Both halves initialize from the controlled Markdown value, so the draft
578-
// survives the flip.
586+
// Extensions are creation-time: toggling styling remounts from the
587+
// controlled Markdown value. Thread changes keep the focused editor alive.
579588
return (
580589
<ComposerPromptEditorTiptapInner key={props.richTextEnabled ? "rich" : "plain"} {...props} />
581590
);
582591
}
583592

584593
function ComposerPromptEditorTiptapInner(props: ComposerPromptEditorProps) {
585594
const {
595+
historyScopeKey,
586596
value,
587597
cursor,
588598
richTextEnabled,
@@ -666,6 +676,7 @@ function ComposerPromptEditorTiptapInner(props: ComposerPromptEditorProps) {
666676
const selectionRangeRef = useRef({ start: initialExpandedCursor, end: initialExpandedCursor });
667677
const isApplyingControlledUpdateRef = useRef(false);
668678
const hasAppliedControlledSelectionRef = useRef(false);
679+
const historyScopeRef = useRef(historyScopeKey);
669680
const citationRequestRef = useRef<ComposerCitationCommentRequest | null>(null);
670681
const [openCitation, setOpenCitation] = useState<OpenCitationComment | null>(null);
671682
const [isEmpty, setIsEmpty] = useState(value.length === 0);
@@ -1041,6 +1052,11 @@ function ComposerPromptEditorTiptapInner(props: ComposerPromptEditorProps) {
10411052
[],
10421053
);
10431054

1055+
useEffect(() => {
1056+
if (!editor) return;
1057+
return registerEditableUndoHistory(editor.view.dom, () => undoDepth(editor.state) > 0);
1058+
}, [editor]);
1059+
10441060
useEffect(() => {
10451061
editor?.setEditable(!disabled);
10461062
}, [disabled, editor]);
@@ -1084,12 +1100,15 @@ function ComposerPromptEditorTiptapInner(props: ComposerPromptEditorProps) {
10841100
// Controlled value/cursor from the store (history recall, chip insertion…).
10851101
useLayoutEffect(() => {
10861102
if (!editor) return;
1103+
const historyScopeChanged = historyScopeRef.current !== historyScopeKey;
1104+
historyScopeRef.current = historyScopeKey;
10871105
const initialSelection = !hasAppliedControlledSelectionRef.current;
10881106
hasAppliedControlledSelectionRef.current = true;
10891107
const normalizedCursor = clampCollapsedComposerCursor(value, cursor);
10901108
const previousSnapshot = snapshotRef.current;
10911109
if (
10921110
!initialSelection &&
1111+
!historyScopeChanged &&
10931112
previousSnapshot.value === value &&
10941113
previousSnapshot.cursor === normalizedCursor
10951114
) {
@@ -1109,7 +1128,8 @@ function ComposerPromptEditorTiptapInner(props: ComposerPromptEditorProps) {
11091128
setIsEmpty(value.length === 0);
11101129
const rootElement = editor.view.dom;
11111130
const isFocused = Boolean(rootElement && document.activeElement === rootElement);
1112-
if (!initialSelection && previousSnapshot.value === value && !isFocused) return;
1131+
if (!initialSelection && !historyScopeChanged && previousSnapshot.value === value && !isFocused)
1132+
return;
11131133

11141134
isApplyingControlledUpdateRef.current = true;
11151135
const pendingCitation =
@@ -1119,6 +1139,11 @@ function ComposerPromptEditorTiptapInner(props: ComposerPromptEditorProps) {
11191139
emitUpdate: false,
11201140
});
11211141
}
1142+
// A different thread or controlled clear starts fresh history, after its
1143+
// content is applied. User deletion has already updated snapshotRef.
1144+
if (historyScopeChanged || (previousSnapshot.value !== value && value === "")) {
1145+
resetComposerUndoHistory(editor);
1146+
}
11221147
const map = serializeEditorDoc(editor.state.doc);
11231148
const flat = collapsedToFlat(map, normalizedCursor);
11241149
editor.commands.setTextSelection(flatToPm(map, flat));
@@ -1146,7 +1171,7 @@ function ComposerPromptEditorTiptapInner(props: ComposerPromptEditorProps) {
11461171
queueMicrotask(() => {
11471172
isApplyingControlledUpdateRef.current = false;
11481173
});
1149-
}, [cursor, editor, richText, skillLabelFor, value]);
1174+
}, [cursor, editor, historyScopeKey, richText, skillLabelFor, value]);
11501175

11511176
const focusAt = useCallback(
11521177
(nextCursor: number) => {
@@ -1186,6 +1211,10 @@ function ComposerPromptEditorTiptapInner(props: ComposerPromptEditorProps) {
11861211
useImperativeHandle(
11871212
editorRef,
11881213
() => ({
1214+
resetUndoHistory: () => {
1215+
if (!editor) return;
1216+
resetComposerUndoHistory(editor);
1217+
},
11891218
focus: () => {
11901219
focusAt(snapshotRef.current.cursor);
11911220
},

‎apps/web/src/components/chat/ChatComposer.tsx‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5965,6 +5965,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
59655965
detectTrigger?: boolean;
59665966
}) => {
59675967
const promptForState = options?.prompt ?? promptRef.current;
5968+
if (promptForState === "") composerEditorRef.current?.resetUndoHistory();
59685969
const cursor = clampCollapsedComposerCursor(promptForState, options?.cursor ?? 0);
59695970
setComposerHighlightedItemId(null);
59705971
setComposerCursor(cursor);
@@ -6845,6 +6846,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
68456846
) : null}
68466847
<ComposerContextActionsContext value={composerContextActions}>
68476848
<ComposerPromptEditor
6849+
historyScopeKey={composerTargetKey(routeThreadRef)}
68486850
editorRef={composerEditorRef}
68496851
richTextEnabled={settings.composerRichTextEnabled}
68506852
value={

‎apps/web/src/components/settings/SettingsFontPreviews.tsx‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@ export function PromptFontPreview() {
3939
return (
4040
<div className="mt-1 mb-2 rounded-lg border border-border bg-background px-3 py-2">
4141
<ComposerPromptEditor
42+
historyScopeKey="font-preview"
4243
editorRef={editorRef}
4344
value={prompt}
4445
cursor={cursor}

0 commit comments

Comments
 (0)