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): confirm before Escape discards a filled-in new-task modal (#21922)

Rdmclin2b84627d6f22d
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index 23cc853fe46..95bdce2dc2f 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -351,6 +351,10 @@
"createTask.assignee": "Agent",
"createTask.collapse": "Hide input",
"createTask.createFailed": "Failed to create task",
+ "createTask.discardConfirm.cancel": "Keep editing",
+ "createTask.discardConfirm.content": "The title, instruction and attachments you added will be lost.",
+ "createTask.discardConfirm.ok": "Discard",
+ "createTask.discardConfirm.title": "Discard this task?",
"createTask.expandToInline": "Dock to page",
"createTask.instructionPlaceholder": "Add task instruction...",
"createTask.member": "Assignee",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index 4fe35e8111d..03207708e0f 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -351,6 +351,10 @@
"createTask.assignee": "助理",
"createTask.collapse": "隐藏输入",
"createTask.createFailed": "创建任务失败",
+ "createTask.discardConfirm.cancel": "继续编辑",
+ "createTask.discardConfirm.content": "已填写的标题、指令和附件都会丢失。",
+ "createTask.discardConfirm.ok": "放弃",
+ "createTask.discardConfirm.title": "放弃这个任务?",
"createTask.expandToInline": "固定到页面",
"createTask.instructionPlaceholder": "添加描述…",
"createTask.member": "负责人",
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index 0ea9d375625..67da95e9ce5 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -2267,6 +2267,11 @@ export default {
'createTask.member': 'Assignee',
'createTask.collapse': 'Hide input',
'createTask.createFailed': 'Failed to create task',
+ 'createTask.discardConfirm.cancel': 'Keep editing',
+ 'createTask.discardConfirm.content':
+ 'The title, instruction and attachments you added will be lost.',
+ 'createTask.discardConfirm.ok': 'Discard',
+ 'createTask.discardConfirm.title': 'Discard this task?',
'createTask.expandToInline': 'Dock to page',
'createTask.instructionPlaceholder': 'Add task instruction...',
'createTask.submit': 'Create task',
diff --git a/src/features/AgentTasks/CreateTaskModal/CreateTaskContent.tsx b/src/features/AgentTasks/CreateTaskModal/CreateTaskContent.tsx
index 53a738af705..ec27a91995a 100644
--- a/src/features/AgentTasks/CreateTaskModal/CreateTaskContent.tsx
+++ b/src/features/AgentTasks/CreateTaskModal/CreateTaskContent.tsx
@@ -7,6 +7,7 @@ import {
ActionIcon,
Block,
Button,
+ confirmModal,
cssVar,
Flexbox,
Text,
@@ -42,12 +43,14 @@ import { UnassignedAssigneeIcon } from '../features/UnassignedAssigneeIcon';
import { useAgentDisplayMeta } from '../shared/useAgentDisplayMeta';
import { useAgentVisibility } from '../shared/useAgentVisibility';
import { useUserDisplayMeta } from '../shared/useUserDisplayMeta';
+import { hasUnsavedTaskDraft } from './hasUnsavedTaskDraft';
import ScheduleChip from './ScheduleChip';
import {
createDefaultScheduleDraft,
type ScheduleDraft,
toScheduledCreateParams,
} from './scheduleDraft';
+import { useEscapeDiscardGuard } from './useEscapeDiscardGuard';
import { useTitleEnterToInstruction } from './useTitleEnterToInstruction';
export interface CreateTaskContentProps {
@@ -240,12 +243,33 @@ const CreateTaskContent = memo<CreateTaskContentProps>(
const handleTitleKeyDown = useTitleEnterToInstruction(editor);
+ // Escape is easy to hit by accident, so it asks before throwing away a
+ // filled-in task; an empty modal still closes straight away.
+ const rootRef = useRef<HTMLDivElement>(null);
+ useEscapeDiscardGuard(rootRef, {
+ hasUnsavedInput: () =>
+ hasUnsavedTaskDraft({
+ editorJson: editor?.getDocument?.('json'),
+ instruction: instructionRef.current,
+ title,
+ }),
+ onEscape: () =>
+ confirmModal({
+ cancelText: t('createTask.discardConfirm.cancel'),
+ content: t('createTask.discardConfirm.content'),
+ okButtonProps: { danger: true },
+ okText: t('createTask.discardConfirm.ok'),
+ onOk: close,
+ title: t('createTask.discardConfirm.title'),
+ }),
+ });
+
// An image pasted into the instruction finishes uploading later; without
// this, that update would move the caret back from the title mid-typing.
const handleTitleFocus = useCallback(() => releaseEditorSelection(editor), [editor]);
return (
- <Flexbox flex={1} style={{ minHeight: 0 }} onKeyDown={handleKeyDown}>
+ <Flexbox flex={1} ref={rootRef} style={{ minHeight: 0 }} onKeyDown={handleKeyDown}>
<Flexbox
horizontal
align={'center'}
diff --git a/src/features/AgentTasks/CreateTaskModal/hasUnsavedTaskDraft.test.ts b/src/features/AgentTasks/CreateTaskModal/hasUnsavedTaskDraft.test.ts
new file mode 100644
index 00000000000..46788424215
--- /dev/null
+++ b/src/features/AgentTasks/CreateTaskModal/hasUnsavedTaskDraft.test.ts
@@ -0,0 +1,44 @@
+import { describe, expect, it } from 'vitest';
+
+import { hasUnsavedTaskDraft } from './hasUnsavedTaskDraft';
+
+const docWith = (...children: unknown[]) => ({
+ root: { children: [{ children, type: 'paragraph' }], type: 'root' },
+});
+
+describe('hasUnsavedTaskDraft', () => {
+ it('is clean for an untouched modal', () => {
+ expect(hasUnsavedTaskDraft({ editorJson: docWith(), instruction: '', title: '' })).toBe(false);
+ });
+
+ it('ignores whitespace-only text', () => {
+ expect(hasUnsavedTaskDraft({ editorJson: docWith(), instruction: ' \n', title: ' ' })).toBe(
+ false,
+ );
+ });
+
+ it('counts a title or an instruction', () => {
+ expect(hasUnsavedTaskDraft({ editorJson: docWith(), instruction: '', title: 'Ship' })).toBe(
+ true,
+ );
+ expect(hasUnsavedTaskDraft({ editorJson: docWith(), instruction: 'Do it', title: '' })).toBe(
+ true,
+ );
+ });
+
+ it('counts an uploaded attachment', () => {
+ const editorJson = docWith({ fileUrl: 'https://x/f.pdf', status: 'uploaded', type: 'file' });
+ expect(hasUnsavedTaskDraft({ editorJson, instruction: '', title: '' })).toBe(true);
+ });
+
+ it('counts an attachment that is still uploading or failed', () => {
+ const uploading = docWith({ status: 'pending', type: 'file' });
+ const failed = docWith({ status: 'error', type: 'image' });
+ expect(hasUnsavedTaskDraft({ editorJson: uploading, instruction: '', title: '' })).toBe(true);
+ expect(hasUnsavedTaskDraft({ editorJson: failed, instruction: '', title: '' })).toBe(true);
+ });
+
+ it('is clean when there is no editor document yet', () => {
+ expect(hasUnsavedTaskDraft({ editorJson: undefined, instruction: '', title: '' })).toBe(false);
+ });
+});
diff --git a/src/features/AgentTasks/CreateTaskModal/hasUnsavedTaskDraft.ts b/src/features/AgentTasks/CreateTaskModal/hasUnsavedTaskDraft.ts
new file mode 100644
index 00000000000..e255982d9a1
--- /dev/null
+++ b/src/features/AgentTasks/CreateTaskModal/hasUnsavedTaskDraft.ts
@@ -0,0 +1,21 @@
+import { getEditorAttachmentStateFromJson } from '@/features/EditorCanvas/editorAttachments';
+
+interface TaskDraft {
+ /** The instruction editor's JSON document. */
+ editorJson: unknown;
+ instruction: string;
+ title: string;
+}
+
+/**
+ * Whether closing the create-task modal would throw away something the user
+ * put in. Attachments count while still uploading or after a failed upload:
+ * they are visible in the draft but missing from the markdown instruction.
+ */
+export const hasUnsavedTaskDraft = ({ editorJson, instruction, title }: TaskDraft): boolean => {
+ if (title.trim() || instruction.trim()) return true;
+
+ const { hasCompletedAttachments, hasIncompleteAttachments } =
+ getEditorAttachmentStateFromJson(editorJson);
+ return hasCompletedAttachments || hasIncompleteAttachments;
+};
diff --git a/src/features/AgentTasks/CreateTaskModal/useEscapeDiscardGuard.test.ts b/src/features/AgentTasks/CreateTaskModal/useEscapeDiscardGuard.test.ts
new file mode 100644
index 00000000000..bc0cccdc11d
--- /dev/null
+++ b/src/features/AgentTasks/CreateTaskModal/useEscapeDiscardGuard.test.ts
@@ -0,0 +1,143 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { renderHook } from '@testing-library/react';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { useEscapeDiscardGuard } from './useEscapeDiscardGuard';
+
+/**
+ * Mirrors the modal DOM: a dialog popup holding the content, with the dialog's
+ * own Escape dismissal listening on `document` like Base UI does.
+ */
+const setup = (hasUnsavedInput: () => boolean) => {
+ const popup = document.createElement('div');
+ popup.setAttribute('role', 'dialog');
+ const content = document.createElement('div');
+ const input = document.createElement('input');
+ content.append(input);
+ popup.append(content);
+ // A picker opened from the modal is portalled outside the popup.
+ const portalledPicker = document.createElement('input');
+ document.body.append(popup, portalledPicker);
+
+ const dismiss = vi.fn();
+ const dismissOnEscape = (event: KeyboardEvent) => {
+ if (event.key === 'Escape') dismiss();
+ };
+ document.addEventListener('keydown', dismissOnEscape);
+
+ const onEscape = vi.fn();
+ const hook = renderHook(() =>
+ useEscapeDiscardGuard({ current: content }, { hasUnsavedInput, onEscape }),
+ );
+
+ const cleanup = () => {
+ hook.unmount();
+ document.removeEventListener('keydown', dismissOnEscape);
+ popup.remove();
+ portalledPicker.remove();
+ };
+
+ return { cleanup, dismiss, input, onEscape, popup, portalledPicker };
+};
+
+const pressEscape = (target: HTMLElement, init: KeyboardEventInit = {}) => {
+ const event = new KeyboardEvent('keydown', {
+ bubbles: true,
+ cancelable: true,
+ key: 'Escape',
+ ...init,
+ });
+ target.dispatchEvent(event);
+ return event;
+};
+
+let cleanup: (() => void) | undefined;
+afterEach(() => {
+ cleanup?.();
+ cleanup = undefined;
+});
+
+describe('useEscapeDiscardGuard', () => {
+ it('lets Escape close an empty modal as before', () => {
+ const ctx = setup(() => false);
+ cleanup = ctx.cleanup;
+
+ pressEscape(ctx.input);
+
+ expect(ctx.dismiss).toHaveBeenCalledTimes(1);
+ expect(ctx.onEscape).not.toHaveBeenCalled();
+ });
+
+ it('asks instead of closing when there is unsaved input', () => {
+ const ctx = setup(() => true);
+ cleanup = ctx.cleanup;
+
+ const event = pressEscape(ctx.input);
+
+ expect(ctx.onEscape).toHaveBeenCalledTimes(1);
+ expect(ctx.dismiss).not.toHaveBeenCalled();
+ expect(event.defaultPrevented).toBe(true);
+ });
+
+ it('also guards Escape pressed with focus on the popup itself', () => {
+ const ctx = setup(() => true);
+ cleanup = ctx.cleanup;
+
+ pressEscape(ctx.popup);
+
+ expect(ctx.onEscape).toHaveBeenCalledTimes(1);
+ expect(ctx.dismiss).not.toHaveBeenCalled();
+ });
+
+ it('reads the unsaved state at keypress time', () => {
+ let dirty = false;
+ const ctx = setup(() => dirty);
+ cleanup = ctx.cleanup;
+
+ dirty = true;
+ pressEscape(ctx.input);
+
+ expect(ctx.onEscape).toHaveBeenCalledTimes(1);
+ expect(ctx.dismiss).not.toHaveBeenCalled();
+ });
+
+ it('ignores other keys', () => {
+ const ctx = setup(() => true);
+ cleanup = ctx.cleanup;
+
+ pressEscape(ctx.input, { key: 'Enter' });
+
+ expect(ctx.onEscape).not.toHaveBeenCalled();
+ });
+
+ it('leaves Escape that cancels an IME composition alone', () => {
+ const ctx = setup(() => true);
+ cleanup = ctx.cleanup;
+
+ pressEscape(ctx.input, { isComposing: true });
+
+ expect(ctx.onEscape).not.toHaveBeenCalled();
+ });
+
+ it('leaves Escape already handled inside the modal alone', () => {
+ const ctx = setup(() => true);
+ cleanup = ctx.cleanup;
+ ctx.input.addEventListener('keydown', (event) => event.preventDefault());
+
+ pressEscape(ctx.input);
+
+ expect(ctx.onEscape).not.toHaveBeenCalled();
+ });
+
+ it('does not intercept Escape from a picker portalled outside the popup', () => {
+ const ctx = setup(() => true);
+ cleanup = ctx.cleanup;
+
+ pressEscape(ctx.portalledPicker);
+
+ expect(ctx.onEscape).not.toHaveBeenCalled();
+ expect(ctx.dismiss).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/src/features/AgentTasks/CreateTaskModal/useEscapeDiscardGuard.ts b/src/features/AgentTasks/CreateTaskModal/useEscapeDiscardGuard.ts
new file mode 100644
index 00000000000..9d628ff7ba8
--- /dev/null
+++ b/src/features/AgentTasks/CreateTaskModal/useEscapeDiscardGuard.ts
@@ -0,0 +1,46 @@
+import { type RefObject, useEffect, useRef } from 'react';
+
+interface EscapeDiscardGuardOptions {
+ /** Read at keypress time, so it can look at refs as well as state. */
+ hasUnsavedInput: () => boolean;
+ /** Called instead of closing when Escape would discard unsaved input. */
+ onEscape: () => void;
+}
+
+/**
+ * Stops Escape from silently discarding a filled-in modal.
+ *
+ * The dialog closes on a `document` keydown listener, so stopping the event at
+ * 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.
+ */
+export const useEscapeDiscardGuard = (
+ anchorRef: RefObject<HTMLElement | null>,
+ options: EscapeDiscardGuardOptions,
+) => {
+ const optionsRef = useRef(options);
+ useEffect(() => {
+ optionsRef.current = options;
+ });
+
+ useEffect(() => {
+ const anchor = anchorRef.current;
+ if (!anchor) return;
+ const popup = anchor.closest<HTMLElement>('[role="dialog"]') ?? anchor;
+
+ const handleKeyDown = (event: KeyboardEvent) => {
+ if (event.key !== 'Escape' || event.defaultPrevented) return;
+ // Escape while composing cancels the IME; Safari reports it as keyCode 229.
+ if (event.isComposing || event.keyCode === 229) return;
+ if (!optionsRef.current.hasUnsavedInput()) return;
+
+ event.preventDefault();
+ event.stopPropagation();
+ optionsRef.current.onEscape();
+ };
+
+ popup.addEventListener('keydown', handleKeyDown);
+ return () => popup.removeEventListener('keydown', handleKeyDown);
+ }, [anchorRef]);
+};