Merge remote-tracking branch 'origin/master' into ji
# Conflicts: # offline-backend-20260512/backend/app/gateway/app.py # offline-backend-20260512/backend/config.yaml # offline-backend-20260512/backend/packages/harness/deerflow/persistence/models/__init__.py # offline-backend-20260512/backend/packages/harness/deerflow/runtime/checkpointer/async_provider.py
This commit is contained in:
commit
87e0ae683e
112 files changed
+25039
-1804
No files matched your search
@@ -119,7 +119,8 @@
|
||||
border: 1px solid;
|
||||
border-color: rgba(43, 143, 254, 0.6);
|
||||
border-radius: 4px;
|
||||
backdrop-filter: blur(2px);
|
||||
backdrop-filter: blur(20px);
|
||||
-webkit-backdrop-filter: blur(20px);
|
||||
position: absolute;
|
||||
left: 108px;
|
||||
top: 0;
|
||||
|
||||
@@ -207,6 +207,12 @@ export const sidebarMenuItems: MenuItem[] = [
|
||||
icon: Settings,
|
||||
children: [
|
||||
{ id: "mgmt-agents", label: "智能体管理", icon: Bot, path: "/page/strategy/agents" },
|
||||
{
|
||||
id: "mgmt-business-chain-mapping",
|
||||
label: "业务链条管理",
|
||||
icon: Network,
|
||||
path: "/page/strategy/business-chain-mapping",
|
||||
},
|
||||
{ id: "mgmt-skills", label: "技能管理", icon: Sparkles, path: "/page/strategy/skills" },
|
||||
{ id: "mgmt-memory", label: "记忆管理", icon: Brain, path: "/page/strategy/memory" },
|
||||
{
|
||||
|
||||
@@ -0,0 +1,273 @@
|
||||
/**
|
||||
* 业务链条管理页 —— 把固定业务码(3Q/6BF/7BF/8BF)绑定到「智能体」+「业务链」。
|
||||
*
|
||||
* 表格三列:业务(只读)/ 智能体 / 业务链。编辑模式下后两列为可搜索下拉:
|
||||
* - 智能体来自 `/api/agents`
|
||||
* - 业务链来自 `/api/roundtable-chains?scope=public`(只列公共链,保证全局共享时各账号都能解析)
|
||||
* 保存调 `PUT /api/business-mapping/{code}`。映射全局共享、无用户隔离。
|
||||
*/
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { Loading, Select } from "tdesign-react";
|
||||
import { Link2, Pencil, Save, Users, X } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
|
||||
import { useTheme } from "@/contexts/ThemeContext";
|
||||
import { listAgents } from "@/core/agents/api";
|
||||
import type { Agent } from "@/core/agents/types";
|
||||
import { listChains } from "@/roundtable-planning/api/chains";
|
||||
import type { BusinessChain } from "@/roundtable-planning/lib/business-chain";
|
||||
import {
|
||||
listBusinessMappings,
|
||||
updateBusinessMapping,
|
||||
type BusinessMapping,
|
||||
} from "@/strategy-components/api/business-mapping";
|
||||
|
||||
interface DraftSelection {
|
||||
agentId: string | null;
|
||||
chainId: string | null;
|
||||
}
|
||||
|
||||
export default function BusinessChainMappingPage() {
|
||||
const { theme } = useTheme();
|
||||
const isDark = theme === "dark";
|
||||
|
||||
const [rows, setRows] = useState<BusinessMapping[]>([]);
|
||||
const [agents, setAgents] = useState<Agent[]>([]);
|
||||
const [chains, setChains] = useState<BusinessChain[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [editingCode, setEditingCode] = useState<string | null>(null);
|
||||
const [draft, setDraft] = useState<DraftSelection>({ agentId: null, chainId: null });
|
||||
const [saving, setSaving] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
(async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const [mappingRes, agentRes, chainRes] = await Promise.allSettled([
|
||||
listBusinessMappings(),
|
||||
listAgents(),
|
||||
listChains("public"),
|
||||
]);
|
||||
if (cancelled) return;
|
||||
if (mappingRes.status === "fulfilled") setRows(mappingRes.value);
|
||||
else toast.error(`加载业务映射失败:${mappingRes.reason}`);
|
||||
if (agentRes.status === "fulfilled") setAgents(agentRes.value);
|
||||
if (chainRes.status === "fulfilled") setChains(chainRes.value);
|
||||
} finally {
|
||||
if (!cancelled) setLoading(false);
|
||||
}
|
||||
})();
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, []);
|
||||
|
||||
const agentOptions = useMemo(
|
||||
() => agents.map((a) => ({ label: a.name || a.id, value: a.id })),
|
||||
[agents],
|
||||
);
|
||||
const chainOptions = useMemo(
|
||||
() => chains.map((c) => ({ label: c.title || c.id, value: c.id })),
|
||||
[chains],
|
||||
);
|
||||
|
||||
const beginEdit = (row: BusinessMapping) => {
|
||||
setEditingCode(row.businessCode);
|
||||
setDraft({ agentId: row.agentId, chainId: row.chainId });
|
||||
};
|
||||
|
||||
const cancelEdit = () => {
|
||||
setEditingCode(null);
|
||||
setDraft({ agentId: null, chainId: null });
|
||||
};
|
||||
|
||||
const handleSave = async (row: BusinessMapping) => {
|
||||
setSaving(true);
|
||||
try {
|
||||
const agentName = draft.agentId
|
||||
? agents.find((a) => a.id === draft.agentId)?.name ?? row.agentName ?? null
|
||||
: null;
|
||||
const chainTitle = draft.chainId
|
||||
? chains.find((c) => c.id === draft.chainId)?.title ?? row.chainTitle ?? null
|
||||
: null;
|
||||
const updated = await updateBusinessMapping(row.businessCode, {
|
||||
agentId: draft.agentId,
|
||||
agentName,
|
||||
chainId: draft.chainId,
|
||||
chainTitle,
|
||||
});
|
||||
if (!updated) {
|
||||
toast.error(`业务「${row.label}」不存在,保存失败`);
|
||||
return;
|
||||
}
|
||||
setRows((prev) => prev.map((r) => (r.businessCode === row.businessCode ? updated : r)));
|
||||
toast.success(`已保存「${row.label}」的配置`);
|
||||
cancelEdit();
|
||||
} catch (err) {
|
||||
toast.error(`保存失败:${(err as Error).message}`);
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const shellClass = isDark
|
||||
? "h-full overflow-y-auto bg-[linear-gradient(180deg,#081322_0%,#0d1d33_42%,#0a1628_100%)] text-slate-100"
|
||||
: "h-full overflow-y-auto bg-[linear-gradient(180deg,#fffdfd_0%,#fff7f7_42%,#fafafa_100%)] text-[#222222]";
|
||||
const cardClass = isDark
|
||||
? "border border-[rgba(67,89,124,0.46)] bg-[rgba(12,29,54,0.94)] shadow-[0_16px_36px_rgba(3,10,22,0.2)]"
|
||||
: "border border-[#E8E8E8] bg-white shadow-[0_14px_30px_rgba(245,34,45,0.06)]";
|
||||
const headRowClass = isDark ? "text-slate-400" : "text-[#8C8C8C]";
|
||||
const rowBorder = isDark ? "border-[rgba(67,89,124,0.32)]" : "border-[#F0F0F0]";
|
||||
const mutedText = isDark ? "text-slate-500" : "text-[#A6A6A6]";
|
||||
const codeBadge = isDark
|
||||
? "bg-[rgba(77,141,255,0.16)] text-[#9CCBFF]"
|
||||
: "bg-[#FFF1F0] text-[#CF1322]";
|
||||
|
||||
return (
|
||||
<div className={shellClass}>
|
||||
<div className="mx-auto flex min-h-full max-w-[1280px] flex-col gap-5 px-6 py-6 lg:px-8">
|
||||
<div className="space-y-1">
|
||||
<h1 className={`text-[26px] font-semibold tracking-[0.02em] ${isDark ? "text-slate-50" : "text-[#222222]"}`}>
|
||||
业务链条管理
|
||||
</h1>
|
||||
<p className={`text-sm ${isDark ? "text-slate-300/80" : "text-slate-500"}`}>
|
||||
为每个业务绑定智能体与业务链。多智能体会商从对应业务自动取用此处配置的业务链。业务链仅可选择「公共」链条。
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<Loading loading={loading} showOverlay={false}>
|
||||
<div className={`overflow-hidden rounded-3xl ${cardClass}`}>
|
||||
<table className="w-full border-collapse text-sm">
|
||||
<thead>
|
||||
<tr className={`text-left text-xs uppercase tracking-widest ${headRowClass}`}>
|
||||
<th className="px-6 py-4 font-semibold">业务</th>
|
||||
<th className="px-6 py-4 font-semibold">智能体</th>
|
||||
<th className="px-6 py-4 font-semibold">业务链</th>
|
||||
<th className="px-6 py-4 text-right font-semibold">操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{rows.length === 0 && !loading ? (
|
||||
<tr>
|
||||
<td colSpan={4} className={`px-6 py-12 text-center ${mutedText}`}>
|
||||
暂无业务数据
|
||||
</td>
|
||||
</tr>
|
||||
) : (
|
||||
rows.map((row) => {
|
||||
const editing = editingCode === row.businessCode;
|
||||
return (
|
||||
<tr key={row.businessCode} className={`border-t ${rowBorder}`}>
|
||||
{/* 业务(只读) */}
|
||||
<td className="px-6 py-4 align-middle">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className={`text-[15px] font-semibold ${isDark ? "text-white" : "text-[#222222]"}`}>
|
||||
{row.label}
|
||||
</span>
|
||||
<span className={`rounded-full px-2 py-0.5 text-[11px] font-mono ${codeBadge}`}>
|
||||
{row.businessCode}
|
||||
</span>
|
||||
</div>
|
||||
</td>
|
||||
|
||||
{/* 智能体 */}
|
||||
<td className="px-6 py-4 align-middle">
|
||||
{editing ? (
|
||||
<Select
|
||||
className="min-w-[200px]"
|
||||
value={draft.agentId ?? undefined}
|
||||
options={agentOptions}
|
||||
filterable
|
||||
clearable
|
||||
placeholder="搜索并选择智能体"
|
||||
onChange={(v) => setDraft((d) => ({ ...d, agentId: (v as string) ?? null }))}
|
||||
/>
|
||||
) : (
|
||||
<span className="inline-flex items-center gap-1.5">
|
||||
<Users className={`h-3.5 w-3.5 ${mutedText}`} />
|
||||
{row.agentName || row.agentId ? (
|
||||
<span>{row.agentName || row.agentId}</span>
|
||||
) : (
|
||||
<span className={mutedText}>未配置</span>
|
||||
)}
|
||||
</span>
|
||||
)}
|
||||
</td>
|
||||
|
||||
{/* 业务链 */}
|
||||
<td className="px-6 py-4 align-middle">
|
||||
{editing ? (
|
||||
<Select
|
||||
className="min-w-[220px]"
|
||||
value={draft.chainId ?? undefined}
|
||||
options={chainOptions}
|
||||
filterable
|
||||
clearable
|
||||
placeholder="搜索并选择业务链(公共)"
|
||||
onChange={(v) => setDraft((d) => ({ ...d, chainId: (v as string) ?? null }))}
|
||||
/>
|
||||
) : (
|
||||
<span className="inline-flex items-center gap-1.5">
|
||||
<Link2 className={`h-3.5 w-3.5 ${mutedText}`} />
|
||||
{row.chainTitle || row.chainId ? (
|
||||
<span>{row.chainTitle || row.chainId}</span>
|
||||
) : (
|
||||
<span className={mutedText}>未配置</span>
|
||||
)}
|
||||
</span>
|
||||
)}
|
||||
</td>
|
||||
|
||||
{/* 操作 */}
|
||||
<td className="px-6 py-4 text-right align-middle">
|
||||
{editing ? (
|
||||
<div className="inline-flex items-center gap-2">
|
||||
<button
|
||||
type="button"
|
||||
disabled={saving}
|
||||
onClick={() => handleSave(row)}
|
||||
className={`inline-flex items-center gap-1 rounded-xl px-3 py-1.5 text-xs font-medium disabled:opacity-50 ${
|
||||
isDark ? "bg-[rgba(34,197,94,0.18)] text-[#86EFAC]" : "bg-[#EEFCF7] text-[#0F9D6C]"
|
||||
}`}
|
||||
>
|
||||
<Save className="h-3.5 w-3.5" />
|
||||
保存
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
disabled={saving}
|
||||
onClick={cancelEdit}
|
||||
className={`inline-flex items-center gap-1 rounded-xl px-3 py-1.5 text-xs font-medium disabled:opacity-50 ${
|
||||
isDark ? "bg-[rgba(110,136,176,0.18)] text-slate-300" : "bg-[#F5F5F5] text-[#575757]"
|
||||
}`}
|
||||
>
|
||||
<X className="h-3.5 w-3.5" />
|
||||
取消
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => beginEdit(row)}
|
||||
className={`inline-flex items-center gap-1 rounded-xl px-3 py-1.5 text-xs font-medium ${
|
||||
isDark ? "bg-[rgba(77,141,255,0.16)] text-[#9CCBFF]" : "bg-[#FFF1F0] text-[#CF1322]"
|
||||
}`}
|
||||
>
|
||||
<Pencil className="h-3.5 w-3.5" />
|
||||
编辑
|
||||
</button>
|
||||
)}
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
})
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</Loading>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -17,6 +17,7 @@ import {
|
||||
} from "@/components/workspace/messages";
|
||||
import { ThreadContext } from "@/components/workspace/messages/context";
|
||||
import { TodoList } from "@/components/workspace/todo-list";
|
||||
import { getAccessToken } from "@/core/auth";
|
||||
import { useI18n } from "@/core/i18n/hooks";
|
||||
import { useModels } from "@/core/models/hooks";
|
||||
import { useNotification } from "@/core/notification/hooks";
|
||||
@@ -33,6 +34,13 @@ import {
|
||||
} from "./iframe-chat-submit";
|
||||
|
||||
type BrainyChatStatus = "started" | "finished";
|
||||
type BrainyAuthTokenMessage = {
|
||||
source: "brainy-iframe";
|
||||
type: "brainy:auth-token";
|
||||
payload: {
|
||||
accessToken: string;
|
||||
};
|
||||
};
|
||||
type BrainyChatInterruptMessage = {
|
||||
source?: string;
|
||||
type?: string;
|
||||
@@ -57,6 +65,18 @@ function postBrainyChatStatus(status: BrainyChatStatus, requestId: string) {
|
||||
);
|
||||
}
|
||||
|
||||
function postBrainyAuthToken(accessToken: string) {
|
||||
const message: BrainyAuthTokenMessage = {
|
||||
source: "brainy-iframe",
|
||||
type: "brainy:auth-token",
|
||||
payload: {
|
||||
accessToken,
|
||||
},
|
||||
};
|
||||
|
||||
window.parent?.postMessage(message, "*");
|
||||
}
|
||||
|
||||
export default function IframeChatPage() {
|
||||
const routeBase = useRouteBase();
|
||||
const router = useRouter();
|
||||
@@ -79,6 +99,28 @@ export default function IframeChatPage() {
|
||||
setMounted(true);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
let lastToken: string | undefined;
|
||||
|
||||
const emitAccessToken = () => {
|
||||
const accessToken = getAccessToken();
|
||||
if (!accessToken || accessToken === lastToken) {
|
||||
return;
|
||||
}
|
||||
lastToken = accessToken;
|
||||
postBrainyAuthToken(accessToken);
|
||||
};
|
||||
|
||||
emitAccessToken();
|
||||
window.addEventListener("focus", emitAccessToken);
|
||||
window.addEventListener("storage", emitAccessToken);
|
||||
|
||||
return () => {
|
||||
window.removeEventListener("focus", emitAccessToken);
|
||||
window.removeEventListener("storage", emitAccessToken);
|
||||
};
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (isNewThread) {
|
||||
setHasStartedConversation(false);
|
||||
|
||||
@@ -20,6 +20,7 @@ import RoundtablePlanningPage from "@/roundtable-planning/pages/RoundtablePlanni
|
||||
import "@/roundtable-planning/styles/roundtable-planning.css";
|
||||
import AgentChatPage from "./AgentChatPage";
|
||||
import AgentsPage from "./AgentsPage";
|
||||
import BusinessChainMappingPage from "./BusinessChainMappingPage";
|
||||
import ChatPage from "./ChatPage";
|
||||
import ChatsPage from "./ChatsPage";
|
||||
import AdminUserLeaderboardPage from "./AdminUserLeaderboardPage";
|
||||
@@ -106,9 +107,9 @@ export default function StrategyRoutes() {
|
||||
path="plan-task/plan-task-fx"
|
||||
element={
|
||||
<TaskAnalyzes
|
||||
title="æµ è¯²å§ŸFX"
|
||||
category="ç‘™å‹«åžæµ 诲姟"
|
||||
subCategory="ç‘™å‹«åžæµ 诲姟"
|
||||
title="任务分析"
|
||||
category="规划任务"
|
||||
subCategory="规划任务"
|
||||
/>
|
||||
}
|
||||
/>
|
||||
@@ -172,6 +173,7 @@ export default function StrategyRoutes() {
|
||||
<Route path="skills" element={<SkillsPage />} />
|
||||
<Route path="skills/evolution" element={<SkillEvolutionPage />} />
|
||||
<Route path="memory" element={<MemoryPage />} />
|
||||
<Route path="business-chain-mapping" element={<BusinessChainMappingPage />} />
|
||||
|
||||
<Route
|
||||
path="scheduled"
|
||||
|
||||
@@ -22,6 +22,12 @@ export interface ChainCreatePayload {
|
||||
title: string;
|
||||
description?: string;
|
||||
seats: ChainSeat[];
|
||||
/** Optional layered orchestration (agent_id groups). null/absent = linear. */
|
||||
stages?: string[][] | null;
|
||||
/** Optional per-stage goals aligned to `stages` (dag-only). null = none. */
|
||||
stageGoals?: (string | null)[] | null;
|
||||
/** Optional coordinator orchestration prompt (dag-only). null/"" = none. */
|
||||
coordinatorPrompt?: string | null;
|
||||
}
|
||||
|
||||
/** Partial update — send only what changed. */
|
||||
@@ -29,8 +35,19 @@ export interface ChainUpdatePayload {
|
||||
title?: string;
|
||||
description?: string;
|
||||
seats?: ChainSeat[];
|
||||
/** Send `null` to clear layering back to linear; omit to leave unchanged. */
|
||||
stages?: string[][] | null;
|
||||
/** Per-stage goals aligned to `stages`; send `null` to clear, omit to leave. */
|
||||
stageGoals?: (string | null)[] | null;
|
||||
/** 写给总控的编排提示;send `null`/"" to clear, omit to leave. */
|
||||
coordinatorPrompt?: string | null;
|
||||
/** 发布开关:true 发布为公共 / false 取消发布;omit 不改。仅 owner 生效。 */
|
||||
isPublic?: boolean;
|
||||
}
|
||||
|
||||
/** 列表筛选范围:`mine` = 我的;`public` = 所有已发布的公共链条。 */
|
||||
export type ChainScope = "mine" | "public";
|
||||
|
||||
const BASE = () => `${getBackendBaseURL()}/api/roundtable-chains`;
|
||||
|
||||
async function readJson<T>(res: Response, ctx: string): Promise<T> {
|
||||
@@ -50,6 +67,11 @@ interface ServerChain {
|
||||
title: string;
|
||||
description: string | null;
|
||||
seats: ChainSeat[];
|
||||
stages?: string[][] | null;
|
||||
stage_goals?: (string | null)[] | null;
|
||||
coordinator_prompt?: string | null;
|
||||
is_public?: boolean;
|
||||
is_mine?: boolean;
|
||||
created_at: string | null;
|
||||
updated_at: string | null;
|
||||
}
|
||||
@@ -60,6 +82,12 @@ function toChain(s: ServerChain): BusinessChain {
|
||||
title: s.title ?? "",
|
||||
description: s.description ?? undefined,
|
||||
seats: Array.isArray(s.seats) ? s.seats : [],
|
||||
stages: Array.isArray(s.stages) ? s.stages : null,
|
||||
stageGoals: Array.isArray(s.stage_goals) ? s.stage_goals : null,
|
||||
coordinatorPrompt: s.coordinator_prompt ?? null,
|
||||
isPublic: s.is_public ?? false,
|
||||
// 后端缺省时按「我的」处理(向后兼容旧响应)。
|
||||
isMine: s.is_mine ?? true,
|
||||
createdAt: s.created_at ?? undefined,
|
||||
updatedAt: s.updated_at ?? undefined,
|
||||
};
|
||||
@@ -71,6 +99,9 @@ function fromCreate(p: ChainCreatePayload) {
|
||||
title: p.title,
|
||||
...(p.description !== undefined ? { description: p.description } : {}),
|
||||
seats: p.seats,
|
||||
...(p.stages !== undefined ? { stages: p.stages } : {}),
|
||||
...(p.stageGoals !== undefined ? { stage_goals: p.stageGoals } : {}),
|
||||
...(p.coordinatorPrompt !== undefined ? { coordinator_prompt: p.coordinatorPrompt } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -79,18 +110,34 @@ function fromUpdate(p: ChainUpdatePayload) {
|
||||
if (p.title !== undefined) out.title = p.title;
|
||||
if (p.description !== undefined) out.description = p.description;
|
||||
if (p.seats !== undefined) out.seats = p.seats;
|
||||
// Forward stages even when explicitly null (clears layering server-side).
|
||||
if (p.stages !== undefined) out.stages = p.stages;
|
||||
// Forward stage goals even when explicitly null (clears goals server-side).
|
||||
if (p.stageGoals !== undefined) out.stage_goals = p.stageGoals;
|
||||
if (p.coordinatorPrompt !== undefined) out.coordinator_prompt = p.coordinatorPrompt;
|
||||
if (p.isPublic !== undefined) out.is_public = p.isPublic;
|
||||
return out;
|
||||
}
|
||||
|
||||
// ── CRUD ────────────────────────────────────────────────────────────────────
|
||||
|
||||
/** List the current user's chains, newest first. */
|
||||
export async function listChains(): Promise<BusinessChain[]> {
|
||||
const res = await apiFetch(BASE(), { method: "GET" });
|
||||
/**
|
||||
* List chains, newest first. `scope`:
|
||||
* - `"mine"`(默认):当前用户自己的链条;
|
||||
* - `"public"`:所有已发布的公共链条(任何账号可见 / 可选入研讨)。
|
||||
*/
|
||||
export async function listChains(scope: ChainScope = "mine"): Promise<BusinessChain[]> {
|
||||
const url = scope === "public" ? `${BASE()}?scope=public` : BASE();
|
||||
const res = await apiFetch(url, { method: "GET" });
|
||||
const data = await readJson<{ chains: ServerChain[] }>(res, "list chains");
|
||||
return (data.chains ?? []).map(toChain);
|
||||
}
|
||||
|
||||
/** 发布 / 取消发布一条链条(仅 owner 生效)。返回更新后的链条,404 返回 null。 */
|
||||
export async function setChainPublic(id: string, isPublic: boolean): Promise<BusinessChain | null> {
|
||||
return updateChain(id, { isPublic });
|
||||
}
|
||||
|
||||
/** Fetch one chain. Returns null on 404. */
|
||||
export async function getChain(id: string): Promise<BusinessChain | null> {
|
||||
const res = await apiFetch(`${BASE()}/${encodeURIComponent(id)}`, { method: "GET" });
|
||||
|
||||
@@ -17,6 +17,7 @@ import { getBackendBaseURL } from "@/core/config";
|
||||
|
||||
import type { IntentSummary } from "@/roundtable-planning/api/intent";
|
||||
import type { ThreadIdMap } from "@/roundtable-planning/api/multi-agent";
|
||||
import type { OrchestrationPlan } from "@/roundtable-planning/lib/dag-types";
|
||||
import type { JobStatus } from "@/roundtable-planning/lib/job-types";
|
||||
|
||||
/**
|
||||
@@ -50,20 +51,33 @@ export interface DraftStep2Snapshot {
|
||||
seatStubMessages?: Record<string, unknown[]>;
|
||||
/**
|
||||
* Step 2 orchestration mode (2026-06 business chains). recommend = leader
|
||||
* dispatches freely; chain = dispatch follows the saved business chain order.
|
||||
* Optional — drafts saved before this won't carry it (hydrate defaults to
|
||||
* "recommend").
|
||||
* dispatches freely; chain = dispatch follows the saved business chain order;
|
||||
* dag = layered Stage DAG (stage-internal parallel, stage-to-stage serial,
|
||||
* see `lib/dag-types.ts`). Optional — drafts saved before this won't carry it
|
||||
* (hydrate defaults to "recommend").
|
||||
*/
|
||||
orchestrationMode?: "recommend" | "chain";
|
||||
orchestrationMode?: "recommend" | "chain" | "dag";
|
||||
/** Source business chain (display only), when `orchestrationMode === "chain"`. */
|
||||
chain?: { id: string; title: string } | null;
|
||||
/**
|
||||
* Layered DAG plan, when `orchestrationMode === "dag"`. Persisted so a reloaded
|
||||
* draft restores the编排. Optional — null/absent for non-dag drafts. Old `chain`
|
||||
* drafts are converted on read via `chainToDagPlan` (compat, original draft
|
||||
* untouched).
|
||||
*/
|
||||
orchestrationPlan?: OrchestrationPlan | null;
|
||||
/**
|
||||
* dag 执行子模式:fast(并行双列禁写)/ sandbox(并行单列可写、沙箱跟随)。
|
||||
* 仅 `orchestrationMode === "dag"` 有意义;缺省 fast。
|
||||
*/
|
||||
dagExecMode?: "fast" | "sandbox";
|
||||
}
|
||||
|
||||
export interface DraftStep2RunSnapshot {
|
||||
id: string;
|
||||
title: string;
|
||||
createdAt: string;
|
||||
source: "initial" | "recommend" | "chain" | "manual";
|
||||
source: "initial" | "recommend" | "chain" | "dag" | "manual";
|
||||
selectedAgents?: Array<{ agent_id: string; name: string }>;
|
||||
threadIds: ThreadIdMap | null;
|
||||
coordinatorName: string | null;
|
||||
@@ -73,8 +87,11 @@ export interface DraftStep2RunSnapshot {
|
||||
consensusPercentage: number;
|
||||
budgetLimit: number;
|
||||
seatStubMessages?: Record<string, unknown[]>;
|
||||
orchestrationMode?: "recommend" | "chain";
|
||||
orchestrationMode?: "recommend" | "chain" | "dag";
|
||||
chain?: { id: string; title: string } | null;
|
||||
orchestrationPlan?: OrchestrationPlan | null;
|
||||
/** dag 执行子模式:fast / sandbox(见 DraftStep2Snapshot.dagExecMode)。 */
|
||||
dagExecMode?: "fast" | "sandbox";
|
||||
step3?: DraftStep3Snapshot | null;
|
||||
jobId?: string | null;
|
||||
jobStatus?: JobStatus | null;
|
||||
|
||||
@@ -203,6 +203,30 @@ export interface StreamMultiAgentRequest {
|
||||
newMessage: string;
|
||||
model?: string;
|
||||
skillStopNames?: string[];
|
||||
/**
|
||||
* 仅 leader 用。置 true 表示这是「派活后让总控判断继续/综合」的轮次:后端会把各已交付
|
||||
* 席位的**完整交付正文**额外注入总控输入,供其写最终方案。派活决策轮(首轮等)传 false/省略,
|
||||
* 后端只给摘要,使总控上下文精简、响应快。
|
||||
*/
|
||||
synthesisMode?: boolean;
|
||||
/**
|
||||
* 仅 leader 用。置 true 抑制「把总控本轮输入广播给各席位 thread」的预广播。DAG「每 stage
|
||||
* 派活轮」置真——否则总控的派活 prompt 会进席位历史,弱模型据此模仿派活。后端缺省 false。
|
||||
*/
|
||||
suppressPreBroadcast?: boolean;
|
||||
/**
|
||||
* 仅 special 用。置 true 表示这是 DAG 并行批次里的席位:后端按 `seat_parallel`
|
||||
* run policy **禁用** write_file / bash / str_replace / present_files 等写文件 /
|
||||
* 沙箱工具(§4),避免同批多席位并发抢同一沙箱。产物以消息正文交付。后端缺失
|
||||
* 该字段时按 false 处理(普通 seat policy),旧前端不受影响。
|
||||
*/
|
||||
parallelNoFile?: boolean;
|
||||
/**
|
||||
* 仅 special 用。前序席位的**完整交付** `[{name, content}]`。后端注入 run context
|
||||
* (`roundtable_peer_deliveries`),席位用 `read_peer_delivery` 工具**按需**取全文
|
||||
* (平时只看广播摘要)。不进 prompt → 不调工具就不耗 token。
|
||||
*/
|
||||
peerDeliveries?: Array<{ name: string; content: string }>;
|
||||
signal?: AbortSignal;
|
||||
/** Fires for every non-status data frame the upstream emits. */
|
||||
onUpstreamFrame?: (frame: unknown) => void;
|
||||
@@ -415,6 +439,14 @@ export async function streamMultiAgent(
|
||||
new_message: req.newMessage,
|
||||
model: req.model,
|
||||
skill_stop_names: req.skillStopNames ?? [],
|
||||
// 仅 leader 用;综合轮让后端注入各席位完整交付正文。省略 → 后端按 false 处理。
|
||||
synthesis_mode: req.synthesisMode ?? false,
|
||||
// 仅 leader 用;DAG 派活轮抑制预广播,避免总控派活 prompt 污染席位 thread。省略 → false。
|
||||
suppress_pre_broadcast: req.suppressPreBroadcast ?? false,
|
||||
// 仅 special 用;DAG 并行批次禁写文件(seat_parallel policy)。省略 → 后端按 false 处理。
|
||||
parallel_no_file: req.parallelNoFile ?? false,
|
||||
// 仅 special 用;前序席位完整交付,后端注入 context 供 read_peer_delivery 按需取全文。
|
||||
peer_deliveries: req.peerDeliveries ?? [],
|
||||
}),
|
||||
signal: req.signal,
|
||||
});
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
/**
|
||||
* 智能体详情抽屉(右侧 Sheet)。
|
||||
*
|
||||
* 业务链条配置页:左栏候选卡片点击卡片本体、右栏席位点「查看详情」都打开这个抽屉,
|
||||
* 展示该智能体的详情(与「智能体」详情页展示的内容差不多):名称 / 模型 / 描述 /
|
||||
* 标签 / 技能 + 工具组 / 人设(SOUL.md)。
|
||||
*
|
||||
* 详情按需拉取:`useAgent(open ? agentId : null)` —— 抽屉打开时才请求 `GET /api/agents/{id}`
|
||||
* (该接口才返回 soul),关闭不请求。字段渲染对齐 `components/workspace/agents/agent-card.tsx`。
|
||||
*/
|
||||
import { Bot, Globe, Loader2, Lock } from "lucide-react";
|
||||
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import {
|
||||
Sheet,
|
||||
SheetContent,
|
||||
SheetDescription,
|
||||
SheetHeader,
|
||||
SheetTitle,
|
||||
} from "@/components/ui/sheet";
|
||||
import { TagChipList } from "@/components/workspace/tags/tag-chip";
|
||||
import { useAgent } from "@/core/agents";
|
||||
import { desensitize } from "@/lib/desensitize";
|
||||
|
||||
export function AgentDetailSheet({
|
||||
agentId,
|
||||
/** 卡片/席位上的名称快照,详情还没拉回来时先用它占位。 */
|
||||
fallbackName,
|
||||
open,
|
||||
onOpenChange,
|
||||
}: {
|
||||
agentId: string | null;
|
||||
fallbackName?: string;
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
}) {
|
||||
// 抽屉打开时才拉详情(含 soul);关闭传 null 让 useAgent 不发请求。
|
||||
const { agent, isLoading } = useAgent(open ? agentId : null);
|
||||
const name = agent?.name || fallbackName || agentId || "";
|
||||
const skillItems = agent?.skills ?? [];
|
||||
const toolGroups = agent?.tool_groups ?? [];
|
||||
const hasSkillsOrTools = skillItems.length > 0 || toolGroups.length > 0;
|
||||
|
||||
return (
|
||||
<Sheet open={open} onOpenChange={onOpenChange}>
|
||||
<SheetContent side="right" className="w-full gap-0 p-0 sm:max-w-md">
|
||||
<SheetHeader className="border-b border-border px-5 py-4">
|
||||
<SheetTitle className="flex items-center gap-2.5">
|
||||
<span className="flex size-8 shrink-0 items-center justify-center rounded-md bg-primary/10 text-primary">
|
||||
<Bot className="size-4" />
|
||||
</span>
|
||||
<span className="min-w-0 flex-1 truncate text-base font-bold">{name}</span>
|
||||
{agent?.model && (
|
||||
<Badge variant="outline" className="shrink-0 text-[10px]">
|
||||
{desensitize(agent.model)}
|
||||
</Badge>
|
||||
)}
|
||||
</SheetTitle>
|
||||
<SheetDescription className="sr-only">智能体详情</SheetDescription>
|
||||
</SheetHeader>
|
||||
|
||||
<div className="min-h-0 flex-1 space-y-5 overflow-y-auto px-5 py-4 text-sm">
|
||||
{isLoading && !agent ? (
|
||||
<div className="flex items-center gap-2 py-8 text-muted-foreground">
|
||||
<Loader2 className="size-4 animate-spin" />
|
||||
正在加载详情…
|
||||
</div>
|
||||
) : !agent ? (
|
||||
<div className="py-8 text-center text-muted-foreground">
|
||||
未找到该智能体的详情(可能已被删除)。
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
{/* 状态徽标 */}
|
||||
<div className="flex flex-wrap items-center gap-1.5">
|
||||
{agent.builtin && (
|
||||
<Badge variant="secondary" className="text-[10px]">内置</Badge>
|
||||
)}
|
||||
{agent.published && (
|
||||
<Badge variant="outline" className="gap-1 text-[10px]">
|
||||
<Globe className="size-3" />
|
||||
已发布
|
||||
</Badge>
|
||||
)}
|
||||
{agent.is_private && (
|
||||
<Badge variant="outline" className="gap-1 text-[10px]">
|
||||
<Lock className="size-3" />
|
||||
私密
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 描述 */}
|
||||
<section className="space-y-1.5">
|
||||
<h4 className="text-[11px] font-bold uppercase tracking-wide text-muted-foreground">
|
||||
描述
|
||||
</h4>
|
||||
<p className="whitespace-pre-wrap leading-relaxed text-foreground">
|
||||
{agent.description?.trim() || "(无描述)"}
|
||||
</p>
|
||||
</section>
|
||||
|
||||
{/* 标签 */}
|
||||
{agent.tags && agent.tags.length > 0 && (
|
||||
<section className="space-y-1.5">
|
||||
<h4 className="text-[11px] font-bold uppercase tracking-wide text-muted-foreground">
|
||||
标签
|
||||
</h4>
|
||||
<TagChipList tags={agent.tags} />
|
||||
</section>
|
||||
)}
|
||||
|
||||
{/* 技能 / 工具组 */}
|
||||
{hasSkillsOrTools && (
|
||||
<section className="space-y-1.5">
|
||||
<h4 className="text-[11px] font-bold uppercase tracking-wide text-muted-foreground">
|
||||
技能与工具
|
||||
</h4>
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{toolGroups.map((group) => (
|
||||
<Badge key={`tg:${group}`} variant="outline" className="text-xs">
|
||||
{desensitize(group)}
|
||||
</Badge>
|
||||
))}
|
||||
{skillItems.map((skill) => (
|
||||
<Badge key={`sk:${skill}`} variant="secondary" className="text-xs">
|
||||
{desensitize(skill)}
|
||||
</Badge>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
|
||||
{/* 人设(SOUL.md) */}
|
||||
{agent.soul?.trim() && (
|
||||
<section className="space-y-1.5">
|
||||
<h4 className="text-[11px] font-bold uppercase tracking-wide text-muted-foreground">
|
||||
人设
|
||||
</h4>
|
||||
<pre className="whitespace-pre-wrap break-words rounded-md border border-border bg-muted/30 p-3 text-[12px] leading-relaxed text-foreground">
|
||||
{agent.soul}
|
||||
</pre>
|
||||
</section>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
);
|
||||
}
|
||||
@@ -9,9 +9,10 @@
|
||||
* 卡片席位名直接用落库快照(`seat.name`),无需实时校验,点「设置」进编辑页后
|
||||
* 会看到实时数据。
|
||||
*/
|
||||
import { Fragment, useEffect, useState } from "react";
|
||||
import { Fragment, useCallback, useEffect, useState } from "react";
|
||||
import {
|
||||
ArrowRightIcon,
|
||||
GlobeIcon,
|
||||
LayersIcon,
|
||||
Loader2Icon,
|
||||
SettingsIcon,
|
||||
@@ -28,7 +29,7 @@ import {
|
||||
} from "@/components/ui/dialog";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
import { listChains } from "../api/chains";
|
||||
import { listChains, setChainPublic, type ChainScope } from "../api/chains";
|
||||
import { chainTagClasses, type BusinessChain } from "../lib/business-chain";
|
||||
import { getAvatarTypeFor } from "../lib/roundtable-constants";
|
||||
|
||||
@@ -47,16 +48,32 @@ export function BusinessChainListDialog({
|
||||
const [chains, setChains] = useState<BusinessChain[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
// 筛选:我的 / 公共(已发布)。
|
||||
const [scope, setScope] = useState<ChainScope>("mine");
|
||||
const [publishingId, setPublishingId] = useState<string | null>(null);
|
||||
|
||||
// 每次打开都重新拉一次,保证配置页改动后回来看到的是最新列表。
|
||||
const refresh = useCallback(async (s: ChainScope) => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const list = await listChains(s);
|
||||
setChains(list);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : String(err));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
// 每次打开 / 切换筛选都重新拉,保证配置页改动后回来看到的是最新列表。
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
let cancelled = false;
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
void (async () => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const list = await listChains();
|
||||
const list = await listChains(scope);
|
||||
if (!cancelled) setChains(list);
|
||||
} catch (err) {
|
||||
if (!cancelled) setError(err instanceof Error ? err.message : String(err));
|
||||
@@ -67,7 +84,22 @@ export function BusinessChainListDialog({
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [open]);
|
||||
}, [open, scope]);
|
||||
|
||||
const handleTogglePublic = useCallback(
|
||||
async (chain: BusinessChain) => {
|
||||
setPublishingId(chain.id);
|
||||
try {
|
||||
await setChainPublic(chain.id, !chain.isPublic);
|
||||
await refresh(scope);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : String(err));
|
||||
} finally {
|
||||
setPublishingId(null);
|
||||
}
|
||||
},
|
||||
[refresh, scope],
|
||||
);
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
@@ -78,10 +110,29 @@ export function BusinessChainListDialog({
|
||||
业务链条
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
可复用的有序智能体编排。点击卡片「设置」可进入配置页编辑该链条。
|
||||
可复用的有序智能体编排。点击卡片「设置」可进入配置页编辑该链条;「发布」后所有账号都能在「公共」里查看 / 选用。
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
{/* 筛选:我的 / 公共 */}
|
||||
<div className="shrink-0 flex items-center gap-1 rounded-lg border border-border bg-muted/40 p-0.5 self-start">
|
||||
{(["mine", "public"] as const).map((s) => (
|
||||
<button
|
||||
key={s}
|
||||
type="button"
|
||||
onClick={() => setScope(s)}
|
||||
className={cn(
|
||||
"rounded-md px-3 py-1 text-xs font-medium transition",
|
||||
scope === s
|
||||
? "bg-primary text-primary-foreground shadow-sm"
|
||||
: "text-muted-foreground hover:text-foreground",
|
||||
)}
|
||||
>
|
||||
{s === "mine" ? "我的" : "公共"}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="custom-scrollbar -mr-1 min-h-0 flex-1 overflow-y-auto py-3 pr-1">
|
||||
{loading ? (
|
||||
<div className="flex items-center gap-2 px-1 py-10 text-sm text-muted-foreground">
|
||||
@@ -95,9 +146,13 @@ export function BusinessChainListDialog({
|
||||
) : chains.length === 0 ? (
|
||||
<div className="flex flex-col items-center justify-center gap-3 px-6 py-12 text-center">
|
||||
<LayersIcon className="size-10 text-primary/40" />
|
||||
<div className="text-sm font-semibold">还没有业务链条</div>
|
||||
<div className="text-sm font-semibold">
|
||||
{scope === "public" ? "还没有公共链条" : "还没有业务链条"}
|
||||
</div>
|
||||
<p className="max-w-sm text-xs leading-relaxed text-muted-foreground">
|
||||
业务链条是可复用的有序智能体编排。点击下方「配置」去创建第一条链条。
|
||||
{scope === "public"
|
||||
? "公共链条是其他账号(或你自己)发布出来、所有人可见的链条。去「我的」里发布一条试试。"
|
||||
: "业务链条是可复用的有序智能体编排。点击下方「配置」去创建第一条链条。"}
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
@@ -106,7 +161,9 @@ export function BusinessChainListDialog({
|
||||
<ChainRow
|
||||
key={chain.id}
|
||||
chain={chain}
|
||||
publishing={publishingId === chain.id}
|
||||
onSettings={() => onConfigure(chain.id)}
|
||||
onTogglePublic={() => handleTogglePublic(chain)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
@@ -128,28 +185,61 @@ export function BusinessChainListDialog({
|
||||
|
||||
function ChainRow({
|
||||
chain,
|
||||
publishing,
|
||||
onSettings,
|
||||
onTogglePublic,
|
||||
}: {
|
||||
chain: BusinessChain;
|
||||
publishing: boolean;
|
||||
onSettings: () => void;
|
||||
onTogglePublic: () => void;
|
||||
}) {
|
||||
const isMine = chain.isMine !== false;
|
||||
return (
|
||||
<div className="rounded-2xl border border-border bg-card p-5 transition-colors hover:border-primary/40">
|
||||
{/* 标题行 + 设置按钮 */}
|
||||
{/* 标题行 + 公共徽标 + 发布/设置按钮 */}
|
||||
<div className="flex items-center gap-2.5">
|
||||
<div className="truncate text-base font-semibold">{chain.title || "未命名链条"}</div>
|
||||
<span className="shrink-0 rounded-full bg-muted px-2 py-0.5 text-xs font-medium tabular-nums text-muted-foreground">
|
||||
{chain.seats.length} 席
|
||||
</span>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={onSettings}
|
||||
className="ml-auto h-8 shrink-0 gap-1.5 px-3 text-sm"
|
||||
>
|
||||
<SettingsIcon className="size-4" />
|
||||
设置
|
||||
</Button>
|
||||
{chain.isPublic && (
|
||||
<span className="shrink-0 inline-flex items-center gap-1 rounded-full bg-emerald-500/10 px-2 py-0.5 text-xs font-medium text-emerald-600 dark:text-emerald-400">
|
||||
<GlobeIcon className="size-3" />
|
||||
公共
|
||||
</span>
|
||||
)}
|
||||
<div className="ml-auto flex shrink-0 items-center gap-1.5">
|
||||
{/* 发布 / 取消发布:仅本人的链条可操作。 */}
|
||||
{isMine && (
|
||||
<Button
|
||||
variant={chain.isPublic ? "secondary" : "outline"}
|
||||
size="sm"
|
||||
onClick={onTogglePublic}
|
||||
disabled={publishing}
|
||||
className="h-8 gap-1.5 px-3 text-sm"
|
||||
>
|
||||
{publishing ? (
|
||||
<Loader2Icon className="size-4 animate-spin" />
|
||||
) : (
|
||||
<GlobeIcon className="size-4" />
|
||||
)}
|
||||
{chain.isPublic ? "取消发布" : "发布"}
|
||||
</Button>
|
||||
)}
|
||||
{/* 设置(编辑):仅本人的链条;公共里别人的链条只读浏览。 */}
|
||||
{isMine && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={onSettings}
|
||||
className="h-8 gap-1.5 px-3 text-sm"
|
||||
>
|
||||
<SettingsIcon className="size-4" />
|
||||
设置
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{chain.description && (
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
*
|
||||
* 详见 `docs/multi-agent-business-chain-dev.md` §6.2 / §7 阶段 3。
|
||||
*/
|
||||
import { Fragment, useEffect, useMemo, useState } from "react";
|
||||
import { useEffect, useMemo, useState, type ReactNode } from "react";
|
||||
import {
|
||||
ArrowRightIcon,
|
||||
CheckIcon,
|
||||
@@ -29,13 +29,14 @@ import { cn } from "@/lib/utils";
|
||||
import { listAgents } from "@/core/agents";
|
||||
|
||||
import { filterRecommendCandidates } from "../api/recommend";
|
||||
import { listChains } from "../api/chains";
|
||||
import { listChains, type ChainScope } from "../api/chains";
|
||||
import {
|
||||
CHAIN_MIN_SEATS,
|
||||
chainTagClasses,
|
||||
type BusinessChain,
|
||||
type SeatSelectionResult,
|
||||
} from "../lib/business-chain";
|
||||
import { buildPlanFromStages } from "../lib/dag-types";
|
||||
import { getAvatarTypeFor } from "../lib/roundtable-constants";
|
||||
|
||||
export interface BusinessChainPickerProps {
|
||||
@@ -54,16 +55,21 @@ export function BusinessChainPicker({
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [selectedId, setSelectedId] = useState<string | null>(null);
|
||||
// 筛选:我的 / 公共(已发布)。
|
||||
const [scope, setScope] = useState<ChainScope>("mine");
|
||||
// null = 候选池未知(agent 列表加载失败)→ 不把任何席位判成「已删除」。
|
||||
const [existingIds, setExistingIds] = useState<Set<string> | null>(null);
|
||||
const [nameById, setNameById] = useState<Map<string, string>>(new Map());
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
setSelectedId(null); // 切换筛选后清空选中(旧选中可能不在新列表里)。
|
||||
void (async () => {
|
||||
try {
|
||||
const [chainList, agents] = await Promise.all([
|
||||
listChains(),
|
||||
listChains(scope),
|
||||
listAgents().catch(() => null), // agent 列表失败不阻断链条展示
|
||||
]);
|
||||
if (cancelled) return;
|
||||
@@ -85,7 +91,7 @@ export function BusinessChainPicker({
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, []);
|
||||
}, [scope]);
|
||||
|
||||
const isExisting = useMemo(
|
||||
() => (agentId: string) => existingIds === null || existingIds.has(agentId),
|
||||
@@ -102,22 +108,68 @@ export function BusinessChainPicker({
|
||||
);
|
||||
const canUse = !!selectedChain && survivingSeats.length >= CHAIN_MIN_SEATS;
|
||||
|
||||
// 选中链条若有分层、且过滤到存活席位后**仍含并行 stage,或任一 stage 带「本阶段目标」**
|
||||
// → 走 dag。并行要 dag 才能并行调度;带目标也要 dag —— 目标靠总控**逐阶段派活**注入
|
||||
// (buildDagStageLeaderTask),chain 模式不消费目标,故串行带目标链同样走 dag。此时让用户在
|
||||
// 「快速(并行双列禁写) / 沙箱(并行单列可写、沙箱跟随)」之间二选一(§DAG 执行子模式)。
|
||||
const dagPlan = useMemo(() => {
|
||||
if (!selectedChain?.stages || selectedChain.stages.length === 0) return null;
|
||||
const surviveIds = survivingSeats.map((s) => s.agent_id);
|
||||
const plan = buildPlanFromStages(
|
||||
selectedChain.stages,
|
||||
surviveIds,
|
||||
true,
|
||||
selectedChain.stageGoals,
|
||||
selectedChain.coordinatorPrompt,
|
||||
);
|
||||
const hasParallel = plan.stages.some((st) => st.agentIds.length > 1);
|
||||
const hasGoal = plan.stages.some((st) => (st.goal?.trim() ?? "") !== "");
|
||||
const hasCoord = (plan.coordinatorPrompt?.trim() ?? "") !== "";
|
||||
return hasParallel || hasGoal || hasCoord ? plan : null;
|
||||
}, [selectedChain, survivingSeats]);
|
||||
const [dagExecMode, setDagExecMode] = useState<"fast" | "sandbox">("fast");
|
||||
|
||||
const handleUse = () => {
|
||||
if (!canUse || !selectedChain) return;
|
||||
const agents = survivingSeats.map((s) => ({
|
||||
agent_id: s.agent_id,
|
||||
name: nameById.get(s.agent_id) ?? s.name,
|
||||
}));
|
||||
onConfirm({
|
||||
agents,
|
||||
mode: "chain",
|
||||
chain: { id: selectedChain.id, title: selectedChain.title },
|
||||
});
|
||||
const chainMeta = { id: selectedChain.id, title: selectedChain.title };
|
||||
const seatNameById = new Map(selectedChain.seats.map((s) => [s.agent_id, s.name]));
|
||||
const nameOf = (id: string) => nameById.get(id) ?? seatNameById.get(id) ?? id;
|
||||
|
||||
// 链条带分层、过滤存活后仍并行 → dag 编排(携带快速/沙箱子模式);否则退回线性 chain。
|
||||
if (dagPlan) {
|
||||
// dag:席位顺序按 stage 展平(与 plan 一致)。
|
||||
const agents = dagPlan.stages
|
||||
.flatMap((st) => st.agentIds)
|
||||
.map((id) => ({ agent_id: id, name: nameOf(id) }));
|
||||
onConfirm({ agents, mode: "dag", chain: chainMeta, plan: dagPlan, dagExecMode });
|
||||
return;
|
||||
}
|
||||
|
||||
const agents = survivingSeats.map((s) => ({ agent_id: s.agent_id, name: nameOf(s.agent_id) }));
|
||||
onConfirm({ agents, mode: "chain", chain: chainMeta });
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<section className="flex-1 min-h-0 flex flex-col overflow-hidden">
|
||||
{/* 筛选:我的 / 公共 */}
|
||||
<div className="mb-2 flex shrink-0 items-center gap-1 self-start rounded-lg border border-border bg-muted/40 p-0.5">
|
||||
{(["mine", "public"] as const).map((s) => (
|
||||
<button
|
||||
key={s}
|
||||
type="button"
|
||||
onClick={() => setScope(s)}
|
||||
className={cn(
|
||||
"rounded-md px-3 py-1 text-xs font-medium transition",
|
||||
scope === s
|
||||
? "bg-primary text-primary-foreground shadow-sm"
|
||||
: "text-muted-foreground hover:text-foreground",
|
||||
)}
|
||||
>
|
||||
{s === "mine" ? "我的" : "公共"}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<div className="min-h-0 flex-1 overflow-y-auto custom-scrollbar pr-1 -mr-1">
|
||||
{loading ? (
|
||||
<div className="flex items-center gap-2 px-1 py-8 text-sm text-muted-foreground">
|
||||
@@ -131,15 +183,20 @@ export function BusinessChainPicker({
|
||||
) : chains.length === 0 ? (
|
||||
<div className="flex h-full flex-col items-center justify-center gap-3 px-6 py-10 text-center">
|
||||
<LayersIcon className="size-10 text-primary/40" />
|
||||
<div className="text-sm font-semibold">还没有业务链条</div>
|
||||
<div className="text-sm font-semibold">
|
||||
{scope === "public" ? "还没有公共链条" : "还没有业务链条"}
|
||||
</div>
|
||||
<p className="max-w-sm text-xs leading-relaxed text-muted-foreground">
|
||||
业务链条是可复用的有序智能体编排。先去配置页面创建第一条链条,
|
||||
之后即可在这里选择使用。
|
||||
{scope === "public"
|
||||
? "公共链条是别人(或你自己)发布出来、所有账号可选用的链条。可在「我的」里发布一条。"
|
||||
: "业务链条是可复用的有序智能体编排。先去配置页面创建第一条链条,之后即可在这里选择使用。"}
|
||||
</p>
|
||||
<Button variant="outline" size="sm" onClick={onGoConfig} className="gap-1.5">
|
||||
<SettingsIcon className="size-4" />
|
||||
去配置业务链条
|
||||
</Button>
|
||||
{scope === "mine" && (
|
||||
<Button variant="outline" size="sm" onClick={onGoConfig} className="gap-1.5">
|
||||
<SettingsIcon className="size-4" />
|
||||
去配置业务链条
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-2.5 py-0.5">
|
||||
@@ -163,6 +220,40 @@ export function BusinessChainPicker({
|
||||
<SettingsIcon className="size-3.5" />
|
||||
配置链条
|
||||
</Button>
|
||||
{/* dag 分层并行 → 选执行子模式(快速双列禁写 / 沙箱单列可写)。 */}
|
||||
{dagPlan && (
|
||||
<div className="flex items-center gap-1.5">
|
||||
<span className="text-xs font-medium text-muted-foreground">执行方式</span>
|
||||
<div className="flex items-center gap-0.5 rounded-lg border border-border bg-muted/40 p-0.5">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setDagExecMode("fast")}
|
||||
title="同 stage 席位并行执行,主区双列同时显示两个;并行期间禁止写文件(产物走正文)"
|
||||
className={cn(
|
||||
"rounded-md px-2.5 py-1 text-xs font-medium transition",
|
||||
dagExecMode === "fast"
|
||||
? "bg-primary text-primary-foreground shadow-sm"
|
||||
: "text-muted-foreground hover:text-foreground",
|
||||
)}
|
||||
>
|
||||
快速 · 双列禁写
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setDagExecMode("sandbox")}
|
||||
title="同 stage 席位仍并行执行,但主区单列显示、允许写文件;点上方头像切换查看,沙箱跟随当前席位"
|
||||
className={cn(
|
||||
"rounded-md px-2.5 py-1 text-xs font-medium transition",
|
||||
dagExecMode === "sandbox"
|
||||
? "bg-primary text-primary-foreground shadow-sm"
|
||||
: "text-muted-foreground hover:text-foreground",
|
||||
)}
|
||||
>
|
||||
沙箱 · 单列可写
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<div className="flex items-center gap-2">
|
||||
{selectedChain && !canUse && (
|
||||
<span className="text-xs text-destructive">存活席位不足 {CHAIN_MIN_SEATS} 个</span>
|
||||
@@ -217,6 +308,11 @@ function ChainCard({
|
||||
<CheckIcon className="size-3" />
|
||||
</span>
|
||||
)}
|
||||
{chain.stages && chain.stages.length > 0 && (
|
||||
<span className="shrink-0 rounded-full border border-amber-400/40 bg-amber-400/10 px-1.5 py-0.5 text-[10px] font-semibold text-amber-600 dark:text-amber-300">
|
||||
分层并行
|
||||
</span>
|
||||
)}
|
||||
<span className="ml-auto shrink-0 rounded-full bg-muted px-1.5 py-0.5 text-[10px] font-medium tabular-nums text-muted-foreground">
|
||||
{chain.seats.length} 席
|
||||
</span>
|
||||
@@ -228,27 +324,35 @@ function ChainCard({
|
||||
|
||||
{/* 智能体名 tag(按顺序,← 箭头连接) */}
|
||||
<div className="mt-2 flex flex-wrap items-center gap-1">
|
||||
{chain.seats.map((seat, i) => {
|
||||
{chain.seats.flatMap((seat, i) => {
|
||||
const alive = isExisting(seat.agent_id);
|
||||
const label = nameById.get(seat.agent_id) ?? seat.name ?? seat.agent_id;
|
||||
return (
|
||||
<Fragment key={seat.agent_id}>
|
||||
{i > 0 && (
|
||||
<ArrowRightIcon className="size-3 shrink-0 text-muted-foreground/50" />
|
||||
// 不用 <Fragment>:dev 期 tagger 会往 Fragment 注入 data-lov-id 触发 React 警告,
|
||||
// 这里改成带 key 的扁平数组(箭头 + tag),注入落到真实元素上即可。
|
||||
const nodes: ReactNode[] = [];
|
||||
if (i > 0) {
|
||||
nodes.push(
|
||||
<ArrowRightIcon
|
||||
key={`arrow-${seat.agent_id}`}
|
||||
className="size-3 shrink-0 text-muted-foreground/50"
|
||||
/>,
|
||||
);
|
||||
}
|
||||
nodes.push(
|
||||
<span
|
||||
key={`tag-${seat.agent_id}`}
|
||||
className={cn(
|
||||
"rounded border px-1.5 py-0.5 text-[11px] font-medium",
|
||||
alive
|
||||
? chainTagClasses(getAvatarTypeFor(seat.agent_id, i))
|
||||
: "border-dashed border-border bg-muted text-muted-foreground/60 line-through",
|
||||
)}
|
||||
<span
|
||||
className={cn(
|
||||
"rounded border px-1.5 py-0.5 text-[11px] font-medium",
|
||||
alive
|
||||
? chainTagClasses(getAvatarTypeFor(seat.agent_id, i))
|
||||
: "border-dashed border-border bg-muted text-muted-foreground/60 line-through",
|
||||
)}
|
||||
title={alive ? undefined : "该智能体已不存在"}
|
||||
>
|
||||
{label}
|
||||
</span>
|
||||
</Fragment>
|
||||
title={alive ? undefined : "该智能体已不存在"}
|
||||
>
|
||||
{label}
|
||||
</span>,
|
||||
);
|
||||
return nodes;
|
||||
})}
|
||||
</div>
|
||||
|
||||
|
||||
@@ -0,0 +1,360 @@
|
||||
/**
|
||||
* 分层 DAG 流程图(Phase 7,§7)。
|
||||
*
|
||||
* 把 `DispatchChainModal` 的**线性**流程图复刻成 **DAG 版**:
|
||||
* 总控 ─▶ ┌Stage1┐ ─▶ ┌Stage2┐ ─▶ … ─▶ 🤝共识 ─▶ 📊结果绘制
|
||||
* │情报● │ │方案✓ │
|
||||
* └风险● ┘ └──────┘
|
||||
* - 按 stage 分**列**,stage 内席位**纵向并列**(并行批次),stage 间用连接线(串行)。
|
||||
* - 节点状态复用 {@link ChainNodeState}(pending / active / done)+ 同款动画
|
||||
* (`animate-ping` 光环 / `Loader2Icon` 转圈 / `CheckIcon` 打勾)。
|
||||
* - 末尾接「共识 → 结果绘制」里程碑(沿用 `DispatchChainModal`)。
|
||||
*
|
||||
* 纯展示组件:所有状态由 props 传入。两种用途:
|
||||
* 1) **编辑器只读预览**(`BusinessChainEditorPage` 底部):不传 `seatStates` → 全 pending,
|
||||
* 仅展示编排结构。
|
||||
* 2) **执行态总览**(Step 2 顶部缩略):`runDagOrchestration` 维护的 `dagNodeStates`
|
||||
* 传进 `seatStates`,节点随执行实时 active/done。
|
||||
*
|
||||
* 节点视觉/连线 CSS 与 `DispatchChainModal` 同源(`rt-chain-connector` 在
|
||||
* `styles/roundtable-planning.css` 全局段);此处自带紧凑版节点渲染,不改动既有 modal。
|
||||
*/
|
||||
import { CheckIcon, ChevronRightIcon, Loader2Icon } from "lucide-react";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
import { getAvatar } from "./Avatars";
|
||||
import { chainTagClasses } from "../lib/business-chain";
|
||||
import { getAvatarTypeFor } from "../lib/roundtable-constants";
|
||||
import type { ChainNodeState } from "../lib/job-types";
|
||||
|
||||
/** 单个席位的展示元数据(名称 + 头像配色)。 */
|
||||
export interface DagFlowSeatMeta {
|
||||
name: string;
|
||||
avatarType: string;
|
||||
}
|
||||
|
||||
export interface DagFlowChartProps {
|
||||
/** 分层计划的 stages(`OrchestrationStage[]` 同形,只取 agentIds)。 */
|
||||
stages: ReadonlyArray<{ id?: string; agentIds: string[] }>;
|
||||
/**
|
||||
* 把 `agentId`(小写)+ 全局序号解析成 {name, avatarType}。
|
||||
* 缺省回退:name=agentId、avatarType=getAvatarTypeFor(agentId, order)。
|
||||
*/
|
||||
resolveSeat?: (agentId: string, order: number) => DagFlowSeatMeta;
|
||||
/** `agentId`(小写)→ 节点状态。缺省 / 未命中 = pending(只读预览即全 pending)。 */
|
||||
seatStates?: Record<string, ChainNodeState>;
|
||||
/** 总控节点状态(默认 pending)。 */
|
||||
coordinatorState?: ChainNodeState;
|
||||
/** 共识里程碑状态(默认 pending)。 */
|
||||
consensusState?: ChainNodeState;
|
||||
/** 结果绘制里程碑状态(默认 pending)。 */
|
||||
reportState?: ChainNodeState;
|
||||
/** 是否显示末尾里程碑(共识 / 结果绘制)。默认 true。 */
|
||||
showMilestones?: boolean;
|
||||
/**
|
||||
* 是否显示「结果绘制」里程碑。`结果绘制` 属于 **Step 3**;Step 2 的流程图只到「共识」即可,
|
||||
* 故 Step 2 / 编辑器预览传 false,只展示 Step 2 流程(总控 → stages → 共识)。默认 true。
|
||||
*/
|
||||
showReportMilestone?: boolean;
|
||||
/** 紧凑模式(顶部缩略 / 底部预览用更小的节点)。默认 false。 */
|
||||
compact?: boolean;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
/** 一个 stage 的聚合状态:任一 active → active;全 done → done;否则 pending。 */
|
||||
function aggregateStageState(
|
||||
agentIds: string[],
|
||||
seatStates: Record<string, ChainNodeState> | undefined,
|
||||
): ChainNodeState {
|
||||
if (!seatStates || agentIds.length === 0) return "pending";
|
||||
let anyActive = false;
|
||||
let allDone = true;
|
||||
for (const id of agentIds) {
|
||||
const st = seatStates[id.toLowerCase()] ?? "pending";
|
||||
if (st === "active") anyActive = true;
|
||||
if (st !== "done") allDone = false;
|
||||
}
|
||||
if (anyActive) return "active";
|
||||
return allDone ? "done" : "pending";
|
||||
}
|
||||
|
||||
export function DagFlowChart({
|
||||
stages,
|
||||
resolveSeat,
|
||||
seatStates,
|
||||
coordinatorState = "pending",
|
||||
consensusState = "pending",
|
||||
reportState = "pending",
|
||||
showMilestones = true,
|
||||
showReportMilestone = true,
|
||||
compact = false,
|
||||
className,
|
||||
}: DagFlowChartProps) {
|
||||
const resolve = (agentId: string, order: number): DagFlowSeatMeta =>
|
||||
resolveSeat?.(agentId, order) ?? {
|
||||
name: agentId,
|
||||
avatarType: getAvatarTypeFor(agentId, order),
|
||||
};
|
||||
|
||||
// 全局序号:跨 stage 连续递增(getAvatarTypeFor 兜底配色 + 节点编号)。
|
||||
let runningOrder = 0;
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"custom-scrollbar overflow-x-auto overflow-y-hidden",
|
||||
compact ? "py-3" : "py-6",
|
||||
className,
|
||||
)}
|
||||
>
|
||||
<div className={cn("flex min-w-max items-center", compact ? "gap-0 px-2" : "gap-0 px-4")}>
|
||||
{/* 总控节点 */}
|
||||
<FlowNode label="总控协调" avatarType="human" state={coordinatorState} compact={compact} />
|
||||
|
||||
{stages.map((stage, stageIdx) => {
|
||||
const stageState = aggregateStageState(stage.agentIds, seatStates);
|
||||
const isParallel = stage.agentIds.length > 1;
|
||||
return (
|
||||
// 用 display:contents 的包裹 div(而非 <Fragment key>):dev 代码标注插件会给具名
|
||||
// <Fragment> 注入 data-lov-id,而 Fragment 只接受 key/children → React 报
|
||||
// 「Invalid prop data-lov-id supplied to React.Fragment」。div.contents 不生成盒子,
|
||||
// Connector / StageColumn 仍作为外层 flex 的直接子项,布局不变,且能正常接收 data-*。
|
||||
<div className="contents" key={stage.id ?? `stage-${stageIdx}`}>
|
||||
<Connector active={stageState === "active"} done={stageState === "done"} compact={compact} />
|
||||
<StageColumn
|
||||
index={stageIdx}
|
||||
isParallel={isParallel}
|
||||
compact={compact}
|
||||
>
|
||||
{stage.agentIds.map((agentId) => {
|
||||
const order = runningOrder++;
|
||||
const meta = resolve(agentId, order);
|
||||
const state = seatStates?.[agentId.toLowerCase()] ?? "pending";
|
||||
return (
|
||||
<FlowNode
|
||||
key={agentId}
|
||||
label={meta.name}
|
||||
avatarType={meta.avatarType}
|
||||
state={state}
|
||||
compact={compact}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</StageColumn>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
|
||||
{showMilestones && (
|
||||
<>
|
||||
<Connector
|
||||
active={consensusState === "active"}
|
||||
done={consensusState === "done"}
|
||||
compact={compact}
|
||||
/>
|
||||
<MilestoneNode label="共识达成" emoji="🤝" state={consensusState} compact={compact} />
|
||||
{showReportMilestone && (
|
||||
<>
|
||||
<Connector
|
||||
active={reportState === "active"}
|
||||
done={reportState === "done"}
|
||||
compact={compact}
|
||||
/>
|
||||
<MilestoneNode label="结果绘制" emoji="📊" state={reportState} compact={compact} />
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ── Stage 列(纵向并列若干席位)────────────────────────────────────────────
|
||||
|
||||
function StageColumn({
|
||||
index,
|
||||
isParallel,
|
||||
compact,
|
||||
children,
|
||||
}: {
|
||||
index: number;
|
||||
isParallel: boolean;
|
||||
compact: boolean;
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<div className="flex flex-col items-center gap-1.5">
|
||||
<span
|
||||
className={cn(
|
||||
"select-none rounded-full px-2 py-0.5 font-semibold text-muted-foreground",
|
||||
compact ? "text-[10px]" : "text-[11px]",
|
||||
)}
|
||||
>
|
||||
Stage {index + 1}
|
||||
{isParallel && (
|
||||
<span className="ml-1 rounded bg-primary/10 px-1 text-primary">并行</span>
|
||||
)}
|
||||
</span>
|
||||
<div
|
||||
className={cn(
|
||||
"flex flex-col items-center rounded-xl border border-dashed border-border/70 bg-muted/20",
|
||||
compact ? "gap-2 p-1.5" : "gap-3 p-2.5",
|
||||
)}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ── 席位 / 总控节点 ─────────────────────────────────────────────────────────
|
||||
|
||||
function FlowNode({
|
||||
label,
|
||||
avatarType,
|
||||
state,
|
||||
compact,
|
||||
}: {
|
||||
label: string;
|
||||
avatarType: string;
|
||||
state: ChainNodeState;
|
||||
compact: boolean;
|
||||
}) {
|
||||
const tag = chainTagClasses(avatarType);
|
||||
const ringSize = compact ? "size-10" : "size-14";
|
||||
const avatarSize = compact ? "h-9 w-9" : "h-12 w-12";
|
||||
return (
|
||||
<div className={cn("flex shrink-0 flex-col items-center gap-1.5 text-center", compact ? "w-16" : "w-24")}>
|
||||
<div className={cn("relative flex items-center justify-center", ringSize)}>
|
||||
{state === "active" && (
|
||||
<span className="absolute inset-0 animate-ping rounded-full bg-primary/30" />
|
||||
)}
|
||||
<span
|
||||
className={cn(
|
||||
"relative flex items-center justify-center rounded-full border-2 transition-all",
|
||||
ringSize,
|
||||
state === "active" && "border-primary shadow-[0_0_0_4px_rgba(22,119,255,0.12)]",
|
||||
state === "done" && "border-emerald-400/70",
|
||||
state === "pending" && "border-border opacity-45 grayscale",
|
||||
)}
|
||||
>
|
||||
{getAvatar(avatarType, avatarSize)}
|
||||
{state === "done" && (
|
||||
<span className="absolute -right-0.5 -top-0.5 flex size-4 items-center justify-center rounded-full bg-emerald-500 text-white shadow">
|
||||
<CheckIcon className="size-2.5" />
|
||||
</span>
|
||||
)}
|
||||
{state === "active" && (
|
||||
<span className="absolute -right-0.5 -top-0.5 flex size-4 items-center justify-center rounded-full bg-primary text-primary-foreground shadow">
|
||||
<Loader2Icon className="size-2.5 animate-spin" />
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
<span
|
||||
className={cn(
|
||||
"max-w-full truncate rounded border px-1.5 py-0.5 font-medium",
|
||||
compact ? "text-[10px]" : "text-[11px]",
|
||||
state === "pending" ? "border-border bg-muted text-muted-foreground" : tag,
|
||||
)}
|
||||
title={label}
|
||||
>
|
||||
{label}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ── 里程碑节点(共识 / 结果绘制)────────────────────────────────────────────
|
||||
|
||||
function MilestoneNode({
|
||||
label,
|
||||
emoji,
|
||||
state,
|
||||
compact,
|
||||
}: {
|
||||
label: string;
|
||||
emoji: string;
|
||||
state: ChainNodeState;
|
||||
compact: boolean;
|
||||
}) {
|
||||
const ringSize = compact ? "size-10" : "size-14";
|
||||
return (
|
||||
<div className={cn("flex shrink-0 flex-col items-center gap-1.5 text-center", compact ? "w-16" : "w-24")}>
|
||||
<div className={cn("relative flex items-center justify-center", ringSize)}>
|
||||
{state === "active" && (
|
||||
<span className="absolute inset-0 animate-ping rounded-full bg-primary/30" />
|
||||
)}
|
||||
<span
|
||||
className={cn(
|
||||
"relative flex items-center justify-center rounded-full border-2 transition-all",
|
||||
ringSize,
|
||||
compact ? "text-lg" : "text-2xl",
|
||||
state === "active" && "border-primary bg-primary/5 shadow-[0_0_0_4px_rgba(22,119,255,0.12)]",
|
||||
state === "done" && "border-emerald-400/70 bg-emerald-500/5",
|
||||
state === "pending" && "border-border bg-muted opacity-45 grayscale",
|
||||
)}
|
||||
>
|
||||
{emoji}
|
||||
{state === "done" && (
|
||||
<span className="absolute -right-0.5 -top-0.5 flex size-4 items-center justify-center rounded-full bg-emerald-500 text-white shadow">
|
||||
<CheckIcon className="size-2.5" />
|
||||
</span>
|
||||
)}
|
||||
{state === "active" && (
|
||||
<span className="absolute -right-0.5 -top-0.5 flex size-4 items-center justify-center rounded-full bg-primary text-primary-foreground shadow">
|
||||
<Loader2Icon className="size-2.5 animate-spin" />
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
<span
|
||||
className={cn(
|
||||
"rounded border px-1.5 py-0.5 font-semibold",
|
||||
compact ? "text-[10px]" : "text-[11px]",
|
||||
state === "pending"
|
||||
? "border-border bg-muted text-muted-foreground"
|
||||
: state === "active"
|
||||
? "border-primary/40 bg-primary/10 text-primary"
|
||||
: "border-emerald-400/40 bg-emerald-500/10 text-emerald-600 dark:text-emerald-400",
|
||||
)}
|
||||
>
|
||||
{label}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ── 连接线(带流动动画,复用 DispatchChainModal 的 rt-chain-connector CSS)────
|
||||
|
||||
function Connector({
|
||||
active,
|
||||
done,
|
||||
compact,
|
||||
}: {
|
||||
active: boolean;
|
||||
done: boolean;
|
||||
compact: boolean;
|
||||
}) {
|
||||
return (
|
||||
<div className={cn("flex shrink-0 items-center justify-center", compact ? "h-10 w-10" : "h-14 w-14")}>
|
||||
<div className="relative flex w-full items-center">
|
||||
<span
|
||||
className={cn(
|
||||
"rt-chain-connector",
|
||||
active && "rt-chain-connector--active",
|
||||
done && !active && "rt-chain-connector--done",
|
||||
)}
|
||||
/>
|
||||
<ChevronRightIcon
|
||||
className={cn(
|
||||
"absolute -right-1 size-4 transition-colors",
|
||||
active ? "text-primary" : done ? "text-primary/70" : "text-muted-foreground/40",
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -211,6 +211,13 @@ export const HighFidelityReport: React.FC<HighFidelityReportProps> = ({
|
||||
[artifactsBySeat],
|
||||
);
|
||||
|
||||
// 只保留「有产出文件」的席位;加载中 / 出错的席位仍保留以展示其状态。
|
||||
// 全部席位都没有文件(且都已加载完成、无错误)时,整块「生成的报告文件」隐藏。
|
||||
const seatsWithFiles = useMemo(
|
||||
() => artifactsBySeat.filter((s) => s.loading || s.error || s.files.length > 0),
|
||||
[artifactsBySeat],
|
||||
);
|
||||
|
||||
const toggleSeat = useCallback((key: string) => {
|
||||
setExpandedSeats((prev) => {
|
||||
const next = new Set(prev);
|
||||
@@ -424,21 +431,20 @@ export const HighFidelityReport: React.FC<HighFidelityReportProps> = ({
|
||||
)}
|
||||
</section>
|
||||
|
||||
{/* Section 3: Generated files per seat —— 点击「查看」进入沙箱分栏预览 */}
|
||||
<section className="bg-white border border-slate-200 rounded-2xl p-5 shadow-[0_2px_8px_rgba(0,0,0,0.02)]">
|
||||
<h4 className="text-xs font-black text-slate-900 uppercase tracking-widest mb-3 flex items-center gap-2">
|
||||
<Download className="w-4 h-4 text-primary" />
|
||||
生成的报告文件
|
||||
<span className="text-[10px] font-mono font-semibold text-slate-400 bg-slate-100 px-1.5 py-0.5 rounded">
|
||||
{totalFileCount}
|
||||
</span>
|
||||
</h4>
|
||||
{/* Section 3: Generated files per seat —— 点击「查看」进入沙箱分栏预览。
|
||||
仅当存在「有产出文件 / 加载中 / 出错」的席位时才渲染;全部席位无文件则整块隐藏。 */}
|
||||
{seatsWithFiles.length > 0 && (
|
||||
<section className="bg-white border border-slate-200 rounded-2xl p-5 shadow-[0_2px_8px_rgba(0,0,0,0.02)]">
|
||||
<h4 className="text-xs font-black text-slate-900 uppercase tracking-widest mb-3 flex items-center gap-2">
|
||||
<Download className="w-4 h-4 text-primary" />
|
||||
生成的报告文件
|
||||
<span className="text-[10px] font-mono font-semibold text-slate-400 bg-slate-100 px-1.5 py-0.5 rounded">
|
||||
{totalFileCount}
|
||||
</span>
|
||||
</h4>
|
||||
|
||||
{artifactsBySeat.length === 0 ? (
|
||||
<p className="text-[11px] text-slate-400 italic">尚未初始化席位线程,无法列出文件。</p>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
{artifactsBySeat.map((seat) => (
|
||||
{seatsWithFiles.map((seat) => (
|
||||
<div key={seat.agentName} className="border border-slate-150 rounded-xl">
|
||||
<div className="flex items-center justify-between gap-2 px-3 py-2 bg-slate-50 border-b border-slate-150 rounded-t-xl">
|
||||
<span className="text-[11.5px] font-bold text-slate-800 truncate">{seat.displayName}</span>
|
||||
@@ -501,8 +507,8 @@ export const HighFidelityReport: React.FC<HighFidelityReportProps> = ({
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
</section>
|
||||
)}
|
||||
|
||||
{/* Footer */}
|
||||
<div className="pt-2 border-t border-slate-100 flex items-center justify-between flex-wrap gap-4">
|
||||
|
||||
@@ -167,8 +167,13 @@ export const sharedMarkdownComponents = {
|
||||
{children}
|
||||
</a>
|
||||
),
|
||||
// 宽表在并行两列 / 窄气泡里会超出容器(模型常输出多列表格,如「法律免责条款」表)。
|
||||
// 套一层 max-w-full + overflow-x-auto 的块级容器:表格保持自然宽度,超出时容器内**横向
|
||||
// 滚动**而不是撑破列宽 / 盖到相邻列。table 不设 max-w,否则单元格会被挤到错乱换行。
|
||||
table: ({ children }: { children?: React.ReactNode }) => (
|
||||
<table className="roundtable-chat-message my-1 border-collapse">{children}</table>
|
||||
<div className="my-1 max-w-full overflow-x-auto">
|
||||
<table className="roundtable-chat-message border-collapse">{children}</table>
|
||||
</div>
|
||||
),
|
||||
th: ({ children }: { children?: React.ReactNode }) => (
|
||||
<th className="border border-slate-300 px-1.5 py-0.5 bg-slate-50 font-bold text-left">
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
/**
|
||||
* 并行批次头像条(§5.2)。
|
||||
*
|
||||
* 并行 stage 执行时显示在消息列表上方、模型选择器左侧。展示当前批次的所有席位头像:
|
||||
* - 进行中(running)→ `animate-ping` 光环 + `Loader2` 角标;
|
||||
* - 已完成(done)→ ✓ 角标;失败(error)→ ✕ 角标;
|
||||
* - 选中(在主区两列里显示的那 ≤2 个)→ 高亮描边。
|
||||
* 点头像 = 切换该席位是否在主区显示(LRU,最多 2,见 hook `toggleParallelSeat`)。
|
||||
*
|
||||
* 复用 `Avatars.getAvatar` 的头像 SVG 与 `DispatchChainModal` 的 loading 动画思路。
|
||||
*/
|
||||
import { CheckIcon, Loader2Icon, XIcon } from "lucide-react";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
import { getAvatar } from "@/roundtable-planning/components/Avatars";
|
||||
import type { ParallelSeatView } from "@/roundtable-planning/hooks/useStep2Orchestration";
|
||||
|
||||
export interface ParallelSeatStripProps {
|
||||
batch: ParallelSeatView[];
|
||||
/** 当前主区显示的席位 agentId(最多 2)。 */
|
||||
selectedSeats: string[];
|
||||
onToggleSeat: (agentId: string) => void;
|
||||
}
|
||||
|
||||
export function ParallelSeatStrip({ batch, selectedSeats, onToggleSeat }: ParallelSeatStripProps) {
|
||||
if (batch.length === 0) return null;
|
||||
const selected = new Set(selectedSeats);
|
||||
const runningCount = batch.filter((s) => s.status === "running").length;
|
||||
|
||||
return (
|
||||
<div className="flex items-center gap-2 overflow-x-auto py-1">
|
||||
<span className="shrink-0 text-[calc(10px*var(--ui-font-scale,1))] font-bold text-slate-500">
|
||||
并行 {batch.length} 席
|
||||
{runningCount > 0 && <span className="text-primary">({runningCount} 进行中)</span>}
|
||||
</span>
|
||||
<div className="flex items-center gap-1.5">
|
||||
{batch.map((seat) => {
|
||||
const isSelected = selected.has(seat.agentId);
|
||||
const isRunning = seat.status === "running";
|
||||
return (
|
||||
<button
|
||||
key={seat.agentId}
|
||||
type="button"
|
||||
onClick={() => onToggleSeat(seat.agentId)}
|
||||
title={`${seat.displayName}${isSelected ? "(主区显示中)" : "(点击在主区显示)"}`}
|
||||
className={cn(
|
||||
"relative shrink-0 rounded-full transition",
|
||||
isSelected ? "ring-2 ring-primary ring-offset-1" : "ring-1 ring-transparent hover:ring-slate-300",
|
||||
)}
|
||||
>
|
||||
{/* 进行中光环 */}
|
||||
{isRunning && (
|
||||
<span className="absolute inset-0 animate-ping rounded-full bg-primary/30" aria-hidden />
|
||||
)}
|
||||
<span className={cn("relative block", !isSelected && "opacity-80")}>
|
||||
{getAvatar(seat.avatarType, "h-7 w-7")}
|
||||
</span>
|
||||
{/* 状态角标 */}
|
||||
<span
|
||||
className={cn(
|
||||
"absolute -bottom-0.5 -right-0.5 flex size-3.5 items-center justify-center rounded-full border border-white shadow-sm",
|
||||
seat.status === "running" && "bg-primary text-white",
|
||||
seat.status === "done" && "bg-emerald-500 text-white",
|
||||
seat.status === "error" && "bg-rose-500 text-white",
|
||||
)}
|
||||
>
|
||||
{seat.status === "running" && <Loader2Icon className="size-2.5 animate-spin" />}
|
||||
{seat.status === "done" && <CheckIcon className="size-2.5" strokeWidth={3} />}
|
||||
{seat.status === "error" && <XIcon className="size-2.5" strokeWidth={3} />}
|
||||
</span>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -16,17 +16,25 @@
|
||||
*
|
||||
* 状态全部来自 `useStep2Orchestration` —— 本组件不调任何后端、不持久化。
|
||||
*/
|
||||
import { useCallback, useRef, useState } from "react";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import {
|
||||
Cpu,
|
||||
FileIcon,
|
||||
HelpCircle,
|
||||
Loader2,
|
||||
Network,
|
||||
Pause,
|
||||
Play,
|
||||
Sparkles,
|
||||
} from "lucide-react";
|
||||
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
|
||||
/** 后台挂起入口 —— 暂时隐藏,恢复时改为 true。 */
|
||||
const SHOW_BACKGROUND_SUSPEND = false;
|
||||
|
||||
@@ -42,13 +50,19 @@ import {
|
||||
StreamingCursor,
|
||||
} from "@/roundtable-planning/components/MessageBubble";
|
||||
import { MessageStepsCard } from "@/roundtable-planning/components/MessageStepsCard";
|
||||
import { ParallelSeatStrip } from "@/roundtable-planning/components/ParallelSeatStrip";
|
||||
import { DagFlowChart } from "@/roundtable-planning/components/DagFlowChart";
|
||||
import { useAutoScroll } from "@/roundtable-planning/hooks/useAutoScroll";
|
||||
import type {
|
||||
AgentConfig,
|
||||
ParallelSeatView,
|
||||
Step2Dialogue,
|
||||
} from "@/roundtable-planning/hooks/useStep2Orchestration";
|
||||
import type {
|
||||
RoleEntry,
|
||||
import type { OrchestrationPlan } from "@/roundtable-planning/lib/dag-types";
|
||||
import type { ChainNodeState } from "@/roundtable-planning/lib/job-types";
|
||||
import {
|
||||
getAvatarTypeFor,
|
||||
type RoleEntry,
|
||||
} from "@/roundtable-planning/lib/roundtable-constants";
|
||||
import { splitInlineReasoning } from "@/roundtable-planning/lib/reasoning";
|
||||
import type { ClarificationPayload } from "@/roundtable-planning/api/multi-agent";
|
||||
@@ -71,6 +85,18 @@ export interface Step2PanelProps {
|
||||
agentConfigs: Record<number, AgentConfig>;
|
||||
selectedAgentId: number | null;
|
||||
roles: RoleEntry[];
|
||||
// ─── 并行显示(§5)────────────────────────────────────────────
|
||||
parallelBatch: ParallelSeatView[];
|
||||
selectedParallelSeats: string[];
|
||||
isParallelRunning: boolean;
|
||||
onToggleParallelSeat: (agentId: string) => void;
|
||||
// ─── Phase 7 DAG 流程图执行态总览(§7)─────────────────────────
|
||||
/** 当前编排模式;=== "dag" 且 plan 非空时,顶部显示 DAG 流程图缩略。 */
|
||||
orchestrationMode: "recommend" | "chain" | "dag";
|
||||
/** dag 模式的分层计划(流程图按 stage 分列渲染)。 */
|
||||
orchestrationPlan: OrchestrationPlan | null;
|
||||
/** agentId(小写) → 节点状态;驱动流程图节点 active/done。 */
|
||||
dagNodeStates: Record<string, ChainNodeState>;
|
||||
/** agent id(小写)→ 席位元数据,用于把派活 chip 的 id 显示成中文席位名。 */
|
||||
agentNameToRole: Record<
|
||||
string,
|
||||
@@ -120,6 +146,13 @@ export function Step2Panel(props: Step2PanelProps) {
|
||||
agentConfigs,
|
||||
selectedAgentId,
|
||||
roles,
|
||||
parallelBatch,
|
||||
selectedParallelSeats,
|
||||
isParallelRunning,
|
||||
onToggleParallelSeat,
|
||||
orchestrationMode,
|
||||
orchestrationPlan,
|
||||
dagNodeStates,
|
||||
agentNameToRole,
|
||||
selectedModel,
|
||||
availableModels,
|
||||
@@ -147,12 +180,74 @@ export function Step2Panel(props: Step2PanelProps) {
|
||||
const { atBottom: step2AtBottom, scrollToBottom: scrollStep2ToBottom } =
|
||||
useAutoScroll(step2ScrollRef, [step2RoundtableDialogues]);
|
||||
|
||||
// 并行进入/退出、或切换主区显示席位时,布局在「平铺列表 ↔ 两列/单列网格」之间切换,
|
||||
// scrollHeight 会突变、scrollTop 被浏览器 clamp → useAutoScroll 误判成「用户上滚」而停跟随
|
||||
// (表现为并行时自动下滑失效)。这里在这些布局切换点**重新拉到底部 + 恢复自动跟随**。
|
||||
useEffect(() => {
|
||||
scrollStep2ToBottom();
|
||||
}, [isParallelRunning, selectedParallelSeats, scrollStep2ToBottom]);
|
||||
|
||||
const resolveAgentName = useCallback(
|
||||
(idOrName: string) =>
|
||||
agentNameToRole[idOrName.toLowerCase()]?.displayName ?? idOrName,
|
||||
[agentNameToRole],
|
||||
);
|
||||
|
||||
// 并行两列:按 bubbleId 取席位流式气泡。固定 2 列(窄屏 1 列,见 CSS 断点)。
|
||||
const dialogueById = useMemo(() => {
|
||||
const m = new Map<number, Step2Dialogue>();
|
||||
for (const d of step2RoundtableDialogues) m.set(d.id, d);
|
||||
return m;
|
||||
}, [step2RoundtableDialogues]);
|
||||
// 主区两列要显示的席位:取被选中的(最多 2),回退到批次最先两个。
|
||||
const parallelColumns = useMemo(() => {
|
||||
if (!isParallelRunning) return [];
|
||||
const pick = selectedParallelSeats.length > 0
|
||||
? selectedParallelSeats
|
||||
: parallelBatch.slice(0, 2).map((s) => s.agentId);
|
||||
return pick
|
||||
.map((agentId) => parallelBatch.find((s) => s.agentId === agentId))
|
||||
.filter((s): s is ParallelSeatView => Boolean(s))
|
||||
.slice(0, 2);
|
||||
}, [isParallelRunning, selectedParallelSeats, parallelBatch]);
|
||||
|
||||
// ─── Phase 7 DAG 流程图执行态总览(§7)──────────────────────────────────
|
||||
const showDagFlow =
|
||||
orchestrationMode === "dag" && (orchestrationPlan?.stages.length ?? 0) > 0;
|
||||
const resolveDagSeat = useCallback(
|
||||
(agentId: string, order: number) => {
|
||||
const meta = agentNameToRole[agentId.toLowerCase()];
|
||||
return {
|
||||
name: meta?.displayName ?? agentId,
|
||||
avatarType: meta?.avatarType ?? getAvatarTypeFor(agentId, order),
|
||||
};
|
||||
},
|
||||
[agentNameToRole],
|
||||
);
|
||||
// 总控 / 共识 / 报告里程碑状态:由节点状态 + 编排/共识标志派生。
|
||||
const { dagCoordinatorState, dagConsensusState } = useMemo(() => {
|
||||
const states = Object.values(dagNodeStates);
|
||||
const anyActive = states.includes("active");
|
||||
const anyStarted = states.some((s) => s !== "pending");
|
||||
const allDone = states.length > 0 && states.every((s) => s === "done");
|
||||
const coordinator: ChainNodeState = anyActive
|
||||
? "done"
|
||||
: isOrchestrating
|
||||
? "active"
|
||||
: anyStarted
|
||||
? "done"
|
||||
: "pending";
|
||||
const consensus: ChainNodeState = hasConsensus
|
||||
? "done"
|
||||
: allDone
|
||||
? "active"
|
||||
: "pending";
|
||||
return { dagCoordinatorState: coordinator, dagConsensusState: consensus };
|
||||
}, [dagNodeStates, isOrchestrating, hasConsensus]);
|
||||
|
||||
// Phase 7:DAG 流程图弹窗开关(点按钮查看,不再内联占空间)。
|
||||
const [dagFlowOpen, setDagFlowOpen] = useState(false);
|
||||
|
||||
// 干预研审:记录指令并自动恢复会商,右上角按钮状态由 isRoundTableRunning 驱动
|
||||
const [pauseFlash, setPauseFlash] = useState(false);
|
||||
|
||||
@@ -249,6 +344,54 @@ export function Step2Panel(props: Step2PanelProps) {
|
||||
|
||||
{/* Conversation log */}
|
||||
<div className="relative flex-1 min-h-0 flex flex-col">
|
||||
{/* Phase 7:dag 模式 —— 流程图改成「点按钮看弹窗」,不再内联占空间(§7)。 */}
|
||||
{showDagFlow && orchestrationPlan && (
|
||||
<div className="shrink-0 flex items-center justify-between gap-2 border-t border-slate-150 bg-slate-50/60 px-6 py-2">
|
||||
<span className="text-xs font-medium text-slate-500">
|
||||
分层编排执行中 · 共 {orchestrationPlan.stages.length} 个阶段
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setDagFlowOpen(true)}
|
||||
className="inline-flex items-center gap-1.5 rounded-lg border border-primary/30 bg-primary/5 px-2.5 py-1 text-xs font-semibold text-primary transition hover:bg-primary/10"
|
||||
>
|
||||
<Network className="size-3.5" />
|
||||
查看编排流程图
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{showDagFlow && orchestrationPlan && (
|
||||
<Dialog open={dagFlowOpen} onOpenChange={setDagFlowOpen}>
|
||||
<DialogContent className="flex max-h-[88vh] w-[94vw] flex-col gap-0 sm:max-w-[1100px]">
|
||||
<DialogHeader className="shrink-0">
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<Network className="size-5 text-primary" />
|
||||
分层编排流程图
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
<div className="min-h-0 flex-1 overflow-auto">
|
||||
<DagFlowChart
|
||||
stages={orchestrationPlan.stages}
|
||||
resolveSeat={resolveDagSeat}
|
||||
seatStates={dagNodeStates}
|
||||
coordinatorState={dagCoordinatorState}
|
||||
consensusState={dagConsensusState}
|
||||
showReportMilestone={false}
|
||||
/>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)}
|
||||
{/* 并行批次头像条(§5.2):消息列表上方,点头像切换主区两列显示的席位。 */}
|
||||
{isParallelRunning && (
|
||||
<div className="shrink-0 px-6 py-2 bg-white border-t border-slate-150">
|
||||
<ParallelSeatStrip
|
||||
batch={parallelBatch}
|
||||
selectedSeats={selectedParallelSeats}
|
||||
onToggleSeat={onToggleParallelSeat}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
<div
|
||||
ref={step2ScrollRef}
|
||||
className="flex-1 min-h-0 overflow-y-auto p-6 space-y-4 bg-white border-t border-slate-150 border-b border-slate-150 shadow-inner"
|
||||
@@ -260,19 +403,57 @@ export function Step2Panel(props: Step2PanelProps) {
|
||||
<div className="text-xs text-slate-400">正在为各席位建立独立线程,请稍候</div>
|
||||
</div>
|
||||
)}
|
||||
{step2RoundtableDialogues.map((msg) => (
|
||||
<Step2Message
|
||||
key={msg.id}
|
||||
msg={msg}
|
||||
resolveAgentName={resolveAgentName}
|
||||
onArtifactStepClick={(step) => openArtifactFromStep(msg, step)}
|
||||
onFileCardClick={(path) => {
|
||||
if (msg.agentThreadId) {
|
||||
openArtifactPreview(msg.agentThreadId, path);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
{isParallelRunning && parallelColumns.length > 0 ? (
|
||||
// 并行进行时:主区固定 2 列(窄屏降 1 列),每列渲染一个被选中席位的消息流。
|
||||
// 未选中席位的气泡仍在 step2RoundtableDialogues 内存里(只是此刻不渲染),
|
||||
// 切换头像即可立刻看到其全部输出(§6 全接收/惰性渲染的基础)。
|
||||
<div
|
||||
className={
|
||||
parallelColumns.length > 1
|
||||
? "grid grid-cols-1 gap-4 lg:grid-cols-2"
|
||||
: "grid grid-cols-1 gap-4"
|
||||
}
|
||||
>
|
||||
{parallelColumns.map((seat) => {
|
||||
const msg = dialogueById.get(seat.bubbleId);
|
||||
return (
|
||||
<div
|
||||
key={seat.agentId}
|
||||
className="flex min-w-0 flex-col rounded-xl border border-slate-200 bg-slate-50/40 p-3"
|
||||
>
|
||||
{msg ? (
|
||||
<Step2Message
|
||||
msg={msg}
|
||||
resolveAgentName={resolveAgentName}
|
||||
onArtifactStepClick={(step) => openArtifactFromStep(msg, step)}
|
||||
onFileCardClick={(path) => {
|
||||
if (msg.agentThreadId) openArtifactPreview(msg.agentThreadId, path);
|
||||
}}
|
||||
/>
|
||||
) : (
|
||||
<div className="py-6 text-center text-xs text-slate-400">
|
||||
{seat.displayName} · 等待输出…
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
) : (
|
||||
step2RoundtableDialogues.map((msg) => (
|
||||
<Step2Message
|
||||
key={msg.id}
|
||||
msg={msg}
|
||||
resolveAgentName={resolveAgentName}
|
||||
onArtifactStepClick={(step) => openArtifactFromStep(msg, step)}
|
||||
onFileCardClick={(path) => {
|
||||
if (msg.agentThreadId) {
|
||||
openArtifactPreview(msg.agentThreadId, path);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
{!step2AtBottom && <ScrollToBottomButton onClick={scrollStep2ToBottom} />}
|
||||
</div>
|
||||
|
||||
@@ -60,8 +60,11 @@ export const markdownComponents = {
|
||||
{children}
|
||||
</a>
|
||||
),
|
||||
// 宽表套横向滚动容器,避免超出卡片宽度(同 MessageBubble.sharedMarkdownComponents)。
|
||||
table: ({ children }: any) => (
|
||||
<table className="roundtable-chat-message my-2 border-collapse">{children}</table>
|
||||
<div className="my-2 max-w-full overflow-x-auto">
|
||||
<table className="roundtable-chat-message border-collapse">{children}</table>
|
||||
</div>
|
||||
),
|
||||
th: ({ children }: any) => (
|
||||
<th className="border border-slate-300 px-1.5 py-0.5 bg-slate-50 font-bold text-left">
|
||||
|
||||
@@ -25,6 +25,12 @@ import {
|
||||
type StreamPhase,
|
||||
type ThreadIdMap,
|
||||
} from "@/roundtable-planning/api/multi-agent";
|
||||
import {
|
||||
buildDagStageLeaderTask,
|
||||
pickDagSeatTask,
|
||||
type OrchestrationPlan,
|
||||
} from "@/roundtable-planning/lib/dag-types";
|
||||
import type { ChainNodeState } from "@/roundtable-planning/lib/job-types";
|
||||
import {
|
||||
DEFAULT_SELECTED_AGENTS,
|
||||
MAX_CYCLES,
|
||||
@@ -56,6 +62,20 @@ export type Step2Dialogue = {
|
||||
}>;
|
||||
};
|
||||
|
||||
/**
|
||||
* 并行批次里的一个席位视图(§5 并行显示)。`runDagOrchestration` 在真并行 stage
|
||||
* 期间发布整批;头像条 / 两列主区据此渲染,`bubbleId` 指向 `step2RoundtableDialogues`
|
||||
* 里该席位的流式气泡。
|
||||
*/
|
||||
export interface ParallelSeatView {
|
||||
agentId: string;
|
||||
displayName: string;
|
||||
avatarType: string;
|
||||
status: "running" | "done" | "error";
|
||||
/** 该席位流式气泡在 step2RoundtableDialogues 里的 id。 */
|
||||
bubbleId: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Stub AI message —— 用于把 special seat SSE 拿到的工具调用注入到 ThreadContext
|
||||
* 的 `thread.messages` 里,让 `useArtifactContent` 在沙箱里通过虚拟 URL
|
||||
@@ -110,9 +130,11 @@ export type Step2Snapshot = {
|
||||
* 注:该字段是主页面 state,由页面在 getStep2Snapshot/hydrateStep2 里读写,
|
||||
* step2 hook 的 hydrateFromDraft 不直接消费它。
|
||||
*/
|
||||
orchestrationMode?: "recommend" | "chain";
|
||||
orchestrationMode?: "recommend" | "chain" | "dag";
|
||||
/** chain 模式来源链条(仅展示用,如「按业务链条 X 研讨」)。 */
|
||||
chain?: { id: string; title: string } | null;
|
||||
/** dag 模式的分层编排计划(见 `lib/dag-types.ts`)。同样是主页面 state,hook 经 option 读取。 */
|
||||
orchestrationPlan?: OrchestrationPlan | null;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -191,11 +213,25 @@ export interface UseStep2OrchestrationOptions {
|
||||
/**
|
||||
* 编排模式:
|
||||
* - `recommend`(默认)—— 总控自由派活循环(`runOrchestration`);
|
||||
* - `chain` —— 总控**按业务链条顺序**逐位派活(`runChainOrchestration`)。
|
||||
* - `chain` —— 总控**按业务链条顺序**逐位派活(`runChainOrchestration`);
|
||||
* - `dag` —— **分层 DAG**:前端直派,stage 内并行、stage 间串行(`runDagOrchestration`,
|
||||
* 需配合 `orchestrationPlan`)。
|
||||
* 由推荐弹窗确认时的 `SeatSelectionResult.mode` 决定;chain 模式下席位顺序 =
|
||||
* `selectedAgents` 的顺序。
|
||||
*/
|
||||
orchestrationMode: "recommend" | "chain";
|
||||
orchestrationMode: "recommend" | "chain" | "dag";
|
||||
/**
|
||||
* dag 模式的分层编排计划。`orchestrationMode === "dag"` 且本计划非空时,
|
||||
* `runActiveOrchestration` 走 `runDagOrchestration`;否则回退到 recommend / chain。
|
||||
*/
|
||||
orchestrationPlan?: OrchestrationPlan | null;
|
||||
/**
|
||||
* dag 执行子模式(仅 `orchestrationMode === "dag"` 生效):
|
||||
* - `fast`(默认):同 stage 席位并行、主区**双列**、**禁写文件**(seat_parallel);
|
||||
* - `sandbox`:同 stage 席位仍并行,但主区**单列**、**允许写文件**(seat),沙箱跟随当前
|
||||
* 显示的席位(切头像 → 沙箱内容随之切换/关闭)。
|
||||
*/
|
||||
dagExecMode?: "fast" | "sandbox";
|
||||
/** 进入 Step 2 时拼装第一轮 leader prompt 的函数(读 Step 1 状态)。 */
|
||||
buildInitialIntent: () => string;
|
||||
/** 主页面统一的 toast。 */
|
||||
@@ -228,6 +264,17 @@ export interface UseStep2OrchestrationReturn {
|
||||
budgetLimit: number;
|
||||
agentConfigs: Record<number, AgentConfig>;
|
||||
selectedAgentId: number | null;
|
||||
// ─── 并行显示(§5)────────────────────────────────────────────────────
|
||||
/** 当前并行批次(非空 = 正在并行 stage)。 */
|
||||
parallelBatch: ParallelSeatView[];
|
||||
/** 主区当前并排显示的席位 agentId(最多 2)。 */
|
||||
selectedParallelSeats: string[];
|
||||
/** 是否正在并行执行(左侧栏折叠 / 头像条 / 两列显示的总开关)。 */
|
||||
isParallelRunning: boolean;
|
||||
/** 点头像切换主区显示的席位(LRU,最多 2)。 */
|
||||
toggleParallelSeat: (agentId: string) => void;
|
||||
/** Phase 7 DAG 流程图执行态:agentId(小写) → pending/active/done。非 dag 模式为空。 */
|
||||
dagNodeStates: Record<string, ChainNodeState>;
|
||||
// ─── Derived ────────────────────────────────────────────────────────
|
||||
roleTemplates: ReadonlyArray<Omit<RoleEntry, "status">>;
|
||||
agentNameToRole: Record<
|
||||
@@ -297,6 +344,8 @@ export function useStep2Orchestration(
|
||||
currentStep,
|
||||
selectedModel,
|
||||
orchestrationMode,
|
||||
orchestrationPlan,
|
||||
dagExecMode = "fast",
|
||||
buildInitialIntent,
|
||||
triggerToast,
|
||||
setRoles,
|
||||
@@ -364,6 +413,30 @@ export function useStep2Orchestration(
|
||||
DEFAULT_AGENT_CONFIGS,
|
||||
);
|
||||
const [selectedAgentId, setSelectedAgentId] = useState<number | null>(null);
|
||||
// 并行批次(§5):runDagOrchestration 在真并行 stage 期间发布;空 = 非并行。
|
||||
const [parallelBatch, setParallelBatch] = useState<ParallelSeatView[]>([]);
|
||||
// Phase 7 DAG 流程图执行态(§7):agentId(小写) → pending/active/done。
|
||||
// runDagOrchestration 跨 stage 维护;DagFlowChart 据此实时点亮节点。非 dag 模式 = 空。
|
||||
const [dagNodeStates, setDagNodeStates] = useState<Record<string, ChainNodeState>>({});
|
||||
// 主区当前并排显示的席位(最多 2,固定 2 列;窄屏只渲染第 1 个)。
|
||||
const [selectedParallelSeats, setSelectedParallelSeats] = useState<string[]>([]);
|
||||
// §6 流式高性能:所有并行席位的增量文本**全量累积进 ref**(O(1),不触发渲染);
|
||||
// 只有被选中的席位才在节流 flush 时把全文挂到 React state 渲染 Markdown。
|
||||
// key = bubbleId。
|
||||
const parallelStreamRef = useRef<Map<number, { text: string; charCount: number }>>(
|
||||
new Map(),
|
||||
);
|
||||
const parallelFlushTimerRef = useRef<number | null>(null);
|
||||
// flush 时要读「当前选中席位」与「批次 bubbleId↔agentId 映射」—— 打到 ref 避免
|
||||
// 把 flush 函数绑进会频繁变化的 state 依赖。
|
||||
const selectedParallelSeatsRef = useRef<string[]>([]);
|
||||
const parallelBatchRef = useRef<ParallelSeatView[]>([]);
|
||||
useEffect(() => {
|
||||
selectedParallelSeatsRef.current = selectedParallelSeats;
|
||||
}, [selectedParallelSeats]);
|
||||
useEffect(() => {
|
||||
parallelBatchRef.current = parallelBatch;
|
||||
}, [parallelBatch]);
|
||||
|
||||
// ─── Derived ──────────────────────────────────────────────────────
|
||||
const roleTemplates = useMemo(
|
||||
@@ -381,6 +454,12 @@ export function useStep2Orchestration(
|
||||
|
||||
// ─── Refs ────────────────────────────────────────────────────────
|
||||
const orchestrationCancelRef = useRef<boolean>(false);
|
||||
// 编排「世代号」。每次启动一轮编排(runOrchestration / runChainOrchestration)就 +1。
|
||||
// 旧循环捕获自己的 epoch,在每个取消检查点比对 —— 一旦 epoch 变了(说明已有新循环
|
||||
// 接管,例如人工干预),旧循环立即退出。这能根治「新循环把 orchestrationCancelRef
|
||||
// 重置为 false 反而把正在退出的旧循环『反取消』,导致旧循环继续又发一个 leader run」
|
||||
// 的并发双发 bug:epoch 是单调递增的,新循环无法把它『重置』回旧循环的值。
|
||||
const orchestrationEpochRef = useRef<number>(0);
|
||||
const step2InitRef = useRef<boolean>(false);
|
||||
const activeAbortersRef = useRef<Set<AbortController>>(new Set());
|
||||
/** 干预研审:恢复会商后待执行的 leader prompt。 */
|
||||
@@ -397,10 +476,29 @@ export function useStep2Orchestration(
|
||||
const isOrchestratingRef = useRef<boolean>(isOrchestrating);
|
||||
// chain 编排:模式 + 当前选中席位(=链条顺序)。同样打到 ref,让编排函数 deps 收窄。
|
||||
const orchestrationModeRef = useRef(orchestrationMode);
|
||||
const orchestrationPlanRef = useRef<OrchestrationPlan | null>(orchestrationPlan ?? null);
|
||||
// dag 执行子模式(fast/sandbox) + 沙箱模式下「当前允许显示沙箱的席位 thread」。
|
||||
// sandbox 模式单列:只有**当前显示**的席位才可自动打开沙箱;后台并行席位写文件不抢占
|
||||
// (见 openSeatVirtualArtifact 的 auto 守卫)。null = 非 sandbox 模式 / 无限制。
|
||||
const dagExecModeRef = useRef<"fast" | "sandbox">(dagExecMode);
|
||||
const sandboxFollowThreadIdRef = useRef<string | null>(null);
|
||||
// 「上次已 reconcile 的显示席位」键(`${mode}:${seat}`)。沙箱跟随 effect 只在**显示席位真正
|
||||
// 变化**时开/关沙箱,避免每次 render(deps 身份变化)都强制重开,把用户手动关闭的沙箱又弹回来。
|
||||
const lastReconciledSeatRef = useRef<string>("");
|
||||
useEffect(() => {
|
||||
dagExecModeRef.current = dagExecMode;
|
||||
}, [dagExecMode]);
|
||||
// dag 计划「已跑过一遍」闸门:DAG 编排只在初次执行一次计划;之后的用户干预 / 恢复 /
|
||||
// 澄清回复都改走 **leader 自由派活循环**(runOrchestration),由总控接着派活,而**不是**
|
||||
// 重新把整张 DAG 从头跑一遍(致命 bug 修复)。新任务 / 重新进入时由 resetInitGate 复位。
|
||||
const dagPlanExecutedRef = useRef<boolean>(false);
|
||||
const selectedAgentsRef = useRef<SelectedAgent[]>(selectedAgents);
|
||||
useEffect(() => {
|
||||
orchestrationModeRef.current = orchestrationMode;
|
||||
}, [orchestrationMode]);
|
||||
useEffect(() => {
|
||||
orchestrationPlanRef.current = orchestrationPlan ?? null;
|
||||
}, [orchestrationPlan]);
|
||||
useEffect(() => {
|
||||
selectedAgentsRef.current = selectedAgents;
|
||||
}, [selectedAgents]);
|
||||
@@ -493,16 +591,46 @@ export function useStep2Orchestration(
|
||||
* auto=false(用户点击步骤 / 文件卡)始终强制打开。
|
||||
*/
|
||||
const openSeatVirtualArtifact = useCallback(
|
||||
(seatThreadId: string, virtualUrl: string, auto: boolean) => {
|
||||
(
|
||||
seatThreadId: string,
|
||||
virtualUrl: string,
|
||||
auto: boolean,
|
||||
opts?: { manual?: boolean },
|
||||
) => {
|
||||
// manual=true → 视为「用户手动接管」,会把全局 autoSelect 置 false(尊重用户后续不再
|
||||
// 自动选/自动开)。默认沿用旧语义:auto=false 即手动点击(文件卡 / 步骤)。
|
||||
// 但**系统程序化打开**(如沙箱跟随 openSeatLatestArtifact)必须传 manual:false ——
|
||||
// 否则会误关 autoSelect,毒化随后实时 write_file 的 auto=true 自动打开,表现为
|
||||
// 「单个智能体发言时沙箱不自动打开、只能手动开」(763eb4d 沙箱跟随引入的回归)。
|
||||
const manual = opts?.manual ?? !auto;
|
||||
if (auto) {
|
||||
if (hasAutoOpenedRef.current.has(virtualUrl)) return;
|
||||
const flags = autoOpenFlagsRef.current;
|
||||
if (!flags.autoOpen || !flags.autoSelect) return;
|
||||
// 快速模式(双列)DAG 并行批次:**完全不**自动开沙箱 —— 双列只看正文,多席位并发写
|
||||
// 文件(现已放开 write_file)会让单沙箱预览反复串台。文件仍写盘,Step3 / 文件卡可查看。
|
||||
if (
|
||||
orchestrationModeRef.current === "dag" &&
|
||||
dagExecModeRef.current === "fast" &&
|
||||
parallelBatchRef.current.length > 0
|
||||
) {
|
||||
return;
|
||||
}
|
||||
// sandbox 单列模式:并行的**后台**席位写文件时不要抢占沙箱 —— 只有当前显示的
|
||||
// 席位(sandboxFollowThreadIdRef)才允许自动打开,否则沙箱内容会和主区列表错位。
|
||||
if (
|
||||
dagExecModeRef.current === "sandbox" &&
|
||||
sandboxFollowThreadIdRef.current &&
|
||||
sandboxFollowThreadIdRef.current !== seatThreadId
|
||||
) {
|
||||
return;
|
||||
}
|
||||
hasAutoOpenedRef.current.add(virtualUrl);
|
||||
}
|
||||
setActiveArtifactThreadId(seatThreadId);
|
||||
const open = () => {
|
||||
selectArtifact(virtualUrl, auto);
|
||||
// select 的第 2 参 = autoSelect:true 表示「自动选,不毒化」;只有真正手动接管才传 false。
|
||||
selectArtifact(virtualUrl, !manual);
|
||||
setArtifactsOpen(true);
|
||||
};
|
||||
if (auto) {
|
||||
@@ -524,6 +652,34 @@ export function useStep2Orchestration(
|
||||
[],
|
||||
);
|
||||
|
||||
/**
|
||||
* sandbox 模式「沙箱跟随」用:打开某席位 thread **最新**写入文件的虚拟预览(强制 auto=false)。
|
||||
* 从该 thread 的 stub messages 里倒序找第一个 write_file / str_replace 的 path。
|
||||
* 无产物返回 false(调用方据此关闭沙箱)。
|
||||
*/
|
||||
const openSeatLatestArtifact = useCallback(
|
||||
(seatThreadId: string): boolean => {
|
||||
const stub = seatStubMessagesRef.current[seatThreadId]?.[0];
|
||||
if (!stub) return false;
|
||||
for (let i = stub.tool_calls.length - 1; i >= 0; i -= 1) {
|
||||
const tc = stub.tool_calls[i];
|
||||
if (tc.name !== "write_file" && tc.name !== "str_replace") continue;
|
||||
const path =
|
||||
typeof (tc.args as { path?: unknown })?.path === "string"
|
||||
? ((tc.args as { path?: string }).path as string)
|
||||
: "";
|
||||
if (!path) continue;
|
||||
const virtualUrl = buildWriteFileVirtualUrl(path, stub.id, tc.id);
|
||||
// manual:false —— 沙箱跟随是系统行为,强制打开但**不**关闭 autoSelect(否则毒化
|
||||
// 后续实时自动打开,见 openSeatVirtualArtifact 注释)。
|
||||
openSeatVirtualArtifact(seatThreadId, virtualUrl, false, { manual: false });
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
},
|
||||
[buildWriteFileVirtualUrl, openSeatVirtualArtifact],
|
||||
);
|
||||
|
||||
/**
|
||||
* 反查某个产出文件是由哪个席位 thread 写入的。
|
||||
*
|
||||
@@ -882,6 +1038,120 @@ export function useStep2Orchestration(
|
||||
);
|
||||
}, []);
|
||||
|
||||
/** 整段替换某气泡正文(§6 flush:把 ref 里累积的全文一次性挂上去)。 */
|
||||
const setDialogueContent = useCallback((id: number, fullText: string) => {
|
||||
setStep2RoundtableDialogues((prev) =>
|
||||
prev.map((d) => (d.id === id ? { ...d, content: fullText } : d)),
|
||||
);
|
||||
}, []);
|
||||
|
||||
// ─── §6 并行流式:全接收 / 惰性渲染 / 节流 ───────────────────────────────
|
||||
/**
|
||||
* 节流 flush(~80ms 一拍,约 12fps):**仅被选中**的席位把 ref 累积的全文挂到
|
||||
* React state 渲染 Markdown(≤2 个)。未选中席位只在 ref 里累积、不挂 DOM —— 6+
|
||||
* 并行也不卡。切到它时下拍即显全文(再叠加选中变化 effect 的即时挂载)。
|
||||
*/
|
||||
const flushParallelStreams = useCallback(() => {
|
||||
parallelFlushTimerRef.current = null;
|
||||
const store = parallelStreamRef.current;
|
||||
if (store.size === 0) return;
|
||||
const selected = new Set(selectedParallelSeatsRef.current);
|
||||
for (const seat of parallelBatchRef.current) {
|
||||
if (selected.has(seat.agentId)) {
|
||||
const entry = store.get(seat.bubbleId);
|
||||
if (entry) setDialogueContent(seat.bubbleId, entry.text);
|
||||
}
|
||||
}
|
||||
}, [setDialogueContent]);
|
||||
|
||||
const scheduleParallelFlush = useCallback(() => {
|
||||
if (parallelFlushTimerRef.current !== null) return;
|
||||
parallelFlushTimerRef.current = window.setTimeout(flushParallelStreams, 80);
|
||||
}, [flushParallelStreams]);
|
||||
|
||||
/** 并行席位的 onTextDelta:全量累积进 ref(O(1)),再调度一次节流 flush。 */
|
||||
const ingestParallelDelta = useCallback(
|
||||
(bubbleId: number, text: string) => {
|
||||
if (!text) return;
|
||||
const store = parallelStreamRef.current;
|
||||
const cur = store.get(bubbleId) ?? { text: "", charCount: 0 };
|
||||
cur.text += text;
|
||||
cur.charCount = cur.text.length;
|
||||
store.set(bubbleId, cur);
|
||||
scheduleParallelFlush();
|
||||
},
|
||||
[scheduleParallelFlush],
|
||||
);
|
||||
|
||||
/** 清空并行流式 store + 取消挂起的 flush(stage 结束 / 抢占 / 异常兜底)。 */
|
||||
const resetParallelStreams = useCallback(() => {
|
||||
parallelStreamRef.current = new Map();
|
||||
if (parallelFlushTimerRef.current !== null) {
|
||||
window.clearTimeout(parallelFlushTimerRef.current);
|
||||
parallelFlushTimerRef.current = null;
|
||||
}
|
||||
}, []);
|
||||
|
||||
// 卸载兜底:清掉可能挂起的 flush 定时器。
|
||||
useEffect(() => resetParallelStreams, [resetParallelStreams]);
|
||||
|
||||
// 选中变化 → 立刻把 ref 里已累积的全文挂给**新选中**的席位(切头像即显全部输出,
|
||||
// 证明流没丢、只是之前没渲染,§6.5)。
|
||||
useEffect(() => {
|
||||
const store = parallelStreamRef.current;
|
||||
if (store.size === 0) return;
|
||||
const selected = new Set(selectedParallelSeats);
|
||||
for (const seat of parallelBatchRef.current) {
|
||||
if (selected.has(seat.agentId)) {
|
||||
const entry = store.get(seat.bubbleId);
|
||||
if (entry) setDialogueContent(seat.bubbleId, entry.text);
|
||||
}
|
||||
}
|
||||
}, [selectedParallelSeats, setDialogueContent]);
|
||||
|
||||
// sandbox 单列模式「沙箱跟随」(防 bug 重点,用户特别强调):切换当前显示的席位时,
|
||||
// 沙箱内容必须等于该席位的内容 —— 有产物则打开它的沙箱,无产物则关闭沙箱面板。
|
||||
// 并把「当前允许显示沙箱的席位 thread」记到 sandboxFollowThreadIdRef,供 openSeatVirtualArtifact
|
||||
// 的 auto 守卫拦掉后台并行席位的抢占(见该函数)。非 sandbox 模式 / 无选中时清空,不干预沙箱。
|
||||
useEffect(() => {
|
||||
const seat = dagExecMode === "sandbox" ? selectedParallelSeats[0] ?? "" : "";
|
||||
// 只在「显示席位真正变化」时 reconcile。否则:本 effect 的 deps(openSeatLatestArtifact /
|
||||
// setArtifactsOpen 等)身份每次 render 都可能变 → effect 反复跑 → 把用户刚手动关闭的沙箱
|
||||
// 又强制重开,表现为「关闭按钮关不掉」。用 key 守卫后,用户关闭(席位没变)时直接早退。
|
||||
const key = `${dagExecMode}:${seat}`;
|
||||
if (lastReconciledSeatRef.current === key) return;
|
||||
lastReconciledSeatRef.current = key;
|
||||
|
||||
if (dagExecMode !== "sandbox" || !seat) {
|
||||
sandboxFollowThreadIdRef.current = null;
|
||||
return;
|
||||
}
|
||||
const ids = threadIdsRef.current;
|
||||
if (!ids) {
|
||||
sandboxFollowThreadIdRef.current = null;
|
||||
return;
|
||||
}
|
||||
const tid = resolveSeatThreadId(ids, seat);
|
||||
sandboxFollowThreadIdRef.current = tid ?? null;
|
||||
if (!tid) return;
|
||||
const opened = openSeatLatestArtifact(tid);
|
||||
if (!opened) {
|
||||
// 当前显示席位**暂时**还没有沙箱产物(常见:并行批次第一个席位刚选中、还没写文件)→
|
||||
// 关闭沙箱面板,但**只用 deselect**(它走 raw setOpen(false),**不**关掉 autoOpen);
|
||||
// 千万别再调 setArtifactsOpen(false) —— 那个 wrapped setter 会把 autoOpen 置 false
|
||||
// (context.tsx:73),导致该席位**随后 live 写文件时 openSeatVirtualArtifact 的
|
||||
// `!autoOpen` 守卫拦掉自动打开**(正是「第一个席位不自动开沙箱、要手动开」的 bug)。
|
||||
setActiveArtifactThreadId(null);
|
||||
deselectArtifact();
|
||||
}
|
||||
}, [
|
||||
selectedParallelSeats,
|
||||
dagExecMode,
|
||||
resolveSeatThreadId,
|
||||
openSeatLatestArtifact,
|
||||
deselectArtifact,
|
||||
]);
|
||||
|
||||
const finalizeDialogue = useCallback(
|
||||
(id: number, finalContent: string, confidence?: string) => {
|
||||
setStep2RoundtableDialogues((prev) =>
|
||||
@@ -969,6 +1239,43 @@ export function useStep2Orchestration(
|
||||
);
|
||||
}, [setRoles]);
|
||||
|
||||
/**
|
||||
* DAG 并行批次:把**一整批**席位同时标为「研讨中」(与 markSpeakerStreaming
|
||||
* 的"排他单发"不同 —— 并行就是要多个 sub 同时高亮)。其余历史残留的"研讨中"清成"在线"。
|
||||
* activeSpeakerSet 天然是 Set,这里放整批 speakerId。
|
||||
*/
|
||||
const markParallelSpeakers = useCallback(
|
||||
(speakerIds: number[]) => {
|
||||
const wanted = new Set(speakerIds);
|
||||
setActiveSpeakerSet(new Set(speakerIds));
|
||||
setRoles((prev) =>
|
||||
prev.map((item) => {
|
||||
if (wanted.has(item.id)) return { ...item, status: "研讨中" };
|
||||
if (item.status === "研讨中") return { ...item, status: "在线" };
|
||||
return item;
|
||||
}),
|
||||
);
|
||||
},
|
||||
[setRoles],
|
||||
);
|
||||
|
||||
/**
|
||||
* 点头像切换主区显示的席位(§5.3):已选中→取消;未选中→加入,超过 2 个按 LRU
|
||||
* 踢掉最早选中的。被换下的席位停止渲染但流仍在内存累积(气泡始终在列表里)。
|
||||
*/
|
||||
const toggleParallelSeat = useCallback((agentId: string) => {
|
||||
setSelectedParallelSeats((prev) => {
|
||||
// sandbox 单列:点头像 = 切换到该席位(始终保留 1 个,点已选中的不取消到空)。
|
||||
if (dagExecModeRef.current === "sandbox") {
|
||||
return prev.length === 1 && prev[0] === agentId ? prev : [agentId];
|
||||
}
|
||||
// fast 双列:点已选中 → 取消;未选中 → 加入,超过 2 个按 LRU 踢最早的。
|
||||
if (prev.includes(agentId)) return prev.filter((id) => id !== agentId);
|
||||
const next = [...prev, agentId];
|
||||
return next.length > 2 ? next.slice(next.length - 2) : next;
|
||||
});
|
||||
}, []);
|
||||
|
||||
// ─── Abort ────────────────────────────────────────────────────────
|
||||
const abortAllInFlight = useCallback(() => {
|
||||
activeAbortersRef.current.forEach((ctrl) => {
|
||||
@@ -993,17 +1300,26 @@ export function useStep2Orchestration(
|
||||
const runOrchestration = useCallback(
|
||||
async (seedMessage: string, ids: ThreadIdMap, coord: string) => {
|
||||
if (isOrchestratingRef.current) return;
|
||||
// **同步**抢占编排锁。isOrchestratingRef 平时由 [isOrchestrating] 的 effect 异步
|
||||
// 回写(见上方),滞后一拍;若只靠它,人工干预里 setIsRoundTableRunning(true) 触发的
|
||||
// 「恢复/干预」effect 会在 ref 尚未变 true 的同一 tick 内再调一次本函数 —— 两个 leader
|
||||
// run 并发打到同一总控 thread(rollback 抢占 → 截断的那个旧报 502、存活的那个重复出现)。
|
||||
// 这里立刻把 ref 置 true,让重入守卫即时生效,堵住二次触发。
|
||||
isOrchestratingRef.current = true;
|
||||
setIsOrchestrating(true);
|
||||
orchestrationCancelRef.current = false;
|
||||
// 认领本轮 epoch。任何更晚启动的循环都会让 epoch 自增 → 本循环 isStale() 立即为真。
|
||||
const myEpoch = (orchestrationEpochRef.current += 1);
|
||||
// 单一「该退出了吗」判定:被显式取消,**或**已被更新的循环接管(epoch 变了)。
|
||||
// 后者专治新循环重置 orchestrationCancelRef=false 把旧循环反取消的并发双发。
|
||||
const isStale = () =>
|
||||
orchestrationCancelRef.current || orchestrationEpochRef.current !== myEpoch;
|
||||
|
||||
let nextLeaderTask = seedMessage;
|
||||
let safetyCounter = 0;
|
||||
|
||||
try {
|
||||
while (
|
||||
!orchestrationCancelRef.current &&
|
||||
safetyCounter < MAX_CYCLES
|
||||
) {
|
||||
while (!isStale() && safetyCounter < MAX_CYCLES) {
|
||||
safetyCounter += 1;
|
||||
// Leader(协调智能体)正在派活,**不应该**让任何 sub agent 显示"研讨中"——
|
||||
// 协调者本身不在右侧"参与角色"面板里(COMMANDER_SEAT_ID=1 是人类主持人,
|
||||
@@ -1034,6 +1350,9 @@ export function useStep2Orchestration(
|
||||
dAgentThreadId: ids,
|
||||
agentName: coord,
|
||||
newMessage: nextLeaderTask,
|
||||
// 第 2 轮起(已有席位交付)才是「综合轮」:让后端注入各席位完整交付供总控收口。
|
||||
// 首轮纯派活、无交付,传 false 保持上下文精简。
|
||||
synthesisMode: safetyCounter > 1,
|
||||
model: selectedModelRef.current || undefined,
|
||||
signal: leaderAborter.signal,
|
||||
onTextDelta: (text) => appendToDialogue(leaderBubbleId, text),
|
||||
@@ -1064,7 +1383,7 @@ export function useStep2Orchestration(
|
||||
}
|
||||
activeAbortersRef.current.delete(leaderAborter);
|
||||
|
||||
if (orchestrationCancelRef.current) break;
|
||||
if (isStale()) break;
|
||||
|
||||
if (leaderRes.clarification) {
|
||||
finalizeDialogue(
|
||||
@@ -1101,7 +1420,7 @@ export function useStep2Orchestration(
|
||||
|
||||
// **顺序**派活 —— 不要改回 Promise.all,详见 §5.4。
|
||||
for (const [subName, task] of leaderRes.dispatched as LeaderDispatch[]) {
|
||||
if (orchestrationCancelRef.current) break;
|
||||
if (isStale()) break;
|
||||
const meta = agentNameToRoleRef.current[subName.toLowerCase()];
|
||||
if (meta) markSpeakerStreaming(meta.speakerId);
|
||||
const perSeatModel = meta
|
||||
@@ -1149,7 +1468,7 @@ export function useStep2Orchestration(
|
||||
onUpstreamFrame: (frame) =>
|
||||
handleUpstreamFrame(frame, seatThreadId),
|
||||
});
|
||||
if (orchestrationCancelRef.current) {
|
||||
if (isStale()) {
|
||||
finalizeDialogue(
|
||||
subBubbleId,
|
||||
specRes.content || "(已停止)",
|
||||
@@ -1181,7 +1500,7 @@ export function useStep2Orchestration(
|
||||
if (aborted) break;
|
||||
}
|
||||
|
||||
if (orchestrationCancelRef.current) break;
|
||||
if (isStale()) break;
|
||||
|
||||
setConsensusPercentage((prev) =>
|
||||
Math.min(95, parseFloat((prev + 8).toFixed(1))),
|
||||
@@ -1229,8 +1548,15 @@ export function useStep2Orchestration(
|
||||
const runChainOrchestration = useCallback(
|
||||
async (seedMessage: string, ids: ThreadIdMap, coord: string) => {
|
||||
if (isOrchestratingRef.current) return;
|
||||
// 同步抢占编排锁(原因同 runOrchestration):堵住人工干预时 isRoundTableRunning
|
||||
// toggle effect 在同一 tick 内的二次触发,避免并发双 leader run。
|
||||
isOrchestratingRef.current = true;
|
||||
setIsOrchestrating(true);
|
||||
orchestrationCancelRef.current = false;
|
||||
// epoch 接管:新循环启动即自增,旧链条循环据此退出(详见 runOrchestration / 声明处注释)。
|
||||
const myEpoch = (orchestrationEpochRef.current += 1);
|
||||
const isStale = () =>
|
||||
orchestrationCancelRef.current || orchestrationEpochRef.current !== myEpoch;
|
||||
|
||||
const chainSeats = selectedAgentsRef.current;
|
||||
const total = chainSeats.length;
|
||||
@@ -1239,7 +1565,7 @@ export function useStep2Orchestration(
|
||||
|
||||
try {
|
||||
for (let i = 0; i < total; i += 1) {
|
||||
if (orchestrationCancelRef.current) {
|
||||
if (isStale()) {
|
||||
finishedAllSeats = false;
|
||||
break;
|
||||
}
|
||||
@@ -1295,7 +1621,7 @@ export function useStep2Orchestration(
|
||||
throw err;
|
||||
}
|
||||
activeAbortersRef.current.delete(leaderAborter);
|
||||
if (orchestrationCancelRef.current) {
|
||||
if (isStale()) {
|
||||
finalizeDialogue(leaderBubbleId, leaderRes.content || "(已停止)", "已停止");
|
||||
finishedAllSeats = false;
|
||||
break;
|
||||
@@ -1357,7 +1683,7 @@ export function useStep2Orchestration(
|
||||
},
|
||||
onUpstreamFrame: (frame) => handleUpstreamFrame(frame, seatThreadId),
|
||||
});
|
||||
if (orchestrationCancelRef.current) {
|
||||
if (isStale()) {
|
||||
finalizeDialogue(subBubbleId, specRes.content || "(已停止)", "已停止");
|
||||
aborted = true;
|
||||
} else {
|
||||
@@ -1384,7 +1710,7 @@ export function useStep2Orchestration(
|
||||
}
|
||||
|
||||
// ── (c) 总控收口:综合全链交付,产出最终结论 ──
|
||||
if (!orchestrationCancelRef.current && finishedAllSeats && total > 0) {
|
||||
if (!isStale() && finishedAllSeats && total > 0) {
|
||||
highlightSpeaker(null);
|
||||
const closeoutBubbleId = appendStreamingDialogue({
|
||||
sender: "总控协调",
|
||||
@@ -1402,6 +1728,8 @@ export function useStep2Orchestration(
|
||||
agentName: coord,
|
||||
newMessage:
|
||||
"各链条席位已按顺序完成发言,请你综合所有席位的交付,输出最终方案与结论。不要再派活、不要再向任何席位分配任务。",
|
||||
// 链条收口就是综合轮:让后端注入各席位完整交付正文。
|
||||
synthesisMode: true,
|
||||
model: selectedModelRef.current || undefined,
|
||||
signal: closeoutAborter.signal,
|
||||
onTextDelta: (text) => appendToDialogue(closeoutBubbleId, text),
|
||||
@@ -1456,13 +1784,366 @@ export function useStep2Orchestration(
|
||||
],
|
||||
);
|
||||
|
||||
// ─── DAG orchestration loop ───────────────────────────────────────
|
||||
// dag 模式(§3 + §3.2 方案 A,2026-06-07 改成「总控驱动」):分层执行 —— stage 内**并行**
|
||||
// (Promise.all)、stage 间**串行**(Promise.all 即 barrier)。每个 stage 的流程与串行同构:
|
||||
// 1) **总控派活轮**:由【总控】对本 stage 计划钉死的席位**真正派活**(buildDagStageLeaderTask
|
||||
// 约束它只派给这些席位、且每个都派到;不自由乱派、不收口)。总控本轮也"承上"——后端
|
||||
// _build_seat_status_block 走轻量 last-ai-message 把此前各席位真实交付(摘要)注入其输入
|
||||
// (§传摘要按需传全文);
|
||||
// 2) **批内并行**:本 stage 席位并行跑总控派给各自的 task(pickDagSeatTask 命中其 agent_name,
|
||||
// 漏派则回退总控正文/模板,不借用别席位 task);完成后交付经后端 detached 广播回总控;
|
||||
// 3) barrier 后进入下一 stage,总控再派下一批(它已能看到上一批交付摘要)。
|
||||
// 所有 stage 跑完后,把锁交回 runOrchestration 由总控综合 / 收口(此时 synthesisMode 才按需
|
||||
// 注入各席位**完整交付正文**——全文只在收口这一轮付出)。
|
||||
//
|
||||
// 与「前端直派(方案 B)」的区别:每 stage 都经总控决策派活(像串行/链条那样),计划只钉死
|
||||
// 「派给谁」、总控负责「派什么活 + 承上启下」。与 chain 模式同构,区别是一次钉死一批、批内并行。
|
||||
//
|
||||
// 与 runOrchestration / runChainOrchestration 的「不要 Promise.all」不变量不同 ——
|
||||
// DAG 并行就是要 Promise.all;N 路 token 级 setState 的卡顿由 Phase 6(全接收 /
|
||||
// 惰性渲染 / 节流)解决,且单 stage 并行度有 warning 上限(PARALLEL_DEGREE_WARN_THRESHOLD)。
|
||||
const runDagOrchestration = useCallback(
|
||||
async (seedMessage: string, ids: ThreadIdMap, coord: string) => {
|
||||
const plan = orchestrationPlanRef.current;
|
||||
if (!plan || plan.stages.length === 0) {
|
||||
triggerToast("⚠️ 没有可执行的 DAG 编排计划");
|
||||
return;
|
||||
}
|
||||
if (isOrchestratingRef.current) return;
|
||||
// 同步抢占编排锁(原因同 runOrchestration):堵住人工干预 / 恢复 toggle 在同一
|
||||
// tick 内的二次触发,避免并发双发。
|
||||
isOrchestratingRef.current = true;
|
||||
setIsOrchestrating(true);
|
||||
orchestrationCancelRef.current = false;
|
||||
const myEpoch = (orchestrationEpochRef.current += 1);
|
||||
const isStale = () =>
|
||||
orchestrationCancelRef.current || orchestrationEpochRef.current !== myEpoch;
|
||||
// 标记 DAG 计划已开始执行:此后任何 runActiveOrchestration(干预 / 恢复 / 澄清)
|
||||
// 都改走 leader 循环,不再重跑整张 DAG。
|
||||
dagPlanExecutedRef.current = true;
|
||||
|
||||
const leaderThreadId = resolveSeatThreadId(ids, coord);
|
||||
let finishedAllStages = true;
|
||||
// 跨 stage 累积的**完整交付** {name, content}[] —— 注入下一 stage 席位的 run context
|
||||
// (peerDeliveries),供 read_peer_delivery 工具按需取全文(§12.9 传摘要按需传全文)。
|
||||
const priorDeliveries: Array<{ name: string; content: string }> = [];
|
||||
|
||||
// Phase 7:初始化 DAG 流程图节点状态 —— 计划内所有席位置 pending,执行过程中逐个点亮。
|
||||
const markDagNode = (agentId: string, state: ChainNodeState) =>
|
||||
setDagNodeStates((prev) => ({ ...prev, [agentId.toLowerCase()]: state }));
|
||||
setDagNodeStates(
|
||||
Object.fromEntries(
|
||||
plan.stages.flatMap((st) => st.agentIds.map((id) => [id.toLowerCase(), "pending" as ChainNodeState])),
|
||||
),
|
||||
);
|
||||
|
||||
try {
|
||||
for (let s = 0; s < plan.stages.length; s += 1) {
|
||||
if (isStale()) {
|
||||
finishedAllStages = false;
|
||||
break;
|
||||
}
|
||||
const stage = plan.stages[s];
|
||||
const isParallel = stage.agentIds.length > 1;
|
||||
// 本 stage 计划钉死的席位元数据(供派活轮 + 并行执行共用)。
|
||||
const stageSeats = stage.agentIds.map((agentId) => {
|
||||
const meta = agentNameToRoleRef.current[agentId.toLowerCase()];
|
||||
return { agentId, meta, name: meta?.displayName ?? agentId };
|
||||
});
|
||||
|
||||
// ── (a) 总控派活轮(§3.2 方案 A + 批内并行):由【总控】对本 stage 计划钉死的
|
||||
// 席位**真正派活**(约束只派给这些席位、且每个都派到),而不是前端直发。总控本轮
|
||||
// 也"承上":后端 _build_seat_status_block 已把此前各席位真实交付(摘要)注入其输入
|
||||
// (传摘要按需传全文)。它不自由乱派、不收口。与 chain 同构,区别是一次钉死一批、批内并行。
|
||||
highlightSpeaker(null);
|
||||
const leaderBubbleId = appendStreamingDialogue({
|
||||
sender: "总控协调",
|
||||
avatarType: "blue",
|
||||
initialContent: "",
|
||||
confidence: s === 0 ? "派活中" : "承上派活中",
|
||||
agentThreadId: leaderThreadId,
|
||||
});
|
||||
const leaderTask = buildDagStageLeaderTask({
|
||||
seedMessage,
|
||||
stageIndex: s,
|
||||
totalStages: plan.stages.length,
|
||||
seats: stageSeats.map((p) => ({ agentId: p.agentId, name: p.name })),
|
||||
isFirst: s === 0,
|
||||
goal: stage.goal, // 业务链条里为本阶段写的「本阶段目标」(可空)
|
||||
coordinatorPrompt: plan.coordinatorPrompt, // 写给总控的整体派活指引(可空,每阶段都注入)
|
||||
});
|
||||
const leaderAborter = new AbortController();
|
||||
activeAbortersRef.current.add(leaderAborter);
|
||||
let leaderRes;
|
||||
try {
|
||||
leaderRes = await streamMultiAgent({
|
||||
agentType: "leader",
|
||||
dAgentThreadId: ids,
|
||||
agentName: coord,
|
||||
newMessage: leaderTask,
|
||||
// 派活轮:传 false,后端只注入各席位摘要;完整交付正文留给末尾收口的 synthesis 轮。
|
||||
synthesisMode: false,
|
||||
// 抑制预广播:别把总控的派活 prompt 播进席位 thread(否则弱模型从历史里捡到派活
|
||||
// 意图、跟着模仿派活 / 绕道 bash 调内部接口)。席位任务由 pickDagSeatTask 干净下发。
|
||||
suppressPreBroadcast: true,
|
||||
model: selectedModelRef.current || undefined,
|
||||
signal: leaderAborter.signal,
|
||||
onTextDelta: (text) => appendToDialogue(leaderBubbleId, text),
|
||||
onPhaseChange: (phase, toolName, args) => {
|
||||
const label = phaseLabel(phase, "leader", toolName);
|
||||
setDialogueConfidence(leaderBubbleId, label);
|
||||
appendStepIfNew(leaderBubbleId, label, `${phase}:${toolName ?? ""}`, args);
|
||||
handleArtifactToolPhase(phase, toolName, args, leaderThreadId);
|
||||
},
|
||||
onUpstreamFrame: (frame) => handleUpstreamFrame(frame, leaderThreadId),
|
||||
});
|
||||
} catch (err) {
|
||||
activeAbortersRef.current.delete(leaderAborter);
|
||||
if (leaderAborter.signal.aborted || (err as Error).name === "AbortError") {
|
||||
finalizeDialogue(leaderBubbleId, "(已停止)", "已停止");
|
||||
finishedAllStages = false;
|
||||
break;
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
activeAbortersRef.current.delete(leaderAborter);
|
||||
if (isStale()) {
|
||||
finalizeDialogue(leaderBubbleId, leaderRes.content || "(已停止)", "已停止");
|
||||
finishedAllStages = false;
|
||||
break;
|
||||
}
|
||||
// 派活轮也可能要求澄清 → 暂停 DAG(回复后走 leader 自由派活、不重跑 DAG)。
|
||||
if (leaderRes.clarification) {
|
||||
finalizeDialogue(leaderBubbleId, leaderRes.content, "等待用户澄清");
|
||||
setPendingClarification(leaderRes.clarification);
|
||||
setClarificationDraft("");
|
||||
triggerToast("❓ 总控需要补充信息,请回答下方问题后继续");
|
||||
finishedAllStages = false;
|
||||
break;
|
||||
}
|
||||
finalizeDialogue(leaderBubbleId, leaderRes.content, "派活说明");
|
||||
if (leaderRes.content) setLastLeaderContent(leaderRes.content);
|
||||
|
||||
// ── (b) 本 stage 席位【并行】执行总控下发的 task ──
|
||||
// 预备各席位气泡(在 Promise.all 之前同步建好,这样并行显示(§5)的头像条/两列
|
||||
// 能立刻拿到每个席位的 bubbleId 去渲染对应消息流)。
|
||||
const seatPrep = stageSeats.map(({ agentId, meta, name }) => {
|
||||
const avatarType = meta?.avatarType ?? "blue";
|
||||
const seatThreadId = resolveSeatThreadId(ids, agentId);
|
||||
const bubbleId = appendStreamingDialogue({
|
||||
sender: name,
|
||||
avatarType,
|
||||
initialContent: "",
|
||||
confidence: "调度中",
|
||||
agentThreadId: seatThreadId,
|
||||
});
|
||||
return { agentId, meta, seatName: name, avatarType, seatThreadId, bubbleId };
|
||||
});
|
||||
|
||||
// 整批高亮(并行)。单节点 stage 退化为高亮一个,行为与串行一致。
|
||||
markParallelSpeakers(
|
||||
seatPrep.map((p) => p.meta?.speakerId).filter((v): v is number => typeof v === "number"),
|
||||
);
|
||||
// Phase 7:本 stage 席位置 active(流程图点亮当前列)。
|
||||
for (const p of seatPrep) markDagNode(p.agentId, "active");
|
||||
|
||||
// 并行 stage(≥2 席位)才发布「并行批次」给前端头像条 + 主区显示。
|
||||
// fast(双列)默认选中最先两个;sandbox(单列)只选最先一个,点头像切换。
|
||||
if (isParallel) {
|
||||
setParallelBatch(
|
||||
seatPrep.map((p) => ({
|
||||
agentId: p.agentId,
|
||||
displayName: p.seatName,
|
||||
avatarType: p.avatarType,
|
||||
status: "running" as const,
|
||||
bubbleId: p.bubbleId,
|
||||
})),
|
||||
);
|
||||
const cols = dagExecModeRef.current === "sandbox" ? 1 : 2;
|
||||
setSelectedParallelSeats(seatPrep.slice(0, cols).map((p) => p.agentId));
|
||||
}
|
||||
const markBatchStatus = (agentId: string, status: ParallelSeatView["status"]) =>
|
||||
setParallelBatch((prev) =>
|
||||
prev.map((p) => (p.agentId === agentId ? { ...p, status } : p)),
|
||||
);
|
||||
|
||||
// ── 批内并行:对 stage 内每个席位发 special run,跑总控本轮派给它的 task ──
|
||||
// 每个席位独立 try/catch 兜底,保证**单席位失败不拖垮整 stage**(§9):
|
||||
// 任务函数永不 reject → Promise.all 不会因一个席位异常整体崩。
|
||||
const stageResults = await Promise.all(
|
||||
seatPrep.map(async ({ agentId, meta, seatName, seatThreadId, bubbleId }): Promise<{ name: string; content: string } | null> => {
|
||||
const perSeatModel = meta
|
||||
? agentConfigsRef.current[meta.speakerId]?.model
|
||||
: undefined;
|
||||
// 用总控本轮派给该席位的 task(命中其 agent_name);总控没用工具只写文字时,
|
||||
// pickDagSeatTask 给干净本职任务、**不**注入总控派活叙述(根治「席位模仿派活」)。
|
||||
// 带上 seedMessage:预广播已抑制,席位 thread 里没有用户原始消息,靠 task 补背景。
|
||||
const task = pickDagSeatTask(
|
||||
leaderRes.dispatched,
|
||||
agentId,
|
||||
seatName,
|
||||
seedMessage,
|
||||
priorDeliveries.length > 0,
|
||||
dagExecModeRef.current === "sandbox", // 仅沙箱模式要求写 .md 文件;快速模式产物走正文
|
||||
stage.goal, // 兜底注入「本阶段目标」(总控没派好时席位仍据此对齐)
|
||||
);
|
||||
|
||||
const subAborter = new AbortController();
|
||||
activeAbortersRef.current.add(subAborter);
|
||||
try {
|
||||
const specRes = await streamMultiAgent({
|
||||
agentType: "special",
|
||||
dAgentThreadId: ids,
|
||||
agentName: agentId,
|
||||
displayName: seatName,
|
||||
newMessage: task,
|
||||
// 写文件只在 **沙箱模式**(seat policy)开放;**快速模式一律禁写文件**(seat_parallel,
|
||||
// 产物走正文,§12.10 用户要求 fast 不生成文件)。与 stage 是否并行无关:fast 单节点
|
||||
// stage 也禁写(保持 fast=无文件的一致体验)。
|
||||
parallelNoFile: dagExecModeRef.current !== "sandbox",
|
||||
// 前序各阶段的完整交付 → 供本席位 read_peer_delivery 按需取全文(§12.9)。
|
||||
peerDeliveries: priorDeliveries,
|
||||
model: perSeatModel || selectedModelRef.current || undefined,
|
||||
signal: subAborter.signal,
|
||||
// §6:并行席位走 ref 全量累积 + 节流 flush(只渲染选中的);单节点
|
||||
// stage 实际串行,1 路流直接 setState 不卡,沿用 appendToDialogue。
|
||||
onTextDelta: (text) =>
|
||||
isParallel ? ingestParallelDelta(bubbleId, text) : appendToDialogue(bubbleId, text),
|
||||
onPhaseChange: (phase, toolName, args) => {
|
||||
const label = phaseLabel(phase, "special", toolName);
|
||||
setDialogueConfidence(bubbleId, label);
|
||||
appendStepIfNew(bubbleId, label, `${phase}:${toolName ?? ""}`, args);
|
||||
handleArtifactToolPhase(phase, toolName, args, seatThreadId);
|
||||
},
|
||||
onUpstreamFrame: (frame) => handleUpstreamFrame(frame, seatThreadId),
|
||||
});
|
||||
if (isStale()) {
|
||||
finalizeDialogue(bubbleId, specRes.content || "(已停止)", "已停止");
|
||||
markBatchStatus(agentId, "done");
|
||||
return null;
|
||||
}
|
||||
finalizeDialogue(bubbleId, specRes.content, "子智能体交付");
|
||||
markBatchStatus(agentId, "done");
|
||||
return specRes.content?.trim() ? { name: seatName, content: specRes.content } : null;
|
||||
} catch (err) {
|
||||
if (subAborter.signal.aborted || (err as Error).name === "AbortError") {
|
||||
finalizeDialogue(bubbleId, "(已停止)", "已停止");
|
||||
markBatchStatus(agentId, "done");
|
||||
} else {
|
||||
console.error(`[dag-special:${agentId}] error:`, err);
|
||||
finalizeDialogue(bubbleId, `(错误) ${(err as Error).message}`, "调用失败");
|
||||
markBatchStatus(agentId, "error");
|
||||
}
|
||||
return null;
|
||||
} finally {
|
||||
activeAbortersRef.current.delete(subAborter);
|
||||
if (meta) markSpeakerIdle(meta.speakerId);
|
||||
// Phase 7:席位到终态(成功/失败/抢占)→ 流程图节点打勾。ChainNodeState 无
|
||||
// error 态,失败也归 done(节点已结束);失败细节体现在气泡正文。
|
||||
markDagNode(agentId, "done");
|
||||
// 终态后从 ref store 删除,节流 flush 不再覆盖已 finalize 的正文。
|
||||
parallelStreamRef.current.delete(bubbleId);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
// 本 stage 结束(barrier 到达):收起并行批次,回到普通流式列表 + 清流式 store。
|
||||
if (isParallel) {
|
||||
setParallelBatch([]);
|
||||
setSelectedParallelSeats([]);
|
||||
resetParallelStreams();
|
||||
}
|
||||
|
||||
// Promise.all 即 barrier:本 stage 全部终态后才进入下一 stage(批间串行)。
|
||||
// 下一 stage 的总控派活轮会"承上"(后端注入本批真实交付摘要),无需前端再拼摘要。
|
||||
if (isStale()) {
|
||||
finishedAllStages = false;
|
||||
break;
|
||||
}
|
||||
// 累积本 stage 的**完整交付**,供后续 stage 席位 read_peer_delivery 按需取全文(§12.9)。
|
||||
for (const r of stageResults) {
|
||||
if (r && r.content?.trim()) priorDeliveries.push(r);
|
||||
}
|
||||
setConsensusPercentage(
|
||||
Math.min(95, Math.round(((s + 1) / plan.stages.length) * 90)),
|
||||
);
|
||||
}
|
||||
|
||||
// ── 计划阶段全部完成 → **交给总控(leader 自由派活循环)继续** ──
|
||||
// 关键修复:并行/各阶段输出完后,一定要回到总控,由它综合并**按需继续派活 / 收口**,
|
||||
// 而不是停在一次性 synthesis。这里把 DAG 的编排锁释放,委托给 runOrchestration
|
||||
// (它有自己的重入守卫 + epoch + 收敛逻辑)。后续用户干预 / 恢复同样走 leader
|
||||
// (见 runActiveOrchestration 的 dagPlanExecutedRef 闸门),不再重跑整张 DAG。
|
||||
if (!isStale() && finishedAllStages && plan.finalSynthesis) {
|
||||
highlightSpeaker(null);
|
||||
isOrchestratingRef.current = false; // 释放锁,让 runOrchestration 即刻接管
|
||||
setIsOrchestrating(false);
|
||||
await runOrchestration(
|
||||
"各阶段席位已按依赖编排完成交付。请你作为总控,综合各席位的交付:若仍需补充则继续派活,否则直接输出最终方案并收口。",
|
||||
ids,
|
||||
coord,
|
||||
);
|
||||
return;
|
||||
} else if (!isStale() && finishedAllStages) {
|
||||
// 不收口(plan.finalSynthesis=false):全部 stage 跑完即视为完成,不再叫总控。
|
||||
setConsensusPercentage(100);
|
||||
setHasConsensus(true);
|
||||
triggerToast("✅ 依赖编排各阶段已全部完成");
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("dag orchestration error:", err);
|
||||
triggerToast(`❌ 依赖编排研讨异常: ${(err as Error).message}`);
|
||||
} finally {
|
||||
highlightSpeaker(null);
|
||||
clearAllStreamingSpeakers();
|
||||
// 兜底收起并行批次(正常路径已在 stage 结束时清空,异常 / 抢占时这里保证不残留)。
|
||||
setParallelBatch([]);
|
||||
setSelectedParallelSeats([]);
|
||||
resetParallelStreams();
|
||||
setIsOrchestrating(false);
|
||||
}
|
||||
},
|
||||
[
|
||||
appendStreamingDialogue,
|
||||
appendToDialogue,
|
||||
appendStepIfNew,
|
||||
setDialogueConfidence,
|
||||
phaseLabel,
|
||||
finalizeDialogue,
|
||||
highlightSpeaker,
|
||||
markParallelSpeakers,
|
||||
markSpeakerIdle,
|
||||
clearAllStreamingSpeakers,
|
||||
triggerToast,
|
||||
handleArtifactToolPhase,
|
||||
handleUpstreamFrame,
|
||||
resolveSeatThreadId,
|
||||
ingestParallelDelta,
|
||||
resetParallelStreams,
|
||||
runOrchestration,
|
||||
],
|
||||
);
|
||||
|
||||
// 按当前模式分发到对应编排函数。init / 恢复 / 干预 / 澄清回复统一走这里。
|
||||
const runActiveOrchestration = useCallback(
|
||||
(seedMessage: string, ids: ThreadIdMap, coord: string) =>
|
||||
orchestrationModeRef.current === "chain"
|
||||
? runChainOrchestration(seedMessage, ids, coord)
|
||||
: runOrchestration(seedMessage, ids, coord),
|
||||
[runOrchestration, runChainOrchestration],
|
||||
(seedMessage: string, ids: ThreadIdMap, coord: string) => {
|
||||
const mode = orchestrationModeRef.current;
|
||||
// dag:**只在计划尚未跑过时**执行整张 DAG;一旦跑过(用户干预 / 恢复 / 澄清回复),
|
||||
// 改走 leader 自由派活循环,由总控接着派活,而不是把 DAG 从头重跑一遍。
|
||||
if (
|
||||
mode === "dag" &&
|
||||
!dagPlanExecutedRef.current &&
|
||||
(orchestrationPlanRef.current?.stages.length ?? 0) > 0
|
||||
) {
|
||||
return runDagOrchestration(seedMessage, ids, coord);
|
||||
}
|
||||
if (mode === "chain") {
|
||||
return runChainOrchestration(seedMessage, ids, coord);
|
||||
}
|
||||
return runOrchestration(seedMessage, ids, coord);
|
||||
},
|
||||
[runOrchestration, runChainOrchestration, runDagOrchestration],
|
||||
);
|
||||
|
||||
// ─── Effects ─────────────────────────────────────────────────────
|
||||
@@ -1604,7 +2285,7 @@ export function useStep2Orchestration(
|
||||
content: `💡 (人工指令介入) ${userText}`,
|
||||
confidence: "最高指令",
|
||||
});
|
||||
pendingInjectPromptRef.current = `用户人工干预新指令:${userText}\n\n请结合当前讨论状态,决定是否继续派活或直接给出更新后的结论。`;
|
||||
pendingInjectPromptRef.current = `用户人工干预新指令:${userText}\n\n请优先按这条新指令,通过 agent_orchestration 把活派给相关的真实席位去获取交付;若用户点名了某个席位(如"前端实现"),必须派给清单里对应的那个 agent_name。**不要**自己代答,也**不要**在没有真正看到该席位「完成…交付内容为:…」的情况下臆造交付或直接收口。只有当用户明确要求收口、或相关席位都已真实交付时,才综合输出结论。`;
|
||||
triggerToast("干预指令已记录,会商已自动恢复执行");
|
||||
}, [appendDialogue, customAgentInput, triggerToast]);
|
||||
|
||||
@@ -1631,7 +2312,7 @@ export function useStep2Orchestration(
|
||||
confidence: "最高指令",
|
||||
});
|
||||
|
||||
const prompt = `用户人工干预新指令:${userText}\n\n请结合当前讨论状态,决定是否继续派活或直接给出更新后的结论。`;
|
||||
const prompt = `用户人工干预新指令:${userText}\n\n请优先按这条新指令,通过 agent_orchestration 把活派给相关的真实席位去获取交付;若用户点名了某个席位(如"前端实现"),必须派给清单里对应的那个 agent_name。**不要**自己代答,也**不要**在没有真正看到该席位「完成…交付内容为:…」的情况下臆造交付或直接收口。只有当用户明确要求收口、或相关席位都已真实交付时,才综合输出结论。`;
|
||||
|
||||
// 确保处于运行状态(同步更新按钮 UI)
|
||||
setIsRoundTableRunning(true);
|
||||
@@ -1739,6 +2420,8 @@ export function useStep2Orchestration(
|
||||
|
||||
const resetInitGate = useCallback(() => {
|
||||
step2InitRef.current = false;
|
||||
// 新一轮研讨:允许 DAG 计划重新执行一遍。
|
||||
dagPlanExecutedRef.current = false;
|
||||
setInitNonce((n) => n + 1);
|
||||
}, []);
|
||||
|
||||
@@ -1794,6 +2477,10 @@ export function useStep2Orchestration(
|
||||
setLastLeaderContent("");
|
||||
setHasConsensus(false);
|
||||
setConsensusPercentage(0);
|
||||
setParallelBatch([]);
|
||||
setSelectedParallelSeats([]);
|
||||
setDagNodeStates({});
|
||||
resetParallelStreams();
|
||||
setActiveArtifactThreadId(null);
|
||||
artifactPathsRef.current = [];
|
||||
setArtifacts([]);
|
||||
@@ -1801,9 +2488,10 @@ export function useStep2Orchestration(
|
||||
setSeatStubMessages({});
|
||||
hasAutoOpenedRef.current = new Set();
|
||||
pendingInjectPromptRef.current = null;
|
||||
dagPlanExecutedRef.current = false;
|
||||
deselectArtifact();
|
||||
step2InitRef.current = false;
|
||||
}, [abortAllInFlight, deselectArtifact, setArtifacts]);
|
||||
}, [abortAllInFlight, deselectArtifact, setArtifacts, resetParallelStreams]);
|
||||
|
||||
return {
|
||||
selectedAgents,
|
||||
@@ -1823,6 +2511,11 @@ export function useStep2Orchestration(
|
||||
activeSpeakerSet,
|
||||
customAgentInput,
|
||||
isUpperPanelCollapsed,
|
||||
parallelBatch,
|
||||
selectedParallelSeats,
|
||||
isParallelRunning: parallelBatch.length > 0,
|
||||
toggleParallelSeat,
|
||||
dagNodeStates,
|
||||
budgetLimit,
|
||||
agentConfigs,
|
||||
selectedAgentId,
|
||||
|
||||
@@ -5,9 +5,12 @@
|
||||
* (`/api/roundtable-chains`,按登录用户隔离)。在 Step 2 圆桌研讨里,总控会**按
|
||||
* 链条顺序逐个派活**(见 `docs/multi-agent-business-chain-dev.md` §6)。
|
||||
*
|
||||
* 这里只放纯类型 / 常量,不含 React 状态或请求逻辑(CRUD 在 `api/chains.ts`)。
|
||||
* 这里放纯类型 / 常量,以及不依赖 React 的纯函数(如 `buildChainSeatSelection`);
|
||||
* 不含状态或请求逻辑(CRUD 在 `api/chains.ts`)。
|
||||
*/
|
||||
|
||||
import { buildPlanFromStages } from "./dag-types";
|
||||
|
||||
/** 链条里的一个有序席位。`seats[0]` 是第一个发言者。 */
|
||||
export interface ChainSeat {
|
||||
agent_id: string;
|
||||
@@ -27,27 +30,114 @@ export interface BusinessChain {
|
||||
description?: string;
|
||||
/** 有序席位列表。 */
|
||||
seats: ChainSeat[];
|
||||
/**
|
||||
* 可选「分层编排」:把 `seats` 分成若干阶段(stage),每个阶段内的 agent_id
|
||||
* 并行、阶段之间串行。如 `[["a","b"],["c"]]` = (a‖b) → c。缺省 / null = 线性链
|
||||
* (每席位独立一层)。有分层时,选入 Step 2 走 `dag` 编排(见 `lib/dag-types.ts`)。
|
||||
*/
|
||||
stages?: string[][] | null;
|
||||
/**
|
||||
* 可选「每阶段目标」:与 `stages` **同下标对齐**(`stageGoals[i]` 是 `stages[i]` 的
|
||||
* 目标),告诉总控本阶段要产出什么、如何依赖上一阶段产出。仅 dag 模式注入;`stages`
|
||||
* 为 null(线性)时本字段也为 null。某位为 null / 空 = 该阶段不带目标。
|
||||
*/
|
||||
stageGoals?: (string | null)[] | null;
|
||||
/**
|
||||
* 可选「总控编排提示」:用户写给**总控(协调)智能体**的一段指引,告诉总控该怎么派活、
|
||||
* 做什么(整体编排策略 / 风格 / 约束)。**仅 dag 模式生效**,注入总控每阶段派活提示。
|
||||
* 空 / null = 不注入。
|
||||
*/
|
||||
coordinatorPrompt?: string | null;
|
||||
/** 是否已发布为公共(所有账号可在「公共」筛选查看 / 选入研讨)。 */
|
||||
isPublic?: boolean;
|
||||
/** 是否当前用户所有(仅本人可编辑 / 删除 / 发布;公共筛选里别人的链条为 false)。 */
|
||||
isMine?: boolean;
|
||||
createdAt?: string;
|
||||
updatedAt?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 推荐弹窗(席位来源选择器)确认后回传给主页面的统一结果。
|
||||
* 两种模式(智能推荐 / 业务链条)最终都产出**有序**的 `agents` + 一个 `mode`。
|
||||
* 三种模式(智能推荐 / 业务链条线性 / 业务链条分层 DAG)最终都产出**有序**的
|
||||
* `agents` + 一个 `mode`。
|
||||
*/
|
||||
export interface SeatSelectionResult {
|
||||
/** 有序席位 —— 与现有 `handleConfirmAgents` 入参兼容。 */
|
||||
/** 有序席位 —— 与现有 `handleConfirmAgents` 入参兼容。dag 模式下按 stage 展平排序。 */
|
||||
agents: Array<{ agent_id: string; name: string }>;
|
||||
/** 决定 Step 2 走哪种编排:自由派活 vs 按链条顺序派活。 */
|
||||
mode: "recommend" | "chain";
|
||||
/** chain 模式带上来源链条(用于草稿快照 / Step 2 展示链名)。 */
|
||||
/**
|
||||
* 决定 Step 2 走哪种编排:
|
||||
* - `recommend` 总控自由派活;
|
||||
* - `chain` 按链条顺序逐位派活;
|
||||
* - `dag` 分层并行(来源链条带 `stages` 时)。
|
||||
*/
|
||||
mode: "recommend" | "chain" | "dag";
|
||||
/** chain / dag 模式带上来源链条(用于草稿快照 / Step 2 展示链名)。 */
|
||||
chain?: Pick<BusinessChain, "id" | "title">;
|
||||
/** dag 模式带上由链条 `stages` 构造的执行计划(见 `lib/dag-types.ts`)。 */
|
||||
plan?: import("./dag-types").OrchestrationPlan;
|
||||
/**
|
||||
* dag 模式的执行子模式(仅 `mode === "dag"` 有意义):
|
||||
* - `fast`(快速):同 stage 席位**并行**、主区**双列**显示、**禁写文件**(seat_parallel);
|
||||
* - `sandbox`(沙箱):同 stage 席位仍**并行**,但主区**单列**显示、**允许写文件**(seat),
|
||||
* 沙箱跟随当前显示的席位(点头像切换,沙箱内容随之切换/关闭)。
|
||||
* 缺省 `fast`。
|
||||
*/
|
||||
dagExecMode?: "fast" | "sandbox";
|
||||
}
|
||||
|
||||
/** 链条席位数硬约束,与圆桌推荐弹窗的 `MIN_SELECTED`/`MAX_SELECTED` 对齐。 */
|
||||
export const CHAIN_MIN_SEATS = 2;
|
||||
export const CHAIN_MAX_SEATS = 8;
|
||||
|
||||
/**
|
||||
* 由一条业务链条 + 当前候选智能体,构造 `SeatSelectionResult`。
|
||||
*
|
||||
* 与 `BusinessChainPicker.handleUse` 同源逻辑,抽成纯函数供「自动选链」复用
|
||||
* (会商自动化串联:从任务页带 chainId 进圆桌时跳过选链弹窗,直接据此进 Step 2):
|
||||
* - 仅保留候选池里仍存在的存活席位;存活不足 `CHAIN_MIN_SEATS` 返回 null(调用方回退弹窗);
|
||||
* - 链条带分层、过滤存活后仍含并行 stage / 任一阶段目标 / 总控提示 → 走 `dag`(默认 fast);
|
||||
* - 否则走线性 `chain`,席位顺序 = 链条顺序。
|
||||
*
|
||||
* `candidates` 为 `{ agent_id, name }` 列表(一般来自 `filterRecommendCandidates(listAgents())`)。
|
||||
*/
|
||||
export function buildChainSeatSelection(
|
||||
chain: BusinessChain,
|
||||
candidates: ReadonlyArray<{ agent_id: string; name: string }>,
|
||||
): SeatSelectionResult | null {
|
||||
const existingIds = new Set(candidates.map((c) => c.agent_id));
|
||||
const nameById = new Map(candidates.map((c) => [c.agent_id, c.name]));
|
||||
const seatNameById = new Map(chain.seats.map((s) => [s.agent_id, s.name]));
|
||||
const nameOf = (id: string) => nameById.get(id) ?? seatNameById.get(id) ?? id;
|
||||
|
||||
const survivingSeats = chain.seats.filter((s) => existingIds.has(s.agent_id));
|
||||
if (survivingSeats.length < CHAIN_MIN_SEATS) return null;
|
||||
|
||||
const chainMeta = { id: chain.id, title: chain.title };
|
||||
|
||||
if (chain.stages && chain.stages.length > 0) {
|
||||
const surviveIds = survivingSeats.map((s) => s.agent_id);
|
||||
const plan = buildPlanFromStages(
|
||||
chain.stages,
|
||||
surviveIds,
|
||||
true,
|
||||
chain.stageGoals,
|
||||
chain.coordinatorPrompt,
|
||||
);
|
||||
const hasParallel = plan.stages.some((st) => st.agentIds.length > 1);
|
||||
const hasGoal = plan.stages.some((st) => (st.goal?.trim() ?? "") !== "");
|
||||
const hasCoord = (plan.coordinatorPrompt?.trim() ?? "") !== "";
|
||||
if (hasParallel || hasGoal || hasCoord) {
|
||||
const agents = plan.stages
|
||||
.flatMap((st) => st.agentIds)
|
||||
.map((id) => ({ agent_id: id, name: nameOf(id) }));
|
||||
return { agents, mode: "dag", chain: chainMeta, plan, dagExecMode: "fast" };
|
||||
}
|
||||
}
|
||||
|
||||
const agents = survivingSeats.map((s) => ({ agent_id: s.agent_id, name: nameOf(s.agent_id) }));
|
||||
return { agents, mode: "chain", chain: chainMeta };
|
||||
}
|
||||
|
||||
/**
|
||||
* 把 `getAvatarTypeFor()` 产出的头像配色(blue/purple/emerald/amber/pink/human)
|
||||
* 映射成 tag chip 的 tailwind 类(背景 + 文字 + 边框,含深色变体)。
|
||||
|
||||
@@ -0,0 +1,230 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
|
||||
import {
|
||||
addEmptyStage,
|
||||
addSeatAsNewStage,
|
||||
addSeatToStage,
|
||||
chainToStageGroups,
|
||||
countSeats,
|
||||
deleteStage,
|
||||
findStageIndexOfSeat,
|
||||
moveSeatToStage,
|
||||
moveStage,
|
||||
removeSeat,
|
||||
setStageGoal,
|
||||
splitSeatToNewStage,
|
||||
stageGroupsToSeats,
|
||||
stageGroupsToStageGoals,
|
||||
stageGroupsToStagePayload,
|
||||
type StageGroups,
|
||||
} from "./chain-stages";
|
||||
|
||||
const seat = (id: string) => ({ agent_id: id, name: id.toUpperCase(), description: "" });
|
||||
/** 把席位数组的数组包成 StageGroup[](测试构造便捷)。 */
|
||||
const grp = (...stages: ReturnType<typeof seat>[][]): StageGroups =>
|
||||
stages.map((seats) => ({ seats }));
|
||||
const ids = (groups: StageGroups) => groups.map((g) => g.seats.map((s) => s.agent_id));
|
||||
|
||||
// ── chainToStageGroups ────────────────────────────────────────────────────────
|
||||
|
||||
test("chainToStageGroups: linear chain (no stages) → one seat per stage", () => {
|
||||
const groups = chainToStageGroups({ seats: [seat("a"), seat("b"), seat("c")] });
|
||||
assert.deepEqual(ids(groups), [["a"], ["b"], ["c"]]);
|
||||
});
|
||||
|
||||
test("chainToStageGroups: with stages → grouped, mapping ids to seats", () => {
|
||||
const groups = chainToStageGroups({
|
||||
seats: [seat("a"), seat("b"), seat("c")],
|
||||
stages: [["a", "b"], ["c"]],
|
||||
});
|
||||
assert.deepEqual(ids(groups), [["a", "b"], ["c"]]);
|
||||
});
|
||||
|
||||
test("chainToStageGroups: drops stage ids with no matching seat, and empty groups", () => {
|
||||
const groups = chainToStageGroups({
|
||||
seats: [seat("a"), seat("c")],
|
||||
stages: [["a", "ghost"], ["c"], ["onlyghost"]],
|
||||
});
|
||||
assert.deepEqual(ids(groups), [["a"], ["c"]]);
|
||||
});
|
||||
|
||||
test("chainToStageGroups: stages that resolve to nothing → linear fallback", () => {
|
||||
const groups = chainToStageGroups({ seats: [seat("a"), seat("b")], stages: [["ghost"]] });
|
||||
assert.deepEqual(ids(groups), [["a"], ["b"]]);
|
||||
});
|
||||
|
||||
// ── serialization ─────────────────────────────────────────────────────────────
|
||||
|
||||
test("stageGroupsToSeats flattens in order", () => {
|
||||
const groups = grp([seat("a"), seat("b")], [seat("c")]);
|
||||
assert.deepEqual(
|
||||
stageGroupsToSeats(groups).map((s) => s.agent_id),
|
||||
["a", "b", "c"],
|
||||
);
|
||||
});
|
||||
|
||||
test("stageGroupsToStagePayload returns null when all singletons AND no goals (linear)", () => {
|
||||
const groups = grp([seat("a")], [seat("b")]);
|
||||
assert.equal(stageGroupsToStagePayload(groups), null);
|
||||
});
|
||||
|
||||
test("stageGroupsToStagePayload returns explicit stages when serial but a goal is set", () => {
|
||||
// 串行单席位 + 任一「本阶段目标」→ 落显式分层(目标必须挂在显式 stages 上,否则丢失)。
|
||||
const groups = setStageGoal(grp([seat("a")], [seat("b")]), 0, "分析目的");
|
||||
assert.deepEqual(stageGroupsToStagePayload(groups), [["a"], ["b"]]);
|
||||
});
|
||||
|
||||
test("stageGroupsToStagePayload forceExplicit lifts a pure-linear chain to explicit stages", () => {
|
||||
// 无并行无目标,但调用方因「总控编排提示」要求强制显式分层(否则提示在线性链里被忽略)。
|
||||
const groups = grp([seat("a")], [seat("b")]);
|
||||
assert.equal(stageGroupsToStagePayload(groups), null);
|
||||
assert.deepEqual(stageGroupsToStagePayload(groups, true), [["a"], ["b"]]);
|
||||
assert.deepEqual(stageGroupsToStageGoals(groups, true), [null, null]);
|
||||
});
|
||||
|
||||
test("stageGroupsToStagePayload returns groups when any stage is parallel", () => {
|
||||
const groups = grp([seat("a"), seat("b")], [seat("c")]);
|
||||
assert.deepEqual(stageGroupsToStagePayload(groups), [["a", "b"], ["c"]]);
|
||||
});
|
||||
|
||||
test("stageGroupsToStagePayload ignores empty stages", () => {
|
||||
const groups = grp([seat("a"), seat("b")], []);
|
||||
assert.deepEqual(stageGroupsToStagePayload(groups), [["a", "b"]]);
|
||||
});
|
||||
|
||||
// ── stage goals ─────────────────────────────────────────────────────────────
|
||||
|
||||
test("stageGroupsToStageGoals returns null when linear AND no goals", () => {
|
||||
const groups = grp([seat("a")], [seat("b")]);
|
||||
assert.equal(stageGroupsToStageGoals(groups), null);
|
||||
});
|
||||
|
||||
test("stageGroupsToStageGoals persists goals on a serial chain when any goal is set", () => {
|
||||
// 旧行为:串行 → 目标折叠为 null(被丢)。现改为:填了目标的串行链也落库,与显式分层对齐,
|
||||
// 否则保存 / 回显皆失(用户反馈的 bug)。stage 1 无目标 → null。
|
||||
const groups = setStageGoal(grp([seat("a")], [seat("b")]), 0, " 分析目的 ");
|
||||
assert.deepEqual(stageGroupsToStageGoals(groups), ["分析目的", null]);
|
||||
});
|
||||
|
||||
test("stageGroupsToStageGoals aligns to surviving stages, trims, nulls empties", () => {
|
||||
let groups = grp([seat("a"), seat("b")], [seat("c")]);
|
||||
groups = setStageGoal(groups, 0, " 分析目的 ");
|
||||
// stage 1 无目标 → null;stage 0 目标 trim。
|
||||
assert.deepEqual(stageGroupsToStageGoals(groups), ["分析目的", null]);
|
||||
});
|
||||
|
||||
test("setStageGoal is immutable + out-of-range no-op", () => {
|
||||
const groups = grp([seat("a"), seat("b")], [seat("c")]);
|
||||
const next = setStageGoal(groups, 1, "g1");
|
||||
assert.equal(next[1].goal, "g1");
|
||||
assert.equal(groups[1].goal, undefined); // 原对象不变
|
||||
assert.equal(setStageGoal(groups, 9, "x"), groups); // 越界返回原引用
|
||||
});
|
||||
|
||||
// ── lookups ───────────────────────────────────────────────────────────────────
|
||||
|
||||
test("findStageIndexOfSeat / countSeats", () => {
|
||||
const groups = grp([seat("a"), seat("b")], [seat("c")]);
|
||||
assert.equal(findStageIndexOfSeat(groups, "c"), 1);
|
||||
assert.equal(findStageIndexOfSeat(groups, "zzz"), -1);
|
||||
assert.equal(countSeats(groups), 3);
|
||||
});
|
||||
|
||||
// ── mutations ─────────────────────────────────────────────────────────────────
|
||||
|
||||
test("addSeatAsNewStage appends a singleton stage, dedupes", () => {
|
||||
let g = grp([seat("a")]);
|
||||
g = addSeatAsNewStage(g, seat("b"));
|
||||
assert.deepEqual(ids(g), [["a"], ["b"]]);
|
||||
g = addSeatAsNewStage(g, seat("a")); // dup → no-op
|
||||
assert.deepEqual(ids(g), [["a"], ["b"]]);
|
||||
});
|
||||
|
||||
test("addSeatToStage inserts into a stage at index, preserves goal", () => {
|
||||
const base = setStageGoal(grp([seat("a")], [seat("c")]), 0, "g0");
|
||||
const g = addSeatToStage(base, seat("b"), 0, 0);
|
||||
assert.deepEqual(ids(g), [["b", "a"], ["c"]]);
|
||||
assert.equal(g[0].goal, "g0"); // goal 保留
|
||||
});
|
||||
|
||||
test("removeSeat drops the seat and prunes an emptied stage", () => {
|
||||
const g = removeSeat(grp([seat("a")], [seat("b"), seat("c")]), "a");
|
||||
assert.deepEqual(ids(g), [["b", "c"]]);
|
||||
});
|
||||
|
||||
test("moveSeatToStage merges across stages and prunes empty source", () => {
|
||||
const g = moveSeatToStage(grp([seat("a")], [seat("b")]), "a", 1);
|
||||
assert.deepEqual(ids(g), [["b", "a"]]);
|
||||
});
|
||||
|
||||
test("moveSeatToStage within same stage reorders", () => {
|
||||
const g = moveSeatToStage(grp([seat("a"), seat("b"), seat("c")]), "c", 0, 0);
|
||||
assert.deepEqual(ids(g), [["c", "a", "b"]]);
|
||||
});
|
||||
|
||||
test("splitSeatToNewStage pulls a seat out; original keeps goal, split has none", () => {
|
||||
const base = setStageGoal(grp([seat("a"), seat("b")], [seat("c")]), 0, "g0");
|
||||
const g = splitSeatToNewStage(base, "b");
|
||||
assert.deepEqual(ids(g), [["a"], ["b"], ["c"]]);
|
||||
assert.equal(g[0].goal, "g0"); // 原 stage 保留目标
|
||||
assert.equal(g[1].goal, undefined); // 拆出的新单席位 stage 无目标
|
||||
});
|
||||
|
||||
test("splitSeatToNewStage on an already-solo seat is a no-op", () => {
|
||||
const g = splitSeatToNewStage(grp([seat("a")], [seat("b")]), "a");
|
||||
assert.deepEqual(ids(g), [["a"], ["b"]]);
|
||||
});
|
||||
|
||||
test("moveStage reorders serial stages, goal travels with the stage", () => {
|
||||
const base = setStageGoal(grp([seat("a")], [seat("b")], [seat("c")]), 2, "gc");
|
||||
const g = moveStage(base, 2, -1);
|
||||
assert.deepEqual(ids(g), [["a"], ["c"], ["b"]]);
|
||||
assert.equal(g[1].goal, "gc"); // c 的目标随它移到了第 2 位
|
||||
});
|
||||
|
||||
test("addEmptyStage / deleteStage", () => {
|
||||
let g = addEmptyStage(grp([seat("a")]));
|
||||
assert.deepEqual(ids(g), [["a"], []]);
|
||||
g = deleteStage(g, 1);
|
||||
assert.deepEqual(ids(g), [["a"]]);
|
||||
});
|
||||
|
||||
// round-trip: editor groups → payload → reload preserves structure + goals
|
||||
test("round-trip: groups → {seats, stages, stageGoals} → chainToStageGroups", () => {
|
||||
const groups = setStageGoal(grp([seat("a"), seat("b")], [seat("c")]), 1, "依赖上一阶段");
|
||||
const seats = stageGroupsToSeats(groups);
|
||||
const stages = stageGroupsToStagePayload(groups);
|
||||
const stageGoals = stageGroupsToStageGoals(groups);
|
||||
const restored = chainToStageGroups({ seats, stages, stageGoals });
|
||||
assert.deepEqual(ids(restored), [["a", "b"], ["c"]]);
|
||||
assert.equal(restored[0].goal, undefined);
|
||||
assert.equal(restored[1].goal, "依赖上一阶段");
|
||||
});
|
||||
|
||||
// round-trip on a **serial single-seat chain with a goal** (the reported bug):
|
||||
// save must persist stages+goals, and reload must show the goal back on its stage.
|
||||
test("round-trip: serial single-seat chain + goal preserves goal across save/reload", () => {
|
||||
const groups = setStageGoal(grp([seat("a")], [seat("b")]), 0, "作战目的分析");
|
||||
const seats = stageGroupsToSeats(groups);
|
||||
const stages = stageGroupsToStagePayload(groups);
|
||||
const stageGoals = stageGroupsToStageGoals(groups);
|
||||
// 不再折叠为 null —— 串行+目标落显式分层。
|
||||
assert.deepEqual(stages, [["a"], ["b"]]);
|
||||
assert.deepEqual(stageGoals, ["作战目的分析", null]);
|
||||
const restored = chainToStageGroups({ seats, stages, stageGoals });
|
||||
assert.deepEqual(ids(restored), [["a"], ["b"]]);
|
||||
assert.equal(restored[0].goal, "作战目的分析");
|
||||
assert.equal(restored[1].goal, undefined);
|
||||
});
|
||||
|
||||
test("chainToStageGroups: goal drops with a stage whose agents are all gone", () => {
|
||||
// stages[0] 全是 ghost → 整组(含 g0)丢弃;存活的 ["c"] 应拿到 g1,不是 g0。
|
||||
const restored = chainToStageGroups({
|
||||
seats: [seat("c")],
|
||||
stages: [["ghosta", "ghostb"], ["c"]],
|
||||
stageGoals: ["g0", "g1"],
|
||||
});
|
||||
assert.deepEqual(ids(restored), [["c"]]);
|
||||
assert.equal(restored[0].goal, "g1");
|
||||
});
|
||||
@@ -0,0 +1,227 @@
|
||||
/**
|
||||
* 业务链条「分层编排」编辑器的纯数据操作。
|
||||
*
|
||||
* 编辑器内部用 `StageGroups`(`StageGroup[]`,每个 `StageGroup` = 一个 stage,含其
|
||||
* 并行席位 `seats` 与可选「本阶段目标」`goal`;stage 内并行、stage 间串行)作为
|
||||
* **单一数据源**:
|
||||
* - 展平得到落库的有序 `seats`({@link stageGroupsToSeats});
|
||||
* - 折叠得到落库的 `stages`({@link stageGroupsToStagePayload});
|
||||
* - 折叠得到落库的 `stageGoals`({@link stageGroupsToStageGoals}),与 `stages` 同下标对齐。
|
||||
*
|
||||
* `goal` 挂在 stage 对象上,随 stage 在增删改 / 重排中自动跟随,避免与席位错位。
|
||||
* 这里只放纯函数(无 React / 无副作用),便于单测;组件只做渲染 + 调用这些函数。
|
||||
* 对应需求文档 `docs/roundtable-dag-orchestration.md` §2(分层编辑器,竖列分组)。
|
||||
*/
|
||||
import type { BusinessChain, ChainSeat } from "@/roundtable-planning/lib/business-chain";
|
||||
|
||||
/** 一个并行 stage:含其并行席位与可选「本阶段目标」(注入给总控/席位,仅 dag 模式生效)。 */
|
||||
export interface StageGroup {
|
||||
seats: ChainSeat[];
|
||||
/** 本阶段目标:告诉总控本阶段要产出什么、如何依赖上一阶段产出。空 = 不注入。 */
|
||||
goal?: string;
|
||||
}
|
||||
|
||||
/** 编辑器内部的分层结构:每个元素是一个并行 stage,外层顺序即串行顺序。 */
|
||||
export type StageGroups = StageGroup[];
|
||||
|
||||
/**
|
||||
* 从一条业务链条还原分层结构。
|
||||
* - 链条带 `stages`:按分层分组(agent_id → 对应 seat),丢弃找不到 seat 的 id 与空组;
|
||||
* `goal` 按**原始 stage 下标**从 `stageGoals` 取,随被丢弃的组一并丢弃;分层全空时回退到线性。
|
||||
* - 无 `stages`(老链条):线性 —— 每个 seat 独立成一层(无 goal)。
|
||||
*/
|
||||
export function chainToStageGroups(
|
||||
chain: Pick<BusinessChain, "seats" | "stages" | "stageGoals">,
|
||||
): StageGroups {
|
||||
const seats = chain.seats ?? [];
|
||||
const byId = new Map(seats.map((s) => [s.agent_id, s]));
|
||||
const goals = chain.stageGoals ?? null;
|
||||
if (chain.stages && chain.stages.length > 0) {
|
||||
const groups: StageGroups = [];
|
||||
chain.stages.forEach((group, idx) => {
|
||||
const mapped = group.map((id) => byId.get(id)).filter((s): s is ChainSeat => Boolean(s));
|
||||
if (mapped.length === 0) return; // 整组解析不到席位 → 连同其 goal 一并丢弃
|
||||
const goal = goals?.[idx]?.trim() || undefined;
|
||||
groups.push(goal ? { seats: mapped, goal } : { seats: mapped });
|
||||
});
|
||||
if (groups.length > 0) return groups;
|
||||
}
|
||||
return seats.map((s) => ({ seats: [s] }));
|
||||
}
|
||||
|
||||
/** 展平成落库 / 校验用的有序席位列表(stage 顺序 → stage 内顺序)。 */
|
||||
export function stageGroupsToSeats(groups: StageGroups): ChainSeat[] {
|
||||
return groups.flatMap((g) => g.seats);
|
||||
}
|
||||
|
||||
/** 一组里是否有人填了「本阶段目标」(trim 后非空)。 */
|
||||
function hasAnyGoal(groups: StageGroups): boolean {
|
||||
return groups.some((g) => (g.goal?.trim() ?? "") !== "");
|
||||
}
|
||||
|
||||
/**
|
||||
* 折叠成落库的 `stages`。返回 null = 线性链(Step 2 走 chain 模式,老行为不变);返回显式
|
||||
* 分层 = Step 2 走 dag 模式。判定:**只要有一个 stage ≥2 席位(并行),或用户给任一 stage
|
||||
* 填了「本阶段目标」,就落显式分层**;否则(纯单席位且无目标)落 null。空 stage 已被忽略。
|
||||
*
|
||||
* 为什么「填了目标也要落显式分层」:每阶段目标按 stage 下标对齐落库(见
|
||||
* {@link stageGroupsToStageGoals}),只能挂在显式 `stages` 上。若串行单席位链照旧折叠为
|
||||
* null,目标就会被一并丢掉——保存丢、回显也丢(正是用户反馈的「本阶段目标没保存上 / 没回显」)。
|
||||
* 填了目标的串行链因此落成「每席位一层」的显式分层,由总控**逐阶段按目标派活**(dag 模式)。
|
||||
*
|
||||
* `forceExplicit`:调用方还有别的「必须走 dag」的理由时(如填了链条级「总控编排提示」,
|
||||
* 仅 dag 模式注入)传 true,强制落显式分层,避免该提示在纯线性链里被静默忽略。
|
||||
*/
|
||||
export function stageGroupsToStagePayload(groups: StageGroups, forceExplicit = false): string[][] | null {
|
||||
const nonEmpty = groups.filter((g) => g.seats.length > 0);
|
||||
const hasParallel = nonEmpty.some((g) => g.seats.length > 1);
|
||||
if (!hasParallel && !hasAnyGoal(nonEmpty) && !forceExplicit) return null;
|
||||
return nonEmpty.map((g) => g.seats.map((s) => s.agent_id));
|
||||
}
|
||||
|
||||
/**
|
||||
* 折叠成落库的 `stageGoals`,与 {@link stageGroupsToStagePayload} 做**完全相同的折叠判定**
|
||||
* (过滤空组;无并行且无目标、且未 `forceExplicit` 时才返回 null),保证两个数组下标一一对应。
|
||||
* 每个存活组取其 `goal`(trim 后为空则该位为 null)。只要落了 `stages`,就同步落目标。
|
||||
*/
|
||||
export function stageGroupsToStageGoals(groups: StageGroups, forceExplicit = false): (string | null)[] | null {
|
||||
const nonEmpty = groups.filter((g) => g.seats.length > 0);
|
||||
const hasParallel = nonEmpty.some((g) => g.seats.length > 1);
|
||||
if (!hasParallel && !hasAnyGoal(nonEmpty) && !forceExplicit) return null;
|
||||
return nonEmpty.map((g) => g.goal?.trim() || null);
|
||||
}
|
||||
|
||||
/** 该席位所在 stage 下标;不存在返回 -1。 */
|
||||
export function findStageIndexOfSeat(groups: StageGroups, agentId: string): number {
|
||||
return groups.findIndex((g) => g.seats.some((s) => s.agent_id === agentId));
|
||||
}
|
||||
|
||||
/** 席位是否已在任意 stage 中。 */
|
||||
export function seatExistsInGroups(groups: StageGroups, agentId: string): boolean {
|
||||
return findStageIndexOfSeat(groups, agentId) >= 0;
|
||||
}
|
||||
|
||||
/** 总席位数(用于 2–8 约束)。 */
|
||||
export function countSeats(groups: StageGroups): number {
|
||||
return groups.reduce((n, g) => n + g.seats.length, 0);
|
||||
}
|
||||
|
||||
/** 设置某个 stage 的「本阶段目标」(不可变,供编辑器 onChange)。 */
|
||||
export function setStageGoal(groups: StageGroups, stageIdx: number, goal: string): StageGroups {
|
||||
if (stageIdx < 0 || stageIdx >= groups.length) return groups;
|
||||
return groups.map((g, i) => (i === stageIdx ? { ...g, goal } : g));
|
||||
}
|
||||
|
||||
// ── 变换(均返回新结构,不可变)──────────────────────────────────────────────
|
||||
|
||||
/** 末尾追加一个**新单席位 stage**(线性追加,pool 点击加入默认行为)。 */
|
||||
export function addSeatAsNewStage(groups: StageGroups, seat: ChainSeat): StageGroups {
|
||||
if (seatExistsInGroups(groups, seat.agent_id)) return groups;
|
||||
return [...groups, { seats: [seat] }];
|
||||
}
|
||||
|
||||
/** 把席位加入指定 stage(可选插入位置);席位已存在则不动。保留目标 stage 的 goal。 */
|
||||
export function addSeatToStage(
|
||||
groups: StageGroups,
|
||||
seat: ChainSeat,
|
||||
stageIdx: number,
|
||||
atIndex?: number,
|
||||
): StageGroups {
|
||||
if (seatExistsInGroups(groups, seat.agent_id)) return groups;
|
||||
if (stageIdx < 0 || stageIdx >= groups.length) return groups;
|
||||
return groups.map((g, i) => {
|
||||
if (i !== stageIdx) return g;
|
||||
const next = [...g.seats];
|
||||
const at = atIndex == null ? next.length : Math.max(0, Math.min(atIndex, next.length));
|
||||
next.splice(at, 0, seat);
|
||||
return { ...g, seats: next };
|
||||
});
|
||||
}
|
||||
|
||||
/** 移除一个席位;该 stage 因此变空则连 stage(含其 goal)一起删掉。 */
|
||||
export function removeSeat(groups: StageGroups, agentId: string): StageGroups {
|
||||
return groups
|
||||
.map((g) => ({ ...g, seats: g.seats.filter((s) => s.agent_id !== agentId) }))
|
||||
.filter((g) => g.seats.length > 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* 把席位移动到目标 stage(跨 stage 合并 / stage 内移动)。
|
||||
* 源 stage 变空则删除;删除会改变下标,这里用 agent_id 与目标 stage 的**身份**而非下标
|
||||
* 重新定位,保证语义稳定。`atIndex` 为目标 stage 内插入位置。
|
||||
*/
|
||||
export function moveSeatToStage(
|
||||
groups: StageGroups,
|
||||
agentId: string,
|
||||
targetStageIdx: number,
|
||||
atIndex?: number,
|
||||
): StageGroups {
|
||||
const from = findStageIndexOfSeat(groups, agentId);
|
||||
if (from < 0 || targetStageIdx < 0 || targetStageIdx >= groups.length) return groups;
|
||||
const seat = groups[from].seats.find((s) => s.agent_id === agentId);
|
||||
if (!seat) return groups;
|
||||
// 先按身份记下目标 stage 引用,避免删空源 stage 后下标错位。goal 始终随 stage 保留。
|
||||
const targetRef = groups[targetStageIdx];
|
||||
let next: StageGroups = groups.map((g) =>
|
||||
g === targetRef ? g : { ...g, seats: g.seats.filter((s) => s.agent_id !== agentId) },
|
||||
);
|
||||
next = next.map((g) => {
|
||||
if (g !== targetRef) return g;
|
||||
if (g.seats.some((s) => s.agent_id === agentId)) {
|
||||
// stage 内移动:先抽出再按 atIndex 插回。
|
||||
const without = g.seats.filter((s) => s.agent_id !== agentId);
|
||||
const at = atIndex == null ? without.length : Math.max(0, Math.min(atIndex, without.length));
|
||||
without.splice(at, 0, seat);
|
||||
return { ...g, seats: without };
|
||||
}
|
||||
const merged = [...g.seats];
|
||||
const at = atIndex == null ? merged.length : Math.max(0, Math.min(atIndex, merged.length));
|
||||
merged.splice(at, 0, seat);
|
||||
return { ...g, seats: merged };
|
||||
});
|
||||
return next.filter((g) => g.seats.length > 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* 把席位从当前 stage 抽出,独立成一个**新 stage**(插在原 stage 之后)。
|
||||
* 原 stage 保留其 `goal`(目标描述的是这一批),拆出的新单席位 stage 无 goal。
|
||||
*/
|
||||
export function splitSeatToNewStage(groups: StageGroups, agentId: string): StageGroups {
|
||||
const from = findStageIndexOfSeat(groups, agentId);
|
||||
if (from < 0) return groups;
|
||||
const seat = groups[from].seats.find((s) => s.agent_id === agentId);
|
||||
if (!seat) return groups;
|
||||
if (groups[from].seats.length === 1) return groups; // 已经独占一层,无需拆
|
||||
const out: StageGroups = [];
|
||||
groups.forEach((g, i) => {
|
||||
if (i === from) {
|
||||
out.push({ ...g, seats: g.seats.filter((s) => s.agent_id !== agentId) });
|
||||
out.push({ seats: [seat] });
|
||||
} else {
|
||||
out.push(g);
|
||||
}
|
||||
});
|
||||
return out.filter((g) => g.seats.length > 0);
|
||||
}
|
||||
|
||||
/** 整段 stage 上移 / 下移(改串行顺序)。goal 随 stage 一起移动。 */
|
||||
export function moveStage(groups: StageGroups, stageIdx: number, dir: -1 | 1): StageGroups {
|
||||
const target = stageIdx + dir;
|
||||
if (stageIdx < 0 || stageIdx >= groups.length || target < 0 || target >= groups.length) {
|
||||
return groups;
|
||||
}
|
||||
const next = [...groups];
|
||||
[next[stageIdx], next[target]] = [next[target], next[stageIdx]];
|
||||
return next;
|
||||
}
|
||||
|
||||
/** 末尾追加一个空 stage(用户「新建 Stage」后再拖 / 加席位进去)。 */
|
||||
export function addEmptyStage(groups: StageGroups): StageGroups {
|
||||
return [...groups, { seats: [] }];
|
||||
}
|
||||
|
||||
/** 删除整个 stage(含其席位)。 */
|
||||
export function deleteStage(groups: StageGroups, stageIdx: number): StageGroups {
|
||||
if (stageIdx < 0 || stageIdx >= groups.length) return groups;
|
||||
return groups.filter((_, i) => i !== stageIdx);
|
||||
}
|
||||
@@ -0,0 +1,539 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
|
||||
import {
|
||||
buildDagStageLeaderTask,
|
||||
buildDagTransitTask,
|
||||
buildDependencySummary,
|
||||
buildPlanFromStages,
|
||||
buildStageTask,
|
||||
chainToDagPlan,
|
||||
emptyPlan,
|
||||
isParallelStage,
|
||||
PARALLEL_DEGREE_WARN_THRESHOLD,
|
||||
pickDagSeatTask,
|
||||
validatePlan,
|
||||
type OrchestrationPlan,
|
||||
} from "./dag-types";
|
||||
|
||||
// ── chainToDagPlan:链条 → 单节点-stage DAG(§1.3 兼容转换)────────────────────
|
||||
|
||||
test("chainToDagPlan turns a linear chain into one-node-per-stage DAG", () => {
|
||||
const plan = chainToDagPlan(["a", "b", "c"]);
|
||||
assert.equal(plan.mode, "dag");
|
||||
assert.equal(plan.finalSynthesis, true);
|
||||
assert.deepEqual(
|
||||
plan.stages.map((s) => s.agentIds),
|
||||
[["a"], ["b"], ["c"]],
|
||||
);
|
||||
// stage id 稳定且唯一(diff / 拖拽重排用)。
|
||||
assert.deepEqual(
|
||||
plan.stages.map((s) => s.id),
|
||||
["stage-0", "stage-1", "stage-2"],
|
||||
);
|
||||
});
|
||||
|
||||
test("chainToDagPlan preserves order and respects finalSynthesis=false", () => {
|
||||
const plan = chainToDagPlan(["x", "y"], false);
|
||||
assert.equal(plan.finalSynthesis, false);
|
||||
assert.deepEqual(
|
||||
plan.stages.map((s) => s.agentIds[0]),
|
||||
["x", "y"],
|
||||
);
|
||||
});
|
||||
|
||||
test("chainToDagPlan on empty chain yields an empty plan", () => {
|
||||
const plan = chainToDagPlan([]);
|
||||
assert.deepEqual(plan.stages, []);
|
||||
});
|
||||
|
||||
test("emptyPlan is a valid empty dag plan", () => {
|
||||
assert.deepEqual(emptyPlan(), { mode: "dag", stages: [], finalSynthesis: true });
|
||||
});
|
||||
|
||||
// ── isParallelStage ──────────────────────────────────────────────────────────
|
||||
|
||||
test("isParallelStage is true only for ≥2 seats", () => {
|
||||
assert.equal(isParallelStage({ id: "s", agentIds: ["a"] }), false);
|
||||
assert.equal(isParallelStage({ id: "s", agentIds: ["a", "b"] }), true);
|
||||
});
|
||||
|
||||
// ── validatePlan ──────────────────────────────────────────────────────────────
|
||||
|
||||
const roster = ["a", "b", "c", "d"];
|
||||
|
||||
test("validatePlan accepts a valid mixed serial/parallel plan", () => {
|
||||
const plan: OrchestrationPlan = {
|
||||
mode: "dag",
|
||||
finalSynthesis: true,
|
||||
stages: [
|
||||
{ id: "s0", agentIds: ["a"] },
|
||||
{ id: "s1", agentIds: ["b", "c"] },
|
||||
{ id: "s2", agentIds: ["d"] },
|
||||
],
|
||||
};
|
||||
const res = validatePlan(plan, roster);
|
||||
assert.equal(res.ok, true);
|
||||
assert.deepEqual(res.errors, []);
|
||||
assert.deepEqual(res.warnings, []);
|
||||
});
|
||||
|
||||
test("validatePlan rejects an empty plan", () => {
|
||||
const res = validatePlan(emptyPlan(), roster);
|
||||
assert.equal(res.ok, false);
|
||||
assert.equal(res.errors.length, 1);
|
||||
});
|
||||
|
||||
test("validatePlan rejects an empty stage", () => {
|
||||
const plan: OrchestrationPlan = {
|
||||
mode: "dag",
|
||||
finalSynthesis: true,
|
||||
stages: [{ id: "s0", agentIds: ["a"] }, { id: "s1", agentIds: [] }],
|
||||
};
|
||||
const res = validatePlan(plan, roster);
|
||||
assert.equal(res.ok, false);
|
||||
assert.match(res.errors[0], /第 2 阶段为空/);
|
||||
});
|
||||
|
||||
test("validatePlan rejects a seat not in the roster", () => {
|
||||
const plan: OrchestrationPlan = {
|
||||
mode: "dag",
|
||||
finalSynthesis: true,
|
||||
stages: [{ id: "s0", agentIds: ["a", "zzz"] }],
|
||||
};
|
||||
const res = validatePlan(plan, roster);
|
||||
assert.equal(res.ok, false);
|
||||
assert.match(res.errors[0], /未选定的席位/);
|
||||
});
|
||||
|
||||
test("validatePlan rejects the same seat across two stages", () => {
|
||||
const plan: OrchestrationPlan = {
|
||||
mode: "dag",
|
||||
finalSynthesis: true,
|
||||
stages: [
|
||||
{ id: "s0", agentIds: ["a"] },
|
||||
{ id: "s1", agentIds: ["a"] },
|
||||
],
|
||||
};
|
||||
const res = validatePlan(plan, roster);
|
||||
assert.equal(res.ok, false);
|
||||
assert.match(res.errors[0], /只能跑一次/);
|
||||
});
|
||||
|
||||
test("validatePlan rejects a duplicate seat within one stage", () => {
|
||||
const plan: OrchestrationPlan = {
|
||||
mode: "dag",
|
||||
finalSynthesis: true,
|
||||
stages: [{ id: "s0", agentIds: ["a", "a"] }],
|
||||
};
|
||||
const res = validatePlan(plan, roster);
|
||||
assert.equal(res.ok, false);
|
||||
assert.match(res.errors[0], /重复/);
|
||||
});
|
||||
|
||||
test("validatePlan warns (but allows) when parallel degree exceeds the threshold", () => {
|
||||
const big = Array.from({ length: PARALLEL_DEGREE_WARN_THRESHOLD + 1 }, (_, i) => `p${i}`);
|
||||
const plan: OrchestrationPlan = {
|
||||
mode: "dag",
|
||||
finalSynthesis: true,
|
||||
stages: [{ id: "s0", agentIds: big }],
|
||||
};
|
||||
const res = validatePlan(plan, big);
|
||||
assert.equal(res.ok, true);
|
||||
assert.equal(res.errors.length, 0);
|
||||
assert.equal(res.warnings.length, 1);
|
||||
assert.match(res.warnings[0], /并发限流/);
|
||||
});
|
||||
|
||||
// chain→dag round-trip is always valid against its own roster.
|
||||
test("a chainToDagPlan validates clean against its own roster", () => {
|
||||
const chain = ["alpha", "beta", "gamma"];
|
||||
const res = validatePlan(chainToDagPlan(chain), chain);
|
||||
assert.equal(res.ok, true);
|
||||
});
|
||||
|
||||
// ── buildPlanFromStages (链条 stages → 执行计划) ──────────────────────────────
|
||||
|
||||
test("buildPlanFromStages maps groups to stages with stable ids", () => {
|
||||
const plan = buildPlanFromStages([["a", "b"], ["c"]]);
|
||||
assert.equal(plan.mode, "dag");
|
||||
assert.equal(plan.finalSynthesis, true);
|
||||
assert.deepEqual(
|
||||
plan.stages.map((s) => s.agentIds),
|
||||
[["a", "b"], ["c"]],
|
||||
);
|
||||
assert.deepEqual(
|
||||
plan.stages.map((s) => s.id),
|
||||
["stage-0", "stage-1"],
|
||||
);
|
||||
});
|
||||
|
||||
test("buildPlanFromStages filters out non-surviving ids and drops emptied stages", () => {
|
||||
// "b" deleted; stage that becomes empty is dropped.
|
||||
const plan = buildPlanFromStages([["a", "b"], ["x"]], ["a", "c"]);
|
||||
assert.deepEqual(
|
||||
plan.stages.map((s) => s.agentIds),
|
||||
[["a"]],
|
||||
);
|
||||
});
|
||||
|
||||
test("buildPlanFromStages on all-filtered yields empty stages (caller falls back)", () => {
|
||||
const plan = buildPlanFromStages([["x"], ["y"]], ["a"]);
|
||||
assert.deepEqual(plan.stages, []);
|
||||
});
|
||||
|
||||
test("a chain plan validates clean against its surviving roster", () => {
|
||||
const plan = buildPlanFromStages([["a", "b"], ["c"]], ["a", "b", "c"]);
|
||||
const res = validatePlan(plan, ["a", "b", "c"]);
|
||||
assert.equal(res.ok, true);
|
||||
});
|
||||
|
||||
test("buildPlanFromStages stamps per-stage goals (trimmed), aligned to source index", () => {
|
||||
const plan = buildPlanFromStages([["a", "b"], ["c"]], undefined, true, [" 目的 ", ""]);
|
||||
assert.equal(plan.stages[0].goal, "目的"); // trim
|
||||
assert.equal(plan.stages[1].goal, undefined); // 空 → 无 goal
|
||||
});
|
||||
|
||||
test("buildPlanFromStages drops a filtered-out stage's goal, keeps survivor's by source index", () => {
|
||||
// stage 0 全被过滤 → 连同 goals[0] 丢弃;存活的 ["c"] 是源下标 1 → 拿 goals[1]。
|
||||
const plan = buildPlanFromStages([["x"], ["c"]], ["c"], true, ["g0", "g1"]);
|
||||
assert.deepEqual(plan.stages.map((s) => s.agentIds), [["c"]]);
|
||||
assert.equal(plan.stages[0].goal, "g1");
|
||||
});
|
||||
|
||||
test("buildPlanFromStages without goals leaves stage.goal undefined (old plans)", () => {
|
||||
const plan = buildPlanFromStages([["a"], ["b"]]);
|
||||
assert.equal(plan.stages[0].goal, undefined);
|
||||
assert.equal(plan.stages[1].goal, undefined);
|
||||
});
|
||||
|
||||
test("buildPlanFromStages stamps trimmed coordinatorPrompt onto the plan", () => {
|
||||
const plan = buildPlanFromStages([["a"], ["b"]], undefined, true, null, " 按阶段派活 ");
|
||||
assert.equal(plan.coordinatorPrompt, "按阶段派活");
|
||||
});
|
||||
|
||||
test("buildPlanFromStages leaves coordinatorPrompt undefined when blank/absent", () => {
|
||||
assert.equal(buildPlanFromStages([["a"], ["b"]]).coordinatorPrompt, undefined);
|
||||
assert.equal(buildPlanFromStages([["a"]], undefined, true, null, " ").coordinatorPrompt, undefined);
|
||||
});
|
||||
|
||||
// ── buildDependencySummary (§3.1 依赖摘要注入) ─────────────────────────────────
|
||||
|
||||
test("buildDependencySummary is empty for no deliveries (first stage)", () => {
|
||||
assert.equal(buildDependencySummary([]), "");
|
||||
});
|
||||
|
||||
test("buildDependencySummary lists each seat's delivery with its name", () => {
|
||||
const out = buildDependencySummary([
|
||||
{ seatName: "情报收集", content: "情报正文" },
|
||||
{ seatName: "环境评估", content: "评估正文" },
|
||||
]);
|
||||
assert.match(out, /【情报收集】/);
|
||||
assert.match(out, /情报正文/);
|
||||
assert.match(out, /【环境评估】/);
|
||||
assert.match(out, /评估正文/);
|
||||
});
|
||||
|
||||
test("buildDependencySummary truncates long content", () => {
|
||||
const long = "x".repeat(3000);
|
||||
const out = buildDependencySummary([{ seatName: "A", content: long }], 100);
|
||||
assert.match(out, /…(已截断)/);
|
||||
assert.ok(out.length < 3000);
|
||||
});
|
||||
|
||||
test("buildDependencySummary handles empty content gracefully", () => {
|
||||
const out = buildDependencySummary([{ seatName: "A", content: " " }]);
|
||||
assert.match(out, /(无文本输出)/);
|
||||
});
|
||||
|
||||
// ── buildStageTask (§3.2 直派提示) ────────────────────────────────────────────
|
||||
|
||||
test("buildStageTask for first stage embeds the task background", () => {
|
||||
const task = buildStageTask({
|
||||
seedMessage: "做一个容灾方案",
|
||||
seatName: "情报收集",
|
||||
priorSummary: "",
|
||||
isParallel: false,
|
||||
});
|
||||
assert.match(task, /任务背景/);
|
||||
assert.match(task, /做一个容灾方案/);
|
||||
assert.match(task, /情报收集/);
|
||||
// serial node — no parallel no-file warning.
|
||||
assert.doesNotMatch(task, /并行研讨/);
|
||||
});
|
||||
|
||||
test("buildStageTask for a later stage embeds the prior summary, not the seed", () => {
|
||||
const task = buildStageTask({
|
||||
seedMessage: "原始任务",
|
||||
seatName: "方案设计",
|
||||
priorSummary: "【情报收集】的交付:\n情报正文",
|
||||
isParallel: false,
|
||||
});
|
||||
assert.match(task, /此前各阶段已完成席位的交付摘要/);
|
||||
assert.match(task, /情报正文/);
|
||||
assert.doesNotMatch(task, /原始任务/);
|
||||
});
|
||||
|
||||
test("buildStageTask in a parallel stage forbids writing files", () => {
|
||||
const task = buildStageTask({
|
||||
seedMessage: "原始任务",
|
||||
seatName: "方案设计",
|
||||
priorSummary: "",
|
||||
isParallel: true,
|
||||
});
|
||||
assert.match(task, /并行研讨/);
|
||||
assert.match(task, /不要写文件/);
|
||||
});
|
||||
|
||||
test("buildStageTask with priorIsBridge frames prior context as the leader's bridge", () => {
|
||||
const bridge = "总控综合:情报已收集,下一步聚焦架构设计";
|
||||
const task = buildStageTask({
|
||||
seedMessage: "原始任务",
|
||||
seatName: "方案设计",
|
||||
priorSummary: bridge,
|
||||
isParallel: false,
|
||||
priorIsBridge: true,
|
||||
});
|
||||
// 措辞切换到「承上启下」综合说明,而非机械「交付摘要」。
|
||||
assert.match(task, /承上启下/);
|
||||
assert.match(task, /综合说明/);
|
||||
assert.match(task, /总控综合/);
|
||||
assert.doesNotMatch(task, /已完成席位的交付摘要/);
|
||||
});
|
||||
|
||||
// ── buildDagTransitTask (§12.3 Stage 间总控中转 + 广播) ─────────────────────────
|
||||
|
||||
test("buildDagTransitTask names completed + next seats and forbids dispatch/closeout", () => {
|
||||
const task = buildDagTransitTask({
|
||||
completedSeatNames: ["情报收集", "环境评估"],
|
||||
nextSeatNames: ["方案设计", "风险审查"],
|
||||
});
|
||||
assert.match(task, /中转轮/);
|
||||
assert.match(task, /情报收集、环境评估/);
|
||||
assert.match(task, /方案设计、风险审查/);
|
||||
assert.match(task, /承上启下/);
|
||||
// 计划钉死下一批 → 总控不自由派活、不收口。
|
||||
assert.match(task, /不要.*派活/);
|
||||
assert.match(task, /不要现在收口/);
|
||||
});
|
||||
|
||||
test("buildDagTransitTask falls back gracefully when seat name lists are empty", () => {
|
||||
const task = buildDagTransitTask({ completedSeatNames: [], nextSeatNames: [] });
|
||||
assert.match(task, /本批席位/);
|
||||
assert.match(task, /下一阶段席位/);
|
||||
});
|
||||
|
||||
// ── buildDagStageLeaderTask (§3.2 方案 A:总控驱动每 stage 派活) ─────────────────
|
||||
|
||||
test("buildDagStageLeaderTask first stage embeds task background + pins seats", () => {
|
||||
const task = buildDagStageLeaderTask({
|
||||
seedMessage: "做一个容灾方案",
|
||||
stageIndex: 0,
|
||||
totalStages: 3,
|
||||
seats: [
|
||||
{ agentId: "intel", name: "情报收集" },
|
||||
{ agentId: "env", name: "环境评估" },
|
||||
],
|
||||
isFirst: true,
|
||||
});
|
||||
assert.match(task, /任务背景/);
|
||||
assert.match(task, /做一个容灾方案/);
|
||||
assert.match(task, /第 1\/3 个阶段/);
|
||||
// 每个钉死席位都要带 agent_name 让总控逐字派活。
|
||||
assert.match(task, /agent_name: intel/);
|
||||
assert.match(task, /agent_name: env/);
|
||||
assert.match(task, /情报收集/);
|
||||
assert.match(task, /环境评估/);
|
||||
// 约束:只派给清单内、不收口。
|
||||
assert.match(task, /不要派给清单外/);
|
||||
assert.match(task, /不要.*给出最终结论/);
|
||||
// 多席位 → 并行提示。
|
||||
assert.match(task, /并行/);
|
||||
});
|
||||
|
||||
test("buildDagStageLeaderTask later stage relies on injected prior deliveries, not seed", () => {
|
||||
const task = buildDagStageLeaderTask({
|
||||
seedMessage: "原始任务",
|
||||
stageIndex: 1,
|
||||
totalStages: 2,
|
||||
seats: [{ agentId: "plan", name: "方案设计" }],
|
||||
isFirst: false,
|
||||
});
|
||||
assert.match(task, /承上启下/);
|
||||
assert.match(task, /第 2\/2 个阶段/);
|
||||
assert.doesNotMatch(task, /原始任务/);
|
||||
// 单席位 stage → 不加并行提示。
|
||||
assert.doesNotMatch(task, /会\*\*并行\*\*执行/);
|
||||
});
|
||||
|
||||
// ── pickDagSeatTask (§3.2 方案 A:取总控派给某席位的 task,多席位不张冠李戴) ────────
|
||||
|
||||
test("pickDagSeatTask returns the exact dispatch matched by agent_name (+ role guard)", () => {
|
||||
const dispatched: [string, string][] = [
|
||||
["plan", "设计架构"],
|
||||
["risk", "审查风险"],
|
||||
];
|
||||
const riskTask = pickDagSeatTask(dispatched, "risk", "风险审查");
|
||||
assert.match(riskTask, /审查风险/);
|
||||
assert.doesNotMatch(riskTask, /设计架构/);
|
||||
const planTask = pickDagSeatTask(dispatched, "plan", "方案设计");
|
||||
assert.match(planTask, /设计架构/);
|
||||
// 角色边界护栏:禁止席位派活/调度。
|
||||
assert.match(riskTask, /执行席位/);
|
||||
assert.match(riskTask, /严禁.*派活|严禁.*调度/);
|
||||
});
|
||||
|
||||
test("pickDagSeatTask gives a CLEAN own-role task on miss — never injects the dispatch narrative", () => {
|
||||
const dispatched: [string, string][] = [["plan", "设计架构"]];
|
||||
// risk 没被派到 → 既不借 plan 的「设计架构」,也**不**注入总控派活叙述(防模仿派活)。
|
||||
const task = pickDagSeatTask(dispatched, "risk", "风险审查");
|
||||
assert.doesNotMatch(task, /设计架构/);
|
||||
assert.match(task, /风险审查/);
|
||||
assert.match(task, /独立完成/);
|
||||
// 角色边界护栏:禁止席位派活/调度/绕道脚本。
|
||||
assert.match(task, /执行席位/);
|
||||
assert.match(task, /严禁/);
|
||||
assert.match(task, /bash|脚本|内部接口/);
|
||||
});
|
||||
|
||||
test("pickDagSeatTask with empty dispatched falls back to clean own-role task", () => {
|
||||
const task = pickDagSeatTask([], "risk", "风险审查");
|
||||
assert.match(task, /风险审查/);
|
||||
assert.match(task, /本阶段/);
|
||||
assert.match(task, /执行席位/);
|
||||
});
|
||||
|
||||
test("pickDagSeatTask embeds the seed message as task background when provided", () => {
|
||||
const task = pickDagSeatTask([], "risk", "风险审查", "做一个容灾方案");
|
||||
assert.match(task, /任务背景/);
|
||||
assert.match(task, /做一个容灾方案/);
|
||||
// exact-match 分支也带背景。
|
||||
const exactTask = pickDagSeatTask([["risk", "审查风险"]], "risk", "风险审查", "做一个容灾方案");
|
||||
assert.match(exactTask, /做一个容灾方案/);
|
||||
assert.match(exactTask, /审查风险/);
|
||||
});
|
||||
|
||||
test("pickDagSeatTask mentions read_peer_delivery only when peers exist (§12.9)", () => {
|
||||
const noPeers = pickDagSeatTask([], "risk", "风险审查", "种子", false);
|
||||
assert.doesNotMatch(noPeers, /read_peer_delivery/);
|
||||
const withPeers = pickDagSeatTask([], "risk", "风险审查", "种子", true);
|
||||
assert.match(withPeers, /read_peer_delivery/);
|
||||
assert.match(withPeers, /按需取全文|完整交付/);
|
||||
});
|
||||
|
||||
test("pickDagSeatTask (sandbox mode, allowFiles) asks for .md and forbids .py (§12.8)", () => {
|
||||
// allowFiles=true(沙箱模式):产出 md、禁 .py。
|
||||
const miss = pickDagSeatTask([], "risk", "风险审查", "", false, true);
|
||||
const hit = pickDagSeatTask([["risk", "审查风险"]], "risk", "风险审查", "", false, true);
|
||||
for (const t of [miss, hit]) {
|
||||
assert.match(t, /Markdown(\.md)文件|\.md/);
|
||||
assert.match(t, /不要写 \.py|不要 \.py/);
|
||||
assert.match(t, /产物要求/);
|
||||
}
|
||||
});
|
||||
|
||||
test("pickDagSeatTask (fast mode, default) keeps output in the message body — no file (§12.10)", () => {
|
||||
// allowFiles 默认 false(快速模式):产物走正文,不写文件、不写 md。
|
||||
const t = pickDagSeatTask([], "risk", "风险审查");
|
||||
assert.match(t, /直接写在回复正文|产物走正文|不要写文件/);
|
||||
assert.doesNotMatch(t, /Markdown(\.md)文件/);
|
||||
});
|
||||
|
||||
test("buildDagStageLeaderTask insists on actually calling the tool (not narrating)", () => {
|
||||
const task = buildDagStageLeaderTask({
|
||||
seedMessage: "x",
|
||||
stageIndex: 0,
|
||||
totalStages: 2,
|
||||
seats: [
|
||||
{ agentId: "a", name: "甲" },
|
||||
{ agentId: "b", name: "乙" },
|
||||
],
|
||||
isFirst: true,
|
||||
});
|
||||
assert.match(task, /真正调用 agent_orchestration 工具/);
|
||||
assert.match(task, /不要.*只用文字/);
|
||||
});
|
||||
|
||||
// ── per-stage goal injection (本阶段目标) ──────────────────────────────────────
|
||||
|
||||
test("buildDagStageLeaderTask injects the stage goal when provided", () => {
|
||||
const task = buildDagStageLeaderTask({
|
||||
seedMessage: "x",
|
||||
stageIndex: 1,
|
||||
totalStages: 2,
|
||||
seats: [{ agentId: "actor", name: "行为体分析" }],
|
||||
isFirst: false,
|
||||
goal: "根据上一阶段的各个目的,分析出行为体",
|
||||
});
|
||||
assert.match(task, /本阶段目标/);
|
||||
assert.match(task, /分析出行为体/);
|
||||
assert.match(task, /显式承接上一阶段/);
|
||||
});
|
||||
|
||||
test("buildDagStageLeaderTask omits the goal line when goal is empty/blank", () => {
|
||||
const task = buildDagStageLeaderTask({
|
||||
seedMessage: "x",
|
||||
stageIndex: 0,
|
||||
totalStages: 1,
|
||||
seats: [{ agentId: "a", name: "甲" }],
|
||||
isFirst: true,
|
||||
goal: " ",
|
||||
});
|
||||
assert.doesNotMatch(task, /本阶段目标/);
|
||||
});
|
||||
|
||||
// ── coordinator prompt injection (写给总控的编排提示) ─────────────────────────
|
||||
|
||||
test("buildDagStageLeaderTask injects the coordinator prompt as a top-priority guideline", () => {
|
||||
const task = buildDagStageLeaderTask({
|
||||
seedMessage: "x",
|
||||
stageIndex: 0,
|
||||
totalStages: 2,
|
||||
seats: [{ agentId: "a", name: "甲" }],
|
||||
isFirst: true,
|
||||
coordinatorPrompt: "严格按阶段顺序派活,最终做综合收口",
|
||||
});
|
||||
assert.match(task, /总控编排指引/);
|
||||
assert.match(task, /严格按阶段顺序派活,最终做综合收口/);
|
||||
});
|
||||
|
||||
test("buildDagStageLeaderTask injects the coordinator prompt on later stages too", () => {
|
||||
const task = buildDagStageLeaderTask({
|
||||
seedMessage: "x",
|
||||
stageIndex: 1,
|
||||
totalStages: 2,
|
||||
seats: [{ agentId: "b", name: "乙" }],
|
||||
isFirst: false,
|
||||
coordinatorPrompt: "聚焦本职、显式承接",
|
||||
});
|
||||
assert.match(task, /总控编排指引/);
|
||||
assert.match(task, /聚焦本职、显式承接/);
|
||||
});
|
||||
|
||||
test("buildDagStageLeaderTask omits the coordinator block when prompt is empty/blank", () => {
|
||||
const task = buildDagStageLeaderTask({
|
||||
seedMessage: "x",
|
||||
stageIndex: 0,
|
||||
totalStages: 1,
|
||||
seats: [{ agentId: "a", name: "甲" }],
|
||||
isFirst: true,
|
||||
coordinatorPrompt: " ",
|
||||
});
|
||||
assert.doesNotMatch(task, /总控编排指引/);
|
||||
});
|
||||
|
||||
test("pickDagSeatTask injects the stage goal in BOTH the exact-match and the miss branches", () => {
|
||||
const goal = "根据上一阶段的各个目的,分析出行为体";
|
||||
const hit = pickDagSeatTask([["actor", "干这个"]], "actor", "行为体", "种子", true, false, goal);
|
||||
const miss = pickDagSeatTask([], "actor", "行为体", "种子", true, false, goal);
|
||||
for (const t of [hit, miss]) {
|
||||
assert.match(t, /本阶段目标/);
|
||||
assert.match(t, /分析出行为体/);
|
||||
assert.match(t, /显式承接上一阶段/);
|
||||
}
|
||||
});
|
||||
|
||||
test("pickDagSeatTask omits the goal block when no goal (old plans)", () => {
|
||||
const t = pickDagSeatTask([], "actor", "行为体", "种子", true);
|
||||
assert.doesNotMatch(t, /本阶段目标/);
|
||||
});
|
||||
@@ -0,0 +1,474 @@
|
||||
/**
|
||||
* 圆桌 DAG 编排(分层 Stage 模型)共享类型 + 纯函数。
|
||||
*
|
||||
* 对应 `docs/roundtable-dag-orchestration.md` §1「数据模型」。本文件只放纯类型 +
|
||||
* 可单测的纯函数(校验 / chain→dag 兼容转换),不含任何 React / 网络副作用,
|
||||
* 后续 Phase 2(编辑器)/ Phase 3(`runDagOrchestration`)会引用这些类型。
|
||||
*
|
||||
* 设计要点(§0.3 / §1.1):
|
||||
* - DAG 用「有序的 stage 列表」表示:stage 内并行、stage 间串行。
|
||||
* - 线性链是 DAG 的特例(每层 1 个节点),见 {@link chainToDagPlan}。
|
||||
* - 自由连线画布本期不做,仅在数据模型上预留 {@link DagGraph}(§1.2)避免返工。
|
||||
*/
|
||||
|
||||
// ── 分层(Stage)表示:本期主模型(§1.1)──────────────────────────────────────
|
||||
|
||||
/** 一个并行批次:stage 内所有席位并行执行。 */
|
||||
export interface OrchestrationStage {
|
||||
/** stage 稳定 id(拖拽重排 / diff 用)。 */
|
||||
id: string;
|
||||
/** 本 stage 并行执行的席位(agent_id 列表)。1 个 = 退化为串行节点。 */
|
||||
agentIds: string[];
|
||||
/**
|
||||
* 可选「本阶段目标」:来自业务链条 `stageGoals`,注入总控派活提示(主)与席位任务
|
||||
* (兜底),告诉本阶段要产出什么、如何依赖上一阶段产出。空 = 不注入。
|
||||
*/
|
||||
goal?: string;
|
||||
}
|
||||
|
||||
/** 用户编排出的执行计划。stages 顺序即串行顺序。 */
|
||||
export interface OrchestrationPlan {
|
||||
/** 编排模式标识,持久化进 step2。 */
|
||||
mode: "dag";
|
||||
/** 串行执行的批次;每批内并行。 */
|
||||
stages: OrchestrationStage[];
|
||||
/** 收口:是否在所有 stage 完成后由总控综合(默认 true)。 */
|
||||
finalSynthesis: boolean;
|
||||
/**
|
||||
* 可选「总控编排提示」:来自业务链条 `coordinatorPrompt`,写给总控的整体派活指引
|
||||
* (怎么派活 / 做什么)。注入总控**每阶段**派活提示({@link buildDagStageLeaderTask})。
|
||||
* 空 = 不注入。
|
||||
*/
|
||||
coordinatorPrompt?: string;
|
||||
}
|
||||
|
||||
// ── 通用 DAG 表示:自由连线时才需要(§1.2,本期仅预留)───────────────────────
|
||||
|
||||
/** from 完成后才能跑 to。 */
|
||||
export interface DagEdge {
|
||||
from: string;
|
||||
to: string;
|
||||
}
|
||||
|
||||
/** 自由连线画布的图表示。执行前需 toposort → 分层落回 {@link OrchestrationStage}。 */
|
||||
export interface DagGraph {
|
||||
nodes: string[];
|
||||
edges: DagEdge[];
|
||||
}
|
||||
|
||||
// ── 常量 ──────────────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* 单 stage 并行度软上限:超过给 warning(远程模型并发限流 + 沙箱压力,§1.4 / §9)。
|
||||
* 仅提示,不阻断保存。
|
||||
*/
|
||||
export const PARALLEL_DEGREE_WARN_THRESHOLD = 6;
|
||||
|
||||
// ── 校验(纯函数,可单测,§1.4)──────────────────────────────────────────────
|
||||
|
||||
/** {@link validatePlan} 的返回。`errors` 阻断保存,`warnings` 仅提示。 */
|
||||
export interface PlanValidation {
|
||||
ok: boolean;
|
||||
/** 面向用户的中文错误(非空 = 无法保存)。 */
|
||||
errors: string[];
|
||||
/** 面向用户的中文提示(不阻断保存)。 */
|
||||
warnings: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验一份编排计划是否可执行 / 可保存。
|
||||
*
|
||||
* 校验项(§1.4):
|
||||
* - 至少 1 个 stage。
|
||||
* - 不允许空 stage。
|
||||
* - 每个席位必须在本次选定席位 `selectedAgentIds` 内(防编排不存在的席位)。
|
||||
* - 同一席位不允许出现在多个 stage(一个席位只跑一次);同一 stage 内也不允许重复。
|
||||
* - (warning)单 stage 并行度 > {@link PARALLEL_DEGREE_WARN_THRESHOLD}。
|
||||
*
|
||||
* @param plan 待校验的计划。
|
||||
* @param selectedAgentIds 本次选定的席位 agent_id 全集(roster)。
|
||||
*/
|
||||
export function validatePlan(
|
||||
plan: OrchestrationPlan,
|
||||
selectedAgentIds: string[],
|
||||
): PlanValidation {
|
||||
const errors: string[] = [];
|
||||
const warnings: string[] = [];
|
||||
const roster = new Set(selectedAgentIds);
|
||||
|
||||
if (!plan.stages || plan.stages.length === 0) {
|
||||
errors.push("编排为空:请至少添加一个阶段(Stage)。");
|
||||
return { ok: false, errors, warnings };
|
||||
}
|
||||
|
||||
// 记录每个席位首次出现的 stage 序号,用来检测跨 stage 重复。
|
||||
const seenInStage = new Map<string, number>();
|
||||
|
||||
plan.stages.forEach((stage, idx) => {
|
||||
const human = idx + 1;
|
||||
|
||||
if (!stage.agentIds || stage.agentIds.length === 0) {
|
||||
errors.push(`第 ${human} 阶段为空:请至少放入一个席位,或删除该阶段。`);
|
||||
return;
|
||||
}
|
||||
|
||||
const seenInThisStage = new Set<string>();
|
||||
for (const agentId of stage.agentIds) {
|
||||
if (!roster.has(agentId)) {
|
||||
errors.push(`第 ${human} 阶段包含未选定的席位「${agentId}」,请先把它加入参与角色。`);
|
||||
continue;
|
||||
}
|
||||
if (seenInThisStage.has(agentId)) {
|
||||
errors.push(`第 ${human} 阶段内席位「${agentId}」重复,一个席位每阶段只能出现一次。`);
|
||||
continue;
|
||||
}
|
||||
seenInThisStage.add(agentId);
|
||||
|
||||
const firstStage = seenInStage.get(agentId);
|
||||
if (firstStage !== undefined) {
|
||||
errors.push(
|
||||
`席位「${agentId}」同时出现在第 ${firstStage + 1} 与第 ${human} 阶段,一个席位只能跑一次。`,
|
||||
);
|
||||
} else {
|
||||
seenInStage.set(agentId, idx);
|
||||
}
|
||||
}
|
||||
|
||||
if (stage.agentIds.length > PARALLEL_DEGREE_WARN_THRESHOLD) {
|
||||
warnings.push(
|
||||
`第 ${human} 阶段并行 ${stage.agentIds.length} 个席位,可能触发远程模型并发限流或沙箱压力,建议拆分。`,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
return { ok: errors.length === 0, errors, warnings };
|
||||
}
|
||||
|
||||
// ── 链条 → DAG 兼容转换(§1.3)───────────────────────────────────────────────
|
||||
|
||||
/** 生成稳定的 stage id。不依赖随机数,便于单测与 diff(用序号即可,stages 不重排前唯一)。 */
|
||||
function stageId(index: number): string {
|
||||
return `stage-${index}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 把线性链条(有序席位数组)转换成「每层 1 个节点」的 DAG 计划。
|
||||
*
|
||||
* 老 `chain` 模式的数据只是有序的 `selectedAgents`(线性),读取时即时转换为
|
||||
* 单节点-stage 的 dag,不破坏老 draft(§1.3 兼容层)。
|
||||
*
|
||||
* @param orderedAgentIds 链条顺序的席位 agent_id。
|
||||
* @param finalSynthesis 是否收口综合,默认 true。
|
||||
*/
|
||||
export function chainToDagPlan(
|
||||
orderedAgentIds: string[],
|
||||
finalSynthesis = true,
|
||||
): OrchestrationPlan {
|
||||
return {
|
||||
mode: "dag",
|
||||
stages: orderedAgentIds.map((agentId, idx) => ({
|
||||
id: stageId(idx),
|
||||
agentIds: [agentId],
|
||||
})),
|
||||
finalSynthesis,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 构造一个空计划(编辑器初始态 / 兜底)。
|
||||
*/
|
||||
export function emptyPlan(finalSynthesis = true): OrchestrationPlan {
|
||||
return { mode: "dag", stages: [], finalSynthesis };
|
||||
}
|
||||
|
||||
/**
|
||||
* 把业务链条的 `stages`(agent_id 分组的 string[][])转成执行计划。
|
||||
*
|
||||
* - `allowedIds` 提供时,过滤掉不在其中的 agent_id(如链条里有席位被删除),
|
||||
* 并丢弃过滤后变空的 stage —— 保证选入 Step 2 的计划只含存活席位。
|
||||
* - 全部为空时返回空 stages(调用方据此判断退回 chain / recommend)。
|
||||
*
|
||||
* @param stages 链条分层(每组并行、组间串行)。
|
||||
* @param allowedIds 仅保留这些 agent_id(存活席位);省略则全保留。
|
||||
* @param finalSynthesis 是否收口综合,默认 true。
|
||||
* @param goals 可选「每阶段目标」,与 `stages` **同源下标**对齐;存活 stage 取对应 goal
|
||||
* (被丢弃的 stage 其 goal 一并丢弃,因为按源下标取)。
|
||||
* @param coordinatorPrompt 可选「总控编排提示」(写给总控的整体派活指引),挂在计划上,
|
||||
* 注入总控每阶段派活提示。空 = 不带。
|
||||
*/
|
||||
export function buildPlanFromStages(
|
||||
stages: string[][],
|
||||
allowedIds?: Iterable<string>,
|
||||
finalSynthesis = true,
|
||||
goals?: ReadonlyArray<string | null> | null,
|
||||
coordinatorPrompt?: string | null,
|
||||
): OrchestrationPlan {
|
||||
const allow = allowedIds ? new Set(allowedIds) : null;
|
||||
const cleaned: OrchestrationStage[] = [];
|
||||
stages.forEach((group, idx) => {
|
||||
const ids = allow ? group.filter((id) => allow.has(id)) : group.slice();
|
||||
if (ids.length === 0) return;
|
||||
const goal = goals?.[idx]?.trim() || undefined;
|
||||
cleaned.push(goal ? { id: stageId(idx), agentIds: ids, goal } : { id: stageId(idx), agentIds: ids });
|
||||
});
|
||||
const cp = coordinatorPrompt?.trim() || undefined;
|
||||
return cp
|
||||
? { mode: "dag", stages: cleaned, finalSynthesis, coordinatorPrompt: cp }
|
||||
: { mode: "dag", stages: cleaned, finalSynthesis };
|
||||
}
|
||||
|
||||
/** 该 stage 是否真并行(≥2 席位)—— Phase 3 决定是否禁写文件 / Phase 5 决定显示。 */
|
||||
export function isParallelStage(stage: OrchestrationStage): boolean {
|
||||
return stage.agentIds.length > 1;
|
||||
}
|
||||
|
||||
// ── 派活提示构造(纯函数,Phase 3 调度用,可单测,§3.1 依赖摘要注入)──────────────
|
||||
|
||||
/** 已完成席位的一条交付(喂给后续 stage 当依赖上下文)。 */
|
||||
export interface StageDelivery {
|
||||
/** 席位显示名(中文优先)。 */
|
||||
seatName: string;
|
||||
/** 该席位本轮交付正文。 */
|
||||
content: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 把前面所有 stage 已交付席位的正文拼成「依赖摘要」,注入下一 stage 的派活提示。
|
||||
* 每条按 `maxCharsPerSeat` 截断,避免后续席位上下文过长(§3.1:stage 边界拉一次摘要)。
|
||||
* 无交付(首 stage)返回空串。
|
||||
*/
|
||||
export function buildDependencySummary(
|
||||
deliveries: StageDelivery[],
|
||||
maxCharsPerSeat = 1200,
|
||||
): string {
|
||||
if (deliveries.length === 0) return "";
|
||||
return deliveries
|
||||
.map((d) => {
|
||||
const body = (d.content ?? "").trim();
|
||||
const clipped =
|
||||
body.length > maxCharsPerSeat ? `${body.slice(0, maxCharsPerSeat)}…(已截断)` : body;
|
||||
return `【${d.seatName}】的交付:\n${clipped || "(无文本输出)"}`;
|
||||
})
|
||||
.join("\n\n");
|
||||
}
|
||||
|
||||
/**
|
||||
* 为某 stage 内一个席位构造 special 派活提示(DAG 直派,无 leader,§3.2 方案 B)。
|
||||
*
|
||||
* - 首 stage(`priorSummary` 为空):带任务背景。
|
||||
* - 后续 stage:带前序交付摘要让其承接(§3.1 依赖可见性)。
|
||||
* - 并行 stage(`isParallel`):明确要求**产出写在正文、禁止写文件 / 沙箱命令**
|
||||
* (§4.3 / §9:并行禁写文件,降低模型困惑,与后端 `seat_parallel` policy 呼应)。
|
||||
*/
|
||||
export function buildStageTask(args: {
|
||||
seedMessage: string;
|
||||
seatName: string;
|
||||
/**
|
||||
* 上一阶段的上下文:
|
||||
* - 默认(`priorIsBridge` 假):{@link buildDependencySummary} 拼出的机械交付摘要;
|
||||
* - `priorIsBridge` 真:总控「承上启下」中转轮({@link buildDagTransitTask})的综合说明。
|
||||
* 首 stage 传空串。
|
||||
*/
|
||||
priorSummary: string;
|
||||
isParallel: boolean;
|
||||
/**
|
||||
* `priorSummary` 是否为总控中转轮(§12.3)产出的「承上启下」说明(而非机械交付摘要)。
|
||||
* 真时改用对应措辞,让席位知道这是总控综合后的指引。缺省 false(机械摘要)。
|
||||
*/
|
||||
priorIsBridge?: boolean;
|
||||
}): string {
|
||||
const { seedMessage, seatName, priorSummary, isParallel, priorIsBridge } = args;
|
||||
const lines: string[] = [];
|
||||
if (!priorSummary) {
|
||||
lines.push("这是一次【分层 DAG 编排】的多智能体圆桌研讨。任务背景如下:", seedMessage, "");
|
||||
} else if (priorIsBridge) {
|
||||
lines.push("分层研讨继续。以下是总控对此前各阶段的【承上启下】综合说明,请据此承接:", "", priorSummary, "");
|
||||
} else {
|
||||
lines.push("分层研讨继续。以下是此前各阶段已完成席位的交付摘要,供你承接:", "", priorSummary, "");
|
||||
}
|
||||
lines.push(`请你作为「${seatName}」,从你的专业职责出发,完成本阶段的分析与交付。`);
|
||||
if (isParallel) {
|
||||
lines.push(
|
||||
"⚠️ 本阶段为并行研讨:请把你的产出**直接写在回复正文里**,不要写文件、不要执行沙箱命令——并行期间禁止文件写入,以免与同批其他席位互相打架。需要落文件的产物会留到后续串行 / 收口阶段单独处理。",
|
||||
);
|
||||
}
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
||||
/**
|
||||
* 总控「中转轮」派活提示(§12.3 Stage 间经总控中转 + 广播)。
|
||||
*
|
||||
* DAG 各 stage 之间插入一轮 leader:综合上一批并行席位的交付,产出一段「承上启下」
|
||||
* 说明,再作为下一 stage 席位 task 的上下文(见 {@link buildStageTask} 的
|
||||
* `priorIsBridge`)。下一批席位由编排计划**钉死**(已在 `nextSeatNames` 列出),
|
||||
* 故提示明确要求总控**不要自己派活、不要收口**——只做综合(前端照计划直派下一批)。
|
||||
*
|
||||
* 「传摘要按需传全文」:各席位真实交付由后端 `_collect_delivery_status`(轻量
|
||||
* `GET /last-ai-message?max_chars=N` 接口)实读后注入总控输入——中转轮默认只注入
|
||||
* 每席位 ~600 字**摘要**,完整交付正文留到最终收口的 synthesis 轮才按需读取。
|
||||
* 本提示因此不重复塞交付正文,保持总控上下文精简、响应快。
|
||||
*/
|
||||
export function buildDagTransitTask(args: {
|
||||
/** 刚完成的本批席位显示名(仅用于提示文案,真实交付由后端核对注入)。 */
|
||||
completedSeatNames: string[];
|
||||
/** 下一阶段由计划钉死、即将执行的席位显示名。 */
|
||||
nextSeatNames: string[];
|
||||
}): string {
|
||||
const { completedSeatNames, nextSeatNames } = args;
|
||||
const done = completedSeatNames.join("、") || "本批席位";
|
||||
const next = nextSeatNames.join("、") || "下一阶段席位";
|
||||
return [
|
||||
"【分层 DAG · 总控中转轮】本阶段并行席位已全部完成交付。",
|
||||
`已完成席位:${done}。系统已把各席位的真实交付(摘要)客观核对后注入到你本轮输入里,以此为准。`,
|
||||
"请你作为总控,综合这一批的交付,产出一段【承上启下】说明:提炼关键结论与未决问题,并给出对下一阶段的指引。",
|
||||
`下一阶段将由编排计划**钉死**执行的席位是:${next}。这些席位由系统按计划直接派活,` +
|
||||
"**你不需要、也不要**通过 agent_orchestration 自行派活,更不要现在收口或输出最终方案。",
|
||||
"只输出这段承上启下的综合说明即可——它会作为下一阶段席位承接前序结论的上下文。",
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
// ── 总控驱动的「每 stage 派活轮」(§3.2 方案 A + 批内并行,2026-06-07 改)─────────
|
||||
//
|
||||
// 把 DAG 执行从「前端直派」改成「总控驱动」:每个 stage 由总控**真正派活**给该 stage
|
||||
// 计划钉死的席位(约束总控只派给这些席位、且每个都派到),席位并行执行、完成后交付经
|
||||
// 后端广播 + `_collect_delivery_status` 回到总控,总控下一 stage 继续派活。与 chain 模式
|
||||
// 同构(`buildChainLeaderTask` 单席位),区别是一次钉死**一批**席位、批内并行。
|
||||
|
||||
/**
|
||||
* 总控「每 stage 派活轮」提示:约束总控只对本 stage 钉死的若干席位派活(§3.2 方案 A)。
|
||||
*
|
||||
* - 首 stage(`isFirst`):带任务背景;后续 stage:靠后端注入的此前交付摘要承上。
|
||||
* - `seats` 是本 stage 计划钉死的席位(≥2 即并行批次),要求总控对**每个**席位都
|
||||
* 通过 agent_orchestration 派一个聚焦其职责的 task,不要派给清单外席位、不要自答 / 收口。
|
||||
*
|
||||
* 「传摘要按需传全文」:此处不塞各席位交付正文——后端 `_build_seat_status_block` 已把
|
||||
* 此前各席位的真实交付(摘要)注入总控本轮输入;完整正文留到末尾收口的 synthesis 轮。
|
||||
*/
|
||||
export function buildDagStageLeaderTask(args: {
|
||||
seedMessage: string;
|
||||
/** 0-based stage 序号。 */
|
||||
stageIndex: number;
|
||||
totalStages: number;
|
||||
/** 本 stage 计划钉死的席位。 */
|
||||
seats: Array<{ agentId: string; name: string }>;
|
||||
isFirst: boolean;
|
||||
/** 可选「本阶段目标」:用户在业务链条里为本阶段写的产出 / 依赖说明。空 = 不注入。 */
|
||||
goal?: string;
|
||||
/**
|
||||
* 可选「总控编排提示」:用户在业务链条里写给总控的整体派活指引(怎么派活 / 做什么 /
|
||||
* 风格 / 约束)。每个 stage 的派活轮都注入,作为总控的高优先编排原则。空 = 不注入。
|
||||
*/
|
||||
coordinatorPrompt?: string;
|
||||
}): string {
|
||||
const { seedMessage, stageIndex, totalStages, seats, isFirst, goal, coordinatorPrompt } = args;
|
||||
const ordinal = `${stageIndex + 1}/${totalStages}`;
|
||||
const seatList = seats
|
||||
.map((s) => `「${s.name}」(agent_name: ${s.agentId})`)
|
||||
.join("、");
|
||||
const isParallel = seats.length > 1;
|
||||
const goalText = goal?.trim();
|
||||
const coordText = coordinatorPrompt?.trim();
|
||||
const lines: string[] = [];
|
||||
if (isFirst) {
|
||||
lines.push("这是一次【分层 DAG 编排】的多智能体圆桌研讨。任务背景如下:", seedMessage, "");
|
||||
} else {
|
||||
lines.push(
|
||||
"分层研讨继续。系统已把此前各阶段席位的真实交付(摘要)客观核对后注入到你本轮输入里,请据此承上启下。",
|
||||
"",
|
||||
);
|
||||
}
|
||||
if (coordText) {
|
||||
lines.push(
|
||||
"【总控编排指引(用户预设,最高优先)】以下是本次业务链条为你(总控)预设的整体派活原则,请在每一阶段派活时都严格遵循:",
|
||||
coordText,
|
||||
"",
|
||||
);
|
||||
}
|
||||
lines.push(
|
||||
`本研讨严格按预设分层顺序进行,共 ${totalStages} 个阶段,现在是第 ${ordinal} 个阶段。`,
|
||||
`本阶段需要执行的席位(已由编排计划钉死)是:${seatList}。`,
|
||||
);
|
||||
if (goalText) {
|
||||
lines.push(
|
||||
`【本阶段目标】${goalText}`,
|
||||
"请据此目标为每个席位拆解任务,并要求他们**显式承接上一阶段的产出**来完成本阶段目标。",
|
||||
);
|
||||
}
|
||||
lines.push(
|
||||
`请你作为总控,通过 agent_orchestration 技能**分别**向上述${isParallel ? `这 ${seats.length} 个席位` : "席位"}派活,结合任务背景${goalText ? "、本阶段目标" : ""}与此前交付,为每个席位分配聚焦其职责的本阶段任务。`,
|
||||
"只派给上述席位、且每个都必须派到;不要派给清单外的任何席位,也不要自己直接作答或给出最终结论。",
|
||||
"⚠️ 必须**真正调用 agent_orchestration 工具**来派活(每个席位对应一次工具调用);**不要**只用文字罗列「席位1:…席位2:…」这样的任务清单——只写文字而不调用工具,系统无法把任务下发给席位。",
|
||||
);
|
||||
if (isParallel) {
|
||||
lines.push(
|
||||
`注意:本阶段这 ${seats.length} 个席位会**并行**执行,请确保给每个席位的 task 都能独立完成,不要让它们互相等待。`,
|
||||
);
|
||||
}
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
||||
/**
|
||||
* 从总控「每 stage 派活轮」的终态里,取出派给**某个**钉死席位的 task 文本:
|
||||
* 1) 命中 agent_name === seatAgentId 的结构化派活(总控真调了 agent_orchestration 工具)
|
||||
* → 用它的 task(正常路径);
|
||||
* 2) 总控**没用工具、只写了文字**(弱模型常见,dispatched 为空 / 没命中该席位)→ **绝不**把
|
||||
* 总控的整段派活叙述喂给席位 —— 否则席位会把「我来调度…席位1/2/3」当成自己的任务照抄、
|
||||
* 模仿派活,甚至绕道 bash/python 调内部接口去派活(已在生产观测到)。改给一个**干净的本职
|
||||
* 任务**:任务背景与此前各阶段交付已由后端广播进席位线程上下文,席位据此承接即可。
|
||||
*
|
||||
* 所有分支都追加「角色边界护栏」,明确席位**不是总控、不许派活**(席位本就被 run policy 禁了
|
||||
* agent_orchestration,但弱模型会空转叙述 / 绕道,故再从提示层钉死)。
|
||||
*/
|
||||
export function pickDagSeatTask(
|
||||
dispatched: ReadonlyArray<readonly [string, string]>,
|
||||
seatAgentId: string,
|
||||
seatName: string,
|
||||
seedMessage = "",
|
||||
/** 是否已有前序席位交付(决定是否提示 read_peer_delivery 工具按需取全文,§12.9)。 */
|
||||
hasPeers = false,
|
||||
/**
|
||||
* 是否允许写文件(§12.10):
|
||||
* - `true`(**沙箱模式**):要求把交付**写成 .md 文件** + 正文摘要,禁 .py;
|
||||
* - `false`(**快速模式**,默认):产物**直接写在正文**,不写文件(fast 模式产物走正文)。
|
||||
*/
|
||||
allowFiles = false,
|
||||
/**
|
||||
* 可选「本阶段目标」(兜底注入):总控派活质量差 / 没派到时,席位仍据此知道本阶段要产出
|
||||
* 什么、如何依赖上一阶段产出。空 = 不注入。
|
||||
*/
|
||||
goal = "",
|
||||
): string {
|
||||
const guard =
|
||||
`\n\n【角色边界·必读】你是**执行席位**「${seatName}」,不是总控协调者,本轮**只**对你自己的交付负责。**严禁**任何形式的派活 / 调度:不要调用 agent_orchestration 或 skill_list,不要用 python / 脚本去访问内部接口(如 /api/agents、agent_orchestration)来调度,不要罗列或给其他席位分配任务清单、不要复述「我来调度各智能体」这类总控口吻。`;
|
||||
// 产物要求(§12.8 / §12.10):沙箱模式产出 .md 文件(禁 .py);快速模式产物走正文、不写文件。
|
||||
const fileRule = allowFiles
|
||||
? `\n\n【产物要求】请把你的**完整交付写成一个 Markdown(.md)文件**(用 write_file 写到 outputs 目录,文件名体现你的职责),并在回复正文里给出要点摘要。**不要写 .py 或任何可执行脚本文件**(不要写脚本去生成产物);直接产出成品文档,.md / .html / .txt 等其它格式都可以,唯独不要 .py。`
|
||||
: `\n\n【产物要求】本轮为**快速并行**模式:请把你的产物**直接写在回复正文里**,**不要写文件、不要执行脚本/命令**(需要落文件的产物留给沙箱模式或后续阶段)。`;
|
||||
// 任务背景:DAG 派活轮抑制了 leader 预广播(防席位模仿派活),所以席位 thread 里可能没有
|
||||
// 用户原始消息 —— 把任务背景直接写进席位 task,确保它有上下文(此前各阶段交付仍由后端
|
||||
// 席位间 detached 广播注入,故只补背景)。
|
||||
const bg = seedMessage.trim() ? `本次研讨的任务背景:\n${seedMessage.trim()}\n\n` : "";
|
||||
// §12.9:此前各阶段席位的交付,你默认只看到**摘要**(广播进来的);若某个前序席位的摘要不够、
|
||||
// 你需要它的**完整交付**,调用 read_peer_delivery('<席位名>') 按需取全文(平时不必调,优先用摘要)。
|
||||
const peerRule = hasPeers
|
||||
? `\n\n【按需取全文】此前各阶段席位的交付你默认只看到**摘要**;若需要某个前序席位的**完整交付**,调用工具 read_peer_delivery('<该席位名称>') 取回全文(摘要够用就不必调)。`
|
||||
: "";
|
||||
// 本阶段目标(兜底):用户为本阶段写的产出/依赖说明,即便总控没派好,席位也据此对齐本阶段意图。
|
||||
const goalRule = goal.trim()
|
||||
? `\n\n【本阶段目标】${goal.trim()}\n请确保你的交付服务于该目标,并显式承接上一阶段的产出。`
|
||||
: "";
|
||||
const wanted = seatAgentId.toLowerCase();
|
||||
const exact = dispatched.find(([name]) => name.toLowerCase() === wanted);
|
||||
if (exact && exact[1]?.trim()) {
|
||||
return `${bg}请你作为「${seatName}」,完成总控派给你的本阶段任务:\n${exact[1].trim()}${goalRule}${fileRule}${peerRule}${guard}`;
|
||||
}
|
||||
// dispatched 为空 / 未命中 → 干净本职任务,**不**注入总控派活叙述(根治「席位模仿派活」)。
|
||||
return (
|
||||
`${bg}请你作为「${seatName}」,从你的专业职责出发,独立完成本阶段属于你的分析与交付。` +
|
||||
`此前各阶段席位的交付已在你的会话上下文里,请据此承接。` +
|
||||
goalRule +
|
||||
fileRule +
|
||||
peerRule +
|
||||
guard
|
||||
);
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -23,7 +23,7 @@
|
||||
* 6) 模型选择全局默认 `availableModels[0].name`,Persona 覆盖更高优先级
|
||||
*/
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useNavigate, useLocation } from "react-router-dom";
|
||||
import {
|
||||
Activity,
|
||||
Check,
|
||||
@@ -51,6 +51,7 @@ import {
|
||||
|
||||
import { useTheme } from "@/contexts/ThemeContext";
|
||||
import { useArtifacts } from "@/components/workspace/artifacts";
|
||||
import { useSidebarSafe } from "@/components/ui/sidebar";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { useModels } from "@/core/models/hooks";
|
||||
|
||||
@@ -83,13 +84,44 @@ import {
|
||||
type RoleEntry,
|
||||
type SelectedAgent,
|
||||
} from "@/roundtable-planning/lib/roundtable-constants";
|
||||
import type { SeatSelectionResult } from "@/roundtable-planning/lib/business-chain";
|
||||
import {
|
||||
buildChainSeatSelection,
|
||||
type SeatSelectionResult,
|
||||
} from "@/roundtable-planning/lib/business-chain";
|
||||
import type { OrchestrationPlan } from "@/roundtable-planning/lib/dag-types";
|
||||
import { getJobByDraft, startJob } from "@/roundtable-planning/api/roundtable-jobs";
|
||||
import { getChain } from "@/roundtable-planning/api/chains";
|
||||
import { filterRecommendCandidates } from "@/roundtable-planning/api/recommend";
|
||||
import { listAgents } from "@/core/agents";
|
||||
import { listBusinessMappings } from "@/strategy-components/api/business-mapping";
|
||||
|
||||
/** 从任务页带进来的预填(经 navigation state 传递)。见会商自动化串联(模块 C)。 */
|
||||
interface RoundtablePrefill {
|
||||
/** 任务名称(注入 Step 1 首条用户消息)。 */
|
||||
taskTitle?: string;
|
||||
/** 任务描述(注入 Step 1 首条用户消息)。 */
|
||||
taskGoal?: string;
|
||||
/** 来源业务码(如 "6BF"):据此查业务映射拿到要自动选用的业务链。 */
|
||||
businessCode?: string;
|
||||
/** 是否进入即自动开跑 Step 1 意图分析。 */
|
||||
autoStart?: boolean;
|
||||
}
|
||||
|
||||
export default function RoundtablePlanningPage() {
|
||||
const { theme } = useTheme();
|
||||
const isDark = theme === "dark";
|
||||
const navigate = useNavigate();
|
||||
const location = useLocation();
|
||||
|
||||
// ─── 会商自动化串联(模块 C):任务页带进来的预填 ─────────────────
|
||||
// 只在首次渲染读一次 navigation state;随后清掉 history state,避免刷新/后退重放。
|
||||
const prefillRef = useRef<RoundtablePrefill | null>(
|
||||
((location.state as { roundtablePrefill?: RoundtablePrefill } | null)?.roundtablePrefill) ?? null,
|
||||
);
|
||||
// 由 prefill.businessCode 解析出的「自动选用业务链」结果;有值时「进入研讨」跳过选链弹窗直接进 Step 2。
|
||||
const [autoChainResult, setAutoChainResult] = useState<SeatSelectionResult | null>(null);
|
||||
const autoStartedRef = useRef(false);
|
||||
const prefillClearedRef = useRef(false);
|
||||
|
||||
const { models: availableModels, isLoading: modelsLoading } = useModels();
|
||||
|
||||
@@ -104,13 +136,19 @@ export default function RoundtablePlanningPage() {
|
||||
// 「导入会商」弹窗(输入分享码把别人分享的会商复制到本账号)。
|
||||
const [isImportOpen, setIsImportOpen] = useState<boolean>(false);
|
||||
const [selectedModel, setSelectedModel] = useState<string>("");
|
||||
// Step 2 编排模式:recommend = 总控自由派活;chain = 总控按业务链条顺序派活。
|
||||
// Step 2 编排模式:recommend = 总控自由派活;chain = 总控按业务链条顺序派活;
|
||||
// dag = 分层 DAG(stage 内并行、stage 间串行,配合 orchestrationPlan)。
|
||||
// 由推荐弹窗确认时的 SeatSelectionResult.mode 决定(见 handleConfirmAgents)。
|
||||
const [orchestrationMode, setOrchestrationMode] = useState<"recommend" | "chain">(
|
||||
const [orchestrationMode, setOrchestrationMode] = useState<"recommend" | "chain" | "dag">(
|
||||
"recommend",
|
||||
);
|
||||
// chain 模式来源链条(仅展示/持久化用)。
|
||||
const [chainMeta, setChainMeta] = useState<{ id: string; title: string } | null>(null);
|
||||
// dag 模式的分层编排计划(Phase 2 编辑器产出;持久化进 step2.orchestrationPlan)。
|
||||
const [orchestrationPlan, setOrchestrationPlan] = useState<OrchestrationPlan | null>(null);
|
||||
// dag 执行子模式:fast(并行双列禁写)/ sandbox(并行单列可写、沙箱跟随)。
|
||||
// 由推荐弹窗的「执行方式」选择决定(仅 dag 有意义)。
|
||||
const [dagExecMode, setDagExecMode] = useState<"fast" | "sandbox">("fast");
|
||||
const [step2SidebarExpanded, setStep2SidebarExpanded] = useState(true);
|
||||
const [step2Runs, setStep2Runs] = useState<DraftStep2RunSnapshot[]>([]);
|
||||
const [activeStep2RunId, setActiveStep2RunId] = useState<string | null>(null);
|
||||
@@ -121,6 +159,9 @@ export default function RoundtablePlanningPage() {
|
||||
const [step3SavedTick, setStep3SavedTick] = useState<number>(0);
|
||||
const step2RunsRef = useRef<DraftStep2RunSnapshot[]>([]);
|
||||
const activeStep2RunIdRef = useRef<string | null>(null);
|
||||
// 并行执行时收起左侧栏 —— 全局工作区侧栏(最左)走 useSidebarSafe(与「打开沙箱」同一路径,
|
||||
// 见 artifacts/context.tsx 的 sidebar.setOpen(false)),圆桌「参与角色」栏走 step2SidebarExpanded。
|
||||
const sidebar = useSidebarSafe();
|
||||
|
||||
// 角色面板(LeftSidebar)。原页面把它当成两步共用的展示数据,这里继续放在
|
||||
// 主页 —— Step 1 / Step 2 / Step 3 都会读 / 写它,任何 hook 单独持有都不合适。
|
||||
@@ -194,6 +235,8 @@ export default function RoundtablePlanningPage() {
|
||||
currentStep,
|
||||
selectedModel,
|
||||
orchestrationMode,
|
||||
orchestrationPlan,
|
||||
dagExecMode,
|
||||
buildInitialIntent,
|
||||
triggerToast,
|
||||
setRoles,
|
||||
@@ -243,10 +286,14 @@ export default function RoundtablePlanningPage() {
|
||||
seatStubMessages: step2.seatStubMessages,
|
||||
orchestrationMode,
|
||||
chain: chainMeta,
|
||||
orchestrationPlan,
|
||||
dagExecMode,
|
||||
}),
|
||||
[
|
||||
chainMeta,
|
||||
orchestrationMode,
|
||||
orchestrationPlan,
|
||||
dagExecMode,
|
||||
step2.budgetLimit,
|
||||
step2.consensusPercentage,
|
||||
step2.coordinatorName,
|
||||
@@ -279,6 +326,8 @@ export default function RoundtablePlanningPage() {
|
||||
seatStubMessages: snapshot.seatStubMessages ?? {},
|
||||
orchestrationMode: snapshot.orchestrationMode,
|
||||
chain: snapshot.chain ?? null,
|
||||
orchestrationPlan: snapshot.orchestrationPlan ?? null,
|
||||
dagExecMode: snapshot.dagExecMode,
|
||||
step3: step3Report,
|
||||
}),
|
||||
[step3Report],
|
||||
@@ -362,6 +411,8 @@ export default function RoundtablePlanningPage() {
|
||||
(run: DraftStep2RunSnapshot) => {
|
||||
setOrchestrationMode(run.orchestrationMode ?? "recommend");
|
||||
setChainMeta(run.chain ?? null);
|
||||
setOrchestrationPlan(run.orchestrationPlan ?? null);
|
||||
setDagExecMode(run.dagExecMode ?? "fast");
|
||||
setStep3Report(run.step3 ?? null);
|
||||
step2.hydrateFromDraft(run as unknown as Step2Snapshot);
|
||||
},
|
||||
@@ -421,6 +472,8 @@ export default function RoundtablePlanningPage() {
|
||||
}
|
||||
setOrchestrationMode(snapshot.orchestrationMode ?? "recommend");
|
||||
setChainMeta(snapshot.chain ?? null);
|
||||
setOrchestrationPlan(snapshot.orchestrationPlan ?? null);
|
||||
setDagExecMode(snapshot.dagExecMode ?? "fast");
|
||||
step2.hydrateFromDraft(snapshot as unknown as Step2Snapshot);
|
||||
},
|
||||
cancelAllStreams: () => {
|
||||
@@ -504,6 +557,19 @@ export default function RoundtablePlanningPage() {
|
||||
drafts.loadedFromDraftRef,
|
||||
]);
|
||||
|
||||
// 并行执行 → 收起左侧栏腾出横向空间放两列(和「打开沙箱」一样的收起体验):
|
||||
// - 全局工作区侧栏(最左):sidebar.setOpen(false)(与 artifacts 打开沙箱同一路径);
|
||||
// - 圆桌「参与角色」栏:setStep2SidebarExpanded(false)。
|
||||
// **不自动复原**:并行结束后再进入单智能体回答时保持收起(用户需要时手动展开),
|
||||
// 与沙箱收起后不自动回弹一致。
|
||||
useEffect(() => {
|
||||
if (step2.isParallelRunning) {
|
||||
sidebar?.setOpen(false);
|
||||
setStep2SidebarExpanded(false);
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [step2.isParallelRunning]);
|
||||
|
||||
// ─── 步骤间转场 handler ───────────────────────────────────
|
||||
const handleConfirmAgents = useCallback(
|
||||
(result: SeatSelectionResult) => {
|
||||
@@ -537,7 +603,10 @@ export default function RoundtablePlanningPage() {
|
||||
budgetLimit: step2.budgetLimit,
|
||||
seatStubMessages: {},
|
||||
orchestrationMode: result.mode,
|
||||
chain: result.mode === "chain" ? result.chain ?? null : null,
|
||||
// chain / dag 都来自业务链条,保留来源链名;recommend 无。
|
||||
chain: result.mode === "recommend" ? null : result.chain ?? null,
|
||||
orchestrationPlan: result.mode === "dag" ? result.plan ?? null : null,
|
||||
dagExecMode: result.mode === "dag" ? result.dagExecMode ?? "fast" : undefined,
|
||||
step3: null,
|
||||
};
|
||||
setStep2Runs([...syncedRuns, newRun]);
|
||||
@@ -546,20 +615,88 @@ export default function RoundtablePlanningPage() {
|
||||
step2.resetStep2State();
|
||||
step2.setSelectedAgents(normalized);
|
||||
step2.resetInitGate();
|
||||
// result.mode 决定 Step 2 编排:recommend = 总控自由派活;chain = 按链条顺序派活。
|
||||
// result.mode 决定 Step 2 编排:recommend = 总控自由派活;chain = 按链条顺序派活;
|
||||
// dag = 分层并行(来源链条带 stages,携带 result.plan)。
|
||||
setOrchestrationMode(result.mode);
|
||||
setChainMeta(result.mode === "chain" ? result.chain ?? null : null);
|
||||
setChainMeta(result.mode === "recommend" ? null : result.chain ?? null);
|
||||
setOrchestrationPlan(result.mode === "dag" ? result.plan ?? null : null);
|
||||
setDagExecMode(result.mode === "dag" ? result.dagExecMode ?? "fast" : "fast");
|
||||
setIsRecommendDialogOpen(false);
|
||||
setCurrentStep(2);
|
||||
triggerToast(
|
||||
result.mode === "chain"
|
||||
? `成功确认!将按业务链条「${result.chain?.title ?? ""}」顺序研讨`
|
||||
: "成功确认!已切换至第二阶段圆桌研讨系统",
|
||||
result.mode === "dag"
|
||||
? `成功确认!将按业务链条「${result.chain?.title ?? ""}」分层并行研讨`
|
||||
: result.mode === "chain"
|
||||
? `成功确认!将按业务链条「${result.chain?.title ?? ""}」顺序研讨`
|
||||
: "成功确认!已切换至第二阶段圆桌研讨系统",
|
||||
);
|
||||
},
|
||||
[buildCurrentStep2Snapshot, mergeActiveRun, step2, step3Report, triggerToast],
|
||||
);
|
||||
|
||||
// ─── 会商自动化串联(模块 C) ──────────────────────────────────
|
||||
// 消费 prefill 后清掉 history state,避免刷新 / 后退重放自动开跑与自动选链。
|
||||
useEffect(() => {
|
||||
if (prefillClearedRef.current || !prefillRef.current) return;
|
||||
prefillClearedRef.current = true;
|
||||
try {
|
||||
window.history.replaceState({ ...window.history.state, usr: null }, "");
|
||||
} catch {
|
||||
/* noop */
|
||||
}
|
||||
}, []);
|
||||
|
||||
// C2:带 autoStart 时,等 Step 1 意图线程就绪后自动把「任务名称/描述」作为首条用户消息发出,
|
||||
// 触发任务理解智能体自动分析(只发一次)。
|
||||
useEffect(() => {
|
||||
const prefill = prefillRef.current;
|
||||
if (!prefill?.autoStart || autoStartedRef.current) return;
|
||||
if (currentStep !== 1) return;
|
||||
if (!step1.intentThreadId || step1.intentReady) return;
|
||||
const title = prefill.taskTitle?.trim();
|
||||
const goal = prefill.taskGoal?.trim();
|
||||
const text = [title ? `任务名称:${title}` : "", goal ? `任务描述:${goal}` : ""]
|
||||
.filter(Boolean)
|
||||
.join("\n");
|
||||
if (!text) return;
|
||||
autoStartedRef.current = true;
|
||||
void step1.sendIntentMessage(text);
|
||||
}, [currentStep, step1.intentThreadId, step1.intentReady, step1.sendIntentMessage]);
|
||||
|
||||
// C3:据 prefill.businessCode 查业务映射 → 取 chainId → 拉公共链 + 候选智能体 → 构造自动选链结果。
|
||||
// 解析成功后「进入研讨」会跳过选链弹窗直接据此进 Step 2;解析失败(未配置 / 链不存在 / 席位不足)
|
||||
// 静默回退到弹窗手选。
|
||||
// 不加「已启动」永久闸门 —— StrictMode 的 mount→unmount→remount 会让首次 run 在 cleanup
|
||||
// 里被 cancelled,闸门又让 remount 跳过重启,导致 autoChainResult 永远设不上(与
|
||||
// useStep1Intent 同款坑)。改为:每次 setup 都重跑,靠 cancelled 丢弃过期的首次结果,
|
||||
// 末次 setup 正常落地(生产无 StrictMode 只跑一次)。
|
||||
useEffect(() => {
|
||||
const prefill = prefillRef.current;
|
||||
if (!prefill?.businessCode) return;
|
||||
let cancelled = false;
|
||||
void (async () => {
|
||||
try {
|
||||
const mappings = await listBusinessMappings();
|
||||
const row = mappings.find((m) => m.businessCode === prefill.businessCode);
|
||||
const chainId = row?.chainId;
|
||||
if (!chainId) return;
|
||||
const [chain, agents] = await Promise.all([
|
||||
getChain(chainId),
|
||||
listAgents().catch(() => []),
|
||||
]);
|
||||
if (cancelled || !chain) return;
|
||||
const candidates = filterRecommendCandidates(agents);
|
||||
const result = buildChainSeatSelection(chain, candidates);
|
||||
if (!cancelled && result) setAutoChainResult(result);
|
||||
} catch {
|
||||
/* 解析失败 → 保持 null,回退弹窗手选 */
|
||||
}
|
||||
})();
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, []);
|
||||
|
||||
// 把页面重置回「第一步全新任务」——新建任务 + 后台挂起后都复用。
|
||||
// 注意:只清前端状态,不删后端已建的草稿 / 已挂起的后台作业(它们继续在后台跑,
|
||||
// 在历史记录里可见)。
|
||||
@@ -570,6 +707,8 @@ export default function RoundtablePlanningPage() {
|
||||
setActiveStep2RunId(null);
|
||||
setOrchestrationMode("recommend");
|
||||
setChainMeta(null);
|
||||
setOrchestrationPlan(null);
|
||||
setDagExecMode("fast");
|
||||
setStep3Report(null);
|
||||
step1.stopIntentStream();
|
||||
drafts.loadedFromDraftRef.current = false;
|
||||
@@ -609,7 +748,9 @@ export default function RoundtablePlanningPage() {
|
||||
intent: buildInitialIntent(),
|
||||
agents,
|
||||
model: selectedModel || undefined, // 模型沿用第二步选择
|
||||
orchestrationMode,
|
||||
// 后台作业引擎暂不支持 dag(分层 DAG 只在前端 runDagOrchestration 跑);
|
||||
// 挂起到后台时降级为 recommend(总控自由派活)。
|
||||
orchestrationMode: orchestrationMode === "dag" ? "recommend" : orchestrationMode,
|
||||
chain: chainMeta,
|
||||
// 不传 threadIds:后台作业由真网关自建全新线程,绝不复用前端本地研讨的线程
|
||||
// (那些线程可能有活跃 run,复用会撞 409)。
|
||||
@@ -855,6 +996,13 @@ export default function RoundtablePlanningPage() {
|
||||
triggerToast("⚠️ 请先与任务理解智能体完成澄清,生成任务摘要后再进入");
|
||||
return;
|
||||
}
|
||||
// 会商自动化串联(模块 C):若任务页带来的业务链已解析成功,跳过选链弹窗,
|
||||
// 直接据该业务链进入 Step 2 研讨(用户无需再手选)。
|
||||
if (autoChainResult) {
|
||||
const result = autoChainResult;
|
||||
void drafts.ensureDraft(1).finally(() => handleConfirmAgents(result));
|
||||
return;
|
||||
}
|
||||
// 先把草稿落地拿到 draft_id,推荐历史才有归属;失败也照常打开弹窗
|
||||
// (弹窗在无 draftId 时退化为「直接推荐、不存历史」)。
|
||||
void drafts.ensureDraft(1).finally(() => setIsRecommendDialogOpen(true));
|
||||
@@ -878,6 +1026,13 @@ export default function RoundtablePlanningPage() {
|
||||
agentConfigs={step2.agentConfigs}
|
||||
selectedAgentId={step2.selectedAgentId}
|
||||
roles={roles}
|
||||
parallelBatch={step2.parallelBatch}
|
||||
selectedParallelSeats={step2.selectedParallelSeats}
|
||||
isParallelRunning={step2.isParallelRunning}
|
||||
onToggleParallelSeat={step2.toggleParallelSeat}
|
||||
orchestrationMode={orchestrationMode}
|
||||
orchestrationPlan={orchestrationPlan}
|
||||
dagNodeStates={step2.dagNodeStates}
|
||||
agentNameToRole={step2.agentNameToRole}
|
||||
selectedModel={selectedModel}
|
||||
availableModels={availableModels}
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
/**
|
||||
* 全局业务映射(业务码 → 智能体 / 业务链)API 客户端。
|
||||
*
|
||||
* 后端:`/api/business-mapping`(见 app/gateway/routers/business_mapping.py)。
|
||||
* 全局共享、无用户隔离;只读列表 + 更新 agent / chain 两列(业务行由后端 seed 固定)。
|
||||
* snake_case ⇄ camelCase 在此边界收敛,调用方保持干净。
|
||||
*/
|
||||
|
||||
import { apiFetch } from "@/core/api/fetch-client";
|
||||
import { getBackendBaseURL } from "@/core/config";
|
||||
|
||||
export interface BusinessMapping {
|
||||
businessCode: string;
|
||||
label: string;
|
||||
agentId: string | null;
|
||||
agentName: string | null;
|
||||
chainId: string | null;
|
||||
chainTitle: string | null;
|
||||
sortOrder: number;
|
||||
}
|
||||
|
||||
/** 部分更新 —— 只发改动的字段;显式传 null 清空该字段。 */
|
||||
export interface BusinessMappingPatch {
|
||||
agentId?: string | null;
|
||||
agentName?: string | null;
|
||||
chainId?: string | null;
|
||||
chainTitle?: string | null;
|
||||
}
|
||||
|
||||
const BASE = () => `${getBackendBaseURL()}/api/business-mapping`;
|
||||
|
||||
interface ServerMapping {
|
||||
business_code: string;
|
||||
label: string;
|
||||
agent_id: string | null;
|
||||
agent_name: string | null;
|
||||
chain_id: string | null;
|
||||
chain_title: string | null;
|
||||
sort_order: number;
|
||||
}
|
||||
|
||||
function toMapping(s: ServerMapping): BusinessMapping {
|
||||
return {
|
||||
businessCode: s.business_code,
|
||||
label: s.label ?? "",
|
||||
agentId: s.agent_id ?? null,
|
||||
agentName: s.agent_name ?? null,
|
||||
chainId: s.chain_id ?? null,
|
||||
chainTitle: s.chain_title ?? null,
|
||||
sortOrder: s.sort_order ?? 0,
|
||||
};
|
||||
}
|
||||
|
||||
async function readJson<T>(res: Response, ctx: string): Promise<T> {
|
||||
if (!res.ok) {
|
||||
const text = await res.text().catch(() => "");
|
||||
throw new Error(`${ctx} failed (${res.status}): ${text}`);
|
||||
}
|
||||
return (await res.json()) as T;
|
||||
}
|
||||
|
||||
/** 列出全部业务映射(按展示顺序)。 */
|
||||
export async function listBusinessMappings(): Promise<BusinessMapping[]> {
|
||||
const res = await apiFetch(BASE(), { method: "GET" });
|
||||
const data = await readJson<{ mappings: ServerMapping[] }>(res, "list business mappings");
|
||||
return (data.mappings ?? []).map(toMapping);
|
||||
}
|
||||
|
||||
/** 更新某业务行的智能体 / 业务链选择。404 返回 null。 */
|
||||
export async function updateBusinessMapping(
|
||||
businessCode: string,
|
||||
patch: BusinessMappingPatch,
|
||||
): Promise<BusinessMapping | null> {
|
||||
const body: Record<string, unknown> = {};
|
||||
if (patch.agentId !== undefined) body.agent_id = patch.agentId;
|
||||
if (patch.agentName !== undefined) body.agent_name = patch.agentName;
|
||||
if (patch.chainId !== undefined) body.chain_id = patch.chainId;
|
||||
if (patch.chainTitle !== undefined) body.chain_title = patch.chainTitle;
|
||||
const res = await apiFetch(`${BASE()}/${encodeURIComponent(businessCode)}`, {
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
if (res.status === 404) return null;
|
||||
const data = await readJson<ServerMapping>(res, "update business mapping");
|
||||
return toMapping(data);
|
||||
}
|
||||
@@ -4,9 +4,10 @@ import { Bot, ChevronRight, Download, Edit, Eye, FileText, Layers, MoreHorizonta
|
||||
import React, { useEffect, useRef, useState } from 'react';
|
||||
import { format } from 'date-fns';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { Col, Empty, Loading, Pagination, Progress, Row } from 'tdesign-react';
|
||||
import { Col, Loading, Pagination, Progress, Row } from 'tdesign-react';
|
||||
import { requestCrudService } from '@/service/request-axios-service';
|
||||
import { ActionColumn } from './ActionColumn';
|
||||
import { resolveStatusIcon } from './icons';
|
||||
|
||||
interface ActionAnalyzesProps {
|
||||
TaskType?: string;
|
||||
@@ -78,7 +79,6 @@ export const ActionAnalyzes: React.FC<ActionAnalyzesProps> = ({ title, category,
|
||||
setTaskLoading(true);
|
||||
const res = await service.post(`${zncmUrl}/action/cop-action-tasks`, param);
|
||||
setTaskLoading(false);
|
||||
console.log('任务搜索', res);
|
||||
const result = res.data;
|
||||
result.forEach((item: TaskListItem) => {
|
||||
item.progress = item.endCount / item.sumAll || 0; // 获取已完成和未完成的占比
|
||||
@@ -86,7 +86,6 @@ export const ActionAnalyzes: React.FC<ActionAnalyzesProps> = ({ title, category,
|
||||
})
|
||||
setTaskList(result || []); // 设置任务列表页
|
||||
const totalRes = await service.post(`${zncmUrl}/action/cop-action-tasks-count`, param); // 查询任务总数
|
||||
console.log('totalRes', totalRes)
|
||||
setTotal(totalRes.data || 0); // 设置总数
|
||||
if (result.length > 0) {
|
||||
setTaskId(result[0].id);
|
||||
@@ -101,7 +100,6 @@ export const ActionAnalyzes: React.FC<ActionAnalyzesProps> = ({ title, category,
|
||||
}
|
||||
setActionLoading(true);
|
||||
const res = await service.get(`${zncmUrl}/action/cop-task-actions`, param);
|
||||
console.log('行动查询', res);
|
||||
setActionLoading(false);
|
||||
const result = res.data;
|
||||
setActionColumnList([
|
||||
@@ -151,7 +149,7 @@ export const ActionAnalyzes: React.FC<ActionAnalyzesProps> = ({ title, category,
|
||||
<div className="text-[var(--text-color)] text-[17px] mb-[5px] font-[500]">{item.taskName}</div>
|
||||
<div className="text-[#7f7f7f] mb-[5px]">{format(new Date(item.taskStartDate), 'yyyy-MM-dd HH:mm:ss')}</div>
|
||||
<div className="flex items-center mb-[8px]">
|
||||
<img src={`/icon/${item?.taskStatusData?.icon}`} alt="" />
|
||||
<img src={resolveStatusIcon(item?.taskStatusData?.icon)} className="w-[20px]" alt="" />
|
||||
<span className="ml-[5px] leading-[16px]">{item?.taskStatusData?.label}</span>
|
||||
</div>
|
||||
<div className="pb-[10px] pt-[10px]">
|
||||
@@ -195,7 +193,11 @@ export const ActionAnalyzes: React.FC<ActionAnalyzesProps> = ({ title, category,
|
||||
))
|
||||
}
|
||||
{
|
||||
actionColumnList.length === 0 && <Empty/>
|
||||
actionColumnList.length === 0 && (
|
||||
<div className={`col-span-4 flex items-center justify-center py-[60px] text-sm ${isDark ? 'text-slate-500' : 'text-[#bfbfbf]'}`}>
|
||||
暂无数据
|
||||
</div>
|
||||
)
|
||||
}
|
||||
</div>
|
||||
</Loading>
|
||||
|
||||
@@ -4,8 +4,9 @@ import { Bot, ChevronRight, Download, Edit, Eye, FileText, Layers, MoreHorizonta
|
||||
import React, { useEffect, useRef, useState } from 'react';
|
||||
import { format } from 'date-fns';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { Col, Empty, Pagination, Progress, Row } from 'tdesign-react';
|
||||
import { Col, Pagination, Progress, Row } from 'tdesign-react';
|
||||
import { requestCrudService } from '@/service/request-axios-service';
|
||||
import { resolveStatusIcon } from './icons';
|
||||
|
||||
interface ActionColumnProps {
|
||||
TaskType?: string;
|
||||
@@ -66,7 +67,7 @@ export const ActionColumn: React.FC<ActionColumnProps> = ({ title, category, sub
|
||||
<div className={`h-[calc(100vh-100px)] p-[10px] flex-1 ${isDark? 'dark-action-bg' : `bg-white action-bg${columnIndex} shadow-[2px_0px_6px_rgba(0,0,0,0.12)]`} rounded-[4px]`}>
|
||||
<div className="mb-[10px]">
|
||||
<div className="flex items-center mb-[20px]">
|
||||
<img src={`/icon/${icon}`} className="w-[24px] mr-[10px]" alt="" />
|
||||
<img src={resolveStatusIcon(icon)} className="w-[24px] mr-[10px]" alt="" />
|
||||
<span className="text-[#222222] text-[18px] font-bold mr-[20px]">{columnName}</span>
|
||||
<span className="text-[#222222] text-[18px] font-bold mr-[20px]">{actionCount}</span>
|
||||
</div>
|
||||
@@ -99,13 +100,11 @@ export const ActionColumn: React.FC<ActionColumnProps> = ({ title, category, sub
|
||||
))
|
||||
}
|
||||
{
|
||||
actionList.length === 0 && <Empty image={
|
||||
<img
|
||||
src="/icon/empty-list.png"
|
||||
alt="empty"
|
||||
className="w-[135px]"
|
||||
/>
|
||||
} />
|
||||
actionList.length === 0 && (
|
||||
<div className={`flex items-center justify-center py-[48px] text-sm ${isDark ? 'text-slate-500' : 'text-[#bfbfbf]'}`}>
|
||||
暂无数据
|
||||
</div>
|
||||
)
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import React, { useState } from 'react';
|
||||
import { ChevronRight, FileText } from 'lucide-react';
|
||||
import { FileText } from 'lucide-react';
|
||||
import { Pagination } from 'tdesign-react';
|
||||
import { useTheme } from '@/contexts/ThemeContext';
|
||||
import { TaskListItem } from './TaskManagement';
|
||||
@@ -11,8 +11,8 @@ interface KanbanColumnProps {
|
||||
color: string;
|
||||
tasks: TaskListItem[];
|
||||
taskType: string;
|
||||
TaskDataType?: string;
|
||||
pageIndexSearch: (taskType: string, pageIndex: number) => void;
|
||||
taskDataType?: string;
|
||||
pageIndexSearch: (taskType: string, pageIndex: number) => void | Promise<void>;
|
||||
handleStartAnalysis: (task: TaskListItem) => void;
|
||||
}
|
||||
|
||||
@@ -22,7 +22,7 @@ export const KanbanColumn: React.FC<KanbanColumnProps> = ({
|
||||
color,
|
||||
tasks,
|
||||
taskType,
|
||||
TaskDataType = 'task',
|
||||
taskDataType = 'task',
|
||||
pageIndexSearch,
|
||||
handleStartAnalysis,
|
||||
}) => {
|
||||
@@ -30,94 +30,79 @@ export const KanbanColumn: React.FC<KanbanColumnProps> = ({
|
||||
const isDark = theme === 'dark';
|
||||
const [pageNum, setPageNum] = useState(1);
|
||||
|
||||
const pageIndexChange = async (value: number) => {
|
||||
const handlePageChange = async (value: number) => {
|
||||
setPageNum(value);
|
||||
await pageIndexSearch(taskType, value);
|
||||
};
|
||||
|
||||
const columnClass = isDark
|
||||
? 'border border-[rgba(67,89,124,0.46)] bg-[linear-gradient(180deg,rgba(18,36,67,0.96),rgba(12,28,54,0.96))] shadow-[0_18px_40px_rgba(3,10,22,0.18)]'
|
||||
: 'border border-[#E8E8E8] bg-[linear-gradient(180deg,#FFFFFF_0%,#FFF9F9_100%)] shadow-[0_14px_28px_rgba(245,34,45,0.06)]';
|
||||
|
||||
return (
|
||||
<div
|
||||
className={`theme-transition flex h-full min-h-0 flex-col rounded-[28px] border p-4 md:p-5 ${
|
||||
isDark
|
||||
? 'theme-card border-[rgba(110,136,176,0.24)] shadow-[0_18px_50px_rgba(2,8,20,0.24)]'
|
||||
: 'border-slate-200 bg-white shadow-sm'
|
||||
}`}
|
||||
>
|
||||
<div className="mb-4 flex items-start justify-between gap-3">
|
||||
<div className="flex items-start gap-3">
|
||||
<div className={`mt-1 h-2.5 w-2.5 rounded-full ${color}`} />
|
||||
<div>
|
||||
<div className="flex items-center gap-2">
|
||||
<h2 className={`text-base font-semibold ${isDark ? 'text-slate-50' : 'text-slate-900'}`}>{title}</h2>
|
||||
<span
|
||||
className={`rounded-full px-2 py-0.5 text-xs ${
|
||||
isDark ? 'bg-[rgba(20,47,86,0.92)] text-slate-300' : 'bg-slate-100 text-slate-600'
|
||||
}`}
|
||||
>
|
||||
{count}
|
||||
</span>
|
||||
</div>
|
||||
<p className={`mt-1 text-xs ${isDark ? 'text-slate-400' : 'text-slate-500'}`}>
|
||||
按时间倒序展示,支持分页切换。
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<div
|
||||
className={`hidden rounded-xl p-2 lg:flex ${
|
||||
isDark ? 'bg-[rgba(10,30,54,0.82)] text-slate-300' : 'bg-slate-50 text-slate-500'
|
||||
}`}
|
||||
>
|
||||
<ChevronRight className="h-4 w-4" />
|
||||
</div>
|
||||
<Pagination
|
||||
className="sentiment-pagination"
|
||||
total={count}
|
||||
size="small"
|
||||
theme="simple"
|
||||
current={pageNum}
|
||||
pageSize={10}
|
||||
maxPageBtn={3}
|
||||
showPageSize={false}
|
||||
totalContent={false}
|
||||
onCurrentChange={(page) => pageIndexChange(Number(page))}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="scrollbar-thin flex-1 space-y-3 overflow-y-auto pr-1">
|
||||
{tasks.length === 0 ? (
|
||||
<div
|
||||
className={`flex h-full min-h-[260px] flex-col items-center justify-center rounded-2xl border border-dashed ${
|
||||
isDark
|
||||
? 'border-[rgba(110,136,176,0.24)] bg-[rgba(9,25,46,0.38)]'
|
||||
: 'border-slate-200 bg-slate-50'
|
||||
}`}
|
||||
>
|
||||
<div
|
||||
className={`mb-3 flex h-12 w-12 items-center justify-center rounded-2xl ${
|
||||
isDark ? 'bg-[rgba(13,42,78,0.92)] text-slate-300' : 'bg-white text-slate-500'
|
||||
<section className={`flex h-full flex-col rounded-[28px] p-4 ${columnClass}`}>
|
||||
<div className="flex items-center justify-between gap-4">
|
||||
<div className="flex min-w-0 items-center gap-2">
|
||||
<div className="flex min-w-0 items-center gap-2">
|
||||
<span className={`h-2.5 w-2.5 rounded-full ${color}`} />
|
||||
<h2
|
||||
className={`whitespace-nowrap text-[15px] font-semibold leading-none ${
|
||||
isDark ? 'text-white' : 'text-[#222222]'
|
||||
}`}
|
||||
>
|
||||
<FileText className="h-5 w-5" />
|
||||
</div>
|
||||
<div className={`text-sm ${isDark ? 'text-slate-300' : 'text-slate-600'}`}>暂无任务</div>
|
||||
<div className={`mt-1 text-xs ${isDark ? 'text-slate-500' : 'text-slate-400'}`}>
|
||||
可以尝试调整筛选条件或切换数据模式。
|
||||
</div>
|
||||
{title}
|
||||
</h2>
|
||||
<span
|
||||
className={`inline-flex rounded-full px-2 py-0.5 text-xs ${
|
||||
isDark ? 'bg-[rgba(77,141,255,0.14)] text-[#9CCBFF]' : 'bg-[#FFF1F0] text-[#CF1322]'
|
||||
}`}
|
||||
>
|
||||
{count}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Pagination
|
||||
className="sentiment-pagination shrink-0"
|
||||
total={count}
|
||||
size="small"
|
||||
theme="simple"
|
||||
current={pageNum}
|
||||
pageSize={10}
|
||||
maxPageBtn={3}
|
||||
showPageSize={false}
|
||||
totalContent={false}
|
||||
onCurrentChange={(page) => handlePageChange(Number(page))}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<p className={`mt-2 text-xs leading-6 ${isDark ? 'text-slate-400' : 'text-[#8C8C8C]'}`}>
|
||||
按时间倒序展示,支持分页切换。
|
||||
</p>
|
||||
|
||||
<div className="mt-4 flex-1 space-y-4">
|
||||
{tasks.length === 0 ? (
|
||||
<div
|
||||
className={`flex h-full min-h-[220px] flex-col items-center justify-center rounded-[22px] border border-dashed ${
|
||||
isDark
|
||||
? 'border-[rgba(87,111,149,0.42)] bg-[rgba(12,24,44,0.46)] text-slate-400'
|
||||
: 'border-[#F3C4C8] bg-[#FFF7F7] text-[#A6A6A6]'
|
||||
}`}
|
||||
>
|
||||
<FileText className="h-8 w-8 opacity-70" />
|
||||
<p className="mt-3 text-sm">暂无任务</p>
|
||||
</div>
|
||||
) : (
|
||||
tasks.map((task) => (
|
||||
<TaskCard
|
||||
key={task.id}
|
||||
task={task}
|
||||
TaskType={TaskDataType}
|
||||
taskDataType={taskDataType}
|
||||
handleStartAnalysis={handleStartAnalysis}
|
||||
/>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
};
|
||||
+306
-446
@@ -1,13 +1,14 @@
|
||||
import React, { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { ArrowRight, Bot, Clock3, Layers, Search, Sparkles, Users, X } from 'lucide-react';
|
||||
import { DateRangePicker, DateRangeValue, Loading } from 'tdesign-react';
|
||||
import { ArrowRight, Bot, Layers, Plus, Search, Users, X } from 'lucide-react';
|
||||
import dayjs from 'dayjs';
|
||||
import { DateRangePicker, DateRangePickerProps, DateRangeValue, Loading } from 'tdesign-react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useTheme } from '@/contexts/ThemeContext';
|
||||
import { useChatContext } from '@/contexts/ChatContext';
|
||||
import { requestCrudService } from '@/service/request-axios-service';
|
||||
import { toast } from 'sonner';
|
||||
import { KanbanColumn } from './KanbanColumn';
|
||||
import { TaskListItem } from './TaskManagement';
|
||||
import { listBusinessMappings } from '@/strategy-components/api/business-mapping';
|
||||
|
||||
interface TaskListPageProps {
|
||||
title: string;
|
||||
@@ -15,189 +16,27 @@ interface TaskListPageProps {
|
||||
subCategory: string;
|
||||
}
|
||||
|
||||
type TaskType = 'single' | 'consultation' | 'scene' | 'multi-agent' | 'task-search';
|
||||
type ColumnType = 'unanalyzed' | 'analyzing' | 'completed';
|
||||
interface StateItem {
|
||||
startTime: string;
|
||||
endTime: string;
|
||||
task: TaskListItem | null;
|
||||
}
|
||||
|
||||
type ColumnType = 'unanalyzed' | 'running' | 'completed';
|
||||
|
||||
const service = requestCrudService;
|
||||
const zncmUrl = import.meta.env.VITE_API_BASE_URL || '';
|
||||
const ENABLE_SENTIMENT_DEMO_BY_DEFAULT = import.meta.env.DEV;
|
||||
|
||||
const buildMockTask = (
|
||||
id: string,
|
||||
name: string,
|
||||
overview: string,
|
||||
column: ColumnType,
|
||||
type: TaskType,
|
||||
priority: 1 | 2 | 3,
|
||||
progress: number,
|
||||
createTime: string,
|
||||
updateTime: string,
|
||||
owner: string,
|
||||
): TaskListItem => ({
|
||||
id,
|
||||
taskName: name,
|
||||
overview,
|
||||
column,
|
||||
type,
|
||||
priority,
|
||||
progress,
|
||||
createTime,
|
||||
updateTime,
|
||||
owner,
|
||||
creator: owner,
|
||||
executor: owner,
|
||||
scene: JSON.stringify({
|
||||
taskJson: JSON.stringify({
|
||||
task_title: name,
|
||||
task_goal: overview,
|
||||
}),
|
||||
}),
|
||||
});
|
||||
|
||||
const MOCK_TASKS: Record<ColumnType, TaskListItem[]> = {
|
||||
unanalyzed: [
|
||||
buildMockTask(
|
||||
'demo-u-1',
|
||||
'新能源价格舆情波动分析',
|
||||
'聚焦近 7 日新能源整车与动力电池价格讨论热度,识别社媒与媒体端异常扩散信号。',
|
||||
'unanalyzed',
|
||||
'single',
|
||||
2,
|
||||
0,
|
||||
'2026-06-05 09:10:00',
|
||||
'2026-06-05 09:10:00',
|
||||
'王晓楠',
|
||||
),
|
||||
buildMockTask(
|
||||
'demo-u-2',
|
||||
'重点项目负面反馈聚类',
|
||||
'从任务评论、审批意见和业务群消息中抽取高频情绪主题,辅助判断风险聚焦点。',
|
||||
'unanalyzed',
|
||||
'consultation',
|
||||
3,
|
||||
0,
|
||||
'2026-06-05 08:40:00',
|
||||
'2026-06-05 08:40:00',
|
||||
'刘志诚',
|
||||
),
|
||||
buildMockTask(
|
||||
'demo-u-3',
|
||||
'竞品发布会用户情绪追踪',
|
||||
'围绕发布会直播、短视频评论与论坛帖子,建立情绪转折时间线并识别主要触发事件。',
|
||||
'unanalyzed',
|
||||
'scene',
|
||||
1,
|
||||
0,
|
||||
'2026-06-04 18:20:00',
|
||||
'2026-06-04 18:20:00',
|
||||
'陈思雨',
|
||||
),
|
||||
buildMockTask(
|
||||
'demo-u-4',
|
||||
'区域渠道满意度扫描',
|
||||
'基于周报、工单和售后回访文本,发现华东区域渠道服务满意度下行趋势。',
|
||||
'unanalyzed',
|
||||
'task-search',
|
||||
2,
|
||||
0,
|
||||
'2026-06-04 15:35:00',
|
||||
'2026-06-04 15:35:00',
|
||||
'赵明宇',
|
||||
),
|
||||
],
|
||||
analyzing: [
|
||||
buildMockTask(
|
||||
'demo-a-1',
|
||||
'新车上市口碑监测会商',
|
||||
'正在联合多个智能体汇总平台评价、媒体测评与用户问答,生成阶段性情绪画像。',
|
||||
'analyzing',
|
||||
'multi-agent',
|
||||
3,
|
||||
56,
|
||||
'2026-06-05 07:50:00',
|
||||
'2026-06-05 10:05:00',
|
||||
'张雨桐',
|
||||
),
|
||||
buildMockTask(
|
||||
'demo-a-2',
|
||||
'投诉热点归因拆解',
|
||||
'拆分售后投诉中关于续航、交付和门店服务的负面占比,分析主要归因与蔓延路径。',
|
||||
'analyzing',
|
||||
'consultation',
|
||||
2,
|
||||
78,
|
||||
'2026-06-04 20:10:00',
|
||||
'2026-06-05 09:48:00',
|
||||
'何嘉成',
|
||||
),
|
||||
],
|
||||
completed: [
|
||||
buildMockTask(
|
||||
'demo-c-1',
|
||||
'车展传播效果情绪复盘',
|
||||
'已输出传播节点热度变化、核心评论主题以及 KOL 内容对情绪曲线的影响分析。',
|
||||
'completed',
|
||||
'single',
|
||||
1,
|
||||
100,
|
||||
'2026-06-03 14:20:00',
|
||||
'2026-06-04 17:30:00',
|
||||
'孙怡宁',
|
||||
),
|
||||
buildMockTask(
|
||||
'demo-c-2',
|
||||
'智能驾驶争议议题扫描',
|
||||
'已完成争议议题聚类、情绪倾向分层和外部平台扩散链路分析,可直接查看结论。',
|
||||
'completed',
|
||||
'scene',
|
||||
3,
|
||||
100,
|
||||
'2026-06-03 09:00:00',
|
||||
'2026-06-04 11:45:00',
|
||||
'李承泽',
|
||||
),
|
||||
buildMockTask(
|
||||
'demo-c-3',
|
||||
'品牌联名活动舆情总结',
|
||||
'已完成用户态度分布统计与正负面声音对比,附带评论样本摘要和建议动作。',
|
||||
'completed',
|
||||
'task-search',
|
||||
2,
|
||||
100,
|
||||
'2026-06-02 16:50:00',
|
||||
'2026-06-03 19:12:00',
|
||||
'周清越',
|
||||
),
|
||||
],
|
||||
};
|
||||
|
||||
const paginateTasks = (tasks: TaskListItem[], pageIndex: number, pageSize: number) => {
|
||||
const start = (pageIndex - 1) * pageSize;
|
||||
return tasks.slice(start, start + pageSize);
|
||||
};
|
||||
/** 本页对应的业务码(3QFX = 3Q);用于查业务映射拿到要自动选用的业务链 / 单智能体。 */
|
||||
const BUSINESS_CODE = '3Q';
|
||||
|
||||
const SentimentAnalyzes: React.FC<TaskListPageProps> = ({ title, category, subCategory }) => {
|
||||
const { theme } = useTheme();
|
||||
const { setStartConfig } = useChatContext();
|
||||
const navigate = useNavigate();
|
||||
const isDark = theme === 'dark';
|
||||
const shellClass = isDark
|
||||
? 'strategy-data min-h-full bg-[radial-gradient(circle_at_top_left,rgba(27,94,168,0.28),transparent_32%),linear-gradient(180deg,#081322_0%,#0d1d33_42%,#0a1628_100%)] text-slate-100'
|
||||
: 'strategy-data min-h-full bg-[#f8fafc] text-slate-900';
|
||||
const metricCardClass = isDark
|
||||
? 'border border-[rgba(110,136,176,0.24)] bg-[linear-gradient(180deg,rgba(12,32,58,0.96),rgba(9,22,39,0.96))] shadow-[0_14px_42px_rgba(2,8,20,0.30)]'
|
||||
: 'border border-slate-200 bg-white shadow-sm';
|
||||
const inputClass = isDark
|
||||
? 'border-[rgba(110,136,176,0.3)] bg-[rgba(8,23,42,0.92)] text-slate-100 placeholder:text-slate-500'
|
||||
: 'border-slate-200 bg-white text-slate-900 placeholder:text-slate-400';
|
||||
const panelGlowClass = isDark
|
||||
? 'before:pointer-events-none before:absolute before:inset-x-8 before:top-0 before:h-px before:bg-[linear-gradient(90deg,transparent,rgba(96,165,250,0.45),transparent)]'
|
||||
: '';
|
||||
|
||||
const [searchQuery, setSearchQuery] = useState('');
|
||||
const [showAnalysisModal, setShowAnalysisModal] = useState(false);
|
||||
const [selectedTaskForAnalysis, setSelectedTaskForAnalysis] = useState<TaskListItem | null>(null);
|
||||
const [useDemoData, setUseDemoData] = useState(ENABLE_SENTIMENT_DEMO_BY_DEFAULT);
|
||||
const [selectedTask, setSelectedTask] = useState<TaskListItem | null>(null);
|
||||
const [unanalyzedTotal, setUnanalyzedTotal] = useState(0);
|
||||
const [runningTotal, setRunningTotal] = useState(0);
|
||||
const [completedTotal, setCompletedTotal] = useState(0);
|
||||
@@ -207,378 +46,399 @@ const SentimentAnalyzes: React.FC<TaskListPageProps> = ({ title, category, subCa
|
||||
const [unanalyzedLoading, setUnanalyzedLoading] = useState(false);
|
||||
const [runningLoading, setRunningLoading] = useState(false);
|
||||
const [completedLoading, setCompletedLoading] = useState(false);
|
||||
const [dateRange, setDateRange] = useState<DateRangeValue>([
|
||||
dayjs().startOf('month').format('YYYY-MM-DD'),
|
||||
dayjs().endOf('day').format('YYYY-MM-DD'),
|
||||
]);
|
||||
const [range, setRange] = useState<DateRangeValue>([]);
|
||||
|
||||
const pageSizeRef = useRef(10);
|
||||
const stateRef = useRef<StateItem>({
|
||||
startTime: '',
|
||||
endTime: '',
|
||||
task: null,
|
||||
});
|
||||
|
||||
const filteredMock = useMemo(() => {
|
||||
const keyword = searchQuery.trim().toLowerCase();
|
||||
const filterItems = (items: TaskListItem[]) => {
|
||||
if (!keyword) return items;
|
||||
return items.filter((item) => {
|
||||
const text = `${item.taskName} ${item.overview} ${item.owner || ''}`.toLowerCase();
|
||||
return text.includes(keyword);
|
||||
});
|
||||
};
|
||||
const presets = useMemo<DateRangePickerProps['presets']>(
|
||||
() => ({
|
||||
最近7天: [dayjs().subtract(6, 'day').toDate(), dayjs().toDate()],
|
||||
最近3天: [dayjs().subtract(2, 'day').toDate(), dayjs().toDate()],
|
||||
今天: [dayjs().toDate(), dayjs().toDate()],
|
||||
}),
|
||||
[],
|
||||
);
|
||||
|
||||
return {
|
||||
unanalyzed: filterItems(MOCK_TASKS.unanalyzed),
|
||||
analyzing: filterItems(MOCK_TASKS.analyzing),
|
||||
completed: filterItems(MOCK_TASKS.completed),
|
||||
};
|
||||
}, [searchQuery]);
|
||||
const taskStatusMap: Record<ColumnType, number[]> = {
|
||||
unanalyzed: [0, 10],
|
||||
running: [20],
|
||||
completed: [25, 30, 40, 60, 70, 80, 90, 100, 110],
|
||||
};
|
||||
|
||||
const applyMockColumn = (column: ColumnType, pageIndex = 1) => {
|
||||
const source = filteredMock[column];
|
||||
const pageItems = paginateTasks(source, pageIndex, pageSizeRef.current);
|
||||
const setRangeChange = async (value: DateRangeValue) => {
|
||||
setRange(value);
|
||||
stateRef.current.startTime = '';
|
||||
stateRef.current.endTime = '';
|
||||
|
||||
if (column === 'unanalyzed') {
|
||||
setUnanalyzedTotal(source.length);
|
||||
setUnanalyzedList(pageItems);
|
||||
setUnanalyzedLoading(false);
|
||||
} else if (column === 'analyzing') {
|
||||
setRunningTotal(source.length);
|
||||
setRunningList(pageItems);
|
||||
setRunningLoading(false);
|
||||
} else {
|
||||
setCompletedTotal(source.length);
|
||||
setCompletedList(pageItems);
|
||||
setCompletedLoading(false);
|
||||
if (Array.isArray(value) && value.length > 1) {
|
||||
stateRef.current.startTime = String(value[0] || '');
|
||||
stateRef.current.endTime = String(value[1] || '');
|
||||
}
|
||||
|
||||
await taskDataChange();
|
||||
};
|
||||
|
||||
const taskListSearch = async (
|
||||
taskStatus: ColumnType,
|
||||
pageIndex = 1,
|
||||
pageSize = pageSizeRef.current,
|
||||
taskType: ColumnType,
|
||||
pageNum = 1,
|
||||
pageSize = 10,
|
||||
) => {
|
||||
pageSizeRef.current = pageSize;
|
||||
|
||||
const setLoadingByType = (loading: boolean) => {
|
||||
if (taskStatus === 'unanalyzed') setUnanalyzedLoading(loading);
|
||||
if (taskStatus === 'analyzing') setRunningLoading(loading);
|
||||
if (taskStatus === 'completed') setCompletedLoading(loading);
|
||||
};
|
||||
|
||||
setLoadingByType(true);
|
||||
|
||||
if (useDemoData) {
|
||||
applyMockColumn(taskStatus, pageIndex);
|
||||
return;
|
||||
}
|
||||
if (taskType === 'unanalyzed') setUnanalyzedLoading(true);
|
||||
if (taskType === 'running') setRunningLoading(true);
|
||||
if (taskType === 'completed') setCompletedLoading(true);
|
||||
|
||||
try {
|
||||
const [startTime, endTime] = Array.isArray(dateRange) ? dateRange : ['', ''];
|
||||
const payload = {
|
||||
pageNum: pageIndex,
|
||||
const response = await service.post(`${zncmUrl}/three/cop-three-tasks`, {
|
||||
content: searchQuery,
|
||||
pageNum,
|
||||
pageSize,
|
||||
taskStatus,
|
||||
taskCategoryName: category,
|
||||
taskTypeName: subCategory,
|
||||
searchKey: searchQuery.trim() || undefined,
|
||||
startTime,
|
||||
endTime,
|
||||
};
|
||||
taskStatus: taskStatusMap[taskType],
|
||||
startTime: stateRef.current.startTime,
|
||||
endTime: stateRef.current.endTime,
|
||||
taskDirection: '',
|
||||
});
|
||||
|
||||
const response = await service.post(`${zncmUrl}/three/cop-three-tasks`, payload);
|
||||
const rows = response?.rows || response?.data?.rows || [];
|
||||
const total = response?.total || response?.data?.total || 0;
|
||||
const mappedList = rows.map((item: TaskListItem) => ({
|
||||
const result = response?.data ?? {};
|
||||
const records = Array.isArray(result.records) ? result.records : [];
|
||||
const normalized = records.map((item: TaskListItem) => ({
|
||||
...item,
|
||||
column: taskStatus === 'analyzing' ? 'running' : taskStatus,
|
||||
column: taskType,
|
||||
taskLevel: item.taskLevel || 1,
|
||||
}));
|
||||
const total = Number(result.total ?? normalized.length);
|
||||
|
||||
if (taskStatus === 'unanalyzed') {
|
||||
setUnanalyzedList(mappedList);
|
||||
if (taskType === 'unanalyzed') {
|
||||
setUnanalyzedTotal(total);
|
||||
} else if (taskStatus === 'analyzing') {
|
||||
setRunningList(mappedList);
|
||||
setUnanalyzedList(normalized);
|
||||
} else if (taskType === 'running') {
|
||||
setRunningTotal(total);
|
||||
setRunningList(normalized);
|
||||
} else {
|
||||
setCompletedList(mappedList);
|
||||
setCompletedTotal(total);
|
||||
setCompletedList(normalized);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('sentiment task list fetch failed', error);
|
||||
applyMockColumn(taskStatus, pageIndex);
|
||||
setUseDemoData(true);
|
||||
} finally {
|
||||
setLoadingByType(false);
|
||||
if (taskType === 'unanalyzed') setUnanalyzedLoading(false);
|
||||
if (taskType === 'running') setRunningLoading(false);
|
||||
if (taskType === 'completed') setCompletedLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const refreshAllColumns = async () => {
|
||||
const pageIndexChange = async (type: string, pageIndex: number) => {
|
||||
await taskListSearch(type as ColumnType, pageIndex);
|
||||
};
|
||||
|
||||
const taskDataChange = async (pageNum = 1, pageSize = 10) => {
|
||||
await Promise.all([
|
||||
taskListSearch('unanalyzed', 1),
|
||||
taskListSearch('analyzing', 1),
|
||||
taskListSearch('completed', 1),
|
||||
taskListSearch('unanalyzed', pageNum, pageSize),
|
||||
taskListSearch('running', pageNum, pageSize),
|
||||
taskListSearch('completed', pageNum, pageSize),
|
||||
]);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
refreshAllColumns();
|
||||
}, [useDemoData]);
|
||||
|
||||
useEffect(() => {
|
||||
const timer = window.setTimeout(() => {
|
||||
refreshAllColumns();
|
||||
}, useDemoData ? 120 : 260);
|
||||
|
||||
return () => window.clearTimeout(timer);
|
||||
}, [searchQuery, dateRange, useDemoData]);
|
||||
|
||||
const metrics = [
|
||||
{
|
||||
label: '全部任务',
|
||||
value: unanalyzedTotal + runningTotal + completedTotal,
|
||||
icon: Layers,
|
||||
accent: 'from-[#4D8DFF] to-[#76C2FF]',
|
||||
},
|
||||
{
|
||||
label: '未分析',
|
||||
value: unanalyzedTotal,
|
||||
icon: Clock3,
|
||||
accent: 'from-[#38BDF8] to-[#7DD3FC]',
|
||||
},
|
||||
{
|
||||
label: '分析中',
|
||||
value: runningTotal,
|
||||
icon: Sparkles,
|
||||
accent: 'from-[#2DD4BF] to-[#67E8F9]',
|
||||
},
|
||||
{
|
||||
label: '已完成',
|
||||
value: completedTotal,
|
||||
icon: Bot,
|
||||
accent: 'from-[#60A5FA] to-[#A78BFA]',
|
||||
},
|
||||
];
|
||||
|
||||
const handleStartAnalysis = (task: TaskListItem) => {
|
||||
setSelectedTaskForAnalysis(task);
|
||||
setSelectedTask(task);
|
||||
stateRef.current.task = task;
|
||||
setShowAnalysisModal(true);
|
||||
};
|
||||
|
||||
const handleViewTaskDetail = () => {
|
||||
if (!selectedTaskForAnalysis) return;
|
||||
setStartConfig({
|
||||
task_title: selectedTaskForAnalysis.taskName,
|
||||
task_goal: selectedTaskForAnalysis.overview,
|
||||
task_context: selectedTaskForAnalysis.overview,
|
||||
llm_preset_id: 'BAILING',
|
||||
consistency_mode: 'soft',
|
||||
phase_config: { diverge_rounds: 3 },
|
||||
});
|
||||
const handleOpenTaskDetail = () => {
|
||||
if (!stateRef.current.task) return;
|
||||
window.open(`https://ch1.b.uat.4.cn/web/#/task/item-aicoh/step-info-search?id=${stateRef.current.task.id}`);
|
||||
setShowAnalysisModal(false);
|
||||
navigate('/qa-center/mope-chat');
|
||||
};
|
||||
|
||||
const handleMultiAgentDiscussion = () => {
|
||||
if (!selectedTaskForAnalysis) return;
|
||||
setStartConfig({
|
||||
task_title: selectedTaskForAnalysis.taskName,
|
||||
task_goal: selectedTaskForAnalysis.overview,
|
||||
task_context: selectedTaskForAnalysis.overview,
|
||||
llm_preset_id: 'BAILING',
|
||||
consistency_mode: 'soft',
|
||||
phase_config: { diverge_rounds: 3 },
|
||||
const handleOpenConsultation = () => {
|
||||
const task = stateRef.current.task;
|
||||
if (!task) return;
|
||||
// 会商自动化串联(模块 C):跳转圆桌规划页,带上任务名称/描述 + 本页业务码(3Q=三情分析)。
|
||||
// 圆桌据此自动开跑 Step 1,并在「进入研讨」时自动选用 3Q 配置的业务链(跳过选链弹窗)。
|
||||
navigate('/page/strategy/qa/multi-agent-roundtable', {
|
||||
state: {
|
||||
roundtablePrefill: {
|
||||
taskTitle: task.taskName,
|
||||
taskGoal: task.overview,
|
||||
businessCode: BUSINESS_CODE,
|
||||
autoStart: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
setShowAnalysisModal(false);
|
||||
navigate('/page/workspace/roundtable/planning');
|
||||
};
|
||||
|
||||
// 单智能体分析:用「业务链条管理」里为本业务配置的智能体,跳转到其问答页(新会话),
|
||||
// 把任务名称/简介作为开场消息暂存,由 AgentChatPage 读取 sessionStorage.pendingAgentMessage
|
||||
// 自动发出并开始问答。未配置智能体则提示去配置。
|
||||
const handleSingleAgentAnalysis = async () => {
|
||||
const task = stateRef.current.task;
|
||||
if (!task) return;
|
||||
let agentId: string | null = null;
|
||||
try {
|
||||
const mappings = await listBusinessMappings();
|
||||
agentId = mappings.find((m) => m.businessCode === BUSINESS_CODE)?.agentId ?? null;
|
||||
} catch {
|
||||
/* ignore → 下面按未配置处理 */
|
||||
}
|
||||
if (!agentId) {
|
||||
toast.error('该业务尚未在「业务链条管理」中配置单智能体');
|
||||
return;
|
||||
}
|
||||
const text = [
|
||||
task.taskName ? `任务名称:${task.taskName}` : '',
|
||||
task.overview ? `任务简介:${task.overview}` : '',
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join('\n');
|
||||
try {
|
||||
sessionStorage.setItem(
|
||||
'pendingAgentMessage',
|
||||
JSON.stringify({ agentId, text }),
|
||||
);
|
||||
} catch {
|
||||
/* noop */
|
||||
}
|
||||
navigate(`/page/strategy/agents/${agentId}/chats/new`);
|
||||
setShowAnalysisModal(false);
|
||||
};
|
||||
|
||||
const handleKeyDown = async (event: React.KeyboardEvent<HTMLInputElement>) => {
|
||||
if ((event.metaKey || event.ctrlKey || event.shiftKey) && event.key === 'Enter') {
|
||||
event.preventDefault();
|
||||
} else if (event.key === 'Enter') {
|
||||
event.preventDefault();
|
||||
await taskDataChange();
|
||||
} else if (event.key === '/') {
|
||||
event.preventDefault();
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
taskDataChange();
|
||||
}, []);
|
||||
|
||||
const shellClass = isDark
|
||||
? 'strategy-data h-full overflow-y-auto bg-[linear-gradient(180deg,#081322_0%,#0d1d33_42%,#0a1628_100%)]'
|
||||
: 'strategy-data h-full overflow-y-auto bg-[linear-gradient(180deg,#FFFDFD_0%,#FFF7F7_46%,#FAFAFA_100%)]';
|
||||
|
||||
const toolbarClass = isDark
|
||||
? 'border border-[rgba(67,89,124,0.46)] bg-[rgba(10,23,42,0.94)] text-white shadow-[0_16px_36px_rgba(3,10,22,0.2)]'
|
||||
: 'border border-[#E8E8E8] bg-white text-[#222222] shadow-[0_14px_30px_rgba(245,34,45,0.06)]';
|
||||
|
||||
const metricClass = isDark
|
||||
? 'border border-[rgba(67,89,124,0.46)] bg-[rgba(12,29,54,0.94)]'
|
||||
: 'border border-[#E8E8E8] bg-white';
|
||||
|
||||
const inputClass = isDark
|
||||
? 'border-[rgba(67,89,124,0.46)] bg-[rgba(8,19,35,0.9)] text-white placeholder:text-slate-500'
|
||||
: 'border-[#E8E8E8] bg-white text-[#222222] placeholder:text-[#A6A6A6]';
|
||||
|
||||
const metrics = [
|
||||
{ label: '全部任务', value: unanalyzedTotal + runningTotal + completedTotal },
|
||||
{ label: '未分析', value: unanalyzedTotal },
|
||||
{ label: '分析中', value: runningTotal },
|
||||
{ label: '已完成', value: completedTotal },
|
||||
];
|
||||
|
||||
return (
|
||||
<div className={shellClass}>
|
||||
<div className={`relative mx-auto flex h-full max-w-[1680px] flex-col gap-5 px-6 py-6 lg:px-8 ${panelGlowClass}`}>
|
||||
<div className="flex flex-col gap-4 xl:flex-row xl:items-end xl:justify-between">
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="flex h-11 w-11 items-center justify-center rounded-2xl border border-[rgba(96,165,250,0.28)] bg-[linear-gradient(180deg,rgba(22,119,255,0.28),rgba(14,63,135,0.18))] shadow-[0_10px_30px_rgba(14,63,135,0.24)]">
|
||||
<Bot className="h-5 w-5 text-[#7CC9FF]" />
|
||||
<div className="mx-auto flex min-h-full max-w-[1680px] flex-col gap-4 px-6 py-6 lg:px-8">
|
||||
<section className={`rounded-[28px] p-5 ${toolbarClass}`}>
|
||||
<div className="flex flex-col gap-4 xl:flex-row xl:items-start xl:justify-between">
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-center gap-2 text-xs">
|
||||
<span className={`rounded-full px-3 py-1 ${isDark ? 'bg-[rgba(77,141,255,0.16)] text-[#9CCBFF]' : 'bg-[#FFF1F0] text-[#CF1322]'}`}>
|
||||
{category}
|
||||
</span>
|
||||
<ArrowRight className={`h-3.5 w-3.5 ${isDark ? 'text-slate-500' : 'text-[#A6A6A6]'}`} />
|
||||
<span className={`rounded-full px-3 py-1 ${isDark ? 'bg-[rgba(34,197,94,0.14)] text-[#89E8B8]' : 'bg-[#FFF6E8] text-[#D46B08]'}`}>
|
||||
{subCategory}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<div className="flex items-center gap-2">
|
||||
<h1 className="text-[26px] font-semibold tracking-[0.02em] text-slate-50">{title}</h1>
|
||||
{useDemoData ? (
|
||||
<span className="rounded-full border border-[rgba(125,211,252,0.28)] bg-[rgba(56,189,248,0.14)] px-2.5 py-1 text-xs text-[#8EDCFF]">
|
||||
演示数据
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
<p className={`mt-1 text-sm ${isDark ? 'text-slate-300/80' : 'text-slate-500'}`}>
|
||||
<h1 className={`text-[28px] font-semibold ${isDark ? 'text-white' : 'text-[#222222]'}`}>{title}</h1>
|
||||
<p className={`mt-2 text-sm ${isDark ? 'text-slate-300' : 'text-[#575757]'}`}>
|
||||
面向规划任务的情绪与倾向分析看板,支持快速检索、会商启动与结果回看。
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className={`inline-flex items-center gap-2 rounded-full border px-3 py-1 text-xs ${isDark ? 'border-[rgba(110,136,176,0.28)] bg-[rgba(9,25,46,0.72)] text-slate-300' : 'border-slate-200 bg-white text-slate-600'}`}>
|
||||
<span>{category}</span>
|
||||
<ArrowRight className="h-3.5 w-3.5 opacity-70" />
|
||||
<span>{subCategory}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-3 xl:items-end">
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<label className={`flex h-11 min-w-[320px] items-center gap-3 rounded-2xl border px-4 ${inputClass}`}>
|
||||
<Search className="h-4 w-4 text-[#7CC9FF]" />
|
||||
<input
|
||||
value={searchQuery}
|
||||
onChange={(event) => setSearchQuery(event.target.value)}
|
||||
className="w-full bg-transparent text-sm outline-none"
|
||||
placeholder="搜索任务名称、摘要或负责人"
|
||||
<div className="flex flex-col gap-3 xl:items-end">
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<label className={`flex h-11 min-w-[320px] items-center gap-3 rounded-xl border px-4 ${inputClass}`}>
|
||||
<Search className={`h-4 w-4 ${isDark ? 'text-slate-400' : 'text-[#A6A6A6]'}`} />
|
||||
<input
|
||||
value={searchQuery}
|
||||
onChange={(event) => setSearchQuery(event.target.value)}
|
||||
onKeyDown={handleKeyDown}
|
||||
className="w-full bg-transparent text-sm outline-none"
|
||||
placeholder="搜索任务名称"
|
||||
/>
|
||||
</label>
|
||||
<DateRangePicker
|
||||
className="sentiment-date-range"
|
||||
value={range}
|
||||
presets={presets}
|
||||
onChange={setRangeChange}
|
||||
enableTimePicker
|
||||
clearable
|
||||
popupProps={{ overlayClassName: 'sentiment-date-range-popup' }}
|
||||
/>
|
||||
</label>
|
||||
<DateRangePicker
|
||||
className="sentiment-date-range"
|
||||
value={dateRange}
|
||||
enableTimePicker={false}
|
||||
clearable={false}
|
||||
popupProps={{ overlayClassName: 'sentiment-date-range-popup' }}
|
||||
rangeInputProps={{
|
||||
inputProps: [
|
||||
{ inputClass: 'sentiment-date-range-input' },
|
||||
{ inputClass: 'sentiment-date-range-input' },
|
||||
],
|
||||
}}
|
||||
onChange={(value) => setDateRange(value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setUseDemoData(true)}
|
||||
className={`rounded-xl px-4 py-2 text-sm transition ${useDemoData ? 'bg-[#1677FF] text-white shadow-[0_8px_22px_rgba(22,119,255,0.28)]' : isDark ? 'bg-[rgba(10,30,54,0.9)] text-slate-300 hover:bg-[rgba(13,42,78,0.95)]' : 'bg-white text-slate-700 hover:bg-slate-50'}`}
|
||||
className={`inline-flex items-center gap-2 rounded-xl px-4 py-2 text-sm ${isDark ? 'bg-[rgba(77,141,255,0.16)] text-[#9CCBFF]' : 'bg-[#FFF1F0] text-[#CF1322]'}`}
|
||||
>
|
||||
演示数据
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setUseDemoData(false)}
|
||||
className={`rounded-xl px-4 py-2 text-sm transition ${!useDemoData ? 'bg-[#0EA5E9] text-white shadow-[0_8px_22px_rgba(14,165,233,0.24)]' : isDark ? 'bg-[rgba(10,30,54,0.9)] text-slate-300 hover:bg-[rgba(13,42,78,0.95)]' : 'bg-white text-slate-700 hover:bg-slate-50'}`}
|
||||
>
|
||||
真实数据
|
||||
<Plus className="h-4 w-4" />
|
||||
新建任务
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<div className="grid grid-cols-1 gap-4 md:grid-cols-2 xl:grid-cols-4">
|
||||
{metrics.map(({ label, value, icon: Icon, accent }) => (
|
||||
<div key={label} className={`rounded-3xl p-5 ${metricCardClass}`}>
|
||||
<section className="grid grid-cols-1 gap-4 md:grid-cols-2 xl:grid-cols-4">
|
||||
{metrics.map((item, index) => (
|
||||
<div key={item.label} className={`rounded-[24px] p-5 ${metricClass}`}>
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<p className={`text-sm ${isDark ? 'text-slate-300/78' : 'text-slate-500'}`}>{label}</p>
|
||||
<p className="mt-3 text-3xl font-semibold tracking-[0.03em] text-white">{value}</p>
|
||||
<p className={`text-sm ${isDark ? 'text-slate-400' : 'text-[#8C8C8C]'}`}>{item.label}</p>
|
||||
<p className={`mt-3 text-[36px] font-semibold ${isDark ? 'text-white' : index === 0 ? 'text-[#222222]' : 'text-[#F5222D]'}`}>
|
||||
{item.value}
|
||||
</p>
|
||||
</div>
|
||||
<div className={`flex h-12 w-12 items-center justify-center rounded-2xl bg-gradient-to-br ${accent} shadow-[inset_0_1px_0_rgba(255,255,255,0.18)]`}>
|
||||
<Icon className="h-5 w-5 text-white" />
|
||||
<div className={`flex h-12 w-12 items-center justify-center rounded-2xl ${isDark ? 'bg-[rgba(77,141,255,0.18)] text-[#9CCBFF]' : 'bg-[#FFF1F0] text-[#CF1322]'}`}>
|
||||
<Layers className="h-5 w-5" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<div className="grid min-h-0 flex-1 grid-cols-1 gap-4 xl:grid-cols-3">
|
||||
<div className="min-h-[420px]">
|
||||
<Loading loading={unanalyzedLoading} showOverlay={false}>
|
||||
<KanbanColumn
|
||||
title="未分析"
|
||||
count={unanalyzedTotal}
|
||||
color="bg-[#38BDF8]"
|
||||
tasks={unanalyzedList}
|
||||
taskType="unanalyzed"
|
||||
TaskDataType="sentiment"
|
||||
pageIndexSearch={(taskType, pageIndex) => taskListSearch(taskType as ColumnType, pageIndex)}
|
||||
handleStartAnalysis={handleStartAnalysis}
|
||||
/>
|
||||
<section className="grid grid-cols-1 items-stretch gap-4 xl:grid-cols-3">
|
||||
<div className="h-full">
|
||||
<Loading className="block h-full" loading={unanalyzedLoading} showOverlay={false}>
|
||||
<div className="h-full">
|
||||
<KanbanColumn
|
||||
title="未分析"
|
||||
count={unanalyzedTotal}
|
||||
color={isDark ? 'bg-[#7CC9FF]' : 'bg-[#F5222D]'}
|
||||
tasks={unanalyzedList}
|
||||
taskType="unanalyzed"
|
||||
taskDataType="sentiment"
|
||||
pageIndexSearch={pageIndexChange}
|
||||
handleStartAnalysis={handleStartAnalysis}
|
||||
/>
|
||||
</div>
|
||||
</Loading>
|
||||
</div>
|
||||
<div className="min-h-[420px]">
|
||||
<Loading loading={runningLoading} showOverlay={false}>
|
||||
<KanbanColumn
|
||||
title="分析中"
|
||||
count={runningTotal}
|
||||
color="bg-[#2DD4BF]"
|
||||
tasks={runningList}
|
||||
taskType="analyzing"
|
||||
TaskDataType="sentiment"
|
||||
pageIndexSearch={(taskType, pageIndex) => taskListSearch(taskType as ColumnType, pageIndex)}
|
||||
handleStartAnalysis={handleStartAnalysis}
|
||||
/>
|
||||
|
||||
<div className="h-full">
|
||||
<Loading className="block h-full" loading={runningLoading} showOverlay={false}>
|
||||
<div className="h-full">
|
||||
<KanbanColumn
|
||||
title="分析中"
|
||||
count={runningTotal}
|
||||
color={isDark ? 'bg-[#5EEAD4]' : 'bg-[#1677FF]'}
|
||||
tasks={runningList}
|
||||
taskType="running"
|
||||
taskDataType="sentiment"
|
||||
pageIndexSearch={pageIndexChange}
|
||||
handleStartAnalysis={handleStartAnalysis}
|
||||
/>
|
||||
</div>
|
||||
</Loading>
|
||||
</div>
|
||||
<div className="min-h-[420px]">
|
||||
<Loading loading={completedLoading} showOverlay={false}>
|
||||
<KanbanColumn
|
||||
title="已完成"
|
||||
count={completedTotal}
|
||||
color="bg-[#60A5FA]"
|
||||
tasks={completedList}
|
||||
taskType="completed"
|
||||
TaskDataType="sentiment"
|
||||
pageIndexSearch={(taskType, pageIndex) => taskListSearch(taskType as ColumnType, pageIndex)}
|
||||
handleStartAnalysis={handleStartAnalysis}
|
||||
/>
|
||||
|
||||
<div className="h-full">
|
||||
<Loading className="block h-full" loading={completedLoading} showOverlay={false}>
|
||||
<div className="h-full">
|
||||
<KanbanColumn
|
||||
title="已完成"
|
||||
count={completedTotal}
|
||||
color={isDark ? 'bg-[#67E8A5]' : 'bg-[#52C41A]'}
|
||||
tasks={completedList}
|
||||
taskType="completed"
|
||||
taskDataType="sentiment"
|
||||
pageIndexSearch={pageIndexChange}
|
||||
handleStartAnalysis={handleStartAnalysis}
|
||||
/>
|
||||
</div>
|
||||
</Loading>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
{showAnalysisModal && selectedTaskForAnalysis ? (
|
||||
<div className="fixed inset-0 z-[2000] flex items-center justify-center bg-[rgba(3,10,22,0.62)] px-4 backdrop-blur-sm">
|
||||
<div className={`w-full max-w-[560px] rounded-[28px] border p-6 ${isDark ? 'border-[rgba(110,136,176,0.26)] bg-[linear-gradient(180deg,rgba(10,29,54,0.98),rgba(8,20,37,0.98))] text-slate-100 shadow-[0_28px_80px_rgba(2,8,20,0.42)]' : 'border-slate-200 bg-white text-slate-900 shadow-xl'}`}>
|
||||
{showAnalysisModal && selectedTask ? (
|
||||
<div className="fixed inset-0 z-[2000] flex items-center justify-center bg-black/45 px-4">
|
||||
<div className={`w-full max-w-[560px] rounded-[28px] border p-6 ${isDark ? 'border-[rgba(67,89,124,0.46)] bg-[rgba(10,23,42,0.98)] text-white' : 'border-[#E8E8E8] bg-white text-[#222222] shadow-[0_18px_36px_rgba(0,0,0,0.12)]'}`}>
|
||||
<div className="flex items-start justify-between gap-4">
|
||||
<div>
|
||||
<h3 className="text-xl font-semibold">选择分析模式</h3>
|
||||
<p className={`mt-2 text-sm ${isDark ? 'text-slate-300/78' : 'text-slate-500'}`}>
|
||||
当前任务:{selectedTaskForAnalysis.taskName}
|
||||
<p className={`mt-2 text-sm ${isDark ? 'text-slate-300' : 'text-[#575757]'}`}>
|
||||
为任务“{selectedTask.taskName}”选择分析方式
|
||||
</p>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowAnalysisModal(false)}
|
||||
className={`rounded-xl p-2 transition ${isDark ? 'hover:bg-[rgba(15,41,74,0.88)]' : 'hover:bg-slate-100'}`}
|
||||
className={`rounded-xl p-2 ${isDark ? 'hover:bg-[rgba(21,42,72,0.9)]' : 'hover:bg-[#FFF1F0]'}`}
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="mt-6 grid gap-3">
|
||||
<div className="mt-6 space-y-3">
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleViewTaskDetail}
|
||||
className={`group flex items-center justify-between rounded-2xl border px-5 py-4 text-left transition ${isDark ? 'border-[rgba(110,136,176,0.24)] bg-[rgba(10,30,54,0.9)] hover:border-[rgba(96,165,250,0.48)] hover:bg-[rgba(12,38,69,0.96)]' : 'border-slate-200 bg-slate-50 hover:border-sky-200 hover:bg-sky-50'}`}
|
||||
onClick={handleOpenTaskDetail}
|
||||
className={`flex w-full items-center justify-between rounded-[22px] border px-5 py-4 text-left transition ${isDark ? 'border-[rgba(67,89,124,0.46)] bg-[rgba(15,33,60,0.92)] hover:border-[rgba(110,168,255,0.46)]' : 'border-[#E8E8E8] bg-[#FFF9F9] hover:border-[#F6B0B4]'}`}
|
||||
>
|
||||
<div className="flex items-center gap-4">
|
||||
<div className="flex h-11 w-11 items-center justify-center rounded-2xl bg-[linear-gradient(180deg,#1677FF,#0EA5E9)]">
|
||||
<Layers className="h-5 w-5 text-white" />
|
||||
</div>
|
||||
<div>
|
||||
<div className="font-medium">查看任务详情</div>
|
||||
<div className={`mt-1 text-sm ${isDark ? 'text-slate-300/72' : 'text-slate-500'}`}>进入单任务分析视图,查看步骤、结论和上下文信息。</div>
|
||||
<div>
|
||||
<div className="font-medium">查看任务详情</div>
|
||||
<div className={`mt-1 text-sm ${isDark ? 'text-slate-300' : 'text-[#575757]'}`}>
|
||||
进入 B1 系统查看任务详情。
|
||||
</div>
|
||||
</div>
|
||||
<ArrowRight className="h-4 w-4 opacity-70 transition group-hover:translate-x-0.5" />
|
||||
<ArrowRight className="h-4 w-4 opacity-70" />
|
||||
</button>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleMultiAgentDiscussion}
|
||||
className={`group flex items-center justify-between rounded-2xl border px-5 py-4 text-left transition ${isDark ? 'border-[rgba(110,136,176,0.24)] bg-[rgba(10,30,54,0.9)] hover:border-[rgba(45,212,191,0.48)] hover:bg-[rgba(10,42,58,0.96)]' : 'border-slate-200 bg-slate-50 hover:border-emerald-200 hover:bg-emerald-50'}`}
|
||||
onClick={handleOpenConsultation}
|
||||
className={`flex w-full items-center justify-between rounded-[22px] border px-5 py-4 text-left transition ${isDark ? 'border-[rgba(67,89,124,0.46)] bg-[rgba(15,33,60,0.92)] hover:border-[rgba(103,232,165,0.42)]' : 'border-[#E8E8E8] bg-[#FFF9F9] hover:border-[#F6B0B4]'}`}
|
||||
>
|
||||
<div className="flex items-center gap-4">
|
||||
<div className="flex h-11 w-11 items-center justify-center rounded-2xl bg-[linear-gradient(180deg,#14B8A6,#22C55E)]">
|
||||
<Users className="h-5 w-5 text-white" />
|
||||
</div>
|
||||
<div className="flex items-start gap-3">
|
||||
<Users className={`mt-0.5 h-5 w-5 ${isDark ? 'text-[#89E8B8]' : 'text-[#CF1322]'}`} />
|
||||
<div>
|
||||
<div className="font-medium">多智能体会商</div>
|
||||
<div className={`mt-1 text-sm ${isDark ? 'text-slate-300/72' : 'text-slate-500'}`}>启动会商模式,由多个智能体并行分析情绪走势与影响因素。</div>
|
||||
<div className={`mt-1 text-sm ${isDark ? 'text-slate-300' : 'text-[#575757]'}`}>
|
||||
多个 AI 智能体从不同视角开展讨论并形成共识。
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<ArrowRight className="h-4 w-4 opacity-70 transition group-hover:translate-x-0.5" />
|
||||
<ArrowRight className="h-4 w-4 opacity-70" />
|
||||
</button>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleSingleAgentAnalysis}
|
||||
className={`flex w-full items-center justify-between rounded-[22px] border px-5 py-4 text-left transition ${isDark ? 'border-[rgba(67,89,124,0.46)] bg-[rgba(15,33,60,0.92)] hover:border-[rgba(167,139,250,0.46)]' : 'border-[#E8E8E8] bg-[#FFF9F9] hover:border-[#F6B0B4]'}`}
|
||||
>
|
||||
<div className="flex items-start gap-3">
|
||||
<Bot className={`mt-0.5 h-5 w-5 ${isDark ? 'text-[#C4B5FD]' : 'text-[#7C3AED]'}`} />
|
||||
<div>
|
||||
<div className="font-medium">单智能体分析</div>
|
||||
<div className={`mt-1 text-sm ${isDark ? 'text-slate-300' : 'text-[#575757]'}`}>
|
||||
由单个 AI 智能体直接对该任务进行分析问答。
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<ArrowRight className="h-4 w-4 opacity-70" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
+380
-555
File diff suppressed because it is too large.
Load diff
@@ -1,20 +1,54 @@
|
||||
import React from 'react';
|
||||
import { format } from 'date-fns';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { Bot, Eye, Layers, Play, User, Users, Workflow } from 'lucide-react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useTheme } from '@/contexts/ThemeContext';
|
||||
import { useChatContext } from '@/contexts/ChatContext';
|
||||
import { TaskListItem } from './TaskManagement';
|
||||
|
||||
interface TaskCardProps {
|
||||
TaskType?: string;
|
||||
task: TaskListItem;
|
||||
taskDataType?: string;
|
||||
handleStartAnalysis: (task: TaskListItem) => void;
|
||||
}
|
||||
|
||||
const getTaskTypeConfig = (taskType?: number) => {
|
||||
switch (taskType) {
|
||||
case 2:
|
||||
return { label: '场景', icon: Workflow };
|
||||
case 3:
|
||||
return { label: '会商', icon: Users };
|
||||
case 4:
|
||||
return { label: '多智能体', icon: Layers };
|
||||
case 5:
|
||||
return { label: '检索', icon: Layers };
|
||||
case 1:
|
||||
default:
|
||||
return { label: '单任务', icon: Bot };
|
||||
}
|
||||
};
|
||||
|
||||
const getTaskLevelLabel = (taskLevel?: number) => {
|
||||
switch (taskLevel) {
|
||||
case 2:
|
||||
return '紧急';
|
||||
case 3:
|
||||
return '加急';
|
||||
case 1:
|
||||
default:
|
||||
return '一般';
|
||||
}
|
||||
};
|
||||
|
||||
const getColumnLabel = (column?: string) => {
|
||||
if (column === 'running' || column === 'analyzing') return '分析中';
|
||||
if (column === 'completed') return '已完成';
|
||||
return '待分析';
|
||||
};
|
||||
|
||||
export const TaskCard: React.FC<TaskCardProps> = ({
|
||||
task,
|
||||
TaskType = 'task',
|
||||
taskDataType = 'task',
|
||||
handleStartAnalysis,
|
||||
}) => {
|
||||
const { theme } = useTheme();
|
||||
@@ -22,209 +56,159 @@ export const TaskCard: React.FC<TaskCardProps> = ({
|
||||
const navigate = useNavigate();
|
||||
const isDark = theme === 'dark';
|
||||
|
||||
const sceneDataChange = (currentTask: TaskListItem) => {
|
||||
if (!currentTask.scene) return;
|
||||
const typeConfig = getTaskTypeConfig(task.taskType);
|
||||
const TypeIcon = typeConfig.icon;
|
||||
const isCompleted = task.column === 'completed';
|
||||
const isRunning = task.column === 'running' || task.column === 'analyzing';
|
||||
|
||||
const openConversation = () => {
|
||||
try {
|
||||
const sceneItem = task.scene ? JSON.parse(task.scene) : {};
|
||||
const taskJson = sceneItem?.taskJson ? JSON.parse(sceneItem.taskJson) : {};
|
||||
|
||||
const sceneItem = JSON.parse(currentTask.scene);
|
||||
if (sceneItem.taskJson) {
|
||||
sceneItem.taskJson = JSON.parse(sceneItem.taskJson);
|
||||
setStartConfig({
|
||||
...sceneItem.taskJson,
|
||||
...taskJson,
|
||||
task_title: task.taskName,
|
||||
task_goal: task.overview,
|
||||
task_context: task.overview,
|
||||
llm_preset_id: 'BAILING',
|
||||
consistency_mode: 'soft',
|
||||
phase_config: { diverge_rounds: 3 },
|
||||
});
|
||||
} catch (error) {
|
||||
setStartConfig({
|
||||
task_title: task.taskName,
|
||||
task_goal: task.overview,
|
||||
task_context: task.overview,
|
||||
llm_preset_id: 'BAILING',
|
||||
consistency_mode: 'soft',
|
||||
phase_config: { diverge_rounds: 3 },
|
||||
task_context: currentTask.overview,
|
||||
});
|
||||
navigate('/qa-center/mope-chat');
|
||||
}
|
||||
|
||||
navigate('/qa-center/mope-chat');
|
||||
};
|
||||
|
||||
const handleTaskClick = (currentTask: TaskListItem) => {
|
||||
if (TaskType === 'sentiment') {
|
||||
sceneDataChange(currentTask);
|
||||
const handleCardClick = () => {
|
||||
if (taskDataType === 'sentiment') {
|
||||
openConversation();
|
||||
return;
|
||||
}
|
||||
|
||||
if (currentTask.column === 'completed') {
|
||||
if (isCompleted) {
|
||||
navigate('/strategy-result');
|
||||
return;
|
||||
}
|
||||
|
||||
if (currentTask.column === 'running' || currentTask.column === 'analyzing') {
|
||||
sceneDataChange(currentTask);
|
||||
if (isRunning) {
|
||||
openConversation();
|
||||
}
|
||||
};
|
||||
|
||||
const handleStartChange = (currentTask: TaskListItem) => {
|
||||
handleStartAnalysis(currentTask);
|
||||
};
|
||||
const handleActionClick = (event: React.MouseEvent<HTMLButtonElement>) => {
|
||||
event.stopPropagation();
|
||||
|
||||
const getTypeConfig = (type: string) => {
|
||||
const common = isDark ? 'border border-white/10 text-slate-200' : 'border border-slate-200 text-slate-700';
|
||||
switch (type) {
|
||||
case 'single':
|
||||
return {
|
||||
label: '单任务',
|
||||
icon: Layers,
|
||||
className: `${common} ${isDark ? 'bg-[rgba(22,119,255,0.14)]' : 'bg-sky-50'}`,
|
||||
};
|
||||
case 'consultation':
|
||||
return {
|
||||
label: '会商',
|
||||
icon: Users,
|
||||
className: `${common} ${isDark ? 'bg-[rgba(20,184,166,0.14)]' : 'bg-emerald-50'}`,
|
||||
};
|
||||
case 'scene':
|
||||
return {
|
||||
label: '场景',
|
||||
icon: Workflow,
|
||||
className: `${common} ${isDark ? 'bg-[rgba(168,85,247,0.14)]' : 'bg-violet-50'}`,
|
||||
};
|
||||
case 'multi-agent':
|
||||
return {
|
||||
label: '多智能体',
|
||||
icon: Bot,
|
||||
className: `${common} ${isDark ? 'bg-[rgba(99,102,241,0.16)]' : 'bg-indigo-50'}`,
|
||||
};
|
||||
default:
|
||||
return {
|
||||
label: '检索',
|
||||
icon: Layers,
|
||||
className: `${common} ${isDark ? 'bg-[rgba(59,130,246,0.12)]' : 'bg-slate-100'}`,
|
||||
};
|
||||
if (isCompleted) {
|
||||
handleCardClick();
|
||||
return;
|
||||
}
|
||||
|
||||
handleStartAnalysis(task);
|
||||
};
|
||||
|
||||
const getLevel = (priority: number = 1) => {
|
||||
if (priority >= 3) return '加急';
|
||||
if (priority === 2) return '紧急';
|
||||
return '一般';
|
||||
};
|
||||
const panelClass = isDark
|
||||
? 'border border-[rgba(67,89,124,0.46)] bg-[rgba(19,39,72,0.9)] shadow-[0_14px_34px_rgba(3,10,22,0.2)] hover:border-[rgba(110,168,255,0.52)]'
|
||||
: 'border border-[#E8E8E8] bg-white shadow-[0_10px_24px_rgba(245,34,45,0.06)] hover:border-[#F6B0B4] hover:shadow-[0_16px_32px_rgba(245,34,45,0.12)]';
|
||||
|
||||
const getStatusConfig = (column: string) => {
|
||||
switch (column) {
|
||||
case 'completed':
|
||||
return {
|
||||
label: '已完成',
|
||||
className: isDark
|
||||
? 'bg-[rgba(34,197,94,0.16)] text-emerald-300 border border-emerald-400/20'
|
||||
: 'bg-emerald-50 text-emerald-600 border border-emerald-100',
|
||||
};
|
||||
case 'running':
|
||||
case 'analyzing':
|
||||
return {
|
||||
label: '分析中',
|
||||
className: isDark
|
||||
? 'bg-[rgba(14,165,233,0.16)] text-sky-300 border border-sky-400/20'
|
||||
: 'bg-sky-50 text-sky-600 border border-sky-100',
|
||||
};
|
||||
default:
|
||||
return {
|
||||
label: '待分析',
|
||||
className: isDark
|
||||
? 'bg-[rgba(96,165,250,0.14)] text-blue-200 border border-blue-300/15'
|
||||
: 'bg-blue-50 text-blue-600 border border-blue-100',
|
||||
};
|
||||
}
|
||||
};
|
||||
const typeBadgeClass = isDark
|
||||
? 'bg-[rgba(77,141,255,0.14)] text-[#A9D2FF] border border-[rgba(108,161,255,0.24)]'
|
||||
: 'bg-[#FFF1F0] text-[#CF1322] border border-[#FFD6D6]';
|
||||
|
||||
const typeConfig = getTypeConfig(task.type || 'single');
|
||||
const statusConfig = getStatusConfig(task.column || 'unanalyzed');
|
||||
const TypeIcon = typeConfig.icon;
|
||||
const progressValue = Math.max(0, Math.min(task.progress || 0, 100));
|
||||
const levelClass = isDark
|
||||
? 'text-slate-400'
|
||||
: 'text-[#8C8C8C]';
|
||||
|
||||
const statusClass =
|
||||
task.column === 'completed'
|
||||
? isDark
|
||||
? 'bg-[rgba(18,184,134,0.16)] text-[#59E2B1] border border-[rgba(89,226,177,0.2)]'
|
||||
: 'bg-[#EEFCF7] text-[#0F9D6C] border border-[#B7F0D5]'
|
||||
: task.column === 'running' || task.column === 'analyzing'
|
||||
? isDark
|
||||
? 'bg-[rgba(34,197,94,0.12)] text-[#67E8A5] border border-[rgba(103,232,165,0.2)]'
|
||||
: 'bg-[#EAF4FF] text-[#1677FF] border border-[#CDE2FF]'
|
||||
: isDark
|
||||
? 'bg-[rgba(96,165,250,0.12)] text-[#8FD1FF] border border-[rgba(143,209,255,0.2)]'
|
||||
: 'bg-[#FFF1F0] text-[#F5222D] border border-[#FFD6D6]';
|
||||
|
||||
const actionClass = isCompleted
|
||||
? isDark
|
||||
? 'bg-[rgba(12,48,82,0.95)] text-white hover:bg-[rgba(15,60,104,0.98)]'
|
||||
: 'bg-[#FFF1F0] text-[#CF1322] hover:bg-[#FFE4E6]'
|
||||
: isDark
|
||||
? 'bg-[linear-gradient(90deg,#1677FF,#22A8F0)] text-white hover:brightness-110'
|
||||
: 'bg-[linear-gradient(90deg,#F5222D,#FF6B73)] text-white hover:brightness-105';
|
||||
|
||||
return (
|
||||
<div
|
||||
className={`theme-card theme-card-hover theme-transition rounded-[24px] border p-4 ${
|
||||
isDark
|
||||
? 'border-[rgba(110,136,176,0.2)] shadow-[0_12px_30px_rgba(2,8,20,0.20)]'
|
||||
: 'border-slate-200 bg-white shadow-sm'
|
||||
}`}
|
||||
<article
|
||||
className={`group rounded-[24px] p-4 transition-all duration-200 ${panelClass}`}
|
||||
onClick={handleCardClick}
|
||||
>
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<div className={`inline-flex items-center gap-2 rounded-full px-3 py-1 text-xs ${typeConfig.className}`}>
|
||||
<span
|
||||
className={`inline-flex items-center gap-1.5 rounded-full px-3 py-1 text-xs font-medium ${typeBadgeClass}`}
|
||||
>
|
||||
<TypeIcon className="h-3.5 w-3.5" />
|
||||
<span>{typeConfig.label}</span>
|
||||
</div>
|
||||
<span className={`inline-flex items-center rounded-full px-2.5 py-1 text-xs ${statusConfig.className}`}>
|
||||
{statusConfig.label}
|
||||
{typeConfig.label}
|
||||
</span>
|
||||
<span
|
||||
className={`inline-flex items-center rounded-full px-3 py-1 text-xs font-medium ${statusClass}`}
|
||||
>
|
||||
{getColumnLabel(task.column)}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<h3
|
||||
className={`mt-5 text-[16px] font-semibold leading-7 ${
|
||||
isDark ? 'text-white' : 'text-[#222222]'
|
||||
}`}
|
||||
>
|
||||
{task.taskName}
|
||||
</h3>
|
||||
|
||||
<p
|
||||
className={`mt-3 min-h-[56px] text-sm leading-7 ${
|
||||
isDark ? 'text-slate-300' : 'text-[#575757]'
|
||||
}`}
|
||||
>
|
||||
{task.overview || '暂无任务摘要'}
|
||||
</p>
|
||||
|
||||
<div className="mt-4 flex items-center justify-between gap-3 text-sm">
|
||||
<div className={`flex items-center gap-2 ${isDark ? 'text-slate-300' : 'text-[#575757]'}`}>
|
||||
<User className="h-4 w-4" />
|
||||
<span>{task.taskDirection || '未分配'}</span>
|
||||
</div>
|
||||
<div className={levelClass}>优先级:{getTaskLevelLabel(task.taskLevel)}</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
className={`mt-4 grid grid-cols-2 gap-3 text-xs ${
|
||||
isDark ? 'text-slate-400' : 'text-[#8C8C8C]'
|
||||
}`}
|
||||
>
|
||||
<div>创建于 {format(new Date(task.createTime), 'MM-dd HH:mm')}</div>
|
||||
<div className="text-right">更新于 {format(new Date(task.updateTime), 'MM-dd HH:mm')}</div>
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleTaskClick(task)}
|
||||
className="mt-4 block w-full text-left"
|
||||
onClick={handleActionClick}
|
||||
className={`mt-5 flex h-12 w-full items-center justify-center gap-2 rounded-full text-sm font-medium transition ${actionClass}`}
|
||||
>
|
||||
<div className={`line-clamp-2 text-[15px] font-semibold leading-6 ${isDark ? 'text-slate-50' : 'text-slate-900'}`}>
|
||||
{task.taskName}
|
||||
</div>
|
||||
<p className={`mt-2 line-clamp-3 text-sm leading-6 ${isDark ? 'text-slate-300/78' : 'text-slate-500'}`}>
|
||||
{task.overview || '暂无任务摘要'}
|
||||
</p>
|
||||
{isCompleted ? <Eye className="h-4 w-4" /> : <Play className="h-4 w-4" />}
|
||||
{isCompleted ? '查看结果' : '开始分析'}
|
||||
</button>
|
||||
|
||||
<div className="mt-4 space-y-3">
|
||||
<div className="flex items-center justify-between text-xs">
|
||||
<div className={`flex items-center gap-1.5 ${isDark ? 'text-slate-400' : 'text-slate-500'}`}>
|
||||
<User className="h-3.5 w-3.5" />
|
||||
<span>{task.owner || task.creator || '未分配'}</span>
|
||||
</div>
|
||||
<div className={`${isDark ? 'text-slate-500' : 'text-slate-400'}`}>优先级:{getLevel(task.priority)}</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<div className="mb-1.5 flex items-center justify-between text-xs">
|
||||
<span className={isDark ? 'text-slate-400' : 'text-slate-500'}>分析进度</span>
|
||||
<span className={isDark ? 'text-slate-300' : 'text-slate-700'}>{progressValue}%</span>
|
||||
</div>
|
||||
<div className={`h-2 overflow-hidden rounded-full ${isDark ? 'bg-[rgba(255,255,255,0.08)]' : 'bg-slate-100'}`}>
|
||||
<div
|
||||
className="h-full rounded-full bg-[linear-gradient(90deg,#1677FF,#5EEAD4)]"
|
||||
style={{ width: `${progressValue}%` }}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between text-xs">
|
||||
<span className={isDark ? 'text-slate-500' : 'text-slate-400'}>
|
||||
创建于 {task.createTime ? format(new Date(task.createTime), 'MM-dd HH:mm') : '--'}
|
||||
</span>
|
||||
<span className={isDark ? 'text-slate-500' : 'text-slate-400'}>
|
||||
更新于 {task.updateTime ? format(new Date(task.updateTime), 'MM-dd HH:mm') : '--'}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mt-4 flex gap-2">
|
||||
{task.column === 'completed' ? (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleTaskClick(task)}
|
||||
className={`flex-1 rounded-xl px-3 py-2 text-sm transition ${
|
||||
isDark
|
||||
? 'bg-[rgba(11,40,71,0.95)] text-slate-100 hover:bg-[rgba(15,49,87,0.98)]'
|
||||
: 'bg-slate-900 text-white hover:bg-slate-800'
|
||||
}`}
|
||||
>
|
||||
<span className="inline-flex items-center gap-2">
|
||||
<Eye className="h-4 w-4" />
|
||||
查看结果
|
||||
</span>
|
||||
</button>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleStartChange(task)}
|
||||
className="flex-1 rounded-xl bg-[linear-gradient(90deg,#1677FF,#0EA5E9)] px-3 py-2 text-sm text-white shadow-[0_10px_24px_rgba(22,119,255,0.28)] transition hover:brightness-110"
|
||||
>
|
||||
<span className="inline-flex items-center gap-2">
|
||||
<Play className="h-4 w-4" />
|
||||
开始分析
|
||||
</span>
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</article>
|
||||
);
|
||||
};
|
||||
+46
-36
@@ -77,28 +77,16 @@
|
||||
border-radius: 3px;
|
||||
}
|
||||
|
||||
.strategy-data::-webkit-scrollbar,
|
||||
.strategy-data *::-webkit-scrollbar {
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
}
|
||||
|
||||
.strategy-data::-webkit-scrollbar-thumb,
|
||||
.strategy-data *::-webkit-scrollbar-thumb {
|
||||
background: rgba(203, 213, 225, 0.75);
|
||||
border-radius: 999px;
|
||||
}
|
||||
|
||||
.strategy-data::-webkit-scrollbar-track,
|
||||
.strategy-data *::-webkit-scrollbar-track {
|
||||
background: rgba(241, 245, 249, 0.9);
|
||||
border-radius: 999px;
|
||||
}
|
||||
|
||||
.dark .strategy-data .scrollbar-thin {
|
||||
scrollbar-color: rgba(148, 163, 184, 0.45) transparent;
|
||||
}
|
||||
|
||||
.dark .strategy-data::-webkit-scrollbar,
|
||||
.dark .strategy-data *::-webkit-scrollbar {
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
}
|
||||
|
||||
.dark .strategy-data,
|
||||
.dark .strategy-data * {
|
||||
scrollbar-width: thin;
|
||||
@@ -262,27 +250,39 @@
|
||||
min-width: 320px;
|
||||
}
|
||||
|
||||
.sentiment-date-range-popup .t-date-picker__panel,
|
||||
.sentiment-date-range-popup .t-date-range-picker__panel,
|
||||
.sentiment-date-range-popup .t-date-picker__panel-body,
|
||||
.sentiment-date-range-popup .t-date-picker__panel-content,
|
||||
.sentiment-date-range-popup .t-date-picker__table,
|
||||
.sentiment-date-range-popup .t-time-picker__panel {
|
||||
html.dark .sentiment-date-range-popup .t-date-picker__panel,
|
||||
html.dark .sentiment-date-range-popup .t-date-range-picker__panel,
|
||||
html.dark .sentiment-date-range-popup .t-date-picker__panel-body,
|
||||
html.dark .sentiment-date-range-popup .t-date-picker__panel-content,
|
||||
html.dark .sentiment-date-range-popup .t-date-picker__table,
|
||||
html.dark .sentiment-date-range-popup .t-time-picker__panel,
|
||||
html[theme-mode='dark'] .sentiment-date-range-popup .t-date-picker__panel,
|
||||
html[theme-mode='dark'] .sentiment-date-range-popup .t-date-range-picker__panel,
|
||||
html[theme-mode='dark'] .sentiment-date-range-popup .t-date-picker__panel-body,
|
||||
html[theme-mode='dark'] .sentiment-date-range-popup .t-date-picker__panel-content,
|
||||
html[theme-mode='dark'] .sentiment-date-range-popup .t-date-picker__table,
|
||||
html[theme-mode='dark'] .sentiment-date-range-popup .t-time-picker__panel {
|
||||
background: #0d1d33 !important;
|
||||
color: #e6f4ff !important;
|
||||
}
|
||||
|
||||
.sentiment-date-range-popup .t-popup__content {
|
||||
html.dark .sentiment-date-range-popup .t-popup__content,
|
||||
html[theme-mode='dark'] .sentiment-date-range-popup .t-popup__content {
|
||||
background: #0d1d33 !important;
|
||||
border: 1px solid rgba(110, 136, 176, 0.24);
|
||||
box-shadow: 0 24px 60px rgba(2, 8, 20, 0.42);
|
||||
}
|
||||
|
||||
.sentiment-date-range-popup .t-date-picker__cell,
|
||||
.sentiment-date-range-popup .t-date-picker__cell-inner,
|
||||
.sentiment-date-range-popup .t-date-picker__header,
|
||||
.sentiment-date-range-popup .t-date-picker__text,
|
||||
.sentiment-date-range-popup .t-button {
|
||||
html.dark .sentiment-date-range-popup .t-date-picker__cell,
|
||||
html.dark .sentiment-date-range-popup .t-date-picker__cell-inner,
|
||||
html.dark .sentiment-date-range-popup .t-date-picker__header,
|
||||
html.dark .sentiment-date-range-popup .t-date-picker__text,
|
||||
html.dark .sentiment-date-range-popup .t-button,
|
||||
html[theme-mode='dark'] .sentiment-date-range-popup .t-date-picker__cell,
|
||||
html[theme-mode='dark'] .sentiment-date-range-popup .t-date-picker__cell-inner,
|
||||
html[theme-mode='dark'] .sentiment-date-range-popup .t-date-picker__header,
|
||||
html[theme-mode='dark'] .sentiment-date-range-popup .t-date-picker__text,
|
||||
html[theme-mode='dark'] .sentiment-date-range-popup .t-button {
|
||||
color: #e6f4ff !important;
|
||||
}
|
||||
|
||||
@@ -296,7 +296,7 @@
|
||||
color: #ffffff;
|
||||
}
|
||||
|
||||
.strategy-data .dark-theme:hover {
|
||||
.dark .strategy-data .dark-theme:hover {
|
||||
background: #0062d966;
|
||||
color: #ffffff;
|
||||
border-color: #0062d9 !important;
|
||||
@@ -307,8 +307,8 @@
|
||||
border-color: var(--card-border);
|
||||
}
|
||||
|
||||
.strategy-data .dark-theme.task-active,
|
||||
.strategy-data .dark-theme .task-active {
|
||||
.dark .strategy-data .dark-theme.task-active,
|
||||
.dark .strategy-data .dark-theme .task-active {
|
||||
border-color: #0062d9 !important;
|
||||
}
|
||||
|
||||
@@ -351,20 +351,20 @@
|
||||
background: linear-gradient(180deg, #f5f5f5, #fff 17.89% 100%);
|
||||
}
|
||||
|
||||
.strategy-data .dark-action-bg {
|
||||
.dark .strategy-data .dark-action-bg {
|
||||
background: rgba(3, 38, 80, 0.6) !important;
|
||||
border: 1px solid rgba(43, 143, 254, 0.6) !important;
|
||||
border-radius: 8px !important;
|
||||
box-shadow: 0 1px 16px rgba(0, 0, 0, 0.08) !important;
|
||||
}
|
||||
|
||||
.strategy-data .dark-action-item {
|
||||
.dark .strategy-data .dark-action-item {
|
||||
background: #0062d91a;
|
||||
border: 1px solid #2b8ffe99;
|
||||
border-radius: 8px;
|
||||
}
|
||||
|
||||
.strategy-data .dark-action-item:hover {
|
||||
.dark .strategy-data .dark-action-item:hover {
|
||||
background: #0062d966;
|
||||
border-color: #0062d9;
|
||||
}
|
||||
@@ -373,6 +373,16 @@
|
||||
.strategy-data .t-loading,
|
||||
.strategy-data .t-loading__parent {
|
||||
min-height: 0;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
.strategy-data .t-loading {
|
||||
display: block;
|
||||
}
|
||||
|
||||
.strategy-data .t-loading__parent {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.strategy-data .t-loading--full {
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
/**
|
||||
* 行动 / 任务状态图标。
|
||||
*
|
||||
* 用 `import` 引入 SVG,让 Vite 把它们打进产物并生成带 hash 的最终 URL,
|
||||
* 这样无论部署到子路径(base)还是带指纹的静态资源服务都能正确访问 ——
|
||||
* 不能再用 `/icon/xxx.svg` 这种运行时绝对路径(部署后会 404)。
|
||||
*
|
||||
* key 沿用后端 / taskStatusList 里给的中文文件名,方便按名取用。
|
||||
*/
|
||||
import daiQianShou from "./待签收.svg";
|
||||
import daiCEH from "./待CEH.svg";
|
||||
import jinXingZhong from "./进行中.svg";
|
||||
import wanCheng from "./完成.svg";
|
||||
import weiTongGuo from "./未通过.svg";
|
||||
import yiZhongZhi from "./已终止.svg";
|
||||
|
||||
export const statusIconMap: Record<string, string> = {
|
||||
"待签收.svg": daiQianShou,
|
||||
"待CEH.svg": daiCEH,
|
||||
"进行中.svg": jinXingZhong,
|
||||
"完成.svg": wanCheng,
|
||||
"未通过.svg": weiTongGuo,
|
||||
"已终止.svg": yiZhongZhi,
|
||||
};
|
||||
|
||||
/** 按文件名取打包后的图标 URL;取不到返回 undefined(<img> 不渲染 broken icon)。 */
|
||||
export function resolveStatusIcon(name?: string | null): string | undefined {
|
||||
if (!name) return undefined;
|
||||
return statusIconMap[name];
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none">
|
||||
<circle cx="12" cy="12" r="11" fill="#1eb07f"/>
|
||||
<path d="M7.5 12.3 10.5 15.3 16.5 9" stroke="#fff" stroke-width="2" fill="none" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 284 B |
@@ -0,0 +1,4 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none">
|
||||
<circle cx="12" cy="12" r="11" fill="#8c8c8c"/>
|
||||
<rect x="8.7" y="8.7" width="6.6" height="6.6" rx="1.4" fill="#fff"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 225 B |
@@ -0,0 +1,5 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none">
|
||||
<circle cx="12" cy="12" r="11" fill="#2f9acc"/>
|
||||
<circle cx="11" cy="11" r="3.2" stroke="#fff" stroke-width="1.8" fill="none"/>
|
||||
<path d="M13.4 13.4 16.2 16.2" stroke="#fff" stroke-width="1.8" stroke-linecap="round"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 325 B |
@@ -0,0 +1,6 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none">
|
||||
<circle cx="12" cy="12" r="11" fill="#0062d9"/>
|
||||
<rect x="7.6" y="7.8" width="8.8" height="9.6" rx="1.6" stroke="#fff" stroke-width="1.5" fill="none"/>
|
||||
<path d="M9.8 7.8v-.5a1 1 0 0 1 1-1h2.4a1 1 0 0 1 1 1v.5" stroke="#fff" stroke-width="1.5" fill="none" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M9.8 11h4.4M9.8 13.6h2.8" stroke="#fff" stroke-width="1.5" stroke-linecap="round"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 507 B |
@@ -0,0 +1,4 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none">
|
||||
<circle cx="12" cy="12" r="11" fill="#cf1322"/>
|
||||
<path d="M8.8 8.8 15.2 15.2M15.2 8.8 8.8 15.2" stroke="#fff" stroke-width="2" stroke-linecap="round"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 258 B |
@@ -0,0 +1,4 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none">
|
||||
<circle cx="12" cy="12" r="11" fill="#d97b00"/>
|
||||
<path d="M10.2 8.4 15.4 12l-5.2 3.6z" fill="#fff" stroke="#fff" stroke-width="1.2" stroke-linejoin="round"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 264 B |
Reference in new issue
Block a user