Files
monkey-ai-web/src/pages/CloudBrain/index.jsx
T

2888 lines
114 KiB
React
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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 (
<span className={`brain-status brain-status--${meta.tone}`}>
<Icon size={13} className={status === 'running' ? 'brain-spin' : ''} />
{t(meta.label)}
</span>
);
};
const BetaBadge = () => (
<span className='brain-beta'>{I18N_TECHNICAL_TEXT.BETA}</span>
);
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 (
<section
className={`cloud-brain-shell app-scrollbar${
organization ? '' : ' cloud-brain-shell--experience'
}`}
aria-label={t('云端大脑')}
>
<div className='brain-atmosphere' aria-hidden='true'>
<span className='brain-orb brain-orb--one' />
<span className='brain-orb brain-orb--two' />
<span className='brain-grid' />
</div>
{organization ? (
<header className='brain-hero'>
<div>
<div className='brain-eyebrow'>
<Sparkles size={14} />
{organization ? t('企业智能工作空间') : t('个人智能工作空间')}
<BetaBadge />
</div>
<h1>{t('云端大脑')}</h1>
<p>
{t(
'选择经过审核的专业专家,把真实业务信息转化为结构清晰、可直接使用的成果。',
)}
</p>
</div>
<div className='brain-hero-side'>
<PageGuideTrigger guide={guide} />
{organization && canManage && (
<Button onClick={() => setManageOpen((open) => !open)}>
{manageOpen ? t('完成管理') : t('管理企业专家')}
</Button>
)}
<div className='brain-hero-metric'>
<strong>{experts.length}</strong>
<div>
<span>{t('可用专家')}</span>
<small>{t('固定技能 · 全程可追溯')}</small>
</div>
</div>
</div>
</header>
) : (
// 体验中心:页头对齐用户中心规范(面包屑 + 28px 标题 + 副标题 + 右侧操作)
<ExperiencePageHeader
className='brain-page-header'
title={t('云端大脑')}
titleSuffix={<BetaBadge />}
subtitle={t(
'选择经过审核的专业专家,把真实业务信息转化为结构清晰、可直接使用的成果。',
)}
extra={
<>
<PageGuideTrigger guide={guide} />
<span
className='brain-header-stat'
title={t('固定技能 · 全程可追溯')}
>
<span>{t('可用专家')}</span>
<strong>{experts.length}</strong>
</span>
</>
}
/>
)}
{organization ? (
<nav className='brain-tabs' aria-label={t('云端大脑导航')}>
<button
type='button'
className={[
'app-action-button',
view === 'experts' ? 'is-active' : '',
]
.filter(Boolean)
.join(' ')}
onClick={() => setView('experts')}
>
<ActionBot size={17} /> {t('专家广场')}
</button>
<button
type='button'
className={['app-action-button', view === 'runs' ? 'is-active' : '']
.filter(Boolean)
.join(' ')}
onClick={() => setView('runs')}
>
<ListChecks size={17} /> {t('我的任务')}
{runs.some((run) => !terminalStatuses.has(run.status)) && (
<span className='brain-live-dot' aria-label={t('有任务执行中')} />
)}
</button>
</nav>
) : (
// 体验中心:列表页签(UI_COMPONENT_STANDARDS 列表页签规范),只承担导航,内容仍由 view 渲染
<Tabs
className='brain-view-tabs'
activeKey={view}
onChange={setView}
aria-label={t('云端大脑导航')}
items={[
{
key: 'experts',
label: (
<span className='brain-view-tab'>
<ActionBot size={16} aria-hidden='true' />
{t('专家广场')}
</span>
),
},
{
key: 'runs',
label: (
<span className='brain-view-tab'>
<ListChecks size={16} aria-hidden='true' />
{t('我的任务')}
{runs.some((run) => !terminalStatuses.has(run.status)) && (
<span
className='brain-live-dot'
role='status'
aria-label={t('有任务执行中')}
/>
)}
</span>
),
},
]}
/>
)}
<PageGuidePill guide={guide} />
{loading ? (
<div className='brain-loading'>
<Spin size='large' />
<span>{t('正在准备专家工作空间…')}</span>
</div>
) : manageOpen && organization && canManage ? (
<section className='brain-admin-panel'>
<div className='brain-admin-heading'>
<div>
<span>{t('企业专家治理')}</span>
<h2>{t('控制全企业可见的精选专家')}</h2>
<p>
{t(
'关闭后员工无法创建新任务,已经开始的任务会按安全策略停止或完成结算。',
)}
</p>
</div>
<BetaBadge />
</div>
{metrics && (
<div className='brain-admin-metrics'>
<div>
<span>{t('近30天任务')}</span>
<strong>{metrics.total_runs}</strong>
</div>
<div>
<span>{t('任务完成率')}</span>
<strong>
{formatPercent(Number(metrics.completion_rate) * 100, 1)}
</strong>
</div>
<div>
<span>{t('平均耗时')}</span>
<strong>{Math.round(metrics.average_duration_seconds)}s</strong>
</div>
<div>
<span>{t('用户认可率')}</span>
<strong>
{metrics.feedback_count
? formatPercent(Number(metrics.useful_rate) * 100, 1)
: '—'}
</strong>
</div>
</div>
)}
<div className='brain-admin-scope'>
<div>
<span>{t('配置范围')}</span>
<strong>{t('按企业、部门、项目或成员分发专家')}</strong>
</div>
<Select
value={assignmentScope}
onChange={(value) => {
setAssignmentScope(value);
setAssignmentScopeId(0);
}}
optionList={[
{ label: t('全企业'), value: 'organization' },
{ label: t('部门'), value: 'department' },
{ label: t('项目'), value: 'project' },
{ label: t('成员'), value: 'member' },
]}
/>
{assignmentScope !== 'organization' && (
<Select
value={assignmentScopeId || undefined}
placeholder={t('选择具体范围')}
optionList={assignmentTargetOptions}
onChange={setAssignmentScopeId}
filter
/>
)}
</div>
<div className='brain-admin-grid'>
{expertCatalog.map((expert) => {
const enabled = assignmentEnabled(expert.id);
return (
<article key={expert.id}>
<div>
<strong>{expert.name}</strong>
<p>{expert.description}</p>
</div>
<div
className={`brain-admin-toggle ${enabled ? 'is-on' : ''}`}
>
<span>{t(enabled ? '已启用' : '已停用')}</span>
<Switch
checked={enabled}
disabled={
assignmentScope !== 'organization' && !assignmentScopeId
}
aria-label={expert.name}
onChange={(checked) =>
setOrganizationExpertEnabled(expert.id, checked)
}
/>
</div>
</article>
);
})}
</div>
{residualAssignments.length > 0 && (
<div className='brain-admin-residual'>
<div className='brain-admin-residual-head'>
<strong>{t('残留分发规则')}</strong>
<span>
{t(
'这些规则的部门/项目/成员已被删除或停用,当前不生效;一旦对应主体恢复启用会立即复活,建议清理。',
)}
</span>
</div>
{residualAssignments.map((item) => (
<div key={item.id} className='brain-admin-residual-row'>
<Tag size='small' color={item.scope_exists ? 'grey' : 'red'}>
{item.scope_exists ? t('已停用') : t('已删除')}
</Tag>
<span className='brain-admin-residual-scope'>
{item.scope_type_label} · {item.scope_label}
</span>
<span className='brain-admin-residual-expert'>
{item.expert_name} ·{' '}
{t(item.enabled ? '规则为启用' : '规则为停用')}
</span>
<Popconfirm
title={t('确认删除该分发规则?')}
content={t(
'删除后该范围回落到上层默认(企业级规则或默认可用)。',
)}
onConfirm={() => deleteOrganizationAssignment(item.id)}
>
<Button size='small' theme='light' type='danger'>
{t('删除')}
</Button>
</Popconfirm>
</div>
))}
</div>
)}
</section>
) : view === 'experts' ? (
<div
className={`brain-expert-layout ${selectedExpert ? 'is-composing' : ''}`}
>
<div className='brain-expert-grid'>
{experts.length === 0 && (
<div className='brain-experts-empty'>
<Empty
title={t('当前没有可用专家')}
description={t('请联系管理员启用专家,或稍后再试。')}
/>
</div>
)}
{experts.map((expert, index) => {
const presentation = expertPresentation[expert.key] || {
icon: FileText,
tone: 'is-coral',
};
const Icon = presentation.icon;
return (
<article
key={expert.id}
className={`brain-expert-card brain-reveal brain-reveal--${Math.min(index + 1, 4)} ${selectedExpert?.id === expert.id ? 'is-selected' : ''}`}
onClick={() => {
// 拖选卡内文字松手也会派发 click,而撰写态会把描述
// display:none 连选区一起销毁——复制操作优先。
if (window.getSelection()?.toString()) return;
setSelectedExpert(expert);
}}
>
<div className='brain-card-topline'>
<span className={`brain-expert-icon ${presentation.tone}`}>
<Icon size={22} />
</span>
{expert.beta && <BetaBadge />}
</div>
<h2>{expert.name}</h2>
<p>{expert.description}</p>
<div className='brain-scenario'>{expert.scenario}</div>
<div className='brain-skill-list' aria-label={t('审核技能')}>
{(expert.skills || []).map((skill) => (
<span key={skill.id} title={skill.description}>
<CheckCircle2 size={12} /> {skill.name}{' '}
{I18N_TECHNICAL_TEXT.VERSION_PREFIX}
{skill.version}
</span>
))}
</div>
<div className='brain-section-chips'>
{(expert.required_sections || [])
.slice(0, 3)
.map((section) => (
<span key={section}>{section}</span>
))}
</div>
<button
type='button'
className='app-action-button brain-card-action'
onClick={(event) => {
// 阻断冒泡到整卡 onClick,避免同一动作双触发
event.stopPropagation();
setSelectedExpert(expert);
}}
>
{t('开始任务')} <ActionArrowRight size={16} />
</button>
</article>
);
})}
</div>
<aside
className={`brain-composer ${selectedExpert ? 'is-open' : ''}`}
>
{selectedExpert ? (
<>
<button
type='button'
className='app-action-button brain-back'
onClick={() => setSelectedExpert(null)}
>
<ActionArrowLeft size={16} /> {t('返回专家列表')}
</button>
<div className='brain-composer-heading'>
<span className='brain-composer-mark'>
<Sparkles size={20} />
</span>
<div>
<span>{t('当前专家')}</span>
<h2>{selectedExpert.name}</h2>
</div>
</div>
<label htmlFor='brain-task-input'>{t('描述你的任务')}</label>
<p className='brain-input-hint'>
{t(
'请提供目标、受众、已知事实和限制条件。信息越完整,成果越接近可交付状态。',
)}
</p>
{organization && selectableProjects.length > 0 && (
<div className='brain-project-field'>
<label>{t('关联项目(可选)')}</label>
<Select
value={projectId || undefined}
placeholder={t('不关联项目')}
optionList={selectableProjects.map((project) => ({
label: project.name,
value: project.id,
}))}
onChange={(value) => setProjectId(value || 0)}
showClear
filter
/>
<small>
{t('关联后会应用该项目的模型范围、预算和专家分发策略。')}
</small>
</div>
)}
<TextArea
id='brain-task-input'
value={input}
onChange={setInput}
maxCount={20000}
autosize={{ minRows: 12, maxRows: 22 }}
placeholder={t(
'例如:为下周经营会整理一份项目进展汇报。受众是管理层,重点说明目标达成、延期风险、需要决策的事项…',
)}
/>
{!organization && personalSkills.length > 0 && (
<div className='brain-skill-picker'>
<div className='brain-skill-picker-head'>
<span>{t('本次使用的技能')}</span>
<small>
{t('不勾选也会按任务描述自动匹配;最多同时生效 5 个。')}
</small>
</div>
<div className='brain-skill-picker-list'>
{personalSkills.map((skill) => {
const checked = manualSkillIds.includes(skill.skill_id);
const atLimit = manualSkillIds.length >= 5 && !checked;
return (
<button
type='button'
key={skill.skill_id}
title={skill.description}
disabled={atLimit}
className={[
'app-action-button',
`brain-skill-chip ${checked ? 'is-checked' : ''}`,
]
.filter(Boolean)
.join(' ')}
onClick={() =>
setManualSkillIds((previous) =>
previous.includes(skill.skill_id)
? previous.filter(
(id) => id !== skill.skill_id,
)
: [...previous, skill.skill_id],
)
}
>
{checked ? <ActionCheckCircle2 size={13} /> : null}
{skill.name || skill.canonical_id}
</button>
);
})}
</div>
</div>
)}
<div className='brain-attachments'>
<input
ref={attachmentInputRef}
type='file'
accept='.txt,.md,.docx,.pdf'
hidden
onChange={uploadAttachment}
/>
<Button
icon={<ActionFileUp size={16} />}
loading={attachmentBusy}
disabled={attachmentBusy || attachments.length >= 5}
onClick={() => attachmentInputRef.current?.click()}
>
{t('添加安全附件')}
</Button>
<small>
{t(
'最多 5 个;单个 10 MiB、合计 25 MiB。完成病毒扫描和隔离解析后才能提交。',
)}
</small>
{attachments.map((attachment) => (
<div className='brain-attachment-chip' key={attachment.id}>
<FileText size={15} />
<span>{attachment.original_name}</span>
<em>
{t(
attachment.status === 'ready'
? '安全检查通过'
: '安全处理中',
)}
</em>
<button
className='app-action-button'
type='button'
aria-label={t('移除附件')}
onClick={() => removeAttachment(attachment)}
>
<ActionX size={14} />
</button>
</div>
))}
</div>
<div className='brain-privacy-note'>
<CheckCircle2 size={15} />
{t(
'仅使用你提供的信息,不虚构数据;任务过程和产物可随时回看。',
)}
</div>
<Button
theme='solid'
type='primary'
size='large'
block
icon={<ActionSend size={17} />}
loading={submitting}
disabled={
!input.trim() ||
attachmentBusy ||
attachments.some((item) => item.status !== 'ready')
}
onClick={createRun}
>
{t('提交给云端专家')}
</Button>
</>
) : (
<div className='brain-composer-empty'>
<span>
<MessageSquareMore size={26} />
</span>
<h3>{t('先选择一位专家')}</h3>
<p>{t('右侧会显示清晰的任务说明和提交入口。')}</p>
</div>
)}
</aside>
</div>
) : (
<div className='brain-runs-layout'>
<aside className='brain-run-list app-scrollbar'>
<div className='brain-list-heading'>
<div>
<span>{t('任务记录')}</span>
<strong>{runs.length}</strong>
</div>
<Button
icon={<ActionRotateCcw size={15} />}
onClick={loadRuns}
aria-label={t('刷新任务')}
/>
</div>
{runs.length === 0 ? (
<Empty
title={t('还没有专家任务')}
description={t('从专家广场开始第一个任务')}
/>
) : (
runs.map((run) => {
const expert = expertById.get(run.expert_id);
return (
<button
type='button'
key={run.id}
className={`brain-run-item ${selectedRunId === run.id ? 'is-selected' : ''}`}
onClick={() => selectRunAndReveal(run.id)}
>
<div className='brain-run-item-top'>
<span>{expert?.name || t('云端专家')}</span>
<StatusPill status={run.status} />
</div>
<p>{run.input_text}</p>
<time>{safeDate(run.created_at, i18n.language)}</time>
</button>
);
})
)}
</aside>
<main className='brain-run-detail' ref={runDetailRef}>
{!selectedRunId ? (
<div className='brain-detail-empty'>
<span>
<ListChecks size={30} />
</span>
<h2>{t('选择一个任务查看完整过程')}</h2>
<p>
{t('执行状态、关键事件、结算状态和最终产物都会保留在这里。')}
</p>
</div>
) : detailLoading ? (
<div className='brain-loading'>
<Spin size='large' />
</div>
) : activeRun ? (
<>
<div className='brain-detail-header'>
<div>
<div className='brain-detail-kicker'>
{expertById.get(activeRun.expert_id)?.name ||
t('云端专家')}
<BetaBadge />
</div>
<h2>{t('专家任务产物')}</h2>
<div className='brain-detail-meta'>
<StatusPill status={activeRun.status} />
<span>
{safeDate(activeRun.created_at, i18n.language)}
</span>
<span>
<Trans
t={t}
i18nKey='计费状态: {{label}}'
values={{ label: t(activeRun.billing_status) }}
/>
</span>
{activeRun.started_at > 0 &&
activeRun.finished_at > 0 && (
<span>
{t('耗时')}:{' '}
{elapsedText(
activeRun.started_at,
activeRun.finished_at,
)}
</span>
)}
{!terminalStatuses.has(activeRun.status) && (
<span
className={`brain-stream-state brain-stream-state--${streamState}`}
>
{streamState === 'reconnecting'
? t('事件连接正在恢复')
: streamState === 'connected'
? t('进度已实时连接')
: t('正在连接任务进度')}
</span>
)}
</div>
<div className='brain-detail-skills'>
<span>{t('本次专家使用的审核技能')}</span>
{(expertById.get(activeRun.expert_id)?.skills || []).map(
(skill) => (
<small key={skill.id}>
{skill.name} {I18N_TECHNICAL_TEXT.VERSION_PREFIX}
{skill.version} · {skill.license}
</small>
),
)}
</div>
</div>
<div className='brain-detail-actions'>
{!terminalStatuses.has(activeRun.status) && (
<Button onClick={cancelRun}>{t('取消任务')}</Button>
)}
{runDetail.artifact?.content && (
<Button
icon={<ActionCopy size={15} />}
onClick={copyArtifact}
>
{t('复制')}
</Button>
)}
{runDetail.artifact?.content &&
terminalStatuses.has(activeRun.status) && (
<Button
icon={<ActionRotateCcw size={15} />}
onClick={() => setRevisionOpen((open) => !open)}
>
{t('修订产物')}
</Button>
)}
</div>
</div>
<section className='brain-source-card'>
<span>
{activeRun.revision_number > 0
? t('第 {{number}} 次修订要求', {
number: activeRun.revision_number,
})
: t('任务输入')}
</span>
<p>{activeRun.input_text}</p>
</section>
{revisionOpen && (
<section className='brain-revision-card'>
<div>
<span>{t('创建新修订')}</span>
<strong>{t('说明希望保留、调整或补充的内容')}</strong>
<p>
{t(
'新任务会引用当前产物,原任务、历史版本和计费记录不会被覆盖。',
)}
</p>
</div>
<TextArea
value={revisionInstruction}
onChange={setRevisionInstruction}
maxCount={10000}
autosize={{ minRows: 4, maxRows: 10 }}
placeholder={t(
'例如:保留风险与行动项,将核心结论压缩为三点,并补充一段面向管理层的决策建议。',
)}
/>
<div className='brain-revision-actions'>
<Button onClick={() => setRevisionOpen(false)}>
{t('暂不修订')}
</Button>
<Button
theme='solid'
type='primary'
icon={<ActionSend size={15} />}
loading={revising}
disabled={!revisionInstruction.trim()}
onClick={reviseRun}
>
{t('提交修订')}
</Button>
</div>
</section>
)}
{!terminalStatuses.has(activeRun.status) && (
<section className='brain-progress-card'>
<div className='brain-progress-beacon'>
<Sparkles size={19} />
</div>
<div>
<strong>
{activeRun.status === 'queued'
? t('任务正在排队')
: t('专家正在组织内容')}
</strong>
{activeRun.status !== 'queued' &&
Number(activeRun.total_steps || 0) > 0 && (
<p className='brain-progress-step'>
{t('第 {{current}}/{{total}} 步', {
current: Math.min(
Number(activeRun.completed_steps || 0) + 1,
Number(activeRun.total_steps),
),
total: Number(activeRun.total_steps),
})}
{runningStep?.step_name
? ` · ${runningStep.step_name}`
: ''}
</p>
)}
<p>{t('可以离开此页面,任务会在云端继续执行。')}</p>
</div>
<span className='brain-progress-line' />
</section>
)}
{(runDetail.confirmations || [])
.filter((confirmation) => confirmation.status === 'pending')
.map((confirmation) => (
<section
className='brain-confirm-card'
key={confirmation.id}
>
<div className='brain-confirm-heading'>
<TriangleAlert size={19} />
<div>
<span>{t('需要人工确认')}</span>
<strong>
{t('专家请求执行 {{method}}', {
method: confirmation.method_key,
})}
</strong>
<p>
{t(
'参数已冻结;确认时服务端会再次校验 Connector、授权、凭据和预算。',
)}
</p>
</div>
</div>
<details>
<summary>{t('查看冻结参数')}</summary>
<pre className='app-scrollbar'>
{(() => {
try {
return JSON.stringify(
JSON.parse(confirmation.parameters),
null,
2,
);
} catch {
return confirmation.parameters;
}
})()}
</pre>
</details>
<TextArea
value={confirmationReason}
onChange={setConfirmationReason}
maxCount={500}
placeholder={t(
'填写确认或拒绝原因(至少 2 个字符,将进入审计)',
)}
/>
<div className='brain-confirm-actions'>
<Button
type='danger'
disabled={confirmationReason.trim().length < 2}
loading={confirmationBusy}
onClick={() =>
decideToolConfirmation(confirmation, false)
}
>
{t('拒绝操作')}
</Button>
<Button
theme='solid'
disabled={confirmationReason.trim().length < 2}
loading={confirmationBusy}
onClick={() =>
decideToolConfirmation(confirmation, true)
}
>
{t('确认并继续')}
</Button>
</div>
</section>
))}
{activeRun.error_message && (
<section className='brain-error-card'>
<TriangleAlert size={18} />
<div>
<strong>{t('任务未能完成')}</strong>
<p>
{t(
runErrorMessages[activeRun.error_code] ||
failureReason.reason ||
activeRun.error_message,
)}
</p>
{runErrorMessages[activeRun.error_code] &&
failureReason.reason && (
<p className='brain-error-reason'>
<Trans
t={t}
i18nKey='失败原因:{{label}}'
values={{ label: t(failureReason.reason) }}
/>
</p>
)}
{(failureReason.raw || activeRun.error_code) && (
<details className='brain-error-detail'>
<summary>{t('查看技术详情')}</summary>
{activeRun.error_code && (
<p>
{t('错误码')}:{activeRun.error_code}
</p>
)}
{failureReason.raw && (
<pre className='app-scrollbar'>
{failureReason.raw}
</pre>
)}
</details>
)}
<Button
className='brain-error-copy'
size='small'
theme='light'
type='danger'
icon={<ActionCopy size={13} />}
onClick={copyErrorReport}
>
{t('复制报错信息')}
</Button>
</div>
</section>
)}
{runDetail.artifact?.artifact_type !== 'file' &&
runDetail.artifact?.content && (
<article className='brain-artifact'>
<div className='brain-artifact-label'>
<FileText size={16} /> {t('最终产物')}
</div>
<div className='brain-markdown'>
<ReactMarkdown remarkPlugins={[remarkGfm]}>
{runDetail.artifact.content}
</ReactMarkdown>
</div>
<footer>
<span>{t('这份成果对你有帮助吗?')}</span>
<div>
{organization && (
<button
type='button'
className='brain-time-confirm'
onClick={() => {
setTimeConfirmation({
confirmed_manual_minutes: 30,
actual_minutes: Math.max(
0,
Math.ceil(
Number(
activeRun.active_execution_ms || 0,
) / 60000,
),
),
comment: '',
});
setTimeConfirmOpen(true);
}}
>
{t('确认节省时间')}
</button>
)}
<button
className={[
'app-action-button',
feedback === 'useful' ? 'is-active' : '',
]
.filter(Boolean)
.join(' ')}
onClick={() => submitFeedback('useful')}
aria-label={t('有帮助')}
>
<ActionThumbsUp size={16} />
</button>
<button
className={[
'app-action-button',
feedback === 'not_useful' ? 'is-active' : '',
]
.filter(Boolean)
.join(' ')}
onClick={() => submitFeedback('not_useful')}
aria-label={t('没有帮助')}
>
<ActionThumbsDown size={16} />
</button>
</div>
</footer>
</article>
)}
{runDetail.artifact?.artifact_type === 'file' && (
<article className='brain-artifact'>
<div className='brain-artifact-label'>
<FileText size={16} /> {t('文件产物')}
</div>
<div className='brain-artifact-file'>
<div>
<strong>{runDetail.artifact.file_name}</strong>
<span>
{runDetail.artifact.content_type} ·{' '}
{Math.ceil(
Number(runDetail.artifact.size_bytes || 0) / 1024,
)}{' '}
{I18N_TECHNICAL_TEXT.KIB_SEPARATOR}{' '}
{t('恶意软件扫描已通过')}
</span>
</div>
<Button
theme='solid'
icon={<ActionDownload size={16} />}
onClick={downloadArtifact}
>
{t('获取短期下载链接')}
</Button>
</div>
</article>
)}
{!runDetail.artifact && runDetail.snapshot?.content && (
<article className='brain-artifact'>
<div className='brain-artifact-label'>
<FileText size={16} /> {t('生成中的输出快照')}
</div>
<div className='brain-markdown'>
<ReactMarkdown remarkPlugins={[remarkGfm]}>
{runDetail.snapshot.content}
</ReactMarkdown>
</div>
</article>
)}
{(runDetail.citations || []).length > 0 && (
<section className='brain-citations'>
<div className='brain-citations-heading'>
<BookOpenCheck size={17} />
<div>
<strong>{t('企业知识来源')}</strong>
<span>
{t('仅展示本次任务实际注入并经权限校验的来源')}
</span>
</div>
</div>
<div className='brain-citation-list'>
{runDetail.citations.map((citation) => (
<div key={citation.id} className='brain-citation-row'>
<b>[{citation.citation_id}]</b>
<span>{citation.source_label}</span>
<small>
{t('相关度')}{' '}
{formatPercent(Number(citation.score) * 100, 1)}
</small>
</div>
))}
</div>
</section>
)}
{runSteps.length > 0 && (
<section className='brain-steps'>
<h3>{t('执行步骤')}</h3>
{runSteps.map((step) => {
const meta = stepStatusMeta[step.status];
const facts = [
step.actual_model,
stepDurationText(step),
stepTokenText(step),
].filter(Boolean);
return (
<article
key={step.id}
className={`brain-step brain-step--${meta?.tone || 'pending'}`}
>
<span className='brain-step-seq'>
{step.step_seq}
</span>
<div>
<strong>{step.step_name || step.step_key}</strong>
{facts.length > 0 && (
<small>{facts.join(' · ')}</small>
)}
</div>
<code>{t(meta?.label || step.status)}</code>
</article>
);
})}
</section>
)}
{(runDetail.tool_calls || []).length > 0 && (
<section className='brain-tool-timeline'>
<h3>{t('工具调用轨迹')}</h3>
{(runDetail.tool_calls || []).map((call) => (
<article key={call.id}>
<span
className={`brain-tool-state brain-tool-state--${call.status}`}
/>
<div>
<strong>{call.method_key}</strong>
<small>
{t('第 {{round}} 轮', { round: call.round })} ·{' '}
{call.operation_type}
</small>
</div>
<code>{call.status}</code>
</article>
))}
</section>
)}
<section className='brain-timeline'>
<h3>{t('任务时间线')}</h3>
{timelineItems.map((item) => (
<div key={item.id} className='brain-timeline-item'>
<span />
<div>
<strong>{item.label}</strong>
{item.summary && (
<small className='brain-timeline-summary'>
{item.summary}
</small>
)}
<time>
{item.time}
{item.gap ? ` · +${item.gap}` : ''}
</time>
</div>
</div>
))}
</section>
</>
) : null}
</main>
</div>
)}
<Modal
title={t('确认本任务人工耗时')}
visible={timeConfirmOpen}
onCancel={() => setTimeConfirmOpen(false)}
onOk={submitTimeConfirmation}
>
<div className='brain-time-confirm-form'>
<label>{t('不用 Agent 时预计需要的分钟数')}</label>
<InputNumber
min={1}
max={1440}
value={timeConfirmation.confirmed_manual_minutes}
onChange={(confirmed_manual_minutes) =>
setTimeConfirmation({
...timeConfirmation,
confirmed_manual_minutes,
})
}
/>
<label>{t('本次实际投入分钟数')}</label>
<InputNumber
min={0}
max={1440}
value={timeConfirmation.actual_minutes}
onChange={(actual_minutes) =>
setTimeConfirmation({ ...timeConfirmation, actual_minutes })
}
/>
<TextArea
placeholder={t('可选:说明估算依据')}
maxCount={500}
value={timeConfirmation.comment}
onChange={(comment) =>
setTimeConfirmation({ ...timeConfirmation, comment })
}
/>
</div>
</Modal>
<PageGuideDrawer guide={guide} />
</section>
);
};
export default CloudBrain;