Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

feat(composer): post-send caret policy per surface (afterAccepted) (#6014)

Naiyuan Qingb5f19adbab67
diff --git a/packages/views/chat/components/chat-input.test.tsx b/packages/views/chat/components/chat-input.test.tsx
index ad58730ec5..aeb2a3520d 100644
--- a/packages/views/chat/components/chat-input.test.tsx
+++ b/packages/views/chat/components/chat-input.test.tsx
@@ -1291,8 +1291,11 @@ describe("ChatInput commit handoff", () => {
await typeAndSend(onSend);
expect(editorState.cleared).toBeGreaterThan(0);
- expect(editorState.blurred).toBeGreaterThan(0);
expect(useChatStore.getState().clearInputDraft).toHaveBeenCalledWith("__draft_new__");
+ // Chat is a conversation: the caret returns to the box for the next turn
+ // rather than being dropped (MUL-5181 follow-up).
+ await waitFor(() => expect(editorState.focused).toBeGreaterThan(0));
+ expect(editorState.blurred).toBe(0);
});
it("leaves the editor intact on a fire-and-forget commit but still clears the sent draft", async () => {
@@ -1307,5 +1310,9 @@ describe("ChatInput commit handoff", () => {
expect(editorState.blurred).toBe(0);
// …but the sent session's persisted draft is cleared regardless.
expect(useChatStore.getState().clearInputDraft).toHaveBeenCalledWith("__draft_new__");
+ // And the caret must NOT be pulled into an editor that is showing someone
+ // else's draft: refocus is bound to having actually scrubbed the document.
+ await new Promise((resolve) => requestAnimationFrame(() => resolve(null)));
+ expect(editorState.focused).toBe(0);
});
});
diff --git a/packages/views/chat/components/chat-input.tsx b/packages/views/chat/components/chat-input.tsx
index 4015c37335..9ef2c3790f 100644
--- a/packages/views/chat/components/chat-input.tsx
+++ b/packages/views/chat/components/chat-input.tsx
@@ -151,6 +151,7 @@ export function ChatInput({
const { t: tEditor } = useT("editor");
const sendShortcut = useShortcut("send");
const editorRef = useRef<ContentEditorRef>(null);
+ const composerRef = useRef<HTMLDivElement>(null);
const activeSessionId = useChatStore((s) => s.activeSessionId);
// Two keys with deliberately different concerns:
//
@@ -410,10 +411,22 @@ export function ChatInput({
// `submitting` lock/spinner. The chat-specific work — the loaded-draft guard,
// attachment-id resolution, and the owner-driven `commitInput` handoff — stays
// here in `onSubmit`, which receives the already-normalized content.
+ // Set by `commitInput` when it actually scrubbed the visible document; read
+ // back by `afterAccepted` a moment later to decide whether the caret may
+ // return. Reset at the top of every submit so a rejected send cannot leave a
+ // stale `true` behind for the next one.
+ const editorScrubbedRef = useRef(false);
+
const { submitting, submit } = useComposerSubmit({
editorRef,
uploadGate: gate,
+ containerRef: composerRef,
+ // Chat keeps the caret in the box after a send (the next turn is typed in
+ // the same place), except when the commit left the editor alone — see
+ // `editorScrubbedRef`.
+ afterAccepted: () => (editorScrubbedRef.current ? "refocus" : "none"),
onSubmit: async (content: string): Promise<boolean> => {
+ editorScrubbedRef.current = false;
// These states disable the SubmitButton, but Mod+Enter bypasses it — so a
// read-only or busy composer must still refuse the keyboard path.
if (isRunning || disabled || noAgent) {
@@ -472,14 +485,13 @@ export function ChatInput({
const untouched = liveDraft === undefined || liveDraft === draftValueAtSend;
if (options?.clearEditor !== false && untouched) {
editorRef.current?.clearContent();
- // Drop focus so the caret doesn't keep blinking under the StatusPill /
- // streaming reply that's about to take over the user's attention. The
- // input is also `disabled` once isRunning flips, and a focused-but-
- // disabled editor reads as a stale cursor. We deliberately don't auto-
- // refocus on completion — that would interrupt the user if they're
- // selecting text from the assistant reply; one click to refocus is
- // a fair price for not stealing focus mid-action.
- editorRef.current?.blur();
+ // Scrubbed the document the user was looking at, so the caret belongs
+ // back here: chat is a conversation and the next turn is typed in the
+ // same box. `useComposerSubmit` reads this flag to decide, because the
+ // other branches must NOT grab focus — a fire-and-forget send from
+ // another session (`clearEditor: false`) leaves this shared editor
+ // showing a DIFFERENT draft the user may be typing into.
+ editorScrubbedRef.current = true;
setIsEmpty(true);
}
// The sent draft's data is cleared only when untouched — the message
@@ -534,6 +546,7 @@ export function ChatInput({
return (
<div
+ ref={composerRef}
className={cn(
// The composer grows with the draft up to half the surface it sits on
// — a fixed 160px cap made long drafts unreadable in a five-line
diff --git a/packages/views/editor/content-editor.tsx b/packages/views/editor/content-editor.tsx
index c63d464a94..a4587a0b33 100644
--- a/packages/views/editor/content-editor.tsx
+++ b/packages/views/editor/content-editor.tsx
@@ -233,9 +233,9 @@ interface ContentEditorRef {
* long documents.
*/
focusAtAnchor: (anchor: TextAnchor) => void;
- /** Drop focus from the editor — used by chat after send so the caret
- * stops competing with the StatusPill / streaming reply for the user's
- * attention. */
+ /** Drop focus from the editor. Used by `useComposerSubmit`'s
+ * `afterAccepted: "blur"` on surfaces where a send ends the turn, so the
+ * composer stops reading as "still writing". */
blur: () => void;
uploadFile: (file: File) => void;
/** True when file uploads are still in progress. */
diff --git a/packages/views/editor/index.ts b/packages/views/editor/index.ts
index 9d15ea278d..c17edca2f0 100644
--- a/packages/views/editor/index.ts
+++ b/packages/views/editor/index.ts
@@ -15,6 +15,7 @@ export {
useComposerSubmit,
type ComposerSubmit,
type ComposerSubmitOptions,
+ type ComposerAfterAccepted,
} from "./use-composer-submit";
export { useEditorUpload } from "./use-editor-upload";
export { FileDropOverlay } from "./file-drop-overlay";
diff --git a/packages/views/editor/use-composer-submit.test.tsx b/packages/views/editor/use-composer-submit.test.tsx
index c74cbf1683..f14fa18083 100644
--- a/packages/views/editor/use-composer-submit.test.tsx
+++ b/packages/views/editor/use-composer-submit.test.tsx
@@ -10,6 +10,24 @@ function editorWith(markdown: string) {
};
}
+/** Editor stub that records the focus calls `afterAccepted` makes. */
+function focusTrackingEditor(markdown = "hello") {
+ const calls = { focused: 0, blurred: 0 };
+ const ref = {
+ current: {
+ getMarkdown: () => markdown,
+ focus: () => { calls.focused += 1; },
+ blur: () => { calls.blurred += 1; },
+ } as unknown as ContentEditorRef,
+ };
+ return { ref, calls };
+}
+
+/** `afterAccepted` defers a frame; flush it. */
+function nextFrame() {
+ return new Promise((resolve) => requestAnimationFrame(() => resolve(null)));
+}
+
const openGate: UploadGate = {
uploading: false,
onUploadingChange: () => {},
@@ -94,3 +112,153 @@ describe("useComposerSubmit", () => {
expect(onSubmit).toHaveBeenCalledTimes(1);
});
});
+
+// `afterAccepted` — where the caret goes once a send is accepted. Each surface
+// picks its own policy; the mechanics (defer a frame, respect unmount, don't
+// steal focus the user moved elsewhere) live in the hook.
+describe("useComposerSubmit afterAccepted", () => {
+ it("defaults to leaving focus alone", async () => {
+ const { ref, calls } = focusTrackingEditor();
+ const { result } = renderHook(() =>
+ useComposerSubmit({
+ editorRef: ref,
+ uploadGate: openGate,
+ onSubmit: vi.fn().mockResolvedValue(true),
+ }),
+ );
+ await act(async () => { await result.current.submit(); });
+ await act(async () => { await nextFrame(); });
+ expect(calls.focused).toBe(0);
+ expect(calls.blurred).toBe(0);
+ });
+
+ it("refocuses the editor after an accepted submit", async () => {
+ const { ref, calls } = focusTrackingEditor();
+ const { result } = renderHook(() =>
+ useComposerSubmit({
+ editorRef: ref,
+ uploadGate: openGate,
+ onSubmit: vi.fn().mockResolvedValue(true),
+ afterAccepted: "refocus",
+ }),
+ );
+ await act(async () => { await result.current.submit(); });
+ // Deferred on purpose: a synchronous grab loses to a dialog's focus trap.
+ expect(calls.focused).toBe(0);
+ await act(async () => { await nextFrame(); });
+ expect(calls.focused).toBe(1);
+ });
+
+ it("blurs the editor when the surface hands attention elsewhere", async () => {
+ const { ref, calls } = focusTrackingEditor();
+ const { result } = renderHook(() =>
+ useComposerSubmit({
+ editorRef: ref,
+ uploadGate: openGate,
+ onSubmit: vi.fn().mockResolvedValue(true),
+ afterAccepted: "blur",
+ }),
+ );
+ await act(async () => { await result.current.submit(); });
+ await act(async () => { await nextFrame(); });
+ expect(calls.blurred).toBe(1);
+ expect(calls.focused).toBe(0);
+ });
+
+ it("does nothing when the server rejects", async () => {
+ const { ref, calls } = focusTrackingEditor();
+ const { result } = renderHook(() =>
+ useComposerSubmit({
+ editorRef: ref,
+ uploadGate: openGate,
+ onSubmit: vi.fn().mockResolvedValue(false),
+ afterAccepted: "refocus",
+ }),
+ );
+ await act(async () => { await result.current.submit(); });
+ await act(async () => { await nextFrame(); });
+ expect(calls.focused).toBe(0);
+ });
+
+ it("resolves a function mode at accept time, not a frame later", async () => {
+ const { ref, calls } = focusTrackingEditor();
+ let allow = true;
+ const { result } = renderHook(() =>
+ useComposerSubmit({
+ editorRef: ref,
+ uploadGate: openGate,
+ onSubmit: vi.fn().mockResolvedValue(true),
+ afterAccepted: () => (allow ? "refocus" : "none"),
+ }),
+ );
+ await act(async () => { await result.current.submit(); });
+ // Flipping after acceptance must not retroactively cancel the decision —
+ // chat's flag is only true for the instant around the commit.
+ allow = false;
+ await act(async () => { await nextFrame(); });
+ expect(calls.focused).toBe(1);
+ });
+
+ it("does not steal focus the user moved outside the composer", async () => {
+ const { ref, calls } = focusTrackingEditor();
+ const container = document.createElement("div");
+ const outside = document.createElement("input");
+ document.body.append(container, outside);
+ outside.focus();
+ const { result } = renderHook(() =>
+ useComposerSubmit({
+ editorRef: ref,
+ uploadGate: openGate,
+ onSubmit: vi.fn().mockResolvedValue(true),
+ afterAccepted: "refocus",
+ containerRef: { current: container },
+ }),
+ );
+ await act(async () => { await result.current.submit(); });
+ await act(async () => { await nextFrame(); });
+ expect(calls.focused).toBe(0);
+ container.remove();
+ outside.remove();
+ });
+
+ it("reclaims focus that is still inside the composer", async () => {
+ const { ref, calls } = focusTrackingEditor();
+ const container = document.createElement("div");
+ const sendButton = document.createElement("button");
+ container.append(sendButton);
+ document.body.append(container);
+ sendButton.focus();
+ const { result } = renderHook(() =>
+ useComposerSubmit({
+ editorRef: ref,
+ uploadGate: openGate,
+ onSubmit: vi.fn().mockResolvedValue(true),
+ afterAccepted: "refocus",
+ containerRef: { current: container },
+ }),
+ );
+ await act(async () => { await result.current.submit(); });
+ await act(async () => { await nextFrame(); });
+ expect(calls.focused).toBe(1);
+ container.remove();
+ });
+
+ it("does not touch an editor whose composer unmounted mid-flight", async () => {
+ const { ref, calls } = focusTrackingEditor();
+ let resolve!: (v: boolean) => void;
+ const { result, unmount } = renderHook(() =>
+ useComposerSubmit({
+ editorRef: ref,
+ uploadGate: openGate,
+ onSubmit: () => new Promise<boolean>((r) => { resolve = r; }),
+ afterAccepted: "refocus",
+ }),
+ );
+ let pending!: Promise<void>;
+ act(() => { pending = result.current.submit(); });
+ await act(async () => { resolve(true); await pending; });
+ unmount();
+ await act(async () => { await nextFrame(); });
+ expect(calls.focused).toBe(0);
+ });
+});
diff --git a/packages/views/editor/use-composer-submit.ts b/packages/views/editor/use-composer-submit.ts
index 6190305c52..0e691227ad 100644
--- a/packages/views/editor/use-composer-submit.ts
+++ b/packages/views/editor/use-composer-submit.ts
@@ -20,12 +20,28 @@
* interactive (Tiptap cannot toggle editable post-mount), so callers' accepted
* handlers guard on a submit-time snapshot: success clears ONLY the draft it
* submitted, and anything typed during the request survives.
+ *
+ * It also owns the post-send FOCUS decision (`afterAccepted`). Where the caret
+ * lands after a send is a per-surface product call — a reply box the user keeps
+ * writing in refocuses, a top-level comment ends the turn and drops the caret —
+ * but the mechanics are identical everywhere and easy to get wrong (must run
+ * after the clear, must survive a dialog focus trap, must not steal focus the
+ * user moved elsewhere mid-flight). Those live here once.
*/
-import { useCallback, useRef, useState, type RefObject } from "react";
+import { useCallback, useEffect, useRef, useState, type RefObject } from "react";
import type { ContentEditorRef } from "./content-editor";
import type { UploadGate } from "./use-upload-gate";
+/**
+ * What happens to keyboard focus after an accepted submit.
+ * - `refocus`: put the caret back in the composer so the user keeps writing.
+ * - `blur`: drop the caret, because the send ended the turn and the composer
+ * should stop reading as "still writing".
+ * - `none`: leave focus exactly where the send left it.
+ */
+export type ComposerAfterAccepted = "refocus" | "blur" | "none";
+
export interface ComposerSubmitOptions {
editorRef: RefObject<ContentEditorRef | null>;
uploadGate: UploadGate;
@@ -42,6 +58,28 @@ export interface ComposerSubmitOptions {
onAccepted?: () => void;
/** Normalize the raw markdown before the empty-guard and `onSubmit`. */
normalize?: (raw: string) => string;
+ /**
+ * Focus handling once `onAccepted` has cleared the composer. Defaults to
+ * `none`.
+ *
+ * INVARIANT: a surface whose `onAccepted` can decline to clear must pass a
+ * FUNCTION and resolve to `none` on those paths. Every composer here has a
+ * stale-submit guard that keeps text typed during the request — and chat can
+ * be sent fire-and-forget while the user is on another session, leaving the
+ * shared editor on someone else's draft. Acting on a document the accepted
+ * handler deliberately left alone drops the caret out of a sentence the user
+ * is still writing. A literal mode is only safe when acceptance ALWAYS
+ * scrubs the editor.
+ */
+ afterAccepted?: ComposerAfterAccepted | (() => ComposerAfterAccepted);
+ /**
+ * Root element of the composer, used only by `refocus`. Focus is taken back
+ * only when it still belongs to this composer — the send button, the editor
+ * itself, or nothing at all. Without this the composer would yank the caret
+ * away from a field the user moved to while a slow send was in flight.
+ * Omitting it refocuses unconditionally.
+ */
+ containerRef?: RefObject<HTMLElement | null>;
}
export interface ComposerSubmit {
@@ -60,6 +98,53 @@ export function useComposerSubmit(opts: ComposerSubmitOptions): ComposerSubmit {
const inFlight = useRef(false);
const optsRef = useRef(opts);
optsRef.current = opts;
+ // The focus effect lands a frame after acceptance, by which time this
+ // composer may be gone (an inline edit closes on save) — never touch a ref
+ // whose owner unmounted, and never leave a queued frame behind.
+ const mountedRef = useRef(true);
+ const focusFrameRef = useRef<number | null>(null);
+ useEffect(() => {
+ mountedRef.current = true;
+ return () => {
+ mountedRef.current = false;
+ if (focusFrameRef.current !== null) {
+ cancelAnimationFrame(focusFrameRef.current);
+ focusFrameRef.current = null;
+ }
+ };
+ }, []);
+
+ const runAfterAccepted = useCallback(() => {
+ const o = optsRef.current;
+ // Resolve the mode NOW, not inside the frame: callers decide from state
+ // that acceptance just settled (chat's "did we actually scrub the shared
+ // editor" flag), and a frame later that state can already have moved on.
+ const mode =
+ typeof o.afterAccepted === "function"
+ ? o.afterAccepted()
+ : (o.afterAccepted ?? "none");
+ if (mode === "none") return;
+ // Defer one frame. `onAccepted` has just cleared the editor and the draft,
+ // and a composer inside a dialog is still competing with the focus trap,
+ // which bounces focus back to the first focusable header control on the
+ // next tick if we grab it synchronously.
+ if (focusFrameRef.current !== null) cancelAnimationFrame(focusFrameRef.current);
+ focusFrameRef.current = requestAnimationFrame(() => {
+ focusFrameRef.current = null;
+ if (!mountedRef.current) return;
+ if (mode === "blur") {
+ optsRef.current.editorRef.current?.blur();
+ return;
+ }
+ const container = optsRef.current.containerRef?.current;
+ const active = typeof document === "undefined" ? null : document.activeElement;
+ // `body` means the clear already dropped focus — that is still "ours".
+ const ownsFocus =
+ !container || !active || active === document.body || container.contains(active);
+ if (!ownsFocus) return;
+ optsRef.current.editorRef.current?.focus();
+ });
+ }, []);
const submit = useCallback(async () => {
const o = optsRef.current;
@@ -74,7 +159,10 @@ export function useComposerSubmit(opts: ComposerSubmitOptions): ComposerSubmit {
setSubmitting(true);
try {
const accepted = await o.onSubmit(content);
- if (accepted) o.onAccepted?.();
+ if (accepted) {
+ o.onAccepted?.();
+ runAfterAccepted();
+ }
} catch {
// A thrown send is a rejection: keep the draft, let the caller's
// onSubmit surface its own error toast.
@@ -82,7 +170,7 @@ export function useComposerSubmit(opts: ComposerSubmitOptions): ComposerSubmit {
inFlight.current = false;
setSubmitting(false);
}
- }, []);
+ }, [runAfterAccepted]);
return { submitting, submit };
}
diff --git a/packages/views/issues/components/comment-composers.test.tsx b/packages/views/issues/components/comment-composers.test.tsx
index 682d127d4b..ee96ab166b 100644
--- a/packages/views/issues/components/comment-composers.test.tsx
+++ b/packages/views/issues/components/comment-composers.test.tsx
@@ -20,6 +20,9 @@ const editorDefaultValues = vi.hoisted(() => ({
// Observability + failure control for the write-back insert path (MUL-5181):
// `insertMarkdownAtEnd` returns false while the (simulated) Tiptap instance
// doesn't exist yet, exactly like the real handle.
+// Post-send caret policy: the top-level composer blurs (the page scrolls to the
+// posted comment instead), a thread reply keeps the caret for the next reply.
+const focusCalls = vi.hoisted(() => ({ focused: 0, blurred: 0 }));
const insertMarkdownSpy = vi.hoisted(() => vi.fn());
const insertMarkdownBehavior = vi.hoisted(() => ({ succeed: true }));
@@ -108,9 +111,9 @@ vi.mock("../../editor", async () => ({
clearContent: () => {
valueRef.current = "";
},
- focus: () => {},
+ focus: () => { focusCalls.focused += 1; },
focusAtCoords: () => {},
- blur: () => {},
+ blur: () => { focusCalls.blurred += 1; },
uploadFile: async (file: File) => {
inFlightRef.current += 1;
if (inFlightRef.current === 1) onUploadingChange?.(true);
@@ -219,6 +222,8 @@ beforeEach(() => {
// path and hide the shell the next test expects.
useCommentDraftStore.setState({ drafts: {} });
editorDefaultValues.values = [];
+ focusCalls.focused = 0;
+ focusCalls.blurred = 0;
});
describe("comment composers", () => {
@@ -346,6 +351,50 @@ describe("comment composers", () => {
expect(screen.getByTestId("editor").closest("[aria-busy]")).toBeNull();
});
+ // Post-send caret policy. The two composers deliberately disagree: posting a
+ // top-level comment ends the turn and drops the caret, while a thread reply
+ // leaves the user mid-conversation with the box ready for the next one.
+ it("blurs the top-level composer after a posted comment", async () => {
+ const { container } = renderCommentInput();
+
+ activateComposer("comment-composer-shell");
+ fireEvent.change(screen.getByTestId("editor"), { target: { value: "posted" } });
+ // Discard the focus the lazy shell→editor swap performed; what follows is
+ // entirely the post-send policy.
+ focusCalls.focused = 0;
+ fireEvent.click(getSubmitButton(container));
+
+ await waitFor(() => expect(focusCalls.blurred).toBeGreaterThan(0));
+ expect(focusCalls.focused).toBe(0);
+ });
+
+ it("keeps the caret in the reply box after a posted reply", async () => {
+ const { container } = renderReplyInput();
+
+ activateComposer("reply-composer-shell");
+ fireEvent.change(screen.getByTestId("editor"), { target: { value: "replied" } });
+ // Discard the shell→editor activation focus; what follows is the refocus.
+ focusCalls.focused = 0;
+ fireEvent.click(getSubmitButton(container));
+
+ await waitFor(() => expect(focusCalls.focused).toBeGreaterThan(0));
+ expect(focusCalls.blurred).toBe(0);
+ });
+
+ it("does not refocus the reply box when the send fails", async () => {
+ const onSubmit = vi.fn().mockResolvedValue(false);
+ const { container } = renderReplyInput({ onSubmit });
+
+ activateComposer("reply-composer-shell");
+ fireEvent.change(screen.getByTestId("editor"), { target: { value: "nope" } });
+ focusCalls.focused = 0;
+ fireEvent.click(getSubmitButton(container));
+
+ await waitFor(() => expect(onSubmit).toHaveBeenCalled());
+ await new Promise((resolve) => requestAnimationFrame(() => resolve(null)));
+ expect(focusCalls.focused).toBe(0);
+ });
+
// Regression: the tab-switch flush re-writes IDENTICAL content mid-flight;
// that must not read as "edited during the request" — the posted comment's
// draft still clears (it previously resurrected with Send re-enabled).
@@ -399,6 +448,38 @@ describe("comment composers", () => {
});
expect(useCommentDraftStore.getState().getDraft("new:issue-1")).toBe("draft A plus more");
+ // …and the post-send caret policy must stand down with it: the guard left
+ // the editor holding "draft A plus more", so blurring would yank the caret
+ // out of the sentence the user is still writing.
+ await new Promise((resolve) => requestAnimationFrame(() => resolve(null)));
+ expect(focusCalls.blurred).toBe(0);
+ });
+
+ // Same coupling on the reply side: refocus is bound to having actually wiped
+ // the editor, not merely to acceptance.
+ it("does not refocus a reply box whose mid-flight draft was kept", async () => {
+ let resolveSubmit!: (v: boolean) => void;
+ const onSubmit = vi.fn(() => new Promise<boolean>((r) => { resolveSubmit = r; }));
+ renderReplyInput({ onSubmit, draftKey: "reply:issue-1:comment-1" });
+ activateComposer("reply-composer-shell");
+ const editor = screen.getByTestId("editor");
+ fireEvent.change(editor, { target: { value: "reply A" } });
+ fireEvent.keyDown(editor, { key: "Enter", metaKey: true });
+ await waitFor(() => expect(onSubmit).toHaveBeenCalled());
+
+ fireEvent.change(editor, { target: { value: "reply A plus more" } });
+ focusCalls.focused = 0;
+
+ await act(async () => {
+ resolveSubmit(true);
+ await Promise.resolve();
+ });
+
+ expect(useCommentDraftStore.getState().getDraft("reply:issue-1:comment-1")).toBe(
+ "reply A plus more",
+ );
+ await new Promise((resolve) => requestAnimationFrame(() => resolve(null)));
+ expect(focusCalls.focused).toBe(0);
});
// MUL-5181 P0: a submit that outlives its composer may only clear the draft
diff --git a/packages/views/issues/components/comment-input.tsx b/packages/views/issues/components/comment-input.tsx
index b09a559398..6699ac30bc 100644
--- a/packages/views/issues/components/comment-input.tsx
+++ b/packages/views/issues/components/comment-input.tsx
@@ -125,11 +125,21 @@ function CommentInput({ issueId, onSubmit }: CommentInputProps) {
};
}, []);
const submittedEntryRef = useRef<unknown>(null);
+ // Set by `onAccepted` only on the branch that actually wiped the editor; read
+ // back by `afterAccepted`. Bound this way because the stale-submit guard can
+ // leave a mid-flight draft in place: dropping the caret then would yank it
+ // out of the sentence the user is still typing.
+ const editorScrubbedRef = useRef(false);
const { submitting, submit } = useComposerSubmit({
editorRef,
uploadGate: gate,
+ // A top-level comment ends a turn: the caret is dropped rather than kept,
+ // so the composer stops reading as "still writing" once the comment is
+ // posted above it. Thread replies are the opposite — see ReplyInput.
+ afterAccepted: () => (editorScrubbedRef.current ? "blur" : "none"),
onSubmit: (content) => {
+ editorScrubbedRef.current = false;
// Flush the editor's pending debounce before snapshotting — a late flush
// of pre-submit typing must not read as an edit made during the request.
const pending = editorRef.current?.flushPendingUpdate?.();
@@ -168,6 +178,7 @@ function CommentInput({ issueId, onSubmit }: CommentInputProps) {
setContent("");
setIsEmpty(true);
setSuppressedAgentIds(new Set());
+ editorScrubbedRef.current = true;
},
});
diff --git a/packages/views/issues/components/issue-detail.test.tsx b/packages/views/issues/components/issue-detail.test.tsx
index 25dd6a151d..c11de11a67 100644
--- a/packages/views/issues/components/issue-detail.test.tsx
+++ b/packages/views/issues/components/issue-detail.test.tsx
@@ -190,6 +190,10 @@ vi.mock("../../editor", async () => ({
clearContent: () => { valueRef.current = ""; setEditorValue(""); },
focus: () => {},
focusAtCoords: () => {},
+ // The top-level composer blurs after a posted comment (afterAccepted).
+ blur: () => {},
+ // Read by the submit-time upload gate; no uploads are exercised here.
+ hasActiveUploads: () => false,
uploadFile: () => {},
}));
return (
diff --git a/packages/views/issues/components/reply-input.tsx b/packages/views/issues/components/reply-input.tsx
index faeb954c88..7733645a36 100644
--- a/packages/views/issues/components/reply-input.tsx
+++ b/packages/views/issues/components/reply-input.tsx
@@ -55,6 +55,7 @@ function ReplyInput({
const sendShortcut = useShortcut("send");
const placeholderText = placeholder ?? t(($) => $.reply.placeholder);
const editorRef = useRef<ContentEditorRef>(null);
+ const composerRef = useRef<HTMLDivElement>(null);
// See CommentInput — replying mid-upload posts without the file.
const uploadGate = useUploadGate(editorRef);
// If a draft key is provided, hydrate from store on mount (defaultValue is
@@ -139,11 +140,22 @@ function ReplyInput({
};
}, []);
const submittedEntryRef = useRef<unknown>(null);
+ // See CommentInput: bound to the branch that actually wiped the editor, so a
+ // draft the stale-submit guard kept is never disturbed.
+ const editorScrubbedRef = useRef(false);
const { submitting, submit } = useComposerSubmit({
editorRef,
uploadGate: gate,
+ containerRef: composerRef,
+ // A thread reply is rarely the last thing the user has to say, so the caret
+ // stays in the box for the next one. Unlike a top-level comment, the posted
+ // reply lands directly above the box that is still focused — nothing needs
+ // to pull the eye elsewhere. `containerRef` keeps this from stealing focus
+ // if the user moved to another composer while the reply was in flight.
+ afterAccepted: () => (editorScrubbedRef.current ? "refocus" : "none"),
onSubmit: (content) => {
+ editorScrubbedRef.current = false;
if (draftKey) {
// Flush pending debounce before snapshotting — see CommentInput.
const pending = editorRef.current?.flushPendingUpdate?.();
@@ -183,6 +195,7 @@ function ReplyInput({
setContent("");
setIsEmpty(true);
setSuppressedAgentIds(new Set());
+ editorScrubbedRef.current = true;
},
});
@@ -198,6 +211,7 @@ function ReplyInput({
/>
<div
{...dropZoneProps}
+ ref={composerRef}
className={cn(
"relative min-w-0 flex-1 flex flex-col",
!isEmpty && "pb-9",
diff --git a/packages/views/modals/quick-create-issue.tsx b/packages/views/modals/quick-create-issue.tsx
index 0e4721fa36..9a9706256a 100644
--- a/packages/views/modals/quick-create-issue.tsx
+++ b/packages/views/modals/quick-create-issue.tsx
@@ -384,6 +384,10 @@ export function AgentCreatePanel({
};
}, []);
const submittedDraftRef = useRef<IssueCreateDraft | null>(null);
+ // Set by `onAccepted` only on the branch that keeps the panel open and wipes
+ // the editor; read back by `afterAccepted`. The closing branch must not
+ // refocus an editor that is about to unmount with the dialog.
+ const refocusAfterAcceptRef = useRef(false);
const composer = useComposerSubmit({
editorRef,
@@ -459,7 +463,13 @@ export function AgentCreatePanel({
return false;
}
},
+ // Continuous-creation mode puts the caret back so the next prompt can be
+ // typed immediately. Deliberately no `containerRef`: this is a dialog whose
+ // own focus trap already bounds where focus can be, and reclaiming it is the
+ // point of keep-open mode.
+ afterAccepted: () => (refocusAfterAcceptRef.current ? "refocus" : "none"),
onAccepted: () => {
+ refocusAfterAcceptRef.current = false;
// A successful create ends this whole draft (shared + manual + agent);
// last-successful actor/project preferences were saved in onSubmit.
// Success may only consume the draft it submitted: flush the editor's
@@ -480,7 +490,7 @@ export function AgentCreatePanel({
setSentCount((c) => c + 1);
setJustSent(true);
setTimeout(() => setJustSent(false), 1500);
- requestAnimationFrame(() => editorRef.current?.focus());
+ refocusAfterAcceptRef.current = true;
} else {
onClose();
}