import { formatIdReference } from '../../helpers/safeDisplay'; import { formatPercent } from '../../helpers/safeDisplay'; import { Trans } from 'react-i18next'; import { I18N_TECHNICAL_TEXT } from '../../i18n/technicalText.js'; import { Bot as ActionBot, ArrowRight as ActionArrowRight, ArrowLeft as ActionArrowLeft, CheckCircle2 as ActionCheckCircle2, FileUp as ActionFileUp, X as ActionX, Send as ActionSend, RotateCcw as ActionRotateCcw, Copy as ActionCopy, ThumbsUp as ActionThumbsUp, ThumbsDown as ActionThumbsDown, Download as ActionDownload, } from '@/components/common/icons/ActionIcons'; import React, { useCallback, useEffect, useMemo, useRef, useState, } from 'react'; import { useTranslation } from 'react-i18next'; import { Button, Empty, InputNumber, Modal, Popconfirm, Select, Spin, Switch, Tag, TextArea, } from '@/components/ui'; import { Bot, BriefcaseBusiness, BookOpenCheck, CheckCircle2, CircleDashed, Clock3, FileText, ListChecks, MessageSquareMore, Sparkles, Square, TriangleAlert, } from 'lucide-react'; import ReactMarkdown from 'react-markdown'; import remarkGfm from 'remark-gfm'; import { SSE } from 'sse.js'; import { API } from '../../helpers/api'; import { getServerURL } from '../../helpers/config'; import { copy, showError, showSuccess, getUserIdFromLocalStorage, } from '../../helpers'; import { usePageGuide, PageGuideDrawer, PageGuidePill, PageGuideTrigger, } from '../../components/common/PageGuide'; import { Tabs } from 'antd'; import ExperiencePageHeader from '../ExperienceCenter/components/ExperiencePageHeader'; import './cloud-brain.css'; // Must match GetCloudBrainRun's per-request event limit; the timeline pages // with `events_after` only when a full page comes back. const EVENT_PAGE_SIZE = 200; // Bound the catch-up so a pathological run cannot fan out unboundedly. const MAX_EXTRA_EVENT_PAGES = 5; const terminalStatuses = new Set([ 'succeeded', 'completed_with_warnings', 'failed', 'cancelled', 'stopped', ]); const statusMeta = { queued: { icon: Clock3, tone: 'amber', label: '等待执行' }, running: { icon: CircleDashed, tone: 'blue', label: '正在生成' }, waiting_confirmation: { icon: Clock3, tone: 'amber', label: '等待操作确认' }, succeeded: { icon: CheckCircle2, tone: 'green', label: '已完成' }, completed_with_warnings: { icon: TriangleAlert, tone: 'amber', label: '完成但有提醒', }, failed: { icon: TriangleAlert, tone: 'red', label: '执行失败' }, cancelled: { icon: Square, tone: 'grey', label: '已取消' }, stopped: { icon: Square, tone: 'grey', label: '已停止' }, }; const safeDate = (timestamp, locale) => { if (!timestamp) return '—'; return new Intl.DateTimeFormat(locale || undefined, { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit', }).format(new Date(timestamp * 1000)); }; const stableRequestKey = (holder, fingerprint) => { if (holder.current?.fingerprint === fingerprint) return holder.current.key; const key = globalThis.crypto?.randomUUID?.() || `${Date.now()}-${Math.random().toString(16).slice(2)}`; holder.current = { fingerprint, key }; return key; }; const StatusPill = ({ status }) => { const { t } = useTranslation(); const meta = statusMeta[status] || statusMeta.queued; const Icon = meta.icon; return ( {t(meta.label)} ); }; const BetaBadge = () => ( {I18N_TECHNICAL_TEXT.BETA} ); const expertPresentation = { 'management-report': { icon: BriefcaseBusiness, tone: 'is-sage' }, 'sales-proposal': { icon: FileText, tone: 'is-coral' }, 'operations-analysis': { icon: ListChecks, tone: 'is-sage' }, 'meeting-action': { icon: MessageSquareMore, tone: 'is-coral' }, 'project-review': { icon: CheckCircle2, tone: 'is-sage' }, 'customer-discovery': { icon: Bot, tone: 'is-coral' }, 'launch-readiness': { icon: Sparkles, tone: 'is-sage' }, }; const runErrorMessages = { invalid_snapshot: '任务配置不可用,请重新创建任务。', gateway_rejected: '任务执行策略已变化,本次任务未调用模型。', upstream_failed: '模型服务暂时未能完成任务,请稍后重试。', invalid_upstream_response: '模型已返回结果,但结果格式无法生成产物。', worker_lost_after_dispatch: '执行节点中断,账务正在安全核对。', upstream_result_unknown: '模型调用结果未知,账务正在安全核对。', gateway_unreachable: '执行服务暂时不可达,本次预留额度已退回。', response_lost_usage_settled: '模型用量已完成核对,但响应内容无法恢复。', reservation_adjustment_failed: '模型用量已确认,追加预留失败,账务正在安全核对。', known_usage_settlement_failed: '模型用量已确认,结算未完成,账务正在安全核对。', cancelled: '任务已按请求取消。', output_contract_warning: '任务已完成,但产物未完全满足输出契约,请人工复核。', // 契约修复后仍有严重告警时任务直接失败;缺少这条映射会把后端拼接的英文 // 告警列表原样显示给用户。 output_contract_failed: '产物未通过输出契约校验,任务已停止,请补充关键信息后重新提交。', confirmation_timeout: '工具操作确认已超时,任务按已发生用量结算。', connector_execution_failed: '业务系统调用失败,请查看工具轨迹了解详情。', connector_resume_failed: '确认后任务恢复失败,账务正在安全核对。', tool_validation_failed: '工具参数校验未通过,任务未执行该操作。', tool_not_authorized: '当前成员没有该业务系统操作的授权。', tool_confirmation_batch_rejected: '等待确认的操作已被批量拒绝。', // 采样参数重试没能开出新一次调用(拿不到租约、并发改写等)。缺这条映射会把 // 后端的英文内部错误原样念给成员听。 sampling_retry_prepare_failed: '任务重试未能启动,请稍后重试。', }; // error_code 的映射文案只能说"失败了",真正的原因藏在 error_message 里—— // upstream_failed 的 error_message 是网关回传的响应体(OpenAI 风格 // {"error":{"message":...}}),无可用渠道 / 额度不足 / 模型不存在在页面上长得 // 一模一样。这里把响应体里的 message 抽出来,作为"失败原因"单独显示一行。 const extractGatewayReason = (raw) => { const text = String(raw || '').trim(); if (!text) return ''; const first = text[0]; if (first !== '{' && first !== '[' && first !== '"') return text; try { const parsed = JSON.parse(text); // 网关对非 JSON 的上游响应(代理的 HTML 错误页、纯文本 502)会做一次 // json.Marshal(string(...)),这里把那层引号剥掉再显示。 if (typeof parsed === 'string') return parsed.trim(); const node = parsed?.error ?? parsed; if (typeof node === 'string') return node.trim(); // 响应体是 JSON 但没有可读的 message(例如上游只回了个空 completion): // 把整段 JSON 当"失败原因"念给用户听毫无意义,交给折叠的技术详情即可。 return String(node?.message || node?.error || '').trim(); } catch { // 非 JSON 的网关错误(代理返回的纯文本、Go error 字符串)原样保留。 return text; } }; // 上游原文常常是英文(provider 直接回传),命中已知形态时换成可执行的中文说明, // 原文仍保留在"技术详情"里,便于管理员排查。 const gatewayReasonHints = [ [ /无可用渠道|no available channel|no channel/i, '该模型当前没有可用渠道,请联系管理员检查渠道配置。', ], [ /额度|quota|insufficient[_ ]?(balance|credit|quota)|欠费/i, '账户或密钥额度不足,请充值后重试。', ], [ /rate.?limit|too many requests|429|请求过于频繁/i, '上游模型限流,请稍后重试。', ], [ /timeout|timed out|deadline exceeded|超时/i, '上游模型响应超时,请稍后重试或改用更小的输入。', ], [ /unauthorized|invalid[_ ]?api[_ ]?key|authentication|401|鉴权/i, '渠道鉴权失败,请联系管理员检查渠道密钥。', ], [ /model.*(not found|does not exist|not exist)|不存在该模型|无效的模型/i, '该模型在网关上不可用,请联系管理员确认模型配置。', ], [ /context length|maximum context|too long|token.*exceed/i, '输入内容超出模型上下文长度,请精简任务描述或附件。', ], ]; // 只有这些码的 error_message 才是网关/上游回传的失败原因,值得直接摊开显示; // 其余码(如 output_contract_failed)的 error_message 是后端拼接的英文内部文本, // 仍然只进折叠的技术详情,避免原样糊到终端用户脸上。 const gatewayReasonCodes = new Set([ 'upstream_failed', 'gateway_rejected', 'invalid_upstream_response', 'connector_execution_failed', ]); // reason 是给用户看的一句话;raw 是原始响应体,只在与 reason 不同时才值得折叠 // 展示(否则技术详情里是同一句话)。中文化 hint 只对网关/上游回传的原文生效—— // 内部 Go 错误里的 "timeout" 之类字样含义完全不同,套上游文案会指错方向。 const describeRunFailure = (code, message) => { const raw = String(message || '').trim(); if (!raw) return { reason: '', raw: '' }; const detail = extractGatewayReason(raw); // 抽不出可读原因时原文仍要留给技术详情——排查要的就是这段。 if (!detail) return { reason: '', raw }; const gatewayOrigin = gatewayReasonCodes.has(code); const hint = gatewayOrigin ? gatewayReasonHints.find(([pattern]) => pattern.test(detail)) : null; // 未映射的错误码沿用旧行为:主文案本来就是原文,这里照样交出去。 const reason = (hint && hint[1]) || (gatewayOrigin || !runErrorMessages[code] ? detail : ''); return { reason, raw: raw === reason ? '' : raw }; }; // 步骤状态直接来自 agent_steps.status,取值见 service/cloud_brain_steps.go: // running / succeeded / failed / cancelled / pending_reconciliation / // ambiguous_upstream_result(后两个是账务待核对,不是"跑挂了")。 const stepStatusMeta = { running: { label: '进行中', tone: 'running' }, succeeded: { label: '已完成', tone: 'succeeded' }, failed: { label: '失败', tone: 'failed' }, cancelled: { label: '已取消', tone: 'cancelled' }, pending_reconciliation: { label: '账务核对中', tone: 'pending' }, ambiguous_upstream_result: { label: '结果待核对', tone: 'pending' }, }; const formatDurationSeconds = (seconds) => { if (!Number.isFinite(seconds) || seconds < 0) return ''; if (seconds < 60) return `${seconds}s`; const minutes = Math.floor(seconds / 60); const rest = seconds % 60; if (minutes < 60) return rest ? `${minutes}m ${rest}s` : `${minutes}m`; const hours = Math.floor(minutes / 60); return minutes % 60 ? `${hours}h ${minutes % 60}m` : `${hours}h`; }; const formatTokenCount = (count) => { if (!Number.isFinite(count) || count <= 0) return ''; return count >= 1000 ? `${(count / 1000).toFixed(1)}k` : String(count); }; // 秒级时间戳下"起止同秒"很常见(步骤秒开秒挂、排队→开始→失败落在同一秒), // 显示 0s 会读成"没花时间",统一显示 <1s。 const elapsedText = (from, to) => { if (!from || !to) return ''; const seconds = to - from; if (seconds < 0) return ''; return seconds === 0 ? '<1s' : formatDurationSeconds(seconds); }; const stepDurationText = (step) => elapsedText(step?.started_at, step?.finished_at); const stepTokenText = (step) => { const total = Number(step?.prompt_tokens || 0) + Number(step?.completion_tokens || 0); const formatted = formatTokenCount(total); return formatted ? `${formatted} tokens` : ''; }; // 时间线原来只有事件名,真正能定位问题的信息全在 payload 里(降级到了哪个模型、 // 命中几条知识、跑到第几步)。白名单式格式化:只渲染确定有意义且确定能给终端用户 // 看的字段——额度金额一律不进时间线(本页对成员从不展示费用数字),工具确认的 // parameters 也不展开(冻结的业务参数在确认卡里另有受控入口)。未登记的事件类型 // 保持只显示事件名,不会把内部 JSON 糊到页面上。 const eventPayloadSummaries = { 'step.queued': (payload, t) => payload.step_seq ? t('第 {{seq}} 步', { seq: payload.step_seq }) : '', 'step.completed': (payload, t) => payload.step_seq ? t('第 {{seq}} 步', { seq: payload.step_seq }) : '', 'tool.round.completed': (payload, t) => payload.step_seq ? t('第 {{seq}} 步', { seq: payload.step_seq }) : '', 'model.fallback': (payload, t) => { if (!payload.from_model || !payload.to_model) return ''; const switched = `${payload.from_model} → ${payload.to_model}`; // 降级原因就是网关回传的上游报错,复用失败原因的中文化逻辑。 const cause = describeRunFailure('upstream_failed', payload.reason).reason; return cause ? `${switched} · ${t(cause)}` : switched; }, // 上游拒收我们硬编码的采样参数后,云脑会原模型去掉该参数重试一次。这条事件 // 说明"任务没挂、只是换了个请求形态",上游英文原文仍留给管理员的技术详情。 'model.sampling_retry': (payload, t) => payload.model ? t('{{model}} · 不接受 {{parameter}} 参数', { model: payload.model, parameter: payload.parameter || 'temperature', }) : '', 'knowledge.retrieved': (payload, t) => { const hits = Number(payload.citation_count || 0); const filtered = Number(payload.injection_filtered_count || 0); const parts = [t('命中 {{count}} 条知识', { count: hits })]; if (filtered > 0) parts.push(t('过滤 {{count}} 条可疑内容', { count: filtered })); return parts.join(' · '); }, 'output.snapshot': (payload, t) => Number(payload.characters || 0) > 0 ? t('已生成 {{count}} 字', { count: Number(payload.characters) }) : '', 'run.failed': (payload, t) => { const contractErrors = Array.isArray(payload.contract_errors) ? payload.contract_errors.length : 0; if (contractErrors > 0) return t('输出契约未通过 · {{count}} 项', { count: contractErrors }); return payload.error_code ? t(runErrorMessages[payload.error_code] || payload.error_code) : ''; }, 'run.completed_with_warnings': (payload, t) => { const warnings = Array.isArray(payload.contract_warnings) ? payload.contract_warnings.length : 0; return warnings > 0 ? t('输出提醒 {{count}} 项', { count: warnings }) : ''; }, 'run.cancelled': (payload, t) => { const reasons = { confirmation_timeout: '操作确认超时', waiting_confirmation_cancelled: '等待确认期间被取消', }; return reasons[payload.reason] ? t(reasons[payload.reason]) : ''; }, 'tool.confirmation.required': (payload) => payload.method || '', 'tool.confirmation.decided': (payload, t) => payload.approved ? t('已确认') : t('已拒绝'), }; const summarizeRunEvent = (event, t) => { const summarize = eventPayloadSummaries[event?.event_type]; if (!summarize) return ''; let payload = null; try { payload = JSON.parse(event.payload || '{}'); } catch { return ''; } if (!payload || typeof payload !== 'object') return ''; const text = summarize(payload, t); return typeof text === 'string' ? text.trim() : ''; }; // 附件的 error_message 是 truncateBrainError(err.Error())——原始 Go 错误文本 // (如 "attachment extracted text exceeds the configured limit"),直接抛给 // showError 就会原样显示给终端用户。按 error_code 映射中文,码来自 // service/agent_attachment.go 的 finalize 分支。 const attachmentErrorMessages = { attachment_security_rejected: '附件未通过安全扫描,已被隔离,请更换文件。', scan_unavailable: '安全扫描服务暂时不可用,附件未入库,请稍后重试。', attachment_parse_failed: '附件解析失败,请确认文件未损坏后重新上传。', }; const CloudBrain = ({ organization = false, orgId = 0, canManage = false }) => { const { t, i18n } = useTranslation(); // 与 SkillMarket / SkillPlatform 同向兜底:数据层只有 zh/en 两套, // 非中文界面(en/ko/th/...)一律取 en——对韩泰用户英文远比中文可用。 const language = i18n.language?.startsWith('zh') ? 'zh' : 'en'; const basePath = organization ? '/api/org/brain' : '/api/brain'; const headers = useMemo( () => (organization ? { 'X-Org-Id': String(orgId) } : {}), [organization, orgId], ); const [view, setView] = useState('experts'); const [experts, setExperts] = useState([]); const [runs, setRuns] = useState([]); const [selectedExpert, setSelectedExpert] = useState(null); const [selectedRunId, setSelectedRunId] = useState(''); const runDetailRef = useRef(null); // 窄屏下主从是上下堆叠、且任务列表被限高 310px,详情整个在折叠线以下: // 点任务只会改变一个看不见的区域,观感是「点了没反应」。选中后主动滚过去。 const selectRunAndReveal = useCallback((runId) => { setSelectedRunId(runId); if (typeof window === 'undefined') return; if (!window.matchMedia('(max-width: 1024px)').matches) return; requestAnimationFrame(() => { runDetailRef.current?.scrollIntoView({ behavior: 'smooth', block: 'start', }); }); }, []); const [runDetail, setRunDetail] = useState(null); const [input, setInput] = useState(''); const [loading, setLoading] = useState(true); const [detailLoading, setDetailLoading] = useState(false); const [submitting, setSubmitting] = useState(false); const [feedback, setFeedback] = useState(null); const [timeConfirmOpen, setTimeConfirmOpen] = useState(false); const [timeConfirmation, setTimeConfirmation] = useState({ confirmed_manual_minutes: 30, actual_minutes: 1, comment: '', }); const [revisionOpen, setRevisionOpen] = useState(false); const [revisionInstruction, setRevisionInstruction] = useState(''); const [revising, setRevising] = useState(false); const [confirmationReason, setConfirmationReason] = useState(''); const [confirmationBusy, setConfirmationBusy] = useState(false); const [manageOpen, setManageOpen] = useState(false); const [assignments, setAssignments] = useState([]); const [expertCatalog, setExpertCatalog] = useState([]); const [metrics, setMetrics] = useState(null); const [projects, setProjects] = useState([]); const [departments, setDepartments] = useState([]); const [members, setMembers] = useState([]); const [projectId, setProjectId] = useState(0); const [attachments, setAttachments] = useState([]); // 个人技能勾选(方案 §2.3 使用面 B)。仅个人云脑有:企业侧的技能由分发规则 // 与锁定策略在后端解析,不经前端勾选,这里刻意不动企业链路。 const [personalSkills, setPersonalSkills] = useState([]); const [manualSkillIds, setManualSkillIds] = useState([]); useEffect(() => { if (organization) { setPersonalSkills([]); setManualSkillIds([]); return; } let cancelled = false; const loadPersonalSkills = async () => { try { const response = await API.get('/api/user/skills/mine'); if (cancelled || !response.data?.success) return; // 只有仍然可用(已发布且未紧急停用)且被启用的技能才进勾选器; // 失效项留在技能超市里让用户清理,不在提交页制造困惑。 setPersonalSkills( (response.data.data || []).filter( (item) => item.enabled && item.available, ), ); } catch (_error) { if (!cancelled) setPersonalSkills([]); } }; void loadPersonalSkills(); return () => { cancelled = true; }; }, [organization]); const [attachmentBusy, setAttachmentBusy] = useState(false); const attachmentInputRef = useRef(null); const [assignmentScope, setAssignmentScope] = useState('organization'); const [assignmentScopeId, setAssignmentScopeId] = useState(0); const [streamState, setStreamState] = useState('idle'); const streamRef = useRef(null); const expertsSeqRef = useRef(0); const runsSeqRef = useRef(0); const assignmentsSeqRef = useRef(0); const contextSeqRef = useRef(0); const detailSeqRef = useRef(0); const detailVisibleSeqRef = useRef(0); // Opening an already-finished run makes the SSE stream replay its whole // history in 200-event batches, and every batch triggers a quiet refresh. // Without this marker each of those refreshes would redo the catch-up paging, // multiplying one user action into dozens of full detail reads. Visible loads // (the user actually opened the run) always page; quiet ones only once per run. const pagedQuietRunRef = useRef(''); const createRequestRef = useRef(null); const revisionRequestRef = useRef(null); const contextIdentity = `${organization ? 'organization' : 'personal'}:${orgId}`; const contextIdentityRef = useRef(contextIdentity); contextIdentityRef.current = contextIdentity; // Write-callback fence: async completions must not repaint the detail panel // when the user has already selected another run. const selectedRunIdRef = useRef(selectedRunId); selectedRunIdRef.current = selectedRunId; useEffect(() => { expertsSeqRef.current += 1; runsSeqRef.current += 1; assignmentsSeqRef.current += 1; contextSeqRef.current += 1; detailSeqRef.current += 1; detailVisibleSeqRef.current += 1; createRequestRef.current = null; revisionRequestRef.current = null; pagedQuietRunRef.current = ''; setExperts([]); setRuns([]); setAssignments([]); setExpertCatalog([]); setMetrics(null); setProjects([]); setDepartments([]); setMembers([]); setSelectedRunId(''); setRunDetail(null); setSubmitting(false); setRevising(false); setFeedback(null); setRevisionOpen(false); setRevisionInstruction(''); setConfirmationReason(''); setConfirmationBusy(false); // Tenant-scoped editor and governance state must not survive an // organization switch: a stale expert/project would submit against the // previous tenant and fail with a confusing policy error. setSelectedExpert(null); setInput(''); setProjectId(0); setAttachments([]); setAttachmentBusy(false); setAssignmentScope('organization'); setAssignmentScopeId(0); setManageOpen(false); setView('experts'); }, [orgId, organization]); const localizedRequestError = useCallback( (error) => { const code = error?.response?.data?.code; const known = { insufficient_quota: '可用额度不足,请补充额度后重试。', active_run_limit: '同时执行的任务较多,请等待已有任务完成。', idempotency_key_invalid: '请求标识无效,请刷新页面后重试。', idempotency_key_conflict: '同一请求标识对应了不同内容(例如个人技能集已变更),请刷新后重试。', revision_conflict: '该任务已有更新的修订版本,请刷新任务列表后继续。', cancel_failed: '任务状态已变化,取消未生效,请刷新后重试。', run_not_found: '任务不存在或已不可见,请刷新任务列表。', run_create_failed: '任务暂时无法创建,请检查专家与模型权限。', revision_create_failed: '修订任务暂时无法创建,请稍后重试。', scope_invalid: '所选范围不可用,请刷新后重新选择。', invalid_assignment: '分发配置无效,请刷新后重试。', expert_unavailable: '该专家暂不可用,请刷新专家列表。', assignment_failed: '分发保存失败,请稍后重试。', feedback_not_ready: '任务完成后才能提交反馈。', tool_confirmation_failed: '确认未生效:授权、凭据或操作内容已变化,请刷新任务后重试。', time_confirmation_invalid: '耗时数值无效,请检查后重新提交。', time_confirmation_rejected: '仅本人已完成的任务可提交耗时抽样。', }; return known[code] ? t(known[code]) : error?.response?.data?.message || error?.message || String(error); }, [t], ); const loadExperts = useCallback(async () => { const seq = ++expertsSeqRef.current; const identity = contextIdentity; const response = await API.get(`${basePath}/experts`, { params: { locale: language, project_id: organization ? projectId : undefined, }, headers, disableDuplicate: true, skipErrorHandler: true, }); if (!response.data.success) throw new Error(response.data.message); if ( seq === expertsSeqRef.current && identity === contextIdentityRef.current ) { const nextExperts = response.data.data || []; setExperts(nextExperts); setSelectedExpert((current) => current && nextExperts.some((item) => item.id === current.id) ? current : null, ); } }, [basePath, contextIdentity, headers, language, organization, projectId]); const loadRuns = useCallback(async () => { const seq = ++runsSeqRef.current; const identity = contextIdentity; const response = await API.get(`${basePath}/runs`, { params: { page: 1, page_size: 50 }, headers, disableDuplicate: true, skipErrorHandler: true, }); if (!response.data.success) throw new Error(response.data.message); if (seq === runsSeqRef.current && identity === contextIdentityRef.current) setRuns(response.data.data || []); }, [basePath, contextIdentity, headers]); const loadAssignments = useCallback(async () => { if (!organization || !canManage) return; const seq = ++assignmentsSeqRef.current; const identity = contextIdentity; const [assignmentResponse, catalogResponse, metricsResponse] = await Promise.all([ API.get(`${basePath}/assignments`, { headers, disableDuplicate: true, skipErrorHandler: true, }), API.get(`${basePath}/catalog`, { params: { locale: language }, headers, disableDuplicate: true, skipErrorHandler: true, }), API.get(`${basePath}/metrics`, { headers, disableDuplicate: true, skipErrorHandler: true, }).catch(() => null), ]); if (!assignmentResponse.data.success) throw new Error(assignmentResponse.data.message); if (!catalogResponse.data.success) throw new Error(catalogResponse.data.message); if ( seq !== assignmentsSeqRef.current || identity !== contextIdentityRef.current ) return; setAssignments(assignmentResponse.data.data || []); setExpertCatalog(catalogResponse.data.data || []); if (metricsResponse?.data?.success) setMetrics(metricsResponse.data.data); }, [basePath, canManage, contextIdentity, headers, language, organization]); const loadOrganizationContext = useCallback(async () => { if (!organization) return; const seq = ++contextSeqRef.current; const identity = contextIdentity; const projectResponse = await API.get('/api/org/project', { headers, disableDuplicate: true, skipErrorHandler: true, }).catch(() => null); if ( seq === contextSeqRef.current && identity === contextIdentityRef.current && projectResponse?.data?.success ) { setProjects(projectResponse.data.data || []); } if (!canManage) return; const [departmentResponse, memberResponse] = await Promise.all([ API.get('/api/org/dept', { headers, disableDuplicate: true, skipErrorHandler: true, }).catch(() => null), API.get('/api/org/members/all', { headers, disableDuplicate: true, skipErrorHandler: true, }).catch(() => null), ]); if ( seq !== contextSeqRef.current || identity !== contextIdentityRef.current ) return; if (departmentResponse?.data?.success) { setDepartments(departmentResponse.data.data || []); } if (memberResponse?.data?.success) { // /api/org/members/all returns a plain array, not a paginated envelope. setMembers(memberResponse.data.data || []); } }, [canManage, contextIdentity, headers, organization]); const loadDetail = useCallback( async (runId, quiet = false) => { if (!runId) return; const seq = ++detailSeqRef.current; // Quiet refreshes (SSE-triggered) share the data fence but must not own // the spinner: if they bumped the shared seq, the initial visible load // would skip its finally-clear and the panel would spin forever. const visibleSeq = quiet ? detailVisibleSeqRef.current : ++detailVisibleSeqRef.current; const identity = contextIdentity; if (!quiet) setDetailLoading(true); try { const response = await API.get(`${basePath}/runs/${runId}`, { headers, disableDuplicate: true, skipErrorHandler: true, }); if (!response.data.success) throw new Error(response.data.message); const detail = response.data.data; // The backend returns the OLDEST 200 events per request and exposes // `events_after` for paging. Without it a long run's timeline freezes // on early events while the status pill already reads "finished". // Two guards keep this off the hot path: (1) only terminal runs page at // all, so a live run still costs exactly one request per refresh; // (2) quiet (SSE-triggered) refreshes page at most once per run — // opening a finished run replays its history in 200-event batches and // every batch fires a refresh, which would otherwise redo the catch-up // each time and multiply one click into dozens of full detail reads. if ( detail?.run && terminalStatuses.has(detail.run.status) && (detail.events || []).length === EVENT_PAGE_SIZE && (!quiet || pagedQuietRunRef.current !== runId) ) { if (quiet) pagedQuietRunRef.current = runId; // Catch-up pages are best effort: a failure here must keep the first // page that already succeeded, not bubble out and discard the whole // detail load (a quiet refresh would additionally roll its seq back // and leave the panel on stale data). try { for (let page = 0; page < MAX_EXTRA_EVENT_PAGES; page += 1) { if ( seq !== detailSeqRef.current || identity !== contextIdentityRef.current ) break; const lastSeq = detail.events[detail.events.length - 1]?.event_seq; if (!lastSeq) break; const nextPage = await API.get(`${basePath}/runs/${runId}`, { params: { events_after: lastSeq }, headers, disableDuplicate: true, skipErrorHandler: true, }); if (!nextPage.data?.success) break; const more = nextPage.data.data?.events || []; if (more.length === 0) break; detail.events = detail.events.concat(more); if (more.length < EVENT_PAGE_SIZE) break; } } catch { // Keep whatever pages already landed. } } if ( seq === detailSeqRef.current && identity === contextIdentityRef.current ) { setRunDetail(detail); setFeedback(detail?.feedback?.decision || null); // Fresh data on screen means loading is over, whichever request // (visible or quiet) delivered it. setDetailLoading(false); } } catch (error) { // A failed quiet refresh must not invalidate an in-flight visible // load: roll back its own seq bump so the earlier response can still // land instead of leaving the panel blank until the next refresh. if (quiet && seq === detailSeqRef.current) { detailSeqRef.current = seq - 1; } if ( !quiet && seq === detailSeqRef.current && visibleSeq === detailVisibleSeqRef.current && identity === contextIdentityRef.current ) showError(localizedRequestError(error)); } finally { if ( !quiet && visibleSeq === detailVisibleSeqRef.current && identity === contextIdentityRef.current ) setDetailLoading(false); } }, [basePath, contextIdentity, headers, localizedRequestError], ); useEffect(() => { let active = true; setLoading(true); Promise.all([ loadExperts(), loadRuns(), loadAssignments(), loadOrganizationContext(), ]) .catch((error) => active && showError(error.message || error)) .finally(() => active && setLoading(false)); return () => { active = false; }; }, [loadAssignments, loadExperts, loadOrganizationContext, loadRuns]); useEffect(() => { if (!selectedRunId) { detailSeqRef.current += 1; detailVisibleSeqRef.current += 1; setRunDetail(null); setDetailLoading(false); setStreamState('idle'); return undefined; } loadDetail(selectedRunId); streamRef.current?.close(); const identity = contextIdentity; let disposed = false; let finished = false; let attempt = 0; let reconnectTimer = null; let lastEventId = ''; // Trailing throttle: a multi-step run emits bursts of SSE events // (step.queued/completed, output.snapshot, …) and each full detail // reload is an expensive request — collapse bursts to one reload per // 1.5s. Terminal events bypass the throttle so the final state can // never be dropped by the cleanup clearing a pending timer. let refreshTimer = null; let refreshQueued = false; const doRefresh = () => { void Promise.allSettled([loadDetail(selectedRunId, true), loadRuns()]); }; const refresh = (immediate = false) => { if (immediate) { if (refreshTimer) { clearTimeout(refreshTimer); refreshTimer = null; refreshQueued = false; } doRefresh(); return; } if (refreshTimer) { refreshQueued = true; return; } doRefresh(); refreshTimer = window.setTimeout(() => { refreshTimer = null; if (refreshQueued && !disposed) { refreshQueued = false; refresh(); } }, 1500); }; const eventNames = [ 'run.started', 'run.succeeded', 'run.completed_with_warnings', 'run.failed', 'run.cancelled', 'run.reconciliation_required', 'run.cancel_requested', 'run.reconciled', 'run.recovered', 'step.queued', 'step.completed', 'output.snapshot', 'tool.confirmation.required', 'tool.confirmation.decided', 'tool.round.completed', ]; // run.reconciliation_required is not terminal: the backend keeps the // stream open so run.reconciled can still arrive and settle the UI state. const streamTerminalEvents = new Set([ 'run.succeeded', 'run.completed_with_warnings', 'run.failed', 'run.cancelled', 'run.reconciled', ]); const scheduleReconnect = () => { if ( disposed || finished || reconnectTimer || identity !== contextIdentityRef.current ) return; setStreamState('reconnecting'); const delay = Math.min(30000, 1000 * 2 ** Math.min(attempt, 5)); attempt += 1; reconnectTimer = setTimeout(() => { reconnectTimer = null; if (!disposed) connect(); }, delay); }; const connect = () => { if (disposed || finished || identity !== contextIdentityRef.current) return; const source = new SSE( `${getServerURL()}${basePath}/runs/${selectedRunId}/events`, { // sse.js (XHR polyfill) bypasses the axios interceptors, so the // auth marker header must be attached explicitly — UserAuth rejects // any request without New-Api-User with a 401. The Accept header is // what lets the backend return SSE-aware auth failures (403 instead // of the JSON 200 envelope) so revoked members stop reconnecting. headers: { ...headers, 'New-Api-User': getUserIdFromLocalStorage(), Accept: 'text/event-stream', }, method: 'GET', withCredentials: getServerURL() !== '', // The SSE constructor auto-sends the request unless start is false; // deferring to the explicit stream() below is what lets the // lastEventId assignment take effect as the Last-Event-ID header. start: false, }, ); streamRef.current = source; // sse.js sends this value as the Last-Event-ID header, letting the // backend replay only the events we have not seen yet. if (lastEventId) source.lastEventId = lastEventId; setStreamState(attempt === 0 ? 'connecting' : 'reconnecting'); source.addEventListener('open', (event) => { if (disposed || identity !== contextIdentityRef.current) return; // sse.js fires 'open' on HEADERS_RECEIVED regardless of HTTP status // (the event carries responseCode). Resetting the backoff for a // 429/5xx response would pin the reconnect loop at the minimum delay // forever; only a real 2xx stream counts. const status = event.responseCode ?? source.xhr?.status; if (status >= 200 && status < 300) { attempt = 0; setStreamState('connected'); } }); source.addEventListener('error', (event) => { if (disposed || identity !== contextIdentityRef.current) return; // 404 (run_not_found) mirrors the in-band run_unavailable case: a run // that was purged between reconnects will 404 forever, so retrying // would loop indefinitely. if ( event.responseCode === 401 || event.responseCode === 403 || event.responseCode === 404 ) { finished = true; setStreamState('error'); return; } // In-band terminal errors (server emits `event: error` with a code). // sse.js only attaches responseCode on HTTP-level failures, so a // defined responseCode means this is an HTTP error body — those are // NEVER definitive (e.g. a transient 500 whose JSON happens to carry a // code); only true in-band events may terminate the stream. const inBand = event.responseCode === undefined; let code = ''; try { code = JSON.parse(event.data || '{}')?.code || ''; } catch { code = ''; } if ( inBand && (code === 'access_revoked' || code === 'run_unavailable' || code === 'run_not_found') ) { finished = true; setStreamState('error'); source.close(); return; } // Graceful finish: the run is terminal with nothing left to stream // (e.g. archived runs whose event rows were pruned). Reconnecting // would only repeat an instant open/close cycle. if (inBand && code === 'stream_ended') { finished = true; refresh(); source.close(); setStreamState('complete'); return; } scheduleReconnect(); }); // The server can close the connection without a terminal event (deploy // restart, proxy idle timeout): sse.js only flips readyState to CLOSED. source.addEventListener('readystatechange', (event) => { if (event.readyState === 2 && !disposed && !finished) scheduleReconnect(); }); eventNames.forEach((eventName) => source.addEventListener(eventName, (event) => { if (disposed || identity !== contextIdentityRef.current) return; // A delivered event is the definitive healthy signal — reset the // reconnect backoff here rather than trusting 'open' alone. attempt = 0; if (event.lastEventId) lastEventId = event.lastEventId; refresh(streamTerminalEvents.has(eventName)); if (streamTerminalEvents.has(eventName)) { finished = true; source.close(); setStreamState('complete'); } }), ); source.stream(); }; connect(); return () => { disposed = true; if (reconnectTimer) clearTimeout(reconnectTimer); if (refreshTimer) clearTimeout(refreshTimer); streamRef.current?.close(); streamRef.current = null; }; }, [basePath, contextIdentity, headers, loadDetail, loadRuns, selectedRunId]); // 选中专家后把焦点移交任务输入框:撰写态会隐藏原焦点元素(选中卡的 // 「开始任务」按钮 visibility:hidden、窄屏下整个专家列 display:none), // 不移交则键盘焦点静默回落 document,Tab 序从页面头重来。 useEffect(() => { if (!selectedExpert) return undefined; const frame = requestAnimationFrame(() => { document.getElementById('brain-task-input')?.focus(); }); return () => cancelAnimationFrame(frame); }, [selectedExpert]); useEffect(() => { setFeedback(null); setRevisionOpen(false); setRevisionInstruction(''); // A confirmation reason typed for one task must not carry over into // another task's pending confirmation card. setConfirmationReason(''); revisionRequestRef.current = null; }, [selectedRunId]); const createRun = async () => { if ( !selectedExpert || !input.trim() || attachmentBusy || attachments.some((item) => item.status !== 'ready') ) return; const identity = contextIdentity; setSubmitting(true); try { const skillIds = organization ? [] : [...manualSkillIds].sort(); const fingerprint = JSON.stringify({ expertId: selectedExpert.id, input: input.trim(), language, projectId: organization ? projectId : 0, attachmentIds: attachments.map((item) => item.id), // 勾选变化必须进指纹:否则换了技能仍复用同一幂等键,后端会因 // request_hash 不一致而返回 409,而不是按新技能集重新执行。 skillIds, }); const idempotencyKey = stableRequestKey(createRequestRef, fingerprint); const response = await API.post( `${basePath}/runs`, { expert_id: selectedExpert.id, input: input.trim(), locale: language, project_id: organization ? projectId : 0, attachment_ids: attachments.map((item) => item.id), skill_ids: skillIds, }, { headers: { ...headers, 'Idempotency-Key': idempotencyKey }, skipErrorHandler: true, }, ); if (!response.data.success) throw new Error(response.data.message); if (identity !== contextIdentityRef.current) return; setInput(''); setAttachments([]); setManualSkillIds([]); createRequestRef.current = null; setSelectedExpert(null); setSelectedRunId(response.data.data.id); setView('runs'); await loadRuns(); showSuccess(t('任务已提交,云端专家正在处理')); } catch (error) { if (identity === contextIdentityRef.current) showError(localizedRequestError(error)); } finally { if (identity === contextIdentityRef.current) setSubmitting(false); } }; const uploadAttachment = async (event) => { const file = event.target.files?.[0]; event.target.value = ''; if (!file) return; const extension = file.name.split('.').pop()?.toLowerCase(); if ( !['txt', 'md', 'docx', 'pdf'].includes(extension) || file.size <= 0 || file.size > 10 * 1024 * 1024 ) { showError(t('附件仅支持 10 MiB 内的 TXT、Markdown、DOCX 或 PDF')); return; } const contentType = file.type || { txt: 'text/plain', md: 'text/markdown', docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', pdf: 'application/pdf', }[extension]; const identity = contextIdentity; setAttachmentBusy(true); try { const sessionResponse = await API.post( `${basePath}/attachments/uploads`, { original_name: file.name, content_type: contentType, size_bytes: file.size, }, { headers, skipErrorHandler: true }, ); if (!sessionResponse.data?.success) throw new Error( sessionResponse.data?.message || t('附件上传会话创建失败'), ); const ticket = sessionResponse.data.data; const abort = new AbortController(); const uploadTimeout = window.setTimeout( () => abort.abort(), 10 * 60 * 1000, ); let uploadResponse; try { uploadResponse = await fetch(ticket.upload_url, { method: 'PUT', headers: { 'Content-Type': contentType }, body: file, signal: abort.signal, }); } finally { window.clearTimeout(uploadTimeout); } if (!uploadResponse.ok) throw new Error(`${t('附件对象上传失败')} (${uploadResponse.status})`); const finalizeResponse = await API.post( `${basePath}/attachments/uploads/${ticket.session_id}/finalize`, {}, { headers, skipErrorHandler: true }, ); if (!finalizeResponse.data?.success) throw new Error(finalizeResponse.data?.message || t('附件固化失败')); let attachment = finalizeResponse.data.data; if (identity !== contextIdentityRef.current) { await API.delete(`${basePath}/attachments/${attachment.id}`, { headers, skipErrorHandler: true, }).catch(() => undefined); return; } setAttachments((current) => [...current, attachment]); for ( let attempt = 0; attempt < 90 && identity === contextIdentityRef.current && ['uploaded', 'processing'].includes(attachment.status); attempt += 1 ) { await new Promise((resolve) => setTimeout(resolve, 1000)); const statusResponse = await API.get( `${basePath}/attachments/${attachment.id}`, { headers, skipErrorHandler: true, disableDuplicate: true }, ); if (!statusResponse.data?.success) throw new Error( statusResponse.data?.message || t('附件状态读取失败'), ); attachment = statusResponse.data.data; if (identity === contextIdentityRef.current) { setAttachments((current) => current.map((item) => item.id === attachment.id ? attachment : item, ), ); } } if (identity !== contextIdentityRef.current) return; if (attachment.status !== 'ready') { // 轮询上限 90 次后附件可能仍在处理中(error_code 为空)——此时说 // "安全处理未通过"是误导,要与真正的失败态分开。 const stillProcessing = ['uploaded', 'processing'].includes( attachment.status, ); throw new Error( t( stillProcessing ? '附件仍在安全处理中,请稍后在附件列表查看结果。' : attachmentErrorMessages[attachment.error_code] || '附件安全处理未通过', ), ); } } catch (error) { if (identity === contextIdentityRef.current) showError(localizedRequestError(error)); } finally { if (identity === contextIdentityRef.current) setAttachmentBusy(false); } }; const removeAttachment = async (attachment) => { setAttachments((current) => current.filter((item) => item.id !== attachment.id), ); try { await API.delete(`${basePath}/attachments/${attachment.id}`, { headers, skipErrorHandler: true, }); } catch { // The server may retain an attachment already frozen into a task. } }; const cancelRun = async () => { if (!selectedRunId) return; const identity = contextIdentity; const runId = selectedRunId; try { const response = await API.post( `${basePath}/runs/${runId}/cancel`, {}, { headers, skipErrorHandler: true }, ); if (!response.data.success) throw new Error(response.data.message); if (identity !== contextIdentityRef.current) return; if (runId === selectedRunIdRef.current) { await Promise.all([loadDetail(runId), loadRuns()]); } else { // The user already switched runs: refreshing the detail panel with the // old id would overwrite the newly selected run's view. await loadRuns(); } if (identity !== contextIdentityRef.current) return; showSuccess(t('已提交取消请求')); } catch (error) { if (identity === contextIdentityRef.current) showError(localizedRequestError(error)); } }; const decideToolConfirmation = async (confirmation, approve) => { if (!selectedRunId || confirmationReason.trim().length < 2) return; const identity = contextIdentity; const runId = selectedRunId; setConfirmationBusy(true); try { const response = await API.post( `${basePath}/runs/${runId}/confirmations/${confirmation.id}/decision`, { approve, reason: confirmationReason.trim() }, { headers, skipErrorHandler: true }, ); if (!response.data?.success) throw new Error(response.data?.message || t('操作失败')); if (identity !== contextIdentityRef.current) return; setConfirmationReason(''); if (runId === selectedRunIdRef.current) { await Promise.all([loadDetail(runId), loadRuns()]); } else { // The user switched runs while the decision was in flight; refreshing // the panel with the old id would repaint it over the new selection. await loadRuns(); } showSuccess( t( approve ? '操作已确认,任务将由可用 Worker 继续执行' : '操作已拒绝,专家将根据拒绝结果继续处理', ), ); } catch (error) { if (identity === contextIdentityRef.current) { showError(localizedRequestError(error)); // A 409 usually means the frozen payload/credential changed server // side; re-sync the panel so the pending card converges instead of // inviting repeated failing clicks. Await it so the button stays // disabled until the card state has converged. if (runId === selectedRunIdRef.current) await loadDetail(runId, true); } } finally { if (identity === contextIdentityRef.current) setConfirmationBusy(false); } }; const submitFeedback = async (decision) => { if (!selectedRunId) return; const identity = contextIdentity; const runId = selectedRunId; try { const response = await API.post( `${basePath}/runs/${runId}/feedback`, { decision, rating: decision === 'useful' ? 5 : 2, comment: '' }, { headers, skipErrorHandler: true }, ); // Middleware failures (member disabled, feature off) come back as // HTTP 200 + success:false — treat them as errors, not as saved votes. if (!response.data?.success) throw new Error(response.data?.message || t('反馈提交失败')); if (identity !== contextIdentityRef.current) return; if (runId !== selectedRunIdRef.current) return; // Invalidate in-flight detail snapshots taken before the vote was // written, so a late quiet refresh cannot repaint the thumb back to // the unvoted state. detailSeqRef.current += 1; setFeedback(decision); showSuccess(t('感谢反馈,我们会持续优化专家效果')); } catch (error) { if (identity === contextIdentityRef.current) showError(localizedRequestError(error)); } }; const submitTimeConfirmation = async () => { if (!selectedRunId || !organization) return; try { const response = await API.put( `${basePath}/runs/${selectedRunId}/time-confirmation`, timeConfirmation, { headers, skipErrorHandler: true }, ); if (!response.data?.success) throw new Error(response.data?.message || t('时间确认失败')); setTimeConfirmOpen(false); showSuccess(t('人工耗时抽样已保存')); } catch (error) { showError(localizedRequestError(error)); } }; const reviseRun = async () => { if (!selectedRunId || !revisionInstruction.trim()) return; const identity = contextIdentity; setRevising(true); try { const fingerprint = JSON.stringify({ runId: selectedRunId, instruction: revisionInstruction.trim(), }); const idempotencyKey = stableRequestKey(revisionRequestRef, fingerprint); const response = await API.post( `${basePath}/runs/${selectedRunId}/revise`, { instruction: revisionInstruction.trim() }, { headers: { ...headers, 'Idempotency-Key': idempotencyKey }, skipErrorHandler: true, }, ); if (!response.data.success) throw new Error(response.data.message); if (identity !== contextIdentityRef.current) return; setRevisionInstruction(''); revisionRequestRef.current = null; setRevisionOpen(false); setSelectedRunId(response.data.data.id); await loadRuns(); showSuccess(t('修订任务已提交,原产物会完整保留')); } catch (error) { if (identity === contextIdentityRef.current) showError(localizedRequestError(error)); } finally { if (identity === contextIdentityRef.current) setRevising(false); } }; const copyArtifact = async () => { const content = runDetail?.artifact?.content; if (!content) return; const identity = contextIdentity; // 走公共 copy:HTTP 部署下 navigator.clipboard 为 undefined,裸调复制不到 if (await copy(content)) { if (identity === contextIdentityRef.current) showSuccess(t('已复制产物内容')); } else { if (identity === contextIdentityRef.current) showError(t('复制失败,请手动选择文本复制')); } }; // 报障排查的一键复制:把任务 ID / 错误码 / 失败原因 / 原始报错拼成一段文本, // 用户转给管理员时不用再对着折叠的技术详情逐项截图凑信息。 const copyErrorReport = async () => { const run = runDetail?.run; if (!run?.error_message) return; const identity = contextIdentity; const { reason, raw } = describeRunFailure( run.error_code, run.error_message, ); const expertName = expertById.get(run.expert_id)?.name || ''; const lines = [ `${t('任务 ID')}: ${run.id}`, expertName ? `${t('专家')}: ${expertName}` : '', `${t('状态')}: ${run.status}`, run.finished_at > 0 ? `${t('结束时间')}: ${safeDate(run.finished_at, i18n.language)}` : '', run.error_code ? `${t('错误码')}: ${run.error_code}` : '', reason ? `${t('失败原因')}: ${t(reason)}` : '', raw ? `${t('原始报错')}: ${raw}` : '', ].filter(Boolean); if (await copy(lines.join('\n'))) { if (identity === contextIdentityRef.current) showSuccess(t('已复制报错信息')); } else { if (identity === contextIdentityRef.current) showError(t('复制失败,请手动选择文本复制')); } }; const downloadArtifact = async () => { if (!selectedRunId || runDetail?.artifact?.artifact_type !== 'file') return; const identity = contextIdentity; try { const response = await API.get( `${basePath}/runs/${selectedRunId}/artifact/download`, { headers, skipErrorHandler: true }, ); if (!response.data.success) throw new Error(response.data.message); if (identity !== contextIdentityRef.current) return; const anchor = document.createElement('a'); anchor.href = response.data.data.url; anchor.download = response.data.data.file_name || 'artifact'; anchor.target = '_blank'; anchor.rel = 'noopener noreferrer'; document.body.appendChild(anchor); anchor.click(); anchor.remove(); } catch (error) { if (identity === contextIdentityRef.current) showError(localizedRequestError(error)); } }; const setOrganizationExpertEnabled = async (expertId, enabled) => { if (assignmentScope !== 'organization' && !assignmentScopeId) return; const identity = contextIdentity; try { const response = await API.put( `${basePath}/assignments`, { expert_id: expertId, scope_type: assignmentScope, scope_id: assignmentScope === 'organization' ? 0 : assignmentScopeId, enabled, }, { headers, skipErrorHandler: true }, ); if (!response.data.success) throw new Error(response.data.message); if (identity !== contextIdentityRef.current) return; await Promise.all([loadAssignments(), loadExperts()]); if (identity !== contextIdentityRef.current) return; showSuccess(t(enabled ? '企业专家已启用' : '企业专家已停用')); } catch (error) { if (identity === contextIdentityRef.current) showError(localizedRequestError(error)); } }; const deleteOrganizationAssignment = async (assignmentId) => { const identity = contextIdentity; try { const response = await API.delete( `${basePath}/assignments/${assignmentId}`, { headers, skipErrorHandler: true }, ); if (!response.data.success) throw new Error(response.data.message); if (identity !== contextIdentityRef.current) return; await Promise.all([loadAssignments(), loadExperts()]); if (identity !== contextIdentityRef.current) return; showSuccess(t('分发规则已删除')); } catch (error) { if (identity === contextIdentityRef.current) showError(localizedRequestError(error)); } }; const assignmentEnabled = (expertId) => { const organizationDefault = assignments.find( (item) => item.expert_id === expertId && item.scope_type === 'organization' && item.scope_id === 0, ); const fallback = organizationDefault ? organizationDefault.enabled : true; if (assignmentScope === 'organization') return fallback; const departmentIds = new Set(); let departmentId = 0; if (assignmentScope === 'department') { departmentId = assignmentScopeId; } else if (assignmentScope === 'member') { departmentId = members.find((item) => item.id === assignmentScopeId)?.department_id || 0; } const departmentById = new Map(departments.map((item) => [item.id, item])); // Mirror backend organizationCanUseBrainExpert: a disabled actor // department drops the whole subtree chain, and a disabled rule scope // never matches, so residual assignments on deactivated departments fall // back to the organization default instead of flipping the switch. const isActiveDepartment = (id) => departmentById.get(id)?.status === 1; if (departmentId && !isActiveDepartment(departmentId)) { departmentId = 0; } for ( const visited = new Set(); departmentId && !visited.has(departmentId); ) { visited.add(departmentId); departmentIds.add(departmentId); departmentId = departmentById.get(departmentId)?.parent_id || 0; } const matching = assignments.filter((item) => { if (item.expert_id !== expertId) return false; if (item.scope_type === 'department') { return ( departmentIds.has(item.scope_id) && isActiveDepartment(item.scope_id) ); } return ( item.scope_type === assignmentScope && item.scope_id === assignmentScopeId ); }); if (matching.some((item) => !item.enabled)) return false; if (matching.length > 0) return true; return fallback; }; // The upsert API rejects disabled departments and disabled/expired projects // (scope_invalid), so never offer them as assignment targets. Admin-facing // /api/org/project returns every project regardless of state. const selectableProjects = useMemo( () => projects.filter( (item) => item.status === 1 && (!item.expired_at || item.expired_at * 1000 > Date.now()), ), [projects], ); const assignmentTargetOptions = useMemo(() => { if (assignmentScope === 'department') { return departments .filter((item) => item.status === 1) .map((item) => ({ label: item.name, value: item.id })); } if (assignmentScope === 'project') { return selectableProjects.map((item) => ({ label: item.name, value: item.id, })); } if (assignmentScope === 'member') { return members.map((item) => ({ label: item.display_name || item.username || formatIdReference(item.id), value: item.id, })); } return []; }, [assignmentScope, departments, members, selectableProjects]); // 残留分发规则:作用域主体已被删除(scope_exists=false)或已停用(scope_active=false)。 // 这类规则运行时不再匹配,但会一直躺在库里,且主体一旦恢复启用就立刻复活—— // 上面的范围选择器又刻意不列停用主体,于是它们在界面上彻底隐身。这里显式列出来供清理。 // 旧后端不返回 scope_* 字段时(undefined)不做判断,避免把正常规则误报为残留。 const residualAssignments = useMemo(() => { const expertNameById = new Map( expertCatalog.map((item) => [item.id, item.name]), ); const scopeTypeLabel = { department: t('部门'), project: t('项目'), member: t('成员'), organization: t('全企业'), }; return assignments .filter( (item) => item.scope_exists !== undefined && (!item.scope_exists || !item.scope_active), ) .map((item) => ({ ...item, expert_name: expertNameById.get(item.expert_id) || formatIdReference(item.expert_id), scope_type_label: scopeTypeLabel[item.scope_type] || item.scope_type, scope_label: item.scope_name || formatIdReference(item.scope_id), })); }, [assignments, expertCatalog, t]); const activeRun = runDetail?.run; const failureReason = useMemo( () => describeRunFailure(activeRun?.error_code, activeRun?.error_message), [activeRun?.error_code, activeRun?.error_message], ); const runSteps = useMemo(() => runDetail?.steps || [], [runDetail]); const runningStep = useMemo( () => runSteps.find((step) => step.status === 'running') || null, [runSteps], ); // 事件条数上限是一页 200 条、长任务还会继续翻页,而这块每来一个流式事件就 // 重渲一次——payload 解析放进 useMemo,避免每帧把整条时间线重新 JSON.parse。 const timelineItems = useMemo(() => { const events = runDetail?.events || []; return events.map((event, index) => { const previous = events[index - 1]; const gapSeconds = previous ? event.created_at - previous.created_at : 0; return { id: event.id, label: t(event.event_type), summary: summarizeRunEvent(event, t), time: safeDate(event.created_at, i18n.language), // 同秒相邻事件不挂 "+0s":排队→开始→失败经常落在同一秒,每行都挂只是噪音。 gap: gapSeconds > 0 ? formatDurationSeconds(gapSeconds) : '', }; }); }, [runDetail?.events, t, i18n.language]); const expertById = useMemo( () => new Map(experts.map((expert) => [expert.id, expert])), [experts], ); // 使用指引:核心流程「选专家 → 描述任务 → 等结果 → 采纳产物」。 // 完成态由任务列表真实数据驱动;企业/个人两种挂载共用,企业特有的 // 项目与效能条目按 organization 条件注入。 const hasTerminalRun = runs.some((run) => terminalStatuses.has(run.status)); const hasDeliveredRun = runs.some( (run) => run.status === 'succeeded' || run.status === 'completed_with_warnings', ); const guide = usePageGuide({ guideKey: organization ? 'org-cloud-brain' : 'cloud-brain', ready: !loading, title: t('云端大脑 · 使用指引'), intro: t('选专家 → 描述任务 → 等结果;任务异步执行,提交后可以离开页面'), steps: [ { title: t('选一位专家'), detail: t('专家广场按适用场景标注了每位专家擅长的任务'), done: runs.length > 0 || Boolean(selectedExpert), cta: t('去专家广场'), onAction: () => setView('experts'), points: [ t('每张专家卡标明适用场景与审核过的技能版本'), t('点卡片上的「开始任务」,右侧打开任务提交面板'), organization ? t('专家广场为空说明管理员尚未启用专家,请联系企业管理员') : t('专家广场为空时请稍后刷新重试'), ], }, { title: t('描述任务并提交'), detail: t('写清目标、受众、已知事实与限制条件,信息越全成果越可用'), done: runs.length > 0, cta: t('去发起任务'), onAction: () => setView('experts'), points: [ t( '任务描述最多 2 万字:目标、受众、已知事实、限制条件写得越清楚,成果越接近可直接交付', ), ...(organization ? [ t( '可选关联项目:应用该项目的模型范围与预算,任务用量计入该项目', ), ] : []), t( '安全附件支持 TXT/MD/DOCX/PDF,最多 5 个、单个 10MiB;通过安全检查后才能提交', ), t('提交成功后自动切到「我的任务」,可以离开页面,任务在云端继续执行'), ], }, { title: t('跟踪进度与确认操作'), detail: t('详情页实时推送进度;专家调用业务系统前需要你确认'), done: hasTerminalRun, cta: t('去我的任务'), onAction: () => setView('runs'), points: [ t('在任务列表点任意一条查看详情,执行中的任务可随时「取消任务」'), t( '出现「等待操作确认」时,核对冻结参数后填写原因,选择「确认并继续」或「拒绝操作」', ), t('长时间不处理会触发确认超时,任务按已发生用量结算后结束'), ], }, { title: t('采纳产物'), detail: t('复制或下载产物、反馈评价;不满意用「修订」迭代一轮'), done: hasDeliveredRun, cta: t('去看产物'), onAction: () => setView('runs'), points: [ t('Markdown 产物可一键复制;文件产物点「获取短期下载链接」下载'), organization ? t('产物底部点 👍/👎 反馈;「确认节省时间」会进入企业效能看板') : t('产物底部点 👍/👎 反馈,帮助持续改进专家质量'), t( '「修订产物」说明希望保留、调整或补充的内容,会生成新任务,原任务与历史版本不会被覆盖', ), ], }, ], faq: [ ...(organization ? [ { q: t('提交被拦截提示额度不足?'), a: t('企业可用额度不足,请联系管理员补充额度后重试'), }, ] : []), { q: t('提示「产物未通过输出契约校验」?'), a: t('任务描述缺少关键信息,按专家要求的结构补充后重新提交'), }, { q: t('提示「该专家暂不可用」?'), a: t('专家被停用或版本变更,刷新专家列表后重新选择'), }, ], }); const closeGuide = guide.close; useEffect(() => { closeGuide(); }, [orgId, closeGuide]); return (
{organization ? (
{organization ? t('企业智能工作空间') : t('个人智能工作空间')}

{t('云端大脑')}

{t( '选择经过审核的专业专家,把真实业务信息转化为结构清晰、可直接使用的成果。', )}

{organization && canManage && ( )}
{experts.length}
{t('可用专家')} {t('固定技能 · 全程可追溯')}
) : ( // 体验中心:页头对齐用户中心规范(面包屑 + 28px 标题 + 副标题 + 右侧操作) } subtitle={t( '选择经过审核的专业专家,把真实业务信息转化为结构清晰、可直接使用的成果。', )} extra={ <> {t('可用专家')} {experts.length} } /> )} {organization ? ( ) : ( // 体验中心:列表页签(UI_COMPONENT_STANDARDS 列表页签规范),只承担导航,内容仍由 view 渲染