Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(desktop): workflow 卡片入口化——点击打开后台任务面板详情
Kafeifei614c72302106
diff --git a/apps/desktop/src/renderer/__tests__/AgentTaskCard.test.ts b/apps/desktop/src/renderer/__tests__/AgentTaskCard.test.tsindex 1188d77bf4..8ee58c909a 100644--- a/apps/desktop/src/renderer/__tests__/AgentTaskCard.test.ts+++ b/apps/desktop/src/renderer/__tests__/AgentTaskCard.test.ts@@ -13,6 +13,12 @@ vi.mock('react-i18next', () => ({if (key === 'chat.agentTask.status.running') return 'Running';if (key === 'chat.agentTask.tokens') return `${vars?.count} tokens`;if (key === 'chat.agentTask.toolUses') return `${vars?.count} tool uses`;+ if (key === 'chat.agentTask.workflowProgressLine') {+ return `${vars?.phase} · ${vars?.done}/${vars?.total} Agent`;+ }+ if (key === 'chat.agentTask.workflowProgressCount') {+ return `${vars?.done}/${vars?.total} Agent`;+ }return key;},}),@@ -25,6 +31,13 @@ vi.mock('@/hooks/useExpandedBlockMemory', () => ({}),}));+const { openBackgroundTasksTabMock } = vi.hoisted(() => ({+ openBackgroundTasksTabMock: vi.fn().mockResolvedValue(undefined),+}));+vi.mock('@/features/right-sidebar/lib/openBackgroundTasksTab', () => ({+ openBackgroundTasksTab: openBackgroundTasksTabMock,+}));+import { AgentTaskCard } from '@/components/chat/AgentTaskCard';describe('AgentTaskCard', () => {@@ -186,4 +199,153 @@ describe('AgentTaskCard', () => {);expect(stopButton(noSession.container)).toBeNull();});++ // workflow-card:整卡 = 后台任务面板入口 -------------------------------------+ const headerButton = (container: HTMLElement) =>+ container.querySelector<HTMLButtonElement>('button[aria-label="chat.agentTask.openInPanel"]');++ it('opens the background tasks panel focused on the task when a workflow card is clicked', () => {+ openBackgroundTasksTabMock.mockClear();+ const { container } = render(+ React.createElement(AgentTaskCard, {+ sessionId: 'session-1',+ update: {+ provider: 'claude-code',+ taskId: 'wf-1',+ status: 'running',+ taskType: 'local_workflow',+ workflowName: 'Release pipeline',+ },+ }),+ );+ const btn = headerButton(container);+ expect(btn).not.toBeNull();+ // workflow 卡不是展开 toggle:无 aria-expanded。+ expect(btn!.hasAttribute('aria-expanded')).toBe(false);+ act(() => {+ btn!.click();+ });+ expect(openBackgroundTasksTabMock).toHaveBeenCalledWith('session-1', { focusTaskId: 'wf-1' });+ });++ it('degrades to a no-op when sessionId or taskId is missing on a workflow card', () => {+ openBackgroundTasksTabMock.mockClear();+ const { container } = render(+ React.createElement(AgentTaskCard, {+ // sessionId 缺失 → 点击不跳转,外观不变。+ update: {+ provider: 'claude-code',+ taskId: 'wf-1',+ status: 'running',+ taskType: 'local_workflow',+ },+ }),+ );+ const btn = headerButton(container);+ expect(btn).not.toBeNull();+ act(() => {+ btn!.click();+ });+ expect(openBackgroundTasksTabMock).not.toHaveBeenCalled();+ });++ it('renders no inline expand region for workflow cards', () => {+ const { container } = render(+ React.createElement(AgentTaskCard, {+ sessionId: 'session-1',+ update: {+ provider: 'claude-code',+ taskId: 'wf-1',+ status: 'completed',+ taskType: 'local_workflow',+ workflowName: 'Release pipeline',+ description: 'WORKFLOW_DESCRIPTION_HIDDEN',+ summary: 'WORKFLOW_SUMMARY_HIDDEN',+ },+ }),+ );+ // useExpandedBlockMemory mock 恒为 expanded=true,仍不得渲染展开区内容。+ expect(container.textContent).not.toContain('WORKFLOW_DESCRIPTION_HIDDEN');+ expect(container.textContent).not.toContain('WORKFLOW_SUMMARY_HIDDEN');+ expect(container.querySelector('[aria-expanded]')).toBeNull();+ });++ const progressLine = (container: HTMLElement) =>+ container.querySelector('[data-workflow-progress-line="true"]');++ it('renders the live progress line from workflowProgress entries', () => {+ const { container } = render(+ React.createElement(AgentTaskCard, {+ sessionId: 'session-1',+ update: {+ provider: 'claude-code',+ taskId: 'wf-1',+ status: 'running',+ taskType: 'local_workflow',+ workflowProgress: [+ { type: 'workflow_phase', index: 0, title: 'Build' },+ { type: 'workflow_agent', index: 1, label: 'a', phaseTitle: 'Build', state: 'done' },+ { type: 'workflow_agent', index: 2, label: 'b', phaseTitle: 'Test', state: 'progress' },+ { type: 'workflow_agent', index: 3, label: 'c', phaseTitle: 'Test', state: 'error' },+ ],+ },+ }),+ );+ expect(progressLine(container)?.textContent).toBe('Test · 2/3 Agent');+ });++ it('falls back to counts only when no running agent carries a phaseTitle', () => {+ const { container } = render(+ React.createElement(AgentTaskCard, {+ sessionId: 'session-1',+ update: {+ provider: 'claude-code',+ taskId: 'wf-1',+ status: 'completed',+ taskType: 'local_workflow',+ workflowProgress: [+ { type: 'workflow_agent', index: 0, label: 'a', state: 'done' },+ { type: 'workflow_agent', index: 1, label: 'b', state: 'done' },+ ],+ },+ }),+ );+ expect(progressLine(container)?.textContent).toBe('2/2 Agent');+ });++ it('renders no progress line when workflowProgress is absent, and keeps non-workflow cards off the panel entry', () => {+ openBackgroundTasksTabMock.mockClear();+ const workflow = render(+ React.createElement(AgentTaskCard, {+ sessionId: 'session-1',+ update: {+ provider: 'claude-code',+ taskId: 'wf-1',+ status: 'running',+ taskType: 'local_workflow',+ },+ }),+ );+ expect(progressLine(workflow.container)).toBeNull();++ const normal = render(+ React.createElement(AgentTaskCard, {+ sessionId: 'session-1',+ update: {+ provider: 'claude-code',+ taskId: 'task-1',+ status: 'running',+ title: 'Inspect files',+ },+ }),+ );+ // 普通卡头部仍是展开 toggle,不触发面板。+ const toggleBtn = normal.container.querySelector<HTMLButtonElement>('button[aria-expanded]');+ expect(toggleBtn).not.toBeNull();+ act(() => {+ toggleBtn!.click();+ });+ expect(openBackgroundTasksTabMock).not.toHaveBeenCalled();+ expect(progressLine(normal.container)).toBeNull();+ });});diff --git a/apps/desktop/src/renderer/components/chat/AgentTaskCard.tsx b/apps/desktop/src/renderer/components/chat/AgentTaskCard.tsxindex 946f418418..495719ec56 100644--- a/apps/desktop/src/renderer/components/chat/AgentTaskCard.tsx+++ b/apps/desktop/src/renderer/components/chat/AgentTaskCard.tsx@@ -6,6 +6,7 @@ import {ChevronRight,CircleStop,LoaderCircle,+ PanelRight,Square,SquareTerminal,Workflow,@@ -17,9 +18,9 @@ import { Collapse } from '@/components/ui/collapse';import { Spinner } from '@/components/ui/spinner';import type { AgentTaskUpdate, ChatMessage } from '@/hooks/useCCAgentChat';import { isRemoteSession } from '@/lib/makerTransport';+import { openBackgroundTasksTab } from '@/features/right-sidebar/lib/openBackgroundTasksTab';import { cn } from '@/lib/utils';import { formatModelShortLabel } from '@/lib/modelShortLabel';-import { WorkflowAgentTree } from './WorkflowAgentTree';interface AgentTaskCardProps {toolCall?: ChatMessage;@@ -32,8 +33,8 @@ interface AgentTaskCardProps {*/subagentModel?: string;/**- * workflow-card: 当前会话 id。仅 workflow 卡片用来经 IPC 拉逐 agent 进度树- * (getWorkflowProgress(sessionId, taskId));普通 Agent/Task 卡片不需要。+ * 当前会话 id。workflow 卡用于打开右栏后台任务面板并定位详情;stop 按钮+ * 定位任务也依赖它。*/sessionId?: string;}@@ -98,8 +99,8 @@ export function AgentTaskCard({ toolCall, update, result, subagentModel, session);// workflow-card: Workflow 工具在父会话事件流里是单个 local_workflow 任务(内部子 agent// 不发独立 task 事件,只有 workflow 级聚合进度)。按 taskType / toolName 识别:标题优先取- // workflowName、头像换 Workflow 图标、provider 标签显示 "Workflow";其余(状态 / 聚合- // usage / 展开详情)复用本卡既有逻辑。+ // workflowName、头像换 Workflow 图标、provider 标签显示 "Workflow"。workflow 卡不展开 ——+ // 主视图在右栏「后台任务」面板,整卡是打开面板并定位详情的入口。const isWorkflow = update?.taskType === 'local_workflow' || toolCall?.toolName === 'Workflow';// bash-task-card: 后台 Bash(run_in_background)与子 Agent 共用本卡,但视觉上// 是「后台命令」—— 终端图标 + shell provider 标签,避免用户把跑测试的 bash@@ -152,6 +153,45 @@ export function AgentTaskCard({ toolCall, update, result, subagentModel, session.finally(() => setStopping(false));}, [sessionId, update?.taskId]);+ // workflow 卡整卡点击 → 打开右栏后台任务面板并定位本任务;sessionId / taskId+ // 任一缺失(历史孤儿卡)时降级 no-op,外观不变。+ const workflowTaskId = update?.taskId;+ const openInPanel = useCallback(() => {+ if (!sessionId || !workflowTaskId) return;+ void openBackgroundTasksTab(sessionId, { focusTaskId: workflowTaskId });+ }, [sessionId, workflowTaskId]);++ // workflow 摘要行:当前运行中 agent 的 phaseTitle + 已收口/总数。收口词表与后台+ // 任务面板同口径(事件流 done/error;wf 文件 failed/stopped/killed)。+ const workflowSummary = useMemo(() => {+ if (!isWorkflow) return null;+ const entries = update?.workflowProgress;+ if (!entries || entries.length === 0) return null;+ let total = 0;+ let done = 0;+ let phase: string | undefined;+ for (const entry of entries) {+ if (entry.type !== 'workflow_agent') continue;+ total += 1;+ const state = entry.state;+ if (+ state === 'done' ||+ state === 'error' ||+ state === 'failed' ||+ state === 'stopped' ||+ state === 'killed'+ ) {+ done += 1;+ } else if (+ (state === 'start' || state === 'progress' || state === 'running') &&+ entry.phaseTitle+ ) {+ phase = entry.phaseTitle;+ }+ }+ return total > 0 ? { phase, done, total } : null;+ }, [isWorkflow, update?.workflowProgress]);+const meta = useMemo(() => {const parts: Array<{ key: string; text: string }> = [{ key: 'provider', text: providerLabel },@@ -169,28 +209,22 @@ export function AgentTaskCard({ toolCall, update, result, subagentModel, sessionreturn (<div className="flex w-full justify-start">- <div- // workflow-card: /workflows 命令据此 data 属性在**本会话作用域内**定位最近一张- // workflow 卡(data-workflow-session 限定会话,防多会话同挂 DOM 时选错),并用- // data-workflow-expandkey(= 本卡的 useExpandedBlockMemory blockId)命令式展开它。- {...(isWorkflow- ? {- 'data-workflow-card': 'true',- 'data-workflow-session': sessionId ?? '',- 'data-workflow-expandkey': blockId,- }- : {})}- className="w-full rounded-[12px] border border-[var(--border-default)] bg-[var(--surface-elevated)] px-3 py-2"- >- {/* 折叠头 = 展开 toggle + 可选的停止按钮。button 不能嵌套,停止按钮以- 兄弟节点挂在 toggle 右侧(仅 running 时出现)。 */}+ <div className="w-full rounded-[12px] border border-[var(--border-default)] bg-[var(--surface-elevated)] px-3 py-2">+ {/* 头部按钮:普通卡 = 展开 toggle;workflow 卡 = 打开后台任务面板入口。+ button 不能嵌套,停止按钮以兄弟节点挂在右侧(仅 running 时出现)。 */}<div className="flex w-full items-start gap-2"><buttontype="button"- onClick={toggle}+ onClick={isWorkflow ? openInPanel : toggle}className="flex min-w-0 flex-1 items-start gap-2 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]"- aria-expanded={expanded}- aria-label={expanded ? t('chat.agentTask.hideDetails') : t('chat.agentTask.showDetails')}+ {...(isWorkflow+ ? { 'aria-label': t('chat.agentTask.openInPanel') }+ : {+ 'aria-expanded': expanded,+ 'aria-label': expanded+ ? t('chat.agentTask.hideDetails')+ : t('chat.agentTask.showDetails'),+ })}><span className="mt-[2px] inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-[var(--surface-chip)] text-[var(--text-secondary)]"><AvatarIcon size={14} aria-hidden="true" />@@ -226,16 +260,41 @@ export function AgentTaskCard({ toolCall, update, result, subagentModel, session</Fragment>))}</span>- </span>- <ChevronRight- size={14}- className={cn(- 'mt-1 shrink-0 text-[var(--text-tertiary)]',- 'transition-transform duration-[var(--motion-fast,150ms)]',- expanded && 'rotate-90',+ {workflowSummary && (+ <span+ data-workflow-progress-line="true"+ className="mt-0.5 block truncate text-12 leading-4 text-[var(--text-tertiary)]"+ >+ {workflowSummary.phase+ ? t('chat.agentTask.workflowProgressLine', {+ phase: workflowSummary.phase,+ done: workflowSummary.done,+ total: workflowSummary.total,+ })+ : t('chat.agentTask.workflowProgressCount', {+ done: workflowSummary.done,+ total: workflowSummary.total,+ })}+ </span>)}- aria-hidden="true"- />+ </span>+ {isWorkflow ? (+ <PanelRight+ size={14}+ className="mt-1 shrink-0 text-[var(--text-tertiary)]"+ aria-hidden="true"+ />+ ) : (+ <ChevronRight+ size={14}+ className={cn(+ 'mt-1 shrink-0 text-[var(--text-tertiary)]',+ 'transition-transform duration-[var(--motion-fast,150ms)]',+ expanded && 'rotate-90',+ )}+ aria-hidden="true"+ />+ )}</button>{canStop && (<button@@ -257,31 +316,25 @@ export function AgentTaskCard({ toolCall, update, result, subagentModel, session)}</div>- <Collapse open={expanded}>- <div className="mt-2 border-l-2 border-[var(--agent-actions-rail)] pl-3 text-13 leading-5 text-[var(--text-secondary)]">- {description && <p className="mb-1">{description}</p>}- {summary && <p className="mb-1 whitespace-pre-wrap">{summary}</p>}- {update?.lastToolName && (- <p className="text-12 leading-4 text-[var(--text-tertiary)]">- {t('chat.agentTask.lastTool', { tool: update.lastToolName })}- </p>- )}- {update?.outputFile && (- <p className="text-12 leading-4 text-[var(--text-tertiary)]">- {t('chat.agentTask.outputFile', { path: update.outputFile })}- </p>- )}- {/* workflow-card: 逐 agent 进度树(增强)。读不到记录 → 渲染 null,上面的- workflow 级信息(名字/状态/聚合 usage)照常展示,即 v1 形态优雅回退。 */}- {isWorkflow && (- <WorkflowAgentTree- {...(sessionId ? { sessionId } : {})}- {...(update?.taskId ? { taskId: update.taskId } : {})}- isRunning={status === 'running'}- />- )}- </div>- </Collapse>+ {/* workflow 卡不渲染展开区:详情(逐 agent 进度树等)在后台任务面板。 */}+ {!isWorkflow && (+ <Collapse open={expanded}>+ <div className="mt-2 border-l-2 border-[var(--agent-actions-rail)] pl-3 text-13 leading-5 text-[var(--text-secondary)]">+ {description && <p className="mb-1">{description}</p>}+ {summary && <p className="mb-1 whitespace-pre-wrap">{summary}</p>}+ {update?.lastToolName && (+ <p className="text-12 leading-4 text-[var(--text-tertiary)]">+ {t('chat.agentTask.lastTool', { tool: update.lastToolName })}+ </p>+ )}+ {update?.outputFile && (+ <p className="text-12 leading-4 text-[var(--text-tertiary)]">+ {t('chat.agentTask.outputFile', { path: update.outputFile })}+ </p>+ )}+ </div>+ </Collapse>+ )}</div></div>);diff --git a/apps/desktop/src/renderer/components/chat/WorkflowAgentTree.tsx b/apps/desktop/src/renderer/components/chat/WorkflowAgentTree.tsxdeleted file mode 100644index fe43976677..0000000000--- a/apps/desktop/src/renderer/components/chat/WorkflowAgentTree.tsx+++ /dev/null@@ -1,191 +0,0 @@-import { useEffect, useMemo, useState } from 'react';-import {- AlertCircle,- CheckCircle2,- CircleDashed,- CircleStop,- LoaderCircle,-} from 'lucide-react';-import { useTranslation } from 'react-i18next';--import type { WorkflowAgentProgress, WorkflowProgress } from '../../../shared/workflow-progress';-import { cn } from '@/lib/utils';-import { Spinner } from '@/components/ui/spinner';-import { formatModelShortLabel } from '@/lib/modelShortLabel';--interface WorkflowAgentTreeProps {- sessionId?: string;- /** workflow 任务的 task_id(= 记录文件顶层 taskId,用于关联)。 */- taskId?: string;- /** workflow 是否仍在运行(决定是否轮询记录文件)。 */- isRunning: boolean;-}--/** 运行中轮询记录文件的间隔(记录文件可能随 agent 状态变化被增量重写)。 */-const POLL_INTERVAL_MS = 2500;--/**- * 读取并订阅某个 workflow 的逐 agent 进度。- *- * - 挂载时拉一次;`isRunning` 为真时按 POLL_INTERVAL_MS 轮询(记录文件实时写则近实时,- * 只在结束写则完成后一次到位)。`isRunning` 翻假 → effect 重跑 → 停轮询 + 拉最终一次。- * - IPC 读不到 / 解析失败返回 null;这里原样透传,让卡片回退到 workflow 级展示。- */-function useWorkflowProgress(- sessionId: string | undefined,- taskId: string | undefined,- isRunning: boolean,-): WorkflowProgress | null {- const [progress, setProgress] = useState<WorkflowProgress | null>(null);-- useEffect(() => {- if (!sessionId || !taskId) {- setProgress(null);- return;- }- let cancelled = false;- let timer: ReturnType<typeof setTimeout> | undefined;-- const fetchOnce = async () => {- try {- const next = await window.electronAPI.maker.getWorkflowProgress(sessionId, taskId);- // null = 本次没读到(记录还没写 / 瞬时读失败)。已有进度时不覆盖为 null,避免- // 轮询过程中树闪没;首帧本就是 null,保持 null 无副作用。换 task 由 key 重挂载复位,- // 不依赖这里清空。- if (!cancelled && next !== null) setProgress(next);- } catch {- // best-effort:读取抛错同样保持上一次结果,不抛出- }- };-- void fetchOnce();- if (isRunning) {- const tick = () => {- timer = setTimeout(async () => {- await fetchOnce();- if (!cancelled) tick();- }, POLL_INTERVAL_MS);- };- tick();- }-- return () => {- cancelled = true;- if (timer) clearTimeout(timer);- };- }, [sessionId, taskId, isRunning]);-- return progress;-}--function agentStateIcon(state: string) {- switch (state) {- case 'done':- case 'completed':- return CheckCircle2;- case 'failed':- case 'error':- return AlertCircle;- case 'stopped':- case 'killed':- return CircleStop;- case 'queued':- case 'pending':- return CircleDashed;- default:- return LoaderCircle; // running / 未知 → 转圈- }-}--function isSpinning(state: string): boolean {- return state === 'running' || (state !== 'done' && state !== 'completed' && state !== 'failed'- && state !== 'error' && state !== 'stopped' && state !== 'killed' && state !== 'queued'- && state !== 'pending');-}--/**- * WorkflowAgentTree —— workflow 卡片展开区里的逐 agent 进度树。- *- * 数据来自 main 的 workflow-progress reader(读 Claude Code 内部记录文件)。这是对- * workflow 级卡片的**增强**:拿到数据就按 phase 分组、逐 agent 列出(状态图标 + label +- * 模型 chip);拿不到(SDK 未写记录 / 格式变化 / 非 workflow)则渲染 null,卡片其余部分照常。- */-export function WorkflowAgentTree({ sessionId, taskId, isRunning }: WorkflowAgentTreeProps) {- const { t } = useTranslation();- const progress = useWorkflowProgress(sessionId, taskId, isRunning);-- // 按 phase 顺序分组 agents;phaseTitle 不在 phases 列表里的(或缺失)归到末尾一组。- const grouped = useMemo(() => {- if (!progress) return [];- const byPhase = new Map<string, WorkflowAgentProgress[]>();- const orderedTitles = progress.phases.map((p) => p.title);- for (const title of orderedTitles) byPhase.set(title, []);- const orphans: WorkflowAgentProgress[] = [];- for (const agent of progress.agents) {- const key = agent.phaseTitle;- if (key && byPhase.has(key)) byPhase.get(key)!.push(agent);- else orphans.push(agent);- }- const out: Array<{ title: string | null; agents: WorkflowAgentProgress[] }> = [];- for (const title of orderedTitles) {- const agents = byPhase.get(title) ?? [];- if (agents.length > 0) out.push({ title, agents });- }- if (orphans.length > 0) out.push({ title: null, agents: orphans });- return out;- }, [progress]);-- if (!progress || progress.agents.length === 0) return null;-- return (- <div className="mt-2 space-y-2">- <div className="text-12 leading-4 text-[var(--text-tertiary)]">- {t('chat.workflowTree.agentsCount', { count: progress.agentCount ?? progress.agents.length })}- </div>- {grouped.map((group, gi) => (- <div key={group.title ?? `orphan-${gi}`} className="space-y-1">- {group.title && (- <div className="text-11 font-medium uppercase tracking-wide text-[var(--text-tertiary)]">- {group.title}- </div>- )}- {group.agents.map((agent) => {- const Icon = agentStateIcon(agent.state);- const spinning = isSpinning(agent.state);- const modelLabel = formatModelShortLabel(agent.model);- const stateLabel = t(`chat.workflowTree.state.${agent.state}`, {- defaultValue: agent.state,- });- return (- <div key={agent.agentId} className="flex min-w-0 items-center gap-2">- <Spinner- icon={Icon}- size={13}- spinning={spinning}- aria-label={stateLabel}- className={cn(- 'text-[var(--text-secondary)]',- (agent.state === 'failed' || agent.state === 'error') && 'text-[var(--error-fg)]',- )}- />- <span className="truncate text-13 leading-5 text-[var(--text-primary)]">- {agent.label}- </span>- {modelLabel && (- <span className="shrink-0 rounded-[4px] bg-[var(--surface-chip)] px-1.5 py-0.5 text-11 leading-4 text-[var(--text-tertiary)]">- {modelLabel}- </span>- )}- {typeof agent.attempt === 'number' && agent.attempt > 1 && (- <span className="shrink-0 text-11 leading-4 text-[var(--text-tertiary)]">- {t('chat.workflowTree.attempt', { count: agent.attempt })}- </span>- )}- </div>- );- })}- </div>- ))}- </div>- );-}diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsxindex b20e5fecfb..124cfaa80a 100644--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx@@ -27,7 +27,6 @@ import { useLocation, useNavigate, useOutletContext, useParams } from 'react-rouimport { useTranslation } from 'react-i18next';import type { AgentInputReference } from '@cindy/maker-shared/agent-input-projection';import { useProportionalWidth } from '@/hooks/useProportionalWidth';-import { setBlockExpanded } from '@/hooks/useExpandedBlockMemory';import {Activity,AlertCircle,@@ -120,8 +119,11 @@ import { toast } from '@/lib/toast';import {decodeRemoteErrorMessage,makerChatStore,+ type AgentTaskUpdate,type MessageDeliveryMode,} from '@/lib/makerChatStore';+import { openBackgroundTasksTab } from '@/features/right-sidebar/lib/openBackgroundTasksTab';+import { subscribeChatTaskFocus } from '@/features/right-sidebar/plugins/background-tasks/chatTaskFocusIntent';import { getMakerMemoryEnabled } from '@/lib/memorySettingsStore';import { useWorktreeCreation, worktreeCreationStore } from '@/lib/worktreeCreationStore';import { useWorktreeForSession } from '@/contexts/WorktreeContext';@@ -388,27 +390,28 @@ function RightSidebarWorkdirRegistration({}/**- * /workflows 命中卡片时的短暂描边高亮(模块级单例)。- *- * 只保留「当前正在高亮的那张卡 + 它的定时器」:起新高亮前先清掉上一次(无论同张还是另一张),- * 并把上一张恢复成无 inline boxShadow('' → 回落到样式表)。恢复值恒为 '' 而非「上次读到的- * boxShadow」,因此快速连按 /workflows 也不会把高亮值当原值存回去、造成描边永久残留。+ * /workflows:从任务表挑最近的 local_workflow 任务。taskUpdates 里同一任务按+ * taskId / parentToolUseId 存多个别名键(指向同一 merged 对象),先按引用去重,+ * 再取 updatedAt/createdAt 最新的一个;时间缺失按 0 参与比较(平局取遍历靠后者)。*/-let activeWorkflowFlash: { el: HTMLElement; timer: ReturnType<typeof setTimeout> } | null = null;--function flashWorkflowCard(el: HTMLElement): void {- if (activeWorkflowFlash) {- clearTimeout(activeWorkflowFlash.timer);- activeWorkflowFlash.el.style.boxShadow = '';- activeWorkflowFlash = null;+function findLatestWorkflowTask(+ taskUpdates: ReadonlyMap<string, AgentTaskUpdate>,+): AgentTaskUpdate | undefined {+ let latest: AgentTaskUpdate | undefined;+ let latestTs = Number.NEGATIVE_INFINITY;+ const seen = new Set<AgentTaskUpdate>();+ for (const update of taskUpdates.values()) {+ if (update.taskType !== 'local_workflow' || seen.has(update)) continue;+ seen.add(update);+ const raw = update.updatedAt ?? update.createdAt;+ const parsed = raw ? Date.parse(raw) : Number.NaN;+ const ts = Number.isFinite(parsed) ? parsed : 0;+ if (ts >= latestTs) {+ latest = update;+ latestTs = ts;+ }}- el.style.transition = 'box-shadow 0.25s ease';- el.style.boxShadow = '0 0 0 2px var(--focus-ring)';- const timer = setTimeout(() => {- el.style.boxShadow = '';- if (activeWorkflowFlash?.el === el) activeWorkflowFlash = null;- }, 1200);- activeWorkflowFlash = { el, timer };+ return latest;}export function CCAgentSessionView({@@ -877,6 +880,39 @@ export function CCAgentSessionView({t,]);+ // 后台任务面板行点击 → 聊天流定位对应任务卡:sessionId 匹配当前会话才消费;+ // 消息不在已加载窗口时先 loadAround 补上下文再定位(与搜索跳转同一收口)。+ useEffect(() => {+ if (!sessionId) return;+ let cancelled = false;+ const unsubscribe = subscribeChatTaskFocus((focusSessionId, clientId) => {+ if (cancelled || focusSessionId !== sessionId) return;+ const existing = makerChatStore+ .getSnapshot(sessionId)+ .messages.some((message) => message.clientId === clientId);+ if (existing) {+ requestFocusMessage(clientId);+ return;+ }+ void makerChatStore+ .loadAroundMessageClientId(sessionId, clientId, { radius: 60 })+ .then((message) => {+ if (cancelled) return;+ requestFocusMessage(message?.clientId ?? clientId);+ if (!message) toast.error(t('ccAgent.search.jumpFailed'));+ })+ .catch((err) => {+ if (cancelled) return;+ log.warn('Failed to load chat task focus context:', err);+ toast.error(t('ccAgent.search.jumpFailed'));+ });+ });+ return () => {+ cancelled = true;+ unsubscribe();+ };+ }, [requestFocusMessage, sessionId, t]);+// 选中一个 Worker session 时,如果当前是普通单 session 路由,自动跳到 Lead// 普通路由并用 worker query 作为协同 tab 的初始 hint。doc 模式 (`/cc-agent/files/...`) 下不跳——doc 应该一直// 是 doc,Worker session 就在 chat rail 里正常渲染。@@ -1457,6 +1493,13 @@ export function CCAgentSessionView({});}, [getHelpCommandsSnapshot, insertSystemCard]);+ // /workflows 要在命令 handler 里读"当下"的任务表;走 ref 镜像,避免 taskUpdates+ // 高频变化把 IPC 命令监听反复重订阅。+ const taskUpdatesRef = useRef(taskUpdates);+ useEffect(() => {+ taskUpdatesRef.current = taskUpdates;+ }, [taskUpdates]);+useEffect(() => {const unsub = window.electronAPI.maker.onDesktopCommandTriggered((payload) => {if (payload.sessionId && payload.sessionId !== sessionId) return;@@ -1510,26 +1553,15 @@ export function CCAgentSessionView({return;}if (payload.command === 'workflows') {- // workflow 进度内联在消息流里(Workflow 工具调用 → workflow 进度卡,AgentTaskCard 带- // data-workflow-card / data-workflow-session / data-workflow-expandkey)。/workflows 在- // **本会话作用域内**定位最近一张 workflow 卡:展开它 → 滚动到视野中央 → 短暂描边高亮;- // 无卡时 toast。数据/展现全在本地,不回 SDK(原生 /workflows 在非交互 SDK 模式下不可用)。- // 作用域限定:多个 CCAgentSessionView 可能同挂 DOM(Orca split view / workdir 浏览栏),- // 全局 querySelectorAll 会选到别的会话的卡,故按 data-workflow-session 限定当前会话。- const scopeSelector = sessionId- ? `[data-workflow-session="${CSS.escape(sessionId)}"][data-workflow-card]`- : '[data-workflow-card]';- const cards = document.querySelectorAll<HTMLElement>(scopeSelector);- const last = cards.item(cards.length - 1);- if (!last) {+ // workflow 的主视图在右栏「后台任务」面板:从本会话任务表取最近一个+ // local_workflow 任务,打开面板并定位到该任务详情;没有则 toast。数据/展现+ // 全在本地,不回 SDK(原生 /workflows 在非交互 SDK 模式下不可用)。+ const latest = findLatestWorkflowTask(taskUpdatesRef.current);+ if (!sessionId || !latest) {toast.warning(t('workflows.toast.none'));return;}- // 展开卡片:逐 agent 进度树只在展开区渲染,命令语义是「打开并展开最近一张 workflow 卡」。- const expandKey = last.getAttribute('data-workflow-expandkey');- if (expandKey) setBlockExpanded(expandKey, true);- last.scrollIntoView({ behavior: 'smooth', block: 'center' });- flashWorkflowCard(last);+ void openBackgroundTasksTab(sessionId, { focusTaskId: latest.taskId });return;}// 'issue' 命令由下方独立 effect 处理(需要 handleSend,其声明在本 effect 之后)。diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/WorkflowProgressTree.tsx b/apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/WorkflowProgressTree.tsxindex 8002a15328..7ed43a0260 100644--- a/apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/WorkflowProgressTree.tsx+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/WorkflowProgressTree.tsx@@ -5,8 +5,7 @@* - 数据由上层用 buildWorkflowTreeModel 合并好后传入;本组件不拉数据、不轮询、无状态;* - 无列表动画(DESIGN.md §14.4:静态渲染;唯一动效是 Spinner 的 compositor-only 转圈);* - 颜色全走语义 token,Light/Dark 同源;- * - 状态图标/词表口径与聊天流 WorkflowAgentTree 一致,并补齐事件流词表- * (start/progress → 转圈)。+ * - 状态图标/词表覆盖两套词表:wf 文件词表 + 事件流词表(start/progress → 转圈)。*/import {diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/workflowProgressModel.ts b/apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/workflowProgressModel.tsindex 4c4ff3889f..2b075c9a4b 100644--- a/apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/workflowProgressModel.ts+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/workflowProgressModel.ts@@ -139,7 +139,7 @@ export function buildWorkflowTreeModel(input: {/*** entries 主结构:workflow_phase 条目出现顺序定 phase 顺序(同名只保留首个),* workflow_agent 按 phaseTitle 归组;不属于任何 phase 的进末尾 title=null 组。- * 分组口径与 WorkflowAgentTree 一致:没有 agent 的 phase 不产出分组。+ * 分组口径:没有 agent 的 phase 不产出分组。*/function groupsFromEntries(entries: readonly WorkflowProgressEntry[],diff --git a/apps/desktop/src/renderer/hooks/useExpandedBlockMemory.ts b/apps/desktop/src/renderer/hooks/useExpandedBlockMemory.tsindex 3906c22c1d..0c23fb4db6 100644--- a/apps/desktop/src/renderer/hooks/useExpandedBlockMemory.ts+++ b/apps/desktop/src/renderer/hooks/useExpandedBlockMemory.ts@@ -27,14 +27,6 @@ const store = createExpandedBlockStore({onSubscriberError: (err) => log.warn('subscriber error:', err),});-/**- * 命令式设置某个 block 的展开态(供 /workflows 这类外部入口用,无需持有 hook 实例)。- * 走同一个 module-level store + pub/sub,所有挂载的 useExpandedBlockMemory 会同步。- */-export function setBlockExpanded(blockId: string, expanded: boolean): void {- store.setExpanded(blockId, expanded);-}-export interface UseExpandedBlockMemoryReturn {/** Whether this block is currently expanded. Default: false (collapsed). */expanded: boolean;diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex ed89d4f2d4..03969e1a73 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -4348,6 +4348,9 @@"stopped": "Stopped"},"stop": "Stop this task",+ "openInPanel": "Open in the background tasks panel",+ "workflowProgressLine": "{{phase}} · {{done}}/{{total}} agents",+ "workflowProgressCount": "{{done}}/{{total}} agents","tokens": "{{count}} tokens","toolUses_one": "{{count}} tool use","toolUses_other": "{{count}} tool uses",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex fef0c2e286..0f00344584 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -4347,6 +4347,9 @@"stopped": "停止済み"},"stop": "このタスクを停止",+ "openInPanel": "バックグラウンドタスクパネルで開く",+ "workflowProgressLine": "{{phase}} · {{done}}/{{total}} Agent",+ "workflowProgressCount": "{{done}}/{{total}} Agent","tokens": "{{count}} tokens","toolUses_one": "{{count}} 回のツール使用","toolUses_other": "{{count}} 回のツール使用",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex ddb268359b..2ae9d0f098 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -4347,6 +4347,9 @@"stopped": "중지됨"},"stop": "이 작업 중지",+ "openInPanel": "백그라운드 작업 패널에서 열기",+ "workflowProgressLine": "{{phase}} · {{done}}/{{total}} Agent",+ "workflowProgressCount": "{{done}}/{{total}} Agent","tokens": "{{count}} tokens","toolUses_one": "도구 호출 {{count}}회","toolUses_other": "도구 호출 {{count}}회",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex e7203f33a1..7cf3427cc9 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -4347,6 +4347,9 @@"stopped": "已停止"},"stop": "停止该任务",+ "openInPanel": "在后台任务面板中打开",+ "workflowProgressLine": "{{phase}} · {{done}}/{{total}} Agent",+ "workflowProgressCount": "{{done}}/{{total}} Agent","tokens": "{{count}} tokens","toolUses_one": "{{count}} 次工具调用","toolUses_other": "{{count}} 次工具调用",