🤯 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): stage track + plan chain on the /goal card (#20173)
Arvin Xu06f288edd150
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex 72bd5460bdf..5df61e7ef17 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -955,19 +955,24 @@"goalProcess.tag.retired": "Retired","goalProcess.tag.verifying": "Verifying","goalTask.checks": "{{passed}}/{{total}} checks passed",- "goalTask.currentStep": "Current: {{title}}",- "goalTask.nextStep": "Up next: {{title}}",+ "goalTask.plan.drafting": "Breaking the goal into tasks…","goalTask.round": "Round {{current}}","goalTask.roundWithBudget": "Round {{current}}/{{total}}",+ "goalTask.stage.achieved": "Achieve",+ "goalTask.stage.executing": "Execute",+ "goalTask.stage.planning": "Plan",+ "goalTask.stage.verifying": "Accept","goalTask.status.achieved": "Achieved","goalTask.status.canceled": "Canceled","goalTask.status.error": "Needs attention","goalTask.status.paused": "Paused",+ "goalTask.status.planning": "Planning","goalTask.status.repairing": "Repairing","goalTask.status.review": "Pending acceptance","goalTask.status.running": "Executing","goalTask.status.verifying": "Verifying","goalTask.status.waiting": "Waiting",+ "goalTask.step.queued": "Not started","goalTask.tasksDone": "{{passed}}/{{total}} tasks done","goalTurn.authorUser": "User","goalTurn.continuation": "Why planning reopened",diff --git a/locales/en-US/plugin.json b/locales/en-US/plugin.jsonindex 491c4462fc1..47e4ffc2872 100644--- a/locales/en-US/plugin.json+++ b/locales/en-US/plugin.json@@ -72,6 +72,12 @@"builtins.github.render.error": "Error","builtins.github.render.rawResult": "Raw result","builtins.github.render.updatedAt": "Updated {{time}}",+ "builtins.goalCommand.create.completed": "Goal created",+ "builtins.goalCommand.create.failed": "Couldn't create goal",+ "builtins.goalCommand.create.loading": "Creating goal",+ "builtins.goalCommand.plan.completed": "Goal plan submitted",+ "builtins.goalCommand.plan.failed": "Couldn't submit goal plan",+ "builtins.goalCommand.plan.loading": "Planning goal tasks","builtins.linear.render.empty": "No {{collection}} found","builtins.linear.render.updatedAt": "Updated {{time}}","builtins.lobe-activator.apiName.activateTools": "Activate Tools",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex 62f21f0a5cf..ac5be50efd9 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -955,19 +955,24 @@"goalProcess.tag.retired": "已放弃","goalProcess.tag.verifying": "验证中","goalTask.checks": "{{passed}}/{{total}} 项通过",- "goalTask.currentStep": "当前:{{title}}",- "goalTask.nextStep": "下一步:{{title}}",+ "goalTask.plan.drafting": "正在拆解任务…","goalTask.round": "第 {{current}} 轮","goalTask.roundWithBudget": "第 {{current}}/{{total}} 轮",+ "goalTask.stage.achieved": "达成",+ "goalTask.stage.executing": "执行",+ "goalTask.stage.planning": "规划",+ "goalTask.stage.verifying": "验收","goalTask.status.achieved": "已达成","goalTask.status.canceled": "已取消","goalTask.status.error": "需要处理","goalTask.status.paused": "已暂停",+ "goalTask.status.planning": "规划中","goalTask.status.repairing": "修复中","goalTask.status.review": "待验收","goalTask.status.running": "执行中","goalTask.status.verifying": "验证中","goalTask.status.waiting": "等待中",+ "goalTask.step.queued": "待开始","goalTask.tasksDone": "{{passed}}/{{total}} 项任务完成","goalTurn.authorUser": "用户","goalTurn.continuation": "重新规划的原因",diff --git a/locales/zh-CN/plugin.json b/locales/zh-CN/plugin.jsonindex db88b733b49..72f830bcc96 100644--- a/locales/zh-CN/plugin.json+++ b/locales/zh-CN/plugin.json@@ -72,6 +72,12 @@"builtins.github.render.error": "错误","builtins.github.render.rawResult": "原始结果","builtins.github.render.updatedAt": "更新于 {{time}}",+ "builtins.goalCommand.create.completed": "已创建目标",+ "builtins.goalCommand.create.failed": "创建目标失败",+ "builtins.goalCommand.create.loading": "正在创建目标",+ "builtins.goalCommand.plan.completed": "已提交目标规划",+ "builtins.goalCommand.plan.failed": "提交目标规划失败",+ "builtins.goalCommand.plan.loading": "正在规划目标任务","builtins.linear.render.empty": "没有找到 {{collection}}","builtins.linear.render.updatedAt": "更新于 {{time}}","builtins.lobe-activator.apiName.activateTools": "激活工具",diff --git a/packages/builtin-tool-claude-code/src/client/Inspector/Bash.tsx b/packages/builtin-tool-claude-code/src/client/Inspector/Bash.tsxnew file mode 100644index 00000000000..4b1ad24dfaa--- /dev/null+++ b/packages/builtin-tool-claude-code/src/client/Inspector/Bash.tsx@@ -0,0 +1,31 @@+'use client';++import { getGoalCommand } from '@lobechat/shared-tool-ui/goal-command';+import {+ createRunCommandInspector,+ GoalCommandInspector,+} from '@lobechat/shared-tool-ui/inspectors';+import type { BuiltinInspectorProps } from '@lobechat/types';+import { memo } from 'react';++import { ClaudeCodeApiName } from '../../types';++const RunCommandInspector = createRunCommandInspector(ClaudeCodeApiName.Bash);++interface BashArgs {+ command: string;+ description?: string;+}++/**+ * `/goal` reaches LobeHub from a CC run as `lh goal create` / `lh goal plan`+ * shell calls, so those steps read as goal progress instead of raw commands.+ */+export const BashInspector = memo<BuiltinInspectorProps<BashArgs>>((props) => {+ const goalCommand = getGoalCommand(props.args?.command || props.partialArgs?.command);+ if (goalCommand) return <GoalCommandInspector {...props} goalCommand={goalCommand} />;++ return <RunCommandInspector {...props} />;+});++BashInspector.displayName = 'ClaudeCodeBashInspector';diff --git a/packages/builtin-tool-claude-code/src/client/Inspector/index.ts b/packages/builtin-tool-claude-code/src/client/Inspector/index.tsindex fa13ea7573a..d8c54458d95 100644--- a/packages/builtin-tool-claude-code/src/client/Inspector/index.ts+++ b/packages/builtin-tool-claude-code/src/client/Inspector/index.ts@@ -3,13 +3,13 @@import {createGlobLocalFilesInspector,createGrepContentInspector,- createRunCommandInspector,} from '@lobechat/shared-tool-ui/inspectors';import type { BuiltinInspector } from '@lobechat/types';import { ClaudeCodeApiName } from '../../types';import { AgentInspector } from './Agent';import { AskUserQuestionInspector } from './AskUserQuestion';+import { BashInspector } from './Bash';import { BrowserMcpInspectors } from './BrowserMcp';import { EditInspector } from './Edit';import { LinearMcpInspectors } from './LinearMcp';@@ -34,13 +34,14 @@ import { WriteInspector } from './Write';// the "translation key" and let react-i18next's missing-key fallback echo it// back verbatim. Keeps this package out of the plugin locale file.//-// Bash / Glob / Grep can use the shared factories directly — Glob / Grep only-// need `pattern`. Edit / Read / Write need arg mapping (or synthesized plugin-// state for diff stats), so they live in their own sibling files.+// Glob / Grep can use the shared factories directly — they only need+// `pattern`. Bash reads `lh goal` steps as goal progress, and Edit / Read /+// Write need arg mapping (or synthesized plugin state for diff stats), so they+// live in their own sibling files.const FixedClaudeCodeInspectors = {[ClaudeCodeApiName.Agent]: AgentInspector,[ClaudeCodeApiName.AskUserQuestion]: AskUserQuestionInspector,- [ClaudeCodeApiName.Bash]: createRunCommandInspector(ClaudeCodeApiName.Bash),+ [ClaudeCodeApiName.Bash]: BashInspector,[ClaudeCodeApiName.Edit]: EditInspector,[ClaudeCodeApiName.EnterWorktree]: EnterWorktreeInspector,[ClaudeCodeApiName.ExitWorktree]: ExitWorktreeInspector,diff --git a/packages/builtin-tools/src/codex/CommandExecutionInspector.tsx b/packages/builtin-tools/src/codex/CommandExecutionInspector.tsxindex da696c8dbee..eeedf30ddd3 100644--- a/packages/builtin-tools/src/codex/CommandExecutionInspector.tsx+++ b/packages/builtin-tools/src/codex/CommandExecutionInspector.tsx@@ -1,9 +1,11 @@'use client';import { SiGit, SiGooglechrome, SiNodedotjs, SiPython } from '@icons-pack/react-simple-icons';+import { getGoalCommand } from '@lobechat/shared-tool-ui/goal-command';import {createGrepContentInspector,createReadLocalFileInspector,+ GoalCommandInspector,RunCommandInspector,} from '@lobechat/shared-tool-ui/inspectors';import type { RunCommandState } from '@lobechat/tool-runtime';@@ -121,6 +123,10 @@ const CommandExecutionInspector = memo<toolCallId,} = props;+ // `/goal` in a Codex conversation creates and plans the goal through `lh`.+ const goalCommand = getGoalCommand(args?.command) ?? getGoalCommand(partialArgs?.command);+ if (goalCommand) return <GoalCommandInspector {...props} goalCommand={goalCommand} />;+const readArgs = mapCommandToReadArgs(args?.command);const partialReadArgs = mapCommandToReadArgs(partialArgs?.command);if (readArgs || partialReadArgs) {diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex b058446ddb8..c6e4c1ec567 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -2027,8 +2027,6 @@ export default {'goalList.status.verifying': 'Verifying','goalList.status.waiting': 'Waiting','goalTask.checks': '{{passed}}/{{total}} checks passed',- 'goalTask.currentStep': 'Current: {{title}}',- 'goalTask.nextStep': 'Up next: {{title}}','goalTask.round': 'Round {{current}}','goalTask.roundWithBudget': 'Round {{current}}/{{total}}','goalTask.tasksDone': '{{passed}}/{{total}} tasks done',@@ -2036,11 +2034,18 @@ export default {'goalTask.status.canceled': 'Canceled','goalTask.status.error': 'Needs attention','goalTask.status.paused': 'Paused',+ 'goalTask.status.planning': 'Planning','goalTask.status.repairing': 'Repairing','goalTask.status.review': 'Pending acceptance','goalTask.status.running': 'Executing','goalTask.status.verifying': 'Verifying','goalTask.status.waiting': 'Waiting',+ 'goalTask.plan.drafting': 'Breaking the goal into tasks…',+ 'goalTask.stage.achieved': 'Achieve',+ 'goalTask.stage.executing': 'Execute',+ 'goalTask.stage.planning': 'Plan',+ 'goalTask.stage.verifying': 'Accept',+ 'goalTask.step.queued': 'Not started','goalList.title': 'Goals','goalDetail.acceptance': 'Acceptance checks','goalAcceptance.add': 'Add criterion',diff --git a/packages/locales/src/default/plugin.ts b/packages/locales/src/default/plugin.tsindex 4d969f6d048..9d4453b1ca0 100644--- a/packages/locales/src/default/plugin.ts+++ b/packages/locales/src/default/plugin.ts@@ -173,6 +173,12 @@ export default {'builtins.codex.collabTool.spawnAgent': 'Spawn subagent','builtins.codex.collabTool.wait': 'Wait for subagents','builtins.codex.commandExecution.agentBrowser': 'Operate browser',+ 'builtins.goalCommand.create.completed': 'Goal created',+ 'builtins.goalCommand.create.failed': "Couldn't create goal",+ 'builtins.goalCommand.create.loading': 'Creating goal',+ 'builtins.goalCommand.plan.completed': 'Goal plan submitted',+ 'builtins.goalCommand.plan.failed': "Couldn't submit goal plan",+ 'builtins.goalCommand.plan.loading': 'Planning goal tasks','builtins.codex.agentBrowser.click': 'Clicked element','builtins.codex.agentBrowser.eval': 'Evaluated page','builtins.codex.agentBrowser.fill': 'Filled input',diff --git a/packages/shared-tool-ui/package.json b/packages/shared-tool-ui/package.jsonindex 9137aa823e0..70975787318 100644--- a/packages/shared-tool-ui/package.json+++ b/packages/shared-tool-ui/package.json@@ -6,6 +6,7 @@".": "./src/index.ts","./ask-user": "./src/AskUserQuestion/index.ts","./components": "./src/components/index.ts",+ "./goal-command": "./src/utils/goalCommand.ts","./inspectors": "./src/Inspector/index.ts","./inspectors/github-labels": "./src/Inspector/GitHub/labels.ts","./inspectors/linear-labels": "./src/Inspector/Linear/labels.ts",diff --git a/packages/shared-tool-ui/src/Inspector/GoalCommand/index.tsx b/packages/shared-tool-ui/src/Inspector/GoalCommand/index.tsxnew file mode 100644index 00000000000..018a6786836--- /dev/null+++ b/packages/shared-tool-ui/src/Inspector/GoalCommand/index.tsx@@ -0,0 +1,76 @@+'use client';++import type { RunCommandState } from '@lobechat/tool-runtime';+import type { BuiltinInspectorProps } from '@lobechat/types';+import { createStaticStyles, cssVar, cx } from 'antd-style';+import { Target, X } from 'lucide-react';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import { inspectorTextStyles, shinyTextStyles } from '../../styles';+import { type GoalCommand, isGoalCommandFailed } from '../../utils/goalCommand';++const styles = createStaticStyles(({ css, cssVar }) => ({+ chip: css`+ overflow: hidden;+ flex-shrink: 1;++ min-width: 0;+ margin-inline-start: 6px;+ padding-block: 2px;+ padding-inline: 10px;+ border-radius: 999px;++ font-size: 12px;+ color: ${cssVar.colorText};+ text-overflow: ellipsis;+ white-space: nowrap;++ background: ${cssVar.colorFillTertiary};+ `,+ icon: css`+ flex-shrink: 0;+ margin-inline-end: 6px;+ color: ${cssVar.colorTextDescription};+ `,+ statusIcon: css`+ flex-shrink: 0;+ margin-inline-start: 4px;+ `,+}));++export interface GoalCommandInspectorProps extends BuiltinInspectorProps<+ { command?: string },+ RunCommandState+> {+ goalCommand: GoalCommand;+}++/**+ * A CLI agent's `lh goal create` / `lh goal plan` step, read as the goal step it+ * is rather than a raw shell command: while it runs the user sees the goal being+ * created, then planned, and the settled row keeps the goal's title.+ */+export const GoalCommandInspector = memo<GoalCommandInspectorProps>(+ ({ goalCommand, isArgumentsStreaming, isLoading, pluginState, result }) => {+ const { t } = useTranslation('plugin');++ const inFlight = !!(isArgumentsStreaming || isLoading);+ const failed = !inFlight && isGoalCommandFailed({ error: result?.error, state: pluginState });+ const status = inFlight ? 'loading' : failed ? 'failed' : 'completed';+ const title = goalCommand.kind === 'create' ? goalCommand.title : undefined;++ return (+ <div className={inspectorTextStyles.root}>+ <Target className={styles.icon} size={14} />+ <span className={cx(inFlight && shinyTextStyles.shinyText)}>+ {t(`builtins.goalCommand.${goalCommand.kind}.${status}` as any)}+ </span>+ {title && <span className={styles.chip}>{title}</span>}+ {failed && <X className={styles.statusIcon} color={cssVar.colorError} size={14} />}+ </div>+ );+ },+);++GoalCommandInspector.displayName = 'GoalCommandInspector';diff --git a/packages/shared-tool-ui/src/Inspector/index.ts b/packages/shared-tool-ui/src/Inspector/index.tsindex 2c314f94933..586b41ab3c4 100644--- a/packages/shared-tool-ui/src/Inspector/index.ts+++ b/packages/shared-tool-ui/src/Inspector/index.ts@@ -1,6 +1,7 @@export { createEditLocalFileInspector } from './EditLocalFile';export { GITHUB_TOOL_NAMES, GitHubInspector } from './GitHub';export { createGlobLocalFilesInspector } from './GlobLocalFiles';+export { GoalCommandInspector } from './GoalCommand';export { createGrepContentInspector } from './GrepContent';export { LINEAR_TOOL_NAMES, LinearInspector } from './Linear';export { createListLocalFilesInspector } from './ListLocalFiles';diff --git a/packages/shared-tool-ui/src/utils/goalCommand.test.ts b/packages/shared-tool-ui/src/utils/goalCommand.test.tsnew file mode 100644index 00000000000..3c4cf78a103--- /dev/null+++ b/packages/shared-tool-ui/src/utils/goalCommand.test.ts@@ -0,0 +1,129 @@+import { describe, expect, it } from 'vitest';++import { getCreatedGoal, getGoalCommand } from './goalCommand';++describe('getGoalCommand', () => {+ it('reads a conversation goal create with its title and criteria', () => {+ expect(+ getGoalCommand(+ 'lh goal create "整理 LobeHub 目标页区块清单" --conversation -r "需求" --criterion "至少 4 个区块" --criterion "保存为文稿" --json',+ ),+ ).toEqual({+ conversation: true,+ criteriaCount: 2,+ kind: 'create',+ title: '整理 LobeHub 目标页区块清单',+ });+ });++ it('unescapes a double-quoted title and accepts single quotes', () => {+ expect(getGoalCommand('lh goal create "Say \\"hi\\"" --conversation')).toMatchObject({+ title: 'Say "hi"',+ });+ expect(getGoalCommand("lh goal create 'Fog report'")).toEqual({+ conversation: false,+ criteriaCount: 0,+ kind: 'create',+ title: 'Fog report',+ });+ });++ it('scans adversarial separator / env-assignment runs in linear time', () => {+ const inputs = [+ `x\nA${'=\nA'.repeat(20_000)}`,+ `x\nA=${'\nA= '.repeat(20_000)}`,+ `x\n${'&!'.repeat(20_000)}`,+ `${'A=1 '.repeat(20_000)}echo`,+ ];++ const startedAt = performance.now();+ for (const input of inputs) expect(getGoalCommand(input)).toBeUndefined();+ expect(performance.now() - startedAt).toBeLessThan(1000);+ });++ it('reads a call behind env assignments and a path, after a separator', () => {+ expect(+ getGoalCommand('cd /tmp && FOO=1 BAR=x ./bin/lh goal create "Ship it" --conversation'),+ ).toEqual({ conversation: true, criteriaCount: 0, kind: 'create', title: 'Ship it' });+ expect(getGoalCommand('(lh goal plan goal_9 --file p.json)')).toEqual({+ goalId: 'goal_9',+ kind: 'plan',+ });+ expect(getGoalCommand('lh goal created x')).toBeUndefined();+ });++ it('ignores separators inside quoted or escaped arguments', () => {+ expect(getGoalCommand("echo 'x; lh goal create demo'")).toBeUndefined();+ expect(getGoalCommand('printf "x && lh goal plan goal_1"')).toBeUndefined();+ expect(getGoalCommand('echo "say \\" ; lh goal create demo"')).toBeUndefined();+ expect(getGoalCommand('echo x\\; lh goal create demo')).toBeUndefined();+ expect(getGoalCommand("echo 'done' && lh goal create demo")).toMatchObject({+ kind: 'create',+ title: 'demo',+ });+ });++ it('reads the goal id of a plan submission', () => {+ expect(+ getGoalCommand('lh goal plan goal_P0NhivSBktCf --token t --file /tmp/plan.json'),+ ).toEqual({ goalId: 'goal_P0NhivSBktCf', kind: 'plan' });+ });++ it('sees through a shell wrapper and a preceding command', () => {+ expect(+ getGoalCommand(`/bin/zsh -lc 'cd /tmp && lh goal plan goal_1 --token t --file p.json'`),+ ).toEqual({ goalId: 'goal_1', kind: 'plan' });+ });++ it('keeps an unfinished title undefined while arguments stream', () => {+ expect(getGoalCommand('lh goal create "整理 LobeHub')).toMatchObject({+ kind: 'create',+ title: undefined,+ });+ });++ it('ignores other commands', () => {+ expect(getGoalCommand('lh goal show goal_1')).toBeUndefined();+ expect(getGoalCommand('echo lh goal-create')).toBeUndefined();+ // Only a command in command position ran; as an argument it is just text.+ expect(getGoalCommand('echo lh goal create "demo"')).toBeUndefined();+ expect(getGoalCommand('grep -r "lh goal plan" .')).toBeUndefined();+ });++ it('still reads lh behind separators, env assignments and a path', () => {+ expect(getGoalCommand('cd /tmp && lh goal create "A"')).toMatchObject({ title: 'A' });+ expect(getGoalCommand('true; lh goal plan goal_1')).toMatchObject({ goalId: 'goal_1' });+ expect(getGoalCommand('LOBEHUB_X=1 lh goal create "B"')).toMatchObject({ title: 'B' });+ expect(getGoalCommand('~/.local/bin/lh goal create "C"')).toMatchObject({ title: 'C' });+ expect(getGoalCommand('')).toBeUndefined();+ expect(getGoalCommand()).toBeUndefined();+ });+});++describe('getCreatedGoal', () => {+ it('reads the goal from the --json graph snapshot', () => {+ expect(+ getCreatedGoal(+ JSON.stringify({+ edges: [],+ goal: { id: 'goal_P0NhivSBktCf', title: '整理 LobeHub 目标页区块清单' },+ turnToken: 'token',+ }),+ ),+ ).toEqual({ goalId: 'goal_P0NhivSBktCf', title: '整理 LobeHub 目标页区块清单' });+ });++ it('falls back to the printed URL or event ids when the output is not JSON', () => {+ expect(+ getCreatedGoal('goal: http://localhost:3010/goal/goal_abc123\nplanning turn: …'),+ ).toEqual({ goalId: 'goal_abc123' });+ expect(getCreatedGoal('{"events": [{"goalId": "goal_xyz", "eventType": "created"')).toEqual({+ goalId: 'goal_xyz',+ });+ });++ it('returns nothing for output without a goal', () => {+ expect(getCreatedGoal('Error: An operation-bound token is required')).toBeUndefined();+ expect(getCreatedGoal(null)).toBeUndefined();+ });+});diff --git a/packages/shared-tool-ui/src/utils/goalCommand.ts b/packages/shared-tool-ui/src/utils/goalCommand.tsnew file mode 100644index 00000000000..4a735ad6645--- /dev/null+++ b/packages/shared-tool-ui/src/utils/goalCommand.ts@@ -0,0 +1,138 @@+import { getRunCommandDisplayCommand } from './runCommand';++/**+ * An `lh goal` call a CLI agent ran from its shell. `/goal` in a heterogeneous+ * agent conversation reaches LobeHub this way instead of through the builtin+ * goal tool, so these commands are the only record of the goal in the turn.+ */+export type GoalCommand =+ | {+ /** `--conversation`: the goal is bound to, and supervised from, this conversation. */+ conversation: boolean;+ criteriaCount: number;+ kind: 'create';+ title?: string;+ }+ | { goalId?: string; kind: 'plan' };++// `lh` must be in command position — the start of the command, or right after+// a separator (`&&`, `||`, `;`, `|`, `(`, newline), optionally behind env+// assignments or a path. As a mere argument (`echo lh goal create x`, or a+// separator inside a quoted argument: `echo 'x; lh goal create y'`) it never ran.+// Scanned in one linear pass rather than with one regex: a pattern that has to+// try every separator, env assignment and path prefix backtracks polynomially.+const COMMAND_SEPARATORS = new Set([';', '&', '|', '(', '\n']);+const TOKEN_PATTERN = /\S+/g;+const ENV_ASSIGNMENT_PATTERN = /^[A-Z_]\w*=/i;+const GOAL_VERBS = new Set(['create', 'plan']);+const FIRST_POSITIONAL_PATTERN = /^\s+(?:"((?:[^"\\]|\\.)*)"|'([^']*)'|([^\s"'-]\S*))/;++const isLhBinary = (token: string) => token === 'lh' || token.endsWith('/lh');++/** `[start, end)` of each simple command, splitting only on unquoted, unescaped separators. */+const getCommandSegments = (command: string): [number, number][] => {+ const segments: [number, number][] = [];+ let start = 0;+ let quote: '"' | "'" | undefined;++ for (let index = 0; index < command.length; index += 1) {+ const char = command[index];+ if (quote) {+ if (char === quote) quote = undefined;+ else if (char === '\\' && quote === '"') index += 1;+ } else if (char === '\\') {+ index += 1;+ } else if (char === '"' || char === "'") {+ quote = char;+ } else if (COMMAND_SEPARATORS.has(char)) {+ segments.push([start, index]);+ start = index + 1;+ }+ }+ segments.push([start, command.length]);++ return segments;+};++/** The first `lh goal <verb>` in command position, and everything after its verb. */+const findGoalCall = (command: string): { rest: string; verb: string } | undefined => {+ for (const [start, end] of getCommandSegments(command)) {+ const tokens = [...command.slice(start, end).matchAll(TOKEN_PATTERN)];++ let index = 0;+ while (index < tokens.length && ENV_ASSIGNMENT_PATTERN.test(tokens[index][0])) index += 1;++ const verb = tokens[index + 2];+ if (+ verb &&+ isLhBinary(tokens[index][0]) &&+ tokens[index + 1][0] === 'goal' &&+ GOAL_VERBS.has(verb[0])+ ) {+ return { rest: command.slice(start + verb.index + verb[0].length), verb: verb[0] };+ }+ }+};++export const getGoalCommand = (command?: string): GoalCommand | undefined => {+ const call = findGoalCall(getRunCommandDisplayCommand(command));+ if (!call) return;++ const { rest, verb } = call;+ const positional = rest.match(FIRST_POSITIONAL_PATTERN);+ const value = positional+ ? (positional[1]?.replaceAll(/\\(.)/g, '$1') ?? positional[2] ?? positional[3])+ : undefined;++ if (verb === 'plan') return { goalId: value, kind: 'plan' };++ return {+ conversation: /(?:^|\s)--conversation(?=\s|$)/.test(rest),+ criteriaCount: rest.match(/(?:^|\s)--criterion(?=\s|$)/g)?.length ?? 0,+ kind: 'create',+ title: value,+ };+};++const isRecord = (value: unknown): value is Record<string, unknown> =>+ typeof value === 'object' && value !== null;++/**+ * The goal an `lh goal create` call produced, read from its output: the+ * `--json` graph snapshot, or — when the output was not JSON or got truncated —+ * the goal id from its printed URL or events.+ */+export const getCreatedGoal = (+ output?: string | null,+): { goalId: string; title?: string } | undefined => {+ if (!output?.trim()) return;++ try {+ const parsed: unknown = JSON.parse(output);+ const goal = isRecord(parsed) ? parsed.goal : undefined;+ if (isRecord(goal) && typeof goal.id === 'string' && goal.id) {+ return {+ goalId: goal.id,+ title: typeof goal.title === 'string' && goal.title ? goal.title : undefined,+ };+ }+ } catch {+ // Not JSON — fall through to the id the output prints.+ }++ const goalId =+ output.match(/\/goal\/(goal_[\w-]+)/)?.[1] ?? output.match(/"goalId":\s*"(goal_[\w-]+)"/)?.[1];++ return goalId ? { goalId } : undefined;+};++/**+ * Whether a settled `lh goal` step failed. A shell step reports failure either+ * as a tool error or only through its run state (`success: false` with a+ * nonzero exit code); every surface that labels the step must read both.+ */+export const isGoalCommandFailed = (result?: {+ error?: unknown;+ state?: { exitCode?: number; success?: boolean } | null;+}): boolean =>+ !!result?.error || (result?.state?.success === false && result?.state?.exitCode !== 0);diff --git a/src/features/Conversation/ChatInput/LinkedGoalTray/index.tsx b/src/features/Conversation/ChatInput/LinkedGoalTray/index.tsxindex 4ac00bb9bcb..68558475e65 100644--- a/src/features/Conversation/ChatInput/LinkedGoalTray/index.tsx+++ b/src/features/Conversation/ChatInput/LinkedGoalTray/index.tsx@@ -51,6 +51,7 @@ const LinkedGoalRow = memo<{ item: GoalListItem }>(({ item }) => {const openGoal = useChatStore((s) => s.openGoal);const { goal, pendingDecisions, taskDone, taskTotal } = item;const open = () => openGoal(goal.id);+ const planning = taskTotal === 0 && (goal.status === 'planning' || goal.status === 'running');return (<Flexbox@@ -85,7 +86,8 @@ const LinkedGoalRow = memo<{ item: GoalListItem }>(({ item }) => {))}<Text fontSize={12} style={{ flexShrink: 0 }} type={'secondary'}>- {t(goalStatusKey(goal.status))}+ {/* A `/goal` run marks its goal running at creation; until the plan lands a Task it is still being planned. */}+ {planning ? t('goalTask.status.planning') : t(goalStatusKey(goal.status))}</Text><Icon color={cssVar.colorTextQuaternary} icon={ChevronRight} size={14} /></Flexbox>diff --git a/src/features/Conversation/ChatInput/LinkedGoalTray/linkedGoals.test.ts b/src/features/Conversation/ChatInput/LinkedGoalTray/linkedGoals.test.tsindex 3969c651d2e..2667877ccf0 100644--- a/src/features/Conversation/ChatInput/LinkedGoalTray/linkedGoals.test.ts+++ b/src/features/Conversation/ChatInput/LinkedGoalTray/linkedGoals.test.ts@@ -41,6 +41,35 @@ describe('selectLinkedGoals', () => {expect(result.map((item) => item.goal.id)).toEqual(['goal-cli']);});+ it('keeps a goal a CLI agent created from this conversation even though its turn has a card', () => {+ const cliTurn = {+ children: [+ {+ content: '',+ id: 'block-cli',+ tools: [+ {+ apiName: 'Bash',+ arguments: JSON.stringify({ command: 'lh goal create "Fog" --conversation --json' }),+ id: 'call-cli',+ identifier: 'claude-code',+ result: { content: JSON.stringify({ goal: { id: 'goal-cli' } }), id: 'tool-cli' },+ type: 'default',+ },+ ],+ },+ ],+ content: '',+ createdAt: 0,+ id: 'msg-cli',+ role: 'assistantGroup',+ } as unknown as UIChatMessage;++ expect(selectLinkedGoals([goal('goal-cli')], [cliTurn]).map((item) => item.goal.id)).toEqual([+ 'goal-cli',+ ]);+ });+it('caps the tray at a few goals', () => {const goals = Array.from({ length: MAX_LINKED_GOALS + 2 }, (_, i) => goal(`goal-${i}`));diff --git a/src/features/Conversation/ChatInput/LinkedGoalTray/linkedGoals.ts b/src/features/Conversation/ChatInput/LinkedGoalTray/linkedGoals.tsindex bfa187b741d..551d88ba7e5 100644--- a/src/features/Conversation/ChatInput/LinkedGoalTray/linkedGoals.ts+++ b/src/features/Conversation/ChatInput/LinkedGoalTray/linkedGoals.ts@@ -12,9 +12,10 @@ export const MAX_LINKED_GOALS = 3;* Goals linked to the topic that still need a surface in this conversation.** A goal created by the builtin `createGoal` tool already renders as a live card- * inside its assistant turn, so the tray skips it; what remains are goals the- * conversation planned some other way — a CLI agent's `lh goal create- * --conversation` leaves only Bash output behind.+ * inside its assistant turn, so the tray skips it. A goal a CLI agent created+ * with `lh goal create --conversation` keeps its tray row even though its turn+ * now carries a card too: that agent supervises it from this conversation, so+ * its status stays in reach above the composer after the turn scrolls away.*/export const selectLinkedGoals = (goals: GoalListItem[] = [],@@ -22,7 +23,9 @@ export const selectLinkedGoals = (): GoalListItem[] => {const carded = new Set(messages.flatMap((message) =>- deriveOperationGoals(message.children ?? []).map(({ goalId }) => goalId),+ deriveOperationGoals(message.children ?? []).flatMap(({ goalId, source }) =>+ source === 'tool' ? [goalId] : [],+ ),),);diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/ToolTitle.test.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/ToolTitle.test.tsxindex 672d795ae3d..da06876c629 100644--- a/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/ToolTitle.test.tsx+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/ToolTitle.test.tsx@@ -13,6 +13,72 @@ vi.mock('react-i18next', () => ({}));describe('ToolTitle', () => {+ describe('lh goal steps from a CLI agent', () => {+ const createArgs = {+ command: 'lh goal create "Fog report" --conversation --criterion "Four lines" --json',+ description: 'Create LobeHub goal bound to conversation',+ };++ it('reads a running goal create as the goal being created, with its title', () => {+ render(<ToolTitle isLoading apiName={'Bash'} args={createArgs} identifier={'claude-code'} />);++ expect(screen.getByText('loading')).toBeInTheDocument();+ expect(screen.getByText('Fog report')).toBeInTheDocument();+ // Neither the generic action label nor the model's English description.+ expect(screen.queryByText('Bash')).toBeNull();+ expect(screen.queryByText(createArgs.description)).toBeNull();+ });++ it('flips to the settled label once the step finishes', () => {+ render(<ToolTitle apiName={'Bash'} args={createArgs} identifier={'claude-code'} />);++ expect(screen.getByText('completed')).toBeInTheDocument();+ expect(screen.getByText('Fog report')).toBeInTheDocument();+ });++ it('says the step failed when the goal command errored', () => {+ // The collapsed row used to read "completed" beside a failed status icon.+ render(+ <ToolTitle+ apiName={'Bash'}+ args={createArgs}+ identifier={'claude-code'}+ result={{ state: { exitCode: 1, success: false } }}+ />,+ );++ expect(screen.getByText('failed')).toBeInTheDocument();+ expect(screen.queryByText('completed')).toBeNull();+ });++ it('also treats a result error as failed', () => {+ render(+ <ToolTitle+ apiName={'Bash'}+ args={createArgs}+ identifier={'claude-code'}+ result={{ error: { message: 'unknown option' } }}+ />,+ );++ expect(screen.getByText('failed')).toBeInTheDocument();+ });++ it('reads a plan submission without a raw goal id', () => {+ render(+ <ToolTitle+ isLoading+ apiName={'command_execution'}+ args={{ command: 'lh goal plan goal_1 --token t --file plan.json --json' }}+ identifier={'codex'}+ />,+ );++ expect(screen.getByText('loading')).toBeInTheDocument();+ expect(screen.queryByText(/goal_1/)).toBeNull();+ });+ });+it.each([{ title: '沙盒交付链路问题' },{ description: '修复沙盒权限问题', title: '沙盒交付链路问题' },diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/ToolTitle.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/ToolTitle.tsxindex 69e2a72b4ad..a52fef78477 100644--- a/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/ToolTitle.tsx+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/ToolTitle.tsx@@ -1,3 +1,4 @@+import { getGoalCommand, isGoalCommandFailed } from '@lobechat/shared-tool-ui/goal-command';import { Icon } from '@lobehub/ui';import { createStaticStyles, cx } from 'antd-style';import isEqual from 'fast-deep-equal';@@ -57,6 +58,8 @@ interface ToolTitleProps {isAborted?: boolean;isLoading?: boolean;partialArgs?: Record<string, unknown>;+ /** The settled tool result, so a failed goal command is not titled as done. */+ result?: { error?: unknown; state?: any };}const isCJK = (value: string) => /[\u4E00-\u9FFF\u3040-\u30FF\uAC00-\uD7AF]/.test(value);@@ -69,7 +72,7 @@ const isCJK = (value: string) => /[\u4E00-\u9FFF\u3040-\u30FF\uAC00-\uD7AF]/.tes* keep the "<label> <keyword>" shape in the smaller code font.*/const ToolTitle = memo<ToolTitleProps>(- ({ identifier, apiName, args, partialArgs, isLoading, isAborted }) => {+ ({ identifier, apiName, args, partialArgs, isLoading, isAborted, result }) => {const { t } = useTranslation('plugin');const pluginMeta = useToolStore(toolSelectors.getMetaById(identifier), isEqual);@@ -96,6 +99,31 @@ const ToolTitle = memo<ToolTitleProps>(isCJK(keyword) &&keyword === extractToolKeyword({ description: effectiveArgs?.description });+ // `/goal` in a CLI agent conversation creates and plans the goal through+ // `lh` — that step reads as the goal step, not "执行命令 <description>".+ const goalCommand = useMemo(+ () =>+ typeof effectiveArgs?.command === 'string'+ ? getGoalCommand(effectiveArgs.command)+ : undefined,+ [effectiveArgs],+ );+ if (goalCommand) {+ const goalTitle = goalCommand.kind === 'create' ? goalCommand.title : undefined;+ // Same rule as the expanded GoalCommandInspector, so the collapsed row+ // never says "Goal created" next to a failed status.+ const failed = !isLoading && isGoalCommandFailed(result);+ const status = isLoading ? 'loading' : failed ? 'failed' : 'completed';+ return (+ <div className={cx(styles.root, isAborted && styles.aborted)}>+ <span className={cx(styles.label, isLoading && shinyTextStyles.shinyText)}>+ {t(`builtins.goalCommand.${goalCommand.kind}.${status}`)}+ </span>+ {goalTitle && <span className={styles.standalone}>{goalTitle}</span>}+ </div>+ );+ }+return (<div className={cx(styles.root, isAborted && styles.aborted)}>{isStandaloneDescription ? (diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/index.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/index.tsxindex 8c265d4cdd5..acc4b058ab8 100644--- a/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/index.tsx+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/index.tsx@@ -150,6 +150,7 @@ const Inspectors = memo<InspectorProps>(isAborted={isAborted}isLoading={isTitleLoading}partialArgs={partialJson || undefined}+ result={result}/>)}<ExecutionTimediff --git a/src/features/Conversation/Messages/AssistantGroup/index.tsx b/src/features/Conversation/Messages/AssistantGroup/index.tsxindex 15d28a1e74b..28b282c9d56 100644--- a/src/features/Conversation/Messages/AssistantGroup/index.tsx+++ b/src/features/Conversation/Messages/AssistantGroup/index.tsx@@ -193,7 +193,16 @@ const GroupMessage = memo<GroupMessageProps>(// (the work anchor marks them); without it the card keeps every entry.!!workRootOperationId,);- const operationGoals = useOperationGoals(isGroupGenerating ? undefined : allChildren);+ const derivedGoals = useOperationGoals(allChildren);+ // A goal a CLI agent creates with `lh` gets its card as soon as it exists:+ // `/goal` keeps the same run going to plan it, and the card is how the user+ // sees the goal while that happens. A builtin createGoal call already renders+ // live inline, so its card stays a turn-end artifact like edited files.+ const operationGoals = useMemo(+ () =>+ isGroupGenerating ? derivedGoals.filter((goal) => goal.source === 'command') : derivedGoals,+ [derivedGoals, isGroupGenerating],+ );const isInbox = useAgentStore(builtinAgentSelectors.isInboxAgent);const [toggleSystemRole] = useGlobalStore((s) => [s.toggleSystemRole]);diff --git a/src/features/Conversation/Messages/AssistantGroup/toolDisplayNames.test.ts b/src/features/Conversation/Messages/AssistantGroup/toolDisplayNames.test.tsindex c9f2c1621d1..a46829ac8d1 100644--- a/src/features/Conversation/Messages/AssistantGroup/toolDisplayNames.test.ts+++ b/src/features/Conversation/Messages/AssistantGroup/toolDisplayNames.test.ts@@ -14,6 +14,63 @@ const blk = (p: Partial<AssistantContentBlock> & { id: string }): AssistantConte({ content: '', ...p }) as AssistantContentBlock;describe('tool display names', () => {+ it('reads a running lh goal step as the goal step, not a raw command', () => {+ const goalCall = (+ command: string,+ result?: { content: string; error?: unknown; state?: unknown },+ ) =>+ blk({+ id: 'goal',+ tools: [+ {+ apiName: 'Bash',+ arguments: JSON.stringify({ command, description: 'Create LobeHub goal' }),+ id: 'toolu_goal',+ identifier: 'claude-code',+ result,+ } as any,+ ],+ });++ // The plugin namespace is not loaded here, so labels resolve to their keys.+ expect(+ getWorkflowStreamingHeadlineState([+ goalCall('lh goal create "Fog report" --conversation --json'),+ ]),+ ).toMatchObject({+ fallbackTool: 'builtins.goalCommand.create.loading Fog report',+ kind: 'tool',+ });+ expect(+ getWorkflowStreamingHeadlineState([+ goalCall('lh goal create "Fog report" --conversation --json', { content: '{}' }),+ ]),+ ).toMatchObject({ fallbackTool: 'builtins.goalCommand.create.completed Fog report' });+ expect(+ getWorkflowStreamingHeadlineState([+ goalCall('lh goal create "Fog report" --conversation --json', {+ content: 'Error: An operation-bound token is required',+ error: { message: 'exit 1' },+ }),+ ]),+ ).toMatchObject({ fallbackTool: 'builtins.goalCommand.create.failed Fog report' });+ // A shell step can report failure only through its run state; the headline+ // used to read "completed" then.+ expect(+ getWorkflowStreamingHeadlineState([+ goalCall('lh goal create "Fog report" --conversation --json', {+ content: 'error: unknown option',+ state: { exitCode: 1, success: false },+ }),+ ]),+ ).toMatchObject({ fallbackTool: 'builtins.goalCommand.create.failed Fog report' });+ expect(+ getWorkflowStreamingHeadlineState([+ goalCall('lh goal plan goal_1 --token t --file plan.json --json'),+ ]),+ ).toMatchObject({ fallbackTool: 'builtins.goalCommand.plan.loading' });+ });+it('uses friendly labels for Codex tool api names', () => {expect(getToolDisplayName('command_execution')).toBe('Ran a command');expect(getToolDisplayName('file_change')).toBe('Edited a file');diff --git a/src/features/Conversation/Messages/AssistantGroup/toolDisplayNames.ts b/src/features/Conversation/Messages/AssistantGroup/toolDisplayNames.tsindex 4581179da18..14acae3a586 100644--- a/src/features/Conversation/Messages/AssistantGroup/toolDisplayNames.ts+++ b/src/features/Conversation/Messages/AssistantGroup/toolDisplayNames.ts@@ -2,6 +2,7 @@ import {formatBrowserMcpShortLabel,formatLinearMcpShortLabel,} from '@lobechat/builtin-tool-claude-code/client/labels';+import { getGoalCommand, isGoalCommandFailed } from '@lobechat/shared-tool-ui/goal-command';import type { ChatToolPayloadWithResult } from '@lobechat/types';import { formatDuration } from '@lobechat/utils';import { t } from 'i18next';@@ -143,12 +144,45 @@ export const getExplicitStepHeadlineLine = (tool: ChatToolPayloadWithResult): streturn `${label}: ${short}`;};+/**+ * `/goal` in a CLI agent conversation creates and plans the goal through `lh`+ * shell calls. While the run streams, that step reads as the goal step it is+ * ("正在创建目标 <title>") rather than "执行命令 <description>".+ */+const getGoalCommandHeadlineLine = (tool: ChatToolPayloadWithResult): string => {+ if (!tool.arguments?.includes('goal ')) return '';++ let command: unknown;+ try {+ command = JSON.parse(tool.arguments).command;+ } catch {+ // arguments still streaming or invalid+ return '';+ }+ const goalCommand = typeof command === 'string' ? getGoalCommand(command) : undefined;+ if (!goalCommand) return '';++ const status =+ tool.result == null || tool.result.content === LOADING_FLAT+ ? 'loading'+ : isGoalCommandFailed(tool.result)+ ? 'failed'+ : 'completed';+ const label = t(`builtins.goalCommand.${goalCommand.kind}.${status}`, { ns: 'plugin' });+ const title = goalCommand.kind === 'create' ? goalCommand.title : undefined;++ return title ? `${label} ${title}` : label;+};+/*** C — action label + one keyword (no explicit step). This is the shining line* of a RUNNING collapsed workflow, so it reads as a sentence ("执行命令* monthly.ts"), never as a raw args dump.*/export const getToolFallbackHeadlineLine = (tool: ChatToolPayloadWithResult): string => {+ const goalHeadline = getGoalCommandHeadlineLine(tool);+ if (goalHeadline) return goalHeadline;+const label = getToolActionLabel(tool);const keyword = getToolKeywordDetail(tool);return keyword ? `${label} ${keyword}` : label;diff --git a/src/features/Conversation/Messages/GoalTaskCard/GoalStatusLine.tsx b/src/features/Conversation/Messages/GoalTaskCard/GoalStatusLine.tsxdeleted file mode 100644index 5723e129c94..00000000000--- a/src/features/Conversation/Messages/GoalTaskCard/GoalStatusLine.tsx+++ /dev/null@@ -1,98 +0,0 @@-'use client';--import type { GoalNodeStatus } from '@lobechat/types';-import { Flexbox, Icon } from '@lobehub/ui';-import { Text } from '@lobehub/ui/base-ui';-import { createStaticStyles, cssVar } from 'antd-style';-import type { TargetIcon } from 'lucide-react';-import {- AlertTriangleIcon,- CheckCircle2Icon,- CircleSlashIcon,- Clock3Icon,- LoaderCircleIcon,- PauseCircleIcon,- RefreshCwIcon,- StampIcon,-} from 'lucide-react';-import { memo } from 'react';-import { useTranslation } from 'react-i18next';--import GoalStepTrack from './GoalStepTrack';-import type { GoalTaskPhase } from './goalTaskProgress';--const PHASE_META = {- achieved: { color: cssVar.colorSuccess, icon: CheckCircle2Icon, spin: false },- canceled: { color: cssVar.colorTextTertiary, icon: CircleSlashIcon, spin: false },- error: { color: cssVar.colorError, icon: AlertTriangleIcon, spin: false },- paused: { color: cssVar.colorTextTertiary, icon: PauseCircleIcon, spin: false },- repairing: { color: cssVar.colorWarning, icon: RefreshCwIcon, spin: true },- review: { color: cssVar.colorWarning, icon: StampIcon, spin: false },- running: { color: cssVar.colorInfo, icon: LoaderCircleIcon, spin: true },- verifying: { color: cssVar.colorInfo, icon: LoaderCircleIcon, spin: true },- waiting: { color: cssVar.colorTextSecondary, icon: Clock3Icon, spin: false },-} as const satisfies Record<- GoalTaskPhase,- { color: string; icon: typeof TargetIcon; spin: boolean }->;--const styles = createStaticStyles(({ css }) => ({- status: css`- font-size: 12px;- color: ${cssVar.colorTextTertiary};- `,- statusIcon: css`- flex-shrink: 0;- `,- track: css`- flex: 1;- `,-}));--export interface GoalStatusLineProps {- passed: number;- phase: GoalTaskPhase;- statuses: GoalNodeStatus[];- total: number;-}--/**- * The live Goal status line — lifecycle phase word + the Tasks as a step track- * + closed count. The phase word shows for every phase: it names the stage the- * goal is in, which the track alone cannot. Once the goal is achieved the track- * and count retire: "已达成" already implies full coverage, so repeating "4/4- * 项通过" is noise.- */-const GoalStatusLine = memo<GoalStatusLineProps>(({ passed, phase, statuses, total }) => {- const { t } = useTranslation('chat');- const meta = PHASE_META[phase];- const showChecks = total > 0 && phase !== 'achieved';-- return (- <Flexbox horizontal align={'center'} gap={6}>- {phase !== 'running' && (- <Icon- className={styles.statusIcon}- color={meta.color}- icon={meta.icon}- size={12}- spin={meta.spin}- />- )}- <Text className={styles.status}>{t(`goalTask.status.${phase}`)}</Text>- {showChecks && (- <>- <Text className={styles.status}>·</Text>- <Flexbox className={styles.track}>- <GoalStepTrack statuses={statuses} total={total} />- </Flexbox>- <Text className={styles.status}>{t('goalTask.tasksDone', { passed, total })}</Text>- </>- )}- </Flexbox>- );-});--GoalStatusLine.displayName = 'GoalStatusLine';--export default GoalStatusLine;diff --git a/src/features/Conversation/Messages/GoalTaskCard/GoalStepTrack.tsx b/src/features/Conversation/Messages/GoalTaskCard/GoalStepTrack.tsxdeleted file mode 100644index a5ea2d40bdb..00000000000--- a/src/features/Conversation/Messages/GoalTaskCard/GoalStepTrack.tsx+++ /dev/null@@ -1,77 +0,0 @@-'use client';--import type { GoalNodeStatus } from '@lobechat/types';-import { createStaticStyles, cssVar, cx } from 'antd-style';-import { memo } from 'react';--import { buildGoalStepSegments } from './goalTaskProgress';--const styles = createStaticStyles(({ css }) => ({- active: css`- background: ${cssVar.colorInfo};- animation: goal-step-active-pulse 1.6s ${cssVar.motionEaseInOut} infinite;- `,- done: css`- background: ${cssVar.colorSuccess};- `,- pending: css`- background: ${cssVar.colorFillSecondary};- `,- segment: css`- flex: 1;- height: 4px;- border-radius: 2px;- `,- track: css`- display: flex;- gap: 3px;-- min-width: 96px;- max-width: 320px;- height: 4px;-- @keyframes goal-step-active-pulse {- 0%,- 100% {- opacity: 1;- }-- 50% {- opacity: 0.45;- }- }- `,-}));--export interface GoalStepTrackProps {- statuses: GoalNodeStatus[];- /** Criteria-count fallback for a goal whose graph has not been seeded yet. */- total: number;-}--/**- * The Goal's Tasks as a row of step segments: closed steps fill success, the- * running step pulses info, and the rest stay neutral — the plan reads as- * steps advancing left to right, not one anonymous bar. Before the graph is- * seeded the count is only a draft, so the track shows that many pending- * segments instead of disappearing. Companion count text carries the numbers,- * so the track stays decorative.- */-const GoalStepTrack = memo<GoalStepTrackProps>(({ statuses, total }) => {- const segments = buildGoalStepSegments(- statuses.length > 0 ? statuses : Array.from({ length: total }, () => 'proposed' as const),- );- if (segments.length === 0) return null;-- return (- <div aria-hidden className={styles.track}>- {segments.map((state, index) => (- <div className={cx(styles.segment, styles[state])} key={index} />- ))}- </div>- );-});--GoalStepTrack.displayName = 'GoalStepTrack';--export default GoalStepTrack;diff --git a/src/features/Conversation/Messages/GoalTaskCard/PlanChain.tsx b/src/features/Conversation/Messages/GoalTaskCard/PlanChain.tsxnew file mode 100644index 00000000000..e1eb7ee41a2--- /dev/null+++ b/src/features/Conversation/Messages/GoalTaskCard/PlanChain.tsx@@ -0,0 +1,199 @@+'use client';++import { Flexbox, Icon } from '@lobehub/ui';+import { Text } from '@lobehub/ui/base-ui';+import { createStaticStyles, cssVar, cx } from 'antd-style';+import { ArrowRight, type LucideIcon, ShieldCheck } from 'lucide-react';+import { Fragment, memo } from 'react';+import { useTranslation } from 'react-i18next';++import { TASK_STATUS_VISUALS } from '@/components/ExecutionStatus';+import RunningGlyph from '@/features/Home/components/RunningGlyph';+import { shinyTextStyles } from '@/styles';++import type { GoalCardModel, PlanStep, PlanStepState } from './goalCardModel';++const STEP_VISUAL: Record<+ PlanStepState,+ { color: string; icon?: LucideIcon; labelKey: string; open?: boolean }+> = {+ done: {+ color: TASK_STATUS_VISUALS.completed.color,+ icon: TASK_STATUS_VISUALS.completed.icon,+ labelKey: 'goalProcess.node.done',+ },+ failed: {+ color: TASK_STATUS_VISUALS.failed.color,+ icon: TASK_STATUS_VISUALS.failed.icon,+ labelKey: 'goalTask.status.error',+ },+ lost: {+ color: TASK_STATUS_VISUALS.failed.color,+ icon: TASK_STATUS_VISUALS.failed.icon,+ labelKey: 'goalProcess.tag.lost',+ open: true,+ },+ queued: {+ color: TASK_STATUS_VISUALS.backlog.color,+ icon: TASK_STATUS_VISUALS.backlog.icon,+ labelKey: 'goalTask.step.queued',+ },+ retired: {+ color: TASK_STATUS_VISUALS.canceled.color,+ icon: TASK_STATUS_VISUALS.canceled.icon,+ labelKey: 'goalProcess.tag.retired',+ },+ // Running uses the animated ring shared by every live surface.+ running: {+ color: TASK_STATUS_VISUALS.running.color,+ labelKey: 'goalProcess.node.running',+ open: true,+ },+ stopped: {+ color: TASK_STATUS_VISUALS.canceled.color,+ icon: TASK_STATUS_VISUALS.canceled.icon,+ labelKey: 'goalProcess.node.stopped',+ },+ verifying: {+ color: cssVar.colorInfo,+ icon: ShieldCheck,+ labelKey: 'goalProcess.tag.verifying',+ open: true,+ },+ waiting: {+ color: TASK_STATUS_VISUALS.paused.color,+ icon: TASK_STATUS_VISUALS.paused.icon,+ labelKey: 'goalProcess.node.waiting',+ open: true,+ },+};++const styles = createStaticStyles(({ css }) => ({+ arrow: css`+ flex: none;+ color: ${cssVar.colorTextQuaternary};+ `,+ more: css`+ flex: none;++ padding-block: 3px;+ padding-inline: 8px;+ border-radius: 6px;++ font-size: 12px;+ font-variant-numeric: tabular-nums;+ color: ${cssVar.colorTextTertiary};++ background: ${cssVar.colorFillQuaternary};+ `,+ placeholder: css`+ padding-block: 4px;+ padding-inline: 10px;+ border: 1px dashed ${cssVar.colorBorder};+ border-radius: 6px;+ `,+ step: css`+ overflow: hidden;++ /* Equal share of the row, so a long first title cannot squeeze the rest to a few characters. */+ flex: 1 1 0;++ min-width: 0;+ max-width: 240px;+ padding-block: 4px;+ padding-inline: 8px;+ border: 1px solid ${cssVar.colorBorderSecondary};+ border-radius: 6px;+ `,+ stepOpen: css`+ border-color: ${cssVar.colorBorder};+ background: ${cssVar.colorFillTertiary};+ `,+ stepQueued: css`+ border-style: dashed;+ `,+}));++const Step = memo<{ step: PlanStep }>(({ step }) => {+ const { t } = useTranslation('chat');+ const visual = STEP_VISUAL[step.state];+ const title = step.titleKey ? t(step.titleKey as any) : step.title;++ return (+ <Flexbox+ horizontal+ align={'center'}+ gap={6}+ title={`${t(visual.labelKey as any)} · ${title}`}+ className={cx(+ styles.step,+ visual.open && styles.stepOpen,+ step.state === 'queued' && styles.stepQueued,+ )}+ >+ {visual.icon ? (+ <Icon color={visual.color} icon={visual.icon} size={13} style={{ flex: 'none' }} />+ ) : (+ <RunningGlyph size={13} />+ )}+ <Text+ ellipsis+ fontSize={12}+ style={{ color: visual.open ? cssVar.colorText : cssVar.colorTextSecondary }}+ >+ {title}+ </Text>+ </Flexbox>+ );+});++Step.displayName = 'GoalPlanStep';++/**+ * The plan as a left-to-right chain of its tasks, each carrying its own state,+ * windowed around the task that is moving so a long plan still reads at a glance.+ */+const PlanChain = memo<{+ model: Pick<GoalCardModel, 'hiddenAfter' | 'hiddenBefore' | 'stage' | 'steps'>;+}>(({ model }) => {+ const { t } = useTranslation('chat');+ const { hiddenAfter, hiddenBefore, stage, steps } = model;++ if (steps.length === 0) {+ if (stage !== 'planning') return null;+ return (+ <Flexbox horizontal className={styles.placeholder} style={{ alignSelf: 'flex-start' }}>+ <Text className={shinyTextStyles.shinyText} fontSize={12}>+ {t('goalTask.plan.drafting')}+ </Text>+ </Flexbox>+ );+ }++ return (+ <Flexbox horizontal align={'center'} gap={4} style={{ minWidth: 0, overflow: 'hidden' }}>+ {hiddenBefore > 0 && (+ <>+ <span className={styles.more}>+{hiddenBefore}</span>+ <Icon className={styles.arrow} icon={ArrowRight} size={12} />+ </>+ )}+ {steps.map((step, index) => (+ <Fragment key={step.id}>+ {index > 0 && <Icon className={styles.arrow} icon={ArrowRight} size={12} />}+ <Step step={step} />+ </Fragment>+ ))}+ {hiddenAfter > 0 && (+ <>+ <Icon className={styles.arrow} icon={ArrowRight} size={12} />+ <span className={styles.more}>+{hiddenAfter}</span>+ </>+ )}+ </Flexbox>+ );+});++PlanChain.displayName = 'GoalPlanChain';++export default PlanChain;diff --git a/src/features/Conversation/Messages/GoalTaskCard/StageTrack.tsx b/src/features/Conversation/Messages/GoalTaskCard/StageTrack.tsxnew file mode 100644index 00000000000..864b0860415--- /dev/null+++ b/src/features/Conversation/Messages/GoalTaskCard/StageTrack.tsx@@ -0,0 +1,98 @@+'use client';++import { Flexbox } from '@lobehub/ui';+import { Text } from '@lobehub/ui/base-ui';+import { createStaticStyles, cssVar, cx } from 'antd-style';+import { Fragment, memo } from 'react';+import { useTranslation } from 'react-i18next';++import { GOAL_CARD_STAGES, type GoalCardStage, type GoalCardTone } from './goalCardModel';++const TONE_COLOR: Record<GoalCardTone, string> = {+ active: cssVar.colorInfo,+ canceled: cssVar.colorTextQuaternary,+ error: cssVar.colorError,+ paused: cssVar.colorTextTertiary,+ waiting: cssVar.colorWarning,+};++const styles = createStaticStyles(({ css }) => ({+ connector: css`+ flex: 1;+ min-width: 12px;+ height: 1px;+ background: ${cssVar.colorBorder};+ `,+ connectorDone: css`+ background: ${cssVar.colorSuccessBorder};+ `,+ dot: css`+ flex: none;++ box-sizing: border-box;+ width: 8px;+ height: 8px;+ border: 1px solid ${cssVar.colorTextQuaternary};+ border-radius: 50%;+ `,+ dotCurrent: css`+ width: 10px;+ height: 10px;+ border-width: 2px;+ background: ${cssVar.colorBgElevated};+ `,+ dotDone: css`+ border-color: ${cssVar.colorSuccess};+ background: ${cssVar.colorSuccess};+ `,+}));++/**+ * The goal's big stages as one left-to-right track — where it stands in the+ * plan → execute → accept → achieve arc, with the current stage colored by+ * whether it is moving, paused, waiting on the user, or stopped.+ */+const StageTrack = memo<{ stage: GoalCardStage; tone: GoalCardTone }>(({ stage, tone }) => {+ const { t } = useTranslation('chat');+ const current = GOAL_CARD_STAGES.indexOf(stage);++ return (+ <Flexbox horizontal align={'center'} gap={8}>+ {GOAL_CARD_STAGES.map((key, index) => {+ const done = stage === 'achieved' || index < current;+ const isCurrent = !done && index === current;++ return (+ <Fragment key={key}>+ {index > 0 && (+ <div className={cx(styles.connector, index <= current && styles.connectorDone)} />+ )}+ <Flexbox horizontal align={'center'} gap={6} style={{ flex: 'none' }}>+ <span+ className={cx(styles.dot, done && styles.dotDone, isCurrent && styles.dotCurrent)}+ style={isCurrent ? { borderColor: TONE_COLOR[tone] } : undefined}+ />+ <Text+ fontSize={12}+ weight={isCurrent ? 500 : undefined}+ style={{+ color: isCurrent+ ? cssVar.colorText+ : done+ ? cssVar.colorTextSecondary+ : cssVar.colorTextTertiary,+ }}+ >+ {t(`goalTask.stage.${key}`)}+ </Text>+ </Flexbox>+ </Fragment>+ );+ })}+ </Flexbox>+ );+});++StageTrack.displayName = 'GoalStageTrack';++export default StageTrack;diff --git a/src/features/Conversation/Messages/GoalTaskCard/deriveOperationGoals.test.ts b/src/features/Conversation/Messages/GoalTaskCard/deriveOperationGoals.test.tsindex 1470d7b13b9..05c5ae51454 100644--- a/src/features/Conversation/Messages/GoalTaskCard/deriveOperationGoals.test.ts+++ b/src/features/Conversation/Messages/GoalTaskCard/deriveOperationGoals.test.ts@@ -38,10 +38,83 @@ describe('deriveOperationGoals', () => {]);expect(goals).toEqual([- { criteriaCount: 2, goalId: 'goal-41', name: 'San Francisco night fog' },+ { criteriaCount: 2, goalId: 'goal-41', name: 'San Francisco night fog', source: 'tool' },]);});+ it('derives a card from a CLI agent creating a conversation goal with lh', () => {+ const goals = deriveOperationGoals([+ block([+ {+ apiName: 'Bash',+ arguments: JSON.stringify({+ command:+ 'lh goal create "整理 LobeHub 目标页区块清单" --conversation -r "需求" --criterion "至少 4 个区块" --criterion "保存为文稿" --json',+ description: 'Create LobeHub goal bound to conversation',+ }),+ id: 'toolu_create',+ identifier: 'claude-code',+ result: {+ content: JSON.stringify({+ edges: [],+ goal: { id: 'goal_P0NhivSBktCf', title: '整理 LobeHub 目标页区块清单' },+ turnToken: 'token',+ }),+ id: 'msg_create',+ },+ type: 'default',+ },+ {+ apiName: 'Bash',+ arguments: JSON.stringify({+ command: 'lh goal plan goal_P0NhivSBktCf --token token --file plan.json --json',+ }),+ id: 'toolu_plan',+ identifier: 'claude-code',+ result: { content: '{"recorded": true, "action": "tasks"}', id: 'msg_plan' },+ type: 'default',+ },+ ]),+ ]);++ expect(goals).toEqual([+ {+ criteriaCount: 2,+ goalId: 'goal_P0NhivSBktCf',+ name: '整理 LobeHub 目标页区块清单',+ source: 'command',+ },+ ]);+ });++ it('shows no command card before the goal exists, or after a failure', () => {+ const run = (+ id: string,+ command: string,+ result?: NonNullable<AssistantContentBlock['tools']>[number]['result'],+ ) => ({+ apiName: 'command_execution',+ arguments: JSON.stringify({ command }),+ id,+ identifier: 'codex',+ result,+ type: 'default' as const,+ });++ expect(+ deriveOperationGoals([+ block([+ run('running', 'lh goal create "Fog" --conversation --json'),+ run('failed', 'lh goal create "Fog" --conversation --json', {+ content: 'Error: An operation-bound token is required',+ error: { message: 'exit 1' },+ id: 'tool-failed',+ }),+ ]),+ ]),+ ).toEqual([]);+ });+it('ignores pending, failed, and non-Goal tool calls', () => {expect(deriveOperationGoals([@@ -109,7 +182,9 @@ describe('deriveOperationGoals', () => {]),]);- expect(goals).toEqual([{ criteriaCount: 2, goalId: 'goal_abc123', name: 'Weekly digest' }]);+ expect(goals).toEqual([+ { criteriaCount: 2, goalId: 'goal_abc123', name: 'Weekly digest', source: 'command' },+ ]);});it('falls back to the printed goal URL when the CLI output is not JSON', () => {@@ -132,7 +207,9 @@ describe('deriveOperationGoals', () => {]),]);- expect(goals).toEqual([{ criteriaCount: 0, goalId: 'goal_abc123', name: 'goal_abc123' }]);+ expect(goals).toEqual([+ { criteriaCount: 0, goalId: 'goal_abc123', name: 'goal_abc123', source: 'command' },+ ]);});it('recovers the goal id from truncated output with a shell notice suffix', () => {@@ -159,7 +236,12 @@ describe('deriveOperationGoals', () => {]);expect(goals).toEqual([- { criteriaCount: 1, goalId: 'goal_4aVZVqoD5jhu', name: '凭证委托场景全景' },+ {+ criteriaCount: 1,+ goalId: 'goal_4aVZVqoD5jhu',+ name: '凭证委托场景全景',+ source: 'command',+ },]);});diff --git a/src/features/Conversation/Messages/GoalTaskCard/deriveOperationGoals.ts b/src/features/Conversation/Messages/GoalTaskCard/deriveOperationGoals.tsindex e5cef0b055b..470692ac144 100644--- a/src/features/Conversation/Messages/GoalTaskCard/deriveOperationGoals.ts+++ b/src/features/Conversation/Messages/GoalTaskCard/deriveOperationGoals.ts@@ -6,6 +6,12 @@ export interface OperationGoal {/** The `goals` row the tool created — the card's pointer and its link target. */goalId: string;name: string;+ /**+ * What created it: the builtin `createGoal` tool, or a CLI agent's+ * `lh goal create --conversation` shell call (`/goal` in a heterogeneous+ * agent conversation).+ */+ source: 'command' | 'tool';}const isRecord = (value: unknown): value is Record<string, unknown> =>@@ -28,7 +34,7 @@ const deriveBuiltinGoal = (tool: ChatToolPayloadWithResult): OperationGoal[] =>const name = nonEmptyString(tool.result.state.name) ?? nonEmptyString(args?.name) ?? goalId;const criteriaCount = Array.isArray(args?.criteria) ? args.criteria.length : 0;- return [{ criteriaCount, goalId, name }];+ return [{ criteriaCount, goalId, name, source: 'tool' }];};const GOAL_CREATE_COMMAND = /\blh\s+goal\s+create\b/;@@ -82,6 +88,7 @@ const deriveCliGoal = (tool: ChatToolPayloadWithResult): OperationGoal[] => {criteriaCount: command.match(CRITERION_FLAG)?.length ?? 0,goalId,name: nonEmptyString(goal?.title) ?? titleMatch?.[1] ?? titleMatch?.[2] ?? goalId,+ source: 'command',},];};diff --git a/src/features/Conversation/Messages/GoalTaskCard/goalCardModel.test.ts b/src/features/Conversation/Messages/GoalTaskCard/goalCardModel.test.tsnew file mode 100644index 00000000000..58800c7b402--- /dev/null+++ b/src/features/Conversation/Messages/GoalTaskCard/goalCardModel.test.ts@@ -0,0 +1,170 @@+import { GOAL_ACCEPTANCE_TASK_TITLE } from '@lobechat/const/goal';+import type { GoalGraphNode, GoalGraphSnapshot, GoalItem } from '@lobechat/types';+import { describe, expect, it } from 'vitest';++import { buildGoalCardModel, windowPlanSteps } from './goalCardModel';++const T0 = new Date('2026-08-01T00:00:00Z');+const at = (minutes: number) => new Date(T0.getTime() + minutes * 60_000);+const NOW = at(120).getTime();++const goal = (overrides: Partial<GoalItem> = {}): GoalItem =>+ ({+ agentId: 'agt',+ completedAt: null,+ config: { recovery: { operationLeaseTimeoutMs: 15 * 60_000 } },+ createdAt: T0,+ id: 'goal-1',+ maxRounds: null,+ maxTotalCost: null,+ projectId: null,+ requirement: 'ship it',+ startedAt: T0,+ status: 'running',+ subjectId: null,+ subjectType: 'topic',+ title: 'Goal',+ updatedAt: T0,+ userId: 'user-1',+ workspaceId: null,+ ...overrides,+ }) as GoalItem;++let seq = 0;+const node = (overrides: Partial<GoalGraphNode> = {}): GoalGraphNode => {+ seq += 1;+ return {+ confidence: null,+ createdAt: at(seq),+ createdByAgentId: null,+ createdByUserId: null,+ description: null,+ goalId: 'goal-1',+ id: `n${seq}`,+ kind: 'task',+ priority: 0,+ resolvedAt: null,+ status: 'proposed',+ taskId: null,+ title: `step ${seq}`,+ updatedAt: at(seq),+ ...overrides,+ };+};++const snapshot = (overrides: Partial<GoalGraphSnapshot> = {}): GoalGraphSnapshot =>+ ({+ decisions: [],+ edges: [],+ events: [],+ goal: goal(),+ nodes: [],+ workVersions: [],+ ...overrides,+ }) as GoalGraphSnapshot;++const build = (overrides: Partial<GoalGraphSnapshot>) =>+ buildGoalCardModel(snapshot(overrides), { now: NOW });++describe('buildGoalCardModel', () => {+ it('reads a running goal with no task yet as planning', () => {+ const model = build({ nodes: [node({ kind: 'problem', status: 'active' })] });++ expect(model).toMatchObject({ stage: 'planning', steps: [], taskTotal: 0, tone: 'active' });+ });++ it('lays the plan out in order with each task state, and counts what closed', () => {+ const model = build({+ nodes: [+ node({ kind: 'problem', status: 'active' }),+ node({ status: 'resolved', title: 'research' }),+ node({ status: 'active', taskId: 'task-2', title: 'write', updatedAt: at(118) }),+ node({ title: 'save' }),+ node({ kind: 'finding', status: 'resolved' }),+ ],+ spend: { byTask: [], runs: 2, totalCost: 0.23, totalTokens: 1 },+ });++ expect(model.stage).toBe('executing');+ expect(model.steps.map(({ state, title }) => [title, state])).toEqual([+ ['research', 'done'],+ ['write', 'running'],+ ['save', 'queued'],+ ]);+ expect(model).toMatchObject({ findingCount: 1, taskDone: 1, taskTotal: 3, totalCost: 0.23 });+ });++ it('marks a task whose run went silent as lost', () => {+ const model = build({+ nodes: [node({ status: 'active', taskId: 'task-1', updatedAt: at(10) })],+ });++ expect(model.steps[0].state).toBe('lost');+ });++ it('shows a task the goal ended under as stopped, not running', () => {+ const model = build({+ goal: goal({ status: 'canceled', updatedAt: at(100) }),+ nodes: [node({ status: 'resolved' }), node({ status: 'active', updatedAt: at(99) })],+ });++ expect(model.steps.map((step) => step.state)).toEqual(['done', 'stopped']);+ });++ it('lets a pending decision color the stage as waiting on the user', () => {+ const model = build({+ decisions: [{ id: 'd1', status: 'pending' }] as never,+ goal: goal({ status: 'paused' }),+ nodes: [node({ status: 'resolved' }), node()],+ });++ expect(model).toMatchObject({ needsYou: 1, stage: 'executing', tone: 'waiting' });+ });++ it('reads a stopped goal whose tasks all closed as stopped at acceptance', () => {+ const model = build({+ goal: goal({ status: 'failed' }),+ nodes: [node({ status: 'resolved' }), node({ status: 'rejected' })],+ });++ expect(model).toMatchObject({ stage: 'verifying', tone: 'error' });+ });++ it('reaches the last stage once achieved', () => {+ expect(build({ goal: goal({ status: 'achieved' }) }).stage).toBe('achieved');+ });++ it('names the coordinator acceptance task with its fixed title', () => {+ const model = build({ nodes: [node({ title: GOAL_ACCEPTANCE_TASK_TITLE })] });++ expect(model.steps[0].titleKey).toBe('goalProcess.node.terminalAcceptance');+ });+});++describe('windowPlanSteps', () => {+ const steps = (states: string[]) =>+ states.map((state, index) => ({ id: `s${index}`, state, title: `s${index}` })) as never;++ it('shows the whole plan when it fits', () => {+ expect(windowPlanSteps(steps(['done', 'running']), 4)).toMatchObject({+ hiddenAfter: 0,+ hiddenBefore: 0,+ });+ });++ it('starts one step before the first open task and folds the rest', () => {+ const result = windowPlanSteps(+ steps(['done', 'done', 'done', 'running', 'queued', 'queued', 'queued']),+ 4,+ );++ expect(result.visible.map((step) => step.id)).toEqual(['s2', 's3', 's4', 's5']);+ expect(result).toMatchObject({ hiddenAfter: 1, hiddenBefore: 2 });+ });++ it('keeps the tail in view when every task closed', () => {+ const result = windowPlanSteps(steps(['done', 'done', 'done', 'done', 'done', 'done']), 4);++ expect(result).toMatchObject({ hiddenAfter: 0, hiddenBefore: 2 });+ });+});diff --git a/src/features/Conversation/Messages/GoalTaskCard/goalCardModel.ts b/src/features/Conversation/Messages/GoalTaskCard/goalCardModel.tsnew file mode 100644index 00000000000..c36f2e4b1c3--- /dev/null+++ b/src/features/Conversation/Messages/GoalTaskCard/goalCardModel.ts@@ -0,0 +1,157 @@+import type { GoalStatus } from '@lobechat/const/goal';+import type { GoalGraphSnapshot } from '@lobechat/types';++import { coordinatorNodeTitleKey } from '@/features/AgentGoals/ProcessControl/coordinatorCopy';+import {+ buildGoalGraphView,+ type GoalNodeView,+} from '@/features/AgentGoals/ProcessControl/goalGraphViewModel';++/** The goal's big stages, read left to right on the card. */+export const GOAL_CARD_STAGES = ['planning', 'executing', 'verifying', 'achieved'] as const;++export type GoalCardStage = (typeof GOAL_CARD_STAGES)[number];++/** How the current stage is doing — a stopped goal keeps its stage but changes color. */+export type GoalCardTone = 'active' | 'canceled' | 'error' | 'paused' | 'waiting';++export type PlanStepState =+ | 'done'+ | 'failed'+ | 'lost'+ | 'queued'+ | 'retired'+ | 'running'+ | 'stopped'+ | 'verifying'+ | 'waiting';++export interface PlanStep {+ id: string;+ state: PlanStepState;+ title: string;+ /** Locale key for a coordinator-authored fixed title (the terminal acceptance task). */+ titleKey?: string;+}++export interface GoalCardModel {+ findingCount: number;+ /** Steps folded after the visible window. */+ hiddenAfter: number;+ /** Steps folded before the visible window. */+ hiddenBefore: number;+ needsYou: number;+ stage: GoalCardStage;+ /** The visible window of the plan, in the order the tasks were planned. */+ steps: PlanStep[];+ taskDone: number;+ taskTotal: number;+ tone: GoalCardTone;+ totalCost: number;+}++const CLOSED_NODE_STATUSES = new Set(['resolved', 'rejected', 'retired']);+const CLOSED_STEP_STATES = new Set<PlanStepState>(['done', 'failed', 'retired']);++/** Same vocabulary as the goal map's task chips, reduced to what a chip can show. */+export const planStepState = (view: GoalNodeView): PlanStepState => {+ const { status } = view.node;+ if (status === 'resolved') return 'done';+ if (status === 'rejected') return 'failed';+ if (status === 'retired') return 'retired';+ // The goal closed under this run: it was interrupted, not still going.+ if (view.halted) return 'stopped';+ if (view.decision) return 'waiting';+ if (status === 'active') {+ if (view.isVerifying) return 'verifying';+ if (view.isStale) return 'lost';+ return 'running';+ }+ if (status === 'waiting' || view.blockers.length > 0) return 'waiting';+ return 'queued';+};++const resolveStage = (+ status: GoalStatus,+ taskTotal: number,+ allTasksClosed: boolean,+): GoalCardStage => {+ switch (status) {+ case 'achieved': {+ return 'achieved';+ }+ case 'review':+ case 'verifying': {+ return 'verifying';+ }+ case 'planning': {+ return 'planning';+ }+ }+ // A `/goal` run marks its goal running at creation, before the plan lands a Task.+ if (taskTotal === 0) return 'planning';+ // A goal that stopped after its tasks closed stopped at acceptance, not execution.+ return allTasksClosed && status !== 'running' ? 'verifying' : 'executing';+};++const resolveTone = (status: GoalStatus, needsYou: number): GoalCardTone => {+ if (status === 'canceled') return 'canceled';+ if (status === 'failed') return 'error';+ // A decision gate outranks pause: it is the reason the goal is not moving.+ if (needsYou > 0) return 'waiting';+ if (status === 'paused') return 'paused';+ return 'active';+};++/**+ * Keep the chain readable at any plan size: show a window that starts one step+ * before the first unfinished task, so the card always shows what just closed,+ * what is moving, and what comes next.+ */+export const windowPlanSteps = (steps: PlanStep[], maxSteps: number) => {+ if (steps.length <= maxSteps) return { hiddenAfter: 0, hiddenBefore: 0, visible: steps };++ const firstOpen = steps.findIndex((step) => !CLOSED_STEP_STATES.has(step.state));+ const focus = firstOpen === -1 ? steps.length - 1 : firstOpen;+ const start = Math.min(Math.max(focus - 1, 0), steps.length - maxSteps);++ return {+ hiddenAfter: steps.length - start - maxSteps,+ hiddenBefore: start,+ visible: steps.slice(start, start + maxSteps),+ };+};++/** Everything the conversation card shows about a goal, from one graph snapshot. */+export const buildGoalCardModel = (+ snapshot: GoalGraphSnapshot,+ { maxSteps = 4, now = Date.now() }: { maxSteps?: number; now?: number } = {},+): GoalCardModel => {+ const view = buildGoalGraphView(snapshot, now);+ const tasks = view.nodes.filter((item) => item.node.kind === 'task');+ const taskDone = tasks.filter((item) => CLOSED_NODE_STATUSES.has(item.node.status)).length;+ const needsYou = snapshot.decisions.filter((decision) => decision.status === 'pending').length;++ const { hiddenAfter, hiddenBefore, visible } = windowPlanSteps(+ tasks.map((item) => ({+ id: item.node.id,+ state: planStepState(item),+ title: item.node.title,+ titleKey: coordinatorNodeTitleKey(item),+ })),+ maxSteps,+ );++ return {+ findingCount: view.findings.length,+ hiddenAfter,+ hiddenBefore,+ needsYou,+ stage: resolveStage(snapshot.goal.status, tasks.length, taskDone === tasks.length),+ steps: visible,+ taskDone,+ taskTotal: tasks.length,+ tone: resolveTone(snapshot.goal.status, needsYou),+ totalCost: snapshot.spend?.totalCost ?? 0,+ };+};diff --git a/src/features/Conversation/Messages/GoalTaskCard/goalTaskProgress.test.ts b/src/features/Conversation/Messages/GoalTaskCard/goalTaskProgress.test.tsindex a1a5b9df544..b2b294a6c69 100644--- a/src/features/Conversation/Messages/GoalTaskCard/goalTaskProgress.test.ts+++ b/src/features/Conversation/Messages/GoalTaskCard/goalTaskProgress.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from 'vitest';-import { buildGoalStepSegments, getGoalStepPointer, getGoalTaskProgress } from './goalTaskProgress';+import { getGoalTaskProgress } from './goalTaskProgress';describe('getGoalTaskProgress', () => {it('reports how much of the graph is closed while it runs', () => {@@ -12,12 +12,20 @@ describe('getGoalTaskProgress', () => {it('falls back to the drafted criteria count before the graph is seeded', () => {expect(getGoalTaskProgress({ criteriaCount: 4, status: 'planning' })).toEqual({passed: 0,- phase: 'running',+ phase: 'planning',progress: 0,total: 4,});});+ it('reads a running goal without any Task yet as planning', () => {+ // `/goal` from a conversation adopts that run as the first planning turn and+ // marks the goal running before the plan lands its Tasks.+ expect(getGoalTaskProgress({ criteriaCount: 2, status: 'running', taskTotal: 0 }).phase).toBe(+ 'planning',+ );+ });+it('lets a waiting decision gate outrank the goal status', () => {// A goal keeps its `running` row while a gate is open; the card must still// read as blocked on the user, not as work in progress.@@ -37,59 +45,3 @@ describe('getGoalTaskProgress', () => {expect(getGoalTaskProgress({ criteriaCount: 1, status }).phase).toBe(phase);});});--describe('buildGoalStepSegments', () => {- it('maps one segment per task in plan order', () => {- expect(- buildGoalStepSegments(['resolved', 'active', 'proposed', 'waiting', 'rejected']),- ).toEqual(['done', 'active', 'pending', 'pending', 'done']);- });-- it('retired tasks count as closed steps', () => {- expect(buildGoalStepSegments(['retired', 'proposed'])).toEqual(['done', 'pending']);- });-- it('slices graphs longer than the segment cap, keeping the least advanced state', () => {- const statuses = Array.from({ length: 25 }, (_, index) =>- index < 12 ? 'resolved' : 'proposed',- );-- // ceil(25 / 12) = 3 tasks per segment: indices 0–11 done, 12–24 pending.- expect(buildGoalStepSegments(statuses)).toEqual([- ...Array.from({ length: 4 }, () => 'done'),- ...Array.from({ length: 5 }, () => 'pending'),- ]);- });-});--describe('getGoalStepPointer', () => {- const steps = [- { status: 'resolved', title: 'Reproduce' },- { status: 'active', title: 'Fix the parser' },- { status: 'proposed', title: 'Add regression coverage' },- ] as const;-- it('points at the first active task while one runs', () => {- expect(getGoalStepPointer([...steps], 'running')).toEqual({- kind: 'current',- title: 'Fix the parser',- });- });-- it('falls back to the first open task as up next when nothing is active', () => {- const paused = steps.map((step) =>- step.status === 'active' ? { ...step, status: 'waiting' as const } : step,- );-- expect(getGoalStepPointer(paused, 'paused')).toEqual({- kind: 'next',- title: 'Fix the parser',- });- });-- it('has no pointer once the goal reached a terminal phase', () => {- expect(getGoalStepPointer([...steps], 'achieved')).toBeUndefined();- expect(getGoalStepPointer([...steps], 'error')).toBeUndefined();- expect(getGoalStepPointer([...steps], 'canceled')).toBeUndefined();- });-});diff --git a/src/features/Conversation/Messages/GoalTaskCard/goalTaskProgress.ts b/src/features/Conversation/Messages/GoalTaskCard/goalTaskProgress.tsindex 4c10bd2e767..a404b043615 100644--- a/src/features/Conversation/Messages/GoalTaskCard/goalTaskProgress.ts+++ b/src/features/Conversation/Messages/GoalTaskCard/goalTaskProgress.ts@@ -1,11 +1,11 @@import type { GoalStatus } from '@lobechat/const/goal';-import type { GoalNodeStatus } from '@lobechat/types';export type GoalTaskPhase =| 'achieved'| 'canceled'| 'error'| 'paused'+ | 'planning'| 'repairing'| 'review'| 'running'@@ -21,9 +21,17 @@ interface GoalTaskProgressInput {taskTotal?: number;}-const resolvePhase = (status?: GoalStatus, pendingDecisions = 0): GoalTaskPhase => {+const resolvePhase = (status?: GoalStatus, pendingDecisions = 0, taskTotal = 0): GoalTaskPhase => {if (pendingDecisions > 0) return 'waiting';switch (status) {+ // A goal adopted from a conversation turns `running` the moment it is+ // created, before its first plan lands any Task — both read as planning.+ case 'planning': {+ return 'planning';+ }+ case 'running': {+ return taskTotal > 0 ? 'running' : 'planning';+ }case 'achieved': {return 'achieved';}@@ -59,70 +67,8 @@ export const getGoalTaskProgress = (input: GoalTaskProgressInput) => {return {passed,- phase: resolvePhase(input.status, input.pendingDecisions),+ phase: resolvePhase(input.status, input.pendingDecisions, input.taskTotal),progress: total > 0 ? Math.round((passed / total) * 100) : 0,total,};};--export type GoalStepState = 'active' | 'done' | 'pending';--export interface GoalStep {- status: GoalNodeStatus;- title: string;-}--const CLOSED_NODE_STATUSES = new Set<GoalNodeStatus>(['rejected', 'resolved', 'retired']);--export const toGoalStepState = (status: GoalNodeStatus): GoalStepState => {- if (CLOSED_NODE_STATUSES.has(status)) return 'done';- if (status === 'active') return 'active';- return 'pending';-};--/** A chat card can show at most this many step segments before they stop reading as steps. */-export const MAX_GOAL_STEP_SEGMENTS = 12;--/**- * One track segment per Task so the card reads as a plan of steps instead of one- * anonymous bar. Graphs longer than the segment cap are sliced evenly; a slice- * keeps the least advanced state it contains (pending < active < done), so the- * fill still advances left to right and never overstates progress.- */-export const buildGoalStepSegments = (statuses: GoalNodeStatus[]): GoalStepState[] => {- const states = statuses.map(toGoalStepState);- if (states.length <= MAX_GOAL_STEP_SEGMENTS) return states;-- const perSegment = Math.ceil(states.length / MAX_GOAL_STEP_SEGMENTS);- const segments: GoalStepState[] = [];- for (let start = 0; start < states.length; start += perSegment) {- const slice = states.slice(start, start + perSegment);- segments.push(- slice.includes('pending') ? 'pending' : slice.includes('active') ? 'active' : 'done',- );- }- return segments;-};--export interface GoalStepPointer {- kind: 'current' | 'next';- title: string;-}--/**- * The step the card should point at: the first active Task while one runs, else- * the first not-yet-closed Task as what's up next. Terminal phases have no- * pointer — the phase word already says the outcome.- */-export const getGoalStepPointer = (- steps: GoalStep[],- phase: GoalTaskPhase,-): GoalStepPointer | undefined => {- if (['achieved', 'canceled', 'error'].includes(phase)) return undefined;-- const active = steps.find((step) => step.status === 'active');- if (active) return { kind: 'current', title: active.title };-- const next = steps.find((step) => !CLOSED_NODE_STATUSES.has(step.status));- return next ? { kind: 'next', title: next.title } : undefined;-};diff --git a/src/features/Conversation/Messages/GoalTaskCard/index.tsx b/src/features/Conversation/Messages/GoalTaskCard/index.tsxindex 0b385de2a6e..8fde56d581f 100644--- a/src/features/Conversation/Messages/GoalTaskCard/index.tsx+++ b/src/features/Conversation/Messages/GoalTaskCard/index.tsx@@ -1,61 +1,52 @@'use client';-import { Center, Flexbox, Icon } from '@lobehub/ui';+import { Flexbox } from '@lobehub/ui';import { Text } from '@lobehub/ui/base-ui';import { createStaticStyles, cssVar } from 'antd-style';-import { ChevronRightIcon, CornerDownRightIcon, TargetIcon } from 'lucide-react';-import { memo } from 'react';+import { ChevronRightIcon } from 'lucide-react';+import { memo, useMemo } from 'react';import { useTranslation } from 'react-i18next';-import RingLoadingIcon from '@/components/RingLoading';+import { formatGoalCost } from '@/features/AgentGoals/GoalProgress';+import GoalStatusGlyph from '@/features/AgentGoals/GoalStatusGlyph';+import RunningGlyph from '@/features/Home/components/RunningGlyph';import { useChatStore } from '@/store/chat';import type { OperationGoal } from './deriveOperationGoals';+import { buildGoalCardModel } from './goalCardModel';import GoalElapsedTime from './GoalElapsedTime';-import GoalStatusLine from './GoalStatusLine';import type { GoalTaskPhase } from './goalTaskProgress';-import { getGoalStepPointer } from './goalTaskProgress';+import PlanChain from './PlanChain';+import StageTrack from './StageTrack';import { useGoalTaskStatus } from './useGoalTaskStatus';-const ACTIVE_PHASES = new Set<GoalTaskPhase>(['repairing', 'running', 'verifying']);+const ACTIVE_PHASES = new Set<GoalTaskPhase>(['planning', 'repairing', 'running', 'verifying']);const styles = createStaticStyles(({ css }) => ({card: css`cursor: pointer;width: 100%;- padding-block: 10px;- padding-inline: 12px;+ padding-block: 12px;+ padding-inline: 14px;border: 1px solid ${cssVar.colorBorderSecondary};- border-radius: 8px;+ border-radius: 10px;background: ${cssVar.colorBgElevated};&:hover {- background: ${cssVar.colorFillQuaternary};+ border-color: ${cssVar.colorBorder};}`,chevron: css`flex-shrink: 0;color: ${cssVar.colorTextTertiary};`,- icon: css`- flex-shrink: 0;-- width: 36px;- height: 36px;- border-radius: 8px;-- color: ${cssVar.colorTextSecondary};-- background: ${cssVar.colorFillTertiary};- `,- stepIcon: css`- flex-shrink: 0;- `,- stepLine: css`+ meta: css`font-size: 12px;+ font-variant-numeric: tabular-nums;color: ${cssVar.colorTextTertiary};+ white-space: nowrap;`,title: css`min-width: 0;@@ -67,21 +58,20 @@ const styles = createStaticStyles(({ css }) => ({const GoalCard = memo<{ goal: OperationGoal }>(({ goal }) => {const { t } = useTranslation('chat');const openGoalPortal = useChatStore((s) => s.openGoal);- const { progress, startedAt, steps, title } = useGoalTaskStatus({+ const { progress, snapshot, startedAt, title } = useGoalTaskStatus({criteriaCount: goal.criteriaCount,goalId: goal.goalId,});+ const model = useMemo(() => (snapshot ? buildGoalCardModel(snapshot) : undefined), [snapshot]);const isActive = ACTIVE_PHASES.has(progress.phase);- const stepPointer = getGoalStepPointer(steps, progress.phase);+ const requirement = snapshot?.goal.requirement?.trim();// Same destination as the tool card: the goal's progress beside the chat.const openGoal = () => openGoalPortal(goal.goalId);return (<Flexbox- horizontal- align={'center'}className={styles.card}- gap={10}+ gap={12}role={'button'}tabIndex={0}onClick={openGoal}@@ -91,43 +81,56 @@ const GoalCard = memo<{ goal: OperationGoal }>(({ goal }) => {openGoal();}}>- <Center className={styles.icon}>- {isActive ? (- <RingLoadingIcon- ringColor={cssVar.colorBorder}- size={18}- style={{ color: cssVar.colorWarning }}- />- ) : (- <Icon icon={TargetIcon} size={20} />- )}- </Center>- <Flexbox flex={1} gap={2} style={{ minWidth: 0 }}>- <Text ellipsis className={styles.title}>- {title ?? goal.name}- </Text>- <GoalStatusLine- passed={progress.passed}- phase={progress.phase}- statuses={steps.map((step) => step.status)}- total={progress.total}- />- {stepPointer && (- <Flexbox horizontal align={'center'} gap={4}>- <Icon- className={styles.stepIcon}- color={cssVar.colorTextTertiary}- icon={CornerDownRightIcon}- size={12}- />- <Text ellipsis className={styles.stepLine}>- {t(`goalTask.${stepPointer.kind}Step`, { title: stepPointer.title })}- </Text>- </Flexbox>+ <Flexbox gap={2}>+ <Flexbox horizontal align={'center'} gap={8}>+ {isActive || !snapshot ? (+ <RunningGlyph size={14} />+ ) : (+ <GoalStatusGlyph size={14} status={snapshot.goal.status} />+ )}+ <Text ellipsis className={styles.title} style={{ flex: 1 }}>+ {title ?? goal.name}+ </Text>+ <Text className={styles.meta} style={{ color: cssVar.colorTextSecondary }}>+ {t(`goalTask.status.${progress.phase}`)}+ </Text>+ {isActive && <GoalElapsedTime startedAt={startedAt} />}+ <ChevronRightIcon className={styles.chevron} size={16} />+ </Flexbox>+ {requirement && requirement !== (title ?? goal.name) && (+ <Text ellipsis fontSize={12} style={{ paddingInlineStart: 22 }} type={'secondary'}>+ {requirement}+ </Text>)}</Flexbox>- {isActive && <GoalElapsedTime startedAt={startedAt} />}- <ChevronRightIcon className={styles.chevron} size={16} />+ {model && (+ <>+ <StageTrack stage={model.stage} tone={model.tone} />+ <PlanChain model={model} />+ {(model.taskTotal > 0 || model.needsYou > 0 || model.totalCost > 0) && (+ <Flexbox horizontal align={'center'} gap={12}>+ {model.needsYou > 0 && (+ <span className={styles.meta} style={{ color: cssVar.colorWarning }}>+ {t('goalList.needsYou', { count: model.needsYou })}+ </span>+ )}+ {model.taskTotal > 0 && (+ <span className={styles.meta}>+ {t('goalList.taskProgress', { done: model.taskDone, total: model.taskTotal })}+ </span>+ )}+ {model.findingCount > 0 && (+ <span className={styles.meta}>+ {t('goalList.findings', { count: model.findingCount })}+ </span>+ )}+ {model.totalCost > 0 && (+ <span className={styles.meta}>{formatGoalCost(model.totalCost)}</span>+ )}+ </Flexbox>+ )}+ </>+ )}</Flexbox>);});diff --git a/src/features/Conversation/Messages/GoalTaskCard/useGoalTaskStatus.test.ts b/src/features/Conversation/Messages/GoalTaskCard/useGoalTaskStatus.test.tsindex c7ec92c7247..6e5f3cf1a32 100644--- a/src/features/Conversation/Messages/GoalTaskCard/useGoalTaskStatus.test.ts+++ b/src/features/Conversation/Messages/GoalTaskCard/useGoalTaskStatus.test.ts@@ -81,28 +81,4 @@ describe('useGoalTaskStatus', () => {expect(result.current.progress.phase).toBe('waiting');});-- it('exposes the task nodes as steps in graph creation order', () => {- const task = (id: string, status: string, createdAt: string, title: string) => ({- createdAt: new Date(createdAt),- id,- kind: 'task',- status,- title,- });- mocks.goalGraphById['goal-1'] = snapshot({- nodes: [- task('w2', 'active', '2026-08-14T08:05:00.000Z', 'Fix the parser'),- task('w1', 'resolved', '2026-08-14T08:00:00.000Z', 'Reproduce'),- { id: 'f1', kind: 'finding', status: 'resolved', title: 'Root cause' },- ] as never,- });-- const { result } = renderHook(() => useGoalTaskStatus({ goalId: 'goal-1' }));-- expect(result.current.steps).toEqual([- { status: 'resolved', title: 'Reproduce' },- { status: 'active', title: 'Fix the parser' },- ]);- });});diff --git a/src/features/Conversation/Messages/GoalTaskCard/useGoalTaskStatus.ts b/src/features/Conversation/Messages/GoalTaskCard/useGoalTaskStatus.tsindex be14a16c2f7..b15f4c90c1a 100644--- a/src/features/Conversation/Messages/GoalTaskCard/useGoalTaskStatus.ts+++ b/src/features/Conversation/Messages/GoalTaskCard/useGoalTaskStatus.ts@@ -1,11 +1,11 @@import { goalSelectors, useGoalStore } from '@/store/goal';-import { getGoalTaskProgress, type GoalStep } from './goalTaskProgress';+import { getGoalTaskProgress } from './goalTaskProgress';/**- * Live Goal status for one `goals` row: the graph snapshot → phase, the Tasks- * as ordered steps, and how much of them is closed. The card only holds the- * goal id, so everything else is fetched here.+ * Live Goal status for one `goals` row: the graph snapshot → phase and how much+ * of its Tasks is closed. The card only holds the goal id, so everything else is+ * fetched here.*/export const useGoalTaskStatus = ({criteriaCount = 0,@@ -19,10 +19,6 @@ export const useGoalTaskStatus = ({const snapshot = useGoalStore(goalSelectors.goalGraph(goalId));const taskNodes = snapshot?.nodes.filter((node) => node.kind === 'task') ?? [];- // The graph numbers Tasks in creation order; the step track must read the same.- const steps: GoalStep[] = [...taskNodes]- .sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime())- .map((node) => ({ status: node.status, title: node.title }));return {agentId: snapshot?.goal.agentId ?? undefined,@@ -36,8 +32,8 @@ export const useGoalTaskStatus = ({).length,taskTotal: taskNodes.length,}),+ snapshot,startedAt: snapshot?.goal.startedAt ?? undefined,- steps,title: snapshot?.goal.title,};};diff --git a/src/features/Conversation/WorkingSidebar/GoalSection/GoalWorkflowCard.tsx b/src/features/Conversation/WorkingSidebar/GoalSection/GoalWorkflowCard.tsxindex 7e05fd4c12f..6d23cd96e86 100644--- a/src/features/Conversation/WorkingSidebar/GoalSection/GoalWorkflowCard.tsx+++ b/src/features/Conversation/WorkingSidebar/GoalSection/GoalWorkflowCard.tsx@@ -18,10 +18,10 @@ 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 {+ buildGoalStepSegments,type GoalWorkflowRow,MAX_VISIBLE_WORKFLOW_ROWS,sliceVisibleWorkflowRows,diff --git a/src/features/Conversation/WorkingSidebar/GoalSection/goalWorkflowView.test.ts b/src/features/Conversation/WorkingSidebar/GoalSection/goalWorkflowView.test.tsindex 963a1ddf1d9..2e36f3a8e34 100644--- a/src/features/Conversation/WorkingSidebar/GoalSection/goalWorkflowView.test.ts+++ b/src/features/Conversation/WorkingSidebar/GoalSection/goalWorkflowView.test.ts@@ -1,8 +1,8 @@+import type { GoalNodeStatus } from '@lobechat/types';import { describe, expect, it } from 'vitest';-import type { GoalStep } from '@/features/Conversation/Messages/GoalTaskCard/goalTaskProgress';-import {+ buildGoalStepSegments,buildWorkflowRows,MAX_VISIBLE_WORKFLOW_ROWS,mergeTopicGoals,@@ -13,14 +13,14 @@ import {const step = (id: string, status: string, title = id) => ({id,- status: status as GoalStep['status'],+ status: status as GoalNodeStatus,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' }],+ [{ criteriaCount: 2, goalId: 'goal-tool', name: 'From tool', source: 'tool' }],[{ goal: { id: 'goal-tool', title: 'Persisted copy' } },{ goal: { id: 'goal-cli', title: 'Created by lh' } },@@ -29,17 +29,41 @@ describe('mergeTopicGoals', () => {);expect(merged).toEqual([- { criteriaCount: 2, goalId: 'goal-tool', name: 'From tool' },- { criteriaCount: 0, goalId: 'goal-cli', name: 'Created by lh' },+ { criteriaCount: 2, goalId: 'goal-tool', name: 'From tool', source: 'tool' },+ { criteriaCount: 0, goalId: 'goal-cli', name: 'Created by lh', source: 'command' },]);});it('returns the derived goals untouched when nothing is persisted yet', () => {- const derived = [{ criteriaCount: 1, goalId: 'goal-a', name: 'A' }];+ const derived = [{ criteriaCount: 1, goalId: 'goal-a', name: 'A', source: 'tool' as const }];expect(mergeTopicGoals(derived, undefined)).toEqual(derived);});});+describe('buildGoalStepSegments', () => {+ it('maps one segment per task in plan order', () => {+ expect(+ buildGoalStepSegments(['resolved', 'active', 'proposed', 'waiting', 'rejected']),+ ).toEqual(['done', 'active', 'pending', 'pending', 'done']);+ });++ it('retired tasks count as closed steps', () => {+ expect(buildGoalStepSegments(['retired', 'proposed'])).toEqual(['done', 'pending']);+ });++ it('slices graphs longer than the segment cap, keeping the least advanced state', () => {+ const statuses = Array.from({ length: 25 }, (_, index): GoalNodeStatus =>+ index < 12 ? 'resolved' : 'proposed',+ );++ // ceil(25 / 12) = 3 tasks per segment: indices 0–11 done, 12–24 pending.+ expect(buildGoalStepSegments(statuses)).toEqual([+ ...Array.from({ length: 4 }, () => 'done'),+ ...Array.from({ length: 5 }, () => 'pending'),+ ]);+ });+});+describe('buildWorkflowRows', () => {it('maps node statuses to row states and attaches assignees', () => {const rows = buildWorkflowRows(diff --git a/src/features/Conversation/WorkingSidebar/GoalSection/goalWorkflowView.ts b/src/features/Conversation/WorkingSidebar/GoalSection/goalWorkflowView.tsindex 5162bac7076..81b5dae2d8e 100644--- a/src/features/Conversation/WorkingSidebar/GoalSection/goalWorkflowView.ts+++ b/src/features/Conversation/WorkingSidebar/GoalSection/goalWorkflowView.ts@@ -1,7 +1,6 @@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';@@ -16,7 +15,7 @@ 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 }[],+ nodes: { id: string; status: GoalNodeStatus; title: string }[],assignees?: Record<string, string>,): GoalWorkflowRow[] =>nodes.map((node) => ({@@ -32,8 +31,7 @@ export const buildWorkflowRows = (title: node.title,}));-/** Row states as graph node statuses, so the step track can reuse the- * message card's segmentation (cap + conservative slicing) unchanged. */+/** Row states as graph node statuses, fed to the step track's segmentation. */export const toSegmentStatuses = (rows: GoalWorkflowRow[]): GoalNodeStatus[] =>rows.map((row) =>row.state === 'done'@@ -45,6 +43,38 @@ export const toSegmentStatuses = (rows: GoalWorkflowRow[]): GoalNodeStatus[] =>: 'proposed',);+export type GoalStepState = 'active' | 'done' | 'pending';++const toGoalStepState = (status: GoalNodeStatus): GoalStepState => {+ if (CLOSED_STEP_STATUSES.has(status)) return 'done';+ if (status === 'active') return 'active';+ return 'pending';+};++/** A step track can show at most this many segments before they stop reading as steps. */+export const MAX_GOAL_STEP_SEGMENTS = 12;++/**+ * One track segment per Task so the card reads as a plan of steps instead of one+ * anonymous bar. Graphs longer than the segment cap are sliced evenly; a slice+ * keeps the least advanced state it contains (pending < active < done), so the+ * fill still advances left to right and never overstates progress.+ */+export const buildGoalStepSegments = (statuses: GoalNodeStatus[]): GoalStepState[] => {+ const states = statuses.map(toGoalStepState);+ if (states.length <= MAX_GOAL_STEP_SEGMENTS) return states;++ const perSegment = Math.ceil(states.length / MAX_GOAL_STEP_SEGMENTS);+ const segments: GoalStepState[] = [];+ for (let start = 0; start < states.length; start += perSegment) {+ const slice = states.slice(start, start + perSegment);+ segments.push(+ slice.includes('pending') ? 'pending' : slice.includes('active') ? 'active' : 'done',+ );+ }+ return segments;+};+export interface GoalWorkflowSummary {done: number;running: number;@@ -70,7 +100,9 @@ export const sliceVisibleWorkflowRows = (* (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.+ * position and richer metadata; persisted-only goals follow, deduped by id,+ * as `command` goals — only a CLI agent's shell call leaves a goal without a+ * derivable tool result.*/export const mergeTopicGoals = (derived: OperationGoal[],@@ -80,7 +112,14 @@ export const mergeTopicGoals = (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 [+ {+ criteriaCount: 0,+ goalId: goal.id,+ name: goal.title?.trim() || goal.id,+ source: 'command' as const,+ },+ ];});return [...derived, ...linked];diff --git a/src/features/Conversation/WorkingSidebar/GoalSection/useGoalSection.ts b/src/features/Conversation/WorkingSidebar/GoalSection/useGoalSection.tsindex b3718aebffb..4e575489b27 100644--- a/src/features/Conversation/WorkingSidebar/GoalSection/useGoalSection.ts+++ b/src/features/Conversation/WorkingSidebar/GoalSection/useGoalSection.ts@@ -70,7 +70,9 @@ export interface GoalWorkflowView {* 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 => {+export const useGoalWorkflow = (+ goal: Pick<OperationGoal, 'criteriaCount' | 'goalId' | 'name'>,+): GoalWorkflowView => {const useFetchGoalGraph = useGoalStore((s) => s.useFetchGoalGraph);const { error, isLoading, mutate } = useFetchGoalGraph(goal.goalId);const snapshot = useGoalStore(goalSelectors.goalGraph(goal.goalId));