import { useEffect, useState } from 'react'; import type { AgentTaskState } from '../../tools/agent/agentTaskService.js'; import type { ToolStatusState } from '../../types.js'; import { activityText } from '../activityPresentation.js'; export function backgroundAgentRows(state?: AgentTaskState): ToolStatusState[] { return [...(state?.tasks.values() ?? [])] .filter(task => task.status === 'running' && task.background === true) .map(task => ({ toolName: 'Agent', status: 'running' as const, argsPreview: '', argsFriendly: activityText(task.description, '后台子任务'), progress: activityText(task.progress, '正在启动,尚未报告具体动作'), })); } /** Read the registry's existing progress, without a second task ledger. * Bounded refresh discovers newly added tasks without attaching N listeners. */ export function useBackgroundAgents(binding: { key: string; state: AgentTaskState } | null, key: string) { const [snapshot, setSnapshot] = useState<{ key: string; rows: ToolStatusState[] }>({ key, rows: [] }); useEffect(() => { let previous = ''; const refresh = () => { const rows = binding?.key === key ? backgroundAgentRows(binding.state) : []; const signature = JSON.stringify(rows); if (signature !== previous) { previous = signature; setSnapshot({ key, rows }); } }; refresh(); if (!binding || binding.key !== key) return; const timer = setInterval(refresh, 500); return () => clearInterval(timer); }, [binding, key]); return snapshot.key === key ? snapshot.rows : []; }