🤯 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(goal): let Create Goal modal scroll and confirm on Escape (#21956)
Rdmclin2146950948a49
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex e6cc267c5ff..7560f13fca1 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -307,6 +307,10 @@"createGoal.criterionPlaceholder": "Describe a result that can be clearly checked","createGoal.describeHint": "Describe the outcome first, then complete its execution plan.","createGoal.describeTitle": "What goal do you expect to achieve?",+ "createGoal.discardConfirm.cancel": "Keep editing",+ "createGoal.discardConfirm.content": "The goal description, attachments and acceptance criteria you added will be lost.",+ "createGoal.discardConfirm.ok": "Discard",+ "createGoal.discardConfirm.title": "Discard this goal?","createGoal.generateFailed": "Could not draft acceptance criteria, so your goal was used as the criterion.","createGoal.generating": "Understanding your goal…","createGoal.generatingAlmostDone": "Almost done…",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex 01d5e84a01e..f6edd83eaff 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -307,6 +307,10 @@"createGoal.criterionPlaceholder": "描述一个能够明确检查的结果","createGoal.describeHint": "先描述想要的结果,下一步再完善完整执行计划。","createGoal.describeTitle": "你期望达到的目标",+ "createGoal.discardConfirm.cancel": "继续编辑",+ "createGoal.discardConfirm.content": "已填写的目标描述、附件和验收标准都会丢失。",+ "createGoal.discardConfirm.ok": "放弃",+ "createGoal.discardConfirm.title": "放弃这个目标?","createGoal.generateFailed": "没能自动起草,已将目标内容作为验收标准。","createGoal.generating": "正在理解目标…","createGoal.generatingAlmostDone": "即将完成…",diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex 7c25e951a3e..46c719ed439 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -2242,6 +2242,11 @@ export default {'createGoal.criterionPlaceholder': 'Describe a result that can be clearly checked','createGoal.criteriaHint': 'Review and edit these before the goal starts','createGoal.criteriaTitle': 'Acceptance criteria',+ 'createGoal.discardConfirm.cancel': 'Keep editing',+ 'createGoal.discardConfirm.content':+ 'The goal description, attachments and acceptance criteria you added will be lost.',+ 'createGoal.discardConfirm.ok': 'Discard',+ 'createGoal.discardConfirm.title': 'Discard this goal?','createGoal.describeTitle': 'What goal do you expect to achieve?','createGoal.describeHint': 'Describe the outcome first, then complete its execution plan.','createGoal.generateFailed':diff --git a/src/features/AgentGoals/CreateGoalModal/CreateGoalContent.tsx b/src/features/AgentGoals/CreateGoalModal/CreateGoalContent.tsxindex 8d821de226f..4c4f1acf793 100644--- a/src/features/AgentGoals/CreateGoalModal/CreateGoalContent.tsx+++ b/src/features/AgentGoals/CreateGoalModal/CreateGoalContent.tsx@@ -7,6 +7,7 @@ import { useEditor } from '@lobehub/editor/react';import {ActionIcon,Button,+ confirmModal,createStaticStyles,cssVar,Flexbox,@@ -37,6 +38,7 @@ import {CriterionRow,openCriterionEditModal,} from '@/features/Acceptance';+import { useEscapeDiscardGuard } from '@/features/AgentTasks/shared/useEscapeDiscardGuard';import { EditorCanvas } from '@/features/EditorCanvas';import { pickAndInsertAttachments } from '@/features/EditorCanvas/editorAttachments';import { usePermission } from '@/hooks/usePermission';@@ -47,6 +49,7 @@ import GoalAgentPill from '../GoalAgentPill';import { buildGoalAgents, buildGoalCreateInput, buildReviewedGoalContent } from './goalConfig';import { createFallbackGoalCriterion, generateGoalCriteria } from './goalCriteria';import { deriveGoalTitle } from './goalTitle';+import { hasUnsavedGoalDraft } from './hasUnsavedGoalDraft';const styles = createStaticStyles(({ css }) => ({budgetField: css`@@ -80,6 +83,7 @@ const styles = createStaticStyles(({ css }) => ({max-height: 320px;`,footer: css`+ flex-shrink: 0;padding-block: 8px;padding-inline: 16px;border-block-start: 1px solid ${cssVar.colorBorderSecondary};@@ -139,6 +143,7 @@ const styles = createStaticStyles(({ css }) => ({`,head: css`position: relative;+ min-height: 0;padding-block: 16px 8px;padding-inline: 16px;`,@@ -147,6 +152,13 @@ const styles = createStaticStyles(({ css }) => ({min-height: 208px;background: ${cssVar.colorBgElevated};`,+ /* A block (not flex) scroller: as a flex item the editor's overflow-hidden+ wrapper would shrink to fit and clip instead of scrolling. */+ inputScroller: css`+ overflow-y: auto;+ flex: 1;+ min-height: 0;+ `,instructionEditor: css`min-height: 36px;padding-block: 0 4px;@@ -436,10 +448,34 @@ const CreateGoalContent = memo<CreateGoalContentProps>((props) => {}}, []);+ // Escape is easy to hit by accident, so it asks before throwing away a+ // described or drafted goal; an untouched modal still closes straight away.+ const rootRef = useRef<HTMLDivElement>(null);+ useEscapeDiscardGuard(rootRef, {+ hasUnsavedInput: () =>+ hasUnsavedGoalDraft({+ editorJson: editor?.getDocument?.('json'),+ initialInstruction: initialRequirement ?? initialTitle,+ instruction: instructionRef.current,+ step,+ }),+ onEscape: () =>+ confirmModal({+ cancelText: t('createGoal.discardConfirm.cancel'),+ content: t('createGoal.discardConfirm.content'),+ okButtonProps: { danger: true },+ okText: t('createGoal.discardConfirm.ok'),+ onOk: close,+ title: t('createGoal.discardConfirm.title'),+ }),+ });+return (- <Flexbox onKeyDown={handleKeyDown}>- <Flexbox horizontal className={styles.head}>- <Flexbox flex={1} gap={6}>+ <Flexbox flex={1} ref={rootRef} style={{ minHeight: 0 }} onKeyDown={handleKeyDown}>+ {/* The describe step's editor lives in the head, so the head shrinks and+ its editor scrolls; on review only the body below scrolls. */}+ <Flexbox horizontal className={styles.head} style={{ flexShrink: step === 'review' ? 0 : 1 }}>+ <Flexbox flex={1} gap={6} style={{ minHeight: 0 }}>{step === 'review' && (<Flexbox horizontal align={'center'} gap={8}><ActionIcon@@ -467,16 +503,18 @@ const CreateGoalContent = memo<CreateGoalContentProps>((props) => {{step !== 'review' && (<><GeneratingBorder className={styles.inputShell} generating={step === 'preparing'}>- <EditorCanvas- disabled={!canCreate || step === 'preparing'}- editor={editor}- editorData={{ content: plan.instruction }}- entityId={'create-goal-description'}- floatingToolbar={false}- placeholder={t('createGoal.instructionPlaceholder')}- style={{ fontSize: 14, minHeight: 206, padding: 16 }}- onContentChange={handleContentChange}- />+ <div className={styles.inputScroller}>+ <EditorCanvas+ disabled={!canCreate || step === 'preparing'}+ editor={editor}+ editorData={{ content: plan.instruction }}+ entityId={'create-goal-description'}+ floatingToolbar={false}+ placeholder={t('createGoal.instructionPlaceholder')}+ style={{ fontSize: 14, minHeight: 206, padding: 16 }}+ onContentChange={handleContentChange}+ />+ </div></GeneratingBorder>{step === 'preparing' ? (<Flexboxdiff --git a/src/features/AgentGoals/CreateGoalModal/hasUnsavedGoalDraft.test.ts b/src/features/AgentGoals/CreateGoalModal/hasUnsavedGoalDraft.test.tsnew file mode 100644index 00000000000..6ac0fb09146--- /dev/null+++ b/src/features/AgentGoals/CreateGoalModal/hasUnsavedGoalDraft.test.ts@@ -0,0 +1,63 @@+import { describe, expect, it } from 'vitest';++import { hasUnsavedGoalDraft } from './hasUnsavedGoalDraft';++const docWith = (...children: unknown[]) => ({+ root: { children: [{ children, type: 'paragraph' }], type: 'root' },+});++describe('hasUnsavedGoalDraft', () => {+ it('is clean for an untouched modal', () => {+ expect(hasUnsavedGoalDraft({ editorJson: docWith(), instruction: '', step: 'describe' })).toBe(+ false,+ );+ });++ it('ignores whitespace-only text', () => {+ expect(+ hasUnsavedGoalDraft({ editorJson: docWith(), instruction: ' \n', step: 'describe' }),+ ).toBe(false);+ });++ it('counts a typed description', () => {+ expect(+ hasUnsavedGoalDraft({ editorJson: docWith(), instruction: 'Ship it', step: 'describe' }),+ ).toBe(true);+ });++ it('treats an unchanged example seed as clean, and an edited one as unsaved', () => {+ const seeded = { editorJson: docWith(), initialInstruction: 'Write a report' };+ expect(+ hasUnsavedGoalDraft({ ...seeded, instruction: 'Write a report\n', step: 'describe' }),+ ).toBe(false);+ expect(+ hasUnsavedGoalDraft({ ...seeded, instruction: 'Write a long report', step: 'describe' }),+ ).toBe(true);+ });++ it('counts an attachment, uploaded or not', () => {+ const uploaded = docWith({ fileUrl: 'https://x/a.png', status: 'uploaded', type: 'image' });+ const uploading = docWith({ status: 'pending', type: 'file' });+ expect(hasUnsavedGoalDraft({ editorJson: uploaded, instruction: '', step: 'describe' })).toBe(+ true,+ );+ expect(hasUnsavedGoalDraft({ editorJson: uploading, instruction: '', step: 'describe' })).toBe(+ true,+ );+ });++ it('always counts a draft past the describe step', () => {+ expect(hasUnsavedGoalDraft({ editorJson: undefined, instruction: '', step: 'preparing' })).toBe(+ true,+ );+ expect(hasUnsavedGoalDraft({ editorJson: undefined, instruction: '', step: 'review' })).toBe(+ true,+ );+ });++ it('is clean when there is no editor document yet', () => {+ expect(hasUnsavedGoalDraft({ editorJson: undefined, instruction: '', step: 'describe' })).toBe(+ false,+ );+ });+});diff --git a/src/features/AgentGoals/CreateGoalModal/hasUnsavedGoalDraft.ts b/src/features/AgentGoals/CreateGoalModal/hasUnsavedGoalDraft.tsnew file mode 100644index 00000000000..f4300bb5fca--- /dev/null+++ b/src/features/AgentGoals/CreateGoalModal/hasUnsavedGoalDraft.ts@@ -0,0 +1,32 @@+import { getEditorAttachmentStateFromJson } from '@/features/EditorCanvas/editorAttachments';++interface GoalDraft {+ /** The description editor's JSON document. */+ editorJson: unknown;+ /** Text the modal was opened with (an empty-state example), if any. */+ initialInstruction?: string;+ instruction: string;+ step: 'describe' | 'preparing' | 'review';+}++/**+ * Whether closing the create-goal modal would throw away something the user+ * put in. Past the describe step there is always a drafted plan to lose; an+ * untouched example seed does not count. Attachments count while still+ * uploading or after a failed upload, as they are missing from the markdown.+ */+export const hasUnsavedGoalDraft = ({+ editorJson,+ initialInstruction = '',+ instruction,+ step,+}: GoalDraft): boolean => {+ if (step !== 'describe') return true;++ const text = instruction.trim();+ if (text && text !== initialInstruction.trim()) return true;++ const { hasCompletedAttachments, hasIncompleteAttachments } =+ getEditorAttachmentStateFromJson(editorJson);+ return hasCompletedAttachments || hasIncompleteAttachments;+};diff --git a/src/features/AgentGoals/CreateGoalModal/index.tsx b/src/features/AgentGoals/CreateGoalModal/index.tsxindex c5cc1f50fcc..2fc23bc22d6 100644--- a/src/features/AgentGoals/CreateGoalModal/index.tsx+++ b/src/features/AgentGoals/CreateGoalModal/index.tsx@@ -12,7 +12,12 @@ export const createGoalModal = (props?: CreateGoalContentProps): ModalInstance =footer: null,maskClosable: false,styles: {+ // The popup caps itself at the viewport height; let the body shrink into+ // it so the long content scrolls while the footer stays pinned.content: {+ display: 'flex',+ flexDirection: 'column',+ minHeight: 0,overflow: 'hidden',padding: 0,},diff --git a/src/features/AgentTasks/CreateTaskModal/CreateTaskContent.tsx b/src/features/AgentTasks/CreateTaskModal/CreateTaskContent.tsxindex 13ce59b46ae..1ba05bf82c6 100644--- a/src/features/AgentTasks/CreateTaskModal/CreateTaskContent.tsx+++ b/src/features/AgentTasks/CreateTaskModal/CreateTaskContent.tsx@@ -42,6 +42,7 @@ import TaskVisibilityTag from '../features/TaskVisibilityTag';import { UnassignedAssigneeIcon } from '../features/UnassignedAssigneeIcon';import { useAgentDisplayMeta } from '../shared/useAgentDisplayMeta';import { useAgentVisibility } from '../shared/useAgentVisibility';+import { useEscapeDiscardGuard } from '../shared/useEscapeDiscardGuard';import { useUserDisplayMeta } from '../shared/useUserDisplayMeta';import { hasUnsavedTaskDraft } from './hasUnsavedTaskDraft';import ScheduleChip from './ScheduleChip';@@ -50,7 +51,6 @@ import {type ScheduleDraft,toScheduledCreateParams,} from './scheduleDraft';-import { useEscapeDiscardGuard } from './useEscapeDiscardGuard';import { useTitleEnterToInstruction } from './useTitleEnterToInstruction';export interface CreateTaskContentProps {diff --git a/src/features/AgentTasks/CreateTaskModal/useEscapeDiscardGuard.test.ts b/src/features/AgentTasks/shared/useEscapeDiscardGuard.test.tssimilarity index 72%rename from src/features/AgentTasks/CreateTaskModal/useEscapeDiscardGuard.test.tsrename to src/features/AgentTasks/shared/useEscapeDiscardGuard.test.tsindex bc0cccdc11d..e9a04be1139 100644--- a/src/features/AgentTasks/CreateTaskModal/useEscapeDiscardGuard.test.ts+++ b/src/features/AgentTasks/shared/useEscapeDiscardGuard.test.ts@@ -131,6 +131,59 @@ describe('useEscapeDiscardGuard', () => {expect(ctx.onEscape).not.toHaveBeenCalled();});+ it('guards Escape after focus fell back to the page body', () => {+ const ctx = setup(() => true);+ cleanup = ctx.cleanup;++ // Clicking the modal mask leaves focus on <body>, outside the popup.+ pressEscape(document.body);++ expect(ctx.onEscape).toHaveBeenCalledTimes(1);+ expect(ctx.dismiss).not.toHaveBeenCalled();+ });++ it('lets Escape on the page body close a clean modal', () => {+ const ctx = setup(() => false);+ cleanup = ctx.cleanup;++ pressEscape(document.body);++ expect(ctx.onEscape).not.toHaveBeenCalled();+ expect(ctx.dismiss).toHaveBeenCalledTimes(1);+ });++ it('leaves Escape on the page body to a dialog stacked above the modal', () => {+ const ctx = setup(() => true);+ const stacked = document.createElement('div');+ stacked.setAttribute('role', 'dialog');+ document.body.append(stacked);+ cleanup = () => {+ stacked.remove();+ ctx.cleanup();+ };++ pressEscape(document.body);++ expect(ctx.onEscape).not.toHaveBeenCalled();+ expect(ctx.dismiss).toHaveBeenCalledTimes(1);+ });++ it('ignores a listbox that was already on the page below the modal', () => {+ const listbox = document.createElement('div');+ listbox.setAttribute('role', 'listbox');+ document.body.prepend(listbox);+ const ctx = setup(() => true);+ cleanup = () => {+ ctx.cleanup();+ listbox.remove();+ };++ pressEscape(document.body);++ expect(ctx.onEscape).toHaveBeenCalledTimes(1);+ expect(ctx.dismiss).not.toHaveBeenCalled();+ });+it('does not intercept Escape from a picker portalled outside the popup', () => {const ctx = setup(() => true);cleanup = ctx.cleanup;diff --git a/src/features/AgentTasks/CreateTaskModal/useEscapeDiscardGuard.ts b/src/features/AgentTasks/shared/useEscapeDiscardGuard.tssimilarity index 55%rename from src/features/AgentTasks/CreateTaskModal/useEscapeDiscardGuard.tsrename to src/features/AgentTasks/shared/useEscapeDiscardGuard.tsindex 9d628ff7ba8..2fa689cb804 100644--- a/src/features/AgentTasks/CreateTaskModal/useEscapeDiscardGuard.ts+++ b/src/features/AgentTasks/shared/useEscapeDiscardGuard.ts@@ -1,5 +1,9 @@import { type RefObject, useEffect, useRef } from 'react';+/** Open layers that take Escape before the modal underneath them. */+const OVERLAY_LAYER_SELECTOR =+ '[role="dialog"], [role="alertdialog"], [role="menu"], [role="listbox"]';+interface EscapeDiscardGuardOptions {/** Read at keypress time, so it can look at refs as well as state. */hasUnsavedInput: () => boolean;@@ -14,6 +18,10 @@ interface EscapeDiscardGuardOptions {* the dialog popup keeps it from getting there. Pickers and menus opened from* the modal are portalled outside the popup, so Escape still closes just them;* an empty modal still closes on Escape as before.+ *+ * Clicking the modal mask drops focus onto `<body>`, where Escape never passes+ * through the popup. That case is caught on `window` before the dialog sees it,+ * unless another layer is open on top of the modal and owns the key.*/export const useEscapeDiscardGuard = (anchorRef: RefObject<HTMLElement | null>,@@ -40,7 +48,24 @@ export const useEscapeDiscardGuard = (optionsRef.current.onEscape();};+ const handlePageKeyDown = (event: KeyboardEvent) => {+ if (event.target !== document.body && event.target !== document.documentElement) return;+ // Layers are portalled in opening order, so only one mounted after the+ // popup sits above it; a listbox already on the page does not.+ const hasLayerAbove = Array.from(document.querySelectorAll(OVERLAY_LAYER_SELECTOR)).some(+ (layer) =>+ !popup.contains(layer) &&+ Boolean(popup.compareDocumentPosition(layer) & Node.DOCUMENT_POSITION_FOLLOWING),+ );+ if (hasLayerAbove) return;+ handleKeyDown(event);+ };+popup.addEventListener('keydown', handleKeyDown);- return () => popup.removeEventListener('keydown', handleKeyDown);+ window.addEventListener('keydown', handlePageKeyDown, true);+ return () => {+ popup.removeEventListener('keydown', handleKeyDown);+ window.removeEventListener('keydown', handlePageKeyDown, true);+ };}, [anchorRef]);};