🤯 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(goal): show the conversation goal as a workflow card in the working sidebar (#20120)
Arvin Xu5f227bcd2382
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex df0ded7c461..7ecd9b57fa4 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -2698,6 +2698,11 @@"workingPanel.files.views.changes": "Git Changes","workingPanel.files.views.project": "Project","workingPanel.files.views.title": "File View",+ "workingPanel.goal.collapse": "Show less",+ "workingPanel.goal.decision": "{{count}} decisions pending",+ "workingPanel.goal.more": "{{count}} more",+ "workingPanel.goal.title": "Goal",+ "workingPanel.goal.viewDetails": "View details","workingPanel.localFile.binary": "Binary file — preview unavailable","workingPanel.localFile.close": "Close","workingPanel.localFile.closeLeft": "Close to the Left",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex 0638d0fab82..0d7dadbecc4 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -2698,6 +2698,11 @@"workingPanel.files.views.changes": "Git 变更","workingPanel.files.views.project": "项目","workingPanel.files.views.title": "文件视图",+ "workingPanel.goal.collapse": "收起",+ "workingPanel.goal.decision": "{{count}} 个决策待处理",+ "workingPanel.goal.more": "还有 {{count}} 个",+ "workingPanel.goal.title": "目标",+ "workingPanel.goal.viewDetails": "查看详情","workingPanel.localFile.binary": "二进制文件 — 无法预览","workingPanel.localFile.close": "关闭","workingPanel.localFile.closeLeft": "关闭左侧",diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex c8177b4efef..1549cdafd88 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -2927,6 +2927,11 @@ export default {'workingPanel.overview.ports.none': 'None','workingPanel.overview.ports.openFailed': 'Could not open the link','workingPanel.overview.ports.revoke': 'Stop sharing',+ 'workingPanel.goal.collapse': 'Show less',+ 'workingPanel.goal.decision': '{{count}} decisions pending',+ 'workingPanel.goal.more': '{{count}} more',+ 'workingPanel.goal.viewDetails': 'View details',+ 'workingPanel.goal.title': 'Goal','workingPanel.overview.ports.revokeFailed': 'Could not stop sharing','workingPanel.overview.ports.revoked': 'Sharing stopped','workingPanel.overview.ports.title': 'Ports',diff --git a/src/features/Conversation/Messages/GoalTaskCard/deriveOperationGoals.ts b/src/features/Conversation/Messages/GoalTaskCard/deriveOperationGoals.tsindex 2b554e78061..e5cef0b055b 100644--- a/src/features/Conversation/Messages/GoalTaskCard/deriveOperationGoals.ts+++ b/src/features/Conversation/Messages/GoalTaskCard/deriveOperationGoals.ts@@ -91,8 +91,13 @@ const deriveCliGoal = (tool: ChatToolPayloadWithResult): OperationGoal[] => {* group — the builtin Goal tool for server-side agents, an `lh goal create`* shell call for heterogeneous ones. Like the edited-files aggregate, this is* display-only: no Work row is created and nothing enters Work Gallery/history.+ *+ * Takes the tools-bearing slice of a block, so callers can pass either one+ * group's parsed content blocks or whole messages from the conversation.*/-export const deriveOperationGoals = (blocks: AssistantContentBlock[] = []): OperationGoal[] => {+export const deriveOperationGoals = (+ blocks: { tools?: AssistantContentBlock['tools'] }[] = [],+): OperationGoal[] => {const goals = blocks.flatMap((block) =>(block.tools ?? []).flatMap((tool) => {const builtin = deriveBuiltinGoal(tool);diff --git a/src/features/Conversation/WorkingSidebar/GoalSection/GoalWorkflowCard.test.tsx b/src/features/Conversation/WorkingSidebar/GoalSection/GoalWorkflowCard.test.tsxnew file mode 100644index 00000000000..0192fd41c32--- /dev/null+++ b/src/features/Conversation/WorkingSidebar/GoalSection/GoalWorkflowCard.test.tsx@@ -0,0 +1,132 @@+import { render, screen } from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { GoalWorkflowCard } from './GoalWorkflowCard';+import type { GoalWorkflowView } from './useGoalSection';++const mocks = vi.hoisted(() => ({+ openGoal: vi.fn(),+}));++vi.mock('@/store/chat', () => ({+ useChatStore: (selector: (state: { openGoal: unknown }) => unknown) =>+ selector({ openGoal: mocks.openGoal }),+}));++vi.mock('@/features/AgentGoals/ProcessControl/AssigneeProfileAvatar', () => ({+ default: ({ agentId }: { agentId: string }) => <span data-testid={`assignee-${agentId}`} />,+}));++const baseView: GoalWorkflowView = {+ goalId: 'goal-1',+ pendingDecisions: 0,+ phase: 'running',+ rows: [+ { assigneeId: 'agt-1', id: 't1', state: 'done', title: '盘点凭证委托场景' },+ { assigneeId: 'agt-2', id: 't2', state: 'running', title: '设计代理输入交互' },+ { assigneeId: 'agt-3', id: 't3', state: 'running', title: '产出验证证据' },+ { id: 't4', state: 'pending', title: '整理场景分类' },+ { id: 't5', state: 'pending', title: '编写复现报告' },+ ],+ startedAt: null,+ summary: { done: 1, running: 2, total: 5 },+ title: '凭证委托场景全景',+};++describe('GoalWorkflowCard', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it('renders the actual-flow step track and the first batch of parallel rows', () => {+ render(<GoalWorkflowCard goal={baseView} />);++ // one segment per task, same encoding as the message card+ expect(screen.getByTestId('goal-workflow-step-track')).toBeInTheDocument();+ expect(screen.getByText('盘点凭证委托场景')).toBeInTheDocument();+ expect(screen.getByText('设计代理输入交互')).toBeInTheDocument();+ // collapsed to the visible cap: the 5th task hides behind "more"+ expect(screen.queryByText('编写复现报告')).not.toBeInTheDocument();+ expect(screen.getByText('workingPanel.goal.more')).toBeInTheDocument();+ expect(screen.getByTestId('assignee-agt-2')).toBeInTheDocument();+ // footer leads to details, not a bare fraction+ expect(screen.getByText('workingPanel.goal.viewDetails')).toBeInTheDocument();+ });++ it('honors initialCollapsed for older goals in multi-goal topics', () => {+ render(<GoalWorkflowCard initialCollapsed goal={baseView} />);++ expect(screen.getByText('盘点凭证委托场景')).not.toBeVisible();+ expect(screen.getByText('凭证委托场景全景')).toBeInTheDocument();+ });++ it('expands the hidden rows from "more" and collapses them again', async () => {+ const user = userEvent.setup();+ render(<GoalWorkflowCard goal={baseView} />);++ await user.click(screen.getByText('workingPanel.goal.more'));+ expect(screen.getByText('编写复现报告')).toBeInTheDocument();++ await user.click(screen.getByText('workingPanel.goal.collapse'));+ expect(screen.queryByText('编写复现报告')).not.toBeInTheDocument();+ });++ it('shows the decision gate and opens the portal when it is clicked', async () => {+ const user = userEvent.setup();+ render(<GoalWorkflowCard goal={{ ...baseView, pendingDecisions: 1 }} />);++ await user.click(screen.getByText('workingPanel.goal.decision'));+ expect(mocks.openGoal).toHaveBeenCalledWith('goal-1');+ });++ it('opens the goal portal when a task row is clicked', async () => {+ const user = userEvent.setup();+ render(<GoalWorkflowCard goal={baseView} />);++ await user.click(screen.getByText('产出验证证据'));+ expect(mocks.openGoal).toHaveBeenCalledWith('goal-1');+ });++ it('carries the phase word when the goal is not plainly running', () => {+ render(<GoalWorkflowCard goal={{ ...baseView, phase: 'waiting' }} />);+ expect(screen.getByText('goalTask.status.waiting')).toBeInTheDocument();+ });++ it('names the goal in the header so several cards stay distinguishable', () => {+ render(<GoalWorkflowCard goal={baseView} />);+ expect(screen.getByText('凭证委托场景全景')).toBeInTheDocument();+ });++ it('shows a loading placeholder instead of a fake 0/0 before the graph arrives', () => {+ render(+ <GoalWorkflowCard+ goal={{ ...baseView, loading: true, rows: [], summary: { done: 0, running: 0, total: 0 } }}+ />,+ );++ expect(screen.getByTestId('goal-workflow-loading')).toBeInTheDocument();+ expect(screen.queryByText('0/0')).not.toBeInTheDocument();+ expect(screen.queryByText('workingPanel.goal.stage.planning')).not.toBeInTheDocument();+ });++ it('shows a retryable error when the graph request fails', async () => {+ const user = userEvent.setup();+ const retry = vi.fn();+ render(+ <GoalWorkflowCard+ goal={{+ ...baseView,+ error: new Error('boom'),+ retry,+ rows: [],+ summary: { done: 0, running: 0, total: 0 },+ }}+ />,+ );++ expect(screen.queryByText('0/0')).not.toBeInTheDocument();+ await user.click(screen.getByText('error.retry'));+ expect(retry).toHaveBeenCalledTimes(1);+ });+});diff --git a/src/features/Conversation/WorkingSidebar/GoalSection/GoalWorkflowCard.tsx b/src/features/Conversation/WorkingSidebar/GoalSection/GoalWorkflowCard.tsxnew file mode 100644index 00000000000..7e05fd4c12f--- /dev/null+++ b/src/features/Conversation/WorkingSidebar/GoalSection/GoalWorkflowCard.tsx@@ -0,0 +1,470 @@+'use client';++import { Flexbox, Icon } from '@lobehub/ui';+import { Button, Skeleton } from '@lobehub/ui/base-ui';+import { createStaticStyles, cssVar, cx } from 'antd-style';+import {+ ArrowUpRight,+ CheckCircle2,+ ChevronDown,+ ChevronUp,+ CircleSlash,+ Clock3,+ LoaderCircle,+ Workflow,+} from 'lucide-react';+import { type KeyboardEvent, memo, useCallback, useId, useState } from 'react';+import { useTranslation } from 'react-i18next';++import AsyncError from '@/components/AsyncError';+import AssigneeProfileAvatar from '@/features/AgentGoals/ProcessControl/AssigneeProfileAvatar';+import { buildGoalStepSegments } from '@/features/Conversation/Messages/GoalTaskCard/goalTaskProgress';+import { useChatStore } from '@/store/chat';++import {+ type GoalWorkflowRow,+ MAX_VISIBLE_WORKFLOW_ROWS,+ sliceVisibleWorkflowRows,+ toSegmentStatuses,+} from './goalWorkflowView';+import { type GoalWorkflowView, useGoalWorkflow } from './useGoalSection';++const styles = createStaticStyles(({ css, cssVar }) => ({+ collapsed: css`+ display: none;+ `,+ count: css`+ flex-shrink: 0;++ padding-block: 1px;+ padding-inline: 6px;+ border-radius: 4px;++ font-family: ${cssVar.fontFamilyCode};+ font-size: 11px;+ color: ${cssVar.colorTextSecondary};++ background: ${cssVar.colorFillSecondary};+ `,+ decisionRow: css`+ cursor: pointer;++ margin-block: 2px 6px;+ padding-block: 5px;+ padding-inline: 8px;+ border: 1px solid ${cssVar.colorWarningBorder};+ border-radius: 6px;++ font-size: 12px;+ color: ${cssVar.colorWarning};++ background: ${cssVar.colorWarningBg};++ &:hover {+ background: ${cssVar.colorWarningBorder};+ }+ `,+ footer: css`+ padding-block: 6px 2px;+ `,+ headerRow: css`+ cursor: pointer;+ user-select: none;++ 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};+ outline-offset: 2px;+ }+ `,+ lessRow: css`+ cursor: pointer;++ justify-content: center;++ padding-block: 4px;++ font-size: 12px;+ color: ${cssVar.colorTextTertiary};++ &:hover {+ color: ${cssVar.colorText};+ }+ `,+ moreRow: css`+ cursor: pointer;++ justify-content: center;++ margin-block-start: 2px;+ padding-block: 5px;+ border: 1px dashed ${cssVar.colorBorder};+ border-radius: 6px;++ font-size: 12px;+ color: ${cssVar.colorTextSecondary};++ &:hover {+ color: ${cssVar.colorText};+ background: ${cssVar.colorFillQuaternary};+ }+ `,+ progress: css`+ overflow: hidden;+ flex: 1;++ height: 4px;+ border-radius: 2px;++ background: ${cssVar.colorFillSecondary};+ `,+ progressFill: css`+ height: 100%;+ border-radius: inherit;+ background: ${cssVar.colorSuccess};+ transition: width 0.25s ${cssVar.motionEaseOut};+ `,+ row: css`+ cursor: pointer;+ padding-block: 5px;+ padding-inline: 8px;+ border-radius: 6px;++ &:hover {+ background: ${cssVar.colorFillTertiary};+ }++ &:focus-visible {+ outline: 2px solid ${cssVar.colorPrimaryBorder};+ outline-offset: -2px;+ }+ `,+ loading: css`+ padding-block: 4px 8px;+ padding-inline: 10px;+ `,+ segActive: css`+ background: ${cssVar.colorInfo};+ animation: sidebar-goal-step-pulse 1.6s ${cssVar.motionEaseInOut} infinite;+ `,+ segDone: css`+ background: ${cssVar.colorSuccess};+ `,+ segPending: css`+ background: ${cssVar.colorFillSecondary};+ `,+ segment: css`+ flex: 1;+ height: 4px;+ border-radius: 2px;+ `,+ stepTrack: css`+ display: flex;+ gap: 3px;++ height: 4px;+ margin-block: 2px 8px;+ margin-inline: 10px;++ @keyframes sidebar-goal-step-pulse {+ 0%,+ 100% {+ opacity: 1;+ }++ 50% {+ opacity: 0.45;+ }+ }+ `,+ sectionTitle: css`+ overflow: hidden;+ flex: 1;++ min-width: 0;++ font-size: 13px;+ font-weight: 500;+ color: ${cssVar.colorText};+ text-overflow: ellipsis;+ white-space: nowrap;+ `,+}));++const STATE_VISUALS = {+ done: { color: cssVar.colorSuccess, icon: CheckCircle2 },+ pending: { color: cssVar.colorTextQuaternary, icon: CircleSlash },+ running: { color: cssVar.colorInfo, icon: LoaderCircle, spin: true },+ waiting: { color: cssVar.colorWarning, icon: Clock3 },+} as const;++const WorkflowRow = memo<{ onOpen: () => void; row: GoalWorkflowRow }>(({ row, onOpen }) => {+ const visual = STATE_VISUALS[row.state];+ const handleKeyDown = useCallback(+ (event: KeyboardEvent<HTMLDivElement>) => {+ if (event.key !== 'Enter' && event.key !== ' ') return;+ event.preventDefault();+ onOpen();+ },+ [onOpen],+ );+ return (+ <Flexbox+ horizontal+ align={'center'}+ className={styles.row}+ gap={8}+ role={'button'}+ tabIndex={0}+ onClick={onOpen}+ onKeyDown={handleKeyDown}+ >+ {row.assigneeId ? (+ <AssigneeProfileAvatar agentId={row.assigneeId} size={20} />+ ) : (+ <CircleSlash size={14} style={{ color: cssVar.colorTextQuaternary, flexShrink: 0 }} />+ )}+ <span+ style={{+ flex: 1,+ fontSize: 13,+ minWidth: 0,+ overflow: 'hidden',+ textOverflow: 'ellipsis',+ whiteSpace: 'nowrap',+ }}+ >+ {row.title}+ </span>+ <Icon+ icon={visual.icon}+ size={14}+ spin={'spin' in visual && visual.spin}+ style={{ color: visual.color, flexShrink: 0 }}+ />+ </Flexbox>+ );+});++WorkflowRow.displayName = 'GoalWorkflowRow';++const SEGMENT_CLASS = {+ active: styles.segActive,+ done: styles.segDone,+ pending: styles.segPending,+} as const;++/** The goal's actual flow — one segment per Task, same encoding as the message card. */+const StepTrack = memo<{ rows: GoalWorkflowRow[] }>(({ rows }) => {+ const segments = buildGoalStepSegments(toSegmentStatuses(rows));+ if (segments.length === 0) return null;++ return (+ <div aria-hidden className={styles.stepTrack} data-testid={'goal-workflow-step-track'}>+ {segments.map((state, index) => (+ <div className={cx(styles.segment, SEGMENT_CLASS[state])} key={index} />+ ))}+ </div>+ );+});++StepTrack.displayName = 'GoalWorkflowStepTrack';++/**+ * One conversation goal as a workflow card: the goal's own Tasks as a step+ * track and parallel rows with their assignees. The same pointer the+ * message-area card derives, read at topic scope — the sidebar is where+ * parallel state gets room to breathe.+ */+const GoalWorkflowCard = memo<{+ goal: GoalWorkflowView;+ /** Multi-goal topics keep only the newest card open by default. */+ initialCollapsed?: boolean;+}>(({ goal, initialCollapsed = false }) => {+ const { t } = useTranslation('chat');+ const openGoalPortal = useChatStore((s) => s.openGoal);+ const [collapsed, setCollapsed] = useState(initialCollapsed);+ const [rowsExpanded, setRowsExpanded] = useState(false);+ const bodyId = useId();++ const open = useCallback(() => openGoalPortal(goal.goalId), [goal.goalId, openGoalPortal]);+ const toggleCollapsed = useCallback(() => setCollapsed((prev) => !prev), []);+ const handleHeaderKeyDown = useCallback(+ (event: KeyboardEvent<HTMLDivElement>) => {+ if (event.key !== 'Enter' && event.key !== ' ') return;+ event.preventDefault();+ toggleCollapsed();+ },+ [toggleCollapsed],+ );++ const rows = sliceVisibleWorkflowRows(goal.rows, rowsExpanded);+ const hiddenCount = goal.rows.length - rows.length;+ const percent =+ goal.summary.total > 0 ? Math.round((goal.summary.done / goal.summary.total) * 100) : 0;+ // Without a snapshot there is no honest progress to show — no 0/0 placeholder.+ const hasSnapshot = !goal.loading && !goal.error;+ const title = goal.title || t('workingPanel.goal.title');++ return (+ <div>+ <Flexbox+ horizontal+ align={'center'}+ aria-controls={bodyId}+ aria-expanded={!collapsed}+ className={styles.headerRow}+ gap={8}+ justify="space-between"+ role={'button'}+ tabIndex={0}+ onClick={toggleCollapsed}+ onKeyDown={handleHeaderKeyDown}+ >+ <Flexbox horizontal align={'center'} gap={8} style={{ flex: 1, minWidth: 0 }}>+ <Icon icon={Workflow} size={14} style={{ color: cssVar.colorTextSecondary }} />+ <span className={styles.sectionTitle} title={title}>+ {title}+ </span>+ {hasSnapshot && goal.phase !== 'running' && (+ <span className={styles.count}>{t(`goalTask.status.${goal.phase}`)}</span>+ )}+ {hasSnapshot && (+ <span className={styles.count}>+ {goal.summary.done}/{goal.summary.total}+ </span>+ )}+ </Flexbox>+ <Icon+ icon={collapsed ? ChevronDown : ChevronUp}+ size={14}+ style={{ color: cssVar.colorTextTertiary, flexShrink: 0 }}+ />+ </Flexbox>++ <div className={cx(collapsed && styles.collapsed)} id={bodyId}>+ {goal.error ? (+ <div className={styles.loading}>+ <AsyncError error={goal.error} variant={'inline'} onRetry={goal.retry} />+ </div>+ ) : goal.loading ? (+ <Flexbox className={styles.loading} data-testid={'goal-workflow-loading'} gap={8}>+ <Skeleton height={12} radius={4} />+ <Skeleton height={28} radius={6} />+ <Skeleton height={28} radius={6} />+ </Flexbox>+ ) : (+ <>+ <StepTrack rows={goal.rows} />++ {goal.pendingDecisions > 0 && (+ <Flexbox+ horizontal+ align={'center'}+ className={styles.decisionRow}+ gap={6}+ justify={'space-between'}+ role={'button'}+ tabIndex={0}+ onClick={open}+ onKeyDown={(event) => {+ if (event.key !== 'Enter' && event.key !== ' ') return;+ event.preventDefault();+ open();+ }}+ >+ {t('workingPanel.goal.decision', { count: goal.pendingDecisions })}+ <ArrowUpRight size={13} />+ </Flexbox>+ )}++ <div style={{ paddingInline: 4 }}>+ {rows.map((row) => (+ <WorkflowRow key={row.id} row={row} onOpen={open} />+ ))}+ {hiddenCount > 0 ? (+ <Flexbox+ horizontal+ align={'center'}+ className={styles.moreRow}+ gap={4}+ role={'button'}+ tabIndex={0}+ onClick={() => setRowsExpanded(true)}+ onKeyDown={(event) => {+ if (event.key !== 'Enter' && event.key !== ' ') return;+ event.preventDefault();+ setRowsExpanded(true);+ }}+ >+ {t('workingPanel.goal.more', { count: hiddenCount })}+ <ChevronDown size={13} />+ </Flexbox>+ ) : (+ rowsExpanded &&+ goal.rows.length > MAX_VISIBLE_WORKFLOW_ROWS && (+ <Flexbox+ horizontal+ align={'center'}+ className={styles.lessRow}+ role={'button'}+ tabIndex={0}+ onClick={() => setRowsExpanded(false)}+ onKeyDown={(event) => {+ if (event.key !== 'Enter' && event.key !== ' ') return;+ event.preventDefault();+ setRowsExpanded(false);+ }}+ >+ {t('workingPanel.goal.collapse')}+ </Flexbox>+ )+ )}+ </div>++ <Flexbox+ horizontal+ align={'center'}+ className={styles.footer}+ gap={8}+ style={{ paddingInline: 10 }}+ >+ <div className={styles.progress}>+ <div className={styles.progressFill} style={{ width: `${percent}%` }} />+ </div>+ <Button outdent={'end'} size={'small'} type={'text'} onClick={open}>+ {t('workingPanel.goal.viewDetails')}+ </Button>+ </Flexbox>+ </>+ )}+ </div>+ </div>+ );+});++GoalWorkflowCard.displayName = 'GoalWorkflowCard';++const GoalWorkflowCardContainer = memo<{+ criteriaCount: number;+ goalId: string;+ initialCollapsed?: boolean;+ name: string;+}>(({ criteriaCount, goalId, initialCollapsed, name }) => {+ const view = useGoalWorkflow({ criteriaCount, goalId, name });+ return <GoalWorkflowCard goal={view} initialCollapsed={initialCollapsed} />;+});++GoalWorkflowCardContainer.displayName = 'GoalWorkflowCardContainer';++export { GoalWorkflowCard };+export default GoalWorkflowCardContainer;diff --git a/src/features/Conversation/WorkingSidebar/GoalSection/goalWorkflowView.test.ts b/src/features/Conversation/WorkingSidebar/GoalSection/goalWorkflowView.test.tsnew file mode 100644index 00000000000..963a1ddf1d9--- /dev/null+++ b/src/features/Conversation/WorkingSidebar/GoalSection/goalWorkflowView.test.ts@@ -0,0 +1,95 @@+import { describe, expect, it } from 'vitest';++import type { GoalStep } from '@/features/Conversation/Messages/GoalTaskCard/goalTaskProgress';++import {+ buildWorkflowRows,+ MAX_VISIBLE_WORKFLOW_ROWS,+ mergeTopicGoals,+ sliceVisibleWorkflowRows,+ summarizeWorkflow,+ toSegmentStatuses,+} from './goalWorkflowView';++const step = (id: string, status: string, title = id) => ({+ id,+ status: status as GoalStep['status'],+ title,+});++describe('mergeTopicGoals', () => {+ it('appends topic-linked goals that no message derived, deduped by id', () => {+ const merged = mergeTopicGoals(+ [{ criteriaCount: 2, goalId: 'goal-tool', name: 'From tool' }],+ [+ { goal: { id: 'goal-tool', title: 'Persisted copy' } },+ { goal: { id: 'goal-cli', title: 'Created by lh' } },+ { goal: { id: 'goal-cli', title: 'Duplicate row' } },+ ],+ );++ expect(merged).toEqual([+ { criteriaCount: 2, goalId: 'goal-tool', name: 'From tool' },+ { criteriaCount: 0, goalId: 'goal-cli', name: 'Created by lh' },+ ]);+ });++ it('returns the derived goals untouched when nothing is persisted yet', () => {+ const derived = [{ criteriaCount: 1, goalId: 'goal-a', name: 'A' }];+ expect(mergeTopicGoals(derived, undefined)).toEqual(derived);+ });+});++describe('buildWorkflowRows', () => {+ it('maps node statuses to row states and attaches assignees', () => {+ const rows = buildWorkflowRows(+ [+ step('a', 'resolved'),+ step('b', 'active'),+ step('c', 'waiting'),+ step('d', 'proposed'),+ step('e', 'rejected'),+ ],+ { b: 'agt-2' },+ );++ expect(rows.map((row) => row.state)).toEqual(['done', 'running', 'waiting', 'pending', 'done']);+ expect(rows[1].assigneeId).toBe('agt-2');+ expect(rows[0].assigneeId).toBeUndefined();+ });+});++describe('toSegmentStatuses', () => {+ it('maps row states to graph node statuses for the step track', () => {+ const rows = buildWorkflowRows([+ step('a', 'resolved'),+ step('b', 'active'),+ step('c', 'waiting'),+ step('d', 'proposed'),+ ]);++ expect(toSegmentStatuses(rows)).toEqual(['resolved', 'active', 'waiting', 'proposed']);+ });+});++describe('sliceVisibleWorkflowRows', () => {+ it('caps collapsed rows at the visible maximum', () => {+ const rows = buildWorkflowRows(Array.from({ length: 6 }, (_, i) => step(`t${i}`, 'proposed')));++ expect(sliceVisibleWorkflowRows(rows, false)).toHaveLength(MAX_VISIBLE_WORKFLOW_ROWS);+ expect(sliceVisibleWorkflowRows(rows, true)).toHaveLength(6);+ });+});++describe('summarizeWorkflow', () => {+ it('counts done and running rows for the header summary', () => {+ const rows = buildWorkflowRows([+ step('a', 'resolved'),+ step('b', 'active'),+ step('c', 'active'),+ step('d', 'proposed'),+ ]);++ expect(summarizeWorkflow(rows)).toEqual({ done: 1, running: 2, total: 4 });+ });+});diff --git a/src/features/Conversation/WorkingSidebar/GoalSection/goalWorkflowView.ts b/src/features/Conversation/WorkingSidebar/GoalSection/goalWorkflowView.tsnew file mode 100644index 00000000000..5162bac7076--- /dev/null+++ b/src/features/Conversation/WorkingSidebar/GoalSection/goalWorkflowView.ts@@ -0,0 +1,87 @@+import type { GoalNodeStatus } from '@lobechat/types';++import type { OperationGoal } from '@/features/Conversation/Messages/GoalTaskCard/deriveOperationGoals';+import type { GoalStep } from '@/features/Conversation/Messages/GoalTaskCard/goalTaskProgress';++export type GoalWorkflowRowState = 'done' | 'running' | 'waiting' | 'pending';++export interface GoalWorkflowRow {+ assigneeId?: string;+ id: string;+ state: GoalWorkflowRowState;+ title: string;+}++const CLOSED_STEP_STATUSES = new Set(['rejected', 'resolved', 'retired']);++/** Task nodes as display rows: closed steps read as done, `active` as running. */+export const buildWorkflowRows = (+ nodes: { id: string; status: GoalStep['status']; title: string }[],+ assignees?: Record<string, string>,+): GoalWorkflowRow[] =>+ nodes.map((node) => ({+ assigneeId: assignees?.[node.id],+ id: node.id,+ state: CLOSED_STEP_STATUSES.has(node.status)+ ? 'done'+ : node.status === 'active'+ ? 'running'+ : node.status === 'waiting'+ ? 'waiting'+ : 'pending',+ title: node.title,+ }));++/** Row states as graph node statuses, so the step track can reuse the+ * message card's segmentation (cap + conservative slicing) unchanged. */+export const toSegmentStatuses = (rows: GoalWorkflowRow[]): GoalNodeStatus[] =>+ rows.map((row) =>+ row.state === 'done'+ ? 'resolved'+ : row.state === 'running'+ ? 'active'+ : row.state === 'waiting'+ ? 'waiting'+ : 'proposed',+ );++export interface GoalWorkflowSummary {+ done: number;+ running: number;+ total: number;+}++export const summarizeWorkflow = (rows: GoalWorkflowRow[]): GoalWorkflowSummary => ({+ done: rows.filter((row) => row.state === 'done').length,+ running: rows.filter((row) => row.state === 'running').length,+ total: rows.length,+});++/** A chat sidebar keeps at most this many rows before folding into "N more". */+export const MAX_VISIBLE_WORKFLOW_ROWS = 4;++export const sliceVisibleWorkflowRows = (+ rows: GoalWorkflowRow[],+ expanded: boolean,+): GoalWorkflowRow[] => (expanded ? rows : rows.slice(0, MAX_VISIBLE_WORKFLOW_ROWS));++/**+ * Every goal the conversation created: the ones derived from its messages+ * (builtin `createGoal` results, `lh goal create` shell output) plus the goal+ * rows linked to the topic — a CLI agent's `lh goal create --conversation` can+ * leave no parseable tool result behind. Message-derived goals keep their+ * position and richer metadata; persisted-only goals follow, deduped by id.+ */+export const mergeTopicGoals = (+ derived: OperationGoal[],+ persisted: { goal: { id: string; title?: string | null } }[] = [],+): OperationGoal[] => {+ const seen = new Set(derived.map((goal) => goal.goalId));+ const linked = persisted.flatMap(({ goal }) => {+ if (seen.has(goal.id)) return [];+ seen.add(goal.id);+ return [{ criteriaCount: 0, goalId: goal.id, name: goal.title?.trim() || goal.id }];+ });++ return [...derived, ...linked];+};diff --git a/src/features/Conversation/WorkingSidebar/GoalSection/index.test.tsx b/src/features/Conversation/WorkingSidebar/GoalSection/index.test.tsxnew file mode 100644index 00000000000..3d158f74d83--- /dev/null+++ b/src/features/Conversation/WorkingSidebar/GoalSection/index.test.tsx@@ -0,0 +1,28 @@+import { render, screen } from '@testing-library/react';+import { describe, expect, it, vi } from 'vitest';++import GoalSection from './index';++vi.mock('./GoalWorkflowCard', () => ({+ default: ({ initialCollapsed }: { initialCollapsed?: boolean }) => (+ <div data-collapsed={initialCollapsed ? 'true' : 'false'} data-testid={'goal-card'} />+ ),+}));++vi.mock('./useGoalSection', () => ({+ useTopicOperationGoals: () => [+ { criteriaCount: 5, goalId: 'goal-old', name: '旧目标' },+ { criteriaCount: 3, goalId: 'goal-new', name: '新目标' },+ ],+}));++describe('GoalSection', () => {+ it('keeps only the newest goal card open by default', () => {+ render(<GoalSection />);++ const cards = screen.getAllByTestId('goal-card');+ expect(cards).toHaveLength(2);+ expect(cards[0]).toHaveAttribute('data-collapsed', 'true');+ expect(cards[1]).toHaveAttribute('data-collapsed', 'false');+ });+});diff --git a/src/features/Conversation/WorkingSidebar/GoalSection/index.tsx b/src/features/Conversation/WorkingSidebar/GoalSection/index.tsxnew file mode 100644index 00000000000..234a3d951b5--- /dev/null+++ b/src/features/Conversation/WorkingSidebar/GoalSection/index.tsx@@ -0,0 +1,34 @@+import { memo } from 'react';++import GoalWorkflowCardContainer from './GoalWorkflowCard';+import { useTopicOperationGoals } from './useGoalSection';++/**+ * The conversation's Goals as workflow cards in the working sidebar — one card+ * per goal the topic created. A topic with several goals keeps only the newest+ * card open by default, so the panel leads with what just moved. Topics that+ * created no goal render nothing.+ */+const GoalSection = memo<{ className?: string }>(({ className }) => {+ const goals = useTopicOperationGoals();++ if (goals.length === 0) return null;++ return (+ <div className={className}>+ {goals.map((goal, index) => (+ <GoalWorkflowCardContainer+ criteriaCount={goal.criteriaCount}+ goalId={goal.goalId}+ initialCollapsed={index < goals.length - 1}+ key={goal.goalId}+ name={goal.name}+ />+ ))}+ </div>+ );+});++GoalSection.displayName = 'WorkingSidebarGoalSection';++export default GoalSection;diff --git a/src/features/Conversation/WorkingSidebar/GoalSection/useGoalSection.ts b/src/features/Conversation/WorkingSidebar/GoalSection/useGoalSection.tsnew file mode 100644index 00000000000..b3718aebffb--- /dev/null+++ b/src/features/Conversation/WorkingSidebar/GoalSection/useGoalSection.ts@@ -0,0 +1,110 @@+import { useMemo } from 'react';++import {+ deriveOperationGoals,+ type OperationGoal,+} from '@/features/Conversation/Messages/GoalTaskCard/deriveOperationGoals';+import {+ getGoalTaskProgress,+ type GoalTaskPhase,+} from '@/features/Conversation/Messages/GoalTaskCard/goalTaskProgress';+import { useChatStore } from '@/store/chat';+import { operationSelectors } from '@/store/chat/selectors';+import { messageMapKey } from '@/store/chat/utils/messageMapKey';+import { goalSelectors, useGoalStore } from '@/store/goal';++import { isGoalRequestGenerating } from '../../ChatInput/LinkedGoalTray/linkedGoals';+import { useAgentContext } from '../../useAgentContext';+import {+ buildWorkflowRows,+ type GoalWorkflowRow,+ type GoalWorkflowSummary,+ mergeTopicGoals,+ summarizeWorkflow,+} from './goalWorkflowView';++/**+ * Every Goal a conversation created — the sidebar shows one card per goal.+ * Message-derived goals are merged with the goal rows linked to the topic, so a+ * goal a CLI agent created without a parseable tool result still gets a card.+ */+export const useTopicOperationGoals = (): OperationGoal[] => {+ const context = useAgentContext();+ const chatKey = messageMapKey(context);+ const dbMessages = useChatStore((s) => s.dbMessagesMap[chatKey]);+ // Discover a goal the in-flight `/goal` run is creating, like the composer tray.+ const goalRequestGenerating = useChatStore((s) =>+ isGoalRequestGenerating(+ s.dbMessagesMap[chatKey],+ operationSelectors.isAgentRuntimeRunningByContext(context)(s),+ ),+ );+ const useFetchTopicGoals = useGoalStore((s) => s.useFetchTopicGoals);+ const { data } = useFetchTopicGoals(context.topicId, goalRequestGenerating);++ return useMemo(+ () => mergeTopicGoals(deriveOperationGoals(dbMessages ?? []), data?.goals),+ [dbMessages, data],+ );+};++export interface GoalWorkflowView {+ /** The graph request failed before any snapshot arrived. */+ error?: unknown;+ goalId: string;+ /** No snapshot yet and the first graph request is in flight. */+ loading?: boolean;+ pendingDecisions: number;+ phase: GoalTaskPhase;+ /** Re-request the graph after a failure. */+ retry?: () => void;+ rows: GoalWorkflowRow[];+ startedAt?: Date | null;+ summary: GoalWorkflowSummary;+ title?: string;+}++/**+ * One goal's live workflow view for the sidebar card: the graph snapshot →+ * lifecycle phase, ordered task rows (with their assignees) and open decision+ * gates. The card only holds the goal id, so everything is fetched here,+ * polling while the coordinator advances the graph.+ */+export const useGoalWorkflow = (goal: OperationGoal): GoalWorkflowView => {+ const useFetchGoalGraph = useGoalStore((s) => s.useFetchGoalGraph);+ const { error, isLoading, mutate } = useFetchGoalGraph(goal.goalId);+ const snapshot = useGoalStore(goalSelectors.goalGraph(goal.goalId));++ const taskNodes = snapshot?.nodes.filter((node) => node.kind === 'task') ?? [];+ // The graph numbers Tasks in creation order; the workflow rows must read the same.+ const orderedTaskNodes = [...taskNodes].sort(+ (a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime(),+ );++ const progress = getGoalTaskProgress({+ criteriaCount: goal.criteriaCount,+ pendingDecisions:+ snapshot?.decisions.filter((decision) => decision.status === 'pending').length ?? 0,+ status: snapshot?.goal.status,+ taskDone: taskNodes.filter((node) => ['rejected', 'resolved', 'retired'].includes(node.status))+ .length,+ taskTotal: taskNodes.length,+ });+ const rows = buildWorkflowRows(orderedTaskNodes, snapshot?.assignees);++ return {+ // Like the Goal portal: only a missing snapshot turns into loading / error,+ // so a failed background poll keeps showing the last known graph.+ error: snapshot ? undefined : error,+ goalId: goal.goalId,+ loading: !snapshot && !error && isLoading,+ pendingDecisions:+ snapshot?.decisions.filter((decision) => decision.status === 'pending').length ?? 0,+ phase: progress.phase,+ retry: () => void mutate(),+ rows,+ startedAt: snapshot?.goal.startedAt,+ summary: summarizeWorkflow(rows),+ title: snapshot?.goal.title ?? goal.name,+ };+};diff --git a/src/features/Conversation/WorkingSidebar/Overview/index.tsx b/src/features/Conversation/WorkingSidebar/Overview/index.tsxindex 30cdf18cee1..1fb1de2edc7 100644--- a/src/features/Conversation/WorkingSidebar/Overview/index.tsx+++ b/src/features/Conversation/WorkingSidebar/Overview/index.tsx@@ -46,6 +46,7 @@ import {import { useUserStore } from '@/store/user';import { labPreferSelectors } from '@/store/user/selectors';+import GoalSection from '../GoalSection';import ProgressSection from '../ProgressSection';import { collectChangeStats, isLinkedWorktreeCheckout, shouldShowCiLabel } from './overviewData';import OverviewHeader from './OverviewHeader';@@ -434,6 +435,7 @@ const Overview = memo<OverviewProps>(/>)}+ <GoalSection className={sectionStyles.section} /><ProgressSection className={sectionStyles.section} />{visibleWorks.length > 0 && (