Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

feat(desktop): 右栏新增「后台任务」tab(列表 + workflow 详情)

Kafeifeia25d5a8dc589
diff --git a/apps/desktop/src/renderer/features/right-sidebar/TabBar.tsx b/apps/desktop/src/renderer/features/right-sidebar/TabBar.tsx
index 17ab17eac0..7e880bed53 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/TabBar.tsx
+++ b/apps/desktop/src/renderer/features/right-sidebar/TabBar.tsx
@@ -25,6 +25,7 @@ import {
Terminal,
GitPullRequestArrow,
UsersRound,
+ ListTodo,
Plus,
Puzzle,
X,
@@ -120,6 +121,7 @@ const KIND_ICON: Record<BuiltinTabKindId, LucideIcon> = {
terminal: Terminal,
review: GitPullRequestArrow,
'orca-workers': UsersRound,
+ 'background-tasks': ListTodo,
};
const KIND_LABEL_KEY: Record<BuiltinTabKindId, string> = {
@@ -128,6 +130,7 @@ const KIND_LABEL_KEY: Record<BuiltinTabKindId, string> = {
terminal: 'rightSidebar.tabs.kinds.terminal',
review: 'rightSidebar.tabs.kinds.review',
'orca-workers': 'rightSidebar.tabs.kinds.collaboration',
+ 'background-tasks': 'rightSidebar.tabs.kinds.backgroundTasks',
};
/**
diff --git a/apps/desktop/src/renderer/features/right-sidebar/lib/openBackgroundTasksTab.ts b/apps/desktop/src/renderer/features/right-sidebar/lib/openBackgroundTasksTab.ts
new file mode 100644
index 0000000000..6fa3f8804e
--- /dev/null
+++ b/apps/desktop/src/renderer/features/right-sidebar/lib/openBackgroundTasksTab.ts
@@ -0,0 +1,40 @@
+/**
+ * openBackgroundTasksTab —— "打开右栏「后台任务」面板"的统一程序化入口。
+ *
+ * 范式对齐 openInSidebarBrowser:ensureHydrated → addOrFocusSingletonTab →
+ * requestRightSidebarVisibility。差异:
+ * - 单例 kind:已有 tab 时聚焦而非新开(与 review 同款语义)。
+ * - focusTaskId(可选):写进 tab state,Body 消费后进对应 workflow 详情并清空;
+ * tab 已存在时经 patchTabState 补写(store 无单例 state patch 快捷 API)。
+ * - detached 路由:RsbWindowCommand 目前没有 background-tasks 命令类型,不走
+ * routeSidebarCommand —— 只走本窗口路径;子窗口形态的路由支持归后续阶段
+ * (届时在 shared/rightSidebarWindow.ts 扩 command union 后接 routeSidebarCommand)。
+ */
+
+import { addOrFocusSingletonTab, ensureHydrated, getBucket, patchTabState } from '../store';
+import { requestRightSidebarVisibility } from './sidebarCommands';
+
+/** 打开(或聚焦)指定 session 的后台任务面板,并确保侧边栏可见。 */
+export async function openBackgroundTasksTab(
+ sessionId: string,
+ opts?: { focusTaskId?: string },
+): Promise<void> {
+ // addOrFocusSingletonTab 的乐观写以 bucket 已 hydrate 为前提(与
+ // openUrlInSidebarBrowser 同款竞态说明);已 hydrate 时是同步 no-op。
+ await ensureHydrated(sessionId);
+ const hadExisting = getBucket(sessionId).tabs.some((t) => t.kind === 'background-tasks');
+ const tab = await addOrFocusSingletonTab(sessionId, 'background-tasks', {
+ focusTaskId: opts?.focusTaskId ?? null,
+ });
+ // 已有 tab 时 initialState 不生效,focusTaskId 需补写进现有 state。
+ if (hadExisting && opts?.focusTaskId) {
+ await patchTabState(sessionId, tab.id, (current) => {
+ const base =
+ typeof current === 'object' && current !== null
+ ? (current as Record<string, unknown>)
+ : {};
+ return { ...base, focusTaskId: opts.focusTaskId };
+ });
+ }
+ requestRightSidebarVisibility('open', { sessionId });
+}
diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/BackgroundTasksBody.tsx b/apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/BackgroundTasksBody.tsx
new file mode 100644
index 0000000000..02598ece5d
--- /dev/null
+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/BackgroundTasksBody.tsx
@@ -0,0 +1,588 @@
+/**
+ * BackgroundTasksBody —— 「后台任务」tab 的内容区。
+ *
+ * 两个视图:
+ * - 列表:Running / Completed 两分区(排序由 listSessionTasks 保证:running 按
+ * 启动升序、completed 按完成倒序),行 = kind 图标 + 状态图标 + 标题 + meta
+ * (状态 · 时长 · tokens · 工具调用),running 的 claude-code 任务行尾给 Stop。
+ * - workflow 详情:返回按钮 + 头部(标题 + Stop)+ WorkflowProgressTree 逐 agent
+ * 进度树。
+ *
+ * 数据约束:
+ * - 事件源:makerChatStore 按 sessionId 订阅,快照 getter 只挑
+ * messages / taskUpdates / isStreaming 三个引用比对缓存 —— 不走
+ * useCCAgentChat 的重快照路径,其他字段(流式文本等)高频变更不触发重渲。
+ * - 面板不可见(非激活 tab / 壳子隐藏)时订阅挂空,恢复可见时重订阅自动补读。
+ * - 快照水合:挂载时对本机会话调一次 listSessionBackgroundTasks 经
+ * seedBackgroundTaskSnapshots 补存量(与 useBackgroundBashTasks 同口径,只复用
+ * store 公开函数);device-link 远程会话跳过(main 拿不到 handle,快照必空)。
+ * - wf 文件辅源:详情视图挂载时拉一次 getWorkflowProgressFor,任务从 running 翻
+ * 终态时再拉一次;不轮询。远程/老被控端自动降级返回 null。
+ * - 停止:gating = running + claude-code + 有 taskId + 非远程会话;在飞防连点、
+ * 失败静默,终态交给 task_notification 事件流收口(同 AgentTaskCard 口径)。
+ */
+
+import {
+ useCallback,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+ useSyncExternalStore,
+ type MouseEvent,
+} from 'react';
+import { useTranslation } from 'react-i18next';
+import {
+ AlertCircle,
+ ArrowLeft,
+ Bot,
+ CheckCircle2,
+ CircleDashed,
+ CircleStop,
+ ListTodo,
+ LoaderCircle,
+ Square,
+ SquareTerminal,
+ Workflow,
+} from 'lucide-react';
+import type { LucideIcon } from 'lucide-react';
+
+import { cn } from '@/lib/utils';
+import { Spinner } from '@/components/ui/spinner';
+import { makerChatStore, EMPTY_TASK_UPDATES } from '@/lib/makerChatStore';
+import type { AgentTaskUpdate, ChatMessage } from '@/lib/makerChatStore';
+import { getWorkflowProgressFor, isRemoteSession } from '@/lib/makerTransport';
+import { formatCompactTokens } from '@/lib/usageFormat';
+import type { Message } from '@/lib/ccAgent.types';
+import type { WorkflowProgress } from '../../../../../shared/workflow-progress';
+import type { TabKindHostContext } from '../../types';
+import type { BackgroundTasksState } from './index';
+import { listSessionTasks, type SessionTaskItem } from './listSessionTasks';
+import { buildWorkflowTreeModel } from './workflowProgressModel';
+import { WorkflowProgressTree } from './WorkflowProgressTree';
+import { requestChatTaskFocus } from './chatTaskFocusIntent';
+
+// ---------------------------------------------------------------------------
+// store 订阅(轻量选择器)
+// ---------------------------------------------------------------------------
+
+interface SessionTaskInputs {
+ messages: ChatMessage[];
+ taskUpdates: ReadonlyMap<string, AgentTaskUpdate>;
+ isStreaming: boolean;
+}
+
+const EMPTY_MESSAGES: ChatMessage[] = [];
+/** 无 sessionId 时的稳定空快照(useSyncExternalStore 要求引用稳定)。 */
+const EMPTY_INPUTS: SessionTaskInputs = {
+ messages: EMPTY_MESSAGES,
+ taskUpdates: EMPTY_TASK_UPDATES,
+ isStreaming: false,
+};
+
+/**
+ * 订阅当前会话的 (messages, taskUpdates, isStreaming) 三元组。
+ * paused=true(面板不可见)时订阅挂空 —— 不再接收通知;恢复时 subscribe 引用
+ * 变化触发 React 重订阅并重读快照,数据自动追平,无需额外刷新逻辑。
+ */
+function useSessionTaskInputs(sessionId: string | null, paused: boolean): SessionTaskInputs {
+ const cacheRef = useRef<{
+ messages: ChatMessage[];
+ taskUpdates: ReadonlyMap<string, AgentTaskUpdate>;
+ isStreaming: boolean;
+ snapshot: SessionTaskInputs;
+ } | null>(null);
+
+ const subscribeStore = useCallback(
+ (cb: () => void) => {
+ if (!sessionId || paused) return () => {};
+ return makerChatStore.subscribe(sessionId, cb);
+ },
+ [sessionId, paused],
+ );
+
+ const getInputs = useCallback((): SessionTaskInputs => {
+ if (!sessionId) return EMPTY_INPUTS;
+ const s = makerChatStore.getSnapshot(sessionId);
+ const cached = cacheRef.current;
+ // 三个引用全等 → 返回缓存快照,React Object.is 短路,避免无关字段变更引发重渲。
+ if (
+ cached &&
+ cached.messages === s.messages &&
+ cached.taskUpdates === s.taskUpdates &&
+ cached.isStreaming === s.isStreaming
+ ) {
+ return cached.snapshot;
+ }
+ const snapshot: SessionTaskInputs = {
+ messages: s.messages,
+ // taskUpdates 类型上可缺省(历史快照形态),缺省回落稳定空 Map。
+ taskUpdates: s.taskUpdates ?? EMPTY_TASK_UPDATES,
+ isStreaming: s.isStreaming,
+ };
+ cacheRef.current = { ...snapshot, snapshot };
+ return snapshot;
+ }, [sessionId]);
+
+ return useSyncExternalStore(subscribeStore, getInputs);
+}
+
+// ---------------------------------------------------------------------------
+// 展示辅助
+// ---------------------------------------------------------------------------
+
+/** kind → 行首图标(与聊天卡片的视觉词汇一致)。 */
+function kindIcon(kind: SessionTaskItem['kind']): LucideIcon {
+ if (kind === 'workflow') return Workflow;
+ if (kind === 'bash') return SquareTerminal;
+ if (kind === 'agent') return Bot;
+ return CircleDashed;
+}
+
+/** 标题兜底(listSessionTasks 契约:取不到来源时 title='',由 UI 补 i18n 文案)。 */
+function fallbackTitleKey(kind: SessionTaskItem['kind']): string {
+ if (kind === 'workflow') return 'chat.agentTask.provider.workflow';
+ if (kind === 'bash') return 'chat.agentTask.provider.shell';
+ return 'chat.agentTask.emptyTitle';
+}
+
+/** status → 状态图标(running 由 Spinner 负责旋转)。 */
+function statusIcon(status: string): LucideIcon {
+ if (status === 'completed') return CheckCircle2;
+ if (status === 'failed') return AlertCircle;
+ if (status === 'stopped') return CircleStop;
+ return LoaderCircle;
+}
+
+/** 毫秒 → 紧凑时长文案(与 AgentTaskCard 同口径;该实现未导出,此处内联)。 */
+function formatDuration(ms: number | undefined): string | undefined {
+ if (typeof ms !== 'number' || !Number.isFinite(ms) || ms < 0) return undefined;
+ if (ms < 1000) return `${ms}ms`;
+ const seconds = Math.round(ms / 1000);
+ if (seconds < 60) return `${seconds}s`;
+ const minutes = Math.floor(seconds / 60);
+ const rest = seconds % 60;
+ return rest > 0 ? `${minutes}m ${rest}s` : `${minutes}m`;
+}
+
+/** workflow 行副标题:workflow_agent 条目 done/error 计数 / 总数。 */
+function workflowAgentCounts(
+ update: AgentTaskUpdate | undefined,
+): { done: number; total: number } | null {
+ const entries = update?.workflowProgress;
+ if (!entries || entries.length === 0) return null;
+ let total = 0;
+ let done = 0;
+ for (const entry of entries) {
+ if (entry.type !== 'workflow_agent') continue;
+ total += 1;
+ // 事件流词表 done/error;wf 文件词表 done/failed/stopped/killed —— 都算已收口。
+ if (
+ entry.state === 'done' ||
+ entry.state === 'error' ||
+ entry.state === 'failed' ||
+ entry.state === 'stopped' ||
+ entry.state === 'killed'
+ ) {
+ done += 1;
+ }
+ }
+ return total > 0 ? { done, total } : null;
+}
+
+/** 停止按钮 gating(与 AgentTaskCard 同口径):running + claude-code + 有 taskId + 非远程。 */
+function canStopItem(item: SessionTaskItem, sessionId: string | null): boolean {
+ return (
+ item.status === 'running' &&
+ item.provider === 'claude-code' &&
+ Boolean(item.update?.taskId) &&
+ Boolean(sessionId) &&
+ !(sessionId && isRemoteSession(sessionId))
+ );
+}
+
+/** 停止按钮:在飞防连点、失败静默,状态翻转由事件流收口(不改本地状态)。 */
+function StopButton({ sessionId, taskId }: { sessionId: string; taskId: string }) {
+ const { t } = useTranslation();
+ const [stopping, setStopping] = useState(false);
+ const handleStop = useCallback(
+ (e: MouseEvent) => {
+ // 行点击(进详情 / 聊天定位)不该被停止按钮触发。
+ e.stopPropagation();
+ const api = window.electronAPI?.maker;
+ if (!api?.stopAgentTask || stopping) return;
+ setStopping(true);
+ void api
+ .stopAgentTask(sessionId, taskId)
+ .catch(() => {
+ // 静默:真失败时状态仍是 running,按钮保留可重试。
+ })
+ .finally(() => setStopping(false));
+ },
+ [sessionId, taskId, stopping],
+ );
+ return (
+ <button
+ type="button"
+ onClick={handleStop}
+ disabled={stopping}
+ aria-label={t('rightSidebar.backgroundTasks.stop')}
+ title={t('rightSidebar.backgroundTasks.stop')}
+ className={cn(
+ 'inline-flex h-6 w-6 shrink-0 items-center justify-center rounded-md text-[var(--text-secondary)] transition-colors hover:bg-[var(--surface-hover)] hover:text-[var(--text-primary)]',
+ stopping && 'cursor-default opacity-50',
+ )}
+ >
+ <Square size={12} aria-hidden="true" />
+ </button>
+ );
+}
+
+// ---------------------------------------------------------------------------
+// 列表行
+// ---------------------------------------------------------------------------
+
+function TaskRow({
+ item,
+ sessionId,
+ onOpenWorkflow,
+}: {
+ item: SessionTaskItem;
+ sessionId: string | null;
+ onOpenWorkflow: (key: string) => void;
+}) {
+ const { t } = useTranslation();
+ const KindIcon = kindIcon(item.kind);
+ const StatusIcon = statusIcon(item.status);
+ const running = item.status === 'running';
+
+ // meta:状态 · 时长 · tokens · 工具调用(缺项省略);workflow 行前置 agent 进度摘要。
+ const metaParts = useMemo(() => {
+ const parts: string[] = [];
+ const knownStatus =
+ item.status === 'running' ||
+ item.status === 'completed' ||
+ item.status === 'failed' ||
+ item.status === 'stopped';
+ if (knownStatus) parts.push(t(`chat.agentTask.status.${item.status}`));
+ if (item.kind === 'workflow') {
+ const counts = workflowAgentCounts(item.update);
+ if (counts) {
+ parts.push(
+ t('rightSidebar.backgroundTasks.progressSummary', {
+ done: counts.done,
+ total: counts.total,
+ }),
+ );
+ }
+ }
+ const usage = item.update?.usage;
+ const duration = formatDuration(usage?.durationMs);
+ if (duration) parts.push(duration);
+ if (typeof usage?.totalTokens === 'number') {
+ parts.push(
+ t('rightSidebar.backgroundTasks.tokens', {
+ value: formatCompactTokens(usage.totalTokens),
+ }),
+ );
+ }
+ if (typeof usage?.toolUses === 'number') {
+ parts.push(t('chat.agentTask.toolUses', { count: usage.toolUses }));
+ }
+ return parts;
+ }, [item, t]);
+
+ const handleClick = useCallback(() => {
+ if (item.kind === 'workflow') {
+ onOpenWorkflow(item.key);
+ return;
+ }
+ // 非 workflow 行:发聊天定位意图(消费端接线归后续阶段,当前无订阅者时 no-op)。
+ if (sessionId && item.toolCallClientId) {
+ requestChatTaskFocus(sessionId, item.toolCallClientId);
+ }
+ }, [item, sessionId, onOpenWorkflow]);
+
+ return (
+ <div className="flex items-start gap-1">
+ <button
+ type="button"
+ onClick={handleClick}
+ className="flex min-w-0 flex-1 items-start gap-2 rounded-[8px] px-2 py-1.5 text-left transition-colors hover:bg-[var(--surface-hover)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]"
+ >
+ <span className="mt-[1px] inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-[var(--surface-chip)] text-[var(--text-secondary)]">
+ <KindIcon size={12} aria-hidden="true" />
+ </span>
+ <span className="min-w-0 flex-1">
+ <span className="flex min-w-0 items-center gap-1.5">
+ <Spinner
+ icon={StatusIcon}
+ size={13}
+ spinning={running}
+ className={cn(
+ 'shrink-0 text-[var(--text-secondary)]',
+ item.status === 'failed' && 'text-[var(--error-fg)]',
+ )}
+ />
+ <span className="truncate text-13 leading-5 text-[var(--text-primary)]">
+ {item.title || t(fallbackTitleKey(item.kind))}
+ </span>
+ </span>
+ {metaParts.length > 0 && (
+ <span className="mt-0.5 block truncate text-11 leading-4 text-[var(--text-tertiary)]">
+ {metaParts.join(' · ')}
+ </span>
+ )}
+ </span>
+ </button>
+ {canStopItem(item, sessionId) && sessionId && item.update?.taskId && (
+ <div className="pt-1.5">
+ <StopButton sessionId={sessionId} taskId={item.update.taskId} />
+ </div>
+ )}
+ </div>
+ );
+}
+
+function SectionHeader({ label }: { label: string }) {
+ return (
+ <div className="px-2 pb-1 pt-3 text-11 font-medium uppercase tracking-[0.5px] text-[var(--text-tertiary)]">
+ {label}
+ </div>
+ );
+}
+
+// ---------------------------------------------------------------------------
+// workflow 详情
+// ---------------------------------------------------------------------------
+
+function WorkflowDetail({
+ item,
+ sessionId,
+ onBack,
+}: {
+ item: SessionTaskItem;
+ sessionId: string | null;
+ onBack: () => void;
+}) {
+ const { t } = useTranslation();
+ const taskId = item.update?.taskId ?? item.taskId ?? null;
+ const [fileProgress, setFileProgress] = useState<WorkflowProgress | null>(null);
+
+ // 挂载拉一次 wf 文件辅源;远程会话/老被控端 getWorkflowProgressFor 内部降级 null。
+ useEffect(() => {
+ if (!sessionId || !taskId) return;
+ let disposed = false;
+ void getWorkflowProgressFor(sessionId, taskId)
+ .then((progress) => {
+ if (!disposed && progress) setFileProgress(progress);
+ })
+ .catch(() => {
+ // 静默:文件辅源缺失时详情树退化为事件流数据。
+ });
+ return () => {
+ disposed = true;
+ };
+ }, [sessionId, taskId]);
+
+ // 任务从 running 翻终态时再拉一次(终局数据落盘晚于事件);不轮询。
+ const status = item.status;
+ const prevStatusRef = useRef(status);
+ useEffect(() => {
+ const prev = prevStatusRef.current;
+ prevStatusRef.current = status;
+ if (prev !== 'running' || status === 'running') return;
+ if (!sessionId || !taskId) return;
+ let disposed = false;
+ void getWorkflowProgressFor(sessionId, taskId)
+ .then((progress) => {
+ if (!disposed && progress) setFileProgress(progress);
+ })
+ .catch(() => {});
+ return () => {
+ disposed = true;
+ };
+ }, [status, sessionId, taskId]);
+
+ const model = useMemo(
+ () =>
+ buildWorkflowTreeModel({
+ entries: item.update?.workflowProgress,
+ fileProgress,
+ taskStatus: item.status,
+ usage: item.update?.usage,
+ }),
+ [item.update?.workflowProgress, fileProgress, item.status, item.update?.usage],
+ );
+
+ const title = item.update?.workflowName ?? (item.title || t(fallbackTitleKey(item.kind)));
+
+ return (
+ <div className="flex min-h-0 flex-1 flex-col">
+ <div className="flex shrink-0 items-center gap-1.5 border-b border-[var(--border-default)] px-2 py-1.5">
+ <button
+ type="button"
+ onClick={onBack}
+ aria-label={t('rightSidebar.backgroundTasks.back')}
+ title={t('rightSidebar.backgroundTasks.back')}
+ className="inline-flex h-6 w-6 shrink-0 items-center justify-center rounded-md text-[var(--text-secondary)] transition-colors hover:bg-[var(--surface-hover)] hover:text-[var(--text-primary)]"
+ >
+ <ArrowLeft size={14} aria-hidden="true" />
+ </button>
+ <span className="inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-[var(--surface-chip)] text-[var(--text-secondary)]">
+ <Workflow size={12} aria-hidden="true" />
+ </span>
+ <span className="min-w-0 flex-1 truncate text-13 font-medium leading-5 text-[var(--text-primary)]">
+ {title}
+ </span>
+ {canStopItem(item, sessionId) && sessionId && item.update?.taskId && (
+ <StopButton sessionId={sessionId} taskId={item.update.taskId} />
+ )}
+ </div>
+ <div className="min-h-0 flex-1 overflow-y-auto px-2 py-2">
+ {model ? (
+ <WorkflowProgressTree model={model} />
+ ) : (
+ <div className="px-2 py-6 text-center text-12 text-[var(--text-tertiary)]">
+ {t('rightSidebar.backgroundTasks.noProgress')}
+ </div>
+ )}
+ </div>
+ </div>
+ );
+}
+
+// ---------------------------------------------------------------------------
+// TabBody
+// ---------------------------------------------------------------------------
+
+export function BackgroundTasksBody({
+ state,
+ ctx,
+ active,
+ shellVisible,
+}: {
+ state: BackgroundTasksState;
+ ctx: TabKindHostContext;
+ active?: boolean;
+ shellVisible?: boolean;
+}) {
+ const { t } = useTranslation();
+ const sessionId = ctx.sessionId || null;
+ // 不可见(非激活 tab / 壳子隐藏)时暂停 store 订阅;active/shellVisible 缺省视为可见。
+ const visible = (active ?? true) && (shellVisible ?? true);
+ const remoteMirror = Boolean(sessionId) && isRemoteSession(sessionId as string);
+
+ // 快照水合:挂载 / 切会话时对本机会话拉一次存量后台任务(订阅前已启动的任务
+ // 事件流看不到)。只复用 store 的公开水合函数;失败静默,实时事件流自然补上。
+ useEffect(() => {
+ if (!sessionId || remoteMirror) return;
+ const api = window.electronAPI?.maker;
+ if (!api?.listSessionBackgroundTasks) return;
+ let disposed = false;
+ void api
+ .listSessionBackgroundTasks(sessionId)
+ .then(({ tasks }) => {
+ if (disposed || !Array.isArray(tasks) || tasks.length === 0) return;
+ makerChatStore.seedBackgroundTaskSnapshots(sessionId, tasks);
+ })
+ .catch(() => {
+ // 静默:与 useBackgroundBashTasks 的快照失败同口径。
+ });
+ return () => {
+ disposed = true;
+ };
+ }, [sessionId, remoteMirror]);
+
+ const inputs = useSessionTaskInputs(sessionId, !visible);
+
+ const { running, completed } = useMemo(
+ () =>
+ listSessionTasks({
+ // listSessionTasks 签名按 DB 行(ccAgent.types.Message)声明,其
+ // readToolCall 已显式兼容 store 侧 ChatMessage 形态(顶层 toolName /
+ // toolInput),此处按契约文档喂 store 消息数组,只做类型断言不改数据。
+ messages: inputs.messages as unknown as readonly Message[],
+ taskUpdates: inputs.taskUpdates,
+ isSessionStreaming: inputs.isStreaming,
+ }),
+ [inputs],
+ );
+
+ // 详情选中:存 item.key(跨状态翻转稳定);条目消失时自动回列表视图。
+ const [selectedKey, setSelectedKey] = useState<string | null>(null);
+ const selectedItem = useMemo(() => {
+ if (!selectedKey) return null;
+ return (
+ running.find((it) => it.key === selectedKey) ??
+ completed.find((it) => it.key === selectedKey) ??
+ null
+ );
+ }, [selectedKey, running, completed]);
+
+ // focusTaskId(tab state)消费:对应 workflow 任务出现后直接进详情并清空请求
+ // (数据可能晚于挂载到达,依赖列表变化重试;消费即清,避免跨重启反复弹详情)。
+ const focusTaskId = state.focusTaskId ?? null;
+ useEffect(() => {
+ if (!focusTaskId) return;
+ const target =
+ running.find((it) => it.kind === 'workflow' && it.taskId === focusTaskId) ??
+ completed.find((it) => it.kind === 'workflow' && it.taskId === focusTaskId);
+ if (!target) return;
+ setSelectedKey(target.key);
+ ctx.patchState({ focusTaskId: null });
+ }, [focusTaskId, running, completed, ctx]);
+
+ const handleOpenWorkflow = useCallback((key: string) => {
+ setSelectedKey(key);
+ }, []);
+ const handleBack = useCallback(() => {
+ setSelectedKey(null);
+ }, []);
+
+ if (selectedItem && selectedItem.kind === 'workflow') {
+ return <WorkflowDetail item={selectedItem} sessionId={sessionId} onBack={handleBack} />;
+ }
+
+ if (running.length === 0 && completed.length === 0) {
+ return (
+ <div className="flex min-h-0 flex-1 flex-col items-center justify-center gap-2 px-6 text-center">
+ <ListTodo size={20} className="text-[var(--text-tertiary)]" aria-hidden="true" />
+ <div className="text-12 text-[var(--text-tertiary)]">
+ {t('rightSidebar.backgroundTasks.empty')}
+ </div>
+ </div>
+ );
+ }
+
+ return (
+ <div className="min-h-0 flex-1 overflow-y-auto px-1 pb-2">
+ {running.length > 0 && (
+ <>
+ <SectionHeader label={t('rightSidebar.backgroundTasks.running')} />
+ {running.map((item) => (
+ <TaskRow
+ key={item.key}
+ item={item}
+ sessionId={sessionId}
+ onOpenWorkflow={handleOpenWorkflow}
+ />
+ ))}
+ </>
+ )}
+ {completed.length > 0 && (
+ <>
+ <SectionHeader label={t('rightSidebar.backgroundTasks.completed')} />
+ {completed.map((item) => (
+ <TaskRow
+ key={item.key}
+ item={item}
+ sessionId={sessionId}
+ onOpenWorkflow={handleOpenWorkflow}
+ />
+ ))}
+ </>
+ )}
+ </div>
+ );
+}
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.tsx
new file mode 100644
index 0000000000..8002a15328
--- /dev/null
+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/WorkflowProgressTree.tsx
@@ -0,0 +1,189 @@
+/**
+ * WorkflowProgressTree —— 后台任务详情页里的 workflow 逐 agent 进度树(纯展示)。
+ *
+ * 约束:
+ * - 数据由上层用 buildWorkflowTreeModel 合并好后传入;本组件不拉数据、不轮询、无状态;
+ * - 无列表动画(DESIGN.md §14.4:静态渲染;唯一动效是 Spinner 的 compositor-only 转圈);
+ * - 颜色全走语义 token,Light/Dark 同源;
+ * - 状态图标/词表口径与聊天流 WorkflowAgentTree 一致,并补齐事件流词表
+ * (start/progress → 转圈)。
+ */
+
+import {
+ AlertCircle,
+ CheckCircle2,
+ CircleDashed,
+ CircleStop,
+ LoaderCircle,
+} from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+
+import { formatDuration } from '@/components/chat/ThinkingCard';
+import { Spinner } from '@/components/ui/spinner';
+import { formatModelShortLabel } from '@/lib/modelShortLabel';
+import { formatCompactTokens } from '@/lib/usageFormat';
+import { cn } from '@/lib/utils';
+
+import type { WorkflowTreeAgentRow, WorkflowTreeModel } from './workflowProgressModel';
+
+interface WorkflowProgressTreeProps {
+ model: WorkflowTreeModel;
+}
+
+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 / start / progress / 未知 → 转圈
+ }
+}
+
+/** 非终态且非等待态(running/start/progress/未知)才转圈。 */
+function isSpinning(state: string): boolean {
+ switch (state) {
+ case 'done':
+ case 'completed':
+ case 'failed':
+ case 'error':
+ case 'stopped':
+ case 'killed':
+ case 'queued':
+ case 'pending':
+ return false;
+ default:
+ return true;
+ }
+}
+
+export function WorkflowProgressTree({ model }: WorkflowProgressTreeProps) {
+ const { t } = useTranslation();
+ const agentRowCount = model.groups.reduce((n, g) => n + g.agents.length, 0);
+ // 没有任何可展示的行(agent 行与 logs 都空)时不渲染,交给上层决定占位。
+ if (agentRowCount === 0 && model.logs.length === 0) return null;
+
+ const { aggregate } = model;
+ const metaParts: string[] = [];
+ if (typeof aggregate.agentCount === 'number') {
+ metaParts.push(t('chat.workflowTree.agentsCount', { count: aggregate.agentCount }));
+ }
+ metaParts.push(
+ t(`chat.workflowTree.state.${aggregate.status}`, { defaultValue: aggregate.status }),
+ );
+ if (typeof aggregate.totalTokens === 'number') {
+ metaParts.push(
+ t('usageDashboard.tokensOnly', { tokens: formatCompactTokens(aggregate.totalTokens) }),
+ );
+ }
+ if (typeof aggregate.totalToolCalls === 'number') {
+ metaParts.push(t('chat.agentTask.toolUses', { count: aggregate.totalToolCalls }));
+ }
+ if (typeof aggregate.durationMs === 'number') {
+ metaParts.push(formatDuration(aggregate.durationMs));
+ }
+
+ return (
+ <div className="space-y-2">
+ <div className="text-12 leading-4 text-[var(--text-secondary)]">
+ {metaParts.join(' · ')}
+ </div>
+ {model.logs.length > 0 && (
+ <div className="space-y-0.5">
+ {model.logs.map((line, index) => (
+ // logs 是只读快照,快照内顺序稳定,index key 足够。
+ <div key={index} className="truncate text-12 leading-4 text-[var(--text-tertiary)]">
+ {line}
+ </div>
+ ))}
+ </div>
+ )}
+ {model.groups.map((group, groupIndex) => (
+ <div key={group.title ?? `orphan-${groupIndex}`} className="space-y-1">
+ {group.title && (
+ <div className="truncate text-11 font-medium uppercase tracking-wide text-[var(--text-tertiary)]">
+ {group.title}
+ {group.detail && <span className="normal-case"> · {group.detail}</span>}
+ </div>
+ )}
+ {group.agents.map((row) => (
+ <AgentRow key={row.key} row={row} />
+ ))}
+ </div>
+ ))}
+ </div>
+ );
+}
+
+function AgentRow({ row }: { row: WorkflowTreeAgentRow }) {
+ const { t } = useTranslation();
+ const Icon = agentStateIcon(row.state);
+ const spinning = isSpinning(row.state);
+ const modelLabel = formatModelShortLabel(row.model);
+ const stateLabel = t(`chat.workflowTree.state.${row.state}`, { defaultValue: row.state });
+ const isErrorState = row.state === 'failed' || row.state === 'error';
+ const isDoneState = row.state === 'done' || row.state === 'completed';
+ // 行尾动态文本:error/failed → error(缺失用 i18n 兜底);done → resultPreview;
+ // 进行中(running/start/progress/未知)→ lastToolName · lastToolSummary。
+ const trailing = isErrorState
+ ? (row.error ?? t('chat.workflowTree.endedEarly'))
+ : isDoneState
+ ? row.resultPreview
+ : spinning && row.lastToolName
+ ? row.lastToolSummary
+ ? `${row.lastToolName} · ${row.lastToolSummary}`
+ : row.lastToolName
+ : undefined;
+
+ return (
+ <div className="flex min-w-0 items-center gap-2">
+ <Spinner
+ icon={Icon}
+ size={13}
+ spinning={spinning}
+ aria-label={stateLabel}
+ className={cn(
+ 'shrink-0 text-[var(--text-secondary)]',
+ isErrorState && 'text-[var(--error-fg)]',
+ )}
+ />
+ <span className="min-w-0 truncate text-13 leading-5 text-[var(--text-primary)]">
+ {row.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 row.attempt === 'number' && row.attempt > 1 && (
+ <span className="shrink-0 text-11 leading-4 text-[var(--text-tertiary)]">
+ {t('chat.workflowTree.attempt', { count: row.attempt })}
+ </span>
+ )}
+ {trailing && (
+ <span
+ className={cn(
+ 'min-w-0 flex-1 truncate text-12 leading-4',
+ isErrorState ? 'text-[var(--error-fg)]' : 'text-[var(--text-tertiary)]',
+ )}
+ >
+ {trailing}
+ </span>
+ )}
+ {isDoneState && typeof row.durationMs === 'number' && (
+ <span className="shrink-0 text-11 leading-4 text-[var(--text-tertiary)]">
+ {formatDuration(row.durationMs)}
+ </span>
+ )}
+ </div>
+ );
+}
diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/__tests__/listSessionTasks.test.ts b/apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/__tests__/listSessionTasks.test.ts
new file mode 100644
index 0000000000..0be1aac346
--- /dev/null
+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/__tests__/listSessionTasks.test.ts
@@ -0,0 +1,411 @@
+/**
+ * listSessionTasks 单测 —— 「后台任务」面板任务枚举纯函数。
+ * 覆盖:配对 / 去重 / 孤儿 gating / 历史 completed 推导 / 后台 Bash 识别 /
+ * 分区排序 / 未知 taskType。构造最小 Message / AgentTaskUpdate 字面量,
+ * 不触碰 store / transport。
+ */
+
+import { describe, expect, it } from 'vitest';
+
+import type { Message } from '@/lib/ccAgent.types';
+import type { AgentTaskUpdate } from '@/lib/makerChatStore';
+
+import { listSessionTasks } from '../listSessionTasks';
+
+// ---------------------------------------------------------------------------
+// 构造器:Message 必填字段(id/clientId/sessionId/role/content/toolUseId/
+// agentMeta/createdAt)全给默认值,测试只声明差异部分。
+// ---------------------------------------------------------------------------
+
+function baseMessage(partial: Partial<Message> & Pick<Message, 'clientId' | 'role'>): Message {
+ return {
+ id: partial.clientId,
+ sessionId: 's1',
+ content: '',
+ toolUseId: null,
+ agentMeta: null,
+ createdAt: '2026-07-27T00:00:00.000Z',
+ ...partial,
+ } as Message;
+}
+
+/** tool_use 行:DB 形态,toolName/input 存 content 对象里。 */
+function toolUse(
+ clientId: string,
+ toolUseId: string | null,
+ toolName: string,
+ input: unknown = {},
+): Message {
+ return baseMessage({
+ clientId,
+ role: 'tool_use',
+ toolUseId,
+ content: { toolName, input },
+ });
+}
+
+function toolResult(clientId: string, toolUseId: string | null, content = 'ok'): Message {
+ return baseMessage({ clientId, role: 'tool_result', toolUseId, content });
+}
+
+function assistant(clientId: string, content = 'text'): Message {
+ return baseMessage({ clientId, role: 'assistant', content });
+}
+
+function makeUpdate(partial: Partial<AgentTaskUpdate> & Pick<AgentTaskUpdate, 'taskId'>): AgentTaskUpdate {
+ return {
+ provider: 'claude-code',
+ status: 'running',
+ ...partial,
+ };
+}
+
+/** 模拟 store reducer 的多 key 别名:taskId 与 parentToolUseId 指向同一 update。 */
+function aliasedMap(update: AgentTaskUpdate): Map<string, AgentTaskUpdate> {
+ const map = new Map<string, AgentTaskUpdate>();
+ map.set(update.taskId, update);
+ if (update.parentToolUseId) map.set(update.parentToolUseId, update);
+ return map;
+}
+
+// ---------------------------------------------------------------------------
+// 配对
+// ---------------------------------------------------------------------------
+
+describe('listSessionTasks 配对', () => {
+ it('Task toolCall 按 toolUseId 配上 update,一行,key = taskId', () => {
+ const update = makeUpdate({
+ taskId: 'task-1',
+ parentToolUseId: 'toolu-1',
+ title: 'Review auth flow',
+ });
+ const { running, completed } = listSessionTasks({
+ messages: [toolUse('c1', 'toolu-1', 'Task', { description: 'fallback desc' })],
+ taskUpdates: aliasedMap(update),
+ isSessionStreaming: true,
+ });
+ expect(completed).toHaveLength(0);
+ expect(running).toHaveLength(1);
+ expect(running[0]).toMatchObject({
+ key: 'task-1',
+ taskId: 'task-1',
+ kind: 'agent',
+ title: 'Review auth flow',
+ status: 'running',
+ provider: 'claude-code',
+ toolCallClientId: 'c1',
+ toolUseId: 'toolu-1',
+ });
+ expect(running[0].update).toBe(update);
+ });
+
+ it('toolUseId 查不到时回退 clientId 配对(findTaskUpdate 同口径)', () => {
+ const update = makeUpdate({ taskId: 'task-2', title: 'By clientId' });
+ const map = new Map<string, AgentTaskUpdate>([['c2', update]]);
+ const { running } = listSessionTasks({
+ messages: [toolUse('c2', 'toolu-2', 'Task')],
+ taskUpdates: map,
+ isSessionStreaming: true,
+ });
+ expect(running).toHaveLength(1);
+ expect(running[0].update).toBe(update);
+ expect(running[0].title).toBe('By clientId');
+ });
+
+ it('collab:* toolCall 无 update 时 provider = codex', () => {
+ const { running } = listSessionTasks({
+ messages: [toolUse('c3', 'toolu-3', 'collab:reviewer', { description: 'review it' })],
+ taskUpdates: undefined,
+ isSessionStreaming: false,
+ });
+ expect(running).toHaveLength(1);
+ expect(running[0]).toMatchObject({ kind: 'agent', provider: 'codex', title: 'review it' });
+ });
+
+ it('Workflow toolCall → kind workflow,标题优先 update.workflowName', () => {
+ const update = makeUpdate({
+ taskId: 'wf-1',
+ parentToolUseId: 'toolu-wf',
+ taskType: 'local_workflow',
+ workflowName: 'nightly-release',
+ title: 'should not win',
+ });
+ const { running } = listSessionTasks({
+ messages: [toolUse('c4', 'toolu-wf', 'Workflow')],
+ taskUpdates: aliasedMap(update),
+ isSessionStreaming: true,
+ });
+ expect(running).toHaveLength(1);
+ expect(running[0]).toMatchObject({ kind: 'workflow', title: 'nightly-release' });
+ });
+});
+
+// ---------------------------------------------------------------------------
+// 去重
+// ---------------------------------------------------------------------------
+
+describe('listSessionTasks 去重', () => {
+ it('同一任务的 toolCall 与多 key 别名 update 只出一行(不再当孤儿补渲染)', () => {
+ const update = makeUpdate({ taskId: 'task-1', parentToolUseId: 'toolu-1' });
+ const { running, completed } = listSessionTasks({
+ messages: [toolUse('c1', 'toolu-1', 'Task', { description: 'd' })],
+ taskUpdates: aliasedMap(update), // 两个 key 指向同一 update
+ isSessionStreaming: true, // 孤儿通道开着也不得重复
+ });
+ expect(running.length + completed.length).toBe(1);
+ });
+
+ it('重复 toolUseId 的 toolCall 只出一行(首行为准)', () => {
+ const { running, completed } = listSessionTasks({
+ messages: [
+ toolUse('c1', 'toolu-dup', 'Task', { description: 'first' }),
+ toolUse('c2', 'toolu-dup', 'Task', { description: 'second' }),
+ ],
+ taskUpdates: undefined,
+ isSessionStreaming: false,
+ });
+ expect(running.length + completed.length).toBe(1);
+ expect(running[0]?.title).toBe('first');
+ });
+
+ it('孤儿区内同一任务的多 key 别名只出一行', () => {
+ const update = makeUpdate({ taskId: 'task-x', parentToolUseId: 'toolu-x' });
+ const { running } = listSessionTasks({
+ messages: [],
+ taskUpdates: aliasedMap(update),
+ isSessionStreaming: true,
+ });
+ expect(running).toHaveLength(1);
+ expect(running[0].taskId).toBe('task-x');
+ });
+});
+
+// ---------------------------------------------------------------------------
+// 孤儿 gating
+// ---------------------------------------------------------------------------
+
+describe('listSessionTasks 孤儿 gating', () => {
+ const orphan = makeUpdate({ taskId: 'orphan-1', title: 'Codex collab', provider: 'codex' });
+
+ it('isSessionStreaming=true:孤儿 update 列出,orderIndex 排在消息之后', () => {
+ const { running } = listSessionTasks({
+ messages: [toolUse('c1', 'toolu-1', 'Task', { description: 'inline' })],
+ taskUpdates: new Map([['orphan-1', orphan]]),
+ isSessionStreaming: true,
+ });
+ expect(running).toHaveLength(2);
+ const orphanItem = running.find((it) => it.taskId === 'orphan-1');
+ expect(orphanItem).toMatchObject({
+ key: 'orphan-1',
+ kind: 'agent', // 无 taskType 的孤儿默认 agent(codex collab 典型形态)
+ provider: 'codex',
+ title: 'Codex collab',
+ });
+ // 孤儿排最后:orderIndex 大于消息窗口内条目
+ expect(orphanItem!.orderIndex).toBeGreaterThan(running.find((it) => it.taskId !== 'orphan-1')!.orderIndex);
+ });
+
+ it('isSessionStreaming=false:孤儿是陈旧残留,不列出', () => {
+ const { running, completed } = listSessionTasks({
+ messages: [],
+ taskUpdates: new Map([['orphan-1', orphan]]),
+ isSessionStreaming: false,
+ });
+ expect(running).toHaveLength(0);
+ expect(completed).toHaveLength(0);
+ });
+});
+
+// ---------------------------------------------------------------------------
+// 历史 completed 推导(无 update)
+// ---------------------------------------------------------------------------
+
+describe('listSessionTasks 历史条目状态推导', () => {
+ it('有 tool_result(toolUseId 命中)→ completed;没有 → running', () => {
+ const { running, completed } = listSessionTasks({
+ messages: [
+ toolUse('c1', 'toolu-done', 'Task', { description: 'done task' }),
+ assistant('a1'),
+ toolUse('c2', 'toolu-open', 'Task', { description: 'open task' }),
+ // 结果行不紧邻(orphan tool_result append 到末尾),toolUseId 查表仍要配上
+ toolResult('r1', 'toolu-done'),
+ ],
+ taskUpdates: undefined,
+ isSessionStreaming: false,
+ });
+ expect(completed).toHaveLength(1);
+ expect(completed[0]).toMatchObject({ title: 'done task', status: 'completed' });
+ expect(running).toHaveLength(1);
+ expect(running[0]).toMatchObject({ title: 'open task', status: 'running' });
+ });
+
+ it('旧数据 toolUseId 缺失:紧邻 tool_result 的 adjacency 兜底 → completed', () => {
+ const { completed } = listSessionTasks({
+ messages: [toolUse('c1', null, 'Task', { description: 'legacy' }), toolResult('r1', null)],
+ taskUpdates: undefined,
+ isSessionStreaming: false,
+ });
+ expect(completed).toHaveLength(1);
+ expect(completed[0]).toMatchObject({ title: 'legacy', status: 'completed', key: 'c1' });
+ });
+
+ it('标题链:无 update 时 description 优先,缺 description 回退 prompt 并截断', () => {
+ const longPrompt = 'p'.repeat(200);
+ const { running } = listSessionTasks({
+ messages: [toolUse('c1', 'toolu-1', 'Task', { prompt: longPrompt })],
+ taskUpdates: undefined,
+ isSessionStreaming: false,
+ });
+ expect(running[0].title).toHaveLength(96);
+ expect(running[0].title.endsWith('…')).toBe(true);
+ });
+});
+
+// ---------------------------------------------------------------------------
+// 后台 Bash 识别
+// ---------------------------------------------------------------------------
+
+describe('listSessionTasks 后台 Bash', () => {
+ it('run_in_background=true 的 Bash 进列表,kind=bash,标题 description ?? command', () => {
+ const { running } = listSessionTasks({
+ messages: [
+ toolUse('c1', 'toolu-1', 'Bash', { run_in_background: true, command: 'pnpm dev' }),
+ toolUse('c2', 'toolu-2', 'Bash', {
+ run_in_background: true,
+ command: 'pnpm test:unit',
+ description: 'Run unit tests',
+ }),
+ ],
+ taskUpdates: undefined,
+ isSessionStreaming: false,
+ });
+ expect(running).toHaveLength(2);
+ expect(running[0]).toMatchObject({ kind: 'bash', title: 'pnpm dev', provider: 'claude-code' });
+ expect(running[1]).toMatchObject({ kind: 'bash', title: 'Run unit tests' });
+ });
+
+ it('前台 Bash 与其他普通工具不进列表', () => {
+ const { running, completed } = listSessionTasks({
+ messages: [
+ toolUse('c1', 'toolu-1', 'Bash', { command: 'ls' }),
+ toolUse('c2', 'toolu-2', 'Bash', { command: 'ls', run_in_background: false }),
+ toolUse('c3', 'toolu-3', 'Read', { file_path: '/tmp/x' }),
+ ],
+ taskUpdates: undefined,
+ isSessionStreaming: false,
+ });
+ expect(running).toHaveLength(0);
+ expect(completed).toHaveLength(0);
+ });
+});
+
+// ---------------------------------------------------------------------------
+// 分区排序
+// ---------------------------------------------------------------------------
+
+describe('listSessionTasks 分区排序', () => {
+ it('running 按出现顺序升序;failed/stopped/completed 全进 completed 区', () => {
+ const failed = makeUpdate({ taskId: 't-f', parentToolUseId: 'tu-f', status: 'failed' });
+ const stopped = makeUpdate({ taskId: 't-s', parentToolUseId: 'tu-s', status: 'stopped' });
+ const map = new Map<string, AgentTaskUpdate>([
+ ...aliasedMap(failed),
+ ...aliasedMap(stopped),
+ ]);
+ const { running, completed } = listSessionTasks({
+ messages: [
+ toolUse('c1', 'tu-a', 'Task', { description: 'first running' }),
+ toolUse('c2', 'tu-f', 'Task', { description: 'failed one' }),
+ toolUse('c3', 'tu-s', 'Task', { description: 'stopped one' }),
+ toolUse('c4', 'tu-b', 'Task', { description: 'second running' }),
+ ],
+ taskUpdates: map,
+ isSessionStreaming: true,
+ });
+ expect(running.map((it) => it.title)).toEqual(['first running', 'second running']);
+ expect(completed.map((it) => it.status).sort()).toEqual(['failed', 'stopped']);
+ });
+
+ it('completed 按 update.updatedAt 倒序;缺 updatedAt 的历史条目排后、组内 orderIndex 倒序', () => {
+ const older = makeUpdate({
+ taskId: 't-old',
+ parentToolUseId: 'tu-old',
+ status: 'completed',
+ updatedAt: '2026-07-27T01:00:00.000Z',
+ });
+ const newer = makeUpdate({
+ taskId: 't-new',
+ parentToolUseId: 'tu-new',
+ status: 'completed',
+ updatedAt: '2026-07-27T02:00:00.000Z',
+ });
+ const map = new Map<string, AgentTaskUpdate>([
+ ...aliasedMap(older),
+ ...aliasedMap(newer),
+ ]);
+ const { completed } = listSessionTasks({
+ messages: [
+ // 两条无 update 的历史条目(有结果 → completed,无时间戳)
+ toolUse('h1', 'tu-h1', 'Task', { description: 'history early' }),
+ toolResult('r1', 'tu-h1'),
+ toolUse('h2', 'tu-h2', 'Task', { description: 'history late' }),
+ toolResult('r2', 'tu-h2'),
+ toolUse('c1', 'tu-old', 'Task', { description: 'older live' }),
+ toolUse('c2', 'tu-new', 'Task', { description: 'newer live' }),
+ ],
+ taskUpdates: map,
+ isSessionStreaming: false,
+ });
+ expect(completed.map((it) => it.taskId ?? it.toolUseId)).toEqual([
+ 't-new', // updatedAt 最新
+ 't-old',
+ 'tu-h2', // 无时间戳:orderIndex 倒序
+ 'tu-h1',
+ ]);
+ });
+});
+
+// ---------------------------------------------------------------------------
+// 未知 taskType
+// ---------------------------------------------------------------------------
+
+describe('listSessionTasks 未知 taskType', () => {
+ it("词表外 taskType → kind 'other',不隐藏(toolCall 配对与孤儿两条路径)", () => {
+ const paired = makeUpdate({
+ taskId: 't-1',
+ parentToolUseId: 'tu-1',
+ taskType: 'local_mystery',
+ title: 'paired mystery',
+ });
+ const orphan = makeUpdate({ taskId: 't-2', taskType: 'local_mystery', title: 'orphan mystery' });
+ const map = new Map<string, AgentTaskUpdate>([...aliasedMap(paired), ['t-2', orphan]]);
+ const { running } = listSessionTasks({
+ messages: [toolUse('c1', 'tu-1', 'Task')],
+ taskUpdates: map,
+ isSessionStreaming: true,
+ });
+ expect(running).toHaveLength(2);
+ expect(running.map((it) => it.kind)).toEqual(['other', 'other']);
+ expect(running.map((it) => it.title)).toEqual(['paired mystery', 'orphan mystery']);
+ });
+
+ it("既知 taskType 词表:local_agent/local_workflow/local_bash 映射 agent/workflow/bash", () => {
+ const agent = makeUpdate({ taskId: 'a1', taskType: 'local_agent' });
+ const wf = makeUpdate({ taskId: 'w1', taskType: 'local_workflow' });
+ const bash = makeUpdate({ taskId: 'b1', taskType: 'local_bash' });
+ const map = new Map<string, AgentTaskUpdate>([
+ ['a1', agent],
+ ['w1', wf],
+ ['b1', bash],
+ ]);
+ const { running } = listSessionTasks({
+ messages: [],
+ taskUpdates: map,
+ isSessionStreaming: true,
+ });
+ expect(running.map((it) => [it.taskId, it.kind])).toEqual([
+ ['a1', 'agent'],
+ ['w1', 'workflow'],
+ ['b1', 'bash'],
+ ]);
+ });
+});
diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/__tests__/workflowProgressModel.test.ts b/apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/__tests__/workflowProgressModel.test.ts
new file mode 100644
index 0000000000..f5b6c4295d
--- /dev/null
+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/__tests__/workflowProgressModel.test.ts
@@ -0,0 +1,319 @@
+import { describe, expect, it } from 'vitest';
+
+import type { WorkflowProgressEntry } from '@cindy/maker-shared/agent-task';
+
+import type {
+ WorkflowAgentProgress,
+ WorkflowProgress,
+} from '../../../../../../shared/workflow-progress';
+import { buildWorkflowTreeModel } from '../workflowProgressModel';
+
+function phaseEntry(index: number, title: string): WorkflowProgressEntry {
+ return { type: 'workflow_phase', index, title };
+}
+
+function agentEntry(
+ index: number,
+ overrides: Partial<WorkflowProgressEntry> = {},
+): WorkflowProgressEntry {
+ return { type: 'workflow_agent', index, ...overrides };
+}
+
+function fileAgent(overrides: Partial<WorkflowAgentProgress> = {}): WorkflowAgentProgress {
+ return { label: 'a', agentId: 'file-a', state: 'done', ...overrides };
+}
+
+function fileProgress(overrides: Partial<WorkflowProgress> = {}): WorkflowProgress {
+ return {
+ runId: 'run-1',
+ status: 'running',
+ phases: [],
+ agents: [],
+ ...overrides,
+ };
+}
+
+describe('buildWorkflowTreeModel', () => {
+ it('两源都空时返回 null(undefined / 空数组 / null 各种组合)', () => {
+ expect(buildWorkflowTreeModel({ taskStatus: 'running' })).toBeNull();
+ expect(buildWorkflowTreeModel({ entries: [], fileProgress: null, taskStatus: 'running' })).toBeNull();
+ expect(buildWorkflowTreeModel({ entries: undefined, fileProgress: undefined, taskStatus: 'completed' })).toBeNull();
+ });
+
+ it('entries 在场时主结构来自 entries:phase 顺序、按 phaseTitle 归组、孤儿归末尾 null 组', () => {
+ const entries: WorkflowProgressEntry[] = [
+ phaseEntry(0, 'Research'),
+ phaseEntry(1, 'Write'),
+ agentEntry(2, {
+ agentId: 'a1',
+ label: 'search:web',
+ phaseTitle: 'Research',
+ state: 'done',
+ model: 'claude-haiku-4-5',
+ resultPreview: 'found 3 sources',
+ }),
+ agentEntry(3, {
+ agentId: 'a2',
+ label: 'writer',
+ phaseTitle: 'Write',
+ state: 'progress',
+ lastToolName: 'Write',
+ lastToolSummary: 'draft.md',
+ attempt: 2,
+ }),
+ agentEntry(4, { agentId: 'a3', label: 'stray', state: 'start' }),
+ ];
+ const model = buildWorkflowTreeModel({ entries, taskStatus: 'running' });
+ expect(model).not.toBeNull();
+ expect(model!.groups.map((g) => g.title)).toEqual(['Research', 'Write', null]);
+ expect(model!.groups[0].agents).toEqual([
+ {
+ key: 'a1',
+ label: 'search:web',
+ state: 'done',
+ model: 'claude-haiku-4-5',
+ resultPreview: 'found 3 sources',
+ },
+ ]);
+ expect(model!.groups[1].agents[0]).toMatchObject({
+ key: 'a2',
+ label: 'writer',
+ state: 'progress',
+ lastToolName: 'Write',
+ lastToolSummary: 'draft.md',
+ attempt: 2,
+ });
+ expect(model!.groups[2].agents[0]).toMatchObject({ key: 'a3', label: 'stray', state: 'start' });
+ });
+
+ it('entries 里没有 agent 的 phase 不产出分组;label 缺失回退 agentId', () => {
+ const entries: WorkflowProgressEntry[] = [
+ phaseEntry(0, 'Empty phase'),
+ phaseEntry(1, 'Busy'),
+ agentEntry(2, { agentId: 'only-id', phaseTitle: 'Busy', state: 'running' }),
+ ];
+ const model = buildWorkflowTreeModel({ entries, taskStatus: 'running' })!;
+ expect(model.groups.map((g) => g.title)).toEqual(['Busy']);
+ expect(model.groups[0].agents[0].label).toBe('only-id');
+ });
+
+ it('entries 缺失时整树退回 fileProgress,文件 state 词表原样保留', () => {
+ const file = fileProgress({
+ status: 'running',
+ phases: [
+ { index: 0, title: 'Phase A', detail: 'gather info' },
+ { index: 1, title: 'Phase B' },
+ ],
+ agents: [
+ fileAgent({ label: 'x', agentId: 'fx', phaseTitle: 'Phase A', state: 'done', durationMs: 4000, resultPreview: 'ok' }),
+ fileAgent({ label: 'y', agentId: 'fy', phaseTitle: 'Phase B', state: 'killed', error: 'boom' }),
+ fileAgent({ label: 'z', agentId: 'fz', phaseTitle: 'Unknown', state: 'queued' }),
+ ],
+ });
+ const model = buildWorkflowTreeModel({ fileProgress: file, taskStatus: 'running' })!;
+ expect(model.groups.map((g) => g.title)).toEqual(['Phase A', 'Phase B', null]);
+ expect(model.groups[0].detail).toBe('gather info');
+ expect(model.groups[0].agents[0]).toEqual({
+ key: 'fx',
+ label: 'x',
+ state: 'done',
+ durationMs: 4000,
+ resultPreview: 'ok',
+ });
+ expect(model.groups[1].agents[0]).toMatchObject({ state: 'killed', error: 'boom' });
+ expect(model.groups[2].agents[0]).toMatchObject({ label: 'z', state: 'queued' });
+ });
+
+ it('entries 在场时 logs 与 phase detail 从文件回填', () => {
+ const entries: WorkflowProgressEntry[] = [
+ phaseEntry(0, 'Research'),
+ agentEntry(1, { agentId: 'a1', label: 'search', phaseTitle: 'Research', state: 'running' }),
+ ];
+ const file = fileProgress({
+ logs: ['starting research', 'found sources'],
+ phases: [{ index: 0, title: 'Research', detail: 'parallel web search' }],
+ agents: [],
+ });
+ const model = buildWorkflowTreeModel({ entries, fileProgress: file, taskStatus: 'running' })!;
+ expect(model.logs).toEqual(['starting research', 'found sources']);
+ expect(model.groups[0].detail).toBe('parallel web search');
+ // 运行中(非终态)不做 agent 字段回填,state 保持 entries 原样
+ expect(model.groups[0].agents[0].state).toBe('running');
+ });
+
+ it('无文件时 logs 为空数组、detail 缺失', () => {
+ const entries: WorkflowProgressEntry[] = [
+ phaseEntry(0, 'P'),
+ agentEntry(1, { agentId: 'a1', label: 'w', phaseTitle: 'P', state: 'done' }),
+ ];
+ const model = buildWorkflowTreeModel({ entries, taskStatus: 'running' })!;
+ expect(model.logs).toEqual([]);
+ expect(model.groups[0].detail).toBeUndefined();
+ });
+
+ it('任务终态时按 label+phaseTitle 从文件回填 resultPreview/durationMs/error(只补缺不覆盖,撞名取首个)', () => {
+ const entries: WorkflowProgressEntry[] = [
+ phaseEntry(0, 'P'),
+ // 缺 resultPreview/durationMs → 应回填
+ agentEntry(1, { agentId: 'a1', label: 'w', phaseTitle: 'P', state: 'done' }),
+ // entries 已有 resultPreview → 不覆盖;durationMs 仍回填
+ agentEntry(2, {
+ agentId: 'a2',
+ label: 'v',
+ phaseTitle: 'P',
+ state: 'done',
+ resultPreview: 'from entries',
+ }),
+ ];
+ const file = fileProgress({
+ status: 'completed',
+ agents: [
+ // 与 a1 同 label+phaseTitle 的两条 → 取首个
+ fileAgent({ label: 'w', phaseTitle: 'P', state: 'done', resultPreview: 'first', durationMs: 1000 }),
+ fileAgent({ label: 'w', phaseTitle: 'P', state: 'done', resultPreview: 'second', durationMs: 2000 }),
+ fileAgent({ label: 'v', phaseTitle: 'P', state: 'done', resultPreview: 'from file', durationMs: 3000 }),
+ // label 相同但 phaseTitle 不同 → 不得匹配
+ fileAgent({ label: 'w', phaseTitle: 'Other', state: 'failed', error: 'wrong phase' }),
+ ],
+ });
+ const model = buildWorkflowTreeModel({ entries, fileProgress: file, taskStatus: 'completed' })!;
+ const [a1, a2] = model.groups[0].agents;
+ expect(a1.resultPreview).toBe('first');
+ expect(a1.durationMs).toBe(1000);
+ expect(a1.error).toBeUndefined();
+ expect(a2.resultPreview).toBe('from entries');
+ expect(a2.durationMs).toBe(3000);
+ });
+
+ it('任务非终态时不做文件字段回填', () => {
+ const entries: WorkflowProgressEntry[] = [
+ phaseEntry(0, 'P'),
+ agentEntry(1, { agentId: 'a1', label: 'w', phaseTitle: 'P', state: 'done' }),
+ ];
+ const file = fileProgress({
+ agents: [fileAgent({ label: 'w', phaseTitle: 'P', resultPreview: 'r', durationMs: 500 })],
+ });
+ const model = buildWorkflowTreeModel({ entries, fileProgress: file, taskStatus: 'running' })!;
+ expect(model.groups[0].agents[0].resultPreview).toBeUndefined();
+ expect(model.groups[0].agents[0].durationMs).toBeUndefined();
+ });
+
+ it('终态修正:任务终态而 agent 仍呈 start/progress/running/queued → state 改 error,error 字段留空', () => {
+ const entries: WorkflowProgressEntry[] = [
+ agentEntry(0, { agentId: 'a1', label: 'l1', state: 'start' }),
+ agentEntry(1, { agentId: 'a2', label: 'l2', state: 'progress' }),
+ agentEntry(2, { agentId: 'a3', label: 'l3', state: 'running' }),
+ agentEntry(3, { agentId: 'a4', label: 'l4', state: 'queued' }),
+ agentEntry(4, { agentId: 'a5', label: 'l5', state: 'done' }),
+ agentEntry(5, { agentId: 'a6', label: 'l6', state: 'failed', error: 'real error' }),
+ ];
+ const model = buildWorkflowTreeModel({ entries, taskStatus: 'stopped' })!;
+ const rows = model.groups[0].agents;
+ for (const key of ['a1', 'a2', 'a3', 'a4']) {
+ const row = rows.find((r) => r.key === key)!;
+ expect(row.state).toBe('error');
+ expect(row.error).toBeUndefined();
+ }
+ expect(rows.find((r) => r.key === 'a5')!.state).toBe('done');
+ expect(rows.find((r) => r.key === 'a6')).toMatchObject({ state: 'failed', error: 'real error' });
+ });
+
+ it('终态修正同样作用于 file-only 路径', () => {
+ const file = fileProgress({
+ status: 'failed',
+ agents: [
+ fileAgent({ label: 'x', agentId: 'fx', state: 'running' }),
+ fileAgent({ label: 'y', agentId: 'fy', state: 'stopped' }),
+ ],
+ });
+ const model = buildWorkflowTreeModel({ fileProgress: file, taskStatus: 'failed' })!;
+ expect(model.groups[0].agents.find((r) => r.key === 'fx')!.state).toBe('error');
+ // stopped 是终态,不修正
+ expect(model.groups[0].agents.find((r) => r.key === 'fy')!.state).toBe('stopped');
+ });
+
+ it('任务运行中不做终态修正', () => {
+ const entries: WorkflowProgressEntry[] = [
+ agentEntry(0, { agentId: 'a1', label: 'l1', state: 'progress' }),
+ ];
+ const model = buildWorkflowTreeModel({ entries, taskStatus: 'running' })!;
+ expect(model.groups[0].agents[0].state).toBe('progress');
+ });
+
+ it('aggregate:totalTokens/totalToolCalls/durationMs 文件优先,缺失回退 usage', () => {
+ const entries: WorkflowProgressEntry[] = [
+ agentEntry(0, { agentId: 'a1', label: 'l1', state: 'running' }),
+ ];
+ const usage = { totalTokens: 111, toolUses: 22, durationMs: 3333 };
+ const withFile = buildWorkflowTreeModel({
+ entries,
+ fileProgress: fileProgress({ totalTokens: 999, totalToolCalls: 88, durationMs: 7777 }),
+ taskStatus: 'running',
+ usage,
+ })!;
+ expect(withFile.aggregate).toMatchObject({ totalTokens: 999, totalToolCalls: 88, durationMs: 7777 });
+
+ const withoutFile = buildWorkflowTreeModel({ entries, taskStatus: 'running', usage })!;
+ expect(withoutFile.aggregate).toMatchObject({ totalTokens: 111, totalToolCalls: 22, durationMs: 3333 });
+
+ // 文件在场但字段缺失 → 逐字段回退 usage
+ const partialFile = buildWorkflowTreeModel({
+ entries,
+ fileProgress: fileProgress({ totalTokens: 999 }),
+ taskStatus: 'running',
+ usage,
+ })!;
+ expect(partialFile.aggregate).toMatchObject({ totalTokens: 999, totalToolCalls: 22, durationMs: 3333 });
+ });
+
+ it('aggregate.status:文件终态优先;文件非终态用 taskStatus', () => {
+ const entries: WorkflowProgressEntry[] = [
+ agentEntry(0, { agentId: 'a1', label: 'l1', state: 'done' }),
+ ];
+ // 文件已有终态结论(killed)→ 覆盖 taskStatus
+ const terminalFile = buildWorkflowTreeModel({
+ entries,
+ fileProgress: fileProgress({ status: 'killed' }),
+ taskStatus: 'stopped',
+ })!;
+ expect(terminalFile.aggregate.status).toBe('killed');
+
+ // 文件还是 running(记录滞后)→ 用 taskStatus
+ const staleFile = buildWorkflowTreeModel({
+ entries,
+ fileProgress: fileProgress({ status: 'running' }),
+ taskStatus: 'completed',
+ })!;
+ expect(staleFile.aggregate.status).toBe('completed');
+
+ // 无文件 → taskStatus
+ const noFile = buildWorkflowTreeModel({ entries, taskStatus: 'running' })!;
+ expect(noFile.aggregate.status).toBe('running');
+ });
+
+ it('aggregate.agentCount:file.agentCount 优先,缺失取 agent 行数', () => {
+ const entries: WorkflowProgressEntry[] = [
+ agentEntry(0, { agentId: 'a1', label: 'l1', state: 'running' }),
+ agentEntry(1, { agentId: 'a2', label: 'l2', state: 'running' }),
+ ];
+ const withCount = buildWorkflowTreeModel({
+ entries,
+ fileProgress: fileProgress({ agentCount: 7 }),
+ taskStatus: 'running',
+ })!;
+ expect(withCount.aggregate.agentCount).toBe(7);
+
+ const withoutCount = buildWorkflowTreeModel({ entries, taskStatus: 'running' })!;
+ expect(withoutCount.aggregate.agentCount).toBe(2);
+ });
+
+ it('entries 的 state 缺失按 queued 处理,任务终态时同样被修正为 error', () => {
+ const entries: WorkflowProgressEntry[] = [
+ agentEntry(0, { agentId: 'a1', label: 'l1' }),
+ ];
+ const running = buildWorkflowTreeModel({ entries, taskStatus: 'running' })!;
+ expect(running.groups[0].agents[0].state).toBe('queued');
+ const done = buildWorkflowTreeModel({ entries, taskStatus: 'completed' })!;
+ expect(done.groups[0].agents[0].state).toBe('error');
+ });
+});
diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/chatTaskFocusIntent.ts b/apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/chatTaskFocusIntent.ts
new file mode 100644
index 0000000000..21337109bd
--- /dev/null
+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/chatTaskFocusIntent.ts
@@ -0,0 +1,31 @@
+/**
+ * chatTaskFocusIntent —— 「后台任务面板行点击 → 聊天流定位对应任务卡」的模块级通道。
+ *
+ * 约束:
+ * - 纯模块级 emitter,不落任何状态;本阶段只提供通道,消费端(聊天流滚动定位)
+ * 接线归后续阶段。
+ * - listener 抛错不反噬调用方(与 lib/sidebarCommands 同口径)。
+ */
+
+type ChatTaskFocusListener = (sessionId: string, clientId: string) => void;
+
+const listeners = new Set<ChatTaskFocusListener>();
+
+/** 请求聊天流定位到 clientId 对应的任务卡。无订阅者时为 no-op。 */
+export function requestChatTaskFocus(sessionId: string, clientId: string): void {
+ for (const listener of [...listeners]) {
+ try {
+ listener(sessionId, clientId);
+ } catch {
+ // listener 异常吞掉:通道不因单个坏订阅者失效。
+ }
+ }
+}
+
+/** 订阅定位请求;返回退订函数。 */
+export function subscribeChatTaskFocus(cb: ChatTaskFocusListener): () => void {
+ listeners.add(cb);
+ return () => {
+ listeners.delete(cb);
+ };
+}
diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/index.tsx b/apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/index.tsx
new file mode 100644
index 0000000000..b4f169ce92
--- /dev/null
+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/index.tsx
@@ -0,0 +1,62 @@
+/**
+ * background-tasks plugin —— 右栏「后台任务」页签(本会话所有后台任务的主视图)。
+ *
+ * 约束:
+ * - 每会话单例(singleton),进「+」菜单;程序化入口见
+ * lib/openBackgroundTasksTab.ts。
+ * - state 只持有一次性详情定位 focusTaskId(openBackgroundTasksTab 写入,
+ * Body 消费后清空);serialize/hydrate 防御式,坏形状一律回落默认。
+ * - 注册:模块顶层 import-side-effect,由 plugins/index.ts 汇总。
+ */
+
+import { ListTodo } from 'lucide-react';
+import type { TFunction } from 'i18next';
+
+import { registerTabKind } from '../../registry';
+import type { TabKindPlugin } from '../../types';
+import { BackgroundTasksBody } from './BackgroundTasksBody';
+
+export interface BackgroundTasksState {
+ /** 一次性详情定位请求:对应 workflow 任务时直接进详情,消费后清空。 */
+ focusTaskId?: string | null;
+}
+
+const DEFAULT_STATE: BackgroundTasksState = {};
+
+function BackgroundTasksTabPillTitle({ t }: { state: BackgroundTasksState; t: TFunction }) {
+ return <>{t('rightSidebar.tabs.kinds.backgroundTasks')}</>;
+}
+
+function BackgroundTasksTabPillIcon() {
+ return <ListTodo size={13} />;
+}
+
+const plugin: TabKindPlugin<BackgroundTasksState> = {
+ kind: 'background-tasks',
+ menu: {
+ kind: 'background-tasks',
+ labelKey: 'rightSidebar.tabs.kinds.backgroundTasks',
+ icon: ListTodo,
+ order: 17, // review=15 与 web-browser=20 之间
+ enabled: true,
+ singleton: true, // 每个对话至多 1 个后台任务面板
+ },
+ TabPillTitle: BackgroundTasksTabPillTitle,
+ TabPillIcon: BackgroundTasksTabPillIcon,
+ TabBody: BackgroundTasksBody,
+ defaultState: () => ({ ...DEFAULT_STATE }),
+ // 持久化只留 focusTaskId(未消费的定位请求跨重启至多重放一次;无请求写空对象)。
+ serializeState: (state) =>
+ typeof state.focusTaskId === 'string' && state.focusTaskId
+ ? { focusTaskId: state.focusTaskId }
+ : {},
+ hydrateState: (raw): BackgroundTasksState => {
+ if (!raw || typeof raw !== 'object') return { ...DEFAULT_STATE };
+ const obj = raw as Record<string, unknown>;
+ return typeof obj.focusTaskId === 'string' && obj.focusTaskId
+ ? { focusTaskId: obj.focusTaskId }
+ : { ...DEFAULT_STATE };
+ },
+};
+
+registerTabKind(plugin as unknown as TabKindPlugin, import.meta.hot);
diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/listSessionTasks.ts b/apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/listSessionTasks.ts
new file mode 100644
index 0000000000..809f4a1a85
--- /dev/null
+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/listSessionTasks.ts
@@ -0,0 +1,303 @@
+/**
+ * listSessionTasks —— 「后台任务」面板的任务枚举纯函数。
+ *
+ * 约束(与聊天流渲染层保持同口径,防止面板与卡片状态分叉):
+ * - 工具识别 / update 配对口径 = MessageStream.buildRenderItems + findTaskUpdate:
+ * 先 toolUseId 后 clientId 查 taskUpdates;tool_result 存在性 = toolUseId 查表
+ * 命中,或紧邻其后的 tool_result 行(旧数据 toolUseId 缺失时的 adjacency 兜底)。
+ * - 状态推导口径 = AgentTaskCard:update?.status 优先,无 update 时有结果为
+ * completed、无结果为 running。
+ * - 孤儿 update(map 里有、消息窗口内配不到 toolCall)只在会话运行中列出
+ * (口径 = maker-shared/messageRender.appendOrphanAgentTasks 的 gating 注释:
+ * 空闲态的孤儿是滑出分页窗口的陈旧残留,不得复播)。
+ * - 纯函数:不触碰 store / transport / i18n;title 取不到任何来源时返回空串,
+ * 由 UI 层用本地化兜底文案补齐。
+ * - 本文件签名是并行开发契约,不得改动。
+ */
+
+import { isAgentTaskToolName } from '@cindy/maker-shared/agent-task';
+
+import type { Message } from '@/lib/ccAgent.types';
+import type { AgentTaskStatus, AgentTaskUpdate } from '@/lib/makerChatStore';
+
+export interface SessionTaskItem {
+ /** 稳定 key:taskId ?? toolUseId ?? clientId。 */
+ key: string;
+ taskId?: string;
+ kind: 'workflow' | 'agent' | 'bash' | 'other';
+ /** 标题链取不到任何来源时为 ''(UI 层负责 i18n 兜底)。 */
+ title: string;
+ status: AgentTaskStatus;
+ provider: 'claude-code' | 'codex';
+ update?: AgentTaskUpdate;
+ toolCallClientId?: string;
+ toolUseId?: string;
+ /** 消息窗口内出现顺序;孤儿 update 排最后。 */
+ orderIndex: number;
+}
+
+export interface SessionTaskLists {
+ running: SessionTaskItem[];
+ completed: SessionTaskItem[];
+}
+
+/** 标题截断上限与 AgentTaskCard 的标题链一致(96)。 */
+const TITLE_MAX = 96;
+
+/** update.taskType → 面板 kind 的既知词表;词表外的非空值一律归 'other',不隐藏。 */
+const KNOWN_TASK_TYPE_KIND: Readonly<Record<string, SessionTaskItem['kind']>> = {
+ local_workflow: 'workflow',
+ local_agent: 'agent',
+ local_bash: 'bash',
+};
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return Boolean(value) && typeof value === 'object';
+}
+
+/** 与 AgentTaskCard.readInputString 同口径:按 key 顺序取第一个非空白字符串。 */
+function readInputString(input: unknown, keys: readonly string[]): string | undefined {
+ if (!isRecord(input)) return undefined;
+ for (const key of keys) {
+ const value = input[key];
+ if (typeof value === 'string' && value.trim()) return value.trim();
+ }
+ return undefined;
+}
+
+/** 与 AgentTaskCard.compactText 同口径:压平空白 + 截断加省略号。 */
+function compactText(text: string | undefined, max: number): string | undefined {
+ if (!text) return undefined;
+ const oneLine = text.replace(/\s+/g, ' ').trim();
+ if (!oneLine) return undefined;
+ if (oneLine.length <= max) return oneLine;
+ return `${oneLine.slice(0, max - 1)}…`;
+}
+
+interface ToolCallShape {
+ toolName: string;
+ toolInput: unknown;
+ toolUseId: string | undefined;
+}
+
+/**
+ * 从一条 tool_use 消息里抽 toolName / input / toolUseId。
+ * DB 行(ccAgent.types.Message)形态:content = { toolName, input, toolUseId? }
+ * (legacy 行 toolUseId 存在 content 里,口径 = mapServerMessages);store 侧
+ * ChatMessage 形态是顶层 toolName / toolInput —— 两种形态并存,这里防御兼容,
+ * 避免调用方喂哪一层的消息数组都不至于整表落空。
+ */
+function readToolCall(m: Message): ToolCallShape {
+ const c = isRecord(m.content) ? m.content : undefined;
+ const top = m as unknown as { toolName?: unknown; toolInput?: unknown };
+ const toolName =
+ typeof c?.toolName === 'string'
+ ? c.toolName
+ : typeof top.toolName === 'string'
+ ? top.toolName
+ : '';
+ const toolInput = c && 'input' in c ? c.input : top.toolInput;
+ const toolUseId =
+ (typeof m.toolUseId === 'string' && m.toolUseId.length > 0 ? m.toolUseId : undefined) ??
+ (typeof c?.toolUseId === 'string' && c.toolUseId.length > 0 ? c.toolUseId : undefined);
+ return { toolName, toolInput, toolUseId };
+}
+
+/**
+ * kind 推导:update.taskType 在既知词表内则以它为准;词表外非空值归 'other';
+ * 缺失时按 toolName 回退(Workflow / 后台 Bash / Agent·Task·collab:*);
+ * 孤儿(无 toolName)且无 taskType 时默认 'agent'(典型:codex collab 的
+ * spawning tool-call 尚未送达)。
+ */
+function deriveKind(toolName: string | undefined, update: AgentTaskUpdate | undefined): SessionTaskItem['kind'] {
+ const taskType = update?.taskType;
+ if (taskType) return KNOWN_TASK_TYPE_KIND[taskType] ?? 'other';
+ if (toolName === 'Workflow') return 'workflow';
+ if (toolName === 'Bash') return 'bash';
+ return 'agent';
+}
+
+/**
+ * 标题链(口径 = AgentTaskCard):
+ * - workflow:update.workflowName 优先;
+ * - bash:update.title ?? description ?? command;
+ * - 其余:update.title ?? description/task/name ?? prompt。
+ */
+function deriveTitle(
+ kind: SessionTaskItem['kind'],
+ update: AgentTaskUpdate | undefined,
+ toolInput: unknown,
+): string {
+ if (kind === 'workflow') {
+ return (
+ compactText(
+ update?.workflowName ??
+ update?.title ??
+ readInputString(toolInput, ['description', 'task', 'name']) ??
+ readInputString(toolInput, ['prompt']),
+ TITLE_MAX,
+ ) ?? ''
+ );
+ }
+ if (kind === 'bash') {
+ return (
+ compactText(
+ update?.title ??
+ readInputString(toolInput, ['description']) ??
+ readInputString(toolInput, ['command']),
+ TITLE_MAX,
+ ) ?? ''
+ );
+ }
+ return (
+ compactText(
+ update?.title ??
+ readInputString(toolInput, ['description', 'task', 'name']) ??
+ readInputString(toolInput, ['prompt']),
+ TITLE_MAX,
+ ) ?? ''
+ );
+}
+
+/** 与 findTaskUpdate 同口径:先 toolUseId、后 clientId 查 map。 */
+function findUpdate(
+ taskUpdates: ReadonlyMap<string, AgentTaskUpdate> | undefined,
+ toolUseId: string | undefined,
+ clientId: string,
+): AgentTaskUpdate | undefined {
+ if (!taskUpdates) return undefined;
+ if (toolUseId) {
+ const byToolUseId = taskUpdates.get(toolUseId);
+ if (byToolUseId) return byToolUseId;
+ }
+ return taskUpdates.get(clientId);
+}
+
+/** completed 区排序 key:updatedAt 解析失败/缺失一律视为无时间戳。 */
+function completedTimestamp(item: SessionTaskItem): number | undefined {
+ const iso = item.update?.updatedAt;
+ if (!iso) return undefined;
+ const ms = Date.parse(iso);
+ return Number.isFinite(ms) ? ms : undefined;
+}
+
+/**
+ * completed 区:按 update.updatedAt 倒序;无时间戳的(纯历史条目,update 只存活
+ * 于 live 会话,缺失即更旧)排在有时间戳之后,组内按 orderIndex 倒序。
+ */
+function compareCompleted(a: SessionTaskItem, b: SessionTaskItem): number {
+ const ta = completedTimestamp(a);
+ const tb = completedTimestamp(b);
+ if (ta !== undefined && tb !== undefined) return tb - ta || b.orderIndex - a.orderIndex;
+ if (ta !== undefined) return -1;
+ if (tb !== undefined) return 1;
+ return b.orderIndex - a.orderIndex;
+}
+
+export function listSessionTasks(input: {
+ messages: readonly Message[];
+ taskUpdates: ReadonlyMap<string, AgentTaskUpdate> | undefined;
+ isSessionStreaming: boolean;
+}): SessionTaskLists {
+ const { messages, taskUpdates, isSessionStreaming } = input;
+
+ // Pass 0:tool_result 的 toolUseId 查表(与 buildRenderItems Pass 0 同口径)。
+ const settledToolUseIds = new Set<string>();
+ for (const m of messages) {
+ if (m.role !== 'tool_result') continue;
+ if (typeof m.toolUseId === 'string' && m.toolUseId.length > 0) {
+ settledToolUseIds.add(m.toolUseId);
+ }
+ }
+
+ const items: SessionTaskItem[] = [];
+ // 已上榜任务的全部别名(toolUseId / taskId / parentToolUseId):
+ // 同一任务的重复 toolCall 与孤儿补渲染都要据此去重,一行一个任务。
+ const seenAliasKeys = new Set<string>();
+
+ for (let i = 0; i < messages.length; i++) {
+ const msg = messages[i];
+ if (msg.role !== 'tool_use') continue;
+ const { toolName, toolInput, toolUseId } = readToolCall(msg);
+
+ const isTaskTool = isAgentTaskToolName(toolName);
+ const isWorkflowTool = toolName === 'Workflow';
+ const isBackgroundBash =
+ toolName === 'Bash' && isRecord(toolInput) && toolInput.run_in_background === true;
+ // 其余工具(含前台 Bash)不是后台任务,不进列表。
+ if (!isTaskTool && !isWorkflowTool && !isBackgroundBash) continue;
+
+ const update = findUpdate(taskUpdates, toolUseId, msg.clientId);
+
+ const aliasKeys = [toolUseId, update?.taskId, update?.parentToolUseId].filter(
+ (k): k is string => typeof k === 'string' && k.length > 0,
+ );
+ // 同一任务已出过行(重复 toolCall / 别名撞车)→ 跳过,首行为准。
+ if (aliasKeys.some((k) => seenAliasKeys.has(k))) continue;
+ for (const k of aliasKeys) seenAliasKeys.add(k);
+
+ // tool_result 存在性:toolUseId 查表命中为主路径;adjacency 兜底只认
+ // 自身不带 toolUseId 的紧邻结果行(旧数据形态)—— 带 toolUseId 的结果行
+ // 归属已由查表裁决,不得把别的工具的结果算到本行头上。
+ let settled = toolUseId !== undefined && settledToolUseIds.has(toolUseId);
+ for (let j = i + 1; !settled && j < messages.length && messages[j].role === 'tool_result'; j++) {
+ const resultToolUseId = messages[j].toolUseId;
+ if (typeof resultToolUseId !== 'string' || resultToolUseId.length === 0) settled = true;
+ }
+
+ const kind = deriveKind(toolName, update);
+ const status: AgentTaskStatus = update?.status ?? (settled ? 'completed' : 'running');
+ const provider: SessionTaskItem['provider'] =
+ update?.provider ?? (toolName.startsWith('collab:') ? 'codex' : 'claude-code');
+
+ items.push({
+ key: update?.taskId ?? toolUseId ?? msg.clientId,
+ ...(update?.taskId ? { taskId: update.taskId } : {}),
+ kind,
+ title: deriveTitle(kind, update, toolInput),
+ status,
+ provider,
+ ...(update ? { update } : {}),
+ toolCallClientId: msg.clientId,
+ ...(toolUseId ? { toolUseId } : {}),
+ orderIndex: i,
+ });
+ }
+
+ // 孤儿 update:仅会话运行中列出(LIVE 占位;空闲态是陈旧残留,不复播)。
+ // map 按 taskId + parentToolUseId 多 key 存同一 update,按 taskId 去重。
+ if (isSessionStreaming && taskUpdates) {
+ const seenTaskIds = new Set<string>();
+ let orphanOrder = messages.length;
+ for (const update of taskUpdates.values()) {
+ const primaryKey = update.parentToolUseId ?? update.taskId;
+ if (
+ seenTaskIds.has(update.taskId) ||
+ seenAliasKeys.has(primaryKey) ||
+ seenAliasKeys.has(update.taskId)
+ ) {
+ continue;
+ }
+ seenTaskIds.add(update.taskId);
+ const kind = deriveKind(undefined, update);
+ items.push({
+ key: update.taskId,
+ taskId: update.taskId,
+ kind,
+ title: deriveTitle(kind, update, undefined),
+ status: update.status,
+ provider: update.provider,
+ update,
+ orderIndex: orphanOrder++,
+ });
+ }
+ }
+
+ // 分区:running 按启动(出现)顺序升序;终态(completed/failed/stopped)按
+ // 完成时间倒序 —— 对齐官方 Background tasks 面板的两区排序。
+ const running = items
+ .filter((it) => it.status === 'running')
+ .sort((a, b) => a.orderIndex - b.orderIndex);
+ const completed = items.filter((it) => it.status !== 'running').sort(compareCompleted);
+ return { running, completed };
+}
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.ts
new file mode 100644
index 0000000000..4c4ff3889f
--- /dev/null
+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/workflowProgressModel.ts
@@ -0,0 +1,272 @@
+/**
+ * workflowProgressModel —— workflow 进度双数据源 → 渲染模型的合并层(纯函数)。
+ *
+ * 双源:
+ * - entries:`agent_task_update` 事件流上的 workflowProgress(实时、进程内存,重载后丢失);
+ * - fileProgress:main 侧 wf 记录文件 reader 的结果(重载后仍可读;远程会话 / 老被控端
+ * 降级为 null)。
+ *
+ * 合并约束(本层唯一职责,UI 层不再做任何数据修正):
+ * - entries 在场 → 主结构一律来自 entries,file 只做补缺(logs、phase detail、任务终态
+ * 后缺失的 resultPreview / durationMs / error);
+ * - entries 缺失(重载后)→ 整树退回 fileProgress;
+ * - 两套 state 词表(事件流 start/progress/done/error;文件 queued/running/done/failed/
+ * stopped/killed)一律原样透传,只在任务已终态而 agent 仍呈非终态时置 'error'
+ * (error 文案留空,由 UI 层用 i18n 兜底,本层不写死文案);
+ * - 本层不做 i18n、不做格式化,只输出结构化数据。
+ */
+
+import type { WorkflowProgressEntry } from '@cindy/maker-shared/agent-task';
+
+import type { AgentTaskStatus } from '@/lib/makerChatStore';
+
+import type {
+ WorkflowAgentProgress,
+ WorkflowProgress,
+} from '../../../../../shared/workflow-progress';
+
+export interface WorkflowTreeAgentRow {
+ /** 渲染 key:agentId 优先,缺失时用条目序号兜底(同一次构建内稳定唯一)。 */
+ key: string;
+ label: string;
+ /** 原样透传的运行状态(两套词表任一;终态修正后可能为 'error')。 */
+ state: string;
+ model?: string;
+ attempt?: number;
+ lastToolName?: string;
+ lastToolSummary?: string;
+ resultPreview?: string;
+ durationMs?: number;
+ error?: string;
+}
+
+export interface WorkflowTreeGroup {
+ /** phase 标题;不归属任何 phase 的 agent 收进末尾 title=null 组。 */
+ title: string | null;
+ /** phase 说明(仅 wf 文件有,按 title 回填)。 */
+ detail?: string;
+ agents: WorkflowTreeAgentRow[];
+}
+
+export interface WorkflowTreeModel {
+ aggregate: {
+ agentCount?: number;
+ status: string;
+ totalTokens?: number;
+ totalToolCalls?: number;
+ durationMs?: number;
+ };
+ /** 脚本 log() 叙述行(仅 wf 文件有;无文件时为空数组)。 */
+ logs: string[];
+ groups: WorkflowTreeGroup[];
+}
+
+/** 任务级终态(AgentTaskStatus 词表)。 */
+const TERMINAL_TASK_STATUSES: ReadonlySet<AgentTaskStatus> = new Set([
+ 'completed',
+ 'failed',
+ 'stopped',
+]);
+
+/**
+ * 任务终态后必须修正为 'error' 的 agent state(两套词表里的"仍在进行/等待"状态)。
+ * 终态任务不可能再推进这些行;不修正会永远转圈。
+ */
+const CORRECTABLE_AGENT_STATES: ReadonlySet<string> = new Set([
+ 'start',
+ 'progress',
+ 'running',
+ 'queued',
+]);
+
+/** wf 文件顶层 status 的终态词表:命中时文件结论优先于 taskStatus。 */
+const TERMINAL_FILE_STATUSES: ReadonlySet<string> = new Set([
+ 'completed',
+ 'failed',
+ 'stopped',
+ 'killed',
+ 'done',
+ 'error',
+]);
+
+export function buildWorkflowTreeModel(input: {
+ entries?: readonly WorkflowProgressEntry[];
+ fileProgress?: WorkflowProgress | null;
+ taskStatus: AgentTaskStatus;
+ usage?: { totalTokens?: number; toolUses?: number; durationMs?: number };
+}): WorkflowTreeModel | null {
+ const { entries, fileProgress, taskStatus, usage } = input;
+ const hasEntries = Array.isArray(entries) && entries.length > 0;
+ const file = fileProgress ?? null;
+ // 两源都空 → 没有任何可展示的进度,交给调用方回退到 workflow 级卡片信息。
+ if (!hasEntries && !file) return null;
+
+ const isTerminal = TERMINAL_TASK_STATUSES.has(taskStatus);
+ const groups = hasEntries
+ ? groupsFromEntries(entries, file, isTerminal)
+ : groupsFromFile(file!);
+
+ if (isTerminal) {
+ for (const group of groups) {
+ for (const row of group.agents) {
+ if (CORRECTABLE_AGENT_STATES.has(row.state)) {
+ // error 字段留空:兜底文案由 UI 层 i18n 提供,本层不写死。
+ row.state = 'error';
+ }
+ }
+ }
+ }
+
+ const agentRowCount = groups.reduce((n, g) => n + g.agents.length, 0);
+ const fileStatus = file?.status;
+ return {
+ aggregate: {
+ agentCount: file?.agentCount ?? agentRowCount,
+ // 文件已有终态结论时以文件为准(词表更细,如 killed);否则跟随任务状态。
+ status:
+ fileStatus !== undefined && TERMINAL_FILE_STATUSES.has(fileStatus)
+ ? fileStatus
+ : taskStatus,
+ totalTokens: file?.totalTokens ?? usage?.totalTokens,
+ totalToolCalls: file?.totalToolCalls ?? usage?.toolUses,
+ durationMs: file?.durationMs ?? usage?.durationMs,
+ },
+ logs: file?.logs ?? [],
+ groups,
+ };
+}
+
+/**
+ * entries 主结构:workflow_phase 条目出现顺序定 phase 顺序(同名只保留首个),
+ * workflow_agent 按 phaseTitle 归组;不属于任何 phase 的进末尾 title=null 组。
+ * 分组口径与 WorkflowAgentTree 一致:没有 agent 的 phase 不产出分组。
+ */
+function groupsFromEntries(
+ entries: readonly WorkflowProgressEntry[],
+ file: WorkflowProgress | null,
+ backfillTerminal: boolean,
+): WorkflowTreeGroup[] {
+ const detailByTitle = collectPhaseDetails(file);
+ const byPhase = new Map<string, WorkflowTreeAgentRow[]>();
+ for (const entry of entries) {
+ if (entry.type === 'workflow_phase' && entry.title && !byPhase.has(entry.title)) {
+ byPhase.set(entry.title, []);
+ }
+ }
+ const orphans: WorkflowTreeAgentRow[] = [];
+ let agentOrdinal = 0;
+ for (const entry of entries) {
+ if (entry.type !== 'workflow_agent') continue;
+ const row = rowFromEntry(entry, agentOrdinal);
+ agentOrdinal += 1;
+ // 事件流收尾帧可能缺 resultPreview/durationMs/error(节流或提前断流);任务终态时
+ // 按 label+phaseTitle 从文件回填,撞名取首个;只补缺,绝不覆盖 entries 已有值。
+ if (backfillTerminal && file) backfillRowFromFile(row, entry.phaseTitle, file.agents);
+ if (entry.phaseTitle && byPhase.has(entry.phaseTitle)) {
+ byPhase.get(entry.phaseTitle)!.push(row);
+ } else {
+ orphans.push(row);
+ }
+ }
+ return assembleGroups(byPhase, orphans, detailByTitle);
+}
+
+/** entries 缺失(重载后)整树退回 wf 文件;文件 state 词表原样保留。 */
+function groupsFromFile(file: WorkflowProgress): WorkflowTreeGroup[] {
+ const detailByTitle = collectPhaseDetails(file);
+ const byPhase = new Map<string, WorkflowTreeAgentRow[]>();
+ for (const phase of file.phases) {
+ if (!byPhase.has(phase.title)) byPhase.set(phase.title, []);
+ }
+ const orphans: WorkflowTreeAgentRow[] = [];
+ file.agents.forEach((agent, index) => {
+ const row = rowFromFileAgent(agent, index);
+ if (agent.phaseTitle && byPhase.has(agent.phaseTitle)) {
+ byPhase.get(agent.phaseTitle)!.push(row);
+ } else {
+ orphans.push(row);
+ }
+ });
+ return assembleGroups(byPhase, orphans, detailByTitle);
+}
+
+/** phase detail 只存在于 wf 文件顶层 phases[],按 title 建索引(同名取首个)。 */
+function collectPhaseDetails(file: WorkflowProgress | null): Map<string, string> {
+ const detailByTitle = new Map<string, string>();
+ if (!file) return detailByTitle;
+ for (const phase of file.phases) {
+ if (phase.detail && !detailByTitle.has(phase.title)) {
+ detailByTitle.set(phase.title, phase.detail);
+ }
+ }
+ return detailByTitle;
+}
+
+function assembleGroups(
+ byPhase: ReadonlyMap<string, WorkflowTreeAgentRow[]>,
+ orphans: WorkflowTreeAgentRow[],
+ detailByTitle: ReadonlyMap<string, string>,
+): WorkflowTreeGroup[] {
+ const out: WorkflowTreeGroup[] = [];
+ for (const [title, agents] of byPhase) {
+ if (agents.length === 0) continue;
+ const detail = detailByTitle.get(title);
+ out.push({ title, ...(detail !== undefined ? { detail } : {}), agents });
+ }
+ if (orphans.length > 0) out.push({ title: null, agents: orphans });
+ return out;
+}
+
+/**
+ * 事件条目 → agent 行。字段直接取条目;durationMs 事件流不携带,只能靠终态回填。
+ * state 缺失按 'queued' 处理(条目尚未开跑时事件可能不带 state)。
+ */
+function rowFromEntry(entry: WorkflowProgressEntry, ordinal: number): WorkflowTreeAgentRow {
+ return {
+ key: entry.agentId ?? `entry-${ordinal}`,
+ label: entry.label ?? entry.agentId ?? `#${entry.index}`,
+ state: entry.state ?? 'queued',
+ ...(entry.model !== undefined ? { model: entry.model } : {}),
+ ...(entry.attempt !== undefined ? { attempt: entry.attempt } : {}),
+ ...(entry.lastToolName !== undefined ? { lastToolName: entry.lastToolName } : {}),
+ ...(entry.lastToolSummary !== undefined ? { lastToolSummary: entry.lastToolSummary } : {}),
+ ...(entry.resultPreview !== undefined ? { resultPreview: entry.resultPreview } : {}),
+ ...(entry.error !== undefined ? { error: entry.error } : {}),
+ };
+}
+
+function rowFromFileAgent(agent: WorkflowAgentProgress, index: number): WorkflowTreeAgentRow {
+ return {
+ key: agent.agentId || `file-${index}`,
+ label: agent.label,
+ state: agent.state,
+ ...(agent.model !== undefined ? { model: agent.model } : {}),
+ ...(agent.attempt !== undefined ? { attempt: agent.attempt } : {}),
+ ...(agent.lastToolName !== undefined ? { lastToolName: agent.lastToolName } : {}),
+ ...(agent.lastToolSummary !== undefined ? { lastToolSummary: agent.lastToolSummary } : {}),
+ ...(agent.resultPreview !== undefined ? { resultPreview: agent.resultPreview } : {}),
+ ...(agent.durationMs !== undefined ? { durationMs: agent.durationMs } : {}),
+ ...(agent.error !== undefined ? { error: agent.error } : {}),
+ };
+}
+
+/** 终态补缺:按 label+phaseTitle 匹配文件 agent(撞名取首个),只填 entries 缺失的字段。 */
+function backfillRowFromFile(
+ row: WorkflowTreeAgentRow,
+ phaseTitle: string | undefined,
+ fileAgents: readonly WorkflowAgentProgress[],
+): void {
+ const match = fileAgents.find(
+ (agent) => agent.label === row.label && agent.phaseTitle === phaseTitle,
+ );
+ if (!match) return;
+ if (row.resultPreview === undefined && match.resultPreview !== undefined) {
+ row.resultPreview = match.resultPreview;
+ }
+ if (row.durationMs === undefined && match.durationMs !== undefined) {
+ row.durationMs = match.durationMs;
+ }
+ if (row.error === undefined && match.error !== undefined) {
+ row.error = match.error;
+ }
+}
diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/index.ts b/apps/desktop/src/renderer/features/right-sidebar/plugins/index.ts
index 56789fcd80..da4294954b 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/plugins/index.ts
+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/index.ts
@@ -14,3 +14,4 @@ import './web-browser';
import './terminal';
import './review';
import './orca-workers';
+import './background-tasks';
diff --git a/apps/desktop/src/renderer/features/right-sidebar/types.ts b/apps/desktop/src/renderer/features/right-sidebar/types.ts
index 76bff8a127..8af1684d48 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/types.ts
+++ b/apps/desktop/src/renderer/features/right-sidebar/types.ts
@@ -20,7 +20,13 @@ import type { TabCloseInterceptor } from './store';
* renderer/cindy-brain/ghostTabPlugins.tsx 随已装清单动态注册/注销
* (字符串与顶层布局的 ghostPanelKind 同形,DB kind 列无枚举约束可直存)。
*/
-export type BuiltinTabKindId = 'file-browser' | 'web-browser' | 'terminal' | 'review' | 'orca-workers';
+export type BuiltinTabKindId =
+ | 'file-browser'
+ | 'web-browser'
+ | 'terminal'
+ | 'review'
+ | 'orca-workers'
+ | 'background-tasks';
export type TabKindId = BuiltinTabKindId | `ghost:${string}`;
/** 一个 tab 运行时实例。`state` 由各 plugin 自管理结构 + 序列化,壳子只搬运。 */
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index e437c219ac..ed89d4f2d4 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -3242,6 +3242,7 @@
"browser": "Browser",
"terminal": "Terminal",
"review": "Review",
+ "backgroundTasks": "Background tasks",
"collaboration": "Team",
"unknown": "Unknown tab",
"ghostPanel": "Plugin panel"
@@ -3626,6 +3627,16 @@
"touchCountAria_other": "Edited {{count}} times",
"expandAllAria": "Expand all files",
"collapseAllAria": "Collapse all files"
+ },
+ "backgroundTasks": {
+ "running": "Running",
+ "completed": "Completed",
+ "empty": "No background tasks in this session yet",
+ "stop": "Stop",
+ "back": "Back",
+ "progressSummary": "{{done}}/{{total}} agents",
+ "tokens": "{{value}} tokens",
+ "noProgress": "No progress details yet"
}
},
"update": {
@@ -4891,13 +4902,19 @@
"workflowTree": {
"agentsCount": "{{count}} agents",
"attempt": "attempt {{count}}",
+ "endedEarly": "Ended before completion",
"state": {
"queued": "Queued",
+ "pending": "Pending",
+ "start": "Starting",
"running": "Running",
+ "progress": "Running",
"done": "Done",
"completed": "Completed",
"failed": "Failed",
- "stopped": "Stopped"
+ "error": "Failed",
+ "stopped": "Stopped",
+ "killed": "Killed"
}
},
"credentialSwitchWait": {
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index e956a3079e..fef0c2e286 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -3241,6 +3241,7 @@
"browser": "ブラウザ",
"terminal": "ターミナル",
"review": "レビュー",
+ "backgroundTasks": "バックグラウンドタスク",
"collaboration": "コラボ",
"unknown": "不明なタブ",
"ghostPanel": "プラグインパネル"
@@ -3625,6 +3626,16 @@
"touchCountAria_other": "{{count}} 回編集",
"expandAllAria": "すべてのファイルを展開",
"collapseAllAria": "すべてのファイルを折りたたむ"
+ },
+ "backgroundTasks": {
+ "running": "実行中",
+ "completed": "完了",
+ "empty": "このセッションにバックグラウンドタスクはまだありません",
+ "stop": "停止",
+ "back": "戻る",
+ "progressSummary": "{{done}}/{{total}} Agent",
+ "tokens": "{{value}} tokens",
+ "noProgress": "進行状況の詳細はまだありません"
}
},
"update": {
@@ -4881,13 +4892,19 @@
"workflowTree": {
"agentsCount": "{{count}} 個のエージェント",
"attempt": "{{count}} 回目",
+ "endedEarly": "完了前に終了",
"state": {
"queued": "待機中",
+ "pending": "待機中",
+ "start": "開始中",
"running": "実行中",
+ "progress": "実行中",
"done": "完了",
"completed": "完了",
"failed": "失敗",
- "stopped": "停止"
+ "error": "失敗",
+ "stopped": "停止",
+ "killed": "強制終了"
}
},
"credentialSwitchWait": {
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 02903573b7..ddb268359b 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -3241,6 +3241,7 @@
"browser": "브라우저",
"terminal": "터미널",
"review": "리뷰",
+ "backgroundTasks": "백그라운드 작업",
"collaboration": "협업",
"unknown": "알 수 없는 탭",
"ghostPanel": "플러그인 패널"
@@ -3625,6 +3626,16 @@
"touchCountAria_other": "{{count}}회 편집됨",
"expandAllAria": "모든 파일 펼치기",
"collapseAllAria": "모든 파일 접기"
+ },
+ "backgroundTasks": {
+ "running": "실행 중",
+ "completed": "완료",
+ "empty": "이 세션에는 아직 백그라운드 작업이 없습니다",
+ "stop": "중지",
+ "back": "뒤로",
+ "progressSummary": "{{done}}/{{total}} Agent",
+ "tokens": "{{value}} tokens",
+ "noProgress": "진행 상황 정보가 아직 없습니다"
}
},
"update": {
@@ -4881,13 +4892,19 @@
"workflowTree": {
"agentsCount": "에이전트 {{count}}개",
"attempt": "{{count}}번째 시도",
+ "endedEarly": "완료 전에 종료됨",
"state": {
"queued": "대기 중",
+ "pending": "대기 중",
+ "start": "시작 중",
"running": "실행 중",
+ "progress": "실행 중",
"done": "완료",
"completed": "완료",
"failed": "실패",
- "stopped": "중지됨"
+ "error": "실패",
+ "stopped": "중지됨",
+ "killed": "강제 종료됨"
}
},
"credentialSwitchWait": {
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index 92c9ff0c91..e7203f33a1 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -3241,6 +3241,7 @@
"browser": "浏览器",
"terminal": "终端",
"review": "审查",
+ "backgroundTasks": "后台任务",
"collaboration": "协同",
"unknown": "未知标签页",
"ghostPanel": "插件面板"
@@ -3625,6 +3626,16 @@
"touchCountAria_other": "已修改 {{count}} 次",
"expandAllAria": "展开所有文件",
"collapseAllAria": "收起所有文件"
+ },
+ "backgroundTasks": {
+ "running": "运行中",
+ "completed": "已完成",
+ "empty": "本对话暂无后台任务",
+ "stop": "停止",
+ "back": "返回",
+ "progressSummary": "{{done}}/{{total}} Agent",
+ "tokens": "{{value}} tokens",
+ "noProgress": "暂无进度详情"
}
},
"update": {
@@ -4881,13 +4892,19 @@
"workflowTree": {
"agentsCount": "{{count}} 个 Agent",
"attempt": "第 {{count}} 次尝试",
+ "endedEarly": "未完成即结束",
"state": {
"queued": "排队中",
+ "pending": "排队中",
+ "start": "启动中",
"running": "运行中",
+ "progress": "运行中",
"done": "完成",
"completed": "完成",
"failed": "失败",
- "stopped": "已停止"
+ "error": "失败",
+ "stopped": "已停止",
+ "killed": "已终止"
}
},
"credentialSwitchWait": {
@@ -7264,7 +7281,6 @@
"cancelFailed": "取消订阅失败,请稍后重试。"
},
"topupCard": {
-
"action": "购买点数"
}
},