🤯 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
✨ feat(task): find in the task detail page with Mod+F (#22267)
Rdmclin2b54bfc122d9e
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex 2d8118d089b..6d891ff0cbc 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -2484,6 +2484,13 @@"taskDetail.deleteConfirm.content": "The task moves to the trash with its runs and can be restored within 30 days.","taskDetail.deleteConfirm.ok": "Delete","taskDetail.deleteConfirm.title": "Delete this task?",+ "taskDetail.find.close": "Close find",+ "taskDetail.find.empty": "No results",+ "taskDetail.find.next": "Next match",+ "taskDetail.find.open": "Find in task",+ "taskDetail.find.placeholder": "Find in this task",+ "taskDetail.find.position": "{{current}}/{{total}}",+ "taskDetail.find.prev": "Previous match","taskDetail.followUpFailed": "Couldn’t send the follow-up. Your message is kept — try again.","taskDetail.goalTimeline.hover.cost": "Cost","taskDetail.goalTimeline.hover.duration": "Duration",diff --git a/locales/en-US/hotkey.json b/locales/en-US/hotkey.jsonindex 7c2577f16f1..5671cbf2030 100644--- a/locales/en-US/hotkey.json+++ b/locales/en-US/hotkey.json@@ -17,8 +17,8 @@"desktop.showApp.title": "Show/Hide Main Window","editMessage.desc": "Enter edit mode by holding Alt and double-clicking the message","editMessage.title": "Edit Message",- "findInTopic.desc": "Search every message of the current topic in the right panel",- "findInTopic.title": "Find in Topic",+ "findInTopic.desc": "Search every message of the current topic in the right panel, or find text on the open task page",+ "findInTopic.title": "Find in Topic or Task","navigateToChat.desc": "Switch to the Chat tab and enter Lobe AI","navigateToChat.title": "Switch to Default Chat","nextTab.desc": "Cycle to the next browser-style tab in the Desktop app; wraps around to the first tab at the end",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex 580cf7b9c1e..421a9923ca4 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -2484,6 +2484,13 @@"taskDetail.deleteConfirm.content": "任务及其运行记录会移入回收站,30 天内可以恢复。","taskDetail.deleteConfirm.ok": "删除","taskDetail.deleteConfirm.title": "确认删除此任务?",+ "taskDetail.find.close": "关闭查找",+ "taskDetail.find.empty": "无结果",+ "taskDetail.find.next": "下一个",+ "taskDetail.find.open": "在任务中查找",+ "taskDetail.find.placeholder": "在当前任务中查找",+ "taskDetail.find.position": "{{current}}/{{total}}",+ "taskDetail.find.prev": "上一个","taskDetail.followUpFailed": "追问未发送成功,内容已保留,请重试。","taskDetail.goalTimeline.hover.cost": "成本","taskDetail.goalTimeline.hover.duration": "时长",diff --git a/locales/zh-CN/hotkey.json b/locales/zh-CN/hotkey.jsonindex e9236455e4f..5ee57777f33 100644--- a/locales/zh-CN/hotkey.json+++ b/locales/zh-CN/hotkey.json@@ -17,8 +17,8 @@"desktop.showApp.title": "显示/隐藏主窗口","editMessage.desc": "通过按住 Alt 并双击消息进入编辑模式","editMessage.title": "编辑消息",- "findInTopic.desc": "在右侧面板中搜索当前话题的所有消息",- "findInTopic.title": "在话题中查找",+ "findInTopic.desc": "在右侧面板中搜索当前话题的所有消息;在任务详情页中查找任务内容",+ "findInTopic.title": "在话题或任务中查找","navigateToChat.desc": "切换至会话标签并进入Lobe AI","navigateToChat.title": "切换至默认会话","nextTab.desc": "在桌面端标签页之间循环切换,到达末尾后跳回第一个标签页",diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex 86d4894461b..ee89029557e 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -2162,6 +2162,13 @@ export default {'taskDetail.reportedByAgent': 'the agent','taskDetail.runFollowUp': 'Ask a follow-up','taskDetail.runFollowUpPlaceholder': 'Ask a follow-up about this run...',+ 'taskDetail.find.close': 'Close find',+ 'taskDetail.find.empty': 'No results',+ 'taskDetail.find.next': 'Next match',+ 'taskDetail.find.open': 'Find in task',+ 'taskDetail.find.placeholder': 'Find in this task',+ 'taskDetail.find.position': '{{current}}/{{total}}',+ 'taskDetail.find.prev': 'Previous match','taskDetail.followUpFailed': 'Couldn’t send the follow-up. Your message is kept — try again.','taskDetail.collapseReply': 'Collapse','taskDetail.replyInThread': 'Reply in this thread',diff --git a/packages/locales/src/default/hotkey.ts b/packages/locales/src/default/hotkey.tsindex 8f649aee01b..f436f405234 100644--- a/packages/locales/src/default/hotkey.ts+++ b/packages/locales/src/default/hotkey.ts@@ -17,8 +17,9 @@ export default {'desktop.showApp.title': 'Show/Hide Main Window','editMessage.desc': 'Enter edit mode by holding Alt and double-clicking the message','editMessage.title': 'Edit Message',- 'findInTopic.desc': 'Search every message of the current topic in the right panel',- 'findInTopic.title': 'Find in Topic',+ 'findInTopic.desc':+ 'Search every message of the current topic in the right panel, or find text on the open task page',+ 'findInTopic.title': 'Find in Topic or Task','navigateToChat.desc': 'Switch to the Chat tab and enter Lobe AI','navigateToChat.title': 'Switch to Default Chat','nextTab.desc':diff --git a/src/components/CollapsibleContent/index.tsx b/src/components/CollapsibleContent/index.tsxindex d9274e0b2a4..48edb573706 100644--- a/src/components/CollapsibleContent/index.tsx+++ b/src/components/CollapsibleContent/index.tsx@@ -4,9 +4,11 @@ import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';import * as stylex from '@stylexjs/stylex';import { ChevronDownIcon, ChevronUpIcon } from 'lucide-react';import type { CSSProperties, ReactNode } from 'react';-import { memo, useRef } from 'react';+import { memo, useEffect, useRef } from 'react';import { useTranslation } from 'react-i18next';+import { REVEAL_IN_PAGE_EVENT, type RevealInPageEvent } from '@/utils/findInDom';+import { useCollapsible } from './useCollapsible';const DEFAULT_MAX_HEIGHT = 280;@@ -85,6 +87,7 @@ const CollapsibleContent = memo<CollapsibleContentProps>(const contentRef = useRef<HTMLDivElement | null>(null);const {+ expand,isCollapsed,maxHeight,shouldCollapse,@@ -99,6 +102,20 @@ const CollapsibleContent = memo<CollapsibleContentProps>(overflowThreshold,});+ // Find in page landed on text clipped by the clamp: open so it can be seen.+ useEffect(() => {+ const content = contentRef.current;+ if (!content || !isCollapsed) return;+ const handleReveal = (event: Event) => {+ const { bottom } = (event as RevealInPageEvent).detail;+ const fade = Math.min(DEFAULT_FADE_HEIGHT, maxHeight * FADE_RATIO);+ // Text under the fade mask counts as hidden too.+ if (bottom > content.getBoundingClientRect().bottom - fade) expand();+ };+ content.addEventListener(REVEAL_IN_PAGE_EVENT, handleReveal);+ return () => content.removeEventListener(REVEAL_IN_PAGE_EVENT, handleReveal);+ }, [expand, isCollapsed, maxHeight]);+return (<div {...stylex.props(styles.container)}><divdiff --git a/src/components/CollapsibleContent/useCollapsible.test.ts b/src/components/CollapsibleContent/useCollapsible.test.tsindex 917f3ed5650..4fac26325db 100644--- a/src/components/CollapsibleContent/useCollapsible.test.ts+++ b/src/components/CollapsibleContent/useCollapsible.test.ts@@ -111,4 +111,28 @@ describe('useCollapsible', () => {expect(onOverflowChange).toHaveBeenCalledTimes(1);});++ it('expand opens a collapsed preview and never collapses an open one', () => {+ const onCollapsedChange = vi.fn();+ const { result } = renderHook(() => useCollapsible(options({ onCollapsedChange })));++ expect(result.current.isCollapsed).toBe(true);+ act(() => result.current.expand());+ expect(result.current.isCollapsed).toBe(false);+ expect(onCollapsedChange).toHaveBeenCalledWith(false);++ act(() => result.current.expand());+ expect(onCollapsedChange).toHaveBeenCalledTimes(1);+ });++ it('expand asks a controlled host to open instead of flipping local state', () => {+ const onCollapsedChange = vi.fn();+ const { result } = renderHook(() =>+ useCollapsible(options({ collapsed: true, onCollapsedChange })),+ );++ act(() => result.current.expand());+ expect(onCollapsedChange).toHaveBeenCalledWith(false);+ expect(result.current.isCollapsed).toBe(true);+ });});diff --git a/src/components/CollapsibleContent/useCollapsible.ts b/src/components/CollapsibleContent/useCollapsible.tsindex fc9cef8ced5..90a86edc931 100644--- a/src/components/CollapsibleContent/useCollapsible.ts+++ b/src/components/CollapsibleContent/useCollapsible.ts@@ -78,7 +78,15 @@ export const useCollapsible = ({[collapsed, collapsedProp, onCollapsedChange],);+ // Opens without toggling: find landing on a hidden match only ever expands.+ const expand = useCallback(() => {+ if (!collapsed) return;+ if (collapsedProp === undefined) setUncontrolledCollapsed(false);+ onCollapsedChange?.(false);+ }, [collapsed, collapsedProp, onCollapsedChange]);+return {+ expand,/** Whether the clamp and fade mask are actually applied right now. */isCollapsed: shouldCollapse && collapsed,maxHeight,diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskDetailPage.tsx b/src/features/AgentTasks/AgentTaskDetail/TaskDetailPage.tsxindex 9f96a61d6f1..58ed952bd73 100644--- a/src/features/AgentTasks/AgentTaskDetail/TaskDetailPage.tsx+++ b/src/features/AgentTasks/AgentTaskDetail/TaskDetailPage.tsx@@ -1,4 +1,6 @@-import { Button, Flexbox } from '@lobehub/ui';+import { HotkeyEnum } from '@lobechat/const/hotkeys';+import { ActionIcon, Button, Flexbox } from '@lobehub/ui';+import { SearchIcon } from 'lucide-react';import { memo } from 'react';import { useTranslation } from 'react-i18next';import { Link } from 'react-router';@@ -6,6 +8,7 @@ import { Link } from 'react-router';import NotFound from '@/components/404';import AsyncError from '@/components/AsyncError';import AutoSaveHint from '@/components/Editor/AutoSaveHint';+import { DESKTOP_HEADER_ICON_SMALL_SIZE } from '@/const/layoutTokens';import NavHeader from '@/features/NavHeader';import ToggleRightPanelButton from '@/features/RightPanel/ToggleRightPanelButton';import WideScreenContainer from '@/features/WideScreenContainer';@@ -13,12 +16,15 @@ import { useGlobalStore } from '@/store/global';import { systemStatusSelectors } from '@/store/global/selectors';import { useTaskStore } from '@/store/task';import { taskDetailSelectors } from '@/store/task/selectors';+import { useUserStore } from '@/store/user';+import { settingsSelectors } from '@/store/user/selectors';import Breadcrumb from '../shared/Breadcrumb';import TaskDetailCopyActions from './TaskDetailCopyActions';import TaskDetailHeaderActions from './TaskDetailHeaderActions';import TaskDetailSections from './TaskDetailSections';import TaskDetailSkeleton from './TaskDetailSkeleton';+import { useTaskFindBar } from './TaskFind';import TopicChatDrawer from './TopicChatDrawer';import { useActiveTaskDetail } from './useActiveTaskDetail';@@ -36,6 +42,8 @@ const TaskDetailPage = memo<TaskDetailPageProps>(({ taskId, showTaskAgentPanelTo]);const { isInitialLoading, isNotFound, error, onRetry } = useActiveTaskDetail(taskId);+ const { bar: findBar, openFind, rootRef: findRootRef } = useTaskFindBar();+ const findHotkey = useUserStore(settingsSelectors.getHotkeyById(HotkeyEnum.FindInTopic));// A transient fetch failure (network / 500) is not a 404 — keep the URL and// offer Reload instead of the terminal "task was deleted" dead-end below.@@ -89,6 +97,13 @@ const TaskDetailPage = memo<TaskDetailPageProps>(({ taskId, showTaskAgentPanelTo}right={<>+ <ActionIcon+ icon={SearchIcon}+ size={DESKTOP_HEADER_ICON_SMALL_SIZE}+ title={t('taskDetail.find.open')}+ tooltipProps={{ hotkey: findHotkey, placement: 'bottom' }}+ onClick={openFind}+ /><TaskDetailCopyActions />{showTaskAgentPanelToggle ? (<ToggleRightPanelButton@@ -106,13 +121,18 @@ const TaskDetailPage = memo<TaskDetailPageProps>(({ taskId, showTaskAgentPanelTo},}}/>- <Flexbox flex={1} style={{ minHeight: 0, overflowY: 'auto' }}>- {/* Detail is prose — instruction, deliverables, activity — so it keeps the- centered reading column rather than the list page's full-bleed rows,- whose value is the horizontal room for their metadata columns. */}- <WideScreenContainer>- {isInitialLoading ? <TaskDetailSkeleton chrome={'body'} /> : <TaskDetailSections />}- </WideScreenContainer>+ {/* The find bar floats over the detail rather than inside it, so its own+ re-renders never reach the scroll container's match observer. */}+ <Flexbox flex={1} style={{ minHeight: 0, position: 'relative' }}>+ {findBar}+ <Flexbox flex={1} ref={findRootRef} style={{ minHeight: 0, overflowY: 'auto' }}>+ {/* Detail is prose — instruction, deliverables, activity — so it keeps the+ centered reading column rather than the list page's full-bleed rows,+ whose value is the horizontal room for their metadata columns. */}+ <WideScreenContainer>+ {isInitialLoading ? <TaskDetailSkeleton chrome={'body'} /> : <TaskDetailSections />}+ </WideScreenContainer>+ </Flexbox></Flexbox>{/* The task page has nothing else to read beside a run, so it opens wide. */}<TopicChatDrawer defaultExpanded />diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskFind/TaskFindBar.tsx b/src/features/AgentTasks/AgentTaskDetail/TaskFind/TaskFindBar.tsxnew file mode 100644index 00000000000..8c3b29f32f3--- /dev/null+++ b/src/features/AgentTasks/AgentTaskDetail/TaskFind/TaskFindBar.tsx@@ -0,0 +1,137 @@+'use client';++import { ActionIcon, cssVar as lobeCssVar, Flexbox, Icon, Input } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import { ChevronDownIcon, ChevronUpIcon, SearchIcon, XIcon } from 'lucide-react';+import type { KeyboardEvent } from 'react';+import { memo, useEffect, useRef } from 'react';+import { useTranslation } from 'react-i18next';++import { resolveFindKey } from './findKeys';+import { TASK_FIND_HIGHLIGHT } from './useTaskFind';++// `::highlight()` is a document-level pseudo-element, so it cannot be a scoped+// rule. React hoists and dedupes this sheet by its `href`. It sets the text+// color with the fill so matches stay readable whatever color the text has.+const HIGHLIGHT_SHEET = `+::highlight(${TASK_FIND_HIGHLIGHT.all}) { background-color: ${lobeCssVar.colorWarningBgHover}; color: ${lobeCssVar.colorText}; }+::highlight(${TASK_FIND_HIGHLIGHT.active}) { background-color: ${lobeCssVar.colorWarningBorder}; color: ${lobeCssVar.colorText}; }+`;++const styles = stylex.create({+ bar: {+ backgroundColor: cssVar.colorBgElevated,+ borderColor: cssVar.colorBorderSecondary,+ borderRadius: cssVar.borderRadiusLG,+ borderStyle: 'solid',+ borderWidth: 1,+ boxShadow: cssVar.boxShadowSecondary,+ insetBlockStart: 8,+ insetInlineEnd: 16,+ padding: 6,+ position: 'absolute',+ width: 'min(360px, calc(100% - 32px))',+ zIndex: 10,+ },+ position: {+ color: cssVar.colorTextTertiary,+ fontSize: 12,+ fontVariantNumeric: 'tabular-nums',+ whiteSpace: 'nowrap',+ },+});++interface TaskFindBarProps {+ activeIndex: number;+ count: number;+ /** Bumped by every Mod+F / header click, so a repeat press re-selects the keyword. */+ focusRequest: number;+ onChange: (value: string) => void;+ onClose: () => void;+ onStep: (delta: 1 | -1) => void;+ /** The debounced keyword: the count only reads "no results" once it has settled. */+ settledKeyword: string;+ value: string;+}++const TaskFindBar = memo<TaskFindBarProps>(+ ({ activeIndex, count, focusRequest, onChange, onClose, onStep, settledKeyword, value }) => {+ const { t } = useTranslation('chat');+ const inputRef = useRef<HTMLInputElement>(null);++ useEffect(() => {+ const timer = setTimeout(() => {+ inputRef.current?.focus();+ inputRef.current?.select();+ });+ return () => clearTimeout(timer);+ }, [focusRequest]);++ const handleKeyDown = (event: KeyboardEvent<HTMLInputElement>) => {+ const action = resolveFindKey(event.key, event.shiftKey);+ if (!action) return;+ if (action === 'close') onClose();+ else onStep(action === 'next' ? 1 : -1);++ event.preventDefault();+ event.stopPropagation();+ };++ const showPosition = !!settledKeyword && settledKeyword === value.trim();++ return (+ <div {...stylex.props(styles.bar)} data-testid={'task-find-bar'} role={'search'}>+ <style href={'lobe-task-find-highlight'} precedence={'default'}>+ {HIGHLIGHT_SHEET}+ </style>+ <Input+ aria-label={t('taskDetail.find.placeholder')}+ placeholder={t('taskDetail.find.placeholder')}+ prefix={<Icon icon={SearchIcon} size={13} />}+ ref={inputRef}+ size={'small'}+ value={value}+ variant={'borderless'}+ suffix={+ <Flexbox horizontal align={'center'} gap={2}>+ {showPosition && (+ <span aria-live={'polite'} {...stylex.props(styles.position)}>+ {count > 0+ ? t('taskDetail.find.position', { current: activeIndex + 1, total: count })+ : t('taskDetail.find.empty')}+ </span>+ )}+ <ActionIcon+ disabled={count === 0}+ icon={ChevronUpIcon}+ size={'small'}+ title={t('taskDetail.find.prev')}+ onClick={() => onStep(-1)}+ />+ <ActionIcon+ disabled={count === 0}+ icon={ChevronDownIcon}+ size={'small'}+ title={t('taskDetail.find.next')}+ onClick={() => onStep(1)}+ />+ <ActionIcon+ icon={XIcon}+ size={'small'}+ title={t('taskDetail.find.close')}+ onClick={onClose}+ />+ </Flexbox>+ }+ onChange={(event) => onChange(event.target.value)}+ onKeyDown={handleKeyDown}+ />+ </div>+ );+ },+);++TaskFindBar.displayName = 'TaskFindBar';++export default TaskFindBar;diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskFind/findKeys.test.ts b/src/features/AgentTasks/AgentTaskDetail/TaskFind/findKeys.test.tsnew file mode 100644index 00000000000..792fda3f2f8--- /dev/null+++ b/src/features/AgentTasks/AgentTaskDetail/TaskFind/findKeys.test.ts@@ -0,0 +1,18 @@+import { describe, expect, it } from 'vitest';++import { resolveFindKey } from './findKeys';++describe('resolveFindKey', () => {+ it('steps with Enter, Shift+Enter and the arrows', () => {+ expect(resolveFindKey('Enter', false)).toBe('next');+ expect(resolveFindKey('Enter', true)).toBe('prev');+ expect(resolveFindKey('ArrowDown', false)).toBe('next');+ expect(resolveFindKey('ArrowUp', false)).toBe('prev');+ });++ it('closes with Escape and leaves typing alone', () => {+ expect(resolveFindKey('Escape', false)).toBe('close');+ expect(resolveFindKey('a', false)).toBeUndefined();+ expect(resolveFindKey('Backspace', true)).toBeUndefined();+ });+});diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskFind/findKeys.ts b/src/features/AgentTasks/AgentTaskDetail/TaskFind/findKeys.tsnew file mode 100644index 00000000000..e38155e21a4--- /dev/null+++ b/src/features/AgentTasks/AgentTaskDetail/TaskFind/findKeys.ts@@ -0,0 +1,10 @@+export type FindKeyAction = 'close' | 'next' | 'prev';++/** What a key pressed in the find input does — the browser find-bar conventions. */+export const resolveFindKey = (key: string, shiftKey: boolean): FindKeyAction | undefined => {+ if (key === 'Enter') return shiftKey ? 'prev' : 'next';+ if (key === 'ArrowDown') return 'next';+ if (key === 'ArrowUp') return 'prev';+ if (key === 'Escape') return 'close';+ return undefined;+};diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskFind/index.tsx b/src/features/AgentTasks/AgentTaskDetail/TaskFind/index.tsxnew file mode 100644index 00000000000..864c4955378--- /dev/null+++ b/src/features/AgentTasks/AgentTaskDetail/TaskFind/index.tsx@@ -0,0 +1,58 @@+'use client';++import { HotkeyEnum, HotkeyScopeEnum } from '@lobechat/const/hotkeys';+import { useDebounce } from 'ahooks';+import { useCallback, useState } from 'react';++import { useHotkeyById } from '@/hooks/useHotkeys/useHotkeyById';++import TaskFindBar from './TaskFindBar';+import { useTaskFind } from './useTaskFind';++// Matching walks the rendered DOM, no request involved: a short debounce only+// keeps every keystroke of a long word from repainting the page.+const FIND_DEBOUNCE_MS = 120;++/**+ * Find in the task detail. Mod+F reuses the "find" binding the conversation+ * already owns (one key, one meaning: find in what is open), so a rebind in+ * settings moves both, and the two never show up as conflicting shortcuts.+ */+export const useTaskFindBar = () => {+ // A callback ref into state: the scroll container remounts when Retry+ // replaces the error view, and the search must follow the new element.+ const [root, setRoot] = useState<HTMLElement | null>(null);+ const [open, setOpen] = useState(false);+ const [value, setValue] = useState('');+ const [focusRequest, setFocusRequest] = useState(0);+ const keyword = useDebounce(value, { wait: FIND_DEBOUNCE_MS }).trim();+ const { activeIndex, count, step } = useTaskFind({ enabled: open, keyword, root });++ const openFind = useCallback(() => {+ setOpen(true);+ setFocusRequest((nonce) => nonce + 1);+ }, []);+ // Like a browser's find bar, closing keeps the keyword for the next Mod+F.+ const closeFind = useCallback(() => setOpen(false), []);++ useHotkeyById(HotkeyEnum.FindInTopic, openFind, {+ enableOnContentEditable: true,+ enabled: true,+ scopes: [HotkeyScopeEnum.Global],+ });++ const bar = open ? (+ <TaskFindBar+ activeIndex={activeIndex}+ count={count}+ focusRequest={focusRequest}+ settledKeyword={keyword}+ value={value}+ onChange={setValue}+ onClose={closeFind}+ onStep={step}+ />+ ) : null;++ return { bar, openFind, rootRef: setRoot };+};diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskFind/useTaskFind.test.ts b/src/features/AgentTasks/AgentTaskDetail/TaskFind/useTaskFind.test.tsnew file mode 100644index 00000000000..02483dba930--- /dev/null+++ b/src/features/AgentTasks/AgentTaskDetail/TaskFind/useTaskFind.test.ts@@ -0,0 +1,102 @@+/**+ * @vitest-environment happy-dom+ */+import { act, renderHook, waitFor } from '@testing-library/react';+import { afterEach, describe, expect, it } from 'vitest';++import { useTaskFind } from './useTaskFind';++const mount = (html: string) => {+ const root = document.createElement('div');+ root.innerHTML = html;+ document.body.append(root);+ return root;+};++afterEach(() => {+ document.body.innerHTML = '';+});++describe('useTaskFind', () => {+ it('counts matches in the instruction editor and the rest of the detail', () => {+ const root = mount(+ '<div contenteditable="true"><p>Fix the drive menu</p></div><p>drive acceptance</p><textarea>drive</textarea>',+ );++ const { result } = renderHook(() => useTaskFind({ enabled: true, keyword: 'Drive', root }));++ expect(result.current.count).toBe(2);+ expect(result.current.activeIndex).toBe(0);+ });++ it('steps through matches and wraps around in both directions', () => {+ const root = mount('<p>a x b x c x</p>');+ const { result } = renderHook(() => useTaskFind({ enabled: true, keyword: 'x', root }));++ act(() => result.current.step(1));+ act(() => result.current.step(1));+ expect(result.current.activeIndex).toBe(2);+ act(() => result.current.step(1));+ expect(result.current.activeIndex).toBe(0);+ act(() => result.current.step(-1));+ expect(result.current.activeIndex).toBe(2);+ });++ it('finds nothing while closed or with a blank keyword', () => {+ const root = mount('<p>drive</p>');++ const closed = renderHook(() => useTaskFind({ enabled: false, keyword: 'drive', root }));+ const blank = renderHook(() => useTaskFind({ enabled: true, keyword: ' ', root }));++ expect(closed.result.current.count).toBe(0);+ expect(blank.result.current.count).toBe(0);+ });++ it('recounts when the detail re-renders and keeps the position in range', async () => {+ const root = mount('<p id="a">drive drive</p><p id="b">drive</p>');+ const { result } = renderHook(() => useTaskFind({ enabled: true, keyword: 'drive', root }));++ act(() => result.current.step(-1));+ expect(result.current.activeIndex).toBe(2);++ act(() => {+ root.querySelector('#b')!.remove();+ });++ await waitFor(() => expect(result.current.count).toBe(2));+ expect(result.current.activeIndex).toBe(1);+ });++ it('restarts at the first match when the keyword changes', () => {+ const root = mount('<p>drive menu drive menu</p>');+ const { rerender, result } = renderHook(+ ({ keyword }) => useTaskFind({ enabled: true, keyword, root }),+ { initialProps: { keyword: 'drive' } },+ );++ act(() => result.current.step(1));+ expect(result.current.activeIndex).toBe(1);++ rerender({ keyword: 'menu' });+ expect(result.current.activeIndex).toBe(0);+ expect(result.current.count).toBe(2);+ });++ it('follows a remounted container instead of the one it replaced', () => {+ const first = mount('<p>drive</p>');+ const { rerender, result } = renderHook(+ ({ root }) => useTaskFind({ enabled: true, keyword: 'drive', root }),+ { initialProps: { root: first as HTMLElement | null } },+ );+ expect(result.current.count).toBe(1);++ // Retry after a failed load: the error view unmounts the old container…+ first.remove();+ rerender({ root: null });+ expect(result.current.count).toBe(0);++ // …and a fresh one mounts with the loaded task.+ rerender({ root: mount('<p>drive here, drive there</p>') });+ expect(result.current.count).toBe(2);+ });+});diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskFind/useTaskFind.ts b/src/features/AgentTasks/AgentTaskDetail/TaskFind/useTaskFind.tsnew file mode 100644index 00000000000..1fe287e8d34--- /dev/null+++ b/src/features/AgentTasks/AgentTaskDetail/TaskFind/useTaskFind.ts@@ -0,0 +1,115 @@+import { useCallback, useEffect, useRef, useState } from 'react';++import {+ clearHighlights,+ findKeywordRanges,+ requestReveal,+ scrollRangeIntoView,+ setHighlightRanges,+} from '@/utils/findInDom';++export const TASK_FIND_HIGHLIGHT = {+ active: 'lobe-task-find-active',+ all: 'lobe-task-find',+} as const;++interface UseTaskFindOptions {+ /** The find bar is open; closing it clears every highlight. */+ enabled: boolean;+ keyword: string;+ /**+ * The detail's scroll container: the text searched, and what scrolls to a+ * match. An element, not a ref, so a remount (Retry after a failed load+ * swaps the error view back for a new container) restarts the search there.+ */+ root: HTMLElement | null;+}++/**+ * Find-in-page over the rendered task detail — title aside (a textarea has no+ * text nodes to range over), that is the instruction editor, acceptance,+ * subtasks, deliverables and the activity feed. Matches repaint as the page+ * re-renders (autosave, streaming activity, lazy sections), keeping the user's+ * position when the match under it still exists.+ */+export const useTaskFind = ({ enabled, keyword, root }: UseTaskFindOptions) => {+ const [count, setCount] = useState(0);+ const [activeIndex, setActiveIndex] = useState(0);+ const rangesRef = useRef<Range[]>([]);+ // Steps and repaints read the position synchronously, ahead of the re-render.+ const activeIndexRef = useRef(0);++ const paintActive = useCallback(+ (index: number, scroll: boolean) => {+ const range = rangesRef.current[index];+ setHighlightRanges(TASK_FIND_HIGHLIGHT.active, range ? [range] : [], 2);+ if (!scroll || !range || !root) return;+ // A match inside a clamped "show more" preview opens it first; scroll+ // once the expanded layout has been committed and laid out.+ requestReveal(range);+ requestAnimationFrame(() =>+ requestAnimationFrame(() => {+ if (range.startContainer.isConnected) scrollRangeIntoView(range, root);+ }),+ );+ },+ [root],+ );++ useEffect(() => {+ const needle = keyword.trim();+ if (!enabled || !needle || !root) {+ rangesRef.current = [];+ setCount(0);+ setActiveIndex(0);+ return;+ }++ let frame: number | undefined;+ const collect = () => findKeywordRanges(root, needle, { includeEditable: true });++ // A new keyword starts at its first match and brings it into view.+ rangesRef.current = collect();+ setHighlightRanges(TASK_FIND_HIGHLIGHT.all, rangesRef.current, 1);+ setCount(rangesRef.current.length);+ activeIndexRef.current = 0;+ setActiveIndex(0);+ paintActive(0, true);++ // Later repaints follow the DOM but never scroll: the user may be reading.+ const repaint = () => {+ frame = undefined;+ rangesRef.current = collect();+ const next = Math.min(activeIndexRef.current, Math.max(rangesRef.current.length - 1, 0));+ setHighlightRanges(TASK_FIND_HIGHLIGHT.all, rangesRef.current, 1);+ setCount(rangesRef.current.length);+ activeIndexRef.current = next;+ setActiveIndex(next);+ paintActive(next, false);+ };+ const observer = new MutationObserver(() => {+ frame ??= requestAnimationFrame(repaint);+ });+ observer.observe(root, { characterData: true, childList: true, subtree: true });++ return () => {+ observer.disconnect();+ if (frame !== undefined) cancelAnimationFrame(frame);+ clearHighlights(Object.values(TASK_FIND_HIGHLIGHT));+ };+ }, [enabled, keyword, paintActive, root]);++ const step = useCallback(+ (delta: 1 | -1) => {+ const total = rangesRef.current.length;+ if (total === 0) return;+ const next = (activeIndexRef.current + delta + total) % total;+ activeIndexRef.current = next;+ setActiveIndex(next);+ paintActive(next, true);+ },+ [paintActive],+ );++ return { activeIndex, count, step };+};diff --git a/src/features/Conversation/WorkingSidebar/Search/conversationHighlights.ts b/src/features/Conversation/WorkingSidebar/Search/conversationHighlights.tsindex b03c35a1c56..6329fdc9a53 100644--- a/src/features/Conversation/WorkingSidebar/Search/conversationHighlights.ts+++ b/src/features/Conversation/WorkingSidebar/Search/conversationHighlights.ts@@ -4,67 +4,21 @@* streams, so wrapping matches in mark nodes would mean owning that DOM. A* highlight range owns no DOM and is simply rebuilt from the rendered rows.*/+import { clearHighlights, setHighlightRanges, supportsHighlightApi } from '@/utils/findInDom';++export { findKeywordRanges, supportsHighlightApi } from '@/utils/findInDom';+export const TOPIC_SEARCH_HIGHLIGHT = {active: 'lobe-topic-search-active',all: 'lobe-topic-search',} as const;-const SKIPPED_TAGS = new Set(['INPUT', 'NOSCRIPT', 'SCRIPT', 'STYLE', 'TEXTAREA']);--export const supportsHighlightApi = () =>- typeof CSS !== 'undefined' && 'highlights' in CSS && typeof Highlight !== 'undefined';--/** Ranges of every case-insensitive `keyword` occurrence in the text under `root`. */-export const findKeywordRanges = (root: Node, keyword: string): Range[] => {- const needle = keyword.trim().toLowerCase();- const document = root.ownerDocument;- if (!needle || !document) return [];-- const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, {- acceptNode: (node) => {- const parent = node.parentElement;- return !parent || SKIPPED_TAGS.has(parent.tagName) || parent.isContentEditable- ? NodeFilter.FILTER_REJECT- : NodeFilter.FILTER_ACCEPT;- },- });-- const ranges: Range[] = [];- for (let node = walker.nextNode(); node; node = walker.nextNode()) {- const value = node.nodeValue ?? '';- const text = value.toLowerCase();- // A case fold that changes the length would shift every offset below.- if (text.length !== value.length) continue;-- for (let index = text.indexOf(needle); index !== -1;) {- const range = document.createRange();- range.setStart(node, index);- range.setEnd(node, index + needle.length);- ranges.push(range);- index = text.indexOf(needle, index + needle.length);- }- }-- return ranges;-};--const setRegistry = (name: string, ranges: Range[], priority: number) => {- if (ranges.length === 0) {- CSS.highlights.delete(name);- return;- }- const highlight = new Highlight(...ranges);- highlight.priority = priority;- CSS.highlights.set(name, highlight);-};-export const paintTopicSearchHighlights = (all: Range[], active: Range[]) => {if (!supportsHighlightApi()) return;- setRegistry(TOPIC_SEARCH_HIGHLIGHT.all, all, 1);- setRegistry(TOPIC_SEARCH_HIGHLIGHT.active, active, 2);+ setHighlightRanges(TOPIC_SEARCH_HIGHLIGHT.all, all, 1);+ setHighlightRanges(TOPIC_SEARCH_HIGHLIGHT.active, active, 2);};export const clearTopicSearchHighlights = () => {- if (!supportsHighlightApi()) return;- for (const name of Object.values(TOPIC_SEARCH_HIGHLIGHT)) CSS.highlights.delete(name);+ clearHighlights(Object.values(TOPIC_SEARCH_HIGHLIGHT));};diff --git a/src/features/Conversation/WorkingSidebar/Search/highlightSegments.test.ts b/src/features/Conversation/WorkingSidebar/Search/highlightSegments.test.tsindex 0230d959eb8..f8f15104867 100644--- a/src/features/Conversation/WorkingSidebar/Search/highlightSegments.test.ts+++ b/src/features/Conversation/WorkingSidebar/Search/highlightSegments.test.ts@@ -15,4 +15,11 @@ describe('splitHighlightSegments', () => {expect(splitHighlightSegments('hello', ' ')).toEqual([{ match: false, text: 'hello' }]);expect(splitHighlightSegments('hello', 'bye')).toEqual([{ match: false, text: 'hello' }]);});++ it('still highlights a snippet whose lower-casing changes length', () => {+ expect(splitHighlightSegments('İstanbul deployment', 'Deployment')).toEqual([+ { match: false, text: 'İstanbul ' },+ { match: true, text: 'deployment' },+ ]);+ });});diff --git a/src/features/Conversation/WorkingSidebar/Search/highlightSegments.ts b/src/features/Conversation/WorkingSidebar/Search/highlightSegments.tsindex f4220f8afb9..cfe9260497d 100644--- a/src/features/Conversation/WorkingSidebar/Search/highlightSegments.ts+++ b/src/features/Conversation/WorkingSidebar/Search/highlightSegments.ts@@ -1,3 +1,5 @@+import { findFoldedMatches } from '@/utils/findInDom';+export interface HighlightSegment {match: boolean;text: string;@@ -5,18 +7,15 @@ export interface HighlightSegment {/** Splits `text` into plain and matching runs of a case-insensitive `keyword`. */export const splitHighlightSegments = (text: string, keyword: string): HighlightSegment[] => {- const needle = keyword.trim().toLowerCase();- const haystack = text.toLowerCase();- // A case fold that changes the length would shift every offset below.- if (!needle || haystack.length !== text.length) return [{ match: false, text }];+ const matches = findFoldedMatches(text, keyword.trim().toLowerCase());+ if (matches.length === 0) return [{ match: false, text }];const segments: HighlightSegment[] = [];let cursor = 0;- for (let index = haystack.indexOf(needle); index !== -1;) {- if (index > cursor) segments.push({ match: false, text: text.slice(cursor, index) });- segments.push({ match: true, text: text.slice(index, index + needle.length) });- cursor = index + needle.length;- index = haystack.indexOf(needle, cursor);+ for (const [start, end] of matches) {+ if (start > cursor) segments.push({ match: false, text: text.slice(cursor, start) });+ segments.push({ match: true, text: text.slice(start, end) });+ cursor = end;}if (cursor < text.length) segments.push({ match: false, text: text.slice(cursor) });diff --git a/src/utils/findInDom.test.ts b/src/utils/findInDom.test.tsnew file mode 100644index 00000000000..01fe45443c8--- /dev/null+++ b/src/utils/findInDom.test.ts@@ -0,0 +1,110 @@+import { describe, expect, it, vi } from 'vitest';++import {+ findFoldedMatches,+ findKeywordRanges,+ requestReveal,+ REVEAL_IN_PAGE_EVENT,+ scrollRangeIntoView,+} from './findInDom';++const render = (html: string) => {+ const root = document.createElement('div');+ root.innerHTML = html;+ document.body.append(root);+ return root;+};++describe('findKeywordRanges', () => {+ it('skips editable text unless asked to include it', () => {+ const root = render(+ '<textarea>deploy</textarea><div contenteditable="true"><p>Deploy here</p></div><span>deploy</span>',+ );++ expect(findKeywordRanges(root, 'deploy')).toHaveLength(1);+ expect(+ findKeywordRanges(root, 'deploy', { includeEditable: true }).map((range) => range.toString()),+ ).toEqual(['Deploy', 'deploy']);+ });++ it('keeps form fields out even when editable text is included', () => {+ const root = render('<input value="deploy" /><textarea>deploy</textarea>');++ expect(findKeywordRanges(root, 'deploy', { includeEditable: true })).toEqual([]);+ });++ it('matches CJK text and repeated occurrences in one node', () => {+ const root = render('<p>资源库 Drive 页的资源库</p>');++ expect(findKeywordRanges(root, '资源库')).toHaveLength(2);+ });+});++describe('scrollRangeIntoView', () => {+ const box = (top: number, height: number) =>+ ({ bottom: top + height, height, top, width: 100 }) as DOMRect;++ const setup = (rangeTop: number) => {+ const container = document.createElement('div');+ Object.defineProperty(container, 'scrollTop', { value: 200, writable: true });+ container.getBoundingClientRect = () => box(0, 600);+ container.scrollTo = vi.fn() as typeof container.scrollTo;+ const range = { getBoundingClientRect: () => box(rangeTop, 20) } as unknown as Range;+ return { container, range };+ };++ it('leaves a match that is already well on screen alone', () => {+ const { container, range } = setup(300);+ scrollRangeIntoView(range, container);+ expect(container.scrollTo).not.toHaveBeenCalled();+ });++ it('centers a match below the fold', () => {+ const { container, range } = setup(1000);+ scrollRangeIntoView(range, container);+ // 200 + 1000 - 0 - 300 + 10+ expect(container.scrollTo).toHaveBeenCalledWith({ behavior: 'smooth', top: 910 });+ });+});++describe('requestReveal', () => {+ it('bubbles the match box up to whatever clamps it', () => {+ const root = render('<div class="clamp"><p>deploy</p></div>');+ const listener = vi.fn();+ root.querySelector('.clamp')!.addEventListener(REVEAL_IN_PAGE_EVENT, listener);+ const [range] = findKeywordRanges(root, 'deploy');+ range.getBoundingClientRect = () => ({ bottom: 420, top: 400 }) as DOMRect;++ requestReveal(range);++ expect(listener).toHaveBeenCalledTimes(1);+ expect(listener.mock.calls[0][0].detail).toEqual({ bottom: 420, top: 400 });+ });+});++describe('findFoldedMatches', () => {+ it('keeps matching a node whose lower-casing changes length', () => {+ // `İ`.toLowerCase() is two code units, which used to drop the whole node.+ const text = 'İstanbul deployment failed';+ const [[start, end]] = findFoldedMatches(text, 'deployment');++ expect(text.slice(start, end)).toBe('deployment');+ });++ it('maps a match on the expanded character back to original offsets', () => {+ const text = 'Gİt İstanbul';+ expect(findFoldedMatches(text, 'i̇stanbul').map(([s, e]) => text.slice(s, e))).toEqual([+ 'İstanbul',+ ]);+ });++ it('drops a match that would split one folded character', () => {+ // 'i' alone is only half of the folded `İ` (i + combining dot).+ expect(findFoldedMatches('İ', 'i')).toEqual([]);+ });++ it('matches astral characters by code point', () => {+ const text = 'ship 🚀 now 🚀';+ expect(findFoldedMatches(text, '🚀')).toHaveLength(2);+ });+});diff --git a/src/utils/findInDom.ts b/src/utils/findInDom.tsnew file mode 100644index 00000000000..3a1a849efaf--- /dev/null+++ b/src/utils/findInDom.ts@@ -0,0 +1,151 @@+/**+ * Literal find over rendered text, painted through the CSS Custom Highlight+ * API: a highlight range owns no DOM, so it survives views that re-render+ * underneath it (virtualized lists, streaming rows, rich-text editors) and is+ * simply rebuilt from what is on screen.+ */++/**+ * Asks whatever clamps a range (a "show more" preview) to open up when the+ * range is cut off. Dispatched by find when it lands on a match; a clamp+ * listens on its own root, so hosts need no wiring. `detail` is the range's+ * on-screen box, so the clamp can tell a clipped match from a visible one.+ */+export const REVEAL_IN_PAGE_EVENT = 'lobe:reveal-in-page';++export type RevealInPageEvent = CustomEvent<{ bottom: number; top: number }>;++export const requestReveal = (range: Range) => {+ const element = range.startContainer.parentElement;+ if (!element || typeof range.getBoundingClientRect !== 'function') return;+ const { bottom, top } = range.getBoundingClientRect();+ element.dispatchEvent(+ new CustomEvent(REVEAL_IN_PAGE_EVENT, { bubbles: true, detail: { bottom, top } }),+ );+};++/**+ * `[start, end)` offsets in `text` of every case-insensitive occurrence of an+ * already lower-cased `needle`. Lower-casing can change a character's length+ * (`İ` becomes two code units), so matching runs on the folded text and maps+ * each hit back to original offsets. A hit that starts or ends inside one+ * folded character is dropped; the rest of the text still matches.+ */+export const findFoldedMatches = (text: string, needle: string): [number, number][] => {+ if (!needle) return [];++ let folded = '';+ // For each folded code unit: the original offset of the character it came+ // from, and of the character after it.+ const starts: number[] = [];+ const ends: number[] = [];+ for (let index = 0; index < text.length;) {+ const char = String.fromCodePoint(text.codePointAt(index)!);+ const lower = char.toLowerCase();+ for (let unit = 0; unit < lower.length; unit++) {+ starts.push(index);+ ends.push(index + char.length);+ }+ folded += lower;+ index += char.length;+ }++ const matches: [number, number][] = [];+ for (let index = folded.indexOf(needle); index !== -1;) {+ const last = index + needle.length - 1;+ const startsOnBoundary = index === 0 || starts[index - 1] !== starts[index];+ const endsOnBoundary = last === folded.length - 1 || starts[last + 1] !== starts[last];+ if (startsOnBoundary && endsOnBoundary) {+ matches.push([starts[index], ends[last]]);+ index = folded.indexOf(needle, index + needle.length);+ } else {+ index = folded.indexOf(needle, index + 1);+ }+ }+ return matches;+};++const SKIPPED_TAGS = new Set(['INPUT', 'NOSCRIPT', 'SCRIPT', 'STYLE', 'TEXTAREA']);++export const supportsHighlightApi = () =>+ typeof CSS !== 'undefined' && 'highlights' in CSS && typeof Highlight !== 'undefined';++export interface FindKeywordRangesOptions {+ /**+ * Also match text inside `contenteditable` regions. Off by default: a chat+ * composer is not content. Pages whose content *is* an editor (a task's+ * instruction) turn it on.+ */+ includeEditable?: boolean;+}++/** Ranges of every case-insensitive `keyword` occurrence in the text under `root`. */+export const findKeywordRanges = (+ root: Node,+ keyword: string,+ { includeEditable = false }: FindKeywordRangesOptions = {},+): Range[] => {+ const needle = keyword.trim().toLowerCase();+ const document = root.ownerDocument;+ if (!needle || !document) return [];++ const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, {+ acceptNode: (node) => {+ const parent = node.parentElement;+ if (!parent || SKIPPED_TAGS.has(parent.tagName)) return NodeFilter.FILTER_REJECT;+ if (!includeEditable && parent.isContentEditable) return NodeFilter.FILTER_REJECT;+ return NodeFilter.FILTER_ACCEPT;+ },+ });++ const ranges: Range[] = [];+ for (let node = walker.nextNode(); node; node = walker.nextNode()) {+ for (const [start, end] of findFoldedMatches(node.nodeValue ?? '', needle)) {+ const range = document.createRange();+ range.setStart(node, start);+ range.setEnd(node, end);+ ranges.push(range);+ }+ }++ return ranges;+};++/** Registers `ranges` under `name`, or drops the registry entry when there are none. */+export const setHighlightRanges = (name: string, ranges: Range[], priority: number) => {+ if (!supportsHighlightApi()) return;+ if (ranges.length === 0) {+ CSS.highlights.delete(name);+ return;+ }+ const highlight = new Highlight(...ranges);+ highlight.priority = priority;+ CSS.highlights.set(name, highlight);+};++export const clearHighlights = (names: string[]) => {+ if (!supportsHighlightApi()) return;+ for (const name of names) CSS.highlights.delete(name);+};++const SCROLL_MARGIN = 64;++/**+ * Centers `range` in `container` unless it is already comfortably on screen.+ * Text ranges have no `scrollIntoView`, and scrolling the range's parent+ * element would jump a whole long paragraph to the top instead of the match.+ */+export const scrollRangeIntoView = (range: Range, container: HTMLElement) => {+ // jsdom ranges have no layout.+ if (typeof range.getBoundingClientRect !== 'function') return;+ const rect = range.getBoundingClientRect();+ const box = container.getBoundingClientRect();+ if (rect.height === 0 && rect.width === 0) return;++ if (rect.top >= box.top + SCROLL_MARGIN && rect.bottom <= box.bottom - SCROLL_MARGIN) return;++ container.scrollTo({+ behavior: 'smooth',+ top: container.scrollTop + rect.top - box.top - box.height / 2 + rect.height / 2,+ });+};