🤯 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
🐛 fix(task): continue into the instruction when pressing Enter in the create-task title (#20913)
Lobehub Coderaa87d0ee0c69
diff --git a/src/features/AgentTasks/CreateTaskModal/CreateTaskContent.tsx b/src/features/AgentTasks/CreateTaskModal/CreateTaskContent.tsxindex 03b583f6c9e..6393e990bda 100644--- a/src/features/AgentTasks/CreateTaskModal/CreateTaskContent.tsx+++ b/src/features/AgentTasks/CreateTaskModal/CreateTaskContent.tsx@@ -34,6 +34,7 @@ import { UnassignedAssigneeIcon } from '../features/UnassignedAssigneeIcon';import { useAgentDisplayMeta } from '../shared/useAgentDisplayMeta';import { useAgentVisibility } from '../shared/useAgentVisibility';import { useUserDisplayMeta } from '../shared/useUserDisplayMeta';+import { useTitleEnterToInstruction } from './useTitleEnterToInstruction';export interface CreateTaskContentProps {agentId?: string;@@ -202,6 +203,8 @@ const CreateTaskContent = memo<CreateTaskContentProps>(}}, []);+ const handleTitleKeyDown = useTitleEnterToInstruction(editor);+return (<Flexbox onKeyDown={handleKeyDown}><Flexbox horizontal style={{ padding: '16px 24px 0' }}>@@ -224,6 +227,7 @@ const CreateTaskContent = memo<CreateTaskContentProps>(width: '100%',}}onChange={(e) => setTitle(e.target.value)}+ onKeyDown={handleTitleKeyDown}/><EditorCanvasdisabled={!canCreateTask}diff --git a/src/features/AgentTasks/CreateTaskModal/useTitleEnterToInstruction.test.ts b/src/features/AgentTasks/CreateTaskModal/useTitleEnterToInstruction.test.tsnew file mode 100644index 00000000000..1747a679bdb--- /dev/null+++ b/src/features/AgentTasks/CreateTaskModal/useTitleEnterToInstruction.test.ts@@ -0,0 +1,113 @@+/**+ * @vitest-environment happy-dom+ */+import type { IEditor } from '@lobehub/editor';+import { renderHook } from '@testing-library/react';+import {+ $createParagraphNode,+ $createTextNode,+ $getRoot,+ $getSelection,+ $isRangeSelection,+ createEditor,+ type LexicalEditor,+} from 'lexical';+import type { KeyboardEvent } from 'react';+import { describe, expect, it, vi } from 'vitest';++import { useTitleEnterToInstruction } from './useTitleEnterToInstruction';++const flush = async (editor: LexicalEditor) => {+ await new Promise<void>((resolve) => {+ editor.update(() => undefined, { onUpdate: resolve });+ });+};++const readSnapshot = (editor: LexicalEditor) => {+ let lines: string[] = [];+ let caretLine: number | undefined;+ editor.getEditorState().read(() => {+ lines = $getRoot()+ .getChildren()+ .map((child) => child.getTextContent());+ const selection = $getSelection();+ if ($isRangeSelection(selection)) {+ caretLine = selection.anchor.getNode().getTopLevelElementOrThrow().getIndexWithinParent();+ }+ });+ return { caretLine, lines };+};++/** An instruction that already starts with content, as when an image was pasted first. */+const setup = async () => {+ const lexical = createEditor({+ onError: (e) => {+ throw e;+ },+ });+ lexical.update(() => {+ $getRoot().append($createParagraphNode().append($createTextNode('body')));+ });+ await flush(lexical);++ const focus = vi.fn();+ const editor = { focus, getLexicalEditor: () => lexical } as unknown as IEditor;+ const { result } = renderHook(() => useTitleEnterToInstruction(editor));++ return { focus, lexical, onKeyDown: result.current };+};++interface KeyInit {+ ctrlKey?: boolean;+ isComposing?: boolean;+ key?: string;+ keyCode?: number;+ metaKey?: boolean;+}++const keyDown = ({ isComposing = false, key = 'Enter', keyCode = 13, ...modifiers }: KeyInit) => {+ const preventDefault = vi.fn();+ const event = {+ ctrlKey: false,+ key,+ keyCode,+ metaKey: false,+ nativeEvent: { isComposing },+ preventDefault,+ ...modifiers,+ } as unknown as KeyboardEvent<HTMLInputElement>;+ return { event, preventDefault };+};++describe('useTitleEnterToInstruction', () => {+ it('continues into the instruction on a fresh first line', async () => {+ const { focus, lexical, onKeyDown } = await setup();+ const { event, preventDefault } = keyDown({});++ onKeyDown(event);+ await flush(lexical);++ expect(preventDefault).toHaveBeenCalledTimes(1);+ expect(readSnapshot(lexical)).toEqual({ caretLine: 0, lines: ['', 'body'] });+ expect(focus).toHaveBeenCalledTimes(1);+ });++ it.each<[string, KeyInit]>([+ ['another key', { key: 'a', keyCode: 65 }],+ ['Cmd+Enter, which submits', { metaKey: true }],+ ['Ctrl+Enter, which submits', { ctrlKey: true }],+ ['an Enter that confirms an IME candidate', { isComposing: true }],+ // Safari ends the composition first, so only keyCode 229 marks this Enter.+ ['the IME-confirming Enter on Safari', { keyCode: 229 }],+ ])('leaves %s alone', async (_, init) => {+ const { focus, lexical, onKeyDown } = await setup();+ const { event, preventDefault } = keyDown(init);++ onKeyDown(event);+ await flush(lexical);++ expect(preventDefault).not.toHaveBeenCalled();+ expect(readSnapshot(lexical).lines).toEqual(['body']);+ expect(focus).not.toHaveBeenCalled();+ });+});diff --git a/src/features/AgentTasks/CreateTaskModal/useTitleEnterToInstruction.ts b/src/features/AgentTasks/CreateTaskModal/useTitleEnterToInstruction.tsnew file mode 100644index 00000000000..f25d4de2512--- /dev/null+++ b/src/features/AgentTasks/CreateTaskModal/useTitleEnterToInstruction.ts@@ -0,0 +1,23 @@+import type { IEditor } from '@lobehub/editor';+import { type KeyboardEvent, useCallback } from 'react';++import { focusEditorStartLine } from '@/features/EditorCanvas/focusEditorStartLine';++/**+ * Enter in the title continues into the instruction on a fresh first line.+ * Cmd/Ctrl+Enter is left for the modal's submit shortcut.+ */+export const useTitleEnterToInstruction = (editor: IEditor | undefined) =>+ useCallback(+ (e: KeyboardEvent<HTMLInputElement>) => {+ // An IME Enter only confirms a candidate. Safari ends the composition before+ // this keydown, so isComposing is already false there and only keyCode 229+ // still marks the confirming Enter.+ const isImeConfirm = e.nativeEvent.isComposing || e.keyCode === 229;+ if (e.key !== 'Enter' || e.metaKey || e.ctrlKey || isImeConfirm) return;++ e.preventDefault();+ focusEditorStartLine(editor);+ },+ [editor],+ );diff --git a/src/features/EditorCanvas/focusEditorStartLine.test.ts b/src/features/EditorCanvas/focusEditorStartLine.test.tsnew file mode 100644index 00000000000..1a459486243--- /dev/null+++ b/src/features/EditorCanvas/focusEditorStartLine.test.ts@@ -0,0 +1,80 @@+import {+ $createParagraphNode,+ $createTextNode,+ $getRoot,+ $getSelection,+ $isRangeSelection,+ createEditor,+ type LexicalEditor,+} from 'lexical';+import { describe, expect, it } from 'vitest';++import { selectEditorStartLineOnLexical } from './focusEditorStartLine';++const flush = async (editor: LexicalEditor) => {+ await new Promise<void>((resolve) => {+ editor.update(() => undefined, { onUpdate: resolve });+ });+};++const createTestEditor = () =>+ createEditor({+ onError: (e) => {+ throw e;+ },+ });++const readSnapshot = (editor: LexicalEditor) => {+ let lines: string[] = [];+ let caretLine: number | undefined;+ editor.getEditorState().read(() => {+ lines = $getRoot()+ .getChildren()+ .map((child) => child.getTextContent());+ const selection = $getSelection();+ if ($isRangeSelection(selection)) {+ caretLine = selection.anchor.getNode().getTopLevelElementOrThrow().getIndexWithinParent();+ }+ });+ return { caretLine, lines };+};++describe('selectEditorStartLineOnLexical', () => {+ it('opens an empty line above existing content and puts the caret on it', async () => {+ const editor = createTestEditor();+ editor.update(() => {+ $getRoot().append($createParagraphNode().append($createTextNode('body')));+ });+ await flush(editor);++ selectEditorStartLineOnLexical(editor);+ await flush(editor);++ expect(readSnapshot(editor)).toEqual({ caretLine: 0, lines: ['', 'body'] });+ });++ it('reuses an empty first line instead of stacking another one', async () => {+ const editor = createTestEditor();+ editor.update(() => {+ $getRoot().append(+ $createParagraphNode(),+ $createParagraphNode().append($createTextNode('body')),+ );+ });+ await flush(editor);++ selectEditorStartLineOnLexical(editor);+ await flush(editor);++ expect(readSnapshot(editor)).toEqual({ caretLine: 0, lines: ['', 'body'] });+ });++ it('gives an empty document a line to type on', async () => {+ const editor = createTestEditor();++ selectEditorStartLineOnLexical(editor);+ await flush(editor);++ expect(readSnapshot(editor)).toEqual({ caretLine: 0, lines: [''] });+ });+});diff --git a/src/features/EditorCanvas/focusEditorStartLine.ts b/src/features/EditorCanvas/focusEditorStartLine.tsnew file mode 100644index 00000000000..ff824b2aba7--- /dev/null+++ b/src/features/EditorCanvas/focusEditorStartLine.ts@@ -0,0 +1,39 @@+import type { IEditor } from '@lobehub/editor';+import { $createParagraphNode, $getRoot, $isParagraphNode, type LexicalEditor } from 'lexical';++/** Exported for tests, which drive a bare Lexical editor without the kernel. */+export const selectEditorStartLineOnLexical = (lexicalEditor: LexicalEditor): void => {+ lexicalEditor.update(() => {+ const root = $getRoot();+ const first = root.getFirstChild();++ // An empty first line is already the line the caller wants; adding another+ // would stack a blank line on every call.+ if ($isParagraphNode(first) && first.getChildrenSize() === 0) {+ first.selectStart();+ return;+ }++ const paragraph = $createParagraphNode();+ if (first) first.insertBefore(paragraph);+ else root.append(paragraph);+ paragraph.selectStart();+ });+};++/**+ * Move the caret to an empty first line of the document, opening one above the+ * existing content when the document does not start with it.+ *+ * This is what Enter in a title field hands over to the body: the title and+ * the body read as one document, so Enter at the title continues on a fresh+ * line instead of landing inside whatever the body already starts with (an+ * image, a pasted block, …).+ */+export const focusEditorStartLine = (editor: IEditor | undefined): void => {+ const lexicalEditor = editor?.getLexicalEditor?.();+ if (!editor || !lexicalEditor) return;++ selectEditorStartLineOnLexical(lexicalEditor);+ editor.focus();+};