Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

🐛 fix(task): clear the comment input as soon as a comment is sent (#21849)

Lobehub Coder10c4ee5dd707
diff --git a/src/features/AgentTasks/AgentTaskDetail/CommentInput.tsx b/src/features/AgentTasks/AgentTaskDetail/CommentInput.tsx
index 9cca6bce90a..797c24dcb85 100644
--- a/src/features/AgentTasks/AgentTaskDetail/CommentInput.tsx
+++ b/src/features/AgentTasks/AgentTaskDetail/CommentInput.tsx
@@ -15,17 +15,15 @@ import { useWorkspaceCommentMentionOption } from '@/features/Portal/TopicComment
import { useEnterToSend } from '@/hooks/useEnterToSend';
import { usePermission } from '@/hooks/usePermission';
import { useUserAvatar } from '@/hooks/useUserAvatar';
-import { useTaskStore } from '@/store/task';
import { styles } from '../shared/style';
+import { useCommentSubmit } from './useCommentSubmit';
const CommentInput = memo<{ taskId: string }>(({ taskId }) => {
const { t } = useTranslation('chat');
const { allowed: canEditTask } = usePermission('create_content');
const editor = useEditor();
- const addComment = useTaskStore((s) => s.addComment);
const userAvatar = useUserAvatar();
- const [submitting, setSubmitting] = useState(false);
const [hasContent, setHasContent] = useState(false);
const [hasAttachments, setHasAttachments] = useState(false);
const shouldSendOnEnter = useEnterToSend();
@@ -52,23 +50,20 @@ const CommentInput = memo<{ taskId: string }>(({ taskId }) => {
[editor],
);
- const handleSubmit = useCallback(async () => {
- if (!canEditTask || submitting) return;
- const json = editor?.getDocument?.('json') as unknown;
- const markdown = String(editor?.getDocument?.('markdown') ?? '').trim();
- const hasFiles = getAttachmentFileIdsFromEditor(editor).length > 0;
- if (!markdown && !hasFiles) return;
+ const handleContentReset = useCallback(
+ (state: { hasAttachments: boolean; hasContent: boolean }) => {
+ setHasContent(state.hasContent);
+ setHasAttachments(state.hasAttachments);
+ },
+ [],
+ );
- setSubmitting(true);
- try {
- await addComment(taskId, markdown, { editorData: json });
- editor?.cleanDocument?.();
- setHasContent(false);
- setHasAttachments(false);
- } finally {
- setSubmitting(false);
- }
- }, [canEditTask, taskId, editor, addComment, submitting]);
+ const { submit: handleSubmit, submitting } = useCommentSubmit({
+ canComment: canEditTask,
+ editor,
+ onContentReset: handleContentReset,
+ taskId,
+ });
return (
<Flexbox className={styles.commentInputCard} gap={6}>
diff --git a/src/features/AgentTasks/AgentTaskDetail/useCommentSubmit.test.ts b/src/features/AgentTasks/AgentTaskDetail/useCommentSubmit.test.ts
new file mode 100644
index 00000000000..0c291eb7731
--- /dev/null
+++ b/src/features/AgentTasks/AgentTaskDetail/useCommentSubmit.test.ts
@@ -0,0 +1,193 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import type { IEditor } from '@lobehub/editor';
+import { act, renderHook } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { useCommentSubmit } from './useCommentSubmit';
+
+const mocks = vi.hoisted(() => ({
+ addComment: vi.fn(),
+ fileIds: [] as string[],
+}));
+
+vi.mock('@/store/task', () => ({
+ useTaskStore: (selector: (state: any) => unknown) => selector({ addComment: mocks.addComment }),
+}));
+
+vi.mock('@/features/EditorCanvas/editorAttachments', () => ({
+ getAttachmentFileIdsFromEditor: () => mocks.fileIds,
+ getEditorAttachmentStateFromJson: (json: unknown) => ({
+ hasCompletedAttachments: false,
+ hasIncompleteAttachments: JSON.stringify(json ?? null).includes('"pending"'),
+ }),
+}));
+
+const JSON_DOC = { root: { type: 'root' } };
+
+const createEditor = () => {
+ const doc = { json: JSON_DOC as unknown, markdown: 'looks good' };
+ const editor = {
+ cleanDocument: vi.fn(() => {
+ doc.json = undefined;
+ doc.markdown = '';
+ }),
+ getDocument: (format: string) => (format === 'markdown' ? doc.markdown : doc.json),
+ setDocument: vi.fn((format: string, value: unknown) => {
+ if (format === 'json') doc.json = value;
+ else doc.markdown = String(value);
+ }),
+ };
+ return { doc, editor: editor as unknown as IEditor & typeof editor };
+};
+
+const deferred = () => {
+ let resolve!: () => void;
+ let reject!: (error: Error) => void;
+ const promise = new Promise<void>((res, rej) => {
+ resolve = res;
+ reject = rej;
+ });
+ return { promise, reject, resolve };
+};
+
+const setup = (editor: IEditor, canComment = true) => {
+ const onContentReset = vi.fn();
+ const hook = renderHook(() =>
+ useCommentSubmit({ canComment, editor, onContentReset, taskId: 'task-1' }),
+ );
+ return { hook, onContentReset };
+};
+
+describe('useCommentSubmit', () => {
+ beforeEach(() => {
+ mocks.addComment.mockReset();
+ mocks.fileIds = [];
+ });
+
+ it('clears the input before the comment request settles', async () => {
+ const pending = deferred();
+ mocks.addComment.mockReturnValue(pending.promise);
+ const { doc, editor } = createEditor();
+ const { hook, onContentReset } = setup(editor);
+
+ let submit!: Promise<void>;
+ act(() => {
+ submit = hook.result.current.submit();
+ });
+
+ expect(mocks.addComment).toHaveBeenCalledWith('task-1', 'looks good', { editorData: JSON_DOC });
+ expect(doc.markdown).toBe('');
+ expect(onContentReset).toHaveBeenLastCalledWith({ hasAttachments: false, hasContent: false });
+ expect(hook.result.current.submitting).toBe(true);
+
+ await act(async () => {
+ pending.resolve();
+ await submit;
+ });
+
+ expect(doc.markdown).toBe('');
+ expect(editor.setDocument).not.toHaveBeenCalled();
+ expect(hook.result.current.submitting).toBe(false);
+ });
+
+ it('ignores a second submit while the first is pending', async () => {
+ const pending = deferred();
+ mocks.addComment.mockReturnValue(pending.promise);
+ const { doc, editor } = createEditor();
+ const { hook } = setup(editor);
+
+ let first!: Promise<void>;
+ act(() => {
+ first = hook.result.current.submit();
+ doc.markdown = 'looks good';
+ void hook.result.current.submit();
+ });
+
+ expect(mocks.addComment).toHaveBeenCalledTimes(1);
+
+ await act(async () => {
+ pending.resolve();
+ await first;
+ });
+ });
+
+ it('restores the input when the comment fails to send', async () => {
+ mocks.addComment.mockRejectedValue(new Error('network'));
+ mocks.fileIds = ['file-1'];
+ const { doc, editor } = createEditor();
+ const { hook, onContentReset } = setup(editor);
+
+ await act(async () => {
+ await hook.result.current.submit();
+ });
+
+ expect(editor.setDocument).toHaveBeenCalledWith('json', JSON_DOC);
+ expect(doc.json).toEqual(JSON_DOC);
+ expect(onContentReset).toHaveBeenLastCalledWith({ hasAttachments: true, hasContent: true });
+ expect(hook.result.current.submitting).toBe(false);
+ });
+
+ it('keeps a new draft typed while the failed comment was sending', async () => {
+ const pending = deferred();
+ mocks.addComment.mockReturnValue(pending.promise);
+ const { doc, editor } = createEditor();
+ const { hook } = setup(editor);
+
+ let submit!: Promise<void>;
+ act(() => {
+ submit = hook.result.current.submit();
+ });
+ doc.markdown = 'next comment';
+
+ await act(async () => {
+ pending.reject(new Error('network'));
+ await submit;
+ });
+
+ expect(editor.setDocument).not.toHaveBeenCalled();
+ expect(doc.markdown).toBe('next comment');
+ });
+
+ it('keeps a new draft whose attachment is still uploading', async () => {
+ const pending = deferred();
+ mocks.addComment.mockReturnValue(pending.promise);
+ const { doc, editor } = createEditor();
+ const { hook } = setup(editor);
+
+ let submit!: Promise<void>;
+ act(() => {
+ submit = hook.result.current.submit();
+ });
+ const uploading = { root: { children: [{ status: 'pending', type: 'file' }], type: 'root' } };
+ doc.json = uploading;
+
+ await act(async () => {
+ pending.reject(new Error('network'));
+ await submit;
+ });
+
+ expect(editor.setDocument).not.toHaveBeenCalled();
+ expect(doc.json).toBe(uploading);
+ });
+
+ it('does nothing without permission or content', async () => {
+ const { editor } = createEditor();
+ const denied = setup(editor, false).hook;
+ await act(async () => {
+ await denied.result.current.submit();
+ });
+
+ const empty = createEditor();
+ empty.doc.markdown = ' ';
+ const blank = setup(empty.editor).hook;
+ await act(async () => {
+ await blank.result.current.submit();
+ });
+
+ expect(mocks.addComment).not.toHaveBeenCalled();
+ expect(editor.cleanDocument).not.toHaveBeenCalled();
+ expect(empty.editor.cleanDocument).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/features/AgentTasks/AgentTaskDetail/useCommentSubmit.ts b/src/features/AgentTasks/AgentTaskDetail/useCommentSubmit.ts
new file mode 100644
index 00000000000..80e02692a43
--- /dev/null
+++ b/src/features/AgentTasks/AgentTaskDetail/useCommentSubmit.ts
@@ -0,0 +1,70 @@
+import type { IEditor } from '@lobehub/editor';
+import { useCallback, useRef, useState } from 'react';
+
+import {
+ getAttachmentFileIdsFromEditor,
+ getEditorAttachmentStateFromJson,
+} from '@/features/EditorCanvas/editorAttachments';
+import { useTaskStore } from '@/store/task';
+
+interface UseCommentSubmitOptions {
+ canComment: boolean;
+ editor: IEditor | undefined;
+ /** Called after the input is cleared or restored, so the caller can resync its flags. */
+ onContentReset: (state: { hasAttachments: boolean; hasContent: boolean }) => void;
+ taskId: string;
+}
+
+export const useCommentSubmit = ({
+ canComment,
+ editor,
+ onContentReset,
+ taskId,
+}: UseCommentSubmitOptions) => {
+ const addComment = useTaskStore((s) => s.addComment);
+ const [submitting, setSubmitting] = useState(false);
+ // `submitting` only updates after a render, so a second Enter in the same
+ // tick would still read `false`; the ref closes that window.
+ const submittingRef = useRef(false);
+ const taskIdRef = useRef(taskId);
+ taskIdRef.current = taskId;
+
+ const submit = useCallback(async () => {
+ if (!canComment || submittingRef.current) return;
+ const json = editor?.getDocument?.('json') as unknown;
+ const markdown = String(editor?.getDocument?.('markdown') ?? '').trim();
+ const hasFiles = getAttachmentFileIdsFromEditor(editor).length > 0;
+ if (!markdown && !hasFiles) return;
+
+ // The optimistic row appears as soon as `addComment` starts, but the call
+ // only resolves after the mutation *and* the detail refetch. Clear the
+ // input now so a slow network doesn't leave the sent text sitting there,
+ // inviting a duplicate send; put it back if the send fails.
+ submittingRef.current = true;
+ setSubmitting(true);
+ editor?.cleanDocument?.();
+ onContentReset({ hasAttachments: false, hasContent: false });
+ try {
+ await addComment(taskId, markdown, { editorData: json });
+ } catch {
+ // The tRPC error link already reports the failure; keep the text —
+ // unless the user has started a new comment or moved to another task
+ // while it was sending, which a restore would overwrite or misplace.
+ // Count still-uploading attachments too: they have no file id yet.
+ const attachments = getEditorAttachmentStateFromJson(editor?.getDocument?.('json'));
+ const isEmpty =
+ !String(editor?.getDocument?.('markdown') ?? '').trim() &&
+ !attachments.hasCompletedAttachments &&
+ !attachments.hasIncompleteAttachments;
+ if (!isEmpty || taskIdRef.current !== taskId) return;
+ if (json) editor?.setDocument?.('json', json);
+ else editor?.setDocument?.('markdown', markdown);
+ onContentReset({ hasAttachments: hasFiles, hasContent: !!markdown });
+ } finally {
+ submittingRef.current = false;
+ setSubmitting(false);
+ }
+ }, [canComment, editor, onContentReset, addComment, taskId]);
+
+ return { submit, submitting };
+};