Skip to content

Commit 9cd7a04

Browse files
fix(web): sending from an empty citation comment clears the composer (#33440)
Co-authored-by: Claude Opus 5.5 <[email protected]>
1 parent d290c1f commit 9cd7a04

3 files changed

Lines changed: 96 additions & 20 deletions

File tree

‎apps/web/src/components/ComposerPromptEditorTiptap.citationDraft.browser.test.tsx‎

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,9 +31,11 @@ const promptBefore = `See ${serializeAssistantCitation(citation)} `;
3131
function Composer({
3232
question,
3333
editorRef,
34+
send = "clears",
3435
}: {
3536
question: boolean;
3637
editorRef: React.RefObject<ComposerPromptEditorHandle | null>;
38+
send?: "clears" | "blocked" | "refusedLater";
3739
}) {
3840
const [prompt, setPrompt] = useState(promptBefore);
3941
const [answer, setAnswer] = useState("");
@@ -61,6 +63,11 @@ function Composer({
6163
onCitationDraftSave={(replacedValue, savedValue) => {
6264
if (replacedValue === prompt) setPrompt(savedValue);
6365
}}
66+
onCitationSubmitAndSend={() => {
67+
if (send === "blocked") return false;
68+
if (send === "clears") setPrompt("");
69+
return true;
70+
}}
6471
onPaste={() => {}}
6572
/>
6673
</>
@@ -97,3 +104,58 @@ it("keeps an unsaved citation comment when a question takes the composer", async
97104
);
98105
await expect.element(page.getByLabelText("Edit citation comment")).toBeInTheDocument();
99106
});
107+
108+
it("clears the sent prompt when an empty citation comment sends it", async () => {
109+
const editorRef = createRef<ComposerPromptEditorHandle>();
110+
await using screen = await render(<Composer question={false} editorRef={editorRef} />);
111+
112+
const sourceAnchor = findAssistantCitationSourceAnchor(document, citation);
113+
if (!sourceAnchor) throw new Error("Citation source did not resolve");
114+
await act(async () =>
115+
editorRef.current?.requestCitationComment({
116+
previousValue: "See ",
117+
value: promptBefore,
118+
citationStart: "See ".length,
119+
sourceAnchor,
120+
insertedSpaces: { before: false, after: true },
121+
}),
122+
);
123+
const comment = page.getByLabelText("Comment on selected text");
124+
await expect.element(comment).toHaveFocus();
125+
await userEvent.keyboard("{Control>}{Enter}{/Control}");
126+
127+
await expect.element(comment).not.toBeInTheDocument();
128+
await expect.element(page.getByTestId("composer-editor")).toHaveFocus();
129+
await expect.element(screen.getByRole("status")).toHaveAttribute("data-prompt", "");
130+
});
131+
132+
it.each(["blocked", "refusedLater"] as const)(
133+
"keeps the caret after the citation when save-and-send is %s",
134+
async (send) => {
135+
const editorRef = createRef<ComposerPromptEditorHandle>();
136+
await using screen = await render(
137+
<Composer question={false} editorRef={editorRef} send={send} />,
138+
);
139+
140+
const sourceAnchor = findAssistantCitationSourceAnchor(document, citation);
141+
if (!sourceAnchor) throw new Error("Citation source did not resolve");
142+
await act(async () =>
143+
editorRef.current?.requestCitationComment({
144+
previousValue: "See ",
145+
value: promptBefore,
146+
citationStart: "See ".length,
147+
sourceAnchor,
148+
insertedSpaces: { before: false, after: true },
149+
}),
150+
);
151+
const comment = page.getByLabelText("Comment on selected text");
152+
await expect.element(comment).toHaveFocus();
153+
await userEvent.keyboard("{Control>}{Enter}{/Control}");
154+
await expect.element(comment).not.toBeInTheDocument();
155+
await userEvent.keyboard("x");
156+
157+
await expect
158+
.element(screen.getByRole("status"))
159+
.toHaveAttribute("data-prompt", `See ${serializeAssistantCitation(citation)}x `);
160+
},
161+
);

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

Lines changed: 27 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ import {
2121
Plugin,
2222
PluginKey,
2323
TextSelection,
24+
type Transaction,
2425
} from "@tiptap/pm/state";
2526
import { Decoration, DecorationSet, type EditorView } from "@tiptap/pm/view";
2627
import type { NodeType, ResolvedPos } from "@tiptap/pm/model";
@@ -186,7 +187,7 @@ export interface ComposerPromptEditorProps {
186187
onPageScrollKeyDown?: (key: "PageUp" | "PageDown") => void;
187188
onPageScrollKeyUp?: (key: string) => void;
188189
onPageScrollRelease?: () => void;
189-
onCitationSubmitAndSend?: () => void;
190+
onCitationSubmitAndSend?: () => boolean;
190191
/** Saves unsaved citation text into replacedValue when a controlled rewrite replaces the document. */
191192
onCitationDraftSave?: (replacedValue: string, savedValue: string) => void;
192193
onPaste: React.ClipboardEventHandler<HTMLElement>;
@@ -213,12 +214,12 @@ const ComposerCitationCommentContext = createContext<{
213214
openComment: OpenCitationComment | null;
214215
onOpenChange: (citeKey: string, open: boolean) => void;
215216
onDraftChange: (citeKey: string, comment: string) => void;
216-
onSubmitAndSend: () => void;
217+
onSubmitAndSend: () => boolean;
217218
}>({
218219
openComment: null,
219220
onOpenChange: () => {},
220221
onDraftChange: () => {},
221-
onSubmitAndSend: () => {},
222+
onSubmitAndSend: () => false,
222223
});
223224

224225
const RichComposerSkillsContext = createContext<ReadonlyArray<ServerProviderSkill>>([]);
@@ -477,13 +478,23 @@ function ComposerCitationNodeView({ node, editor, getPos }: NodeViewProps) {
477478
editor.chain().focus().deleteRange({ from, to }).run();
478479
};
479480

481+
const sentRef = useRef(false);
480482
const onRestoreFocus = () => {
483+
const sent = sentRef.current;
484+
sentRef.current = false;
481485
if (!editor.isEditable) return;
482486
const pos = nodePos();
483-
if (pos === null) return;
484-
const current = editor.state.doc.nodeAt(pos);
485-
if (!current || current.type.name !== "composer-citation") return;
486-
editor.commands.focus(pos + current.nodeSize);
487+
const current = pos === null ? null : editor.state.doc.nodeAt(pos);
488+
if (pos === null || current?.type.name !== "composer-citation") {
489+
if (sent) editor.view.focus();
490+
return;
491+
}
492+
// The send's controlled rewrite may still be pending; emitting this caret move would restore the old prompt.
493+
editor
494+
.chain()
495+
.setMeta(SILENT_SELECTION_META, sent)
496+
.focus(pos + current.nodeSize)
497+
.run();
487498
};
488499

489500
return (
@@ -525,7 +536,7 @@ function ComposerCitationNodeView({ node, editor, getPos }: NodeViewProps) {
525536
onDraftChange: (comment) => commentContext.onDraftChange(citeKey, comment),
526537
onSaveAndSend: (comment) => {
527538
if (!onSaveComment(comment)) return false;
528-
commentContext.onSubmitAndSend();
539+
sentRef.current = commentContext.onSubmitAndSend();
529540
return true;
530541
},
531542
onRestoreFocus,
@@ -729,6 +740,8 @@ function chipSelectionDecorations({ doc, selection }: EditorState): DecorationSe
729740

730741
type TiptapEditor = NonNullable<ReturnType<typeof useEditor>>;
731742

743+
const SILENT_SELECTION_META = "composerSilentSelection";
744+
732745
function replaceSkillChips(
733746
editor: TiptapEditor,
734747
replacements: ReturnType<typeof skillChipReplacements>,
@@ -995,10 +1008,10 @@ function ComposerPromptEditorTiptapInner(
9951008
onDraftChange: (nodeKey: string, comment: string) => {
9961009
citationDraftRef.current = { key: nodeKey, comment };
9971010
},
998-
onSubmitAndSend: onCitationSubmitAndSend ?? (() => {}),
1011+
onSubmitAndSend: onCitationSubmitAndSend ?? (() => false),
9991012
};
10001013

1001-
const handleEditorChange = (updated: TiptapEditor) => {
1014+
const handleEditorChange = (updated: TiptapEditor, transaction: Transaction) => {
10021015
const map = serializeEditorDoc(updated.state.doc);
10031016
const contextIds = literalText ? [] : [...map.contextIds];
10041017
const { from, to } = updated.state.selection;
@@ -1025,7 +1038,7 @@ function ComposerPromptEditorTiptapInner(
10251038
previousSnapshot.contextIds.length === contextIds.length &&
10261039
previousSnapshot.contextIds.every((id, index) => id === contextIds[index])
10271040
);
1028-
if (isApplyingControlledUpdateRef.current) return;
1041+
if (isApplyingControlledUpdateRef.current || transaction.getMeta(SILENT_SELECTION_META)) return;
10291042
if (!snapshotChanged) {
10301043
if (didComposerSelectionChangeVisibly(previousSelectionRange, nextSelectionRange)) {
10311044
readCallbacks().onVisibleSelectionChange?.();
@@ -1459,10 +1472,10 @@ function ComposerPromptEditorTiptapInner(
14591472
return;
14601473
}
14611474
}
1462-
handleEditorChange(updated);
1475+
handleEditorChange(updated, transaction);
14631476
},
1464-
onSelectionUpdate: ({ editor: updated }) => {
1465-
handleEditorChange(updated);
1477+
onSelectionUpdate: ({ editor: updated, transaction }) => {
1478+
handleEditorChange(updated, transaction);
14661479
},
14671480
},
14681481
[],

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

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2096,15 +2096,15 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
20962096
if (voiceInputActive) {
20972097
event?.preventDefault();
20982098
submitAfterDictation(() => submitComposerRef.current(dispatchMode, submissionIntent));
2099-
return;
2099+
return false;
21002100
}
21012101
if (
21022102
noProviderAvailable ||
21032103
isSendDisabled ||
21042104
!readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)
21052105
) {
21062106
event?.preventDefault();
2107-
return;
2107+
return false;
21082108
}
21092109
// A send while a pasted image is still compressing would strand that image:
21102110
// the turn snapshot wouldn't include it, and it would surface in the *next*
@@ -2116,7 +2116,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
21162116
title: "Still compressing a pasted image.",
21172117
description: "Send again once its thumbnail appears.",
21182118
});
2119-
return;
2119+
return false;
21202120
}
21212121
if (pendingDraftWork.has(attachmentTargetKey)) {
21222122
event?.preventDefault();
@@ -2125,7 +2125,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
21252125
title: "Still bringing attached context into this message.",
21262126
description: "Send again once its chip resolves.",
21272127
});
2128-
return;
2128+
return false;
21292129
}
21302130
const submission = submitComposerDraft({
21312131
prompt: promptRef.current,
@@ -2148,11 +2148,12 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
21482148
},
21492149
});
21502150
setComposerSubmissionError(submission.validationMessage);
2151-
if (!submission.didDispatch) return;
2151+
if (!submission.didDispatch) return false;
21522152
onTypingGuardSend();
21532153
if (shouldBlurMobileComposerOnSubmit()) {
21542154
blurMobileComposerAfterSend();
21552155
}
2156+
return true;
21562157
};
21572158
const submitComposerStable = useStableCallback(submitComposer);
21582159
// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- publishes the committed submission handler to the asynchronous dictation completion
@@ -2201,7 +2202,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
22012202
};
22022203
const handleSubmitMessageStable = useStableCallback(handleSubmitMessage);
22032204
const submitCitationAndSend = () => {
2204-
submitComposer(
2205+
return submitComposer(
22052206
undefined,
22062207
resolveComposerDispatchMode({
22072208
running: phase === "running",

0 commit comments

Comments
 (0)