Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,11 @@ const promptBefore = `See ${serializeAssistantCitation(citation)} `;
function Composer({
question,
editorRef,
send = "clears",
}: {
question: boolean;
editorRef: React.RefObject<ComposerPromptEditorHandle | null>;
send?: "clears" | "blocked" | "refusedLater";
}) {
const [prompt, setPrompt] = useState(promptBefore);
const [answer, setAnswer] = useState("");
Expand Down Expand Up @@ -61,6 +63,11 @@ function Composer({
onCitationDraftSave={(replacedValue, savedValue) => {
if (replacedValue === prompt) setPrompt(savedValue);
}}
onCitationSubmitAndSend={() => {
if (send === "blocked") return false;
if (send === "clears") setPrompt("");
return true;
}}
onPaste={() => {}}
/>
</>
Expand Down Expand Up @@ -97,3 +104,58 @@ it("keeps an unsaved citation comment when a question takes the composer", async
);
await expect.element(page.getByLabelText("Edit citation comment")).toBeInTheDocument();
});

it("clears the sent prompt when an empty citation comment sends it", async () => {
const editorRef = createRef<ComposerPromptEditorHandle>();
await using screen = await render(<Composer question={false} editorRef={editorRef} />);

const sourceAnchor = findAssistantCitationSourceAnchor(document, citation);
if (!sourceAnchor) throw new Error("Citation source did not resolve");
await act(async () =>
editorRef.current?.requestCitationComment({
previousValue: "See ",
value: promptBefore,
citationStart: "See ".length,
sourceAnchor,
insertedSpaces: { before: false, after: true },
}),
);
const comment = page.getByLabelText("Comment on selected text");
await expect.element(comment).toHaveFocus();
await userEvent.keyboard("{Control>}{Enter}{/Control}");

await expect.element(comment).not.toBeInTheDocument();
await expect.element(page.getByTestId("composer-editor")).toHaveFocus();
await expect.element(screen.getByRole("status")).toHaveAttribute("data-prompt", "");
});

it.each(["blocked", "refusedLater"] as const)(
"keeps the caret after the citation when save-and-send is %s",
async (send) => {
const editorRef = createRef<ComposerPromptEditorHandle>();
await using screen = await render(
<Composer question={false} editorRef={editorRef} send={send} />,
);

const sourceAnchor = findAssistantCitationSourceAnchor(document, citation);
if (!sourceAnchor) throw new Error("Citation source did not resolve");
await act(async () =>
editorRef.current?.requestCitationComment({
previousValue: "See ",
value: promptBefore,
citationStart: "See ".length,
sourceAnchor,
insertedSpaces: { before: false, after: true },
}),
);
const comment = page.getByLabelText("Comment on selected text");
await expect.element(comment).toHaveFocus();
await userEvent.keyboard("{Control>}{Enter}{/Control}");
await expect.element(comment).not.toBeInTheDocument();
await userEvent.keyboard("x");

await expect
.element(screen.getByRole("status"))
.toHaveAttribute("data-prompt", `See ${serializeAssistantCitation(citation)}x `);
},
);
41 changes: 27 additions & 14 deletions apps/web/src/components/ComposerPromptEditorTiptap.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import {
Plugin,
PluginKey,
TextSelection,
type Transaction,
} from "@tiptap/pm/state";
import { Decoration, DecorationSet, type EditorView } from "@tiptap/pm/view";
import type { NodeType, ResolvedPos } from "@tiptap/pm/model";
Expand Down Expand Up @@ -186,7 +187,7 @@ export interface ComposerPromptEditorProps {
onPageScrollKeyDown?: (key: "PageUp" | "PageDown") => void;
onPageScrollKeyUp?: (key: string) => void;
onPageScrollRelease?: () => void;
onCitationSubmitAndSend?: () => void;
onCitationSubmitAndSend?: () => boolean;
/** Saves unsaved citation text into replacedValue when a controlled rewrite replaces the document. */
onCitationDraftSave?: (replacedValue: string, savedValue: string) => void;
onPaste: React.ClipboardEventHandler<HTMLElement>;
Expand All @@ -213,12 +214,12 @@ const ComposerCitationCommentContext = createContext<{
openComment: OpenCitationComment | null;
onOpenChange: (citeKey: string, open: boolean) => void;
onDraftChange: (citeKey: string, comment: string) => void;
onSubmitAndSend: () => void;
onSubmitAndSend: () => boolean;
}>({
openComment: null,
onOpenChange: () => {},
onDraftChange: () => {},
onSubmitAndSend: () => {},
onSubmitAndSend: () => false,
});

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

const sentRef = useRef(false);
const onRestoreFocus = () => {
const sent = sentRef.current;
sentRef.current = false;
if (!editor.isEditable) return;
const pos = nodePos();
if (pos === null) return;
const current = editor.state.doc.nodeAt(pos);
if (!current || current.type.name !== "composer-citation") return;
editor.commands.focus(pos + current.nodeSize);
const current = pos === null ? null : editor.state.doc.nodeAt(pos);
if (pos === null || current?.type.name !== "composer-citation") {
if (sent) editor.view.focus();
return;
}
// The send's controlled rewrite may still be pending; emitting this caret move would restore the old prompt.
editor
.chain()
.setMeta(SILENT_SELECTION_META, sent)
.focus(pos + current.nodeSize)
.run();
};

return (
Expand Down Expand Up @@ -525,7 +536,7 @@ function ComposerCitationNodeView({ node, editor, getPos }: NodeViewProps) {
onDraftChange: (comment) => commentContext.onDraftChange(citeKey, comment),
onSaveAndSend: (comment) => {
if (!onSaveComment(comment)) return false;
commentContext.onSubmitAndSend();
sentRef.current = commentContext.onSubmitAndSend();
return true;
},
onRestoreFocus,
Expand Down Expand Up @@ -729,6 +740,8 @@ function chipSelectionDecorations({ doc, selection }: EditorState): DecorationSe

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

const SILENT_SELECTION_META = "composerSilentSelection";

function replaceSkillChips(
editor: TiptapEditor,
replacements: ReturnType<typeof skillChipReplacements>,
Expand Down Expand Up @@ -995,10 +1008,10 @@ function ComposerPromptEditorTiptapInner(
onDraftChange: (nodeKey: string, comment: string) => {
citationDraftRef.current = { key: nodeKey, comment };
},
onSubmitAndSend: onCitationSubmitAndSend ?? (() => {}),
onSubmitAndSend: onCitationSubmitAndSend ?? (() => false),
};

const handleEditorChange = (updated: TiptapEditor) => {
const handleEditorChange = (updated: TiptapEditor, transaction: Transaction) => {
const map = serializeEditorDoc(updated.state.doc);
const contextIds = literalText ? [] : [...map.contextIds];
const { from, to } = updated.state.selection;
Expand All @@ -1025,7 +1038,7 @@ function ComposerPromptEditorTiptapInner(
previousSnapshot.contextIds.length === contextIds.length &&
previousSnapshot.contextIds.every((id, index) => id === contextIds[index])
);
if (isApplyingControlledUpdateRef.current) return;
if (isApplyingControlledUpdateRef.current || transaction.getMeta(SILENT_SELECTION_META)) return;
if (!snapshotChanged) {
if (didComposerSelectionChangeVisibly(previousSelectionRange, nextSelectionRange)) {
readCallbacks().onVisibleSelectionChange?.();
Expand Down Expand Up @@ -1459,10 +1472,10 @@ function ComposerPromptEditorTiptapInner(
return;
}
}
handleEditorChange(updated);
handleEditorChange(updated, transaction);
},
onSelectionUpdate: ({ editor: updated }) => {
handleEditorChange(updated);
onSelectionUpdate: ({ editor: updated, transaction }) => {
handleEditorChange(updated, transaction);
},
},
[],
Expand Down
13 changes: 7 additions & 6 deletions apps/web/src/components/chat/ChatComposer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2096,15 +2096,15 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
if (voiceInputActive) {
event?.preventDefault();
submitAfterDictation(() => submitComposerRef.current(dispatchMode, submissionIntent));
return;
return false;
}
if (
noProviderAvailable ||
isSendDisabled ||
!readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)
) {
event?.preventDefault();
return;
return false;
}
// A send while a pasted image is still compressing would strand that image:
// the turn snapshot wouldn't include it, and it would surface in the *next*
Expand All @@ -2116,7 +2116,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
title: "Still compressing a pasted image.",
description: "Send again once its thumbnail appears.",
});
return;
return false;
}
if (pendingDraftWork.has(attachmentTargetKey)) {
event?.preventDefault();
Expand All @@ -2125,7 +2125,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
title: "Still bringing attached context into this message.",
description: "Send again once its chip resolves.",
});
return;
return false;
}
const submission = submitComposerDraft({
prompt: promptRef.current,
Expand All @@ -2148,11 +2148,12 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
},
});
setComposerSubmissionError(submission.validationMessage);
if (!submission.didDispatch) return;
if (!submission.didDispatch) return false;
onTypingGuardSend();
if (shouldBlurMobileComposerOnSubmit()) {
blurMobileComposerAfterSend();
}
return true;
};
const submitComposerStable = useStableCallback(submitComposer);
// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- publishes the committed submission handler to the asynchronous dictation completion
Expand Down Expand Up @@ -2201,7 +2202,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
};
const handleSubmitMessageStable = useStableCallback(handleSubmitMessage);
const submitCitationAndSend = () => {
submitComposer(
return submitComposer(
undefined,
resolveComposerDispatchMode({
running: phase === "running",
Expand Down
Loading