Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(agent): add overview-first workspace tabs (#17422)

Inneiecf19dff0443
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index 188c21e4365..af710250f03 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -1547,6 +1547,32 @@
"workingPanel.localFile.preview.render": "Preview",
"workingPanel.localFile.preview.source": "Source",
"workingPanel.localFile.truncated": "File preview truncated to {{limit}} characters",
+ "workingPanel.openMenu.configuration": "Configuration",
+ "workingPanel.openMenu.terminal": "Open Terminal",
+ "workingPanel.openMenu.title": "Open workspace panel",
+ "workingPanel.openMenu.tools": "Tools",
+ "workingPanel.openMenu.workspace": "Workspace",
+ "workingPanel.overview.branch": "Branch",
+ "workingPanel.overview.branch.detached": "Detached HEAD",
+ "workingPanel.overview.changes": "Changes",
+ "workingPanel.overview.changes.clean": "No working tree changes",
+ "workingPanel.overview.changes.files_one": "{{count}} file modified",
+ "workingPanel.overview.changes.files_other": "{{count}} files modified",
+ "workingPanel.overview.empty": "Workspace activity and outputs will appear here as the agent works.",
+ "workingPanel.overview.emptyTitle": "Ready to work",
+ "workingPanel.overview.environment": "Environment",
+ "workingPanel.overview.environmentError": "Could not load the repository status",
+ "workingPanel.overview.execution.device": "Connected device",
+ "workingPanel.overview.execution.local": "This device",
+ "workingPanel.overview.manage": "Manage",
+ "workingPanel.overview.outputs": "Outputs",
+ "workingPanel.overview.resources": "Resources",
+ "workingPanel.overview.resources.desc": "Documents and skills available to this agent",
+ "workingPanel.overview.resources.title": "Agent resources",
+ "workingPanel.overview.title": "Overview",
+ "workingPanel.overview.viewAll": "View all",
+ "workingPanel.overview.workspace.empty": "No workspace selected",
+ "workingPanel.overview.workspace.emptyDesc": "Choose a working directory from the runtime bar",
"workingPanel.progress": "Progress",
"workingPanel.progress.allCompleted": "All tasks completed",
"workingPanel.resources": "Resources",
@@ -1656,6 +1682,13 @@
"workingPanel.skills.section.user": "User skills",
"workingPanel.skills.title": "Skills",
"workingPanel.space": "Space",
+ "workingPanel.tabs.close": "Close tab",
+ "workingPanel.tabs.closeLeft": "Close tabs to the left",
+ "workingPanel.tabs.closeOthers": "Close other tabs",
+ "workingPanel.tabs.closeRight": "Close tabs to the right",
+ "workingPanel.tabs.pin": "Pin tab",
+ "workingPanel.tabs.pinned": "Pinned tab",
+ "workingPanel.tabs.unpin": "Unpin tab",
"workingPanel.title": "Working Panel",
"workingPanel.works.changeType.created": "Created",
"workingPanel.works.changeType.updated": "Updated",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index 50202a2e5f7..b25ac8b00d2 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -1547,6 +1547,32 @@
"workingPanel.localFile.preview.render": "预览",
"workingPanel.localFile.preview.source": "源码",
"workingPanel.localFile.truncated": "文件预览被截断至 {{limit}} 个字符",
+ "workingPanel.openMenu.configuration": "配置",
+ "workingPanel.openMenu.terminal": "打开终端",
+ "workingPanel.openMenu.title": "打开工作区面板",
+ "workingPanel.openMenu.tools": "工具",
+ "workingPanel.openMenu.workspace": "工作区",
+ "workingPanel.overview.branch": "分支",
+ "workingPanel.overview.branch.detached": "游离 HEAD",
+ "workingPanel.overview.changes": "变更",
+ "workingPanel.overview.changes.clean": "工作树没有变更",
+ "workingPanel.overview.changes.files_one": "已修改 {{count}} 个文件",
+ "workingPanel.overview.changes.files_other": "已修改 {{count}} 个文件",
+ "workingPanel.overview.empty": "Agent 开始工作后,工作区活动和产物会显示在这里。",
+ "workingPanel.overview.emptyTitle": "准备就绪",
+ "workingPanel.overview.environment": "环境",
+ "workingPanel.overview.environmentError": "无法加载仓库状态",
+ "workingPanel.overview.execution.device": "已连接设备",
+ "workingPanel.overview.execution.local": "此设备",
+ "workingPanel.overview.manage": "管理",
+ "workingPanel.overview.outputs": "产物",
+ "workingPanel.overview.resources": "资源",
+ "workingPanel.overview.resources.desc": "此 Agent 可用的文档和技能",
+ "workingPanel.overview.resources.title": "Agent 资源",
+ "workingPanel.overview.title": "概览",
+ "workingPanel.overview.viewAll": "查看全部",
+ "workingPanel.overview.workspace.empty": "尚未选择工作区",
+ "workingPanel.overview.workspace.emptyDesc": "请从运行时栏中选择工作目录",
"workingPanel.progress": "进度",
"workingPanel.progress.allCompleted": "所有任务已完成",
"workingPanel.resources": "资源",
@@ -1656,6 +1682,13 @@
"workingPanel.skills.section.user": "用户技能",
"workingPanel.skills.title": "技能",
"workingPanel.space": "空间",
+ "workingPanel.tabs.close": "关闭标签页",
+ "workingPanel.tabs.closeLeft": "关闭左侧标签页",
+ "workingPanel.tabs.closeOthers": "关闭其他标签页",
+ "workingPanel.tabs.closeRight": "关闭右侧标签页",
+ "workingPanel.tabs.pin": "固定标签页",
+ "workingPanel.tabs.pinned": "已固定标签页",
+ "workingPanel.tabs.unpin": "取消固定标签页",
"workingPanel.title": "工作面板",
"workingPanel.works.changeType.created": "已创建",
"workingPanel.works.changeType.updated": "已编辑",
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index 560843f65e2..93f93474033 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -1613,6 +1613,33 @@ export default {
'workingPanel.browser.tool.screenshot': 'Captured screenshot',
'workingPanel.browser.tool.scroll': 'Scrolled page',
'workingPanel.browser.tool.snapshot': 'Read page elements',
+ 'workingPanel.openMenu.configuration': 'Configuration',
+ 'workingPanel.openMenu.terminal': 'Open Terminal',
+ 'workingPanel.openMenu.title': 'Open workspace panel',
+ 'workingPanel.openMenu.tools': 'Tools',
+ 'workingPanel.openMenu.workspace': 'Workspace',
+ 'workingPanel.overview.branch': 'Branch',
+ 'workingPanel.overview.branch.detached': 'Detached HEAD',
+ 'workingPanel.overview.changes': 'Changes',
+ 'workingPanel.overview.changes.clean': 'No working tree changes',
+ 'workingPanel.overview.changes.files_one': '{{count}} file modified',
+ 'workingPanel.overview.changes.files_other': '{{count}} files modified',
+ 'workingPanel.overview.empty':
+ 'Workspace activity and outputs will appear here as the agent works.',
+ 'workingPanel.overview.emptyTitle': 'Ready to work',
+ 'workingPanel.overview.environment': 'Environment',
+ 'workingPanel.overview.environmentError': 'Could not load the repository status',
+ 'workingPanel.overview.execution.device': 'Connected device',
+ 'workingPanel.overview.execution.local': 'This device',
+ 'workingPanel.overview.manage': 'Manage',
+ 'workingPanel.overview.outputs': 'Outputs',
+ 'workingPanel.overview.resources': 'Resources',
+ 'workingPanel.overview.resources.desc': 'Documents and skills available to this agent',
+ 'workingPanel.overview.resources.title': 'Agent resources',
+ 'workingPanel.overview.title': 'Overview',
+ 'workingPanel.overview.viewAll': 'View all',
+ 'workingPanel.overview.workspace.empty': 'No workspace selected',
+ 'workingPanel.overview.workspace.emptyDesc': 'Choose a working directory from the runtime bar',
'workingPanel.progress': 'Progress',
'workingPanel.progress.allCompleted': 'All tasks completed',
'workingPanel.resources': 'Resources',
@@ -1761,6 +1788,13 @@ export default {
'workingPanel.review.wordWrap.disable': 'Disable word wrap',
'workingPanel.review.wordWrap.enable': 'Enable word wrap',
'workingPanel.space': 'Space',
+ 'workingPanel.tabs.close': 'Close tab',
+ 'workingPanel.tabs.closeLeft': 'Close tabs to the left',
+ 'workingPanel.tabs.closeOthers': 'Close other tabs',
+ 'workingPanel.tabs.closeRight': 'Close tabs to the right',
+ 'workingPanel.tabs.pin': 'Pin tab',
+ 'workingPanel.tabs.pinned': 'Pinned tab',
+ 'workingPanel.tabs.unpin': 'Unpin tab',
'workingPanel.documents.close': 'Close',
'workingPanel.documents.error': 'Failed to load document',
'workingPanel.documents.loading': 'Loading document...',
diff --git a/src/features/Work/WorkSummaryCard.tsx b/src/features/Work/WorkSummaryCard.tsx
index 7558117eb28..29a8e7ba86e 100644
--- a/src/features/Work/WorkSummaryCard.tsx
+++ b/src/features/Work/WorkSummaryCard.tsx
@@ -35,6 +35,10 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
flex-shrink: 0;
color: ${cssVar.colorTextTertiary};
`,
+ description: css`
+ min-width: 0;
+ color: ${cssVar.colorTextTertiary};
+ `,
icon: css`
flex-shrink: 0;
@@ -46,10 +50,43 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
background: ${cssVar.colorFillTertiary};
`,
- description: css`
+ inline: css`
+ overflow: hidden;
+
+ width: 100%;
+ padding-block: 8px;
+ padding-inline: 8px;
+ border-radius: 6px;
+
+ transition: background-color 0.12s ease;
+ `,
+ inlineClickable: css`
+ cursor: pointer;
+
+ &:hover {
+ background: ${cssVar.colorFillTertiary};
+ }
+ `,
+ inlineCost: css`
+ flex-shrink: 0;
+ font-family: ${cssVar.fontFamilyCode};
+ font-size: 11px;
+ color: ${cssVar.colorTextTertiary};
+ `,
+ inlineDescription: css`
min-width: 0;
+ font-size: 11px;
color: ${cssVar.colorTextTertiary};
`,
+ inlineIcon: css`
+ flex-shrink: 0;
+ color: ${cssVar.colorTextSecondary};
+ `,
+ inlineTitle: css`
+ min-width: 0;
+ font-size: 13px;
+ font-weight: 500;
+ `,
title: css`
min-width: 0;
font-size: 14px;
@@ -68,96 +105,141 @@ interface WorkSummaryCardProps {
* clickability on external-url presence and task-deleted state.
*/
onOpen?: (item: WorkSummaryItem) => void;
+ /**
+ * `card` (default) renders the elevated 36×36 icon-box layout used across the
+ * chat portal and the works gallery. `inline` renders a flat row (17px icon,
+ * 6px hover fill) for the WorkingSidebar Overview, so a shared card doesn't
+ * dictate the flat sidebar's visual vocabulary.
+ */
+ variant?: 'card' | 'inline';
}
-const WorkSummaryCard = memo<WorkSummaryCardProps>(({ className, item, onOpen }) => {
- const { t } = useTranslation('chat');
- const openDocument = useChatStore((s) => s.openDocument);
- const openTaskDetail = useChatStore((s) => s.openTaskDetail);
- const cost = formatWorkVersionCost(item.totalCost);
-
- const descriptor = getWorkTypeDescriptor(item);
- const Icon = descriptor.getIcon(item);
- const title =
- descriptor.getTitle(item)?.trim() ||
- descriptor.getIdentifier(item) ||
- item.resourceId ||
- item.id;
- const description = descriptor.getDescription(item);
- const openTarget = descriptor.getOpenTarget(item);
- // The backing task was deleted outside the tool path: the Work lingers as an
- // orphan rendered from its snapshot, and opening the gone task detail 404s, so
- // strip the click affordance and surface a "task deleted" badge.
- const taskDeleted = item.resourceType === 'task' && item.taskDeleted;
- const clickable = !!openTarget && !taskDeleted;
-
- const handleOpen = () => {
- if (onOpen) {
- onOpen(item);
- return;
- }
- if (!openTarget) return;
-
- switch (openTarget.kind) {
- case 'document': {
- openDocument(openTarget.documentId, openTarget.agentDocumentId);
- return;
- }
- case 'external': {
- // Defense in depth: only ever hand http(s) to shell.openExternal.
- if (isSafeExternalUrl(openTarget.url))
- window.open(openTarget.url, '_blank', 'noopener,noreferrer');
+const WorkSummaryCard = memo<WorkSummaryCardProps>(
+ ({ className, item, onOpen, variant = 'card' }) => {
+ const { t } = useTranslation('chat');
+ const openDocument = useChatStore((s) => s.openDocument);
+ const openTaskDetail = useChatStore((s) => s.openTaskDetail);
+ const cost = formatWorkVersionCost(item.totalCost);
+
+ const descriptor = getWorkTypeDescriptor(item);
+ const Icon = descriptor.getIcon(item);
+ const title =
+ descriptor.getTitle(item)?.trim() ||
+ descriptor.getIdentifier(item) ||
+ item.resourceId ||
+ item.id;
+ const description = descriptor.getDescription(item);
+ const openTarget = descriptor.getOpenTarget(item);
+ // The backing task was deleted outside the tool path: the Work lingers as an
+ // orphan rendered from its snapshot, and opening the gone task detail 404s, so
+ // strip the click affordance and surface a "task deleted" badge.
+ const taskDeleted = item.resourceType === 'task' && item.taskDeleted;
+ const clickable = !!openTarget && !taskDeleted;
+
+ const handleOpen = () => {
+ if (onOpen) {
+ onOpen(item);
return;
}
- case 'task': {
- openTaskDetail(openTarget.identifier);
+ if (!openTarget) return;
+
+ switch (openTarget.kind) {
+ case 'document': {
+ openDocument(openTarget.documentId, openTarget.agentDocumentId);
+ return;
+ }
+ case 'external': {
+ // Defense in depth: only ever hand http(s) to shell.openExternal.
+ if (isSafeExternalUrl(openTarget.url))
+ window.open(openTarget.url, '_blank', 'noopener,noreferrer');
+ return;
+ }
+ case 'task': {
+ openTaskDetail(openTarget.identifier);
+ }
}
- }
- };
-
- return (
- <Flexbox
- horizontal
- align={'center'}
- className={cx(styles.card, clickable && styles.clickable, className)}
- gap={12}
- onClick={clickable ? handleOpen : undefined}
- >
- <Flexbox align={'center'} className={styles.icon} justify={'center'}>
- <Icon size={18} />
- </Flexbox>
- <Flexbox flex={1} gap={6} style={{ minWidth: 0 }}>
- <Flexbox horizontal align={'center'} gap={8} justify={'space-between'}>
- <Flexbox horizontal align={'center'} gap={8} style={{ minWidth: 0 }}>
- <Text ellipsis className={styles.title}>
- {title}
- </Text>
- {taskDeleted && (
- <Tag color={'warning'} icon={<Trash2Icon size={12} />} size={'small'}>
- {t('workingPanel.works.taskDeleted')}
- </Tag>
+ };
+
+ if (variant === 'inline') {
+ return (
+ <Flexbox
+ horizontal
+ align={'center'}
+ className={cx(styles.inline, clickable && styles.inlineClickable, className)}
+ gap={10}
+ onClick={clickable ? handleOpen : undefined}
+ >
+ <Icon className={styles.inlineIcon} size={17} />
+ <Flexbox flex={1} gap={2} style={{ minWidth: 0 }}>
+ <Flexbox horizontal align={'center'} gap={8} style={{ minWidth: 0 }}>
+ <Text ellipsis className={styles.inlineTitle}>
+ {title}
+ </Text>
+ {taskDeleted && (
+ <Tag color={'warning'} icon={<Trash2Icon size={12} />} size={'small'}>
+ {t('workingPanel.works.taskDeleted')}
+ </Tag>
+ )}
+ </Flexbox>
+ {description && (
+ <Text ellipsis className={styles.inlineDescription}>
+ {description}
+ </Text>
)}
</Flexbox>
{cost && (
- <Text
- code
- className={styles.cost}
- fontSize={12}
- title={t('workingPanel.works.totalCost', { cost })}
- >
+ <span className={styles.inlineCost} title={t('workingPanel.works.totalCost', { cost })}>
{cost}
+ </span>
+ )}
+ </Flexbox>
+ );
+ }
+
+ return (
+ <Flexbox
+ horizontal
+ align={'center'}
+ className={cx(styles.card, clickable && styles.clickable, className)}
+ gap={12}
+ onClick={clickable ? handleOpen : undefined}
+ >
+ <Flexbox align={'center'} className={styles.icon} justify={'center'}>
+ <Icon size={18} />
+ </Flexbox>
+ <Flexbox flex={1} gap={6} style={{ minWidth: 0 }}>
+ <Flexbox horizontal align={'center'} gap={8} justify={'space-between'}>
+ <Flexbox horizontal align={'center'} gap={8} style={{ minWidth: 0 }}>
+ <Text ellipsis className={styles.title}>
+ {title}
+ </Text>
+ {taskDeleted && (
+ <Tag color={'warning'} icon={<Trash2Icon size={12} />} size={'small'}>
+ {t('workingPanel.works.taskDeleted')}
+ </Tag>
+ )}
+ </Flexbox>
+ {cost && (
+ <Text
+ code
+ className={styles.cost}
+ fontSize={12}
+ title={t('workingPanel.works.totalCost', { cost })}
+ >
+ {cost}
+ </Text>
+ )}
+ </Flexbox>
+ {description && (
+ <Text ellipsis className={styles.description} fontSize={13}>
+ {description}
</Text>
)}
</Flexbox>
- {description && (
- <Text ellipsis className={styles.description} fontSize={13}>
- {description}
- </Text>
- )}
</Flexbox>
- </Flexbox>
- );
-});
+ );
+ },
+);
WorkSummaryCard.displayName = 'WorkSummaryCard';
diff --git a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Overview/index.tsx b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Overview/index.tsx
new file mode 100644
index 00000000000..f14bae0a03c
--- /dev/null
+++ b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Overview/index.tsx
@@ -0,0 +1,334 @@
+'use client';
+
+import { Center, Empty, Flexbox, Icon, type IconProps, Skeleton, Tag, Text } from '@lobehub/ui';
+import { Button } from '@lobehub/ui/base-ui';
+import { createStaticStyles, cssVar, cx } from 'antd-style';
+import {
+ BoxesIcon,
+ ChevronRightIcon,
+ ClipboardListIcon,
+ FolderGit2Icon,
+ FolderOpenIcon,
+ GitBranchIcon,
+ LaptopIcon,
+ RefreshCwIcon,
+} from 'lucide-react';
+import { memo, type ReactNode, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { getAllWorkSummaries } from '@/features/Conversation/store/slices/data/workSummaries';
+import WorkSummaryCard from '@/features/Work/WorkSummaryCard';
+import { useChatStore } from '@/store/chat';
+import { dbMessageSelectors } from '@/store/chat/selectors';
+import { useFetchGitAheadBehind, useFetchGitBranch, useReviewPatches } from '@/store/device';
+
+import ProgressSection from '../ProgressSection';
+
+const styles = createStaticStyles(({ css, cssVar }) => ({
+ body: css`
+ overflow-y: auto;
+ padding-block: 8px 12px;
+ padding-inline: 8px 12px;
+ `,
+ changeAdditions: css`
+ font-family: ${cssVar.fontFamilyCode};
+ font-size: 12px;
+ color: ${cssVar.colorSuccess};
+ `,
+ changeDeletions: css`
+ font-family: ${cssVar.fontFamilyCode};
+ font-size: 12px;
+ color: ${cssVar.colorError};
+ `,
+ error: css`
+ min-height: 112px;
+ `,
+ icon: css`
+ flex-shrink: 0;
+ margin-block-start: 1px;
+ color: ${cssVar.colorTextSecondary};
+ `,
+ row: css`
+ cursor: pointer;
+
+ min-height: 40px;
+ padding-block: 8px;
+ padding-inline: 8px;
+ border-radius: 6px;
+
+ transition: background-color 0.12s ease;
+
+ &:hover {
+ background: ${cssVar.colorFillTertiary};
+ }
+ `,
+ rowStatus: css`
+ cursor: default;
+
+ &:hover {
+ background: transparent;
+ }
+ `,
+ rowStatusPrimary: css`
+ font-weight: 400 !important;
+ color: ${cssVar.colorTextSecondary} !important;
+ `,
+ sectionHeader: css`
+ padding-block: 4px 6px;
+ padding-inline: 10px;
+ `,
+ sectionTitle: css`
+ font-size: 10.5px;
+ font-weight: 600;
+ color: ${cssVar.colorTextSecondary};
+ text-transform: uppercase;
+ letter-spacing: 0.08em;
+ `,
+ skeleton: css`
+ padding-block: 4px;
+ padding-inline: 10px;
+ `,
+ stats: css`
+ flex-shrink: 0;
+ `,
+}));
+
+interface OverviewProps {
+ active: boolean;
+ deviceId?: string;
+ onOpenTab: (tab: string) => void;
+ repoType?: string;
+ workingDirectory?: string;
+}
+
+const pathBasename = (path: string) => path.replaceAll('\\', '/').split('/').findLast(Boolean);
+
+const OverviewRowLead = ({ children, icon }: { children: ReactNode; icon: IconProps['icon'] }) => (
+ <Flexbox horizontal align={'flex-start'} flex={1} gap={10} style={{ minWidth: 0 }}>
+ <Icon className={styles.icon} icon={icon} size={17} />
+ {children}
+ </Flexbox>
+);
+
+const Overview = memo<OverviewProps>(
+ ({ active, deviceId, onOpenTab, repoType, workingDirectory }) => {
+ const { t } = useTranslation('chat');
+ const topicId = useChatStore((s) => s.activeTopicId);
+ const threadId = useChatStore((s) => s.activeThreadId);
+ const works = useChatStore((s) =>
+ getAllWorkSummaries(dbMessageSelectors.activeDbMessages(s), threadId),
+ );
+
+ const gitPath = active && repoType ? workingDirectory : undefined;
+ const {
+ data: branchData,
+ error: branchError,
+ isLoading: branchLoading,
+ mutate: mutateBranch,
+ } = useFetchGitBranch(deviceId, gitPath);
+ const {
+ data: aheadBehind,
+ error: aheadBehindError,
+ mutate: mutateAheadBehind,
+ } = useFetchGitAheadBehind(deviceId, gitPath);
+ const {
+ data: reviewData,
+ error: reviewError,
+ isLoading: reviewLoading,
+ mutate: mutateReview,
+ } = useReviewPatches(gitPath, 'unstaged', undefined, deviceId, active);
+
+ const changeStats = useMemo(() => {
+ const patches = [
+ ...(reviewData?.patches ?? []),
+ ...(reviewData?.submodules ?? []).flatMap((submodule) => submodule.patches),
+ ];
+
+ return patches.reduce(
+ (stats, patch) => ({
+ additions: stats.additions + (patch.additions ?? 0),
+ deletions: stats.deletions + (patch.deletions ?? 0),
+ files: stats.files + 1,
+ }),
+ { additions: 0, deletions: 0, files: 0 },
+ );
+ }, [reviewData]);
+
+ const gitError = branchError || aheadBehindError || reviewError;
+ const isGitLoading = branchLoading || reviewLoading;
+ const visibleWorks = works.slice(0, 3);
+ const directoryName = workingDirectory ? pathBasename(workingDirectory) : undefined;
+
+ const retryGit = async () => {
+ await Promise.all([mutateBranch(), mutateAheadBehind(), mutateReview()]);
+ };
+
+ return (
+ <Flexbox className={styles.body} gap={14}>
+ <Flexbox>
+ <Flexbox
+ horizontal
+ align={'center'}
+ className={styles.sectionHeader}
+ justify={'space-between'}
+ >
+ <span className={styles.sectionTitle}>{t('workingPanel.overview.environment')}</span>
+ {workingDirectory && (
+ <Tag size={'small'}>
+ {deviceId
+ ? t('workingPanel.overview.execution.device')
+ : t('workingPanel.overview.execution.local')}
+ </Tag>
+ )}
+ </Flexbox>
+
+ <Flexbox
+ horizontal
+ align={'flex-start'}
+ className={styles.row}
+ gap={10}
+ onClick={workingDirectory ? () => onOpenTab('files') : undefined}
+ >
+ <OverviewRowLead icon={workingDirectory ? FolderGit2Icon : LaptopIcon}>
+ <Flexbox flex={1} style={{ minWidth: 0 }}>
+ <Text ellipsis weight={500}>
+ {directoryName || t('workingPanel.overview.workspace.empty')}
+ </Text>
+ <Text ellipsis color={cssVar.colorTextTertiary} fontSize={12}>
+ {workingDirectory || t('workingPanel.overview.workspace.emptyDesc')}
+ </Text>
+ </Flexbox>
+ </OverviewRowLead>
+ {workingDirectory && <Icon icon={ChevronRightIcon} size={14} />}
+ </Flexbox>
+
+ {repoType && workingDirectory && isGitLoading ? (
+ <div className={styles.skeleton}>
+ <Skeleton active paragraph={{ rows: 2 }} title={false} />
+ </div>
+ ) : gitError ? (
+ <Center className={styles.error} gap={8}>
+ <Text type={'danger'}>{t('workingPanel.overview.environmentError')}</Text>
+ <Button icon={RefreshCwIcon} size={'small'} onClick={retryGit}>
+ {t('retry', { ns: 'common' })}
+ </Button>
+ </Center>
+ ) : repoType && workingDirectory ? (
+ <>
+ <Flexbox
+ horizontal
+ align={'flex-start'}
+ className={cx(styles.row, styles.rowStatus)}
+ gap={10}
+ >
+ <OverviewRowLead icon={GitBranchIcon}>
+ <Flexbox flex={1}>
+ <Text className={styles.rowStatusPrimary}>
+ {t('workingPanel.overview.branch')}
+ </Text>
+ </Flexbox>
+ </OverviewRowLead>
+ <Flexbox horizontal align={'center'} className={styles.stats} gap={6}>
+ <Text ellipsis fontSize={12} style={{ maxWidth: 128 }}>
+ {branchData?.branch || t('workingPanel.overview.branch.detached')}
+ </Text>
+ {!!aheadBehind?.ahead && <Tag size={'small'}>↑{aheadBehind.ahead}</Tag>}
+ {!!aheadBehind?.behind && <Tag size={'small'}>↓{aheadBehind.behind}</Tag>}
+ </Flexbox>
+ </Flexbox>
+ <Flexbox
+ horizontal
+ align={'flex-start'}
+ className={styles.row}
+ gap={10}
+ onClick={() => onOpenTab('review')}
+ >
+ <OverviewRowLead icon={ClipboardListIcon}>
+ <Flexbox flex={1} style={{ minWidth: 0 }}>
+ <Text weight={500}>{t('workingPanel.overview.changes')}</Text>
+ <Text color={cssVar.colorTextTertiary} fontSize={12}>
+ {changeStats.files
+ ? t('workingPanel.overview.changes.files', { count: changeStats.files })
+ : t('workingPanel.overview.changes.clean')}
+ </Text>
+ </Flexbox>
+ </OverviewRowLead>
+ {changeStats.files > 0 && (
+ <Flexbox horizontal className={styles.stats} gap={8}>
+ <span className={styles.changeAdditions}>+{changeStats.additions}</span>
+ <span className={styles.changeDeletions}>−{changeStats.deletions}</span>
+ </Flexbox>
+ )}
+ <Icon icon={ChevronRightIcon} size={14} />
+ </Flexbox>
+ </>
+ ) : null}
+ </Flexbox>
+
+ <ProgressSection />
+
+ {visibleWorks.length > 0 && (
+ <Flexbox>
+ <Flexbox
+ horizontal
+ align={'center'}
+ className={styles.sectionHeader}
+ justify={'space-between'}
+ >
+ <span className={styles.sectionTitle}>{t('workingPanel.overview.outputs')}</span>
+ <Button size={'small'} type={'text'} onClick={() => onOpenTab('works')}>
+ {t('workingPanel.overview.viewAll')}
+ </Button>
+ </Flexbox>
+ {visibleWorks.map((work) => (
+ <WorkSummaryCard item={work} key={work.id} variant={'inline'} />
+ ))}
+ </Flexbox>
+ )}
+
+ <Flexbox>
+ <Flexbox
+ horizontal
+ align={'center'}
+ className={styles.sectionHeader}
+ justify={'space-between'}
+ >
+ <span className={styles.sectionTitle}>{t('workingPanel.overview.resources')}</span>
+ <Button size={'small'} type={'text'} onClick={() => onOpenTab('resources')}>
+ {t('workingPanel.overview.manage')}
+ </Button>
+ </Flexbox>
+ <Flexbox
+ horizontal
+ align={'flex-start'}
+ className={styles.row}
+ gap={10}
+ onClick={() => onOpenTab('resources')}
+ >
+ <OverviewRowLead icon={FolderOpenIcon}>
+ <Flexbox flex={1}>
+ <Text weight={500}>{t('workingPanel.overview.resources.title')}</Text>
+ <Text color={cssVar.colorTextTertiary} fontSize={12}>
+ {t('workingPanel.overview.resources.desc')}
+ </Text>
+ </Flexbox>
+ </OverviewRowLead>
+ <Icon icon={ChevronRightIcon} size={14} />
+ </Flexbox>
+ </Flexbox>
+
+ {!topicId && visibleWorks.length === 0 && !workingDirectory && (
+ <Empty
+ description={t('workingPanel.overview.empty')}
+ icon={BoxesIcon}
+ title={t('workingPanel.overview.emptyTitle')}
+ />
+ )}
+ </Flexbox>
+ );
+ },
+);
+
+Overview.displayName = 'WorkingSidebarOverview';
+
+export default Overview;
diff --git a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/ProgressSection/index.tsx b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/ProgressSection/index.tsx
index de3c6a205b8..364a38950c7 100644
--- a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/ProgressSection/index.tsx
+++ b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/ProgressSection/index.tsx
@@ -1,4 +1,4 @@
-import { Checkbox, Flexbox, Icon, Tag } from '@lobehub/ui';
+import { Checkbox, Flexbox, Icon } from '@lobehub/ui';
import { createStaticStyles, cssVar, cx } from 'antd-style';
import { ChevronDown, ChevronUp, CircleArrowRight } from 'lucide-react';
import { type KeyboardEvent, memo, useCallback, useId, useMemo, useState } from 'react';
@@ -19,47 +19,47 @@ const RING_CIRCUM = 2 * Math.PI * RING_RADIUS;
const styles = createStaticStyles(({ css, cssVar }) => ({
collapsed: css`
grid-template-rows: 0fr;
-
margin-block-start: 0 !important;
padding-block: 0 !important;
- border-block-start: none !important;
-
opacity: 0;
`,
- container: css`
- margin-block-start: 4px;
- margin-inline: 8px 12px;
- padding-block: 8px 10px;
- padding-inline: 12px;
- border: 1px solid ${cssVar.colorBorderSecondary};
- border-radius: 12px;
+ count: css`
+ flex-shrink: 0;
- background: ${cssVar.colorBgElevated};
+ padding-block: 1px;
+ padding-inline: 6px;
+ border-radius: 4px;
- transition: all 0.2s ${cssVar.motionEaseInOut};
- `,
- count: css`
font-family: ${cssVar.fontFamilyCode};
- font-size: 12px;
+ font-size: 11px;
color: ${cssVar.colorTextSecondary};
+
+ background: ${cssVar.colorFillSecondary};
`,
expanded: css`
grid-template-rows: 1fr;
opacity: 1;
`,
header: css`
- overflow: hidden;
-
- font-size: 13px;
- font-weight: 500;
- color: ${cssVar.colorText};
- text-overflow: ellipsis;
- white-space: nowrap;
+ font-size: 10.5px;
+ font-weight: 600;
+ color: ${cssVar.colorTextSecondary};
+ text-transform: uppercase;
+ letter-spacing: 0.08em;
`,
headerRow: css`
cursor: pointer;
user-select: none;
- border-radius: 4px;
+
+ padding-block: 4px 6px;
+ padding-inline: 10px;
+ border-radius: 6px;
+
+ transition: background-color 0.12s ease;
+
+ &:hover {
+ background: ${cssVar.colorFillTertiary};
+ }
&:focus-visible {
outline: 2px solid ${cssVar.colorPrimaryBorder};
@@ -78,15 +78,11 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
`,
listContainer: css`
display: grid;
-
- margin-block-start: 8px;
padding-block: 4px;
- border-block-start: 1px solid ${cssVar.colorBorderSecondary};
-
+ padding-inline: 10px;
transition:
grid-template-rows 0.25s ${cssVar.motionEaseInOut},
opacity 0.2s ${cssVar.motionEaseInOut},
- margin-block-start 0.2s ${cssVar.motionEaseInOut},
padding 0.2s ${cssVar.motionEaseInOut};
`,
listInner: css`
@@ -157,7 +153,7 @@ const ProgressSection = memo(() => {
const ringOffset = RING_CIRCUM * (1 - progress.completionPercent / 100);
return (
- <div className={styles.container} data-testid="workspace-progress">
+ <div data-testid="workspace-progress">
<Flexbox
horizontal
align="center"
@@ -195,15 +191,13 @@ const ProgressSection = memo(() => {
/>
</svg>
<span className={styles.header}>{t('workingPanel.progress')}</span>
- <Tag size="small" style={{ flexShrink: 0 }}>
- <span className={styles.count}>
- {completed}/{total}
- </span>
- </Tag>
+ <span className={styles.count}>
+ {completed}/{total}
+ </span>
</Flexbox>
<Icon
icon={expanded ? ChevronUp : ChevronDown}
- size={16}
+ size={14}
style={{ color: cssVar.colorTextTertiary, flexShrink: 0 }}
/>
</Flexbox>
diff --git a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/WorkspaceTab.tsx b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/WorkspaceTab.tsx
new file mode 100644
index 00000000000..2258429204a
--- /dev/null
+++ b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/WorkspaceTab.tsx
@@ -0,0 +1,165 @@
+import { Icon, type IconProps } from '@lobehub/ui';
+import { type ContextMenuItem, ContextMenuTrigger } from '@lobehub/ui/base-ui';
+import { createStaticStyles } from 'antd-style';
+import { PinIcon, XIcon } from 'lucide-react';
+import { memo, type ReactNode } from 'react';
+
+const styles = createStaticStyles(({ css, cssVar }) => ({
+ close: css`
+ cursor: pointer;
+
+ position: absolute;
+ inset-block-start: 50%;
+ inset-inline-end: 4px;
+ transform: translateY(-50%);
+
+ display: grid;
+ place-items: center;
+
+ width: 20px;
+ height: 20px;
+ padding: 0;
+ border: none;
+ border-radius: 4px;
+
+ color: ${cssVar.colorTextTertiary};
+
+ background: transparent;
+
+ &:hover {
+ color: ${cssVar.colorText};
+ background: ${cssVar.colorFillSecondary};
+ }
+ `,
+ container: css`
+ position: relative;
+
+ display: flex;
+ flex-shrink: 0;
+ align-items: center;
+
+ border-radius: 6px;
+
+ transition: background 0.15s;
+
+ &:hover {
+ background: ${cssVar.colorFillSecondary};
+ }
+ `,
+ containerActive: css`
+ background: ${cssVar.colorFillTertiary};
+ `,
+ pinned: css`
+ pointer-events: none;
+
+ position: absolute;
+ inset-block-start: 50%;
+ inset-inline-end: 8px;
+ transform: translateY(-50%);
+
+ display: grid;
+ place-items: center;
+
+ color: ${cssVar.colorTextSecondary};
+ `,
+ tab: css`
+ cursor: pointer;
+
+ padding-block: 4px;
+ padding-inline: 10px;
+ border: none;
+ border-radius: 6px;
+
+ font-size: 12px;
+ color: ${cssVar.colorTextTertiary};
+ white-space: nowrap;
+
+ background: transparent;
+
+ transition: color 0.15s;
+
+ &:hover {
+ color: ${cssVar.colorText};
+ }
+ `,
+ tabActive: css`
+ color: ${cssVar.colorText};
+ `,
+ tabClosable: css`
+ padding-inline-end: 30px;
+ `,
+ trigger: css`
+ display: flex;
+ gap: 4px;
+ align-items: center;
+ `,
+}));
+
+interface WorkspaceTabProps {
+ active: boolean;
+ closeLabel?: string;
+ contextMenuItems?: ContextMenuItem[];
+ fixed?: boolean;
+ icon: IconProps['icon'];
+ label: ReactNode;
+ onClose?: () => void;
+ onSelect: () => void;
+ pinned?: boolean;
+ pinnedLabel?: string;
+ tabKey: string;
+}
+
+const WorkspaceTab = memo<WorkspaceTabProps>(
+ ({
+ active,
+ closeLabel,
+ contextMenuItems,
+ fixed,
+ icon,
+ label,
+ onClose,
+ onSelect,
+ pinned,
+ pinnedLabel,
+ tabKey,
+ }) => {
+ const content = (
+ <div
+ className={`${styles.container} ${active ? styles.containerActive : ''}`}
+ data-pinned={pinned ? 'true' : undefined}
+ >
+ <button
+ aria-pressed={active}
+ className={`${styles.tab} ${active ? styles.tabActive : ''} ${!fixed && (onClose || pinned) ? styles.tabClosable : ''}`}
+ data-tab-key={tabKey}
+ type="button"
+ onClick={onSelect}
+ >
+ <span className={styles.trigger}>
+ <Icon icon={icon} size={14} />
+ {label}
+ </span>
+ </button>
+ {!fixed && pinned ? (
+ <span aria-label={pinnedLabel} className={styles.pinned} role="img">
+ <Icon icon={PinIcon} size={12} />
+ </span>
+ ) : !fixed && onClose ? (
+ <button aria-label={closeLabel} className={styles.close} type="button" onClick={onClose}>
+ <Icon icon={XIcon} size={12} />
+ </button>
+ ) : null}
+ </div>
+ );
+
+ return contextMenuItems ? (
+ <ContextMenuTrigger items={contextMenuItems}>{content}</ContextMenuTrigger>
+ ) : (
+ content
+ );
+ },
+);
+
+WorkspaceTab.displayName = 'WorkingSidebarTab';
+
+export default WorkspaceTab;
diff --git a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/__tests__/index.test.tsx b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/__tests__/index.test.tsx
index 3cd27669f99..507a4e1c802 100644
--- a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/__tests__/index.test.tsx
+++ b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/__tests__/index.test.tsx
@@ -1,5 +1,5 @@
-import { act, render, screen } from '@testing-library/react';
-import type { ReactNode } from 'react';
+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import type { MouseEvent, ReactNode } from 'react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import AgentWorkingSidebar from '../index';
@@ -48,13 +48,29 @@ const businessTabs = vi.hoisted(() => ({
current: [] as { key: string; label: string; pane: ReactNode }[],
}));
+const paramsSectionState = vi.hoisted(() => ({
+ pending: new Promise<never>(() => undefined),
+ suspend: false,
+}));
+
+const localStorageState = vi.hoisted(() => ({
+ openTabsByContext: {} as Record<string, string[]>,
+ pinnedTabsByAgent: {} as Record<string, string[]>,
+}));
+
+const dropdownMenuState = vi.hoisted(() => ({
+ onOpenChangeComplete: undefined as ((open: boolean) => void) | undefined,
+}));
+
const globalStore = vi.hoisted(() => ({
updateSystemStatus: vi.fn(),
toggleRightPanel: vi.fn(),
+ toggleTerminalPanel: vi.fn(),
setWorkingSidebarTab: vi.fn(),
status: {
showRightPanel: true,
workingSidebarTab: 'params' as string | undefined,
+ workingSidebarTabRequest: undefined as { nonce: number; tab: string } | undefined,
workingSidebarWidth: 360 as number | undefined,
},
}));
@@ -77,8 +93,20 @@ vi.mock('../Files', () => ({
vi.mock('../Review', () => ({ default: () => <div /> }));
vi.mock('../ProgressSection', () => ({ default: () => <div /> }));
vi.mock('../ResourcesSection', () => ({ default: () => <div /> }));
-vi.mock('../ParamsSection', () => ({ default: () => <div /> }));
+vi.mock('../ParamsSection', () => ({
+ default: () => {
+ if (paramsSectionState.suspend) throw paramsSectionState.pending;
+ return <div data-testid="params-section" />;
+ },
+}));
vi.mock('../WorksSection', () => ({ default: () => <div /> }));
+vi.mock('../Overview', () => ({
+ default: ({ onOpenTab }: { onOpenTab: (tab: string) => void }) => (
+ <button type="button" onClick={() => onOpenTab('review')}>
+ Open Review from Overview
+ </button>
+ ),
+}));
vi.mock('@/store/agent', () => ({
getAgentStoreState: () => agentStore,
@@ -131,9 +159,20 @@ vi.mock('@/hooks/useEffectiveAgencyConfig', () => ({
workspaceScoped: effectiveConfig.workspaceScoped,
}),
}));
-vi.mock('@/hooks/useLocalStorageState', () => ({
- useLocalStorageState: () => [reviewState.showTree, vi.fn()],
-}));
+vi.mock('@/hooks/useLocalStorageState', async () => {
+ const { useState } = await import('react');
+
+ return {
+ useLocalStorageState: (key: string) =>
+ useState(
+ key === 'lobechat-review-tree'
+ ? reviewState.showTree
+ : key === 'lobechat-working-sidebar-pinned-tabs-v1'
+ ? localStorageState.pinnedTabsByAgent
+ : localStorageState.openTabsByContext,
+ ),
+ };
+});
vi.mock('@/helpers/agentWorkingDirectory', () => ({ resolveTargetDeviceId: () => undefined }));
vi.mock('@/helpers/executionTarget', () => ({
resolveExecutionTarget: (
@@ -148,16 +187,80 @@ vi.mock('react-i18next', () => ({
}));
vi.mock('@lobehub/ui', () => ({
- ActionIcon: () => <button type="button" />,
+ ActionIcon: ({ onClick, title }: { onClick?: () => void; title?: string }) => (
+ <button aria-label={title} type="button" onClick={onClick} />
+ ),
Flexbox: ({ children }: { children?: ReactNode }) => <div>{children}</div>,
+ Icon: () => <span />,
+ Skeleton: () => <div data-testid="params-loading" />,
}));
+vi.mock('@lobehub/ui/base-ui', async () => {
+ const { useState } = await import('react');
+
+ return {
+ ContextMenuTrigger: ({ children, items }: { children: ReactNode; items: any[] }) => {
+ const [open, setOpen] = useState(false);
+ const menuItems = items.filter((item) => item && item.type !== 'divider');
+
+ return (
+ <span
+ onContextMenu={(event: MouseEvent) => {
+ event.preventDefault();
+ setOpen(true);
+ }}
+ >
+ {children}
+ {open &&
+ menuItems.map((item) => (
+ <button disabled={item.disabled} key={item.key} type="button" onClick={item.onClick}>
+ {item.label}
+ </button>
+ ))}
+ </span>
+ );
+ },
+ DropdownMenu: ({
+ children,
+ items,
+ onOpenChangeComplete,
+ }: {
+ children: ReactNode;
+ items: any[];
+ onOpenChangeComplete?: (open: boolean) => void;
+ }) => {
+ const [open, setOpen] = useState(false);
+ const menuItems = items.flatMap((item) => item.children ?? []);
+ dropdownMenuState.onOpenChangeComplete = onOpenChangeComplete;
+
+ return (
+ <div>
+ <span onClick={() => setOpen((value) => !value)}>{children}</span>
+ {open &&
+ menuItems.map((item) => (
+ <button key={item.key} type="button" onClick={item.onClick}>
+ {item.label}
+ </button>
+ ))}
+ </div>
+ );
+ },
+ };
+});
+
vi.mock('antd-style', () => ({
createStaticStyles: () => () => ({}),
}));
beforeEach(() => {
+ vi.spyOn(window, 'requestAnimationFrame').mockImplementation((callback) => {
+ callback(0);
+ return 1;
+ });
businessTabs.current = [];
+ paramsSectionState.suspend = false;
+ localStorageState.openTabsByContext = { 'draft:default:none': ['params'] };
+ localStorageState.pinnedTabsByAgent = {};
agentStore.activeAgentId = undefined;
agentStore.isHeterogeneous = false;
agentStore.rawAgencyConfig = undefined;
@@ -168,11 +271,14 @@ beforeEach(() => {
reviewState.setRepoType = undefined;
reviewState.showTree = false;
reviewState.workingDirectory = undefined;
+ dropdownMenuState.onOpenChangeComplete = undefined;
globalStore.status.workingSidebarWidth = 360;
globalStore.status.showRightPanel = true;
globalStore.status.workingSidebarTab = 'params';
+ globalStore.status.workingSidebarTabRequest = undefined;
globalStore.updateSystemStatus.mockReset();
globalStore.toggleRightPanel.mockReset();
+ globalStore.toggleTerminalPanel.mockReset();
globalStore.setWorkingSidebarTab.mockReset();
});
@@ -209,6 +315,7 @@ describe('AgentWorkingSidebar — controlled panel width', () => {
reviewState.showTree = true;
reviewState.workingDirectory = 'C:\\repo';
globalStore.status.workingSidebarTab = 'review';
+ localStorageState.openTabsByContext = { 'draft:agent:C:\\repo': ['review'] };
const { unmount } = render(<AgentWorkingSidebar />);
@@ -316,86 +423,317 @@ describe('AgentWorkingSidebar — tab strip', () => {
// Regression: at the 300px minimum panel width, labels such as “Deployments”
// were allowed to shrink and wrap inside words. Tabs now stay on one line in a
// horizontal strip, so a persisted tab near the end must be brought into view.
- it('scrolls an overflowed active tab into view', () => {
+ it('scrolls the whole active tab, including its close button, into view', () => {
globalStore.status.workingSidebarTab = 'params';
vi.spyOn(Element.prototype, 'getBoundingClientRect').mockImplementation(function (
this: Element,
) {
- return this instanceof HTMLButtonElement && this.getAttribute('aria-pressed') === 'true'
- ? ({ left: 220, right: 280 } as DOMRect)
+ return this instanceof HTMLDivElement &&
+ this.firstElementChild instanceof HTMLButtonElement &&
+ this.firstElementChild.getAttribute('aria-pressed') === 'true'
+ ? ({
+ left: 120 - (this.parentElement?.scrollLeft ?? 0),
+ right: 222 - (this.parentElement?.scrollLeft ?? 0),
+ } as DOMRect)
: ({ left: 0, right: 200 } as DOMRect);
});
- const scrollIntoView = vi
- .spyOn(Element.prototype, 'scrollIntoView')
- .mockImplementation(() => undefined);
-
render(<AgentWorkingSidebar />);
const paramsTab = screen.getByRole('button', { name: 'settingModel.params.panel.tab' });
expect(paramsTab).toHaveAttribute('aria-pressed', 'true');
- expect(scrollIntoView).toHaveBeenCalledWith({ block: 'nearest', inline: 'nearest' });
+ expect(paramsTab.parentElement?.parentElement?.parentElement?.scrollLeft).toBe(22);
+ });
+
+ it('restores the complete active tab after the open menu closes and focus moves', async () => {
+ globalStore.status.workingSidebarTab = 'params';
+ vi.spyOn(Element.prototype, 'getBoundingClientRect').mockImplementation(function (
+ this: Element,
+ ) {
+ return this instanceof HTMLDivElement &&
+ this.firstElementChild instanceof HTMLButtonElement &&
+ this.firstElementChild.getAttribute('aria-pressed') === 'true'
+ ? ({
+ left: 120 - (this.parentElement?.scrollLeft ?? 0),
+ right: 222 - (this.parentElement?.scrollLeft ?? 0),
+ } as DOMRect)
+ : ({ left: 0, right: 200 } as DOMRect);
+ });
+ render(<AgentWorkingSidebar />);
+ const paramsTab = screen.getByRole('button', { name: 'settingModel.params.panel.tab' });
+ const tabs = paramsTab.parentElement?.parentElement?.parentElement;
+
+ if (tabs) tabs.scrollLeft = 0;
+ act(() => dropdownMenuState.onOpenChangeComplete?.(false));
+
+ await waitFor(() => expect(tabs?.scrollLeft).toBe(22));
});
it('exposes and reveals a persisted active Works tab', () => {
globalStore.status.workingSidebarTab = 'works';
+ localStorageState.openTabsByContext = { 'draft:default:none': ['works'] };
vi.spyOn(Element.prototype, 'getBoundingClientRect').mockImplementation(function (
this: Element,
) {
- return this instanceof HTMLButtonElement && this.getAttribute('aria-pressed') === 'true'
- ? ({ left: 220, right: 280 } as DOMRect)
+ return this instanceof HTMLDivElement &&
+ this.firstElementChild instanceof HTMLButtonElement &&
+ this.firstElementChild.getAttribute('aria-pressed') === 'true'
+ ? ({ left: 120, right: 222 } as DOMRect)
: ({ left: 0, right: 200 } as DOMRect);
});
- const scrollIntoView = vi
- .spyOn(Element.prototype, 'scrollIntoView')
- .mockImplementation(() => undefined);
-
render(<AgentWorkingSidebar />);
const worksTab = screen.getByRole('button', { name: 'workingPanel.works.title' });
expect(worksTab).toHaveAttribute('aria-pressed', 'true');
- expect(scrollIntoView).toHaveBeenCalledWith({ block: 'nearest', inline: 'nearest' });
+ expect(worksTab.parentElement?.parentElement?.parentElement?.scrollLeft).toBe(22);
});
it('reveals the active tab again when an async tab becomes available', () => {
agentStore.activeAgentId = 'agent';
reviewState.workingDirectory = '/repo';
globalStore.status.workingSidebarTab = 'params';
+ localStorageState.openTabsByContext = { 'draft:agent:/repo': ['params', 'review'] };
vi.spyOn(Element.prototype, 'getBoundingClientRect').mockImplementation(function (
this: Element,
) {
- return this instanceof HTMLButtonElement && this.getAttribute('aria-pressed') === 'true'
- ? ({ left: 220, right: 280 } as DOMRect)
+ return this instanceof HTMLDivElement &&
+ this.firstElementChild instanceof HTMLButtonElement &&
+ this.firstElementChild.getAttribute('aria-pressed') === 'true'
+ ? ({ left: 120, right: 222 } as DOMRect)
: ({ left: 0, right: 200 } as DOMRect);
});
- const scrollIntoView = vi
- .spyOn(Element.prototype, 'scrollIntoView')
- .mockImplementation(() => undefined);
-
render(<AgentWorkingSidebar />);
- expect(scrollIntoView).toHaveBeenCalledTimes(1);
+ const paramsTab = screen.getByRole('button', { name: 'settingModel.params.panel.tab' });
+ const tabs = paramsTab.parentElement?.parentElement?.parentElement;
+ expect(tabs?.scrollLeft).toBe(22);
act(() => reviewState.setRepoType?.('git'));
expect(screen.getByRole('button', { name: 'workingPanel.review.title' })).toBeInTheDocument();
- expect(scrollIntoView).toHaveBeenCalledTimes(2);
+ expect(tabs?.scrollLeft).toBe(44);
});
it('renders business tabs after the built-in ones', () => {
businessTabs.current = [
{ key: 'deployments', label: 'workingPanel.deployments.tab', pane: <div /> },
];
+ localStorageState.openTabsByContext = {
+ 'draft:default:none': ['params', 'deployments'],
+ };
render(<AgentWorkingSidebar />);
const labels = screen
.getAllByRole('button')
+ .filter((button) => button.hasAttribute('aria-pressed'))
.map((button) => button.textContent)
.filter(Boolean);
expect(labels).toEqual([
- 'workingPanel.space',
- 'workingPanel.works.title',
+ 'workingPanel.overview.title',
'settingModel.params.panel.tab',
'workingPanel.deployments.tab',
]);
});
+
+ it('keeps Overview fixed and hides unopened workspace tabs', () => {
+ localStorageState.openTabsByContext = {};
+ globalStore.status.workingSidebarTab = undefined;
+
+ render(<AgentWorkingSidebar />);
+
+ expect(screen.getByRole('button', { name: 'workingPanel.overview.title' })).toHaveAttribute(
+ 'aria-pressed',
+ 'true',
+ );
+ expect(
+ screen.queryByRole('button', { name: 'workingPanel.resources' }),
+ ).not.toBeInTheDocument();
+ expect(
+ screen.queryByRole('button', { name: 'workingPanel.works.title' }),
+ ).not.toBeInTheDocument();
+ });
+
+ it('places Overview in the same horizontal scroll container as on-demand tabs', () => {
+ render(<AgentWorkingSidebar />);
+ const overviewTab = screen.getByRole('button', { name: 'workingPanel.overview.title' });
+ const paramsTab = screen.getByRole('button', { name: 'settingModel.params.panel.tab' });
+
+ expect(overviewTab.parentElement?.parentElement?.parentElement).toBe(
+ paramsTab.parentElement?.parentElement?.parentElement,
+ );
+ });
+
+ it('keeps the working panel chrome visible while the Params pane is suspended', () => {
+ paramsSectionState.suspend = true;
+
+ render(<AgentWorkingSidebar />);
+
+ expect(screen.getByRole('button', { name: 'workingPanel.overview.title' })).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: 'workingPanel.openMenu.title' })).toBeInTheDocument();
+ expect(screen.getByTestId('params-loading')).toBeInTheDocument();
+ });
+
+ it('restores pinned tabs only for the agent that owns them', () => {
+ agentStore.activeAgentId = 'agent-a';
+ localStorageState.openTabsByContext = {};
+ localStorageState.pinnedTabsByAgent = { 'agent-a': ['works'] };
+ globalStore.status.workingSidebarTab = 'overview';
+
+ const { unmount } = render(<AgentWorkingSidebar />);
+ const pinnedWorksTab = screen.getByRole('button', { name: 'workingPanel.works.title' });
+
+ expect(pinnedWorksTab.parentElement).toHaveAttribute('data-pinned', 'true');
+ expect(
+ screen.queryByRole('button', { name: 'workingPanel.tabs.close' }),
+ ).not.toBeInTheDocument();
+
+ unmount();
+ agentStore.activeAgentId = 'agent-b';
+ render(<AgentWorkingSidebar />);
+
+ expect(
+ screen.queryByRole('button', { name: 'workingPanel.works.title' }),
+ ).not.toBeInTheDocument();
+ });
+
+ it('pins and unpins a tab from its context menu', () => {
+ agentStore.activeAgentId = 'agent';
+ localStorageState.openTabsByContext = { 'draft:agent:none': ['params'] };
+ globalStore.status.workingSidebarTab = 'params';
+
+ render(<AgentWorkingSidebar />);
+ const paramsTab = screen.getByRole('button', { name: 'settingModel.params.panel.tab' });
+
+ fireEvent.contextMenu(paramsTab);
+ fireEvent.click(screen.getByRole('button', { name: 'workingPanel.tabs.pin' }));
+
+ expect(paramsTab.parentElement).toHaveAttribute('data-pinned', 'true');
+ expect(screen.getByRole('button', { name: 'workingPanel.tabs.close' })).toBeDisabled();
+
+ fireEvent.click(screen.getByRole('button', { name: 'workingPanel.tabs.unpin' }));
+
+ expect(paramsTab.parentElement).not.toHaveAttribute('data-pinned');
+ expect(
+ screen
+ .getAllByRole('button', { name: 'workingPanel.tabs.close' })
+ .some((button) => !button.hasAttribute('disabled')),
+ ).toBe(true);
+ });
+
+ it('closes the current tab from its context menu', () => {
+ agentStore.activeAgentId = 'agent';
+ localStorageState.openTabsByContext = { 'draft:agent:none': ['params'] };
+ globalStore.status.workingSidebarTab = 'params';
+
+ render(<AgentWorkingSidebar />);
+ fireEvent.contextMenu(screen.getByRole('button', { name: 'settingModel.params.panel.tab' }));
+ fireEvent.click(screen.getByText('workingPanel.tabs.close'));
+
+ expect(
+ screen.queryByRole('button', { name: 'settingModel.params.panel.tab' }),
+ ).not.toBeInTheDocument();
+ expect(globalStore.setWorkingSidebarTab).toHaveBeenCalledWith('overview');
+ });
+
+ it('preserves agent-pinned tabs when closing other tabs', () => {
+ agentStore.activeAgentId = 'agent';
+ localStorageState.openTabsByContext = {
+ 'draft:agent:none': ['resources', 'works', 'params'],
+ };
+ localStorageState.pinnedTabsByAgent = { agent: ['works'] };
+ globalStore.status.workingSidebarTab = 'params';
+
+ render(<AgentWorkingSidebar />);
+ fireEvent.contextMenu(screen.getByRole('button', { name: 'settingModel.params.panel.tab' }));
+ fireEvent.click(screen.getByRole('button', { name: 'workingPanel.tabs.closeOthers' }));
+
+ expect(screen.getByRole('button', { name: 'workingPanel.works.title' })).toBeInTheDocument();
+ expect(
+ screen.queryByRole('button', { name: 'workingPanel.resources' }),
+ ).not.toBeInTheDocument();
+ expect(
+ screen.getByRole('button', { name: 'settingModel.params.panel.tab' }),
+ ).toBeInTheDocument();
+ });
+
+ it('opens an available workspace tab once from the grouped menu', () => {
+ agentStore.activeAgentId = 'agent';
+ reviewState.repoType = 'git';
+ reviewState.workingDirectory = '/repo';
+ localStorageState.openTabsByContext = {};
+ globalStore.status.workingSidebarTab = 'overview';
+
+ render(<AgentWorkingSidebar />);
+
+ fireEvent.click(screen.getByRole('button', { name: 'workingPanel.openMenu.title' }));
+ fireEvent.click(screen.getByRole('button', { name: 'workingPanel.review.title' }));
+ fireEvent.click(screen.getByRole('button', { name: 'workingPanel.openMenu.title' }));
+
+ expect(screen.getAllByRole('button', { name: 'workingPanel.review.title' })).toHaveLength(1);
+ expect(globalStore.setWorkingSidebarTab).toHaveBeenCalledWith('review');
+ });
+
+ it('moves focus to a tab opened from the grouped menu', async () => {
+ localStorageState.openTabsByContext = {};
+ globalStore.status.workingSidebarTab = 'overview';
+ globalStore.setWorkingSidebarTab.mockImplementation((tab: string) => {
+ globalStore.status.workingSidebarTab = tab;
+ });
+
+ render(<AgentWorkingSidebar />);
+ fireEvent.click(screen.getByRole('button', { name: 'workingPanel.openMenu.title' }));
+ fireEvent.click(screen.getByRole('button', { name: 'settingModel.params.panel.tab' }));
+
+ await waitFor(
+ () => {
+ const paramsTab = screen
+ .getAllByRole('button', { name: 'settingModel.params.panel.tab' })
+ .find((button) => button.hasAttribute('aria-pressed'));
+ expect(paramsTab).toHaveFocus();
+ },
+ { timeout: 1000 },
+ );
+ });
+
+ it('returns to Overview when the active on-demand tab closes', () => {
+ agentStore.activeAgentId = 'agent';
+ reviewState.repoType = 'git';
+ reviewState.workingDirectory = '/repo';
+ localStorageState.openTabsByContext = { 'draft:agent:/repo': ['review'] };
+ globalStore.status.workingSidebarTab = 'review';
+
+ render(<AgentWorkingSidebar />);
+ fireEvent.click(screen.getByRole('button', { name: 'workingPanel.tabs.close' }));
+
+ expect(globalStore.setWorkingSidebarTab).toHaveBeenCalledWith('overview');
+ });
+
+ it('reopens a closed tab when the same external target is requested again', async () => {
+ agentStore.activeAgentId = 'agent';
+ reviewState.repoType = undefined;
+ reviewState.workingDirectory = '/repo';
+ localStorageState.openTabsByContext = {};
+ globalStore.status.workingSidebarTab = 'overview';
+
+ render(<AgentWorkingSidebar />);
+ expect(
+ screen.queryByRole('button', { name: 'workingPanel.review.title' }),
+ ).not.toBeInTheDocument();
+
+ globalStore.status.workingSidebarTabRequest = { nonce: 1, tab: 'review' };
+ act(() => reviewState.setRepoType?.('git'));
+ await waitFor(() => {
+ expect(screen.getByRole('button', { name: 'workingPanel.review.title' })).toBeInTheDocument();
+ });
+
+ fireEvent.click(screen.getByRole('button', { name: 'workingPanel.tabs.close' }));
+ expect(
+ screen.queryByRole('button', { name: 'workingPanel.review.title' }),
+ ).not.toBeInTheDocument();
+
+ globalStore.status.workingSidebarTabRequest = { nonce: 2, tab: 'review' };
+ act(() => reviewState.setRepoType?.('github'));
+ await waitFor(() => {
+ expect(screen.getByRole('button', { name: 'workingPanel.review.title' })).toBeInTheDocument();
+ });
+ });
});
diff --git a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/index.tsx b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/index.tsx
index 58e020d8af6..eada79f22dd 100644
--- a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/index.tsx
+++ b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/index.tsx
@@ -1,7 +1,34 @@
-import { ActionIcon, Flexbox } from '@lobehub/ui';
+import { ActionIcon, Flexbox, Icon, Skeleton } from '@lobehub/ui';
+import { type ContextMenuItem, type DropdownItem, DropdownMenu } from '@lobehub/ui/base-ui';
import { createStaticStyles } from 'antd-style';
-import { PanelRightCloseIcon } from 'lucide-react';
-import { lazy, memo, useEffect, useRef, useState } from 'react';
+import {
+ BoxesIcon,
+ CheckIcon,
+ ClipboardListIcon,
+ FilesIcon,
+ FolderOpenIcon,
+ Globe2Icon,
+ LayoutDashboardIcon,
+ PanelRightCloseIcon,
+ PanelsTopLeftIcon,
+ PinIcon,
+ PinOffIcon,
+ PlusIcon,
+ Settings2Icon,
+ SquareTerminalIcon,
+ XIcon,
+} from 'lucide-react';
+import {
+ lazy,
+ memo,
+ type ReactNode,
+ Suspense,
+ useCallback,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+} from 'react';
import { useTranslation } from 'react-i18next';
import { useBusinessWorkingSidebarTabs } from '@/business/client/features/WorkingSidebarTabs';
@@ -25,15 +52,16 @@ import { useUserStore } from '@/store/user';
import { labPreferSelectors } from '@/store/user/selectors';
import Files from './Files';
-import ProgressSection from './ProgressSection';
+import Overview from './Overview';
import ResourcesSection from './ResourcesSection';
import Review from './Review';
+import WorkspaceTab from './WorkspaceTab';
import WorksSection from './WorksSection';
const ParamsSection = lazy(() => import('./ParamsSection'));
const BrowserPane = lazy(() => import('./Browser'));
-const styles = createStaticStyles(({ css, cssVar }) => ({
+const styles = createStaticStyles(({ css }) => ({
body: css`
overflow-y: auto;
flex: 1;
@@ -54,35 +82,12 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
paneHidden: css`
display: none;
`,
- tab: css`
- cursor: pointer;
-
- flex-shrink: 0;
-
- padding-block: 4px;
- padding-inline: 8px;
- border: none;
- border-radius: 6px;
-
- font-size: 12px;
- color: ${cssVar.colorTextTertiary};
- white-space: nowrap;
-
- background: transparent;
-
- transition:
- color 0.15s,
- background 0.15s;
-
- &:hover {
- color: ${cssVar.colorText};
- }
- `,
- tabActive: css`
- color: ${cssVar.colorText};
- background: ${cssVar.colorFillTertiary};
+ paramsLoading: css`
+ width: 100%;
+ padding: 16px;
`,
tabs: css`
+ overflow-anchor: none;
scrollbar-width: none;
overflow-x: auto;
@@ -100,29 +105,41 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
}));
const REVIEW_TREE_STORAGE_KEY = 'lobechat-review-tree';
+const OPEN_TABS_STORAGE_KEY = 'lobechat-working-sidebar-open-tabs-v1';
+const PINNED_TABS_STORAGE_KEY = 'lobechat-working-sidebar-pinned-tabs-v1';
const MAX_PANEL_WIDTH = 1200;
// Two-pane Review (diff list + file-tree rail) is cramped below this.
const TWO_PANE_MIN_WIDTH = 560;
+interface SidebarTabDescriptor {
+ icon: typeof LayoutDashboardIcon;
+ key: string;
+ label: ReactNode;
+}
+
const AgentWorkingSidebar = memo(() => {
const { t } = useTranslation(['chat', 'setting']);
const [
storedWidth,
updateSystemStatus,
toggleRightPanel,
+ toggleTerminalPanel,
setWorkingSidebarTab,
showRightPanel,
storedTab,
+ tabRequest,
] = useGlobalStore((s) => [
systemStatusSelectors.workingSidebarWidth(s),
s.updateSystemStatus,
s.toggleRightPanel,
+ s.toggleTerminalPanel,
s.setWorkingSidebarTab,
// Panel open/collapsed state (drives the `<RightPanel>` expand). Used to gate
// the resources pane's document fetch so a collapsed sidebar doesn't pull the
// full agent-document list into the conversation's initial batch.
s.status.showRightPanel,
s.status.workingSidebarTab,
+ s.status.workingSidebarTabRequest,
]);
const activeAgentId = useAgentStore((s) => s.activeAgentId);
const topicId = useChatStore((s) => s.activeTopicId);
@@ -169,7 +186,9 @@ const AgentWorkingSidebar = memo(() => {
// The in-app browser pages are main-process WebContentsViews — desktop only,
// and gated behind the Labs toggle while the feature matures.
const enableInAppBrowser = useUserStore(labPreferSelectors.enableInAppBrowser);
+ const enableBuiltinTerminal = useUserStore(labPreferSelectors.enableBuiltinTerminal);
const browserAvailable = isDesktop && enableInAppBrowser;
+ const terminalAvailable = isDesktop && enableBuiltinTerminal;
// Must mint the same key the browser tools do (`sessionIdOf` in
// builtin-tool-browser), or the user and the agent would be looking at two
// different pages. A draft topic has no id yet, but the panel is openable
@@ -180,48 +199,286 @@ const AgentWorkingSidebar = memo(() => {
: `draft-agent:${activeAgentId ?? 'default'}`;
const businessTabs = useBusinessWorkingSidebarTabs({ activeAgentId, topicId });
+ const tabDescriptors = useMemo<SidebarTabDescriptor[]>(
+ () => [
+ { icon: FolderOpenIcon, key: 'resources', label: t('workingPanel.resources') },
+ { icon: BoxesIcon, key: 'works', label: t('workingPanel.works.title') },
+ ...(reviewAvailable
+ ? [{ icon: ClipboardListIcon, key: 'review', label: t('workingPanel.review.title') }]
+ : []),
+ ...(filesAvailable
+ ? [{ icon: FilesIcon, key: 'files', label: t('workingPanel.files.title') }]
+ : []),
+ ...(browserAvailable
+ ? [{ icon: Globe2Icon, key: 'browser', label: t('workingPanel.browser.title') }]
+ : []),
+ ...(paramsAvailable
+ ? [
+ {
+ icon: Settings2Icon,
+ key: 'params',
+ label: t('settingModel.params.panel.tab', { ns: 'setting' }),
+ },
+ ]
+ : []),
+ ...businessTabs.map((tab) => ({
+ icon: PanelsTopLeftIcon,
+ key: tab.key,
+ label: tab.label,
+ })),
+ ],
+ [browserAvailable, businessTabs, filesAvailable, paramsAvailable, reviewAvailable, t],
+ );
+ const availableTabs = useMemo(
+ () => new Map(tabDescriptors.map((tab) => [tab.key, tab])),
+ [tabDescriptors],
+ );
+ const availableTabsSignature = JSON.stringify(tabDescriptors.map((tab) => tab.key));
+ const openTabsContextKey = topicId
+ ? `topic:${topicId}`
+ : `draft:${activeAgentId ?? 'default'}:${workingDirectory ?? 'none'}`;
+ const pinnedTabsAgentKey = activeAgentId ?? 'default';
+ const [openTabsByContext, setOpenTabsByContext] = useLocalStorageState<Record<string, string[]>>(
+ OPEN_TABS_STORAGE_KEY,
+ {},
+ );
+ const [pinnedTabsByAgent, setPinnedTabsByAgent] = useLocalStorageState<Record<string, string[]>>(
+ PINNED_TABS_STORAGE_KEY,
+ {},
+ );
+ const lastTabRequestRef = useRef(tabRequest?.nonce);
+ const requestedTab =
+ tabRequest &&
+ lastTabRequestRef.current !== tabRequest.nonce &&
+ tabRequest.tab !== 'overview' &&
+ availableTabs.has(tabRequest.tab)
+ ? tabRequest.tab
+ : undefined;
+ const pinnedTabs = useMemo(
+ () => (pinnedTabsByAgent[pinnedTabsAgentKey] ?? []).filter((tab) => availableTabs.has(tab)),
+ [availableTabs, pinnedTabsAgentKey, pinnedTabsByAgent],
+ );
+ const pinnedTabsSet = useMemo(() => new Set(pinnedTabs), [pinnedTabs]);
+ const openedTabs = Array.from(
+ new Set([
+ ...pinnedTabs,
+ ...(openTabsByContext[openTabsContextKey] ?? []).filter((tab) => availableTabs.has(tab)),
+ ...(requestedTab ? [requestedTab] : []),
+ ]),
+ );
+ const openedTabsSignature = openedTabs.join('\0');
- const availableTabs = new Set<string>([
- 'resources',
- 'works',
- ...(reviewAvailable ? ['review'] : []),
- ...(filesAvailable ? ['files'] : []),
- ...(browserAvailable ? ['browser'] : []),
- ...(paramsAvailable ? ['params'] : []),
- ...businessTabs.map((tab) => tab.key),
- ]);
- const availableTabsSignature = JSON.stringify([...availableTabs]);
-
- const resolveActiveTab = (): string => {
- if (storedTab && availableTabs.has(storedTab)) return storedTab;
- // a persisted tab may reference a business tab that is absent in this build
- if (storedTab) {
- if (paramsAvailable) return 'params';
- if (reviewAvailable) return 'review';
- if (filesAvailable) return 'files';
- return 'resources';
+ const updateOpenedTabs = useCallback(
+ (updater: (tabs: string[]) => string[]) => {
+ setOpenTabsByContext((current) => ({
+ ...current,
+ [openTabsContextKey]: updater(current[openTabsContextKey] ?? []),
+ }));
+ },
+ [openTabsContextKey, setOpenTabsByContext],
+ );
+
+ const updatePinnedTabs = useCallback(
+ (updater: (tabs: string[]) => string[]) => {
+ setPinnedTabsByAgent((current) => ({
+ ...current,
+ [pinnedTabsAgentKey]: updater(current[pinnedTabsAgentKey] ?? []),
+ }));
+ },
+ [pinnedTabsAgentKey, setPinnedTabsByAgent],
+ );
+
+ const openTab = useCallback(
+ (tab: string) => {
+ if (tab !== 'overview' && !availableTabs.has(tab)) return;
+ if (tab !== 'overview') {
+ updateOpenedTabs((current) => (current.includes(tab) ? current : [...current, tab]));
+ }
+ setWorkingSidebarTab(tab);
+ },
+ [availableTabs, setWorkingSidebarTab, updateOpenedTabs],
+ );
+
+ const activeTab: string =
+ storedTab && (storedTab === 'overview' || openedTabs.includes(storedTab))
+ ? storedTab
+ : 'overview';
+
+ useEffect(() => {
+ if (!tabRequest || lastTabRequestRef.current === tabRequest.nonce) return;
+ if (tabRequest.tab !== 'overview' && !availableTabs.has(tabRequest.tab)) return;
+
+ lastTabRequestRef.current = tabRequest.nonce;
+ if (tabRequest.tab !== 'overview') {
+ updateOpenedTabs((current) =>
+ current.includes(tabRequest.tab) ? current : [...current, tabRequest.tab],
+ );
}
- if (isHetero) return 'resources';
- if (reviewAvailable) return 'review';
- if (filesAvailable) return 'files';
- return 'resources';
- };
- const activeTab = resolveActiveTab();
+ }, [availableTabs, availableTabsSignature, tabRequest, updateOpenedTabs]);
+
+ const pinTab = useCallback(
+ (tab: string) => {
+ if (!availableTabs.has(tab)) return;
+ updateOpenedTabs((current) => (current.includes(tab) ? current : [...current, tab]));
+ updatePinnedTabs((current) => (current.includes(tab) ? current : [...current, tab]));
+ },
+ [availableTabs, updateOpenedTabs, updatePinnedTabs],
+ );
+
+ const unpinTab = useCallback(
+ (tab: string) => {
+ // A tab restored only through its agent pin should remain open in the
+ // current topic after unpinning instead of disappearing immediately.
+ updateOpenedTabs((current) => (current.includes(tab) ? current : [...current, tab]));
+ updatePinnedTabs((current) => current.filter((item) => item !== tab));
+ },
+ [updateOpenedTabs, updatePinnedTabs],
+ );
+
+ const closeTabs = useCallback(
+ (tabs: string[], fallbackTab = 'overview') => {
+ const removableTabs = new Set(tabs.filter((tab) => !pinnedTabsSet.has(tab)));
+ if (removableTabs.size === 0) return;
+
+ updateOpenedTabs((current) => current.filter((tab) => !removableTabs.has(tab)));
+ if (removableTabs.has(activeTab)) setWorkingSidebarTab(fallbackTab);
+ },
+ [activeTab, pinnedTabsSet, setWorkingSidebarTab, updateOpenedTabs],
+ );
+
+ const closeTab = useCallback((tab: string) => closeTabs([tab]), [closeTabs]);
+
+ const displayedTabs = openedTabs
+ .map((tab) => availableTabs.get(tab))
+ .filter((tab): tab is SidebarTabDescriptor => Boolean(tab));
+ const createTabContextMenuItems = useCallback(
+ (tab: string, index: number): ContextMenuItem[] => {
+ const pinned = pinnedTabsSet.has(tab);
+ const leftTabs = openedTabs.slice(0, index);
+ const rightTabs = openedTabs.slice(index + 1);
+ const otherTabs = openedTabs.filter((item) => item !== tab);
+ const hasClosable = (tabs: string[]) => tabs.some((item) => !pinnedTabsSet.has(item));
+
+ return [
+ {
+ icon: pinned ? PinOffIcon : PinIcon,
+ key: pinned ? 'unpin' : 'pin',
+ label: t(pinned ? 'workingPanel.tabs.unpin' : 'workingPanel.tabs.pin'),
+ onClick: () => (pinned ? unpinTab(tab) : pinTab(tab)),
+ },
+ { type: 'divider' },
+ {
+ disabled: pinned,
+ icon: XIcon,
+ key: 'close',
+ label: t('workingPanel.tabs.close'),
+ onClick: () => closeTab(tab),
+ },
+ {
+ disabled: !hasClosable(otherTabs),
+ key: 'closeOthers',
+ label: t('workingPanel.tabs.closeOthers'),
+ onClick: () => closeTabs(otherTabs, tab),
+ },
+ { type: 'divider' },
+ {
+ disabled: !hasClosable(leftTabs),
+ key: 'closeLeft',
+ label: t('workingPanel.tabs.closeLeft'),
+ onClick: () => closeTabs(leftTabs, tab),
+ },
+ {
+ disabled: !hasClosable(rightTabs),
+ key: 'closeRight',
+ label: t('workingPanel.tabs.closeRight'),
+ onClick: () => closeTabs(rightTabs, tab),
+ },
+ ];
+ },
+ [closeTab, closeTabs, openedTabs, pinTab, pinnedTabsSet, t, unpinTab],
+ );
+ const overviewContextMenuItems = useMemo<ContextMenuItem[]>(
+ () => [
+ {
+ disabled: !openedTabs.some((tab) => !pinnedTabsSet.has(tab)),
+ key: 'closeOthers',
+ label: t('workingPanel.tabs.closeOthers'),
+ onClick: () => closeTabs(openedTabs),
+ },
+ ],
+ [closeTabs, openedTabs, pinnedTabsSet, t],
+ );
const tabsRef = useRef<HTMLDivElement>(null);
+ const pendingTabFocusRef = useRef<string | undefined>(undefined);
+ const pendingTabFocusTimeoutRef = useRef<number | undefined>(undefined);
- useEffect(() => {
+ const scrollActiveTabIntoView = useCallback(() => {
const tabs = tabsRef.current;
const activeTabButton = tabs?.querySelector<HTMLButtonElement>('button[aria-pressed="true"]');
- if (!tabs || !activeTabButton) return;
+ const activeTabItem = activeTabButton?.parentElement;
+ if (!tabs || !activeTabItem) return;
const tabsRect = tabs.getBoundingClientRect();
- const activeTabRect = activeTabButton.getBoundingClientRect();
- const isVisible = activeTabRect.left >= tabsRect.left && activeTabRect.right <= tabsRect.right;
+ const activeTabRect = activeTabItem.getBoundingClientRect();
+ if (activeTabRect.left < tabsRect.left) {
+ tabs.scrollLeft += activeTabRect.left - tabsRect.left;
+ } else if (activeTabRect.right > tabsRect.right) {
+ tabs.scrollLeft += activeTabRect.right - tabsRect.right;
+ }
+ }, []);
- if (!isVisible) {
- activeTabButton.scrollIntoView?.({ block: 'nearest', inline: 'nearest' });
+ const focusPendingTab = useCallback(() => {
+ const pendingTab = pendingTabFocusRef.current;
+ if (!pendingTab) return;
+
+ const tabButton = Array.from(
+ tabsRef.current?.querySelectorAll<HTMLButtonElement>('button[data-tab-key]') ?? [],
+ ).find((button) => button.dataset.tabKey === pendingTab);
+ if (!tabButton) return;
+
+ if (pendingTabFocusTimeoutRef.current !== undefined) {
+ window.clearTimeout(pendingTabFocusTimeoutRef.current);
+ pendingTabFocusTimeoutRef.current = undefined;
}
- }, [activeTab, availableTabsSignature, storedWidth]);
+ tabButton.focus();
+ pendingTabFocusRef.current = undefined;
+ }, []);
+
+ const requestTabFocus = useCallback(
+ (tab: string) => {
+ pendingTabFocusRef.current = tab;
+ if (pendingTabFocusTimeoutRef.current !== undefined) {
+ window.clearTimeout(pendingTabFocusTimeoutRef.current);
+ }
+ // Base UI normally resolves this through onOpenChangeComplete. A short
+ // fallback also covers background Electron windows where transition
+ // completion is frame-throttled indefinitely.
+ pendingTabFocusTimeoutRef.current = window.setTimeout(() => {
+ if (pendingTabFocusRef.current === tab) focusPendingTab();
+ }, 300);
+ },
+ [focusPendingTab],
+ );
+
+ useEffect(() => {
+ scrollActiveTabIntoView();
+ }, [
+ activeTab,
+ availableTabsSignature,
+ openedTabsSignature,
+ scrollActiveTabIntoView,
+ storedWidth,
+ tabRequest?.nonce,
+ ]);
+
+ useEffect(
+ () => () => {
+ if (pendingTabFocusTimeoutRef.current !== undefined) {
+ window.clearTimeout(pendingTabFocusTimeoutRef.current);
+ }
+ },
+ [],
+ );
// Review's tree-nav rail lives here (not inside Review) so the panel can widen
// when the two-pane layout is on. Hidden by default — the panel shows only the
@@ -239,6 +496,69 @@ const AgentWorkingSidebar = memo(() => {
}, [activeTab]);
const reviewTwoPane = activeTab === 'review' && reviewAvailable && showReviewTree;
const displayWidth = reviewTwoPane ? Math.max(storedWidth, TWO_PANE_MIN_WIDTH) : storedWidth;
+ const openMenuItems = useMemo<DropdownItem[]>(() => {
+ const itemOf = (key: string): DropdownItem | undefined => {
+ const tab = availableTabs.get(key);
+ if (!tab) return undefined;
+
+ return {
+ icon: <Icon icon={openedTabs.includes(key) ? CheckIcon : tab.icon} size={14} />,
+ key,
+ label: tab.label,
+ onClick: () => {
+ openTab(key);
+ requestTabFocus(key);
+ },
+ };
+ };
+ const group = (key: string, label: string, keys: string[]): DropdownItem | undefined => {
+ const children = keys.map(itemOf).filter((item): item is DropdownItem => Boolean(item));
+ return children.length ? { children, key, label, type: 'group' } : undefined;
+ };
+
+ const workspaceGroup = group('workspace', t('workingPanel.openMenu.workspace'), [
+ 'review',
+ 'files',
+ 'works',
+ 'resources',
+ ...businessTabs.map((tab) => tab.key),
+ ]);
+ const toolChildren = [itemOf('browser')].filter((item): item is DropdownItem => Boolean(item));
+ if (terminalAvailable) {
+ toolChildren.push({
+ icon: <Icon icon={SquareTerminalIcon} size={14} />,
+ key: 'terminal',
+ label: t('workingPanel.openMenu.terminal'),
+ onClick: () => toggleTerminalPanel(true),
+ });
+ }
+ const toolGroup = toolChildren.length
+ ? {
+ children: toolChildren,
+ key: 'tools',
+ label: t('workingPanel.openMenu.tools'),
+ type: 'group' as const,
+ }
+ : undefined;
+ const configurationGroup = group('configuration', t('workingPanel.openMenu.configuration'), [
+ 'params',
+ ]);
+
+ return [workspaceGroup, toolGroup, configurationGroup]
+ .filter((item): item is DropdownItem => Boolean(item))
+ .flatMap((item, index, items) =>
+ index < items.length - 1 ? [item, { type: 'divider' as const }] : [item],
+ );
+ }, [
+ availableTabs,
+ businessTabs,
+ openTab,
+ openedTabs,
+ requestTabFocus,
+ t,
+ terminalAvailable,
+ toggleTerminalPanel,
+ ]);
return (
<RightPanel
@@ -267,74 +587,46 @@ const AgentWorkingSidebar = memo(() => {
paddingInline={4}
>
<div className={styles.tabs} ref={tabsRef}>
- <button
- aria-pressed={activeTab === 'resources'}
- className={`${styles.tab} ${activeTab === 'resources' ? styles.tabActive : ''}`}
- type="button"
- onClick={() => setWorkingSidebarTab('resources')}
- >
- {t('workingPanel.space')}
- </button>
- <button
- aria-pressed={activeTab === 'works'}
- className={`${styles.tab} ${activeTab === 'works' ? styles.tabActive : ''}`}
- type="button"
- onClick={() => setWorkingSidebarTab('works')}
- >
- {t('workingPanel.works.title')}
- </button>
- {reviewAvailable && (
- <button
- aria-pressed={activeTab === 'review'}
- className={`${styles.tab} ${activeTab === 'review' ? styles.tabActive : ''}`}
- type="button"
- onClick={() => setWorkingSidebarTab('review')}
- >
- {t('workingPanel.review.title')}
- </button>
- )}
- {filesAvailable && (
- <button
- aria-pressed={activeTab === 'files'}
- className={`${styles.tab} ${activeTab === 'files' ? styles.tabActive : ''}`}
- type="button"
- onClick={() => setWorkingSidebarTab('files')}
- >
- {t('workingPanel.files.title')}
- </button>
- )}
- {browserAvailable && (
- <button
- aria-pressed={activeTab === 'browser'}
- className={`${styles.tab} ${activeTab === 'browser' ? styles.tabActive : ''}`}
- type="button"
- onClick={() => setWorkingSidebarTab('browser')}
- >
- {t('workingPanel.browser.title')}
- </button>
- )}
- {paramsAvailable && (
- <button
- aria-pressed={activeTab === 'params'}
- className={`${styles.tab} ${activeTab === 'params' ? styles.tabActive : ''}`}
- type="button"
- onClick={() => setWorkingSidebarTab('params')}
- >
- {t('settingModel.params.panel.tab', { ns: 'setting' })}
- </button>
- )}
- {businessTabs.map((tab) => (
- <button
- aria-pressed={activeTab === tab.key}
- className={`${styles.tab} ${activeTab === tab.key ? styles.tabActive : ''}`}
+ <WorkspaceTab
+ fixed
+ active={activeTab === 'overview'}
+ contextMenuItems={overviewContextMenuItems}
+ icon={LayoutDashboardIcon}
+ label={t('workingPanel.overview.title')}
+ tabKey={'overview'}
+ onSelect={() => openTab('overview')}
+ />
+ {displayedTabs.map((tab, index) => (
+ <WorkspaceTab
+ active={activeTab === tab.key}
+ closeLabel={t('workingPanel.tabs.close')}
+ contextMenuItems={createTabContextMenuItems(tab.key, index)}
+ icon={tab.icon}
key={tab.key}
- type="button"
- onClick={() => setWorkingSidebarTab(tab.key)}
- >
- {tab.label}
- </button>
+ label={tab.label}
+ pinned={pinnedTabsSet.has(tab.key)}
+ pinnedLabel={t('workingPanel.tabs.pinned')}
+ tabKey={tab.key}
+ onClose={pinnedTabsSet.has(tab.key) ? undefined : () => closeTab(tab.key)}
+ onSelect={() => openTab(tab.key)}
+ />
))}
</div>
+ <DropdownMenu
+ items={openMenuItems}
+ placement={'bottomRight'}
+ onOpenChangeComplete={(open) => {
+ if (open) return;
+ if (pendingTabFocusRef.current) focusPendingTab();
+ else scrollActiveTabIntoView();
+ }}
+ >
+ <ActionIcon
+ icon={PlusIcon}
+ size={DESKTOP_HEADER_ICON_SMALL_SIZE}
+ title={t('workingPanel.openMenu.title')}
+ />
+ </DropdownMenu>
<ActionIcon
className={styles.close}
icon={PanelRightCloseIcon}
@@ -343,9 +635,29 @@ const AgentWorkingSidebar = memo(() => {
/>
</Flexbox>
<Flexbox className={styles.body} width={'100%'}>
+ <Flexbox className={activeTab === 'overview' ? styles.pane : styles.paneHidden}>
+ <Overview
+ active={Boolean(showRightPanel) && activeTab === 'overview'}
+ deviceId={remoteDeviceId}
+ repoType={repoType}
+ workingDirectory={workingDirectory}
+ onOpenTab={openTab}
+ />
+ </Flexbox>
{paramsAvailable && activeTab === 'params' && (
<Flexbox className={styles.pane}>
- <ParamsSection />
+ <Suspense
+ fallback={
+ <Skeleton
+ active
+ className={styles.paramsLoading}
+ paragraph={{ rows: 6 }}
+ title={false}
+ />
+ }
+ >
+ <ParamsSection />
+ </Suspense>
</Flexbox>
)}
{reviewAvailable && (
@@ -382,10 +694,8 @@ const AgentWorkingSidebar = memo(() => {
))}
<Flexbox
className={activeTab === 'resources' ? styles.pane : styles.paneHidden}
- gap={8}
width={'100%'}
>
- <ProgressSection />
<ResourcesSection
deviceId={remoteDeviceId}
enabled={showRightPanel && activeTab === 'resources'}
diff --git a/src/store/global/action.test.ts b/src/store/global/action.test.ts
index 3b02e1ba700..dcc39daf7fd 100644
--- a/src/store/global/action.test.ts
+++ b/src/store/global/action.test.ts
@@ -62,6 +62,32 @@ describe('createPreferenceSlice', () => {
});
});
+ describe('setWorkingSidebarTab', () => {
+ it('emits a new request when the already-selected tab is requested again', () => {
+ const { result } = renderHook(() => useGlobalStore());
+
+ act(() => {
+ useGlobalStore.setState({
+ isStatusInit: true,
+ status: { ...initialState.status, workingSidebarTab: 'review' },
+ });
+ result.current.setWorkingSidebarTab('review');
+ });
+
+ const firstNonce = result.current.status.workingSidebarTabRequest?.nonce;
+
+ act(() => {
+ result.current.setWorkingSidebarTab('review');
+ });
+
+ expect(result.current.status.workingSidebarTab).toBe('review');
+ expect(result.current.status.workingSidebarTabRequest).toEqual({
+ nonce: (firstNonce ?? 0) + 1,
+ tab: 'review',
+ });
+ });
+ });
+
describe('openInBrowserTab / clearBrowserTabRequest', () => {
it('should raise a one-shot browser request and retire it once consumed', () => {
const { result } = renderHook(() => useGlobalStore());
diff --git a/src/store/global/actions/workspacePane.ts b/src/store/global/actions/workspacePane.ts
index a88259d5c46..763f8eea48d 100644
--- a/src/store/global/actions/workspacePane.ts
+++ b/src/store/global/actions/workspacePane.ts
@@ -148,8 +148,14 @@ export class GlobalWorkspacePaneActionImpl {
};
setWorkingSidebarTab = (tab: WorkingSidebarTab): void => {
- if (this.#get().status.workingSidebarTab === tab) return;
- this.#get().updateSystemStatus({ workingSidebarTab: tab }, n('setWorkingSidebarTab', tab));
+ const previousNonce = this.#get().status.workingSidebarTabRequest?.nonce ?? 0;
+ this.#get().updateSystemStatus(
+ {
+ workingSidebarTab: tab,
+ workingSidebarTabRequest: { nonce: previousNonce + 1, tab },
+ },
+ n('setWorkingSidebarTab', tab),
+ );
};
revealInFilesTab = (relativePath: string): void => {
diff --git a/src/store/global/initialState.ts b/src/store/global/initialState.ts
index 6a630d103b7..379700127db 100644
--- a/src/store/global/initialState.ts
+++ b/src/store/global/initialState.ts
@@ -39,7 +39,7 @@ export enum GroupSettingsTabs {
// business builds may register extra sidebar tabs, so any string key is accepted
export type WorkingSidebarTab =
- 'browser' | 'files' | 'params' | 'resources' | 'review' | (string & {});
+ 'browser' | 'files' | 'overview' | 'params' | 'resources' | 'review' | (string & {});
export const DEFAULT_RESOURCE_MANAGER_COLUMN_WIDTHS = {
date: 160,
@@ -353,6 +353,12 @@ export interface SystemStatus {
* can switch the panel to "review" when revealing the right panel.
*/
workingSidebarTab?: WorkingSidebarTab;
+ /**
+ * One-shot request to reveal a WorkingSidebar tab. The nonce makes repeated
+ * requests for the already-selected tab observable, so a closed on-demand tab
+ * can be reopened by Git/File/Browser entry points.
+ */
+ workingSidebarTabRequest?: { nonce: number; tab: WorkingSidebarTab };
/**
* Width of the agent chat right-side WorkingSidebar (space / params / files / …).
* Persisted so resizing survives remounts when navigating away and back.