🤯 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: devtools gallery rebuild, Review polish, queue-tray images (#14423)
Arvin Xu78b3dbed03bd
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex e9c10218d00..60a50d7a45b 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -835,13 +835,23 @@"workingPanel.resources.viewMode.list": "List view","workingPanel.resources.viewMode.tree": "Tree view","workingPanel.review.binary": "Binary file — diff not shown",+ "workingPanel.review.collapseAll": "Collapse all",+ "workingPanel.review.copied": "Path copied",+ "workingPanel.review.copyPath": "Copy file path","workingPanel.review.empty": "No working tree changes","workingPanel.review.error": "Couldn't load this file's diff",+ "workingPanel.review.expandAll": "Expand all",+ "workingPanel.review.more": "More options",+ "workingPanel.review.refresh": "Refresh",+ "workingPanel.review.textDiff.disable": "Disable inline text diff",+ "workingPanel.review.textDiff.enable": "Enable inline text diff","workingPanel.review.title": "Review","workingPanel.review.tooLarge": "File is too large to diff inline","workingPanel.review.unstaged": "Unstaged","workingPanel.review.viewMode.split": "Switch to split view","workingPanel.review.viewMode.unified": "Switch to unified view",+ "workingPanel.review.wordWrap.disable": "Disable word wrap",+ "workingPanel.review.wordWrap.enable": "Enable word wrap","workingPanel.space": "Space","workingPanel.title": "Working Panel","you": "You",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex 0440410020b..9c80067fd6c 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -840,13 +840,23 @@"workingPanel.resources.viewMode.list": "列表视图","workingPanel.resources.viewMode.tree": "树状视图","workingPanel.review.binary": "二进制文件,无法展示 diff",+ "workingPanel.review.collapseAll": "全部折叠",+ "workingPanel.review.copied": "路径已复制",+ "workingPanel.review.copyPath": "复制文件路径","workingPanel.review.empty": "工作区没有未提交的变更","workingPanel.review.error": "无法加载该文件的 diff",+ "workingPanel.review.expandAll": "全部展开",+ "workingPanel.review.more": "更多选项",+ "workingPanel.review.refresh": "同步",+ "workingPanel.review.textDiff.disable": "关闭文字差异",+ "workingPanel.review.textDiff.enable": "启用文字差异","workingPanel.review.title": "审查","workingPanel.review.tooLarge": "文件过大,未在面板内展示 diff","workingPanel.review.unstaged": "未暂存","workingPanel.review.viewMode.split": "切换到双栏对比","workingPanel.review.viewMode.unified": "切换到合并视图",+ "workingPanel.review.wordWrap.disable": "关闭自动换行",+ "workingPanel.review.wordWrap.enable": "启用自动换行","workingPanel.space": "空间","workingPanel.title": "工作面板","you": "你",diff --git a/packages/builtin-tool-claude-code/src/client/Streaming/Agent/index.tsx b/packages/builtin-tool-claude-code/src/client/Streaming/Agent/index.tsxindex 4ee60756591..cbe2da9f6c1 100644--- a/packages/builtin-tool-claude-code/src/client/Streaming/Agent/index.tsx+++ b/packages/builtin-tool-claude-code/src/client/Streaming/Agent/index.tsx@@ -98,9 +98,7 @@ const AgentStreaming = memo<BuiltinStreamingProps<AgentArgs>>(({ args, toolCallI)}</Flexbox><Flexbox className={styles.promptBox}>- <Markdown style={{ maxHeight: 240, overflow: 'auto' }} variant={'chat'}>- {prompt}- </Markdown>+ <Markdown variant={'chat'}>{prompt}</Markdown></Flexbox></Flexbox>)}diff --git a/src/features/ChatInput/RuntimeConfig/GitStatus.tsx b/src/features/ChatInput/RuntimeConfig/GitStatus.tsxindex 2f409ec2858..dbd67306ddb 100644--- a/src/features/ChatInput/RuntimeConfig/GitStatus.tsx+++ b/src/features/ChatInput/RuntimeConfig/GitStatus.tsx@@ -1,4 +1,4 @@-import { Icon, Popover, Tooltip } from '@lobehub/ui';+import { Icon, Tooltip } from '@lobehub/ui';import { createStaticStyles, cssVar } from 'antd-style';import { ArrowDownIcon, ArrowUpIcon, GitBranchIcon, GitPullRequest } from 'lucide-react';import { memo, useCallback, useState } from 'react';@@ -8,12 +8,12 @@ import { message } from '@/components/AntdStaticMethods';import RingLoadingIcon from '@/components/RingLoading';import { electronGitService } from '@/services/electron/git';import { electronSystemService } from '@/services/electron/system';+import { useGlobalStore } from '@/store/global';import BranchSwitcher from './BranchSwitcher';import { useGitAheadBehind } from './useGitAheadBehind';import { useGitInfo } from './useGitInfo';import { useWorkingTreeStatus } from './useWorkingTreeStatus';-import WorkingTreeFilesContent from './WorkingTreeFilesContent';const styles = createStaticStyles(({ css }) => {return {@@ -145,9 +145,10 @@ const GitStatus = memo<GitStatusProps>(({ path, isGithub }) => {const { data: workingStatus, mutate: mutateWorkingStatus } = useWorkingTreeStatus(path);const { data: aheadBehind, mutate: mutateAheadBehind } = useGitAheadBehind(path);const [switcherOpen, setSwitcherOpen] = useState(false);- const [filesOpen, setFilesOpen] = useState(false);const [pulling, setPulling] = useState(false);const [pushing, setPushing] = useState(false);+ const toggleRightPanel = useGlobalStore((s) => s.toggleRightPanel);+ const setWorkingSidebarTab = useGlobalStore((s) => s.setWorkingSidebarTab);const handleOpenPr = useCallback(() => {if (data?.pullRequest?.url) {@@ -155,6 +156,11 @@ const GitStatus = memo<GitStatusProps>(({ path, isGithub }) => {}}, [data?.pullRequest?.url]);+ const handleOpenReview = useCallback(() => {+ setWorkingSidebarTab('review');+ toggleRightPanel(true);+ }, [setWorkingSidebarTab, toggleRightPanel]);+const refreshAfterSync = useCallback(async () => {await Promise.all([mutate(), mutateWorkingStatus(), mutateAheadBehind()]);}, [mutate, mutateWorkingStatus, mutateAheadBehind]);@@ -316,7 +322,7 @@ const GitStatus = memo<GitStatusProps>(({ path, isGithub }) => {const diffNode = (() => {if (!hasChanges || !workingStatus) return null;const diffButton = (- <div className={styles.trigger} role="button">+ <div className={styles.trigger} role="button" onClick={handleOpenReview}><span className={styles.diffStat}>{workingStatus.added > 0 && (<span className={styles.diffStatAdded}>+{workingStatus.added}</span>@@ -330,21 +336,7 @@ const GitStatus = memo<GitStatusProps>(({ path, isGithub }) => {</span></div>);- return (- <Popover- arrow={false}- content={<WorkingTreeFilesContent enabled={filesOpen} path={path} />}- open={filesOpen}- placement="bottomLeft"- styles={{ content: { padding: 0 } }}- trigger="click"- onOpenChange={setFilesOpen}- >- <div>- {filesOpen ? diffButton : <Tooltip title={diffStatTooltip}>{diffButton}</Tooltip>}- </div>- </Popover>- );+ return <Tooltip title={diffStatTooltip}>{diffButton}</Tooltip>;})();return (diff --git a/src/features/ChatInput/RuntimeConfig/WorkingTreeFilesContent.tsx b/src/features/ChatInput/RuntimeConfig/WorkingTreeFilesContent.tsxdeleted file mode 100644index f53a0fc65a0..00000000000--- a/src/features/ChatInput/RuntimeConfig/WorkingTreeFilesContent.tsx+++ /dev/null@@ -1,151 +0,0 @@-import { createStaticStyles, cssVar } from 'antd-style';-import { memo, useMemo } from 'react';-import { useTranslation } from 'react-i18next';--import { useWorkingTreeFiles } from './useWorkingTreeFiles';--const styles = createStaticStyles(({ css }) => ({- container: css`- overflow-y: auto;-- width: 320px;- max-height: 360px;- padding: 4px;-- font-size: 12px;- `,- empty: css`- padding-block: 16px;- color: ${cssVar.colorTextTertiary};- text-align: center;- `,- path: css`- overflow: hidden;- flex: 1;-- color: ${cssVar.colorText};- text-overflow: ellipsis;- white-space: nowrap;- `,- row: css`- display: flex;- gap: 12px;- align-items: center;-- padding-block: 6px;- padding-inline: 12px;- border-radius: 4px;-- line-height: 1.4;-- &:hover {- background: ${cssVar.colorFillTertiary};- }- `,- sectionHeader: css`- padding-block: 6px 4px;- padding-inline: 12px;-- font-size: 11px;- font-weight: 500;- color: ${cssVar.colorTextTertiary};- text-transform: uppercase;- `,- statusAdded: css`- flex: none;- width: 10px;- color: ${cssVar.colorSuccess};- text-align: center;- `,- statusDeleted: css`- flex: none;- width: 10px;- color: ${cssVar.colorError};- text-align: center;- `,- statusModified: css`- flex: none;- width: 10px;- color: ${cssVar.colorWarning};- text-align: center;- `,-}));--interface WorkingTreeFilesContentProps {- enabled: boolean;- path: string;-}--const WorkingTreeFilesContent = memo<WorkingTreeFilesContentProps>(({ path, enabled }) => {- const { t } = useTranslation('plugin');- const { data, isLoading } = useWorkingTreeFiles(path, enabled);-- const sections = useMemo(- () => [- {- items: data?.added ?? [],- key: 'added' as const,- label: t('localSystem.workingDirectory.filesAdded'),- sign: '+',- statusClass: styles.statusAdded,- },- {- items: data?.modified ?? [],- key: 'modified' as const,- label: t('localSystem.workingDirectory.filesModified'),- sign: '±',- statusClass: styles.statusModified,- },- {- items: data?.deleted ?? [],- key: 'deleted' as const,- label: t('localSystem.workingDirectory.filesDeleted'),- sign: '−',- statusClass: styles.statusDeleted,- },- ],- [data, t],- );-- const hasAny = sections.some((s) => s.items.length > 0);-- if (!data && isLoading) {- return (- <div className={styles.container}>- <div className={styles.empty}>{t('localSystem.workingDirectory.filesLoading')}</div>- </div>- );- }-- if (!hasAny) {- return (- <div className={styles.container}>- <div className={styles.empty}>{t('localSystem.workingDirectory.filesEmpty')}</div>- </div>- );- }-- return (- <div className={styles.container}>- {sections.map(({ key, items, label, sign, statusClass }) =>- items.length > 0 ? (- <div key={key}>- <div className={styles.sectionHeader}>- {label} · {items.length}- </div>- {items.map((file) => (- <div className={styles.row} key={`${key}:${file}`} title={file}>- <span className={statusClass}>{sign}</span>- <span className={styles.path}>{file}</span>- </div>- ))}- </div>- ) : null,- )}- </div>- );-});--WorkingTreeFilesContent.displayName = 'WorkingTreeFilesContent';--export default WorkingTreeFilesContent;diff --git a/src/features/ChatInput/RuntimeConfig/useWorkingTreeFiles.ts b/src/features/ChatInput/RuntimeConfig/useWorkingTreeFiles.tsdeleted file mode 100644index e90b0d294b9..00000000000--- a/src/features/ChatInput/RuntimeConfig/useWorkingTreeFiles.ts+++ /dev/null@@ -1,19 +0,0 @@-import { isDesktop } from '@lobechat/const';--import { useClientDataSWR } from '@/libs/swr';-import { electronGitService } from '@/services/electron/git';--/**- * Per-file breakdown of the working tree (paths grouped by add/modify/delete).- * Lazy — only fetched when `enabled` is true (e.g. the popover is open), since- * it's strictly richer than useWorkingTreeStatus and most users never open the list.- */-export const useWorkingTreeFiles = (dirPath?: string, enabled?: boolean) => {- const key = isDesktop && dirPath && enabled ? ['git-working-tree-files', dirPath] : null;-- return useClientDataSWR(key, () => electronGitService.getGitWorkingTreeFiles(dirPath!), {- focusThrottleInterval: 5 * 1000,- revalidateOnFocus: true,- shouldRetryOnError: false,- });-};diff --git a/src/features/Conversation/ChatInput/QueueTray.tsx b/src/features/Conversation/ChatInput/QueueTray.tsxindex d5e678693bc..7f72a3a0701 100644--- a/src/features/Conversation/ChatInput/QueueTray.tsx+++ b/src/features/Conversation/ChatInput/QueueTray.tsx@@ -1,21 +1,27 @@'use client';-import { ActionIcon, Flexbox, Icon } from '@lobehub/ui';+import { ActionIcon, Flexbox, Icon, Image } from '@lobehub/ui';import { createStaticStyles } from 'antd-style';import { ArrowUp, ListEnd, Pencil, Trash2 } from 'lucide-react';import { memo, useCallback, useMemo } from 'react';import { useTranslation } from 'react-i18next';+import FileIcon from '@/components/FileIcon';import { useChatStore } from '@/store/chat';import { operationSelectors } from '@/store/chat/selectors';import {AI_RUNTIME_OPERATION_TYPES,+ type QueuedFile,type QueuedMessage,+ reconstructUploadFilesFromQueue,} from '@/store/chat/slices/operation/types';import { messageMapKey } from '@/store/chat/utils/messageMapKey';+import { useFileStore } from '@/store/file';import { useConversationStore } from '../store';+const PREVIEW_SIZE = 28;+const styles = createStaticStyles(({ css, cssVar }) => ({container: css`border: 1px solid ${cssVar.colorFillSecondary};@@ -23,10 +29,46 @@ const styles = createStaticStyles(({ css, cssVar }) => ({border-radius: 12px 12px 0 0;background: ${cssVar.colorBgElevated};`,+ fileChip: css`+ overflow: hidden;+ flex-shrink: 0;++ max-width: 160px;+ height: 28px;+ padding-block: 0;+ padding-inline: 6px;+ border: 1px solid ${cssVar.colorBorderSecondary};+ border-radius: 6px;++ font-size: 12px;+ color: ${cssVar.colorTextSecondary};+ white-space: nowrap;+ `,+ fileChipName: css`+ overflow: hidden;+ text-overflow: ellipsis;+ `,icon: css`flex-shrink: 0;color: ${cssVar.colorTextDescription};`,+ imageThumb: css`+ flex-shrink: 0;++ width: 28px !important;+ height: 28px !important;+ margin-block: 0 !important;+ border: 1px solid ${cssVar.colorBorderSecondary};+ border-radius: 6px;++ box-shadow: none;++ img {+ width: 28px !important;+ height: 28px !important;+ object-fit: cover;+ }+ `,item: css`padding-block: 6px 4px;padding-inline: 12px 8px;@@ -44,6 +86,43 @@ const styles = createStaticStyles(({ css, cssVar }) => ({`,}));+const isImageFile = (f: QueuedFile) => f.mimeType.startsWith('image') && !!f.url;++interface QueuedFilePreviewProps {+ file: QueuedFile;+}++const QueuedFilePreview = memo<QueuedFilePreviewProps>(({ file }) => {+ if (isImageFile(file)) {+ // Use @lobehub/ui Image so click-to-zoom preview works. Lock both wrapper+ // and inner <img> to PREVIEW_SIZE — `size` alone doesn't constrain the+ // intrinsic image dimensions inside a flex row.+ return (+ <Image+ alt={file.name}+ classNames={{ wrapper: styles.imageThumb }}+ objectFit={'cover'}+ size={PREVIEW_SIZE}+ src={file.url}+ title={file.name}+ styles={{+ image: { height: PREVIEW_SIZE, width: PREVIEW_SIZE },+ wrapper: { height: PREVIEW_SIZE, width: PREVIEW_SIZE },+ }}+ />+ );+ }++ return (+ <Flexbox horizontal align={'center'} className={styles.fileChip} gap={4} title={file.name}>+ <FileIcon fileName={file.name} fileType={file.mimeType} size={14} />+ <span className={styles.fileChipName}>{file.name}</span>+ </Flexbox>+ );+});++QueuedFilePreview.displayName = 'QueuedFilePreview';+const QueueTray = memo(() => {const { t } = useTranslation('chat');const context = useConversationStore((s) => s.context);@@ -60,15 +139,24 @@ const QueueTray = memo(() => {const queuedMessages = useChatStore((s) => operationSelectors.getQueuedMessages(context)(s));const removeQueuedMessage = useChatStore((s) => s.removeQueuedMessage);+ const dispatchChatUploadFileList = useFileStore((s) => s.dispatchChatUploadFileList);const editor = useConversationStore((s) => s.editor);+ // Edit: restore both the text content AND the attached files back to the+ // input area, so the user can tweak the message and re-send. Without the+ // file restore, images attached to a queued message would silently disappear+ // when the user clicks the pencil.const handleEdit = useCallback(- (msgId: string, content: string) => {- removeQueuedMessage(contextKey, msgId);- editor?.setDocument('markdown', content);+ (msg: QueuedMessage) => {+ removeQueuedMessage(contextKey, msg.id);+ editor?.setDocument('markdown', msg.content);editor?.focus();+ if (msg.filesPreview?.length) {+ const restored = reconstructUploadFilesFromQueue(msg.filesPreview);+ dispatchChatUploadFileList({ files: restored, type: 'addFiles' });+ }},- [contextKey, editor, removeQueuedMessage],+ [contextKey, dispatchChatUploadFileList, editor, removeQueuedMessage],);// "Send now": cancel the currently running agent run for this context, then@@ -86,7 +174,13 @@ const QueueTray = memo(() => {if (runningOpId) chat.cancelOperation(runningOpId, 'send_now');removeQueuedMessage(contextKey, msg.id);- const filesArray = msg.files?.length ? msg.files.map((id) => ({ id }) as any) : undefined;+ // Reconstruct UploadFileItem-shaped objects so the optimistic temp message+ // can rebuild imageList/videoList from the snapshotted preview metadata.+ const filesArray = msg.filesPreview?.length+ ? reconstructUploadFilesFromQueue(msg.filesPreview)+ : msg.files?.length+ ? (msg.files.map((id) => ({ id })) as any)+ : undefined;chat.sendMessage({context,@@ -105,38 +199,52 @@ const QueueTray = memo(() => {return (<Flexbox className={styles.container} gap={0}>- {queuedMessages.map((msg, index) => (- <Flexbox- horizontal- align="center"- className={index > 0 ? `${styles.item} ${styles.itemDivider}` : styles.item}- gap={8}- key={msg.id}- >- <Icon className={styles.icon} icon={ListEnd} size={14} />- <Flexbox className={styles.text} flex={1}>- {msg.content}+ {queuedMessages.map((msg, index) => {+ const previews = msg.filesPreview ?? [];+ return (+ <Flexbox+ horizontal+ align="center"+ className={index > 0 ? `${styles.item} ${styles.itemDivider}` : styles.item}+ gap={8}+ key={msg.id}+ >+ <Icon className={styles.icon} icon={ListEnd} size={14} />+ <Flexbox horizontal align={'center'} flex={1} gap={8} style={{ overflow: 'hidden' }}>+ {previews.length > 0 && (+ <Flexbox horizontal flex={'none'} gap={4}>+ {previews.map((file) => (+ <QueuedFilePreview file={file} key={file.id} />+ ))}+ </Flexbox>+ )}+ {msg.content && (+ <Flexbox className={styles.text} flex={1}>+ {msg.content}+ </Flexbox>+ )}+ </Flexbox>+ <ActionIcon+ icon={Pencil}+ size="small"+ title={t('inputQueue.edit')}+ onClick={() => handleEdit(msg)}+ />+ <ActionIcon+ icon={ArrowUp}+ size="small"+ title={t('inputQueue.sendNow')}+ onClick={() => handleSendNow(msg)}+ />+ <ActionIcon+ icon={Trash2}+ size="small"+ title={t('inputQueue.delete')}+ onClick={() => removeQueuedMessage(contextKey, msg.id)}+ /></Flexbox>- <ActionIcon- icon={Pencil}- size="small"- title={t('inputQueue.edit')}- onClick={() => handleEdit(msg.id, msg.content)}- />- <ActionIcon- icon={ArrowUp}- size="small"- title={t('inputQueue.sendNow')}- onClick={() => handleSendNow(msg)}- />- <ActionIcon- icon={Trash2}- size="small"- title={t('inputQueue.delete')}- onClick={() => removeQueuedMessage(contextKey, msg.id)}- />- </Flexbox>- ))}+ );+ })}</Flexbox>);});diff --git a/src/features/DevPanel/RenderGallery/ToolPage.tsx b/src/features/DevPanel/RenderGallery/ToolPage.tsxindex 4dca1268c79..7b911ebfe64 100644--- a/src/features/DevPanel/RenderGallery/ToolPage.tsx+++ b/src/features/DevPanel/RenderGallery/ToolPage.tsx@@ -1,12 +1,19 @@'use client';-import { Flexbox, Tag, Text } from '@lobehub/ui';+import { Flexbox, Segmented, Tag, Text } from '@lobehub/ui';import { createStaticStyles } from 'antd-style';+import { useEffect, useState } from 'react';import { useParams } from 'react-router-dom';+import { LIFECYCLE_MODE_LABEL, LIFECYCLE_MODES, type LifecycleMode } from './lifecycleMode';import ToolPreview from './ToolPreview';import { useDevtoolsEntries } from './useDevtoolsEntries';+const STORAGE_KEY = 'devtools-render-gallery:lifecycle-mode';++const isLifecycleMode = (value: string | null): value is LifecycleMode =>+ !!value && (LIFECYCLE_MODES as string[]).includes(value);+const styles = createStaticStyles(({ css, cssVar }) => ({body: css`gap: 24px;@@ -25,6 +32,22 @@ const styles = createStaticStyles(({ css, cssVar }) => ({gap: 8px;padding-block-end: 4px;`,+ modeBar: css`+ position: sticky;+ z-index: 2;+ inset-block-start: 0;++ gap: 12px;+ align-items: center;++ padding-block: 10px;+ padding-inline: 14px;+ border: 1px solid ${cssVar.colorBorderSecondary};+ border-radius: 14px;++ background: ${cssVar.colorBgContainer};+ box-shadow: ${cssVar.boxShadowTertiary};+ `,}));const DevtoolsToolPage = () => {@@ -32,6 +55,20 @@ const DevtoolsToolPage = () => {const { identifier } = useParams<{ identifier: string }>();const toolset = identifier ? toolsetMap.get(identifier) : undefined;+ const [mode, setMode] = useState<LifecycleMode>('success');++ // Hydrate from localStorage so the choice survives navigation between toolsets.+ useEffect(() => {+ if (typeof window === 'undefined') return;+ const stored = window.localStorage.getItem(STORAGE_KEY);+ if (isLifecycleMode(stored)) setMode(stored);+ }, []);++ useEffect(() => {+ if (typeof window === 'undefined') return;+ window.localStorage.setItem(STORAGE_KEY, mode);+ }, [mode]);+if (!toolset) {return (<Flexbox className={styles.empty}>@@ -64,8 +101,23 @@ const DevtoolsToolPage = () => {)}</Flexbox>+ <Flexbox horizontal className={styles.modeBar}>+ <Text fontSize={12} type={'secondary'} weight={600}>+ Lifecycle+ </Text>+ <Segmented+ size={'small'}+ value={mode}+ options={LIFECYCLE_MODES.map((value) => ({+ label: LIFECYCLE_MODE_LABEL[value],+ value,+ }))}+ onChange={(value) => setMode(value as LifecycleMode)}+ />+ </Flexbox>+{toolset.apis.map((api) => (- <ToolPreview api={api} key={`${api.identifier}:${api.apiName}`} />+ <ToolPreview api={api} key={`${api.identifier}:${api.apiName}`} mode={mode} />))}</Flexbox>);diff --git a/src/features/DevPanel/RenderGallery/ToolPreview.tsx b/src/features/DevPanel/RenderGallery/ToolPreview.tsxindex 3521a765ab5..049871f3284 100644--- a/src/features/DevPanel/RenderGallery/ToolPreview.tsx+++ b/src/features/DevPanel/RenderGallery/ToolPreview.tsx@@ -4,20 +4,16 @@ import { Block, Flexbox, Segmented, Tag, Text } from '@lobehub/ui';import { createStaticStyles } from 'antd-style';import { Component, type ReactNode, useMemo, useState } from 'react';+import {+ bodyKindForMode,+ deriveFixtureProps,+ type FixtureBodyKind,+ type LifecycleMode,+ type ToolRenderFixtureVariant,+} from './lifecycleMode';import type { ApiEntry } from './useDevtoolsEntries';import { toApiAnchor } from './useDevtoolsEntries';-type BodyKind = 'render' | 'streaming' | 'placeholder' | 'intervention';--const BODY_ORDER: BodyKind[] = ['render', 'streaming', 'placeholder', 'intervention'];--const BODY_LABEL: Record<BodyKind, string> = {- intervention: 'Intervention',- placeholder: 'Placeholder',- render: 'Render',- streaming: 'Streaming',-};-const styles = createStaticStyles(({ css, cssVar }) => ({card: css`scroll-margin-block-start: 16px;@@ -128,15 +124,15 @@ const coerceInspectorContent = (value: unknown): string | null => {};const Missing = ({ kind }: { kind: string }) => (- <div className={styles.missingShell}>No {kind} registered for this API.</div>+ <div className={styles.missingShell}>No {kind} component registered for this API.</div>);interface ToolPreviewProps {api: ApiEntry;+ mode: LifecycleMode;}-const ToolPreview = ({ api }: ToolPreviewProps) => {- const { fixture } = api;+const ToolPreview = ({ api, mode }: ToolPreviewProps) => {const messageId = `devtools-${api.identifier}-${api.apiName}`;const toolCallId = `${messageId}-tool`;@@ -146,90 +142,60 @@ const ToolPreview = ({ api }: ToolPreviewProps) => {const Placeholder = api.placeholder;const Intervention = api.intervention;- const availableBodyKinds = useMemo<BodyKind[]>(- () =>- BODY_ORDER.filter((kind) => {- switch (kind) {- case 'render': {- return Boolean(Render);- }- case 'streaming': {- return Boolean(Streaming);- }- case 'placeholder': {- return Boolean(Placeholder);- }- case 'intervention': {- return Boolean(Intervention);- }- default: {- return false;- }- }- }),- [Render, Streaming, Placeholder, Intervention],- );-- const defaultBody = availableBodyKinds[0] ?? 'render';- const [activeBody, setActiveBody] = useState<BodyKind>(defaultBody);+ const variants = api.fixture.variants;+ const [activeVariantId, setActiveVariantId] = useState<string>(variants[0]?.id ?? 'default');+ const activeVariant: ToolRenderFixtureVariant =+ variants.find((variant) => variant.id === activeVariantId) ?? variants[0];- const effectiveBody = availableBodyKinds.includes(activeBody) ? activeBody : defaultBody;+ const derived = useMemo(() => deriveFixtureProps(activeVariant, mode), [activeVariant, mode]);- const segmentOptions = BODY_ORDER.map((kind) => ({- disabled: !availableBodyKinds.includes(kind),- label: BODY_LABEL[kind],- value: kind,- }));+ const targetBodyKind: FixtureBodyKind = bodyKindForMode(mode);const inspectorResult = {- content: coerceInspectorContent(fixture.content),- error: fixture.pluginError,- state: fixture.pluginState,+ content: coerceInspectorContent(activeVariant.content),+ error: derived.pluginError,+ state: derived.pluginState,};- const renderBody = () => {- switch (effectiveBody) {- case 'render': {- return Render ? (- <RenderBoundary label={'Render'}>- <Render- apiName={api.apiName}- args={fixture.args}- content={fixture.content}- identifier={api.identifier}- messageId={messageId}- pluginError={fixture.pluginError}- pluginState={fixture.pluginState}- toolCallId={toolCallId}- />- </RenderBoundary>- ) : (- <Missing kind={'render'} />- );- }+ const bodyContent = (() => {+ switch (targetBodyKind) {case 'streaming': {- return Streaming ? (- <RenderBoundary label={'Streaming'}>- <Streaming- apiName={api.apiName}- args={fixture.args ?? {}}- identifier={api.identifier}- messageId={messageId}- toolCallId={toolCallId}- />- </RenderBoundary>- ) : (- <Missing kind={'streaming'} />- );+ if (Streaming) {+ return (+ <RenderBoundary label={'Streaming'}>+ <Streaming+ apiName={api.apiName}+ args={derived.args}+ identifier={api.identifier}+ messageId={messageId}+ toolCallId={toolCallId}+ />+ </RenderBoundary>+ );+ }+ // No dedicated Streaming slot — fall back to Render shown in streaming state.+ if (Render) {+ return (+ <RenderBoundary label={'Render'}>+ <Render+ apiName={api.apiName}+ args={derived.args}+ content={derived.content}+ identifier={api.identifier}+ messageId={messageId}+ pluginError={derived.pluginError}+ pluginState={derived.pluginState}+ toolCallId={toolCallId}+ />+ </RenderBoundary>+ );+ }+ return <Missing kind={'streaming'} />;}case 'placeholder': {return Placeholder ? (<RenderBoundary label={'Placeholder'}>- <Placeholder- apiName={api.apiName}- args={fixture.args ?? {}}- identifier={api.identifier}- />+ <Placeholder apiName={api.apiName} args={derived.args} identifier={api.identifier} /></RenderBoundary>) : (<Missing kind={'placeholder'} />@@ -240,7 +206,7 @@ const ToolPreview = ({ api }: ToolPreviewProps) => {<RenderBoundary label={'Intervention'}><InterventionapiName={api.apiName}- args={fixture.args ?? {}}+ args={derived.args}identifier={api.identifier}interactionMode={'approval'}messageId={messageId}@@ -251,10 +217,25 @@ const ToolPreview = ({ api }: ToolPreviewProps) => {);}default: {- return null;+ return Render ? (+ <RenderBoundary label={'Render'}>+ <Render+ apiName={api.apiName}+ args={derived.args}+ content={derived.content}+ identifier={api.identifier}+ messageId={messageId}+ pluginError={derived.pluginError}+ pluginState={derived.pluginState}+ toolCallId={toolCallId}+ />+ </RenderBoundary>+ ) : (+ <Missing kind={'render'} />+ );}}- };+ })();return (<Flexbox className={styles.card} id={toApiAnchor(api.apiName)}>@@ -264,11 +245,21 @@ const ToolPreview = ({ api }: ToolPreviewProps) => {{api.apiName}</Text><Tag>{api.identifier}</Tag>- {!Inspector && availableBodyKinds.length === 0 && <Tag color={'warning'}>no renders</Tag>}+ {variants.length > 1 && (+ <Segmented+ size={'small'}+ value={activeVariant.id}+ options={variants.map((variant) => ({+ label: variant.label,+ value: variant.id,+ }))}+ onChange={(value) => setActiveVariantId(value as string)}+ />+ )}</Flexbox>- {api.description && (+ {(api.description || activeVariant.description) && (<Text fontSize={13} type={'secondary'}>- {api.description}+ {activeVariant.description ?? api.description}</Text>)}</Flexbox>@@ -285,10 +276,12 @@ const ToolPreview = ({ api }: ToolPreviewProps) => {<RenderBoundary label={'Inspector'}><InspectorapiName={api.apiName}- args={fixture.args ?? {}}+ args={derived.args}identifier={api.identifier}- isLoading={false}- pluginState={fixture.pluginState}+ isArgumentsStreaming={derived.isArgumentsStreaming}+ isLoading={derived.isLoading}+ partialArgs={derived.partialArgs}+ pluginState={derived.pluginState}result={inspectorResult}/></RenderBoundary>@@ -299,23 +292,13 @@ const ToolPreview = ({ api }: ToolPreviewProps) => {</Flexbox><Flexbox gap={8}>- <Flexbox- horizontal- align={'center'}- className={styles.sectionLabel}- justify={'space-between'}- >+ <Flexbox horizontal className={styles.sectionLabel}><Text fontSize={12} type={'secondary'} weight={600}>Body</Text>- <Segmented- options={segmentOptions}- size={'small'}- value={effectiveBody}- onChange={(value) => setActiveBody(value as BodyKind)}- />+ <Tag>{targetBodyKind}</Tag></Flexbox>- <div className={styles.previewShell}>{renderBody()}</div>+ <div className={styles.previewShell}>{bodyContent}</div></Flexbox><details>@@ -323,10 +306,13 @@ const ToolPreview = ({ api }: ToolPreviewProps) => {<pre className={styles.code}>{JSON.stringify({- args: fixture.args,- content: fixture.content,- pluginError: fixture.pluginError,- pluginState: fixture.pluginState,+ args: derived.args,+ content: derived.content,+ isArgumentsStreaming: derived.isArgumentsStreaming,+ isLoading: derived.isLoading,+ partialArgs: derived.partialArgs,+ pluginError: derived.pluginError,+ pluginState: derived.pluginState,},null,2,diff --git a/src/features/DevPanel/RenderGallery/fixtures/_helpers.ts b/src/features/DevPanel/RenderGallery/fixtures/_helpers.tsnew file mode 100644index 00000000000..3b329d4f2c2--- /dev/null+++ b/src/features/DevPanel/RenderGallery/fixtures/_helpers.ts@@ -0,0 +1,114 @@+'use client';++import type { LobeChatPluginApi } from '@lobechat/types';++import type { ToolRenderFixture, ToolRenderFixtureVariant } from '../lifecycleMode';++/**+ * Wrap a single fixture body into the canonical `{ variants: [...] }` shape so+ * APIs that only need one preview state stay terse.+ */+export const single = (+ variant: Omit<ToolRenderFixtureVariant, 'id' | 'label'> & {+ id?: string;+ label?: string;+ } = {},+): ToolRenderFixture => ({+ variants: [{ id: 'default', label: 'Default', ...variant }],+});++/**+ * Author multiple lifecycle-state variants (e.g. success / empty / failure) for+ * an API. Each entry only needs `label`; `id` defaults to a slugified label.+ */+export const variants = (+ list: Array<Omit<ToolRenderFixtureVariant, 'id'> & { id?: string }>,+): ToolRenderFixture => ({+ variants: list.map((variant, index) => ({+ id: variant.id ?? (variant.label.toLowerCase().replaceAll(/\s+/g, '-') || `variant-${index}`),+ ...variant,+ })),+});++export interface ToolsetFixtureModule {+ /** Optional per-API descriptions when the live manifest doesn't carry them. */+ apiList?: Array<Pick<LobeChatPluginApi, 'description' | 'name'>>;+ /** Map of `apiName -> ToolRenderFixture` for this toolset. */+ fixtures: Record<string, ToolRenderFixture>;+ /** Toolset identifier exactly as registered in the builtin tool registry. */+ identifier: string;+ /** Optional toolset-level metadata (used when the manifest doesn't expose one). */+ meta?: { description?: string; title: string };+}++/**+ * Identity helper that gives authors typed autocomplete + structural validation+ * when defining a per-toolset fixture module.+ */+export const defineFixtures = (definition: ToolsetFixtureModule): ToolsetFixtureModule =>+ definition;++const humanize = (value: string) =>+ value+ .replaceAll('_', ' ')+ .replaceAll(/([a-z0-9])([A-Z])/g, '$1 $2')+ .replaceAll(/\s+/g, ' ')+ .trim()+ .replace(/^./, (char) => char.toUpperCase());++const buildStringSample = (key: string, schema: any) => {+ if (schema?.format === 'uri' || key.toLowerCase().includes('url')) return 'https://example.com';+ if (key.toLowerCase().includes('path'))+ return `/workspace/${key.replace(/Path$/i, '').toLowerCase() || 'file'}.ts`;+ if (key.toLowerCase().includes('id')) return `${key}-sample`;+ if (key.toLowerCase().includes('query')) return 'tool render preview';+ if (key.toLowerCase().includes('title')) return 'Preview title';+ if (key.toLowerCase().includes('description')) return 'Preview description';+ if (key.toLowerCase().includes('content') || key.toLowerCase().includes('prompt')) {+ return `Sample ${humanize(key).toLowerCase()} for the devtools preview.`;+ }++ return `${humanize(key)} sample`;+};++export const buildSchemaSample = (schema: any, key = 'value'): any => {+ if (!schema) return undefined;+ if (schema.default !== undefined) return schema.default;+ if (schema.example !== undefined) return schema.example;+ if (Array.isArray(schema.examples) && schema.examples.length > 0) return schema.examples[0];+ if (Array.isArray(schema.enum) && schema.enum.length > 0) return schema.enum[0];++ switch (schema.type) {+ case 'array': {+ const item = buildSchemaSample(+ schema.items,+ key.endsWith('s') ? key.slice(0, -1) : `${key}Item`,+ );+ return item === undefined ? [] : [item];+ }+ case 'boolean': {+ return true;+ }+ case 'integer':+ case 'number': {+ return 1;+ }+ case 'object': {+ const properties = schema.properties || {};+ return Object.fromEntries(+ Object.entries(properties)+ .map(([propertyKey, propertySchema]) => [+ propertyKey,+ buildSchemaSample(propertySchema, propertyKey),+ ])+ .filter(([, value]) => value !== undefined),+ );+ }+ case 'string':+ default: {+ return buildStringSample(key, schema);+ }+ }+};++export { humanize };diff --git a/src/features/DevPanel/RenderGallery/fixtures/claude-code.ts b/src/features/DevPanel/RenderGallery/fixtures/claude-code.tsnew file mode 100644index 00000000000..c9f2bd15695--- /dev/null+++ b/src/features/DevPanel/RenderGallery/fixtures/claude-code.ts@@ -0,0 +1,242 @@+'use client';++import { ClaudeCodeIdentifier } from '@lobechat/builtin-tool-claude-code/client';++import { defineFixtures, single, variants } from './_helpers';++export default defineFixtures({+ identifier: ClaudeCodeIdentifier,+ meta: {+ description: 'Anthropic Claude Code render previews.',+ title: 'Claude Code',+ },+ apiList: [+ {+ description: 'Spawn and summarize a sub-agent task.',+ name: 'Agent',+ },+ {+ description: 'Run a shell command.',+ name: 'Bash',+ },+ {+ description: 'Patch file contents.',+ name: 'Edit',+ },+ {+ description: 'Find files by glob pattern.',+ name: 'Glob',+ },+ {+ description: 'Search file contents.',+ name: 'Grep',+ },+ {+ description: 'Read file content.',+ name: 'Read',+ },+ {+ description: 'Schedule when to resume work.',+ name: 'ScheduleWakeup',+ },+ {+ description: 'Run a Claude Code skill.',+ name: 'Skill',+ },+ {+ description: 'Read output from a background task.',+ name: 'TaskOutput',+ },+ {+ description: 'Stop a background task.',+ name: 'TaskStop',+ },+ {+ description: 'Track todo progress.',+ name: 'TodoWrite',+ },+ {+ description: 'Look up deferred tools by name or keyword.',+ name: 'ToolSearch',+ },+ {+ description: 'Write a new file.',+ name: 'Write',+ },+ ],+ fixtures: {+ Agent: single({+ args: {+ prompt:+ 'Inspect the generated preview fixtures and reply with a short note about the riskiest missing case.',+ },+ content:+ '- Search-driven renders still need richer empty-state fixtures.\n- The grouped execute-tasks preview depends on seeded agent-group state.',+ }),+ Bash: variants([+ {+ args: { command: 'rg -n "TodoListRender" packages src' },+ content:+ 'packages/builtin-tools/src/codex/TodoListRender.tsx:11:const TodoListRender = memo<...>',+ label: 'Match found',+ pluginState: {+ exitCode: 0,+ isBackground: false,+ output:+ 'packages/builtin-tools/src/codex/TodoListRender.tsx:11:const TodoListRender = memo<...>',+ stdout:+ 'packages/builtin-tools/src/codex/TodoListRender.tsx:11:const TodoListRender = memo<...>',+ success: true,+ },+ },+ {+ args: { command: 'bun run type-check' },+ content:+ 'src/features/DevPanel/RenderGallery/ToolPreview.tsx(48,12): error TS2304: Cannot find name "Foo".\n',+ label: 'Non-zero exit',+ pluginState: {+ exitCode: 2,+ isBackground: false,+ output:+ 'src/features/DevPanel/RenderGallery/ToolPreview.tsx(48,12): error TS2304: Cannot find name "Foo".\n',+ stderr:+ 'src/features/DevPanel/RenderGallery/ToolPreview.tsx(48,12): error TS2304: Cannot find name "Foo".\n',+ success: false,+ },+ },+ {+ args: { command: 'find . -name "*.tsx" -not -path "*/node_modules/*" | head -20' },+ content: Array.from({ length: 20 }, (_, i) => `./src/components/Card${i}.tsx`).join('\n'),+ label: 'Large output',+ pluginState: {+ exitCode: 0,+ isBackground: false,+ output: Array.from({ length: 20 }, (_, i) => `./src/components/Card${i}.tsx`).join('\n'),+ stdout: Array.from({ length: 20 }, (_, i) => `./src/components/Card${i}.tsx`).join('\n'),+ success: true,+ },+ },+ ]),+ Edit: single({+ args: {+ file_path: 'src/spa/router/desktopRouter.config.desktop.tsx',+ new_string: "path: 'tasks',",+ old_string: "path: 'tasks',",+ },+ }),+ Glob: single({+ args: { path: 'src/routes', pattern: '**/index.tsx' },+ content: 'src/routes/(main)/agent/index.tsx\nsrc/routes/(main)/devtools/index.tsx',+ }),+ Grep: variants([+ {+ args: { path: 'packages', pattern: 'BuiltinRenderProps', type: 'ts' },+ content:+ 'packages/types/src/tool/builtin.ts:244:export interface BuiltinRenderProps<Arguments = any, State = any, Content = any> {\npackages/builtin-tools/src/renders.ts:18:type Render = (p: BuiltinRenderProps) => ReactNode;',+ label: 'Many matches',+ },+ {+ args: { path: 'src', pattern: 'NEVER_MATCH_THIS_TOKEN', type: 'tsx' },+ content: '',+ label: 'No matches',+ },+ ]),+ Read: single({+ args: { file_path: 'packages/builtin-tools/src/renders.ts' },+ content:+ "1 import { RunCommandRender } from '@lobechat/shared-tool-ui/renders';\n2 export interface BuiltinRenderRegistryEntry { ... }",+ }),+ ScheduleWakeup: single({+ args: {+ delaySeconds: 1200,+ reason: 'Recheck the failing build once dependencies finish installing.',+ },+ }),+ Skill: single({+ args: { skill: 'codebase-search' },+ content: 'Use ripgrep first, then open only the relevant files to keep context sharp.',+ }),+ TaskOutput: single({+ args: { block: false, task_id: 'task-build-2025-04-25', timeout_ms: 8000 },+ content:+ '✅ Vite: compile and bundle finished (200) http://localhost:9876/\nDebug Proxy: https://app.lobehub.com/_dangerous_local_dev_proxy?debug-host=http://localhost:9876',+ }),+ TaskStop: single({+ args: { task_id: 'task-build-2025-04-25' },+ content: 'Background task stopped (exit code 0).',+ }),+ TodoWrite: variants([+ {+ args: {+ todos: [+ {+ activeForm: 'Capture current registry coverage',+ content: 'Capture current registry coverage',+ status: 'completed',+ },+ {+ activeForm: 'Build /devtools page',+ content: 'Build /devtools page',+ status: 'in_progress',+ },+ {+ activeForm: 'Audit missing fixtures',+ content: 'Audit missing fixtures',+ status: 'pending',+ },+ ],+ },+ label: 'Mixed progress',+ },+ {+ args: {+ todos: [+ {+ activeForm: 'Plan render gallery rewrite',+ content: 'Plan render gallery rewrite',+ status: 'pending',+ },+ {+ activeForm: 'Sketch lifecycle modes',+ content: 'Sketch lifecycle modes',+ status: 'pending',+ },+ ],+ },+ label: 'All pending',+ },+ {+ args: {+ todos: [+ {+ activeForm: 'Migrate fixtures to variants',+ content: 'Migrate fixtures to variants',+ status: 'completed',+ },+ {+ activeForm: 'Verify in /devtools',+ content: 'Verify in /devtools',+ status: 'completed',+ },+ {+ activeForm: 'Push to remote',+ content: 'Push to remote',+ status: 'completed',+ },+ ],+ },+ label: 'All done',+ },+ ]),+ ToolSearch: single({+ args: { max_results: 5, query: 'select:Read,Edit,Grep' },+ content: 'Loaded 3 deferred tool schemas: Read, Edit, Grep.',+ }),+ Write: single({+ args: {+ content: "export const previewEnabled = process.env.NODE_ENV === 'development';\n",+ file_path: 'src/routes/(main)/devtools/featureFlag.ts',+ },+ }),+ },+});diff --git a/src/features/DevPanel/RenderGallery/fixtures/codex.ts b/src/features/DevPanel/RenderGallery/fixtures/codex.tsnew file mode 100644index 00000000000..fa5fc927e43--- /dev/null+++ b/src/features/DevPanel/RenderGallery/fixtures/codex.ts@@ -0,0 +1,97 @@+'use client';++import { defineFixtures, single } from './_helpers';++export default defineFixtures({+ identifier: 'codex',+ meta: {+ description: 'Codex-specific render previews and shared command cards.',+ title: 'Codex',+ },+ apiList: [+ {+ description: 'Run a shell command in Codex.',+ name: 'command_execution',+ },+ {+ description: 'Preview Codex file change summaries.',+ name: 'file_change',+ },+ {+ description: 'Preview Codex todo list rendering.',+ name: 'todo_list',+ },+ ],+ fixtures: {+ command_execution: single({+ args: { command: 'bun run type-check' },+ content: 'Checked 1247 files in 2.3s\nNo type errors found.',+ pluginState: {+ exitCode: 0,+ isBackground: false,+ output: 'Checked 1247 files in 2.3s\nNo type errors found.',+ stdout: 'Checked 1247 files in 2.3s\nNo type errors found.',+ success: true,+ },+ }),+ file_change: single({+ args: {+ changes: [+ {+ kind: 'add',+ linesAdded: 62,+ linesDeleted: 0,+ path: 'src/routes/(main)/devtools/index.tsx',+ },+ {+ kind: 'modify',+ linesAdded: 23,+ linesDeleted: 0,+ path: 'packages/builtin-tools/src/renders.ts',+ },+ {+ kind: 'rename',+ linesAdded: 28,+ linesDeleted: 0,+ path: 'tmp/devtools-preview-old.tsx',+ },+ ],+ },+ content: 'File changes applied (1 added, 1 modified, 1 renamed).',+ pluginState: {+ changes: [+ {+ kind: 'add',+ linesAdded: 62,+ linesDeleted: 0,+ path: 'src/routes/(main)/devtools/index.tsx',+ },+ {+ kind: 'modify',+ linesAdded: 23,+ linesDeleted: 0,+ path: 'packages/builtin-tools/src/renders.ts',+ },+ {+ kind: 'rename',+ linesAdded: 28,+ linesDeleted: 0,+ path: 'tmp/devtools-preview-old.tsx',+ },+ ],+ linesAdded: 113,+ linesDeleted: 0,+ },+ }),+ todo_list: single({+ args: {+ items: [+ { completed: true, text: 'Wire up the render registry export' },+ { completed: false, text: 'Build a devtools preview page' },+ { completed: false, text: 'Verify every tool render fixture' },+ ],+ },+ content: 'Todo list updated (1/3 completed).',+ }),+ },+});diff --git a/src/features/DevPanel/RenderGallery/fixtures/github.ts b/src/features/DevPanel/RenderGallery/fixtures/github.tsnew file mode 100644index 00000000000..9fd93fa70b5--- /dev/null+++ b/src/features/DevPanel/RenderGallery/fixtures/github.ts@@ -0,0 +1,19 @@+'use client';++import { defineFixtures, single } from './_helpers';++export default defineFixtures({+ identifier: 'github',+ fixtures: {+ run_command: single({+ args: {+ command: 'gh api /repos/lobehub/lobe-chat/issues?state=open',+ },+ pluginState: {+ command: 'gh api /repos/lobehub/lobe-chat/issues?state=open',+ exitCode: 0,+ success: true,+ },+ }),+ },+});diff --git a/src/features/DevPanel/RenderGallery/fixtures/index.ts b/src/features/DevPanel/RenderGallery/fixtures/index.tsnew file mode 100644index 00000000000..e75ced3af1e--- /dev/null+++ b/src/features/DevPanel/RenderGallery/fixtures/index.ts@@ -0,0 +1,130 @@+'use client';++import { builtinTools } from '@lobechat/builtin-tools';+import type { BuiltinToolManifest, LobeChatPluginApi } from '@lobechat/types';++import type { ToolRenderFixture } from '../lifecycleMode';+import { buildSchemaSample, humanize, single, type ToolsetFixtureModule } from './_helpers';+import claudeCode from './claude-code';+import codex from './codex';+import github from './github';+import lobeActivator from './lobe-activator';+import lobeAgentBuilder from './lobe-agent-builder';+import lobeAgentDocuments from './lobe-agent-documents';+import lobeAgentManagement from './lobe-agent-management';+import lobeCloudSandbox from './lobe-cloud-sandbox';+import lobeGroupAgentBuilder from './lobe-group-agent-builder';+import lobeGroupManagement from './lobe-group-management';+import lobeGtd from './lobe-gtd';+import lobeKnowledgeBase from './lobe-knowledge-base';+import lobeLocalSystem from './lobe-local-system';+import lobeNotebook from './lobe-notebook';+import lobePageAgent from './lobe-page-agent';+import lobeSkillStore from './lobe-skill-store';+import lobeSkills from './lobe-skills';+import lobeUserInteraction from './lobe-user-interaction';+import lobeUserMemory from './lobe-user-memory';+import lobeWebBrowsing from './lobe-web-browsing';+import lobeWebOnboarding from './lobe-web-onboarding';++export type { ToolRenderFixture, ToolRenderFixtureVariant } from '../lifecycleMode';++export interface ToolRenderMeta {+ api?: LobeChatPluginApi;+ apiName: string;+ description?: string;+ identifier: string;+ toolsetDescription?: string;+ toolsetName: string;+}++export const DEVTOOLS_GROUP_ID = 'devtools-preview-group';++export const DEVTOOLS_GROUP_DETAIL = {+ agents: [+ {+ avatar: '🧭',+ backgroundColor: '#E8F3FF',+ id: 'researcher-agent',+ title: 'Researcher',+ },+ {+ avatar: '🛠',+ backgroundColor: '#FFF3E8',+ id: 'builder-agent',+ title: 'Builder',+ },+ ],+ avatar: '👥',+ backgroundColor: '#EEF2FF',+ description: 'Fixture group used by /devtools to preview grouped task renders.',+ id: DEVTOOLS_GROUP_ID,+ title: 'Devtools Preview Group',+};++const toolsetModules: ToolsetFixtureModule[] = [+ claudeCode,+ codex,+ github,+ lobeActivator,+ lobeAgentBuilder,+ lobeAgentDocuments,+ lobeAgentManagement,+ lobeCloudSandbox,+ lobeGroupAgentBuilder,+ lobeGroupManagement,+ lobeGtd,+ lobeKnowledgeBase,+ lobeLocalSystem,+ lobeNotebook,+ lobePageAgent,+ lobeSkillStore,+ lobeSkills,+ lobeUserInteraction,+ lobeUserMemory,+ lobeWebBrowsing,+ lobeWebOnboarding,+];++const fixtureRegistry = new Map<string, ToolRenderFixture>();+const customToolsets = new Map<string, ToolsetFixtureModule>();++for (const toolset of toolsetModules) {+ customToolsets.set(toolset.identifier, toolset);+ for (const [apiName, fixture] of Object.entries(toolset.fixtures)) {+ fixtureRegistry.set(`${toolset.identifier}:${apiName}`, fixture);+ }+}++const manifestByIdentifier = new Map<string, BuiltinToolManifest>(+ builtinTools.map((tool) => [tool.identifier, tool.manifest]),+);++export const getToolRenderFixture = (+ identifier: string,+ apiName: string,+ api?: LobeChatPluginApi,+): ToolRenderFixture => {+ const fixture = fixtureRegistry.get(`${identifier}:${apiName}`);+ if (fixture) return fixture;++ return single({+ args: buildSchemaSample(api?.parameters, apiName) || {},+ });+};++export const getToolRenderMeta = (identifier: string, apiName: string): ToolRenderMeta => {+ const manifest = manifestByIdentifier.get(identifier);+ const api = manifest?.api.find((item) => item.name === apiName);+ const customToolset = customToolsets.get(identifier);+ const customApi = customToolset?.apiList?.find((item) => item.name === apiName);++ return {+ api,+ apiName,+ description: api?.description || customApi?.description,+ identifier,+ toolsetDescription: manifest?.meta.description || customToolset?.meta?.description,+ toolsetName: manifest?.meta.title || customToolset?.meta?.title || humanize(identifier),+ };+};diff --git a/src/features/DevPanel/RenderGallery/fixtures/lobe-activator.ts b/src/features/DevPanel/RenderGallery/fixtures/lobe-activator.tsnew file mode 100644index 00000000000..9270e4e8ad0--- /dev/null+++ b/src/features/DevPanel/RenderGallery/fixtures/lobe-activator.ts@@ -0,0 +1,17 @@+'use client';++import { defineFixtures, single } from './_helpers';++export default defineFixtures({+ identifier: 'lobe-activator',+ fixtures: {+ activateSkill: single({+ content:+ 'This skill focuses on shipping UI previews fast while keeping the registry easy to extend.',+ pluginState: {+ description: 'A lightweight workflow for building internal preview harnesses.',+ name: 'Preview Builder',+ },+ }),+ },+});diff --git a/src/features/DevPanel/RenderGallery/fixtures/lobe-agent-builder.ts b/src/features/DevPanel/RenderGallery/fixtures/lobe-agent-builder.tsnew file mode 100644index 00000000000..d6fc9f1279d--- /dev/null+++ b/src/features/DevPanel/RenderGallery/fixtures/lobe-agent-builder.ts@@ -0,0 +1,90 @@+'use client';++import { defineFixtures, single } from './_helpers';++export default defineFixtures({+ identifier: 'lobe-agent-builder',+ fixtures: {+ getAvailableModels: single({+ pluginState: {+ providers: [+ {+ id: 'openai',+ models: [+ { abilities: { functionCall: true, reasoning: true, vision: true }, id: 'gpt-5.4' },+ { abilities: { functionCall: true }, id: 'gpt-5.4-mini' },+ ],+ name: 'OpenAI',+ },+ {+ id: 'anthropic',+ models: [{ abilities: { functionCall: true, vision: true }, id: 'claude-sonnet-4' }],+ name: 'Anthropic',+ },+ ],+ },+ }),+ installPlugin: single({+ pluginState: {+ awaitingApproval: false,+ installed: true,+ pluginId: 'lobe-web-browsing',+ pluginName: 'Web Browsing',+ serverStatus: 'active',+ },+ }),+ searchMarketTools: single({+ pluginState: {+ query: 'browser',+ tools: [+ {+ author: 'LobeHub',+ description: 'Search and crawl web pages with configurable engines.',+ icon: '🌐',+ identifier: 'lobe-web-browsing',+ installed: true,+ name: 'Web Browsing',+ tags: ['search', 'crawl'],+ },+ {+ author: 'LobeHub',+ description: 'Run code and inspect local files inside a sandbox.',+ icon: '🧪',+ identifier: 'lobe-cloud-sandbox',+ installed: false,+ name: 'Cloud Sandbox',+ tags: ['files', 'code'],+ },+ ],+ totalCount: 2,+ },+ }),+ updateAgentConfig: single({+ pluginState: {+ config: {+ newValues: { model: 'gpt-5.4', temperature: 0.4 },+ previousValues: { model: 'gpt-5.4-mini', temperature: 0.7 },+ updatedFields: ['model', 'temperature'],+ },+ meta: {+ newValues: {+ description: 'Pairs on internal developer workflows.',+ title: 'Devtools Copilot',+ },+ previousValues: { description: 'General helper.', title: 'Workspace Helper' },+ updatedFields: ['title', 'description'],+ },+ togglePlugin: {+ enabled: true,+ pluginId: 'lobe-web-browsing',+ },+ },+ }),+ updatePrompt: single({+ pluginState: {+ newPrompt:+ 'Be concise, keep teammates unblocked, and prefer reusable preview infrastructure over one-off screenshots.',+ },+ }),+ },+});diff --git a/src/features/DevPanel/RenderGallery/fixtures/lobe-agent-documents.ts b/src/features/DevPanel/RenderGallery/fixtures/lobe-agent-documents.tsnew file mode 100644index 00000000000..0f04b0026d1--- /dev/null+++ b/src/features/DevPanel/RenderGallery/fixtures/lobe-agent-documents.ts@@ -0,0 +1,19 @@+'use client';++import { defineFixtures, single } from './_helpers';++export default defineFixtures({+ identifier: 'lobe-agent-documents',+ fixtures: {+ createDocument: single({+ args: {+ content:+ '# Devtools Preview Plan\n\n- Enumerate every render.\n- Provide a stable sample fixture.\n- Keep the page development-only.',+ title: 'Devtools Preview Plan',+ },+ pluginState: {+ documentId: 'doc_devtools_preview_plan',+ },+ }),+ },+});diff --git a/src/features/DevPanel/RenderGallery/fixtures/lobe-agent-management.ts b/src/features/DevPanel/RenderGallery/fixtures/lobe-agent-management.tsnew file mode 100644index 00000000000..c28c919fe11--- /dev/null+++ b/src/features/DevPanel/RenderGallery/fixtures/lobe-agent-management.ts@@ -0,0 +1,96 @@+'use client';++import { defineFixtures, single } from './_helpers';++export default defineFixtures({+ identifier: 'lobe-agent-management',+ fixtures: {+ callAgent: single({+ args: {+ instruction:+ 'Review the `/devtools` route and list any preview cards that still need richer fixtures.',+ },+ }),+ createAgent: single({+ args: {+ description: 'Internal helper for preview and QA workflows.',+ model: 'gpt-5.4',+ plugins: ['lobe-web-browsing', 'lobe-local-system'],+ provider: 'openai',+ systemRole: 'You help engineers verify UI changes quickly and carefully.',+ title: 'Preview QA Agent',+ },+ }),+ duplicateAgent: single({+ pluginState: {+ newAgentId: 'agent_preview_clone',+ sourceAgentId: 'agent_workspace_helper',+ success: true,+ },+ }),+ getAgentDetail: single({+ pluginState: {+ config: {+ model: 'gpt-5.4',+ plugins: ['lobe-web-browsing', 'lobe-cloud-sandbox'],+ provider: 'openai',+ systemRole: 'Focus on frontend verification and fast local feedback loops.',+ },+ meta: {+ avatar: '🧪',+ backgroundColor: '#EEF6FF',+ description: 'Specialized in preview harnesses and UI regression checks.',+ tags: ['preview', 'qa'],+ title: 'Preview Specialist',+ },+ },+ }),+ installPlugin: single({+ pluginState: {+ installed: true,+ pluginId: 'lobe-cloud-sandbox',+ pluginName: 'Cloud Sandbox',+ },+ }),+ searchAgent: single({+ pluginState: {+ agents: [+ {+ avatar: '🧪',+ backgroundColor: '#EEF6FF',+ description: 'Preview route and fixture maintainer.',+ id: 'agent_preview_specialist',+ isMarket: false,+ title: 'Preview Specialist',+ },+ {+ avatar: '📚',+ backgroundColor: '#FFF7E8',+ description: 'Keeps internal docs and issue writeups tidy.',+ id: 'agent_doc_partner',+ isMarket: true,+ title: 'Documentation Partner',+ },+ ],+ },+ }),+ updateAgent: single({+ args: {+ config: JSON.stringify({+ model: 'gpt-5.4',+ systemRole: 'Prioritize maintainable developer tooling and preview coverage.',+ }),+ meta: JSON.stringify({+ description: 'Expanded to cover internal tooling previews.',+ title: 'Workspace Preview Partner',+ }),+ },+ }),+ updatePrompt: single({+ args: {+ prompt:+ 'When asked for a visual check, prefer building a reusable preview harness before taking a screenshot.',+ },+ }),+ },+});diff --git a/src/features/DevPanel/RenderGallery/fixtures/lobe-cloud-sandbox.ts b/src/features/DevPanel/RenderGallery/fixtures/lobe-cloud-sandbox.tsnew file mode 100644index 00000000000..8bb64411836--- /dev/null+++ b/src/features/DevPanel/RenderGallery/fixtures/lobe-cloud-sandbox.ts@@ -0,0 +1,148 @@+'use client';++import { defineFixtures, single, variants } from './_helpers';++export default defineFixtures({+ identifier: 'lobe-cloud-sandbox',+ fixtures: {+ editLocalFile: single({+ args: { path: '/sandbox/src/routes/devtools.tsx' },+ pluginState: {+ diffText:+ '--- a/sandbox/src/routes/devtools.tsx\n+++ b/sandbox/src/routes/devtools.tsx\n@@ -1,2 +1,3 @@\n export const devtools = true;\n+export const previews = true;\n',+ linesAdded: 1,+ linesDeleted: 0,+ replacements: 1,+ },+ }),+ executeCode: single({+ args: {+ code: 'const tools = ["todo", "file_change", "command_execution"]; console.log(tools.length);',+ language: 'typescript',+ },+ pluginState: {+ output: '3',+ stderr: '',+ },+ }),+ exportFile: single({+ args: { path: '/sandbox/reports/devtools-preview.html' },+ pluginState: {+ downloadUrl: 'https://example.com/devtools-preview.html',+ filename: 'devtools-preview.html',+ success: true,+ },+ }),+ listLocalFiles: variants([+ {+ args: { directoryPath: '/sandbox/src/routes' },+ label: 'Mixed entries',+ pluginState: {+ files: [+ { isDirectory: true, name: 'agent' },+ { isDirectory: false, name: 'index.tsx', size: 2048 },+ { isDirectory: false, name: 'devtools.tsx', size: 4096 },+ ],+ },+ },+ {+ args: { directoryPath: '/sandbox/empty' },+ label: 'Empty directory',+ pluginState: { files: [] },+ },+ {+ args: { directoryPath: '/sandbox/many' },+ label: 'Many files',+ pluginState: {+ files: Array.from({ length: 24 }, (_, i) => ({+ isDirectory: false,+ name: `report-${i.toString().padStart(2, '0')}.csv`,+ size: 4096 + i * 128,+ })),+ },+ },+ ]),+ moveLocalFiles: single({+ pluginState: {+ results: [+ {+ destination: '/sandbox/archive/devtools-preview.tsx',+ source: '/sandbox/tmp/devtools-preview.tsx',+ success: true,+ },+ ],+ successCount: 1,+ totalCount: 1,+ },+ }),+ readLocalFile: single({+ args: { path: '/sandbox/src/routes/devtools.tsx' },+ pluginState: {+ content: 'export default function Devtools() {\n return <div>Preview</div>;\n}\n',+ endLine: 3,+ startLine: 1,+ totalLines: 3,+ },+ }),+ runCommand: variants([+ {+ args: { command: 'bunx vitest run src/spa/router/desktopRouter.sync.test.tsx' },+ content: '1 passed',+ label: 'Tests pass',+ pluginState: {+ exitCode: 0,+ isBackground: false,+ output: '1 passed',+ stdout: '1 passed',+ success: true,+ },+ },+ {+ args: { command: 'bunx vitest run src/spa/router/desktopRouter.sync.test.tsx' },+ content:+ 'FAIL src/spa/router/desktopRouter.sync.test.tsx > desktop router config sync\n expected route /devtools but received undefined.\n',+ label: 'Test failure',+ pluginState: {+ exitCode: 1,+ isBackground: false,+ output:+ 'FAIL src/spa/router/desktopRouter.sync.test.tsx > desktop router config sync\n expected route /devtools but received undefined.\n',+ stderr:+ 'FAIL src/spa/router/desktopRouter.sync.test.tsx > desktop router config sync\n expected route /devtools but received undefined.\n',+ success: false,+ },+ },+ ]),+ searchLocalFiles: variants([+ {+ args: { directory: '/sandbox/src', keyword: 'devtools' },+ label: 'Two matches',+ pluginState: {+ results: [+ { isDirectory: false, name: 'devtools.tsx', path: '/sandbox/src/routes/devtools.tsx' },+ {+ isDirectory: false,+ name: 'desktopRouter.config.tsx',+ path: '/sandbox/src/spa/router/desktopRouter.config.tsx',+ },+ ],+ totalCount: 2,+ },+ },+ {+ args: { directory: '/sandbox/src', keyword: 'no-such-keyword' },+ label: 'No results',+ pluginState: {+ results: [],+ totalCount: 0,+ },+ },+ ]),+ writeLocalFile: single({+ args: {+ content: 'export const isDevtoolsEnabled = true;\n',+ path: '/sandbox/src/routes/devtools/flags.ts',+ },+ }),+ },+});diff --git a/src/features/DevPanel/RenderGallery/fixtures/lobe-group-agent-builder.ts b/src/features/DevPanel/RenderGallery/fixtures/lobe-group-agent-builder.tsnew file mode 100644index 00000000000..ebab922f185--- /dev/null+++ b/src/features/DevPanel/RenderGallery/fixtures/lobe-group-agent-builder.ts@@ -0,0 +1,43 @@+'use client';++import { defineFixtures, single } from './_helpers';++export default defineFixtures({+ identifier: 'lobe-group-agent-builder',+ fixtures: {+ batchCreateAgents: single({+ args: {+ agents: [+ {+ avatar: '🧪',+ description: 'Checks render output and local screenshots.',+ title: 'Preview QA',+ tools: ['lobe-web-browsing', 'lobe-cloud-sandbox'],+ },+ {+ avatar: '📝',+ description: 'Writes issue notes and rollout summaries.',+ title: 'Docs Writer',+ tools: ['lobe-notebook'],+ },+ ],+ },+ pluginState: {+ agents: [+ { agentId: 'agent_preview_qa', success: true, title: 'Preview QA' },+ { agentId: 'agent_docs_writer', success: true, title: 'Docs Writer' },+ ],+ },+ }),+ updateAgentPrompt: single({+ pluginState: {+ newPrompt: 'Focus on validating preview fixtures and reporting only concrete UI issues.',+ },+ }),+ updateGroupPrompt: single({+ pluginState: {+ newPrompt: 'Coordinate fixture coverage across agents and avoid overlapping work.',+ },+ }),+ },+});diff --git a/src/features/DevPanel/RenderGallery/fixtures/lobe-group-management.ts b/src/features/DevPanel/RenderGallery/fixtures/lobe-group-management.tsnew file mode 100644index 00000000000..9ef68e85952--- /dev/null+++ b/src/features/DevPanel/RenderGallery/fixtures/lobe-group-management.ts@@ -0,0 +1,45 @@+'use client';++import { defineFixtures, single } from './_helpers';++export default defineFixtures({+ identifier: 'lobe-group-management',+ fixtures: {+ broadcast: single({+ args: {+ instruction:+ 'Everyone review one tool render section and flag any empty states that look broken.',+ },+ }),+ executeAgentTask: single({+ args: {+ instruction: 'Verify the `/devtools` route works in desktop development mode.',+ timeout: 1_800_000,+ title: 'Desktop smoke check',+ },+ }),+ executeAgentTasks: single({+ args: {+ tasks: [+ {+ agentId: 'researcher-agent',+ instruction: 'Check which render entries still fall back to empty-state samples.',+ title: 'Fixture audit',+ },+ {+ agentId: 'builder-agent',+ instruction:+ 'Verify router gating and ensure production builds cannot navigate to /devtools.',+ title: 'Route audit',+ },+ ],+ },+ }),+ speak: single({+ args: {+ instruction:+ 'Summarize the preview harness approach in two short sentences for the issue update.',+ },+ }),+ },+});diff --git a/src/features/DevPanel/RenderGallery/fixtures/lobe-gtd.ts b/src/features/DevPanel/RenderGallery/fixtures/lobe-gtd.tsnew file mode 100644index 00000000000..b3402ae58be--- /dev/null+++ b/src/features/DevPanel/RenderGallery/fixtures/lobe-gtd.ts@@ -0,0 +1,112 @@+'use client';++import { defineFixtures, single, variants } from './_helpers';++export default defineFixtures({+ identifier: 'lobe-gtd',+ fixtures: {+ clearTodos: single({+ pluginState: {+ todos: {+ items: [+ { status: 'completed', text: 'Capture real stream data' },+ { status: 'processing', text: 'Build /devtools route' },+ ],+ },+ },+ }),+ createPlan: single({+ pluginState: {+ plan: {+ context:+ 'We want a reusable development-only page that renders every registered builtin tool card with a stable sample fixture.',+ description: 'Create a maintainable preview harness for builtin tool renders.',+ goal: 'Build /devtools render preview',+ id: 'plan_devtools_preview',+ },+ },+ }),+ createTodos: variants([+ {+ label: 'Mixed',+ pluginState: {+ todos: {+ items: [+ { status: 'completed', text: 'Enumerate all render entries' },+ { status: 'processing', text: 'Create preview fixtures' },+ { status: 'todo', text: 'Smoke test the route locally' },+ ],+ },+ },+ },+ {+ label: 'Many todos',+ pluginState: {+ todos: {+ items: Array.from({ length: 10 }, (_, i) => ({+ status: i < 3 ? 'completed' : i < 5 ? 'processing' : 'todo',+ text: `Subtask ${i + 1}: prepare fixtures for batch ${i + 1}`,+ })),+ },+ },+ },+ {+ label: 'All done',+ pluginState: {+ todos: {+ items: [+ { status: 'completed', text: 'Enumerate render entries' },+ { status: 'completed', text: 'Author preview fixtures' },+ { status: 'completed', text: 'Smoke-test the gallery' },+ ],+ },+ },+ },+ ]),+ execTask: single({+ pluginState: {+ task: {+ description: 'Smoke test the desktop router config',+ instruction:+ 'Run the desktop router sync test and confirm /devtools only appears in development.',+ },+ },+ }),+ execTasks: single({+ pluginState: {+ tasks: [+ {+ description: 'Audit builtin render coverage',+ instruction: 'Find any registered render without a usable sample fixture.',+ },+ {+ description: 'Check route gating',+ instruction: 'Make sure production builds do not expose /devtools.',+ },+ ],+ },+ }),+ updatePlan: single({+ pluginState: {+ plan: {+ context:+ 'The route is now in place; expand the preview harness by keeping fixture data next to the page.',+ description: 'Track the follow-up work for richer render fixtures.',+ goal: 'Expand /devtools coverage',+ id: 'plan_devtools_preview',+ },+ },+ }),+ updateTodos: single({+ pluginState: {+ todos: {+ items: [+ { status: 'completed', text: 'Export render registry entries' },+ { status: 'processing', text: 'Hydrate grouped task fixtures' },+ { status: 'todo', text: 'Add richer missing-state cases' },+ ],+ },+ },+ }),+ },+});diff --git a/src/features/DevPanel/RenderGallery/fixtures/lobe-knowledge-base.ts b/src/features/DevPanel/RenderGallery/fixtures/lobe-knowledge-base.tsnew file mode 100644index 00000000000..2fbe75d189d--- /dev/null+++ b/src/features/DevPanel/RenderGallery/fixtures/lobe-knowledge-base.ts@@ -0,0 +1,39 @@+'use client';++import { defineFixtures, single } from './_helpers';++export default defineFixtures({+ identifier: 'lobe-knowledge-base',+ fixtures: {+ readKnowledge: single({+ pluginState: {+ files: [+ {+ fileId: 'kb_devtools_guide',+ filename: 'devtools-preview-guide.md',+ preview:+ 'Use the /devtools route to visually verify builtin tool renders during development.',+ totalCharCount: 1420,+ totalLineCount: 42,+ },+ ],+ },+ }),+ searchKnowledgeBase: single({+ pluginState: {+ fileResults: [+ {+ fileId: 'kb_router_preview',+ fileName: 'router-preview-checklist.md',+ relevanceScore: 0.93,+ },+ {+ fileId: 'kb_tool_fixtures',+ fileName: 'tool-render-fixtures.md',+ relevanceScore: 0.88,+ },+ ],+ },+ }),+ },+});diff --git a/src/features/DevPanel/RenderGallery/fixtures/lobe-local-system.ts b/src/features/DevPanel/RenderGallery/fixtures/lobe-local-system.tsnew file mode 100644index 00000000000..cb4e171d23f--- /dev/null+++ b/src/features/DevPanel/RenderGallery/fixtures/lobe-local-system.ts@@ -0,0 +1,107 @@+'use client';++import { defineFixtures, single, variants } from './_helpers';++export default defineFixtures({+ identifier: 'lobe-local-system',+ fixtures: {+ editLocalFile: single({+ args: { path: '/workspace/src/spa/router/desktopRouter.config.tsx' },+ pluginState: {+ diffText:+ "--- a/workspace/src/spa/router/desktopRouter.config.tsx\n+++ b/workspace/src/spa/router/desktopRouter.config.tsx\n@@ -1,3 +1,7 @@\n export const desktopRoutes = [\n+ {\n+ path: 'devtools',\n+ },\n ];\n",+ },+ }),+ listLocalFiles: single({+ pluginState: {+ files: [+ { isDirectory: true, name: 'src' },+ { isDirectory: false, name: 'package.json', size: 1320 },+ { isDirectory: false, name: 'README.md', size: 4096 },+ ],+ },+ }),+ moveLocalFiles: single({+ args: {+ items: [+ {+ newPath: '/workspace/src/routes/(main)/devtools/index.tsx',+ oldPath: '/workspace/tmp/devtools-preview.tsx',+ },+ ],+ },+ }),+ readLocalFile: single({+ args: { path: '/workspace/src/routes/(main)/devtools/index.tsx' },+ pluginState: {+ content:+ 'export default function DevtoolsPage() {\n return <div>Render preview</div>;\n}\n',+ endLine: 3,+ fullPath: '/workspace/src/routes/(main)/devtools/index.tsx',+ path: 'src/routes/(main)/devtools/index.tsx',+ startLine: 1,+ totalLines: 3,+ },+ }),+ runCommand: single({+ args: { command: 'bun run type-check' },+ content: 'Checked 1247 files in 2.3s\nNo type errors found.',+ pluginState: {+ exitCode: 0,+ isBackground: false,+ output: 'Checked 1247 files in 2.3s\nNo type errors found.',+ stdout: 'Checked 1247 files in 2.3s\nNo type errors found.',+ success: true,+ },+ }),+ searchLocalFiles: variants([+ {+ args: { keywords: 'quarterly report sample' },+ label: 'Multiple matches',+ pluginState: {+ results: [+ {+ isDirectory: false,+ name: 'sample-quarterly-report-q1.xlsx',+ path: '/Users/sample-user/Downloads/sample-quarterly-report-q1.xlsx',+ size: 9_400,+ },+ {+ isDirectory: false,+ name: 'sample_quarterly_report_q2_draft.xlsx',+ path: '/Users/sample-user/Downloads/sample_quarterly_report_q2_draft.xlsx',+ size: 35_600,+ },+ {+ isDirectory: false,+ name: 'sample-quarterly-report-q3.xlsx',+ path: '/Users/sample-user/Documents/reports/sample-quarterly-report-q3.xlsx',+ size: 8_300,+ },+ {+ isDirectory: false,+ name: 'sample-quarterly-report-archived.xlsx',+ path: '/Users/sample-user/Documents/archive/2024/sample-quarterly-report-archived.xlsx',+ size: 16_200,+ },+ ],+ totalCount: 4,+ },+ },+ {+ args: { keywords: 'no-such-keyword-on-disk' },+ label: 'No results',+ pluginState: {+ results: [],+ totalCount: 0,+ },+ },+ ]),+ writeLocalFile: single({+ args: {+ content: 'export const devtoolsEnabled = process.env.NODE_ENV === "development";\n',+ path: '/workspace/src/routes/(main)/devtools/flags.ts',+ },+ }),+ },+});diff --git a/src/features/DevPanel/RenderGallery/fixtures/lobe-notebook.ts b/src/features/DevPanel/RenderGallery/fixtures/lobe-notebook.tsnew file mode 100644index 00000000000..86b6841c227--- /dev/null+++ b/src/features/DevPanel/RenderGallery/fixtures/lobe-notebook.ts@@ -0,0 +1,19 @@+'use client';++import { defineFixtures, single } from './_helpers';++export default defineFixtures({+ identifier: 'lobe-notebook',+ fixtures: {+ createDocument: single({+ pluginState: {+ document: {+ content:+ '# Devtools route\n\nThis page renders every registered builtin tool card with sample fixtures so local QA stays fast.',+ id: 'notebook_devtools_route',+ title: 'Devtools Route Notes',+ },+ },+ }),+ },+});diff --git a/src/features/DevPanel/RenderGallery/fixtures/lobe-page-agent.ts b/src/features/DevPanel/RenderGallery/fixtures/lobe-page-agent.tsnew file mode 100644index 00000000000..1b4fdb7f8d4--- /dev/null+++ b/src/features/DevPanel/RenderGallery/fixtures/lobe-page-agent.ts@@ -0,0 +1,75 @@+'use client';++import { defineFixtures, single } from './_helpers';++export default defineFixtures({+ identifier: 'lobe-page-agent',+ meta: {+ description: 'Page Agent inspector previews for document operations.',+ title: 'Page Agent',+ },+ apiList: [+ {+ description: 'Initialize a new document with markdown content.',+ name: 'initPage',+ },+ {+ description: 'Edit the title of the current document.',+ name: 'editTitle',+ },+ {+ description: 'Read the structured XML content of the page.',+ name: 'getPageContent',+ },+ {+ description: 'Insert, modify, or remove document nodes.',+ name: 'modifyNodes',+ },+ {+ description: 'Find-and-replace text across the document.',+ name: 'replaceText',+ },+ ],+ fixtures: {+ initPage: single({+ args: {+ markdown:+ '# Devtools Render Gallery\n\nA development-only preview surface for every builtin tool render.\n\n- Inspector previews mirror the chat title bar.\n- Body segments switch between Render, Streaming, Placeholder, and Intervention.\n',+ },+ pluginState: { nodeCount: 6 },+ }),+ editTitle: single({+ args: { title: 'Devtools Render Gallery — Builtin Tool Previews' },+ pluginState: { previousTitle: 'Devtools Render Gallery' },+ }),+ getPageContent: single({+ args: {},+ pluginState: { nodeCount: 12 },+ content:+ '<doc><heading id="h-1">Devtools Render Gallery</heading><para id="p-1">Preview every registered builtin tool component.</para></doc>',+ }),+ modifyNodes: single({+ args: {+ operations: [+ { afterId: 'h-1', kind: 'insertAfter', xml: '<para>Updated description.</para>' },+ {+ id: 'p-2',+ kind: 'modify',+ xml: '<para id="p-2">Now mentions Segmented body tabs.</para>',+ },+ { id: 'p-3', kind: 'remove' },+ ],+ },+ pluginState: { applied: 3 },+ }),+ replaceText: single({+ args: {+ isRegex: false,+ newText: 'Body segments',+ replaceAll: true,+ searchText: 'Body section',+ },+ pluginState: { replacements: 2 },+ }),+ },+});diff --git a/src/features/DevPanel/RenderGallery/fixtures/lobe-skill-store.ts b/src/features/DevPanel/RenderGallery/fixtures/lobe-skill-store.tsnew file mode 100644index 00000000000..38210ecc042--- /dev/null+++ b/src/features/DevPanel/RenderGallery/fixtures/lobe-skill-store.ts@@ -0,0 +1,41 @@+'use client';++import { defineFixtures, single } from './_helpers';++export default defineFixtures({+ identifier: 'lobe-skill-store',+ fixtures: {+ importFromMarket: single({+ content: 'preview-builder',+ pluginState: {+ name: 'preview-builder',+ status: 'created',+ success: true,+ },+ }),+ importSkill: single({+ content: 'preview-builder',+ pluginState: {+ name: 'preview-builder',+ status: 'updated',+ success: true,+ },+ }),+ searchSkill: single({+ pluginState: {+ items: [+ {+ category: 'Engineering',+ description: 'Scaffold and maintain internal preview routes for UI checks.',+ identifier: 'preview-builder',+ installCount: 128,+ name: 'Preview Builder',+ repository: 'https://github.com/lobehub/preview-builder',+ summary: 'Reusable preview harness workflows.',+ version: '0.3.1',+ },+ ],+ },+ }),+ },+});diff --git a/src/features/DevPanel/RenderGallery/fixtures/lobe-skills.ts b/src/features/DevPanel/RenderGallery/fixtures/lobe-skills.tsnew file mode 100644index 00000000000..63d98d88e96--- /dev/null+++ b/src/features/DevPanel/RenderGallery/fixtures/lobe-skills.ts@@ -0,0 +1,44 @@+'use client';++import { defineFixtures, single } from './_helpers';++export default defineFixtures({+ identifier: 'lobe-skills',+ fixtures: {+ activateSkill: single({+ content: 'Use a fixture-backed route to preview all builtin tool cards locally.',+ pluginState: {+ description: 'Reusable workflow for internal preview harnesses.',+ name: 'Preview Builder',+ },+ }),+ execScript: single({+ args: { command: 'pnpm lint src/routes/(main)/devtools' },+ content: 'No lint issues found.',+ pluginState: {+ command: 'pnpm lint src/routes/(main)/devtools',+ },+ }),+ readReference: single({+ content:+ 'export const listBuiltinRenderEntries = () => [{ identifier: "codex", apiName: "todo_list" }];\n',+ pluginState: {+ encoding: 'utf-8',+ fullPath: '/workspace/packages/builtin-tools/src/renders.ts',+ path: 'packages/builtin-tools/src/renders.ts',+ size: 2048,+ },+ }),+ runCommand: single({+ args: { command: 'bunx vitest run src/spa/router/desktopRouter.sync.test.tsx' },+ content: '1 passed',+ pluginState: {+ exitCode: 0,+ isBackground: false,+ output: '1 passed',+ stdout: '1 passed',+ success: true,+ },+ }),+ },+});diff --git a/src/features/DevPanel/RenderGallery/fixtures/lobe-user-interaction.ts b/src/features/DevPanel/RenderGallery/fixtures/lobe-user-interaction.tsnew file mode 100644index 00000000000..17beb49dc8a--- /dev/null+++ b/src/features/DevPanel/RenderGallery/fixtures/lobe-user-interaction.ts@@ -0,0 +1,51 @@+'use client';++import { defineFixtures, single } from './_helpers';++export default defineFixtures({+ identifier: 'lobe-user-interaction',+ meta: {+ description: 'User Interaction intervention previews.',+ title: 'User Interaction',+ },+ apiList: [+ {+ description: 'Render an inline question card with form fields.',+ name: 'askUserQuestion',+ },+ ],+ fixtures: {+ askUserQuestion: single({+ args: {+ question: {+ description:+ 'Help us tailor the next reply. Pick the rendering surface you want previewed.',+ fields: [+ {+ key: 'surface',+ kind: 'select',+ label: 'Preview surface',+ options: [+ { label: 'Render', value: 'render' },+ { label: 'Streaming', value: 'streaming' },+ { label: 'Placeholder', value: 'placeholder' },+ { label: 'Intervention', value: 'intervention' },+ ],+ placeholder: 'Choose one',+ required: true,+ },+ {+ key: 'note',+ kind: 'textarea',+ label: 'Optional note',+ placeholder: 'Anything to call out about the preview?',+ },+ ],+ id: 'devtools-preview-question',+ mode: 'form',+ prompt: 'Which builtin tool surface should we focus the next preview iteration on?',+ },+ },+ }),+ },+});diff --git a/src/features/DevPanel/RenderGallery/fixtures/lobe-user-memory.ts b/src/features/DevPanel/RenderGallery/fixtures/lobe-user-memory.tsnew file mode 100644index 00000000000..26861c6864b--- /dev/null+++ b/src/features/DevPanel/RenderGallery/fixtures/lobe-user-memory.ts@@ -0,0 +1,92 @@+'use client';++import { defineFixtures, single, variants } from './_helpers';++export default defineFixtures({+ identifier: 'lobe-user-memory',+ fixtures: {+ addExperienceMemory: single({+ args: {+ details: 'A reusable preview harness saved time compared with manual screenshot stitching.',+ summary: 'Building /devtools made visual QA faster and repeatable.',+ tags: ['devtools', 'preview', 'qa'],+ title: 'Preview harness rollout',+ withExperience: {+ action: 'Built a development-only route backed by stable sample fixtures.',+ keyLearning: 'Reusable preview pages reduce repeated manual validation work.',+ possibleOutcome: 'Future render additions can be checked in one place.',+ reasoning: 'A route-based harness is easier to maintain than ad hoc screenshot scripts.',+ situation: 'We needed to verify many builtin tool cards quickly.',+ },+ },+ }),+ addPreferenceMemory: single({+ args: {+ details: 'Prefer route-based previews for UI verification over isolated screenshots.',+ summary: 'Use reusable local preview routes for internal QA.',+ tags: ['workflow', 'frontend'],+ title: 'Preview workflow preference',+ withPreference: {+ appContext: {+ app: 'LobeHub Desktop',+ feature: 'Builtin tool rendering',+ surface: '/devtools',+ },+ conclusionDirectives:+ 'Keep fixtures close to the route and update them when new renders land.',+ originContext: {+ actor: 'Frontend engineer',+ applicableWhen: 'Adding or refactoring tool renders',+ scenario: 'Need to verify many cards at once',+ trigger: 'A screenshot or local QA request comes in',+ },+ suggestions: ['Add a preview fixture before shipping a new render.'],+ type: 'workflow',+ },+ },+ }),+ searchUserMemory: variants([+ {+ label: 'Has results',+ pluginState: {+ activities: [+ {+ feedback: 'The page made local validation much easier.',+ id: 'activity_devtools',+ narrative: 'Implemented a dev-only /devtools route for builtin render previews.',+ notes: 'Devtools preview route',+ tags: ['preview', 'devtools'],+ type: 'engineering',+ },+ ],+ experiences: [+ {+ action: 'Adopted a route-based preview harness.',+ id: 'experience_devtools',+ keyLearning: 'Stable fixtures are cheaper than repeating manual screenshots.',+ situation: 'Needed to verify many render components in one place.',+ tags: ['render', 'qa'],+ },+ ],+ preferences: [+ {+ conclusionDirectives:+ 'Prefer reusable preview infrastructure for repeated UI checks.',+ id: 'preference_devtools',+ tags: ['workflow'],+ title: 'Preview harness preference',+ },+ ],+ },+ },+ {+ label: 'No results',+ pluginState: {+ activities: [],+ experiences: [],+ preferences: [],+ },+ },+ ]),+ },+});diff --git a/src/features/DevPanel/RenderGallery/fixtures/lobe-web-browsing.ts b/src/features/DevPanel/RenderGallery/fixtures/lobe-web-browsing.tsnew file mode 100644index 00000000000..e9c96d450ca--- /dev/null+++ b/src/features/DevPanel/RenderGallery/fixtures/lobe-web-browsing.ts@@ -0,0 +1,92 @@+'use client';++import { defineFixtures, single, variants } from './_helpers';++export default defineFixtures({+ identifier: 'lobe-web-browsing',+ fixtures: {+ crawlMultiPages: single({+ args: {+ urls: ['https://lobehub.com', 'https://docs.lobehub.com'],+ },+ pluginState: {+ results: [+ {+ crawler: 'firecrawl',+ data: {+ content: 'LobeHub ships desktop and web experiences for AI collaboration.',+ description: 'Product homepage',+ title: 'LobeHub',+ url: 'https://lobehub.com',+ },+ originalUrl: 'https://lobehub.com',+ },+ {+ crawler: 'firecrawl',+ data: {+ content: 'Developer documentation for routing, tooling, and local testing.',+ description: 'Docs homepage',+ title: 'LobeHub Docs',+ url: 'https://docs.lobehub.com',+ },+ originalUrl: 'https://docs.lobehub.com',+ },+ ],+ },+ }),+ crawlSinglePage: single({+ args: { url: 'https://lobehub.com/blog' },+ pluginState: {+ results: [+ {+ crawler: 'firecrawl',+ data: {+ content: 'Recent product updates and engineering notes.',+ description: 'Blog landing page',+ title: 'LobeHub Blog',+ url: 'https://lobehub.com/blog',+ },+ originalUrl: 'https://lobehub.com/blog',+ },+ ],+ },+ }),+ search: variants([+ {+ args: {+ query: 'LobeHub devtools preview route',+ searchEngines: ['google', 'bing'],+ },+ label: 'With results',+ pluginState: {+ query: 'LobeHub devtools preview route',+ results: [+ {+ content: 'Documentation and implementation notes about local preview tooling.',+ engines: ['google'],+ title: 'Preview tooling guide',+ url: 'https://docs.example.com/preview-tooling',+ },+ {+ content: 'Issue thread describing the /devtools route rollout.',+ engines: ['bing'],+ title: 'Builtin render devtools issue',+ url: 'https://linear.example.com/issue/LOBE-8114',+ },+ ],+ },+ },+ {+ args: {+ query: 'undocumented internal preview snapshot harness',+ searchEngines: ['google'],+ },+ label: 'No results',+ pluginState: {+ query: 'undocumented internal preview snapshot harness',+ results: [],+ },+ },+ ]),+ },+});diff --git a/src/features/DevPanel/RenderGallery/fixtures/lobe-web-onboarding.ts b/src/features/DevPanel/RenderGallery/fixtures/lobe-web-onboarding.tsnew file mode 100644index 00000000000..c7603a86abf--- /dev/null+++ b/src/features/DevPanel/RenderGallery/fixtures/lobe-web-onboarding.ts@@ -0,0 +1,28 @@+'use client';++import { defineFixtures, single } from './_helpers';++export default defineFixtures({+ identifier: 'lobe-web-onboarding',+ meta: {+ description: 'Web onboarding intervention previews.',+ title: 'Web Onboarding',+ },+ apiList: [+ {+ description: 'Save the agent identity collected during web onboarding.',+ name: 'saveUserQuestion',+ },+ ],+ fixtures: {+ saveUserQuestion: single({+ args: {+ agentEmoji: '🧪',+ agentName: 'Devtools Tester',+ fullName: 'Arvin',+ interests: ['observability', 'dev-tools', 'agent-runtime'],+ responseLanguage: 'en-US',+ },+ }),+ },+});diff --git a/src/features/DevPanel/RenderGallery/index.tsx b/src/features/DevPanel/RenderGallery/index.tsxindex acafb404cc3..79bd4eb98de 100644--- a/src/features/DevPanel/RenderGallery/index.tsx+++ b/src/features/DevPanel/RenderGallery/index.tsx@@ -7,8 +7,8 @@ import { Outlet, useNavigate, useParams } from 'react-router-dom';import { useAgentGroupStore } from '@/store/agentGroup';+import { DEVTOOLS_GROUP_DETAIL, DEVTOOLS_GROUP_ID } from './fixtures';import Sidebar from './Sidebar';-import { DEVTOOLS_GROUP_DETAIL, DEVTOOLS_GROUP_ID } from './toolRenderFixtures';import { toToolsetPath, useDevtoolsEntries } from './useDevtoolsEntries';const styles = createStaticStyles(({ css, cssVar }) => ({diff --git a/src/features/DevPanel/RenderGallery/lifecycleMode.ts b/src/features/DevPanel/RenderGallery/lifecycleMode.tsnew file mode 100644index 00000000000..a51c419f332--- /dev/null+++ b/src/features/DevPanel/RenderGallery/lifecycleMode.ts@@ -0,0 +1,193 @@+'use client';++/**+ * Lifecycle modes the devtools gallery can swap between, each one shapes the+ * props handed to renderers/inspectors so they preview a specific moment in a+ * tool call's life.+ */+export type LifecycleMode =+ | 'streaming'+ | 'loading'+ | 'success'+ | 'error'+ | 'placeholder'+ | 'intervention';++export const LIFECYCLE_MODES: LifecycleMode[] = [+ 'streaming',+ 'loading',+ 'success',+ 'error',+ 'placeholder',+ 'intervention',+];++export const LIFECYCLE_MODE_LABEL: Record<LifecycleMode, string> = {+ error: 'Error',+ intervention: 'Intervention',+ loading: 'Loading',+ placeholder: 'Placeholder',+ streaming: 'Streaming',+ success: 'Success',+};++export type FixtureBodyKind = 'render' | 'streaming' | 'placeholder' | 'intervention';++/**+ * Map a lifecycle mode to the body slot it targets. Streaming/placeholder/+ * intervention have dedicated component slots; everything else feeds the Render+ * slot with mode-specific props.+ */+export const bodyKindForMode = (mode: LifecycleMode): FixtureBodyKind => {+ switch (mode) {+ case 'streaming': {+ return 'streaming';+ }+ case 'placeholder': {+ return 'placeholder';+ }+ case 'intervention': {+ return 'intervention';+ }+ default: {+ return 'render';+ }+ }+};++export interface ToolRenderFixtureVariant {+ args?: Record<string, unknown>;+ content?: unknown;+ description?: string;+ id: string;+ label: string;+ /** Override the auto-derived partialArgs for streaming mode. */+ partialArgs?: Record<string, unknown>;+ /** Optional override for what to surface in error mode. */+ pluginError?: unknown;+ pluginState?: any;+}++export interface ToolRenderFixture {+ variants: ToolRenderFixtureVariant[];+}++/** Truncate string fields and arrays so streaming mode looks "in progress". */+const derivePartialArgs = (args: Record<string, unknown> | undefined) => {+ if (!args) return {};+ const entries = Object.entries(args);+ if (entries.length === 0) return {};++ // Drop the last field to suggest the model is still typing the next key.+ const visible = entries.length > 1 ? entries.slice(0, -1) : entries;++ return Object.fromEntries(+ visible.map(([key, value]) => {+ if (typeof value === 'string') {+ // Keep half the string so the inspector still has something readable.+ const cutoff = Math.max(8, Math.floor(value.length / 2));+ return [key, value.length > cutoff ? `${value.slice(0, cutoff)}…` : value];+ }+ if (Array.isArray(value)) {+ return [key, value.slice(0, Math.max(1, Math.ceil(value.length / 2)))];+ }+ return [key, value];+ }),+ );+};++/**+ * For error mode, mutate a success-shaped pluginState into a failure shape so+ * inspectors that check `success`/`exitCode`/etc. light up the failure path.+ */+const deriveErrorState = (variant: ToolRenderFixtureVariant) => {+ if (variant.pluginState && typeof variant.pluginState === 'object') {+ return {+ ...variant.pluginState,+ error: 'Devtools simulated error: command failed',+ exitCode: 1,+ success: false,+ };+ }+ return {+ error: 'Devtools simulated error: command failed',+ success: false,+ };+};++const deriveErrorPayload = (variant: ToolRenderFixtureVariant) =>+ variant.pluginError ?? {+ body: 'Devtools simulated error: the underlying executor threw before returning a result.',+ message: 'Tool execution failed',+ type: 'PluginServerError',+ };++export interface DerivedFixtureProps {+ args: Record<string, unknown>;+ content: unknown;+ isArgumentsStreaming: boolean;+ isLoading: boolean;+ partialArgs: Record<string, unknown> | undefined;+ pluginError: unknown;+ pluginState: any;+}++/**+ * Reshape a fixture variant into the props a render/inspector should receive+ * for the given lifecycle mode.+ */+export const deriveFixtureProps = (+ variant: ToolRenderFixtureVariant,+ mode: LifecycleMode,+): DerivedFixtureProps => {+ const args = variant.args ?? {};+ const partial = variant.partialArgs ?? derivePartialArgs(variant.args);++ switch (mode) {+ case 'streaming': {+ return {+ args: partial,+ content: '',+ isArgumentsStreaming: true,+ isLoading: false,+ partialArgs: partial,+ pluginError: undefined,+ pluginState: undefined,+ };+ }+ case 'loading': {+ return {+ args,+ content: '',+ isArgumentsStreaming: false,+ isLoading: true,+ partialArgs: undefined,+ pluginError: undefined,+ pluginState: undefined,+ };+ }+ case 'error': {+ return {+ args,+ content: variant.content ?? '',+ isArgumentsStreaming: false,+ isLoading: false,+ partialArgs: undefined,+ pluginError: deriveErrorPayload(variant),+ pluginState: deriveErrorState(variant),+ };+ }+ // success / placeholder / intervention all get the "completed" props shape.+ default: {+ return {+ args,+ content: variant.content ?? '',+ isArgumentsStreaming: false,+ isLoading: false,+ partialArgs: undefined,+ pluginError: undefined,+ pluginState: variant.pluginState,+ };+ }+ }+};diff --git a/src/features/DevPanel/RenderGallery/toolRenderFixtures.ts b/src/features/DevPanel/RenderGallery/toolRenderFixtures.tsdeleted file mode 100644index 63da430f5a8..00000000000--- a/src/features/DevPanel/RenderGallery/toolRenderFixtures.ts+++ /dev/null@@ -1,1251 +0,0 @@-'use client';--import { ClaudeCodeIdentifier } from '@lobechat/builtin-tool-claude-code/client';-import { builtinTools } from '@lobechat/builtin-tools';-import type { BuiltinRenderProps, BuiltinToolManifest, LobeChatPluginApi } from '@lobechat/types';--export interface ToolRenderFixture extends Partial<- Pick<BuiltinRenderProps, 'args' | 'content' | 'pluginError' | 'pluginState'>-> {}--export interface ToolRenderMeta {- api?: LobeChatPluginApi;- apiName: string;- description?: string;- identifier: string;- toolsetDescription?: string;- toolsetName: string;-}--export const DEVTOOLS_GROUP_ID = 'devtools-preview-group';--export const DEVTOOLS_GROUP_DETAIL = {- agents: [- {- avatar: '🧭',- backgroundColor: '#E8F3FF',- id: 'researcher-agent',- title: 'Researcher',- },- {- avatar: '🛠',- backgroundColor: '#FFF3E8',- id: 'builder-agent',- title: 'Builder',- },- ],- avatar: '👥',- backgroundColor: '#EEF2FF',- description: 'Fixture group used by /devtools to preview grouped task renders.',- id: DEVTOOLS_GROUP_ID,- title: 'Devtools Preview Group',-};--const customToolsets: Record<- string,- {- api: Array<Pick<LobeChatPluginApi, 'description' | 'name'>>;- meta: { description?: string; title: string };- }-> = {- [ClaudeCodeIdentifier]: {- api: [- { description: 'Spawn and summarize a sub-agent task.', name: 'Agent' },- { description: 'Run a shell command.', name: 'Bash' },- { description: 'Patch file contents.', name: 'Edit' },- { description: 'Find files by glob pattern.', name: 'Glob' },- { description: 'Search file contents.', name: 'Grep' },- { description: 'Read file content.', name: 'Read' },- { description: 'Schedule when to resume work.', name: 'ScheduleWakeup' },- { description: 'Run a Claude Code skill.', name: 'Skill' },- { description: 'Read output from a background task.', name: 'TaskOutput' },- { description: 'Stop a background task.', name: 'TaskStop' },- { description: 'Track todo progress.', name: 'TodoWrite' },- { description: 'Look up deferred tools by name or keyword.', name: 'ToolSearch' },- { description: 'Write a new file.', name: 'Write' },- ],- meta: {- description: 'Anthropic Claude Code render previews.',- title: 'Claude Code',- },- },- 'codex': {- api: [- { description: 'Run a shell command in Codex.', name: 'command_execution' },- { description: 'Preview Codex file change summaries.', name: 'file_change' },- { description: 'Preview Codex todo list rendering.', name: 'todo_list' },- ],- meta: {- description: 'Codex-specific render previews and shared command cards.',- title: 'Codex',- },- },- 'lobe-page-agent': {- api: [- { description: 'Initialize a new document with markdown content.', name: 'initPage' },- { description: 'Edit the title of the current document.', name: 'editTitle' },- { description: 'Read the structured XML content of the page.', name: 'getPageContent' },- { description: 'Insert, modify, or remove document nodes.', name: 'modifyNodes' },- { description: 'Find-and-replace text across the document.', name: 'replaceText' },- ],- meta: {- description: 'Page Agent inspector previews for document operations.',- title: 'Page Agent',- },- },- 'lobe-user-interaction': {- api: [- { description: 'Render an inline question card with form fields.', name: 'askUserQuestion' },- ],- meta: {- description: 'User Interaction intervention previews.',- title: 'User Interaction',- },- },- 'lobe-web-onboarding': {- api: [- {- description: 'Save the agent identity collected during web onboarding.',- name: 'saveUserQuestion',- },- ],- meta: {- description: 'Web onboarding intervention previews.',- title: 'Web Onboarding',- },- },-};--const manifestByIdentifier = new Map<string, BuiltinToolManifest>(- builtinTools.map((tool) => [tool.identifier, tool.manifest]),-);--const humanize = (value: string) =>- value- .replaceAll('_', ' ')- .replaceAll(/([a-z0-9])([A-Z])/g, '$1 $2')- .replaceAll(/\s+/g, ' ')- .trim()- .replace(/^./, (char) => char.toUpperCase());--const buildStringSample = (key: string, schema: any) => {- if (schema?.format === 'uri' || key.toLowerCase().includes('url')) return 'https://example.com';- if (key.toLowerCase().includes('path'))- return `/workspace/${key.replace(/Path$/i, '').toLowerCase() || 'file'}.ts`;- if (key.toLowerCase().includes('id')) return `${key}-sample`;- if (key.toLowerCase().includes('query')) return 'tool render preview';- if (key.toLowerCase().includes('title')) return 'Preview title';- if (key.toLowerCase().includes('description')) return 'Preview description';- if (key.toLowerCase().includes('content') || key.toLowerCase().includes('prompt')) {- return `Sample ${humanize(key).toLowerCase()} for the devtools preview.`;- }-- return `${humanize(key)} sample`;-};--const buildSchemaSample = (schema: any, key = 'value'): any => {- if (!schema) return undefined;- if (schema.default !== undefined) return schema.default;- if (schema.example !== undefined) return schema.example;- if (Array.isArray(schema.examples) && schema.examples.length > 0) return schema.examples[0];- if (Array.isArray(schema.enum) && schema.enum.length > 0) return schema.enum[0];-- switch (schema.type) {- case 'array': {- const item = buildSchemaSample(- schema.items,- key.endsWith('s') ? key.slice(0, -1) : `${key}Item`,- );- return item === undefined ? [] : [item];- }- case 'boolean': {- return true;- }- case 'integer':- case 'number': {- return 1;- }- case 'object': {- const properties = schema.properties || {};- return Object.fromEntries(- Object.entries(properties)- .map(([propertyKey, propertySchema]) => [- propertyKey,- buildSchemaSample(propertySchema, propertyKey),- ])- .filter(([, value]) => value !== undefined),- );- }- case 'string':- default: {- return buildStringSample(key, schema);- }- }-};--const keyOf = (identifier: string, apiName: string) => `${identifier}:${apiName}`;--const toolRenderFixtures: Record<string, ToolRenderFixture> = {- [keyOf('codex', 'command_execution')]: {- args: { command: 'bun run type-check' },- content: 'Checked 1247 files in 2.3s\nNo type errors found.',- pluginState: {- exitCode: 0,- isBackground: false,- output: 'Checked 1247 files in 2.3s\nNo type errors found.',- stdout: 'Checked 1247 files in 2.3s\nNo type errors found.',- success: true,- },- },- [keyOf('codex', 'file_change')]: {- args: {- changes: [- {- kind: 'add',- linesAdded: 62,- linesDeleted: 0,- path: 'src/routes/(main)/devtools/index.tsx',- },- {- kind: 'modify',- linesAdded: 23,- linesDeleted: 0,- path: 'packages/builtin-tools/src/renders.ts',- },- {- kind: 'rename',- linesAdded: 28,- linesDeleted: 0,- path: 'tmp/devtools-preview-old.tsx',- },- ],- },- content: 'File changes applied (1 added, 1 modified, 1 renamed).',- pluginState: {- changes: [- {- kind: 'add',- linesAdded: 62,- linesDeleted: 0,- path: 'src/routes/(main)/devtools/index.tsx',- },- {- kind: 'modify',- linesAdded: 23,- linesDeleted: 0,- path: 'packages/builtin-tools/src/renders.ts',- },- {- kind: 'rename',- linesAdded: 28,- linesDeleted: 0,- path: 'tmp/devtools-preview-old.tsx',- },- ],- linesAdded: 113,- linesDeleted: 0,- },- },- [keyOf('codex', 'todo_list')]: {- args: {- items: [- { completed: true, text: 'Wire up the render registry export' },- { completed: false, text: 'Build a devtools preview page' },- { completed: false, text: 'Verify every tool render fixture' },- ],- },- content: 'Todo list updated (1/3 completed).',- },-- [keyOf(ClaudeCodeIdentifier, 'Agent')]: {- args: {- prompt:- 'Inspect the generated preview fixtures and reply with a short note about the riskiest missing case.',- },- content:- '- Search-driven renders still need richer empty-state fixtures.\n- The grouped execute-tasks preview depends on seeded agent-group state.',- },- [keyOf(ClaudeCodeIdentifier, 'Bash')]: {- args: { command: 'rg -n "TodoListRender" packages src' },- content:- 'packages/builtin-tools/src/codex/TodoListRender.tsx:11:const TodoListRender = memo<...>',- pluginState: {- exitCode: 0,- isBackground: false,- output:- 'packages/builtin-tools/src/codex/TodoListRender.tsx:11:const TodoListRender = memo<...>',- stdout:- 'packages/builtin-tools/src/codex/TodoListRender.tsx:11:const TodoListRender = memo<...>',- success: true,- },- },- [keyOf(ClaudeCodeIdentifier, 'Edit')]: {- args: {- file_path: 'src/spa/router/desktopRouter.config.desktop.tsx',- new_string: "path: 'tasks',",- old_string: "path: 'tasks',",- },- },- [keyOf(ClaudeCodeIdentifier, 'Glob')]: {- args: { path: 'src/routes', pattern: '**/index.tsx' },- content: 'src/routes/(main)/agent/index.tsx\nsrc/routes/(main)/devtools/index.tsx',- },- [keyOf(ClaudeCodeIdentifier, 'Grep')]: {- args: { path: 'packages', pattern: 'BuiltinRenderProps', type: 'ts' },- content:- 'packages/types/src/tool/builtin.ts:244:export interface BuiltinRenderProps<Arguments = any, State = any, Content = any> {',- },- [keyOf(ClaudeCodeIdentifier, 'Read')]: {- args: { file_path: 'packages/builtin-tools/src/renders.ts' },- content:- "1 import { RunCommandRender } from '@lobechat/shared-tool-ui/renders';\n2 export interface BuiltinRenderRegistryEntry { ... }",- },- [keyOf(ClaudeCodeIdentifier, 'ScheduleWakeup')]: {- args: {- delaySeconds: 1200,- reason: 'Recheck the failing build once dependencies finish installing.',- },- },- [keyOf(ClaudeCodeIdentifier, 'Skill')]: {- args: { skill: 'codebase-search' },- content: 'Use ripgrep first, then open only the relevant files to keep context sharp.',- },- [keyOf(ClaudeCodeIdentifier, 'TaskOutput')]: {- args: { block: false, task_id: 'task-build-2025-04-25', timeout_ms: 8000 },- content:- '✅ Vite: compile and bundle finished (200) http://localhost:9876/\nDebug Proxy: https://app.lobehub.com/_dangerous_local_dev_proxy?debug-host=http://localhost:9876',- },- [keyOf(ClaudeCodeIdentifier, 'TaskStop')]: {- args: { task_id: 'task-build-2025-04-25' },- content: 'Background task stopped (exit code 0).',- },- [keyOf(ClaudeCodeIdentifier, 'TodoWrite')]: {- args: {- todos: [- {- activeForm: 'Capture current registry coverage',- content: 'Capture current registry coverage',- status: 'completed',- },- {- activeForm: 'Build /devtools page',- content: 'Build /devtools page',- status: 'in_progress',- },- {- activeForm: 'Audit missing fixtures',- content: 'Audit missing fixtures',- status: 'pending',- },- ],- },- },- [keyOf(ClaudeCodeIdentifier, 'ToolSearch')]: {- args: { max_results: 5, query: 'select:Read,Edit,Grep' },- content: 'Loaded 3 deferred tool schemas: Read, Edit, Grep.',- },- [keyOf(ClaudeCodeIdentifier, 'Write')]: {- args: {- content: "export const previewEnabled = process.env.NODE_ENV === 'development';\n",- file_path: 'src/routes/(main)/devtools/featureFlag.ts',- },- },-- [keyOf('lobe-activator', 'activateSkill')]: {- content:- 'This skill focuses on shipping UI previews fast while keeping the registry easy to extend.',- pluginState: {- description: 'A lightweight workflow for building internal preview harnesses.',- name: 'Preview Builder',- },- },-- [keyOf('lobe-agent-builder', 'getAvailableModels')]: {- pluginState: {- providers: [- {- id: 'openai',- models: [- { abilities: { functionCall: true, reasoning: true, vision: true }, id: 'gpt-5.4' },- { abilities: { functionCall: true }, id: 'gpt-5.4-mini' },- ],- name: 'OpenAI',- },- {- id: 'anthropic',- models: [{ abilities: { functionCall: true, vision: true }, id: 'claude-sonnet-4' }],- name: 'Anthropic',- },- ],- },- },- [keyOf('lobe-agent-builder', 'installPlugin')]: {- pluginState: {- awaitingApproval: false,- installed: true,- pluginId: 'lobe-web-browsing',- pluginName: 'Web Browsing',- serverStatus: 'active',- },- },- [keyOf('lobe-agent-builder', 'searchMarketTools')]: {- pluginState: {- query: 'browser',- tools: [- {- author: 'LobeHub',- description: 'Search and crawl web pages with configurable engines.',- icon: '🌐',- identifier: 'lobe-web-browsing',- installed: true,- name: 'Web Browsing',- tags: ['search', 'crawl'],- },- {- author: 'LobeHub',- description: 'Run code and inspect local files inside a sandbox.',- icon: '🧪',- identifier: 'lobe-cloud-sandbox',- installed: false,- name: 'Cloud Sandbox',- tags: ['files', 'code'],- },- ],- totalCount: 2,- },- },- [keyOf('lobe-agent-builder', 'updateAgentConfig')]: {- pluginState: {- config: {- newValues: { model: 'gpt-5.4', temperature: 0.4 },- previousValues: { model: 'gpt-5.4-mini', temperature: 0.7 },- updatedFields: ['model', 'temperature'],- },- meta: {- newValues: {- description: 'Pairs on internal developer workflows.',- title: 'Devtools Copilot',- },- previousValues: { description: 'General helper.', title: 'Workspace Helper' },- updatedFields: ['title', 'description'],- },- togglePlugin: {- enabled: true,- pluginId: 'lobe-web-browsing',- },- },- },- [keyOf('lobe-agent-builder', 'updatePrompt')]: {- pluginState: {- newPrompt:- 'Be concise, keep teammates unblocked, and prefer reusable preview infrastructure over one-off screenshots.',- },- },-- [keyOf('lobe-agent-documents', 'createDocument')]: {- args: {- content:- '# Devtools Preview Plan\n\n- Enumerate every render.\n- Provide a stable sample fixture.\n- Keep the page development-only.',- title: 'Devtools Preview Plan',- },- pluginState: {- documentId: 'doc_devtools_preview_plan',- },- },-- [keyOf('lobe-agent-management', 'callAgent')]: {- args: {- instruction:- 'Review the `/devtools` route and list any preview cards that still need richer fixtures.',- },- },- [keyOf('lobe-agent-management', 'createAgent')]: {- args: {- description: 'Internal helper for preview and QA workflows.',- model: 'gpt-5.4',- plugins: ['lobe-web-browsing', 'lobe-local-system'],- provider: 'openai',- systemRole: 'You help engineers verify UI changes quickly and carefully.',- title: 'Preview QA Agent',- },- },- [keyOf('lobe-agent-management', 'duplicateAgent')]: {- pluginState: {- newAgentId: 'agent_preview_clone',- sourceAgentId: 'agent_workspace_helper',- success: true,- },- },- [keyOf('lobe-agent-management', 'getAgentDetail')]: {- pluginState: {- config: {- model: 'gpt-5.4',- plugins: ['lobe-web-browsing', 'lobe-cloud-sandbox'],- provider: 'openai',- systemRole: 'Focus on frontend verification and fast local feedback loops.',- },- meta: {- avatar: '🧪',- backgroundColor: '#EEF6FF',- description: 'Specialized in preview harnesses and UI regression checks.',- tags: ['preview', 'qa'],- title: 'Preview Specialist',- },- },- },- [keyOf('lobe-agent-management', 'installPlugin')]: {- pluginState: {- installed: true,- pluginId: 'lobe-cloud-sandbox',- pluginName: 'Cloud Sandbox',- },- },- [keyOf('lobe-agent-management', 'searchAgent')]: {- pluginState: {- agents: [- {- avatar: '🧪',- backgroundColor: '#EEF6FF',- description: 'Preview route and fixture maintainer.',- id: 'agent_preview_specialist',- isMarket: false,- title: 'Preview Specialist',- },- {- avatar: '📚',- backgroundColor: '#FFF7E8',- description: 'Keeps internal docs and issue writeups tidy.',- id: 'agent_doc_partner',- isMarket: true,- title: 'Documentation Partner',- },- ],- },- },- [keyOf('lobe-agent-management', 'updateAgent')]: {- args: {- config: JSON.stringify({- model: 'gpt-5.4',- systemRole: 'Prioritize maintainable developer tooling and preview coverage.',- }),- meta: JSON.stringify({- description: 'Expanded to cover internal tooling previews.',- title: 'Workspace Preview Partner',- }),- },- },- [keyOf('lobe-agent-management', 'updatePrompt')]: {- args: {- prompt:- 'When asked for a visual check, prefer building a reusable preview harness before taking a screenshot.',- },- },-- [keyOf('lobe-cloud-sandbox', 'editLocalFile')]: {- args: { path: '/sandbox/src/routes/devtools.tsx' },- pluginState: {- diffText:- '--- a/sandbox/src/routes/devtools.tsx\n+++ b/sandbox/src/routes/devtools.tsx\n@@ -1,2 +1,3 @@\n export const devtools = true;\n+export const previews = true;\n',- linesAdded: 1,- linesDeleted: 0,- replacements: 1,- },- },- [keyOf('lobe-cloud-sandbox', 'executeCode')]: {- args: {- code: 'const tools = ["todo", "file_change", "command_execution"]; console.log(tools.length);',- language: 'typescript',- },- pluginState: {- output: '3',- stderr: '',- },- },- [keyOf('lobe-cloud-sandbox', 'exportFile')]: {- args: { path: '/sandbox/reports/devtools-preview.html' },- pluginState: {- downloadUrl: 'https://example.com/devtools-preview.html',- filename: 'devtools-preview.html',- success: true,- },- },- [keyOf('lobe-cloud-sandbox', 'listLocalFiles')]: {- args: { directoryPath: '/sandbox/src/routes' },- pluginState: {- files: [- { isDirectory: true, name: 'agent' },- { isDirectory: false, name: 'index.tsx', size: 2048 },- { isDirectory: false, name: 'devtools.tsx', size: 4096 },- ],- },- },- [keyOf('lobe-cloud-sandbox', 'moveLocalFiles')]: {- pluginState: {- results: [- {- destination: '/sandbox/archive/devtools-preview.tsx',- source: '/sandbox/tmp/devtools-preview.tsx',- success: true,- },- ],- successCount: 1,- totalCount: 1,- },- },- [keyOf('lobe-cloud-sandbox', 'readLocalFile')]: {- args: { path: '/sandbox/src/routes/devtools.tsx' },- pluginState: {- content: 'export default function Devtools() {\n return <div>Preview</div>;\n}\n',- endLine: 3,- startLine: 1,- totalLines: 3,- },- },- [keyOf('lobe-cloud-sandbox', 'runCommand')]: {- args: { command: 'bunx vitest run src/spa/router/desktopRouter.sync.test.tsx' },- content: '1 passed',- pluginState: {- exitCode: 0,- isBackground: false,- output: '1 passed',- stdout: '1 passed',- success: true,- },- },- [keyOf('lobe-cloud-sandbox', 'searchLocalFiles')]: {- args: { directory: '/sandbox/src', keyword: 'devtools' },- pluginState: {- results: [- { isDirectory: false, name: 'devtools.tsx', path: '/sandbox/src/routes/devtools.tsx' },- {- isDirectory: false,- name: 'desktopRouter.config.tsx',- path: '/sandbox/src/spa/router/desktopRouter.config.tsx',- },- ],- totalCount: 2,- },- },- [keyOf('lobe-cloud-sandbox', 'writeLocalFile')]: {- args: {- content: 'export const isDevtoolsEnabled = true;\n',- path: '/sandbox/src/routes/devtools/flags.ts',- },- },-- [keyOf('lobe-group-agent-builder', 'batchCreateAgents')]: {- args: {- agents: [- {- avatar: '🧪',- description: 'Checks render output and local screenshots.',- title: 'Preview QA',- tools: ['lobe-web-browsing', 'lobe-cloud-sandbox'],- },- {- avatar: '📝',- description: 'Writes issue notes and rollout summaries.',- title: 'Docs Writer',- tools: ['lobe-notebook'],- },- ],- },- pluginState: {- agents: [- { agentId: 'agent_preview_qa', success: true, title: 'Preview QA' },- { agentId: 'agent_docs_writer', success: true, title: 'Docs Writer' },- ],- },- },- [keyOf('lobe-group-agent-builder', 'updateAgentPrompt')]: {- pluginState: {- newPrompt: 'Focus on validating preview fixtures and reporting only concrete UI issues.',- },- },- [keyOf('lobe-group-agent-builder', 'updateGroupPrompt')]: {- pluginState: {- newPrompt: 'Coordinate fixture coverage across agents and avoid overlapping work.',- },- },-- [keyOf('lobe-group-management', 'broadcast')]: {- args: {- instruction:- 'Everyone review one tool render section and flag any empty states that look broken.',- },- },- [keyOf('lobe-group-management', 'executeAgentTask')]: {- args: {- instruction: 'Verify the `/devtools` route works in desktop development mode.',- timeout: 1_800_000,- title: 'Desktop smoke check',- },- },- [keyOf('lobe-group-management', 'executeAgentTasks')]: {- args: {- tasks: [- {- agentId: 'researcher-agent',- instruction: 'Check which render entries still fall back to empty-state samples.',- title: 'Fixture audit',- },- {- agentId: 'builder-agent',- instruction:- 'Verify router gating and ensure production builds cannot navigate to /devtools.',- title: 'Route audit',- },- ],- },- },- [keyOf('lobe-group-management', 'speak')]: {- args: {- instruction:- 'Summarize the preview harness approach in two short sentences for the issue update.',- },- },-- [keyOf('lobe-gtd', 'clearTodos')]: {- pluginState: {- todos: {- items: [- { status: 'completed', text: 'Capture real stream data' },- { status: 'processing', text: 'Build /devtools route' },- ],- },- },- },- [keyOf('lobe-gtd', 'createPlan')]: {- pluginState: {- plan: {- context:- 'We want a reusable development-only page that renders every registered builtin tool card with a stable sample fixture.',- description: 'Create a maintainable preview harness for builtin tool renders.',- goal: 'Build /devtools render preview',- id: 'plan_devtools_preview',- },- },- },- [keyOf('lobe-gtd', 'createTodos')]: {- pluginState: {- todos: {- items: [- { status: 'completed', text: 'Enumerate all render entries' },- { status: 'processing', text: 'Create preview fixtures' },- { status: 'todo', text: 'Smoke test the route locally' },- ],- },- },- },- [keyOf('lobe-gtd', 'execTask')]: {- pluginState: {- task: {- description: 'Smoke test the desktop router config',- instruction:- 'Run the desktop router sync test and confirm /devtools only appears in development.',- },- },- },- [keyOf('lobe-gtd', 'execTasks')]: {- pluginState: {- tasks: [- {- description: 'Audit builtin render coverage',- instruction: 'Find any registered render without a usable sample fixture.',- },- {- description: 'Check route gating',- instruction: 'Make sure production builds do not expose /devtools.',- },- ],- },- },- [keyOf('lobe-gtd', 'updatePlan')]: {- pluginState: {- plan: {- context:- 'The route is now in place; expand the preview harness by keeping fixture data next to the page.',- description: 'Track the follow-up work for richer render fixtures.',- goal: 'Expand /devtools coverage',- id: 'plan_devtools_preview',- },- },- },- [keyOf('lobe-gtd', 'updateTodos')]: {- pluginState: {- todos: {- items: [- { status: 'completed', text: 'Export render registry entries' },- { status: 'processing', text: 'Hydrate grouped task fixtures' },- { status: 'todo', text: 'Add richer missing-state cases' },- ],- },- },- },-- [keyOf('lobe-knowledge-base', 'readKnowledge')]: {- pluginState: {- files: [- {- fileId: 'kb_devtools_guide',- filename: 'devtools-preview-guide.md',- preview:- 'Use the /devtools route to visually verify builtin tool renders during development.',- totalCharCount: 1420,- totalLineCount: 42,- },- ],- },- },- [keyOf('lobe-knowledge-base', 'searchKnowledgeBase')]: {- pluginState: {- fileResults: [- {- fileId: 'kb_router_preview',- fileName: 'router-preview-checklist.md',- relevanceScore: 0.93,- },- {- fileId: 'kb_tool_fixtures',- fileName: 'tool-render-fixtures.md',- relevanceScore: 0.88,- },- ],- },- },-- [keyOf('lobe-local-system', 'editLocalFile')]: {- args: { path: '/workspace/src/spa/router/desktopRouter.config.tsx' },- pluginState: {- diffText:- "--- a/workspace/src/spa/router/desktopRouter.config.tsx\n+++ b/workspace/src/spa/router/desktopRouter.config.tsx\n@@ -1,3 +1,7 @@\n export const desktopRoutes = [\n+ {\n+ path: 'devtools',\n+ },\n ];\n",- },- },- [keyOf('lobe-local-system', 'listLocalFiles')]: {- pluginState: {- files: [- { isDirectory: true, name: 'src' },- { isDirectory: false, name: 'package.json', size: 1320 },- { isDirectory: false, name: 'README.md', size: 4096 },- ],- },- },- [keyOf('lobe-local-system', 'moveLocalFiles')]: {- args: {- items: [- {- newPath: '/workspace/src/routes/(main)/devtools/index.tsx',- oldPath: '/workspace/tmp/devtools-preview.tsx',- },- ],- },- },- [keyOf('lobe-local-system', 'readLocalFile')]: {- args: { path: '/workspace/src/routes/(main)/devtools/index.tsx' },- pluginState: {- content: 'export default function DevtoolsPage() {\n return <div>Render preview</div>;\n}\n',- endLine: 3,- fullPath: '/workspace/src/routes/(main)/devtools/index.tsx',- path: 'src/routes/(main)/devtools/index.tsx',- startLine: 1,- totalLines: 3,- },- },- [keyOf('lobe-local-system', 'runCommand')]: {- args: { command: 'bun run type-check' },- content: 'Checked 1247 files in 2.3s\nNo type errors found.',- pluginState: {- exitCode: 0,- isBackground: false,- output: 'Checked 1247 files in 2.3s\nNo type errors found.',- stdout: 'Checked 1247 files in 2.3s\nNo type errors found.',- success: true,- },- },- [keyOf('lobe-local-system', 'searchLocalFiles')]: {- args: { keywords: 'quarterly report sample' },- pluginState: {- results: [- {- isDirectory: false,- name: 'sample-quarterly-report-q1.xlsx',- path: '/Users/sample-user/Downloads/sample-quarterly-report-q1.xlsx',- size: 9_400,- },- {- isDirectory: false,- name: 'sample_quarterly_report_q2_draft.xlsx',- path: '/Users/sample-user/Downloads/sample_quarterly_report_q2_draft.xlsx',- size: 35_600,- },- {- isDirectory: false,- name: 'sample-quarterly-report-q3.xlsx',- path: '/Users/sample-user/Documents/reports/sample-quarterly-report-q3.xlsx',- size: 8_300,- },- {- isDirectory: false,- name: 'sample-quarterly-report-archived.xlsx',- path: '/Users/sample-user/Documents/archive/2024/sample-quarterly-report-archived.xlsx',- size: 16_200,- },- ],- totalCount: 4,- },- },- [keyOf('lobe-local-system', 'writeLocalFile')]: {- args: {- content: 'export const devtoolsEnabled = process.env.NODE_ENV === "development";\n',- path: '/workspace/src/routes/(main)/devtools/flags.ts',- },- },-- [keyOf('lobe-user-memory', 'addExperienceMemory')]: {- args: {- details: 'A reusable preview harness saved time compared with manual screenshot stitching.',- summary: 'Building /devtools made visual QA faster and repeatable.',- tags: ['devtools', 'preview', 'qa'],- title: 'Preview harness rollout',- withExperience: {- action: 'Built a development-only route backed by stable sample fixtures.',- keyLearning: 'Reusable preview pages reduce repeated manual validation work.',- possibleOutcome: 'Future render additions can be checked in one place.',- reasoning: 'A route-based harness is easier to maintain than ad hoc screenshot scripts.',- situation: 'We needed to verify many builtin tool cards quickly.',- },- },- },- [keyOf('lobe-user-memory', 'addPreferenceMemory')]: {- args: {- details: 'Prefer route-based previews for UI verification over isolated screenshots.',- summary: 'Use reusable local preview routes for internal QA.',- tags: ['workflow', 'frontend'],- title: 'Preview workflow preference',- withPreference: {- appContext: {- app: 'LobeHub Desktop',- feature: 'Builtin tool rendering',- surface: '/devtools',- },- conclusionDirectives:- 'Keep fixtures close to the route and update them when new renders land.',- originContext: {- actor: 'Frontend engineer',- applicableWhen: 'Adding or refactoring tool renders',- scenario: 'Need to verify many cards at once',- trigger: 'A screenshot or local QA request comes in',- },- suggestions: ['Add a preview fixture before shipping a new render.'],- type: 'workflow',- },- },- },- [keyOf('lobe-user-memory', 'searchUserMemory')]: {- pluginState: {- activities: [- {- feedback: 'The page made local validation much easier.',- id: 'activity_devtools',- narrative: 'Implemented a dev-only /devtools route for builtin render previews.',- notes: 'Devtools preview route',- tags: ['preview', 'devtools'],- type: 'engineering',- },- ],- experiences: [- {- action: 'Adopted a route-based preview harness.',- id: 'experience_devtools',- keyLearning: 'Stable fixtures are cheaper than repeating manual screenshots.',- situation: 'Needed to verify many render components in one place.',- tags: ['render', 'qa'],- },- ],- preferences: [- {- conclusionDirectives: 'Prefer reusable preview infrastructure for repeated UI checks.',- id: 'preference_devtools',- tags: ['workflow'],- title: 'Preview harness preference',- },- ],- },- },-- [keyOf('lobe-notebook', 'createDocument')]: {- pluginState: {- document: {- content:- '# Devtools route\n\nThis page renders every registered builtin tool card with sample fixtures so local QA stays fast.',- id: 'notebook_devtools_route',- title: 'Devtools Route Notes',- },- },- },-- [keyOf('lobe-skill-store', 'importFromMarket')]: {- content: 'preview-builder',- pluginState: {- name: 'preview-builder',- status: 'created',- success: true,- },- },- [keyOf('lobe-skill-store', 'importSkill')]: {- content: 'preview-builder',- pluginState: {- name: 'preview-builder',- status: 'updated',- success: true,- },- },- [keyOf('lobe-skill-store', 'searchSkill')]: {- pluginState: {- items: [- {- category: 'Engineering',- description: 'Scaffold and maintain internal preview routes for UI checks.',- identifier: 'preview-builder',- installCount: 128,- name: 'Preview Builder',- repository: 'https://github.com/lobehub/preview-builder',- summary: 'Reusable preview harness workflows.',- version: '0.3.1',- },- ],- },- },-- [keyOf('lobe-skills', 'activateSkill')]: {- content: 'Use a fixture-backed route to preview all builtin tool cards locally.',- pluginState: {- description: 'Reusable workflow for internal preview harnesses.',- name: 'Preview Builder',- },- },- [keyOf('lobe-skills', 'execScript')]: {- args: { command: 'pnpm lint src/routes/(main)/devtools' },- content: 'No lint issues found.',- pluginState: {- command: 'pnpm lint src/routes/(main)/devtools',- },- },- [keyOf('lobe-skills', 'readReference')]: {- content:- 'export const listBuiltinRenderEntries = () => [{ identifier: "codex", apiName: "todo_list" }];\n',- pluginState: {- encoding: 'utf-8',- fullPath: '/workspace/packages/builtin-tools/src/renders.ts',- path: 'packages/builtin-tools/src/renders.ts',- size: 2048,- },- },- [keyOf('lobe-skills', 'runCommand')]: {- args: { command: 'bunx vitest run src/spa/router/desktopRouter.sync.test.tsx' },- content: '1 passed',- pluginState: {- exitCode: 0,- isBackground: false,- output: '1 passed',- stdout: '1 passed',- success: true,- },- },-- [keyOf('lobe-web-browsing', 'crawlMultiPages')]: {- args: {- urls: ['https://lobehub.com', 'https://docs.lobehub.com'],- },- pluginState: {- results: [- {- crawler: 'firecrawl',- data: {- content: 'LobeHub ships desktop and web experiences for AI collaboration.',- description: 'Product homepage',- title: 'LobeHub',- url: 'https://lobehub.com',- },- originalUrl: 'https://lobehub.com',- },- {- crawler: 'firecrawl',- data: {- content: 'Developer documentation for routing, tooling, and local testing.',- description: 'Docs homepage',- title: 'LobeHub Docs',- url: 'https://docs.lobehub.com',- },- originalUrl: 'https://docs.lobehub.com',- },- ],- },- },- [keyOf('lobe-web-browsing', 'crawlSinglePage')]: {- args: { url: 'https://lobehub.com/blog' },- pluginState: {- results: [- {- crawler: 'firecrawl',- data: {- content: 'Recent product updates and engineering notes.',- description: 'Blog landing page',- title: 'LobeHub Blog',- url: 'https://lobehub.com/blog',- },- originalUrl: 'https://lobehub.com/blog',- },- ],- },- },- [keyOf('lobe-web-browsing', 'search')]: {- args: {- query: 'LobeHub devtools preview route',- searchEngines: ['google', 'bing'],- },- pluginState: {- query: 'LobeHub devtools preview route',- results: [- {- content: 'Documentation and implementation notes about local preview tooling.',- engines: ['google'],- title: 'Preview tooling guide',- url: 'https://docs.example.com/preview-tooling',- },- {- content: 'Issue thread describing the /devtools route rollout.',- engines: ['bing'],- title: 'Builtin render devtools issue',- url: 'https://linear.example.com/issue/LOBE-8114',- },- ],- },- },-- [keyOf('lobe-page-agent', 'initPage')]: {- args: {- markdown:- '# Devtools Render Gallery\n\nA development-only preview surface for every builtin tool render.\n\n- Inspector previews mirror the chat title bar.\n- Body segments switch between Render, Streaming, Placeholder, and Intervention.\n',- },- pluginState: { nodeCount: 6 },- },- [keyOf('lobe-page-agent', 'editTitle')]: {- args: { title: 'Devtools Render Gallery — Builtin Tool Previews' },- pluginState: { previousTitle: 'Devtools Render Gallery' },- },- [keyOf('lobe-page-agent', 'getPageContent')]: {- args: {},- pluginState: { nodeCount: 12 },- content:- '<doc><heading id="h-1">Devtools Render Gallery</heading><para id="p-1">Preview every registered builtin tool component.</para></doc>',- },- [keyOf('lobe-page-agent', 'modifyNodes')]: {- args: {- operations: [- { afterId: 'h-1', kind: 'insertAfter', xml: '<para>Updated description.</para>' },- {- id: 'p-2',- kind: 'modify',- xml: '<para id="p-2">Now mentions Segmented body tabs.</para>',- },- { id: 'p-3', kind: 'remove' },- ],- },- pluginState: { applied: 3 },- },- [keyOf('lobe-page-agent', 'replaceText')]: {- args: {- isRegex: false,- newText: 'Body segments',- replaceAll: true,- searchText: 'Body section',- },- pluginState: { replacements: 2 },- },-- [keyOf('lobe-user-interaction', 'askUserQuestion')]: {- args: {- question: {- description:- 'Help us tailor the next reply. Pick the rendering surface you want previewed.',- fields: [- {- key: 'surface',- kind: 'select',- label: 'Preview surface',- options: [- { label: 'Render', value: 'render' },- { label: 'Streaming', value: 'streaming' },- { label: 'Placeholder', value: 'placeholder' },- { label: 'Intervention', value: 'intervention' },- ],- placeholder: 'Choose one',- required: true,- },- {- key: 'note',- kind: 'textarea',- label: 'Optional note',- placeholder: 'Anything to call out about the preview?',- },- ],- id: 'devtools-preview-question',- mode: 'form',- prompt: 'Which builtin tool surface should we focus the next preview iteration on?',- },- },- },-- [keyOf('lobe-web-onboarding', 'saveUserQuestion')]: {- args: {- agentEmoji: '🧪',- agentName: 'Devtools Tester',- fullName: 'Arvin',- interests: ['observability', 'dev-tools', 'agent-runtime'],- responseLanguage: 'en-US',- },- },-- [keyOf('github', 'run_command')]: {- args: {- command: 'gh api /repos/lobehub/lobe-chat/issues?state=open',- },- pluginState: {- command: 'gh api /repos/lobehub/lobe-chat/issues?state=open',- exitCode: 0,- success: true,- },- },-};--export const getToolRenderFixture = (- identifier: string,- apiName: string,- api?: LobeChatPluginApi,-): ToolRenderFixture => {- const fixture = toolRenderFixtures[keyOf(identifier, apiName)];- if (fixture) return fixture;-- return {- args: buildSchemaSample(api?.parameters, apiName) || {},- content: '',- pluginState: undefined,- };-};--export const getToolRenderMeta = (identifier: string, apiName: string): ToolRenderMeta => {- const manifest = manifestByIdentifier.get(identifier);- const api = manifest?.api.find((item) => item.name === apiName);- const customToolset = customToolsets[identifier];- const customApi = customToolset?.api.find((item) => item.name === apiName);-- return {- api,- apiName,- description: api?.description || customApi?.description,- identifier,- toolsetDescription: manifest?.meta.description || customToolset?.meta.description,- toolsetName: manifest?.meta.title || customToolset?.meta.title || humanize(identifier),- };-};diff --git a/src/features/DevPanel/RenderGallery/useDevtoolsEntries.ts b/src/features/DevPanel/RenderGallery/useDevtoolsEntries.tsindex 237f3fb2535..2aa108658f9 100644--- a/src/features/DevPanel/RenderGallery/useDevtoolsEntries.ts+++ b/src/features/DevPanel/RenderGallery/useDevtoolsEntries.ts@@ -15,11 +15,7 @@ import type {import type { MenuProps } from '@lobehub/ui';import { useMemo } from 'react';-import {- getToolRenderFixture,- getToolRenderMeta,- type ToolRenderFixture,-} from './toolRenderFixtures';+import { getToolRenderFixture, getToolRenderMeta, type ToolRenderFixture } from './fixtures';export interface ApiEntry {apiName: string;diff --git a/src/hooks/useLocalStorageState.ts b/src/hooks/useLocalStorageState.tsnew file mode 100644index 00000000000..404b40b2846--- /dev/null+++ b/src/hooks/useLocalStorageState.ts@@ -0,0 +1,53 @@+import { useCallback, useEffect, useState } from 'react';++/**+ * Persist a small piece of UI state in `window.localStorage`.+ *+ * - SSR-safe: defers the read until after mount so the server and first client+ * render agree, then hydrates from storage in an effect.+ * - Cross-instance sync: subscribes to `storage` events so multiple panes /+ * windows that mount the same key stay aligned.+ */+export const useLocalStorageState = <T>(+ key: string,+ defaultValue: T,+): [T, (next: T | ((prev: T) => T)) => void] => {+ const [value, setValue] = useState<T>(defaultValue);++ useEffect(() => {+ try {+ const raw = window.localStorage.getItem(key);+ if (raw !== null) setValue(JSON.parse(raw) as T);+ } catch {+ // ignore parse / access failures (private mode, quota, malformed JSON)+ }++ const onStorage = (event: StorageEvent) => {+ if (event.key !== key || event.newValue === null) return;+ try {+ setValue(JSON.parse(event.newValue) as T);+ } catch {+ // ignore+ }+ };+ window.addEventListener('storage', onStorage);+ return () => window.removeEventListener('storage', onStorage);+ }, [key]);++ const update = useCallback(+ (next: T | ((prev: T) => T)) => {+ setValue((prev) => {+ const resolved = typeof next === 'function' ? (next as (p: T) => T)(prev) : next;+ try {+ window.localStorage.setItem(key, JSON.stringify(resolved));+ } catch {+ // ignore write failures+ }+ return resolved;+ });+ },+ [key],+ );++ return [value, update];+};diff --git a/src/locales/default/chat.ts b/src/locales/default/chat.tsindex 0aca4437665..7684dd8530d 100644--- a/src/locales/default/chat.ts+++ b/src/locales/default/chat.ts@@ -914,13 +914,23 @@ export default {'workingPanel.resources.viewMode.list': 'List view','workingPanel.resources.viewMode.tree': 'Tree view','workingPanel.review.binary': 'Binary file — diff not shown',+ 'workingPanel.review.collapseAll': 'Collapse all',+ 'workingPanel.review.copied': 'Path copied',+ 'workingPanel.review.copyPath': 'Copy file path','workingPanel.review.empty': 'No working tree changes','workingPanel.review.error': "Couldn't load this file's diff",+ 'workingPanel.review.expandAll': 'Expand all',+ 'workingPanel.review.more': 'More options',+ 'workingPanel.review.refresh': 'Refresh',+ 'workingPanel.review.textDiff.disable': 'Disable inline text diff',+ 'workingPanel.review.textDiff.enable': 'Enable inline text diff','workingPanel.review.title': 'Review','workingPanel.review.tooLarge': 'File is too large to diff inline','workingPanel.review.unstaged': 'Unstaged','workingPanel.review.viewMode.split': 'Switch to split view','workingPanel.review.viewMode.unified': 'Switch to unified view',+ 'workingPanel.review.wordWrap.disable': 'Disable word wrap',+ 'workingPanel.review.wordWrap.enable': 'Enable word wrap','workingPanel.space': 'Space','workingPanel.documents.close': 'Close','workingPanel.documents.error': 'Failed to load document',diff --git a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Review/FileItem.tsx b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Review/FileItem.tsxindex 6d4cdb86305..de86d0ec69b 100644--- a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Review/FileItem.tsx+++ b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Review/FileItem.tsx@@ -1,16 +1,35 @@'use client';import type { GitFileDiffStatus } from '@lobechat/electron-client-ipc';-import { PatchDiff } from '@lobehub/ui';+import { ActionIcon, copyToClipboard, PatchDiff } from '@lobehub/ui';import { createStaticStyles } from 'antd-style';+import { CopyIcon } from 'lucide-react';import path from 'path-browserify-esm';-import { memo } from 'react';+import { memo, type MouseEvent, useCallback } from 'react';import { useTranslation } from 'react-i18next';+import { message } from '@/components/AntdStaticMethods';+const styles = createStaticStyles(({ css, cssVar }) => ({additions: css`color: ${cssVar.colorSuccess};`,+ // Copy button stays hidden until the row is hovered so it doesn't add+ // visual noise to the long file list. Mirrors GitHub's "Files changed".+ copy: css`+ flex: none;+ color: ${cssVar.colorTextTertiary};+ opacity: 0;+ transition: opacity 0.15s;++ &:focus-visible {+ opacity: 1;+ }++ .ant-collapse-header:hover & {+ opacity: 1;+ }+ `,deletions: css`color: ${cssVar.colorError};`,@@ -19,9 +38,30 @@ const styles = createStaticStyles(({ css, cssVar }) => ({color: ${cssVar.colorTextTertiary};text-align: center;`,+ dir: css`+ direction: rtl;++ /* Only the directory portion shrinks + head-truncates. Short dirs+ sit naturally next to the filename (no awkward right-alignment);+ long dirs collapse leading segments into "…" via the RTL trick. */+ overflow: hidden;+ flex: 0 1 auto;++ min-width: 0;++ color: ${cssVar.colorTextTertiary};+ text-align: start;+ text-overflow: ellipsis;+ white-space: nowrap;+ `,+ fileName: css`+ flex: none;+ color: ${cssVar.colorText};+ white-space: nowrap;+ `,header: css`display: flex;- gap: 12px;+ gap: 8px;align-items: center;width: 100%;@@ -29,13 +69,15 @@ const styles = createStaticStyles(({ css, cssVar }) => ({font-size: 12px;`,- path: css`+ pathWrapper: css`overflow: hidden;- flex: 1;- color: ${cssVar.colorText};- text-overflow: ellipsis;- white-space: nowrap;+ /* Shrink-only (no grow): short paths stay content-sized so stats sit+ right after the filename; long paths still shrink so the dir part+ can head-truncate. */+ display: flex;+ flex: 0 1 auto;+ min-width: 0;`,stats: css`flex: none;@@ -55,16 +97,46 @@ interface FileItemHeaderProps {}export const FileItemHeader = memo<FileItemHeaderProps>(({ filePath, additions, deletions }) => {+ const { t } = useTranslation('chat');++ const lastSlash = filePath.lastIndexOf('/');+ const dir = lastSlash >= 0 ? filePath.slice(0, lastSlash + 1) : '';+ const fileName = lastSlash >= 0 ? filePath.slice(lastSlash + 1) : filePath;++ const handleCopy = useCallback(+ async (event: MouseEvent<HTMLDivElement>) => {+ // Stop propagation so the row doesn't toggle expand on copy click.+ event.stopPropagation();+ await copyToClipboard(filePath);+ message.success(t('workingPanel.review.copied'));+ },+ [filePath, t],+ );+return (<span className={styles.header}>- <span className={styles.path} title={filePath}>- {filePath}+ <span className={styles.pathWrapper} title={filePath}>+ {dir && (+ // bdi keeps the dir's visual order LTR while the span is+ // direction: rtl for head-side truncation of leading segments.+ <span className={styles.dir}>+ <bdi dir={'ltr'}>{dir}</bdi>+ </span>+ )}+ <span className={styles.fileName}>{fileName}</span></span><span className={styles.stats}>{additions > 0 && <span className={styles.additions}>+{additions}</span>}{additions > 0 && deletions > 0 && ' '}{deletions > 0 && <span className={styles.deletions}>-{deletions}</span>}</span>+ <ActionIcon+ className={styles.copy}+ icon={CopyIcon}+ size={'small'}+ title={t('workingPanel.review.copyPath')}+ onClick={handleCopy}+ /></span>);});@@ -77,12 +149,15 @@ interface FileItemBodyProps {filePath: string;isBinary: boolean;patch: string;+ /** Inline word-level diff highlighting; off → plain line-level. */+ textDiff: boolean;truncated: boolean;viewMode: 'unified' | 'split';+ wordWrap: boolean;}const FileItemBody = memo<FileItemBodyProps>(- ({ filePath, patch, isBinary, truncated, expanded, viewMode }) => {+ ({ filePath, patch, isBinary, truncated, expanded, viewMode, wordWrap, textDiff }) => {const { t } = useTranslation('chat');if (!expanded) return null;@@ -102,6 +177,10 @@ const FileItemBody = memo<FileItemBodyProps>(showHeader={false}variant={'borderless'}viewMode={viewMode}+ diffOptions={{+ lineDiffType: textDiff ? 'word-alt' : 'none',+ overflow: wordWrap ? 'wrap' : 'scroll',+ }}/>);},diff --git a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Review/index.tsx b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Review/index.tsxindex 3c6d26b5458..6cb442a85ca 100644--- a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Review/index.tsx+++ b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Review/index.tsx@@ -1,21 +1,33 @@'use client';import { ActionIcon, Center, Collapse, Empty, Flexbox } from '@lobehub/ui';-import { Spin } from 'antd';+import { Dropdown, type MenuProps, Spin } from 'antd';import { createStaticStyles } from 'antd-style';import {ChevronDownIcon,ChevronRightIcon,Columns2Icon,+ FoldVerticalIcon,GitCompareIcon,+ MoreHorizontalIcon,+ RefreshCwIcon,Rows2Icon,+ UnfoldVerticalIcon,+ WholeWordIcon,+ WrapTextIcon,} from 'lucide-react';import { memo, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';+import { useLocalStorageState } from '@/hooks/useLocalStorageState';+import FileItemBody, { FileItemHeader } from './FileItem';import { useWorkingTreePatches } from './useWorkingTreePatches';+const WORD_WRAP_STORAGE_KEY = 'lobechat-review-word-wrap';+const TEXT_DIFF_STORAGE_KEY = 'lobechat-review-text-diff';+const VIEW_MODE_STORAGE_KEY = 'lobechat-review-view-mode';+interface ReviewProps {workingDirectory: string;}@@ -44,6 +56,47 @@ const styles = createStaticStyles(({ css, cssVar }) => ({background: ${cssVar.colorFillTertiary};`,+ totalAdditions: css`+ color: ${cssVar.colorSuccess};+ `,+ totalDeletions: css`+ color: ${cssVar.colorError};+ `,+ totalStats: css`+ display: inline-flex;+ gap: 6px;+ align-items: center;++ font-family: ${cssVar.fontFamilyCode};+ font-size: 12px;+ font-variant-numeric: tabular-nums;+ `,+ // Skip layout/paint of off-screen file panels. Each panel still mounts+ // (so React/Shiki state is preserved across scroll), but the browser+ // short-circuits its layout & paint until it scrolls near the viewport.+ // Crucial for repos with many large diffs where ~38+ panels were+ // previously locking the scroll thread on every frame.+ list: css`+ & :where(.ant-collapse-item) {+ content-visibility: auto;+ contain-intrinsic-size: auto 56px;+ }++ /* antd v6 renders the label slot as .ant-collapse-title (was+ .ant-collapse-header-text in v4/v5). When collapsible is 'header'+ (the @lobehub/ui Collapse default), antd applies a (0,4,0) rule+ on .ant-collapse .ant-item .ant-collapsible-header .ant-title+ that locks flex to 0 0 auto — long paths then push stats and+ chevron off-screen instead of triggering ellipsis on .path. Our+ parent-className selector is only (0,3,0), so we !important to win.+ Verified via getComputedStyle on a real row: without !important the+ title resolves to flex: 0 0 auto; with it, flex: 1 1 0%. */+ & .ant-collapse-collapsible-header .ant-collapse-title {+ overflow: hidden !important;+ flex: 1 1 0 !important;+ min-width: 0 !important;+ }+ `,scopeChip: css`display: inline-flex;gap: 6px;@@ -66,11 +119,18 @@ const styles = createStaticStyles(({ css, cssVar }) => ({const Review = memo<ReviewProps>(({ workingDirectory }) => {const { t } = useTranslation('chat');- const { data, isLoading } = useWorkingTreePatches(workingDirectory);+ const { data, isLoading, isValidating, mutate } = useWorkingTreePatches(workingDirectory);// Memo-stabilise the fallback so downstream useMemo deps don't flap on// every render while the SWR result is undefined.const patches = useMemo(() => data?.patches ?? [], [data]);- const [viewMode, setViewMode] = useState<'unified' | 'split'>('unified');+ const [viewMode, setViewMode] = useLocalStorageState<'unified' | 'split'>(+ VIEW_MODE_STORAGE_KEY,+ 'unified',+ );+ const [wordWrap, setWordWrap] = useLocalStorageState<boolean>(WORD_WRAP_STORAGE_KEY, false);+ // pierre/diffs default lineDiffType is 'word-alt' (text-level highlighting on),+ // so we default the persisted toggle to true to preserve current behaviour.+ const [textDiff, setTextDiff] = useLocalStorageState<boolean>(TEXT_DIFF_STORAGE_KEY, true);// Default-expand by patch-size budget: take entries until cumulative patch// bytes exceed DEFAULT_EXPAND_BYTE_BUDGET, capped at DEFAULT_EXPAND_MAX_COUNT.@@ -121,8 +181,10 @@ const Review = memo<ReviewProps>(({ workingDirectory }) => {filePath={entry.filePath}isBinary={entry.isBinary}patch={entry.patch}+ textDiff={textDiff}truncated={entry.truncated}viewMode={viewMode}+ wordWrap={wordWrap}/>),key,@@ -137,27 +199,103 @@ const Review = memo<ReviewProps>(({ workingDirectory }) => {};});+ const allExpanded = patches.length > 0 && activeKeys.length === patches.length;+ const handleToggleAll = () => {+ setActiveKeys(allExpanded ? [] : patches.map(itemKey));+ };++ const totals = patches.reduce(+ (acc, entry) => {+ acc.additions += entry.additions ?? 0;+ acc.deletions += entry.deletions ?? 0;+ return acc;+ },+ { additions: 0, deletions: 0 },+ );++ const moreMenuItems: MenuProps['items'] = [+ {+ icon: <RefreshCwIcon size={14} />,+ key: 'refresh',+ label: t('workingPanel.review.refresh'),+ onClick: () => void mutate(),+ },+ { type: 'divider' },+ {+ icon: <WrapTextIcon size={14} />,+ key: 'wordWrap',+ label: wordWrap+ ? t('workingPanel.review.wordWrap.disable')+ : t('workingPanel.review.wordWrap.enable'),+ onClick: () => setWordWrap((w) => !w),+ },+ {+ icon: <WholeWordIcon size={14} />,+ key: 'textDiff',+ label: textDiff+ ? t('workingPanel.review.textDiff.disable')+ : t('workingPanel.review.textDiff.enable'),+ onClick: () => setTextDiff((v) => !v),+ },+ {+ icon: viewMode === 'unified' ? <Columns2Icon size={14} /> : <Rows2Icon size={14} />,+ key: 'viewMode',+ label:+ viewMode === 'unified'+ ? t('workingPanel.review.viewMode.split')+ : t('workingPanel.review.viewMode.unified'),+ onClick: () => setViewMode((m) => (m === 'unified' ? 'split' : 'unified')),+ },+ ];+return (<Flexbox style={{ overflow: 'hidden' }} width={'100%'}><div className={styles.subheader}>- <span className={styles.scopeChip}>- {t('workingPanel.review.unstaged')}- <span className={styles.count}>{patches.length}</span>- <ChevronDownIcon className={styles.caret} size={12} />- </span>- <ActionIcon- active={viewMode === 'split'}- icon={viewMode === 'unified' ? Columns2Icon : Rows2Icon}- size={'small'}- title={- viewMode === 'unified'- ? t('workingPanel.review.viewMode.split')- : t('workingPanel.review.viewMode.unified')- }- onClick={() => setViewMode((m) => (m === 'unified' ? 'split' : 'unified'))}- />+ <Flexbox horizontal align={'center'} gap={8}>+ <span className={styles.scopeChip}>+ {t('workingPanel.review.unstaged')}+ <span className={styles.count}>{patches.length}</span>+ <ChevronDownIcon className={styles.caret} size={12} />+ </span>+ {(totals.additions > 0 || totals.deletions > 0) && (+ <span className={styles.totalStats}>+ {totals.additions > 0 && (+ <span className={styles.totalAdditions}>+{totals.additions}</span>+ )}+ {totals.deletions > 0 && (+ <span className={styles.totalDeletions}>-{totals.deletions}</span>+ )}+ </span>+ )}+ </Flexbox>+ <Flexbox horizontal align={'center'} gap={2}>+ <ActionIcon+ icon={allExpanded ? FoldVerticalIcon : UnfoldVerticalIcon}+ size={'small'}+ title={+ allExpanded+ ? t('workingPanel.review.collapseAll')+ : t('workingPanel.review.expandAll')+ }+ onClick={handleToggleAll}+ />+ <Dropdown menu={{ items: moreMenuItems }} placement={'bottomRight'} trigger={['click']}>+ <ActionIcon+ icon={MoreHorizontalIcon}+ loading={isValidating}+ size={'small'}+ title={t('workingPanel.review.more')}+ />+ </Dropdown>+ </Flexbox></div>- <Flexbox gap={6} paddingInline={8} style={{ overflow: 'auto' }} width={'100%'}>+ <Flexbox+ className={styles.list}+ gap={6}+ paddingInline={8}+ style={{ overflow: 'auto' }}+ width={'100%'}+ ><CollapseactiveKey={activeKeys}expandIconPlacement={'end'}diff --git a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/index.tsx b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/index.tsxindex 0dce281cf6c..de7e8273201 100644--- a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/index.tsx+++ b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/index.tsx@@ -1,7 +1,7 @@import { ActionIcon, Flexbox, Text } from '@lobehub/ui';import { createStaticStyles } from 'antd-style';import { PanelRightCloseIcon } from 'lucide-react';-import { memo, useState } from 'react';+import { memo } from 'react';import { useTranslation } from 'react-i18next';import { DESKTOP_HEADER_ICON_SMALL_SIZE } from '@/const/layoutTokens';@@ -68,14 +68,15 @@ type Tab = 'review' | 'resources';const AgentWorkingSidebar = memo(() => {const { t } = useTranslation('chat');const toggleRightPanel = useGlobalStore((s) => s.toggleRightPanel);+ const setWorkingSidebarTab = useGlobalStore((s) => s.setWorkingSidebarTab);+ const storedTab = useGlobalStore((s) => s.status.workingSidebarTab);const workingDirectory = useChatStore(topicSelectors.currentTopicWorkingDirectory);const reviewAvailable = !!workingDirectory;// When the topic has a working directory we lead with Review — that's why// the sidebar is open in agent-coding flows. Otherwise no tab strip at all,// we just show the resources view as before.- const [tab, setTab] = useState<Tab>(reviewAvailable ? 'review' : 'resources');- const activeTab: Tab = reviewAvailable ? tab : 'resources';+ const activeTab: Tab = reviewAvailable ? (storedTab ?? 'review') : 'resources';return (<RightPanel stableLayout defaultWidth={360} maxWidth={720} minWidth={300}>@@ -93,14 +94,14 @@ const AgentWorkingSidebar = memo(() => {<buttonclassName={`${styles.tab} ${activeTab === 'resources' ? styles.tabActive : ''}`}type="button"- onClick={() => setTab('resources')}+ onClick={() => setWorkingSidebarTab('resources')}>{t('workingPanel.space')}</button><buttonclassName={`${styles.tab} ${activeTab === 'review' ? styles.tabActive : ''}`}type="button"- onClick={() => setTab('review')}+ onClick={() => setWorkingSidebarTab('review')}>{t('workingPanel.review.title')}</button>diff --git a/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts b/src/store/chat/slices/aiChat/actions/conversationLifecycle.tsindex ef87a45f843..e98d0dafe72 100644--- a/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts+++ b/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts@@ -46,7 +46,6 @@ import {getCompressionCandidateMessageIds,hasRunningCompressionOperation,} from '@/store/chat/utils/compression';-import { getFileStoreState } from '@/store/file/store';import { useGlobalStore } from '@/store/global';import { systemStatusSelectors } from '@/store/global/selectors';import { type StoreSetter } from '@/store/types';@@ -55,7 +54,7 @@ import { useUserMemoryStore } from '@/store/userMemory';import { dbMessageSelectors, displayMessageSelectors, topicSelectors } from '../../../selectors';import { messageMapKey } from '../../../utils/messageMapKey';import { topicMapKey } from '../../../utils/topicMapKey';-import { AI_RUNTIME_OPERATION_TYPES } from '../../operation/types';+import { AI_RUNTIME_OPERATION_TYPES, type QueuedFile } from '../../operation/types';import type { CommandSendOverrides, SingleAgentMentionDirectRoute } from './commandBus';import {hasNonActionContent,@@ -336,6 +335,16 @@ export class ConversationLifecycleActionImpl {.find((op) => op && AI_RUNTIME_OPERATION_TYPES.includes(op.type) && op.status === 'running');if (runningAgentOp) {+ // Snapshot file previews so the tray can render thumbnails AND the+ // resumed sendMessage can rebuild imageList/videoList — by the time+ // we drain, chatUploadFileList has long been cleared.+ const filesPreview: QueuedFile[] = (files ?? []).map((f) => ({+ id: f.id,+ mimeType: f.file?.type ?? '',+ name: f.file?.name ?? f.id,+ url: f.fileUrl || f.base64Url || f.previewUrl || '',+ }));+this.#get().enqueueMessage(currentContextKey,{@@ -343,6 +352,7 @@ export class ConversationLifecycleActionImpl {content: message,editorData: editorData ?? undefined,files: fileIdList,+ filesPreview: filesPreview.length > 0 ? filesPreview : undefined,interruptMode: 'soft',metadata: userMessageMetadata,createdAt: Date.now(),@@ -392,16 +402,18 @@ export class ConversationLifecycleActionImpl {},});- // Construct local media preview for server-mode temporary messages (S3 URL takes priority)- const filesInStore = getFileStoreState().chatUploadFileList;- const tempImages: ChatImageItem[] = filesInStore+ // Construct local media preview for server-mode temporary messages (S3 URL takes priority).+ // Use the captured `files` param (not the global file store) so the optimistic preview+ // also works on the queue-drain path, where chatUploadFileList has already been cleared.+ const filesForPreview = files ?? [];+ const tempImages: ChatImageItem[] = filesForPreview.filter((f) => f.file?.type?.startsWith('image')).map((f) => ({id: f.id,url: f.fileUrl || f.base64Url || f.previewUrl || '',alt: f.file?.name || f.id,}));- const tempVideos: ChatVideoItem[] = filesInStore+ const tempVideos: ChatVideoItem[] = filesForPreview.filter((f) => f.file?.type?.startsWith('video')).map((f) => ({id: f.id,diff --git a/src/store/chat/slices/aiChat/actions/streamingExecutor.ts b/src/store/chat/slices/aiChat/actions/streamingExecutor.tsindex 26fec5c6078..be8de4368d2 100644--- a/src/store/chat/slices/aiChat/actions/streamingExecutor.ts+++ b/src/store/chat/slices/aiChat/actions/streamingExecutor.ts@@ -52,7 +52,7 @@ import {selectActivatedToolIdsFromMessages,selectTodosFromMessages,} from '../../message/selectors/dbMessage';-import { mergeQueuedMessages } from '../../operation/types';+import { mergeQueuedMessages, reconstructUploadFilesFromQueue } from '../../operation/types';const log = debug('lobe-store:streaming-executor');@@ -786,9 +786,16 @@ export class StreamingExecutorActionImpl {const execContext = { ...context };const mergedContent = merged.content;- // Convert file id strings — sendMessage only reads f.id from each item+ // Rebuild UploadFileItem-shaped objects from the queued file previews so+ // sendMessage can both pass file ids to the server AND construct+ // imageList/videoList for the optimistic temp message. Falls back to+ // id-only wrappers if no preview metadata was captured.const mergedFiles =- merged.files.length > 0 ? merged.files.map((id) => ({ id }) as any) : undefined;+ merged.filesPreview.length > 0+ ? reconstructUploadFilesFromQueue(merged.filesPreview)+ : merged.files.length > 0+ ? (merged.files.map((id) => ({ id })) as any)+ : undefined;setTimeout(() => {useChatStorediff --git a/src/store/chat/slices/operation/__tests__/actions.test.ts b/src/store/chat/slices/operation/__tests__/actions.test.tsindex 728a4842f2e..2f959e2b9eb 100644--- a/src/store/chat/slices/operation/__tests__/actions.test.ts+++ b/src/store/chat/slices/operation/__tests__/actions.test.ts@@ -57,6 +57,35 @@ describe('Operation Actions', () => {);expect(merged.editorData?.root.children[2]).toEqual(secondParagraph);});++ it('should flatten file ids and filesPreview snapshots from queued messages', () => {+ const merged = mergeQueuedMessages([+ {+ content: 'first',+ createdAt: 1,+ files: ['f1'],+ filesPreview: [{ id: 'f1', mimeType: 'image/png', name: 'a.png', url: 'blob:1' }],+ id: 'q1',+ interruptMode: 'soft',+ },+ {+ content: 'second',+ createdAt: 2,+ files: ['f2', 'f3'],+ filesPreview: [+ { id: 'f2', mimeType: 'image/jpeg', name: 'b.jpg', url: 'blob:2' },+ { id: 'f3', mimeType: 'application/pdf', name: 'c.pdf', url: 'https://x/c.pdf' },+ ],+ id: 'q2',+ interruptMode: 'soft',+ },+ ]);++ expect(merged.files).toEqual(['f1', 'f2', 'f3']);+ expect(merged.filesPreview).toHaveLength(3);+ expect(merged.filesPreview[0]).toMatchObject({ id: 'f1', name: 'a.png' });+ expect(merged.filesPreview[2]).toMatchObject({ id: 'f3', mimeType: 'application/pdf' });+ });});describe('startOperation', () => {diff --git a/src/store/chat/slices/operation/types.ts b/src/store/chat/slices/operation/types.tsindex be0a8b7be87..bcf0632b1bb 100644--- a/src/store/chat/slices/operation/types.ts+++ b/src/store/chat/slices/operation/types.ts@@ -1,4 +1,4 @@-import type { ConversationContext, MessageMetadata } from '@lobechat/types';+import type { ConversationContext, MessageMetadata, UploadFileItem } from '@lobechat/types';/*** Operation Type Definitions@@ -186,6 +186,41 @@ export interface Operation {type: OperationType; // Operation type}+/**+ * Per-file preview metadata snapshotted at enqueue time so the queue tray can+ * render thumbnails and the resumed sendMessage can rebuild the optimistic+ * imageList/videoList without relying on the global chat upload store (which+ * is cleared as soon as the user submits).+ */+export interface QueuedFile {+ id: string;+ /** MIME type, e.g. `image/png`, `video/mp4`, `application/pdf` */+ mimeType: string;+ name: string;+ /** Preview URL — S3 URL for uploaded files, blob/base64 for in-memory items */+ url: string;+}++/**+ * Rebuild `UploadFileItem`-shaped objects from queued previews so the resumed+ * `sendMessage` can derive imageList/videoList AND so we can repopulate+ * `chatUploadFileList` when the user edits a queued message. The synthesized+ * `File` carries only `name` + `type` (zero bytes) — the consumers we hit only+ * read `file.name`, `file.type`, plus the URL fields we set below.+ *+ * We mirror the snapshotted `url` into both `fileUrl` and `previewUrl`: the+ * optimistic-message path uses the `fileUrl || base64Url || previewUrl` fallback+ * chain, while the desktop chat-input file preview only reads `previewUrl`.+ */+export const reconstructUploadFilesFromQueue = (files: QueuedFile[]): UploadFileItem[] =>+ files.map((f) => ({+ id: f.id,+ file: new File([], f.name, { type: f.mimeType }),+ fileUrl: f.url || undefined,+ previewUrl: f.url || undefined,+ status: 'success',+ }));+/*** Queued message waiting to be injected into agent runtime*/@@ -195,6 +230,8 @@ export interface QueuedMessage {/** Lexical editor JSON state for rich text rendering */editorData?: Record<string, any>;files?: string[];+ /** Snapshot of file previews (id, name, mime, url) for tray rendering and optimistic resume */+ filesPreview?: QueuedFile[];id: string;interruptMode: 'soft' | 'hard';metadata?: MessageMetadata;@@ -208,6 +245,7 @@ export interface MergedQueuedMessage {/** Lexical editor JSON state for rich text rendering */editorData?: Record<string, any>;files: string[];+ filesPreview: QueuedFile[];metadata?: MessageMetadata;}@@ -314,6 +352,7 @@ export const mergeQueuedMessages = (messages: QueuedMessage[]): MergedQueuedMesscontent: sorted.map((m) => m.content).join('\n\n'),editorData: mergeQueuedEditorData(sorted),files: sorted.flatMap((m) => m.files ?? []),+ filesPreview: sorted.flatMap((m) => m.filesPreview ?? []),metadata,};};diff --git a/src/store/global/actions/workspacePane.ts b/src/store/global/actions/workspacePane.tsindex d9ad0d6a655..553348c6de0 100644--- a/src/store/global/actions/workspacePane.ts+++ b/src/store/global/actions/workspacePane.ts@@ -123,6 +123,11 @@ export class GlobalWorkspacePaneActionImpl {this.#get().updateSystemStatus({ showSystemRole }, n('toggleMobileTopic', newValue));};+ setWorkingSidebarTab = (tab: 'resources' | 'review'): void => {+ if (this.#get().status.workingSidebarTab === tab) return;+ this.#get().updateSystemStatus({ workingSidebarTab: tab }, n('setWorkingSidebarTab', tab));+ };+toggleWideScreen = (newValue?: boolean): void => {const noWideScreen =typeof newValue === 'boolean' ? !newValue : !this.#get().status.noWideScreen;diff --git a/src/store/global/initialState.ts b/src/store/global/initialState.tsindex e00304fd743..a98b5684c62 100644--- a/src/store/global/initialState.ts+++ b/src/store/global/initialState.ts@@ -263,6 +263,12 @@ export interface SystemStatus {videoPanelWidth: number;videoTopicPanelWidth?: number;videoTopicViewMode?: 'grid' | 'list';+ /**+ * Active tab inside the agent chat right-side WorkingSidebar.+ * Lifted to global so external triggers (e.g. the diff badge in the input bar)+ * can switch the panel to "review" when revealing the right panel.+ */+ workingSidebarTab?: 'resources' | 'review';zenMode?: boolean;}