sync update from LAN repo (source master @ ca48c4ec)

This commit is contained in:
gozeros committed 2026-11-05 10:53:54 +08:00
1 parent 8bc8b0e082
commit ea9dcff9c0
873 files changed
+107866 -14011

No files matched your search

@@ -95,6 +95,7 @@ interface ServerChain {
is_public?: boolean;
enabled?: boolean;
pending_review?: boolean;
hidden?: boolean;
is_mine?: boolean;
owner_name?: string | null;
created_at: string | null;
@@ -116,6 +117,8 @@ function toChain(s: ServerChain): BusinessChain {
enabled: s.enabled ?? true,
// 「待审核」标记:缺省 false(旧响应兼容)。
pendingReview: s.pending_review ?? false,
// 管理员目录开关:缺省 false(旧响应兼容)。
hidden: s.hidden ?? false,
// 后端缺省时按「我的」处理(向后兼容旧响应)。
isMine: s.is_mine ?? true,
ownerName: s.owner_name ?? undefined,
@@ -162,9 +165,21 @@ function fromUpdate(p: ChainUpdatePayload) {
* List chains, newest first. `scope`:
* - `"mine"`(默认):当前用户自己的链条;
* - `"public"`:所有已发布的公共链条(任何账号可见 / 可选入研讨)。
*
* `opts`(管理员配置页专用,普通调用方不传):
* - `adminView: true` → 管理视图:不排除被管理员隐藏的链条(后端对非管理员忽略);
* - `hidden: true/false` → 配合 adminView 筛选「只看隐藏 / 只看显示中」。
*/
export async function listChains(scope: ChainScope = "mine"): Promise<BusinessChain[]> {
const url = scope === "mine" ? BASE() : `${BASE()}?scope=${scope}`;
export async function listChains(
scope: ChainScope = "mine",
opts: { adminView?: boolean; hidden?: boolean } = {},
): Promise<BusinessChain[]> {
const qs = new URLSearchParams();
if (scope !== "mine") qs.set("scope", scope);
if (opts.adminView) qs.set("admin_view", "true");
if (opts.hidden != null && opts.adminView) qs.set("hidden", String(opts.hidden));
const query = qs.toString();
const url = query ? `${BASE()}?${query}` : BASE();
const res = await apiFetch(url, { method: "GET" });
const data = await readJson<{ chains: ServerChain[] }>(res, "list chains");
const chains = (data.chains ?? []).map(toChain);
@@ -172,12 +187,31 @@ export async function listChains(scope: ChainScope = "mine"): Promise<BusinessCh
optType: OptType.search,
optDetail: "CM助手-全量-业务链条-查询",
url,
reqParam: { scope },
reqParam: { scope, ...opts },
returnParam: { count: chains.length },
});
return chains;
}
/** 管理员隐藏 / 取消隐藏一条链条(PUT /{id}/hidden,仅 admin)。返回更新后的链条,失败抛错。 */
export async function setChainHidden(id: string, hidden: boolean): Promise<BusinessChain> {
const res = await apiFetch(`${BASE()}/${encodeURIComponent(id)}/hidden`, {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ hidden }),
});
const data = await readJson<ServerChain>(res, "set chain hidden");
const chain = toChain(data);
writeYLog({
optType: OptType.edit,
optDetail: "CM助手-全量-业务链条-设置隐藏",
url: `${BASE()}/${id}/hidden`,
reqParam: { id, hidden },
returnParam: { id: chain.id, title: chain.title },
});
return chain;
}
/** 发布 / 取消发布一条链条(仅 owner 生效)。返回更新后的链条,404 返回 null。 */
export async function setChainPublic(id: string, isPublic: boolean): Promise<BusinessChain | null> {
return updateChain(id, { isPublic });
@@ -188,12 +222,7 @@ export async function setChainEnabled(id: string, enabled: boolean): Promise<Bus
return updateChain(id, { enabled });
}
/** 提交审核(owner 在编辑器发起):进入「待审核」,等待管理员发布。返回更新后的链条,404 返回 null。 */
export async function submitChainForReview(id: string): Promise<BusinessChain | null> {
return updateChain(id, { pendingReview: true });
}
/** 管理员发布「待审核」链条:正式发布为公共并清除待审核标记。返回更新后的链条,404 返回 null。 */
/** 发布「待审核」链条(历史审核流遗留数据):正式发布为公共并清除待审核标记。返回更新后的链条,404 返回 null。 */
export async function approveChainReview(id: string): Promise<BusinessChain | null> {
return updateChain(id, { isPublic: true, pendingReview: false });
}
@@ -2,12 +2,41 @@ import { apiFetch } from "@/core/api/fetch-client";
import { getBackendBaseURL } from "@/core/config";
import { OptType, writeYLog } from "@/core/log/y-log";
import {
isRoundtableCapacityFailure,
RoundtableRoomFullError,
} from "@/roundtable-planning/lib/capacity-error";
import { resolveAllowMultiple } from "@/roundtable-planning/lib/clarification";
import { reportRoundtableError, stageForRoundtableAgent } from "@/roundtable-planning/api/diagnostics-report";
import { createInlineReasoningDeltaFormatter } from "@/roundtable-planning/lib/stream-reasoning";
export type ThreadIdMap = Record<string, string>;
function roomFullError(
rawDetail: string,
status: number | null,
context: string,
): RoundtableRoomFullError {
let activeCount = 0;
let maxRooms = 0;
try {
const body = JSON.parse(rawDetail) as {
detail?: { active_count?: number; max_rooms?: number };
active_count?: number;
max_rooms?: number;
};
activeCount = body.detail?.active_count ?? body.active_count ?? 0;
maxRooms = body.detail?.max_rooms ?? body.max_rooms ?? 0;
} catch {
// 包装后的 502 / SSE 文本通常不是纯 JSON;计数仅供诊断,不影响统一提示。
}
console.error(`[roundtable-capacity] ${context}`, {
status,
detail: rawDetail,
});
return new RoundtableRoomFullError(activeCount, maxRooms);
}
export interface SeatReadyEvent {
agentName: string;
threadId: string;
@@ -24,6 +53,10 @@ export interface InitMultiAgentRequest {
agentNames: string[];
mainAgentName: string;
model?: string;
/** Step-2 room gate. One live page execution shares this identity across all seats/steps. */
draftId?: string;
taskId?: string;
roomSessionId?: string;
/** Fires the moment each sub-agent's thread is ready (real completion order). */
onSeatReady?: (event: SeatReadyEvent) => void;
/** Fires when the coordinator's thread + agent have been created. */
@@ -71,6 +104,9 @@ export async function initMultiAgent(
agent_names: payload.agentNames,
main_agent_name: payload.mainAgentName,
model: payload.model,
draft_id: payload.draftId,
task_id: payload.taskId,
room_session_id: payload.roomSessionId,
}),
signal: payload.signal,
});
@@ -83,6 +119,9 @@ export async function initMultiAgent(
httpStatus: res.status,
detail: { agentNames: payload.agentNames, mainAgentName: payload.mainAgentName },
});
if (res.status === 409 || isRoundtableCapacityFailure(res.status, text)) {
throw roomFullError(text, res.status, "init HTTP request rejected");
}
throw new Error(`init multi-agent failed (${res.status}): ${text}`);
}
@@ -176,6 +215,9 @@ export async function initMultiAgent(
stage: "step2_init", event: "init_error_frame",
message: `第二步会商初始化报错:${errorDetail.slice(0, 800)}`,
});
if (isRoundtableCapacityFailure(null, errorDetail)) {
throw roomFullError(errorDetail, null, "init SSE error frame");
}
throw new Error(`init multi-agent failed: ${errorDetail}`);
}
if (aborted) {
@@ -218,6 +260,10 @@ export interface StreamMultiAgentRequest {
agentType: StreamAgentType;
dAgentThreadId: ThreadIdMap;
agentName: string;
/** Stable room scope; used only by the backend concurrency gate. */
draftId?: string;
taskId?: string;
roomSessionId?: string;
/**
* 人类可读名称(中文/英文)。仅 special 走广播时使用 —— 后端把它拼进
* 「子智能体X完成Y工作,交付内容为:...」里,这样总控 LLM 在下一轮看到自己
@@ -254,6 +300,12 @@ export interface StreamMultiAgentRequest {
* 后端只给摘要,使总控上下文精简、响应快。
*/
synthesisMode?: boolean;
/**
* 仅 leader 用。最终收口轮置 true:后端不再装载任何工具,只允许总控根据已注入的
* 席位交付直接输出正文。该模式不限制模型思考长度,只阻止 write_file / present_files /
* agent_orchestration 等工具把收口重新带回循环。
*/
finalizeOnly?: boolean;
/**
* 仅为兼容旧协议保留。总控 prompt 属于总控私有上下文,前端恒传 true,后端也会无条件隔离。
*/
@@ -530,6 +582,9 @@ export async function streamMultiAgent(
agent_type: req.agentType,
d_agent_thread_id: req.dAgentThreadId,
agent_name: req.agentName,
draft_id: req.draftId,
task_id: req.taskId,
room_session_id: req.roomSessionId,
// 仅 special 用到;后端缺失时 fallback 到 agent_name,旧前端也不破坏。
display_name: req.displayName,
new_message: req.newMessage,
@@ -545,6 +600,8 @@ export async function streamMultiAgent(
skill_stop_names: req.skillStopNames ?? [],
// 仅 leader 用;综合轮让后端注入各席位完整交付正文。省略 → 后端按 false 处理。
synthesis_mode: req.synthesisMode ?? false,
// 仅 leader 最终收口用;纯正文、零工具,且不再受 Step2 房间租约拦截。
finalize_only: req.finalizeOnly ?? false,
// 总控 prompt 永不进入席位 thread;后端同样强制执行,避免旧调用方破坏角色隔离。
suppress_pre_broadcast: req.suppressPreBroadcast ?? true,
// 仅 special 用;DAG 并行批次禁写文件(seat_parallel policy)。省略 → 后端按 false 处理。
@@ -570,6 +627,9 @@ export async function streamMultiAgent(
detail: { agentType: req.agentType },
});
reported = true;
if (res.status === 409 || isRoundtableCapacityFailure(res.status, text)) {
throw roomFullError(text, res.status, "run/stream HTTP request rejected");
}
throw new Error(`run/stream failed (${res.status}): ${text}`);
}
@@ -583,6 +643,7 @@ export async function streamMultiAgent(
let lastEvent = "";
let frameSeq = 0;
let gotFinalStatus = false;
let workerErrorDetail = "";
const debugLabel = `[stream:${req.agentType}:${req.agentName}]`;
// Stream 帧日志(frame# / delta)仅 opt-in 开启。默认关闭,避免 Step 2 流式期间
@@ -761,6 +822,7 @@ export async function streamMultiAgent(
// 单独在这里捕获上报,否则这类「模型没调用成功」的报错会漏收集。
if (lastEvent === "error") {
const obj = parsed && typeof parsed === "object" ? (parsed as Record<string, unknown>) : { raw: parsed };
workerErrorDetail = String(obj.message ?? obj.name ?? "上游运行异常").slice(0, 800);
reportRoundtableError({
stage: stageForRoundtableAgent(req.agentType, req.agentName),
event: "run_worker_error_event",
@@ -936,6 +998,16 @@ export async function streamMultiAgent(
agentName: req.displayName || req.agentName,
detail: { agentType: req.agentType, framesBeforeError: frameSeq },
});
if (isRoundtableCapacityFailure(null, result.content)) {
reported = true;
throw roomFullError(
result.content,
null,
`run/stream SSE error frame (${req.displayName || req.agentName})`,
);
}
reported = true;
throw new Error(result.content || `「${req.displayName || req.agentName}」运行失败`);
}
continue;
}
@@ -954,9 +1026,18 @@ export async function streamMultiAgent(
if (debugEnabled) {
console.debug(debugLabel, `stream ended after ${frameSeq} frames; final content length=${result.content.length}`);
}
if (req.agentType === "special" && !gotFinalStatus) {
result.invalidDelivery = { reason: "truncated" };
result.content = "";
if (!gotFinalStatus) {
if (workerErrorDetail) {
reported = true;
throw new Error(workerErrorDetail);
}
if (req.agentType === "special") {
result.invalidDelivery = { reason: "truncated" };
result.content = "";
} else {
reported = true;
throw new Error(`「${req.displayName || req.agentName}」连接提前结束,未收到会商终态`);
}
}
return result;
} catch (err) {
@@ -1063,6 +1144,21 @@ export interface ReportThreadResponse {
threadId: string;
}
interface RoomScopedThreadInitOptions {
signal?: AbortSignal;
draftId?: string;
taskId?: string;
roomSessionId?: string;
}
function roomScopeBody(options: RoomScopedThreadInitOptions): string {
return JSON.stringify({
draft_id: options.draftId,
task_id: options.taskId,
room_session_id: options.roomSessionId,
});
}
/**
* Create a thread for the Step 3「结果绘制」visualization agent
* (`roundtable-report`, a built-in singleton — this only spins up a cheap
@@ -1071,12 +1167,12 @@ export interface ReportThreadResponse {
* `agentName: "roundtable-report"`, `dAgentThreadId: { [agentName]: threadId }`).
*/
export async function initReportThread(
options: { signal?: AbortSignal } = {},
options: RoomScopedThreadInitOptions = {},
): Promise<ReportThreadResponse> {
const res = await apiFetch(`${getBackendBaseURL()}/api/multi-agent/report/init`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: "{}",
body: roomScopeBody(options),
signal: options.signal,
});
if (!res.ok) {
@@ -1102,12 +1198,12 @@ export async function initReportThread(
* so the agent keeps the prior dashboard context.
*/
export async function initDashboardThread(
options: { signal?: AbortSignal } = {},
options: RoomScopedThreadInitOptions = {},
): Promise<ReportThreadResponse> {
const res = await apiFetch(`${getBackendBaseURL()}/api/multi-agent/dashboard/init`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: "{}",
body: roomScopeBody(options),
signal: options.signal,
});
if (!res.ok) {
@@ -1132,12 +1228,12 @@ export async function initDashboardThread(
* the SAME thread (do not re-init) so the agent keeps the report context.
*/
export async function initSummaryThread(
options: { signal?: AbortSignal } = {},
options: RoomScopedThreadInitOptions = {},
): Promise<ReportThreadResponse> {
const res = await apiFetch(`${getBackendBaseURL()}/api/multi-agent/summary/init`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: "{}",
body: roomScopeBody(options),
signal: options.signal,
});
if (!res.ok) {
@@ -1193,12 +1289,12 @@ export async function initPositionActionPlanThread(
* its SKILL.md and calls it — passing the taskId + summary report + structured flow.
*/
export async function initStructureThread(
options: { signal?: AbortSignal } = {},
options: RoomScopedThreadInitOptions = {},
): Promise<ReportThreadResponse> {
const res = await apiFetch(`${getBackendBaseURL()}/api/multi-agent/structure/init`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: "{}",
body: roomScopeBody(options),
signal: options.signal,
});
if (!res.ok) {
@@ -0,0 +1,102 @@
import { apiFetch } from "@/core/api/fetch-client";
import { getBackendBaseURL } from "@/core/config";
export {
isRoundtableCapacityFailure,
isRoundtableRoomFullError,
RoundtableRoomFullError,
roundtableErrorForDisplay,
ROUNDTABLE_ROOM_FULL_MESSAGE,
} from "@/roundtable-planning/lib/capacity-error";
export interface RoundtableRoomAdmission {
ok: boolean;
enabled: boolean;
maxRooms: number;
activeCount: number;
renewed: boolean;
code: string;
message: string;
}
export interface RoundtableRoomSummary {
enabled: boolean;
maxRooms: number;
activeCount: number;
}
interface RoomPayload {
ok?: boolean;
enabled?: boolean;
max_rooms?: number;
active_count?: number;
renewed?: boolean;
code?: string;
message?: string;
}
function asAdmission(payload: RoomPayload, ok: boolean): RoundtableRoomAdmission {
return {
ok,
enabled: payload.enabled ?? true,
maxRooms: payload.max_rooms ?? 3,
activeCount: payload.active_count ?? 0,
renewed: payload.renewed ?? false,
code: payload.code ?? "",
message: payload.message ?? "",
};
}
async function readPayload(response: Response): Promise<RoomPayload> {
const body = (await response.json().catch(() => ({}))) as { detail?: RoomPayload } & RoomPayload;
if (body.detail && typeof body.detail === "object") return body.detail;
return body;
}
async function postRoom(
path: "acquire" | "heartbeat" | "release",
scope: { draftId: string; taskId?: string | null; roomSessionId: string },
): Promise<RoundtableRoomAdmission> {
const response = await apiFetch(`${getBackendBaseURL()}/api/roundtable-rooms/${path}`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
draftId: scope.draftId,
taskId: scope.taskId || undefined,
roomSessionId: scope.roomSessionId,
}),
});
const payload = await readPayload(response);
if (response.status === 409) {
return asAdmission(payload, false);
}
if (!response.ok) {
throw new Error(payload.message || `会商房间请求失败(HTTP ${response.status})`);
}
return asAdmission(payload, true);
}
export function acquireRoundtableRoom(scope: { draftId: string; taskId?: string | null; roomSessionId: string }) {
return postRoom("acquire", scope);
}
export function heartbeatRoundtableRoom(scope: { draftId: string; taskId?: string | null; roomSessionId: string }) {
return postRoom("heartbeat", scope);
}
export function releaseRoundtableRoom(scope: { draftId: string; taskId?: string | null; roomSessionId: string }) {
return postRoom("release", scope);
}
export async function loadRoundtableRoomSummary(): Promise<RoundtableRoomSummary> {
const response = await apiFetch(`${getBackendBaseURL()}/api/roundtable-rooms/summary`);
if (!response.ok) {
throw new Error(`无法读取会商房间占用(HTTP ${response.status})`);
}
const payload = (await response.json()) as RoomPayload;
return {
enabled: payload.enabled ?? true,
maxRooms: payload.max_rooms ?? 3,
activeCount: payload.active_count ?? 0,
};
}
@@ -18,6 +18,12 @@ import { getBackendBaseURL } from "@/core/config";
import { OptType, writeYLog } from "@/core/log/y-log";
import { getAvatarTypeFor } from "../lib/roundtable-constants";
import {
isRoundtableCapacityFailure,
RoundtableRoomFullError,
roundtableErrorForDisplay,
ROUNDTABLE_ROOM_FULL_MESSAGE,
} from "../lib/capacity-error";
import { reportRoundtableError } from "./diagnostics-report";
import { seatModeToRunParams } from "../lib/seat-mode";
import {
@@ -29,6 +35,15 @@ import {
} from "../lib/job-types";
const BASE = () => `${getBackendBaseURL()}/api/roundtable-jobs`;
const loggedCapacityErrors = new Set<string>();
function logCapacityError(jobId: string, detail: string) {
const key = `${jobId}:${detail}`;
if (loggedCapacityErrors.has(key)) return;
if (loggedCapacityErrors.size >= 100) loggedCapacityErrors.clear();
loggedCapacityErrors.add(key);
console.error("[roundtable-capacity] background job rejected", { jobId, detail });
}
async function readJson<T>(res: Response, ctx: string): Promise<T> {
if (!res.ok) {
@@ -38,6 +53,10 @@ async function readJson<T>(res: Response, ctx: string): Promise<T> {
message: `后台作业接口「${ctx}」失败 (HTTP ${res.status}): ${text.slice(0, 500)}`,
httpStatus: res.status,
});
if (isRoundtableCapacityFailure(res.status, text)) {
logCapacityError(ctx, text);
throw new RoundtableRoomFullError();
}
throw new Error(`${ctx} failed (${res.status}): ${text}`);
}
return (await res.json()) as T;
@@ -63,8 +82,20 @@ function withAvatar(nodes: unknown): DispatchChainNode[] {
/** 后端快照 → 前端 RoundtableJob(容错 + 补 avatarType)。 */
function mapJob(raw: Record<string, unknown>): RoundtableJob {
const id = String(raw.id ?? "");
const rawError = (raw.error as string | null) ?? null;
if (isRoundtableCapacityFailure(null, rawError)) {
logCapacityError(id, rawError ?? "");
}
const dialogues = Array.isArray(raw.dialogues)
? (raw.dialogues as JobDialogue[]).map((dialogue) => {
if (!isRoundtableCapacityFailure(null, dialogue.content)) return dialogue;
logCapacityError(id, dialogue.content);
return { ...dialogue, content: ROUNDTABLE_ROOM_FULL_MESSAGE };
})
: [];
return {
id: String(raw.id ?? ""),
id,
draftId: (raw.draftId as string | null) ?? null,
status: (raw.status as RoundtableJob["status"]) ?? "queued",
phase: (raw.phase as RoundtableJob["phase"]) ?? "initializing",
@@ -76,8 +107,8 @@ function mapJob(raw: Record<string, unknown>): RoundtableJob {
orchestrationMode: (raw.orchestrationMode as RoundtableJob["orchestrationMode"]) ?? "recommend",
chain: (raw.chain as RoundtableJob["chain"]) ?? null,
orchestrationPlan: (raw.orchestrationPlan as RoundtableJob["orchestrationPlan"]) ?? null,
error: (raw.error as string | null) ?? null,
dialogues: Array.isArray(raw.dialogues) ? (raw.dialogues as JobDialogue[]) : [],
error: roundtableErrorForDisplay(rawError),
dialogues,
step3: (raw.step3 as RoundtableJob["step3"]) ?? null,
createdAt: (raw.createdAt as string | null) ?? null,
updatedAt: (raw.updatedAt as string | null) ?? null,
@@ -95,6 +126,7 @@ function toStartBody(p: StartJobPayload) {
draftId: p.draftId ?? null,
// taskId 非空 → task 作业(按 task 共享、不分权,报告写回独立 task-draft 存储)。
...(p.taskId ? { taskId: p.taskId } : {}),
...(p.roomSessionId ? { roomSessionId: p.roomSessionId } : {}),
intent: p.intent,
agents: p.agents,
model: p.model,
@@ -6,8 +6,9 @@
* - footer「配置」按钮 → 进入配置页(空白新建,等价于旧按钮的直接跳转)。
*
* 纯导航 / 浏览用途,不参与研讨席位选择(席位选择走 `BusinessChainPicker`)。
* 卡片席位名优先用实时 agent 数据(`listAgents()`,与 `BusinessChainPicker` 一致),
* agent 改名后此弹窗也能同步显示;解析不到才回退到落库快照(`seat.name`)。
* 卡片席位名用链条响应自带的读时计算富化字段 `seat.live_name`(后端一次批量查询
* 算好,与 `BusinessChainPicker` 一致),agent 改名后此弹窗也能同步显示;解析不到
* 才回退到落库快照(`seat.name`)。**本弹窗不再实时拉 `/api/agents`**。
*/
import { useCallback, useEffect, useMemo, useState } from "react";
import {
@@ -31,12 +32,11 @@ import {
} from "@/components/ui/dialog";
import { Switch } from "@/components/ui/switch";
import { cn } from "@/lib/utils";
import { toast } from "sonner";
import { useDesensitizeSubtree } from "@/roundtable-planning/lib/use-desensitize-subtree";
import { getStoredAuth } from "@/core/auth";
import { listAgents } from "@/core/agents";
import { listChains, setChainEnabled, setChainPublic, submitChainForReview, updateChain, type ChainScope } from "../api/chains";
import { listChains, setChainEnabled, setChainPublic, updateChain, type ChainScope } from "../api/chains";
import { chainTagClasses, isChainEnabled, type BusinessChain } from "../lib/business-chain";
import { getAvatarTypeFor } from "../lib/roundtable-constants";
@@ -84,29 +84,8 @@ export function BusinessChainListBody({
const [enabledFilter, setEnabledFilter] = useState<EnabledFilter>("all");
const [publishingId, setPublishingId] = useState<string | null>(null);
const [togglingId, setTogglingId] = useState<string | null>(null);
// 发布审核选择弹窗的目标链条(null = 关闭)。草稿点「发布」先选 确认审核 / 直接发布。
// 发布确认弹窗的目标链条(null = 关闭)。草稿点「发布」先弹窗确认。
const [reviewTarget, setReviewTarget] = useState<BusinessChain | null>(null);
// 实时名称表(id 小写 → 最新 name):用于把席位的落库快照名刷新成最新(agent 改名同步)。
const [nameById, setNameById] = useState<Map<string, string>>(new Map());
useEffect(() => {
if (!active) return;
let cancelled = false;
void (async () => {
try {
const agents = await listAgents();
if (cancelled) return;
const m = new Map<string, string>();
for (const a of agents) if (a?.id) m.set(a.id.toLowerCase(), a.name ?? a.id);
setNameById(m);
} catch {
// 静默失败:解析不到就回退到席位快照名。
}
})();
return () => {
cancelled = true;
};
}, [active]);
const refresh = useCallback(async (s: ChainScope) => {
setLoading(true);
@@ -142,28 +121,9 @@ export function BusinessChainListBody({
};
}, [active, scope]);
// 发布入口:已发布 → 直接取消发布(旧行为);审核中 → 撤回审核;草稿 → 弹窗选
// 「确认审核 / 直接发布」(与链条编辑页一致)。
// 发布入口:已发布 → 直接取消发布(旧行为);未发布(含遗留「审核中」)→ 弹窗直接发布。
const handleTogglePublic = useCallback(
async (chain: BusinessChain) => {
// 审核中 → 撤回审核,回到草稿。
if (!chain.isPublic && chain.pendingReview) {
if (!window.confirm(`「${chain.title || "未命名链条"}」正在审核中,确认撤回审核?`)) return;
setPublishingId(chain.id);
try {
const updated = await updateChain(chain.id, { pendingReview: false });
if (updated) {
setChains((prev) => prev.map((c) => (c.id === updated.id ? updated : c)));
} else {
await refresh(scope);
}
} catch (err) {
setError(err instanceof Error ? err.message : String(err));
} finally {
setPublishingId(null);
}
return;
}
// 已发布 → 直接取消发布。
if (chain.isPublic) {
setPublishingId(chain.id);
@@ -181,40 +141,23 @@ export function BusinessChainListBody({
}
return;
}
// 草稿 → 弹窗选择。
// 未发布 → 弹窗确认发布(发布同时清除遗留的待审核标记)。
setReviewTarget(chain);
},
[refresh, scope],
);
// 弹窗「确认审核」:提交进入待审核,等待管理员发布。
const handleSubmitReview = useCallback(async () => {
// 弹窗「直接发布 / 提交审核」:两个按钮功能一致,立即发布为公共并清除待审核标记;
// 仅成功提示按所点按钮区分(提交审核 → 「提交成功」)。
const handleDirectPublish = useCallback(async (viaReviewButton = false) => {
const chain = reviewTarget;
if (!chain) return;
setPublishingId(chain.id);
try {
const updated = await submitChainForReview(chain.id);
if (updated) {
setChains((prev) => prev.map((c) => (c.id === updated.id ? updated : c)));
}
setReviewTarget(null);
if (!updated) await refresh(scope);
} catch (err) {
setError(err instanceof Error ? err.message : String(err));
} finally {
setPublishingId(null);
}
}, [reviewTarget, refresh, scope]);
// 弹窗「直接发布」:立即对所有账号可见(旧行为)。
const handleDirectPublish = useCallback(async () => {
const chain = reviewTarget;
if (!chain) return;
setPublishingId(chain.id);
try {
const updated = await setChainPublic(chain.id, true);
const updated = await updateChain(chain.id, { isPublic: true, pendingReview: false });
if (updated) {
setChains((prev) => prev.map((c) => (c.id === updated.id ? updated : c)));
toast.success(viaReviewButton ? "提交成功" : "已发布为公共,所有账号都能查看 / 选用");
}
setReviewTarget(null);
if (!updated) await refresh(scope);
@@ -328,7 +271,6 @@ export function BusinessChainListBody({
key={chain.id}
chain={chain}
canManage={isAdmin || chain.isMine !== false}
nameById={nameById}
publishing={publishingId === chain.id}
toggling={togglingId === chain.id}
onSettings={() => onConfigure(chain.id)}
@@ -340,7 +282,7 @@ export function BusinessChainListBody({
)}
</div>
{/* 发布审核选择弹窗:确认审核 → 待审核(管理员发布);直接发布 → 立即公共可见。 */}
{/* 发布确认弹窗:「直接发布 / 提交审核」两个按钮功能一致,均立即发布为公共。 */}
<Dialog open={reviewTarget !== null} onOpenChange={(o) => !o && setReviewTarget(null)}>
<DialogContent className="sm:max-w-md">
<DialogHeader>
@@ -349,7 +291,7 @@ export function BusinessChainListBody({
发布业务链条
</DialogTitle>
<DialogDescription>
是否需要审核?确认审核后「{reviewTarget?.title || "未命名链条"}」将进入「待审核」,由管理员在业务链条列表中发布;直接发布则立即对所有账号可见 / 选用。
发布后「{reviewTarget?.title || "未命名链条"}」将立即对所有账号可见 / 选用。
</DialogDescription>
</DialogHeader>
<DialogFooter>
@@ -358,16 +300,16 @@ export function BusinessChainListBody({
</Button>
<Button
variant="secondary"
onClick={handleDirectPublish}
onClick={() => void handleDirectPublish(false)}
disabled={reviewTarget ? publishingId === reviewTarget.id : true}
>
直接发布
</Button>
<Button
onClick={handleSubmitReview}
onClick={() => void handleDirectPublish(true)}
disabled={reviewTarget ? publishingId === reviewTarget.id : true}
>
确认审核
提交审核
</Button>
</DialogFooter>
</DialogContent>
@@ -414,7 +356,6 @@ export function BusinessChainListDialog({
function ChainRow({
chain,
canManage,
nameById,
publishing,
toggling,
onSettings,
@@ -424,7 +365,6 @@ function ChainRow({
chain: BusinessChain;
/** 能否编辑 / 发布 / 启停(本人链条 或 管理员)。 */
canManage: boolean;
nameById: Map<string, string>;
publishing: boolean;
toggling: boolean;
onSettings: () => void;
@@ -479,7 +419,7 @@ function ChainRow({
</span>
</label>
)}
{/* 发布 / 取消发布 / 审核中撤回:本人的链条或管理员可操作。 */}
{/* 发布 / 取消发布:本人的链条或管理员可操作;待审核 = 直接审核发布。 */}
{canManage && (
<Button
variant={chain.isPublic ? "secondary" : "outline"}
@@ -490,8 +430,8 @@ function ChainRow({
chain.isPublic
? "取消发布,收回为私有"
: chain.pendingReview
? "审核中,点击撤回审核"
: "发布:可选提交审核(管理员发布)或直接发布"
? "审核通过并发布"
: "发布:立即对所有账号可见 / 选用"
}
className="h-8 gap-1.5 px-3 text-sm"
>
@@ -540,20 +480,14 @@ function ChainRow({
)}
{/* 席位编排:按 stage 分组——并行阶段竖向并列在虚线框里,阶段之间用 → 串联。 */}
<ChainSeatsFlow chain={chain} nameById={nameById} />
<ChainSeatsFlow chain={chain} />
</div>
);
}
// ── 链条席位编排流(体现「同层并行 · 层间串行」)─────────────────────────────
function ChainSeatsFlow({
chain,
nameById,
}: {
chain: BusinessChain;
nameById: Map<string, string>;
}) {
function ChainSeatsFlow({ chain }: { chain: BusinessChain }) {
// 名称回退表:用落库快照(seats)解析 stage 里的 agent_id。
const seatById = new Map(chain.seats.map((s) => [s.agent_id, s] as const));
@@ -576,8 +510,8 @@ function ChainSeatsFlow({
const seatTag = (agentId: string) => {
const seat = seatById.get(agentId);
// 优先实时名称(agent 改名同步)→ 落库快照 → agent_id。
const label = nameById.get(agentId.toLowerCase()) ?? seat?.name ?? agentId;
// 优先后端读时算好的最新名称(live_name,agent 改名同步)→ 落库快照 → agent_id。
const label = seat?.live_name ?? seat?.name ?? agentId;
return (
<span
key={agentId}
@@ -5,8 +5,10 @@
* - 卡片标题(链条 title)+ 存活席位计数。
* - 标题下一排**智能体名 tag**:按链条顺序从左到右排列、不同颜色(`getAvatarTypeFor`
* → `chainTagClasses`),tag 之间用 `→`(ArrowRight)箭头连接表达发言次序。
* - 链条里有 agent 已被删除 → 该 tag 置灰删除线 + 提示;卡片只用**存活**席位,
* 存活不足 `CHAIN_MIN_SEATS` 则不可使用。
* - 席位的存活状态(agent 已删除 → tag 置灰删除线)与最新名称来自链条响应自带的
* 读时计算富化字段 `seat.available` / `seat.live_name`(后端一次批量查询算好),
* **本组件不再实时拉 `/api/agents`**——慢网下打开弹窗只有 1 个 listChains 请求。
* 卡片只用**存活**席位,存活不足 `CHAIN_MIN_SEATS` 则不可使用。
*
* 选中一条 → 高亮;底部「进入研讨」回传 `SeatSelectionResult{ mode:"chain" }`,
* 由父弹窗的 `onConfirm` 透传给主页面(席位顺序 = 链条顺序)。
@@ -27,9 +29,7 @@ import { Button } from "@/components/ui/button";
import { DialogFooter } from "@/components/ui/dialog";
import { cn } from "@/lib/utils";
import { useDesensitizeSubtree } from "@/roundtable-planning/lib/use-desensitize-subtree";
import { listAgents } from "@/core/agents";
import { filterRecommendCandidates } from "../api/recommend";
import { listChains, type ChainScope } from "../api/chains";
import {
CHAIN_MIN_SEATS,
@@ -62,9 +62,6 @@ export function BusinessChainPicker({
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;
@@ -73,19 +70,9 @@ export function BusinessChainPicker({
setSelectedId(null); // 切换筛选后清空选中(旧选中可能不在新列表里)。
void (async () => {
try {
const [chainList, agents] = await Promise.all([
listChains(scope),
listAgents().catch(() => null), // agent 列表失败不阻断链条展示
]);
const chainList = await listChains(scope);
if (cancelled) return;
setChains(chainList.filter(isChainEnabled));
if (agents) {
const candidates = filterRecommendCandidates(agents);
setExistingIds(new Set(candidates.map((c) => c.agent_id)));
setNameById(new Map(candidates.map((c) => [c.agent_id, c.name])));
} else {
setExistingIds(null);
}
} catch (err) {
if (cancelled) return;
setError(err instanceof Error ? err.message : String(err));
@@ -98,11 +85,6 @@ export function BusinessChainPicker({
};
}, [scope]);
const isExisting = useMemo(
() => (agentId: string) => existingIds === null || existingIds.has(agentId),
[existingIds],
);
const selectedChain = useMemo(
() => chains.find((c) => c.id === selectedId) ?? null,
[chains, selectedId],
@@ -116,9 +98,10 @@ export function BusinessChainPicker({
useEffect(() => {
onSelectedChainChangeRef.current?.(selectedChain);
}, [selectedChain]);
// 席位存活:读后端随链条响应算好的 seat.available(undefined = 旧后端未标注 → 视为存活)。
const survivingSeats = useMemo(
() => (selectedChain ? selectedChain.seats.filter((s) => isExisting(s.agent_id)) : []),
[selectedChain, isExisting],
() => (selectedChain ? selectedChain.seats.filter((s) => s.available !== false) : []),
[selectedChain],
);
const canUse = !!selectedChain && survivingSeats.length >= CHAIN_MIN_SEATS;
@@ -146,8 +129,10 @@ export function BusinessChainPicker({
const handleUse = () => {
if (!canUse || !selectedChain) return;
const chainMeta = { id: selectedChain.id, title: selectedChain.title };
// 名称回退表:后端读时算好的最新名(live_name)→ 落库快照(seat.name)→ agent_id。
const seatNameById = new Map(selectedChain.seats.map((s) => [s.agent_id, s.name]));
const nameOf = (id: string) => nameById.get(id) ?? seatNameById.get(id) ?? id;
const liveNameById = new Map(selectedChain.seats.map((s) => [s.agent_id, s.live_name ?? null]));
const nameOf = (id: string) => liveNameById.get(id) ?? seatNameById.get(id) ?? id;
// 席位模型覆盖(链条配置):按 agent_id 取,空/缺省 = 跟随全局模型。
const modelById = new Map(selectedChain.seats.map((s) => [s.agent_id, s.model ?? null]));
const modelOf = (id: string) => modelById.get(id) ?? null;
@@ -235,8 +220,6 @@ export function BusinessChainPicker({
key={chain.id}
chain={chain}
selected={chain.id === selectedId}
isExisting={isExisting}
nameById={nameById}
onSelect={() => setSelectedId(chain.id)}
/>
))}
@@ -305,22 +288,22 @@ export function BusinessChainPicker({
function ChainCard({
chain,
selected,
isExisting,
nameById,
onSelect,
}: {
chain: BusinessChain;
selected: boolean;
isExisting: (agentId: string) => boolean;
nameById: Map<string, string>;
onSelect: () => void;
}) {
const survivingCount = chain.seats.filter((s) => isExisting(s.agent_id)).length;
// 席位存活与最新名称:读后端随链条响应算好的 seat.available / seat.live_name
// (undefined = 旧后端未标注 → 视为存活,名称回退落库快照 seat.name)。
const isExisting = (agentId: string) =>
chain.seats.find((s) => s.agent_id === agentId)?.available !== false;
const survivingCount = chain.seats.filter((s) => s.available !== false).length;
const deletedCount = chain.seats.length - survivingCount;
const usable = survivingCount >= CHAIN_MIN_SEATS;
// ── 席位编排(体现「同层并行 · 层间串行」)─────────────────────────────
// 名称回退表:实时 name(nameById)→ 落库快照(seat.name)→ agent_id。
// 名称回退表:实时名(live_name)→ 落库快照(seat.name)→ agent_id。
const seatById = new Map(chain.seats.map((s) => [s.agent_id, s] as const));
// 带 stages(分层编排)按 stages 渲染(过滤空阶段);否则每席位各成一段、顺序串行。
const stages =
@@ -338,8 +321,9 @@ function ChainCard({
}
// 单个席位 tag:存活按配色,已删除置灰删除线(保留旧行为)。
const seatTag = (agentId: string) => {
const seat = seatById.get(agentId);
const alive = isExisting(agentId);
const label = nameById.get(agentId) ?? seatById.get(agentId)?.name ?? agentId;
const label = seat?.live_name ?? seat?.name ?? agentId;
return (
<span
key={`tag-${agentId}`}
@@ -50,9 +50,9 @@ export interface DispatchChainModalProps {
title?: string;
status: JobStatus;
phase: JobPhase;
/** 当前轮次(0..maxCycles)。 */
/** 当前轮次。 */
cycle: number;
/** 最大轮次(默认 8,对齐 MAX_CYCLES)。 */
/** 第几轮强制进入总控纯正文收口;后台任务未携带启动快照时留空。 */
maxCycles?: number;
/** 派活链路节点(横向排列)。 */
nodes: DispatchChainNode[];
@@ -106,7 +106,7 @@ export function DispatchChainModal({
status,
phase,
cycle,
maxCycles = 8,
maxCycles,
nodes,
consensusPercentage,
onView,
@@ -333,7 +333,7 @@ export function DispatchChainModal({
<DialogFooter className="shrink-0 flex-row items-center justify-between gap-2 border-t pt-3 sm:justify-between">
<span className="text-xs text-muted-foreground">
轮次 {Math.min(cycle, maxCycles)}/{maxCycles}
轮次 {maxCycles == null ? cycle : `${Math.min(cycle, maxCycles)}/${maxCycles}`}
<span className="mx-2 text-muted-foreground/40">·</span>
共识 {Math.round(consensusPercentage)}%
<span className="mx-2 text-muted-foreground/40">·</span>
@@ -40,6 +40,29 @@ test("roundtable keeps ordinary streaming status beside a hidden control step",
assert.match(html, /正在生成正文/);
});
test("grep follows ordinary chat: description is the title and raw arguments stay hidden", () => {
const html = renderToStaticMarkup(
<MessageStepsCard
steps={[
{
id: "grep-1",
key: "tool_calling:grep:call_1",
label: "使用 grep 工具",
ts: "16:43:10",
args: {
description: "Verify no dangling truncation",
pattern: "truncation|…|\\[\\.\\.\\.\\]",
path: "/mnt/user-data/outputs/report.md",
},
},
]}
/>,
);
assert.match(html, /Verify no dangling truncation/);
assert.doesNotMatch(html, /pattern:|16:43:10|truncation\|/);
});
test("roundtable hides begin_write_file without hiding a real write_file step", () => {
const html = renderToStaticMarkup(
<MessageStepsCard
@@ -23,6 +23,7 @@ import {
} from "@/components/ai-elements/chain-of-thought";
import { Button } from "@/components/ui/button";
import { isInternalToolStepKey } from "@/core/tools/visibility";
import { isToolStepKey } from "@/roundtable-planning/lib/step-identity";
import { collectRoundtableDeliverablePaths } from "@/roundtable-planning/lib/streaming-artifacts";
import { cn } from "@/lib/utils";
import {
@@ -55,7 +56,7 @@ export interface MessageStepsCardProps {
/** 工具调用阶段的 step 才进入折叠卡;非工具步骤(connecting/streaming/tool_result)归到「思考」段。 */
function isToolStep(step: BubbleStep): boolean {
// `task`(派生子智能体)单独渲染成任务卡片(SubtaskCard),不在步骤折叠卡里重复展示。
if (step.key === "tool_calling:task") return false;
if (isToolStepKey(step.key, "task")) return false;
return step.key.startsWith("tool_calling:") && step.key.length > "tool_calling:".length;
}
@@ -101,7 +102,6 @@ export function MessageStepsCard({
>
<Icon className="size-3.5 text-slate-400" />
<span>{display.label}</span>
<span className="roundtable-chat-meta text-slate-400 font-mono">{lastReasoning.ts}</span>
</div>
);
}
@@ -204,9 +204,8 @@ function ToolStep({
: undefined
}
label={
<span className="roundtable-chat-message text-slate-700">
<span className="font-medium">{display.label}</span>
<span className="roundtable-chat-meta ml-2 text-slate-400 font-mono">{step.ts}</span>
<span className="roundtable-chat-message font-medium text-slate-700">
{display.label}
</span>
}
>
@@ -222,7 +221,6 @@ function ReasoningStep({ step, streaming }: { step: BubbleStep; streaming: boole
<div className="roundtable-chat-message flex items-center gap-2 text-slate-500">
<Icon className={cn("size-3.5", streaming ? "text-primary animate-pulse" : "text-slate-400")} />
<span>{display.label}</span>
<span className="roundtable-chat-meta text-slate-400 font-mono">{step.ts}</span>
</div>
);
}
@@ -207,7 +207,7 @@ export function RecommendAgentsDialog({
// 席位来源模式:智能推荐 / 业务链条。默认**业务链条**。
const [mode, setMode] = useState<"recommend" | "chain">("chain");
// 席位执行模式(快速/思考/专业问答/多智能体问答)——推荐 / 业务链条两种来源通用,
// 决定第二步每个子智能体席位的推理深度。默认 pro(= 改造前席位固定行为)。
// 决定第二步每个子智能体席位的推理深度。默认快速。
const [seatMode, setSeatMode] = useState<SeatMode>(DEFAULT_SEAT_MODE);
const [state, setState] = useState<InternalState>(INITIAL_STATE);
const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());
@@ -472,6 +472,13 @@ export function RecommendAgentsDialog({
cancelInflight();
};
}, [cancelInflight]);
// 该弹窗在关闭后仍保留在页面树中。每次重新打开时还原为「快速」,避免带入上一次
// 临时选择的模式;用户选中已配置执行模式的业务链条后,链条配置仍会正常覆盖该默认值。
useEffect(() => {
if (open) setSeatMode(DEFAULT_SEAT_MODE);
}, [open]);
useEffect(() => {
if (!open) {
recommendStartedRef.current = false;
@@ -24,6 +24,10 @@ import {
import { Sparkles } from "lucide-react";
import { streamJob } from "@/roundtable-planning/api/roundtable-jobs";
import {
isRoundtableCapacityFailure,
ROUNDTABLE_ROOM_FULL_MESSAGE,
} from "@/roundtable-planning/lib/capacity-error";
import type { RoundtableJob } from "@/roundtable-planning/lib/job-types";
interface RoundtableJobNotifierValue {
@@ -84,7 +88,11 @@ export function RoundtableJobNotifier({ children }: { children: ReactNode }) {
if (job.status === "done") {
setNotice("后台研讨已完成!可在「历史记录」查看结论与报告");
} else if (job.status === "error") {
setNotice("后台任务执行出错,请在「历史记录」中查看");
setNotice(
isRoundtableCapacityFailure(null, job.error)
? ROUNDTABLE_ROOM_FULL_MESSAGE
: "后台任务执行出错,请在「历史记录」中查看",
);
}
// cancelled:用户主动取消,不提示。
}, []);
@@ -43,7 +43,9 @@ const SHOW_BACKGROUND_SUSPEND = true;
import { AutoGrowTextarea } from "@/components/ui/auto-grow-textarea";
import { PositionIntentInput } from "@/position-roundtable/components/PositionIntentInput";
import { useLocalSettings } from "@/core/settings";
import { normalizeStreamingArtifactPath } from "@/core/artifacts/streaming-write-preview";
import { collectRoundtableDeliverablePaths } from "@/roundtable-planning/lib/streaming-artifacts";
import { isToolStepKey } from "@/roundtable-planning/lib/step-identity";
import { cn } from "@/lib/utils";
import type { MessageMetric } from "@/components/workspace/messages/use-message-metrics";
@@ -79,6 +81,7 @@ import type {
ParallelSeatView,
Step2Dialogue,
} from "@/roundtable-planning/hooks/useStep2Orchestration";
import { chainToDagPlan } from "@/roundtable-planning/lib/dag-types";
import type { OrchestrationPlan } from "@/roundtable-planning/lib/dag-types";
import type { ChainNodeState } from "@/roundtable-planning/lib/job-types";
import {
@@ -332,10 +335,19 @@ export function Step2Panel(props: Step2PanelProps) {
// ─── Phase 7 DAG 流程图执行态总览(§7)──────────────────────────────────
// 优化7(2026-06-13):推荐模式总控判定的**并行批**也能看流程图——把当前并行批
// 构造成一个临时单 stage 计划喂给小窗(dag 模式仍用真实 orchestrationPlan)。
// 2026-10-31:串行业务链(chain 模式)同样显示——按链条顺序(agentNameToRole 的
// speakerId = 链条序号 + 2,与 runChainOrchestration 的派活顺序同源)把每位还原成
// 单席位 stage,复用 chainToDagPlan 转成串行 DAG 计划,小窗逐层直角连线渲染。
const effectivePlan = useMemo<OrchestrationPlan | null>(() => {
if (orchestrationMode === "dag" && (orchestrationPlan?.stages.length ?? 0) > 0) {
return orchestrationPlan;
}
if (orchestrationMode === "chain") {
const orderedIds = Object.entries(agentNameToRole)
.sort((a, b) => a[1].speakerId - b[1].speakerId)
.map(([agentId]) => agentId);
if (orderedIds.length > 0) return chainToDagPlan(orderedIds);
}
if (isParallelRunning && parallelBatch.length > 1) {
return {
mode: "dag",
@@ -344,7 +356,7 @@ export function Step2Panel(props: Step2PanelProps) {
} as OrchestrationPlan;
}
return null;
}, [orchestrationMode, orchestrationPlan, isParallelRunning, parallelBatch]);
}, [orchestrationMode, orchestrationPlan, agentNameToRole, isParallelRunning, parallelBatch]);
const showDagFlow = (effectivePlan?.stages.length ?? 0) > 0;
const resolveDagSeat = useCallback(
(agentId: string, order: number) => {
@@ -371,13 +383,25 @@ export function Step2Panel(props: Step2PanelProps) {
for (const [aid, meta] of Object.entries(agentNameToRole)) {
if (deliveredNames.has(meta.displayName)) merged[aid.toLowerCase()] = "done";
}
// 串行业务链(chain 模式):流式中的席位气泡点亮为 active(dagNodeStates 只在 dag
// 编排里维护,chain 靠对话推导;完成后由上面的「子智能体交付」规则置 done)。
if (orchestrationMode === "chain") {
const streamingSenders = new Set(
step2RoundtableDialogues
.filter((d) => d.streaming)
.map((d) => String(d.sender ?? "")),
);
for (const [aid, meta] of Object.entries(agentNameToRole)) {
if (streamingSenders.has(meta.displayName)) merged[aid.toLowerCase()] = "active";
}
}
// 推荐并行批:running 席位点亮为 active、done 席位为 done(小窗实时转圈/打勾)。
for (const s of parallelBatch) {
merged[s.agentId.toLowerCase()] = s.status === "done" ? "done" : "active";
}
for (const [aid, st] of Object.entries(dagNodeStates)) merged[aid.toLowerCase()] = st;
return merged;
}, [dagNodeStates, step2RoundtableDialogues, agentNameToRole, parallelBatch]);
}, [dagNodeStates, step2RoundtableDialogues, agentNameToRole, parallelBatch, orchestrationMode]);
// 总控 / 共识 / 报告里程碑状态:由有效节点状态 + 编排/共识标志派生。
const { dagCoordinatorState, dagConsensusState } = useMemo(() => {
@@ -591,13 +615,21 @@ export function Step2Panel(props: Step2PanelProps) {
{/* Conversation log */}
<div className="relative flex-1 min-h-0 flex flex-col">
{/* 流程图小窗开关条(dag 编排 / 推荐并行批都显示)。 */}
{/* 流程图小窗开关条(dag 编排 / 串行业务链 / 推荐并行批都显示)。 */}
{showDagFlow && effectivePlan && (
<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">
{orchestrationMode === "dag"
? `分层编排执行中 · 共 ${effectivePlan.stages.length} 个阶段`
: `并行执行中 · ${effectivePlan.stages[0]?.agentIds.length ?? 0} 个席位`}
? isOrchestrating
? `分层编排执行中 · 共 ${effectivePlan.stages.length} 个阶段`
: `分层编排 · 共 ${effectivePlan.stages.length} 个阶段`
: orchestrationMode === "chain"
? isOrchestrating
? `链条顺序执行中 · 共 ${effectivePlan.stages.length} 个席位`
: `业务链条 · 共 ${effectivePlan.stages.length} 个席位`
: isOrchestrating
? `并行执行中 · ${effectivePlan.stages[0]?.agentIds.length ?? 0} 个席位`
: `并行编排 · ${effectivePlan.stages[0]?.agentIds.length ?? 0} 个席位`}
</span>
<button
type="button"
@@ -1209,22 +1241,28 @@ function collectPresentedFiles(
if (toolSteps.length === 0 && (!settledArtifactPaths || settledArtifactPaths.length === 0)) return [];
const out: string[] = [];
const seen = new Set<string>();
// 查重 / 输出统一用后端 artifacts 接口的虚拟路径形态(trim + 去前导 `/`):
// 工具步骤里模型写的是 `/mnt/user-data/outputs/x.md`,落盘扫描
// (listSessionArtifacts)返回的是 `mnt/user-data/outputs/x.md` —— 同一文件两种
// 写法若按原始字符串查重会被当成两个文件,气泡下方出现两张一模一样的文件卡片。
// 预览兼容性:无前导斜杠是 buildArtifactDownloadUrl 的文档形态,且后端
// coerce_artifact_virtual_path 对两种形态都放行;stub 反查失配时还有按文件名的兜底。
const canonical = (fp: string) => normalizeStreamingArtifactPath(fp).replace(/^\/+/, "");
const add = (fp: unknown, requirePreviewable = false) => {
if (typeof fp !== "string" || !fp || seen.has(fp)) return;
if (typeof fp !== "string" || !fp.trim()) return;
const key = canonical(fp);
if (!key || seen.has(key)) return;
if (requirePreviewable && collectRoundtableDeliverablePaths([fp]).length === 0) return;
seen.add(fp);
out.push(fp);
seen.add(key);
out.push(key);
};
for (const step of toolSteps) {
if (step.key === "tool_calling:present_files") {
if (isToolStepKey(step.key, "present_files")) {
const fps = step.args?.filepaths;
if (Array.isArray(fps)) fps.forEach((fp) => add(fp));
continue;
}
if (
step.key === "tool_calling:write_file" ||
step.key === "tool_calling:str_replace"
) {
if (isToolStepKey(step.key, "write_file") || isToolStepKey(step.key, "str_replace")) {
add(step.args?.path, true);
}
}
@@ -443,6 +443,7 @@ export function Step3SummaryMode({
error={error}
busy={busy}
mdAvailable={!!mdArtifact}
hasFlowGraph={!!flowGraph}
enableFlow={enableFlow}
flowPhase={summary.flowPhase}
onRegenerateFlow={summary.regenerateFlow}
@@ -593,6 +594,7 @@ function AgentProgressPanel({
error,
busy,
mdAvailable,
hasFlowGraph,
enableFlow,
flowPhase,
onRegenerateFlow,
@@ -617,6 +619,8 @@ function AgentProgressPanel({
busy: boolean;
/** 沙箱里是否已有 Markdown 总结报告。 */
mdAvailable: boolean;
/** 当前是否已有可展示的结构化流程图(历史草稿恢复 / 手动生成后才有)。 */
hasFlowGraph: boolean;
/** 普通会商才会生成、展示和编辑流程图。 */
enableFlow: boolean;
flowPhase: UseStep3SummaryReturn["flowPhase"];
@@ -906,7 +910,7 @@ function AgentProgressPanel({
<div className="flex items-center gap-2 text-xs font-bold text-emerald-600">
<CheckCircle className="w-4 h-4" />
{mdAvailable
? enableFlow
? enableFlow && hasFlowGraph
? "已生成方案总结报告与流程图,右侧可预览 / 下载 .md 或切换流程图。"
: "已生成方案总结报告,右侧可预览 / 下载 .md;可在下方继续修改报告或提问。"
: "已生成方案总结,可在下方继续修改报告或提问。"}
@@ -11,7 +11,7 @@
* 关键不变量:
* 1) special 顺序触发,**不要**改回 `Promise.all`(N 路 token 级 setState 会卡顿)。
* 2) 三段式气泡操作都通过 `id` 匹配,绝不用数组下标。
* 3) MAX_CYCLES=8 是死循环兜底,放宽前先评估对话列表的虚拟滚动。
* 3) 达到配置的 maxCycles 后必须走一次纯正文强制收口,不能直接停止或把未完成当共识。
* 4) 离开 Step 2 **不**清空 threadIds/dialogues,允许返回继续看。
*/
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
@@ -20,6 +20,10 @@ import {
artifactPreviewKey,
useArtifacts,
} from "@/components/workspace/artifacts";
import {
isRoundtableRoomFullError,
type RoundtableRoomFullError,
} from "@/roundtable-planning/api/rooms";
import {
initMultiAgent,
listSessionArtifacts,
@@ -57,16 +61,7 @@ function streamStepKey(
toolName?: string,
toolCallId?: string,
): string {
if (
phase === "tool_calling" &&
(toolName === "agent_orchestration" ||
toolName === "write_file" ||
toolName === "str_replace") &&
toolCallId
) {
return `${phase}:${toolName}:${toolCallId}`;
}
return `${phase}:${toolName ?? ""}`;
return toolStepKey(phase, toolName, toolCallId);
}
/** In-memory cursor for a business-chain human-validation pause. */
@@ -88,6 +83,11 @@ const PARALLEL_JUDGE_NOTE =
const INVALID_DELIVERY_CONFIDENCE = "交付无效(仅思考或中断)";
const FORCED_CLOSEOUT_TASK =
"已达到本次研讨的收口轮次。请停止继续派活,直接综合目前已经取得的全部席位交付," +
"输出一份合并后的最终方案与结论正文。不要按席位逐份复述原文,也不要反复改写同一份总结;" +
"如有席位未成功交付,请在结论中如实标明信息缺口,不要因缺口而省略总结,也不要调用任何工具。";
function isInvalidSeatStream(res: { invalidDelivery?: { reason: string } | null; content?: string | null }): boolean {
return !!res.invalidDelivery || !isValidSeatDelivery(res.content);
}
@@ -159,9 +159,10 @@ import {
} from "@/roundtable-planning/lib/dag-types";
import type { ChainNodeState } from "@/roundtable-planning/lib/job-types";
import { seatModeToRequestFields, type SeatMode } from "@/roundtable-planning/lib/seat-mode";
import { toolStepKey, upsertBubbleSteps } from "@/roundtable-planning/lib/step-identity";
import {
DEFAULT_MAX_CYCLES,
DEFAULT_SELECTED_AGENTS,
MAX_CYCLES,
buildAgentNameToRole,
buildRoleTemplates,
newCoordinatorName,
@@ -411,7 +412,7 @@ export interface UseStep2OrchestrationOptions {
/**
* 席位执行模式(快速/思考/专业问答/多智能体问答)。决定第二步**每个子智能体席位**
* 的推理深度(thinking/reasoning_effort/subagent);总控派活不受影响。由「选择参会
* 智能体」弹窗确认时的 `SeatSelectionResult.seatMode` 决定。缺省 `pro`。
* 智能体」弹窗确认时的 `SeatSelectionResult.seatMode` 决定。缺省 `flash`。
*/
selectedMode: SeatMode;
/**
@@ -442,6 +443,8 @@ export interface UseStep2OrchestrationOptions {
* 研讨真正启动时**取数一次(resetInitGate 复位后下一轮再取),澄清续跑/干预不重复取数。
*/
gatherFirst?: boolean;
/** 全局配置的总控强制收口轮数;一次编排启动时锁定,运行中修改只影响下一次研讨。 */
maxCycles?: number;
/**
* 编排模式:
* - `recommend`(默认)—— 总控自由派活循环(`runOrchestration`);
@@ -472,6 +475,14 @@ export interface UseStep2OrchestrationOptions {
setRoles: React.Dispatch<React.SetStateAction<RoleEntry[]>>;
/** 草稿 hook 共享的 ref;影响 init 期间是否跳过自动 SSE。 */
loadedFromDraftRef: React.MutableRefObject<boolean>;
/** 第二步房间闸门使用的草稿 / 任务范围。页面在渲染期写入。 */
roomScopeRef?: React.MutableRefObject<{
draftId: string | null;
taskId: string | null;
roomSessionId: string;
}>;
/** 服务端拒绝进入第二步时,由页面退回第一步并提示。 */
onRoomFull?: (message: string, activeCount: number, maxRooms: number) => void;
}
export interface UseStep2OrchestrationReturn {
@@ -602,6 +613,7 @@ export function useStep2Orchestration(
manualIntervention = false,
seatModes = {},
gatherFirst = false,
maxCycles = DEFAULT_MAX_CYCLES,
orchestrationMode,
orchestrationPlan,
dagExecMode = "sandbox",
@@ -609,7 +621,15 @@ export function useStep2Orchestration(
triggerToast,
setRoles,
loadedFromDraftRef,
roomScopeRef,
onRoomFull,
} = options;
const onRoomFullRef = useRef(onRoomFull);
onRoomFullRef.current = onRoomFull;
const maxCyclesRef = useRef(DEFAULT_MAX_CYCLES);
maxCyclesRef.current = Number.isFinite(maxCycles)
? Math.max(2, Math.min(100, Math.trunc(maxCycles)))
: DEFAULT_MAX_CYCLES;
const {
artifacts,
@@ -1767,41 +1787,15 @@ export function useStep2Orchestration(
const dialogue = prev[dialogueIndex];
const steps: Step2Dialogue["steps"] = dialogue.steps ?? [];
const last = steps[steps.length - 1];
let nextDialogue: Step2Dialogue;
if (last && last.key === key) {
// 总控派活的 task 是 tool_call JSON 的流式增量。不能沿用普通工具的
// 「首次可见参数即停」策略,否则只显示 agent_name,整段任务会在收尾时
// 才被最终消息一次性补上。
if (key.startsWith("tool_calling:agent_orchestration:") && args) {
const mergedArgs = { ...(last.args ?? {}), ...args };
if (JSON.stringify(last.args ?? {}) === JSON.stringify(mergedArgs)) {
return prev;
}
const nextSteps = [...steps];
nextSteps[nextSteps.length - 1] = { ...last, args: mergedArgs };
nextDialogue = { ...dialogue, steps: nextSteps };
} else {
// 同一个工具调用在流式期间会反复带来增量入参。步骤卡只需在「首次拿到
// 可见参数」时补一次;文件正文由 upstream frame 同步给沙箱,不能随每个
// content chunk 更新对话 state。
const hasVisibleArgs = (value?: Record<string, unknown>) =>
!!value && Object.keys(value).some((argKey) => argKey !== "content");
if (hasVisibleArgs(last.args) || !hasVisibleArgs(args)) return prev;
const nextSteps = [...steps];
nextSteps[nextSteps.length - 1] = { ...last, args };
nextDialogue = { ...dialogue, steps: nextSteps };
}
} else {
nextDialogue = {
...dialogue,
steps: [
...steps,
{ id: `${bubbleId}-${steps.length}`, key, label, ts: nowTime(), args },
],
};
}
const nextSteps = upsertBubbleSteps(steps, {
id: `${bubbleId}-${steps.length}`,
key,
label,
ts: nowTime(),
args,
});
if (nextSteps === steps) return prev;
const nextDialogue: Step2Dialogue = { ...dialogue, steps: nextSteps };
const next = [...prev];
next[dialogueIndex] = nextDialogue;
@@ -2219,12 +2213,31 @@ export function useStep2Orchestration(
abortAllInFlight();
}, [abortAllInFlight]);
const handleRoomFull = useCallback(
(error: RoundtableRoomFullError) => {
orchestrationCancelRef.current = true;
abortAllInFlight();
const handler = onRoomFullRef.current;
if (handler) {
handler(error.message, error.activeCount, error.maxRooms);
} else {
triggerToast(error.message);
}
},
[abortAllInFlight, triggerToast],
);
// ─── Orchestration loop ──────────────────────────────────────────
// 1) leader call → 2) 顺序派 special → 3) 综合 prompt 再 leader …
// 直到 leader.dispatched===[] (共识) 或循环达到 MAX_CYCLES。
// 直到 leader.dispatched===[](共识);到配置轮数时固定切为纯正文收口,绝不直接停止。
// **不要并行 special**(详见文件顶部注释)。
const runOrchestration = useCallback(
async (seedMessage: string, ids: ThreadIdMap, coord: string) => {
async (
seedMessage: string,
ids: ThreadIdMap,
coord: string,
finalizeOnly = false,
) => {
if (isOrchestratingRef.current) return;
// **同步**抢占编排锁。isOrchestratingRef 平时由 [isOrchestrating] 的 effect 异步
// 回写(见上方),滞后一拍;若只靠它,人工干预里 setIsRoundTableRunning(true) 触发的
@@ -2240,6 +2253,8 @@ export function useStep2Orchestration(
// 后者专治新循环重置 orchestrationCancelRef=false 把旧循环反取消的并发双发。
const isStale = () =>
orchestrationCancelRef.current || orchestrationEpochRef.current !== myEpoch;
// 本轮启动时锁定设置,避免管理员中途修改导致正在运行的会商突然改变收口点。
const cycleLimit = maxCyclesRef.current;
// 串/并行交给**总控判断**(2026-06-13):各席位子任务相互独立 → 同一轮一次性
// 派给多个席位(前端并行执行,单列可写显示);有先后依赖 → 每轮只派一个。
@@ -2275,6 +2290,9 @@ export function useStep2Orchestration(
const specRes = await streamMultiAgent({
agentType: "special",
dAgentThreadId: ids,
draftId: roomScopeRef?.current.draftId ?? undefined,
taskId: roomScopeRef?.current.taskId ?? undefined,
roomSessionId: roomScopeRef?.current.roomSessionId,
agentName: a.agentId,
displayName: a.displayName,
newMessage: fullTask,
@@ -2326,6 +2344,9 @@ export function useStep2Orchestration(
finalizeDialogue(a.bubbleId, "(已停止)", "已停止");
return { content: "", aborted: true, invalid: false };
}
if (isRoundtableRoomFullError(err)) {
throw err;
}
if (attempt === 0) {
// 第一次失败 → 清掉半截内容,自动重试一次。
console.warn(`[special:${a.agentId}] 第一次失败,自动重试:`, err);
@@ -2346,8 +2367,9 @@ export function useStep2Orchestration(
let safetyCounter = 0;
try {
while (!isStale() && safetyCounter < MAX_CYCLES) {
while (!isStale() && safetyCounter < cycleLimit) {
safetyCounter += 1;
const forceCloseout = finalizeOnly || safetyCounter === cycleLimit;
// Leader(协调智能体)正在派活,**不应该**让任何 sub agent 显示"研讨中"——
// 协调者本身不在右侧"参与角色"面板里(COMMANDER_SEAT_ID=1 是人类主持人,
// sub agent 从 id=2 起)。历史代码这里写的是 `highlightSpeaker(2)`,会
@@ -2357,8 +2379,8 @@ export function useStep2Orchestration(
// 高亮哪个。activeSpeakerId 同步置空,圆桌可视化也不会高亮错的位置。
highlightSpeaker(null);
// 总控也可能直接 write_file —— 之前只接了 special 流,导致总控写文件时沙箱不自动打开。
// 这里把 leader thread id 绑到气泡 + artifact handler 上,与 special 同样的行为。
// 总控 thread id 仍绑定气泡用于线程追踪。总控工具面由后端白名单控制;最终收口
// 使用 finalizeOnly 纯正文模式,不会再进入文件工具循环。
const leaderThreadId = resolveSeatThreadId(ids, coord);
const leaderBubbleId = appendStreamingDialogue({
sender: "总控协调",
@@ -2375,11 +2397,15 @@ export function useStep2Orchestration(
leaderRes = await streamMultiAgent({
agentType: "leader",
dAgentThreadId: ids,
draftId: roomScopeRef?.current.draftId ?? undefined,
taskId: roomScopeRef?.current.taskId ?? undefined,
roomSessionId: roomScopeRef?.current.roomSessionId,
agentName: coord,
newMessage: nextLeaderTask,
newMessage: forceCloseout ? FORCED_CLOSEOUT_TASK : nextLeaderTask,
// 第 2 轮起(已有席位交付)才是「综合轮」:让后端注入各席位完整交付供总控收口。
// 首轮纯派活、无交付,传 false 保持上下文精简。
synthesisMode: safetyCounter > 1,
synthesisMode: forceCloseout || safetyCounter > 1,
finalizeOnly: forceCloseout,
// 总控 prompt 含派活/编排指令,只能进入总控 thread。任何轮次都禁止广播到席位历史,
// 否则弱模型会模仿总控并声称要加载编排技能。席位上下文由具体 task 与交付广播提供。
suppressPreBroadcast: true,
@@ -2412,6 +2438,11 @@ export function useStep2Orchestration(
finalizeDialogue(leaderBubbleId, "(已停止)", "已停止");
break;
}
finalizeDialogue(
leaderBubbleId,
`(错误) ${(err as Error).message}`,
"调用失败",
);
throw err;
}
activeAbortersRef.current.delete(leaderAborter);
@@ -2431,17 +2462,19 @@ export function useStep2Orchestration(
break;
}
const closeoutReached =
forceCloseout || leaderRes.dispatched.length === 0;
finalizeDialogue(
leaderBubbleId,
leaderRes.content,
leaderRes.dispatched.length === 0 ? "全案盖印" : "派活说明",
closeoutReached ? "全案盖印" : "派活说明",
);
if (leaderRes.content) {
setLastLeaderContent(leaderRes.content);
}
if (leaderRes.dispatched.length === 0) {
if (closeoutReached) {
highlightSpeaker(null);
setConsensusPercentage(100);
setHasConsensus(true);
@@ -2560,11 +2593,12 @@ export function useStep2Orchestration(
nextLeaderTask = buildLeaderContinueTask(invalidNames);
}
if (safetyCounter >= MAX_CYCLES) {
triggerToast("⏱️ 已达到最大研讨轮次,自动停止以避免循环");
}
} catch (err) {
console.error("orchestration error:", err);
if (isRoundtableRoomFullError(err)) {
handleRoomFull(err);
return;
}
triggerToast(`研讨异常: ${(err as Error).message}`);
} finally {
highlightSpeaker(null);
@@ -2592,6 +2626,7 @@ export function useStep2Orchestration(
handleUpstreamFrame,
ingestSubagentTaskFrame,
resolveSeatThreadId,
handleRoomFull,
],
);
@@ -2661,6 +2696,9 @@ export function useStep2Orchestration(
leaderRes = await streamMultiAgent({
agentType: "leader",
dAgentThreadId: ids,
draftId: roomScopeRef?.current.draftId ?? undefined,
taskId: roomScopeRef?.current.taskId ?? undefined,
roomSessionId: roomScopeRef?.current.roomSessionId,
agentName: coord,
newMessage: leaderTask,
// 链条首轮同样不能把「请总控调用 agent_orchestration」广播进席位 thread。
@@ -2692,6 +2730,11 @@ export function useStep2Orchestration(
finishedAllSeats = false;
break;
}
finalizeDialogue(
leaderBubbleId,
`(错误) ${(err as Error).message}`,
"调用失败",
);
throw err;
}
activeAbortersRef.current.delete(leaderAborter);
@@ -2744,6 +2787,9 @@ export function useStep2Orchestration(
const specRes = await streamMultiAgent({
agentType: "special",
dAgentThreadId: ids,
draftId: roomScopeRef?.current.draftId ?? undefined,
taskId: roomScopeRef?.current.taskId ?? undefined,
roomSessionId: roomScopeRef?.current.roomSessionId,
agentName: seat.agent_id,
displayName: seatName,
newMessage: task,
@@ -2788,6 +2834,8 @@ export function useStep2Orchestration(
if (subAborter.signal.aborted || (err as Error).name === "AbortError") {
finalizeDialogue(subBubbleId, "(已停止)", "已停止");
aborted = true;
} else if (isRoundtableRoomFullError(err)) {
throw err;
} else {
console.error(`[chain-special:${seat.agent_id}] error:`, err);
finalizeDialogue(subBubbleId, `(错误) ${(err as Error).message}`, "调用失败");
@@ -2861,11 +2909,15 @@ export function useStep2Orchestration(
const closeoutRes = await streamMultiAgent({
agentType: "leader",
dAgentThreadId: ids,
draftId: roomScopeRef?.current.draftId ?? undefined,
taskId: roomScopeRef?.current.taskId ?? undefined,
roomSessionId: roomScopeRef?.current.roomSessionId,
agentName: coord,
newMessage:
"各链条席位已按顺序完成发言,请你综合所有席位的交付,输出最终方案与结论。不要再派活、不要再向任何席位分配任务。",
// 链条收口就是综合轮:让后端注入各席位完整交付正文。
synthesisMode: true,
finalizeOnly: true,
// 削减重复广播:收口轮不派活、研讨已结束,把总控收口 prompt 播进席位 thread 纯浪费,suppress。
suppressPreBroadcast: true,
model: selectedModelRef.current || undefined,
@@ -2893,6 +2945,8 @@ export function useStep2Orchestration(
} catch (err) {
if (closeoutAborter.signal.aborted || (err as Error).name === "AbortError") {
finalizeDialogue(closeoutBubbleId, "(已停止)", "已停止");
} else if (isRoundtableRoomFullError(err)) {
throw err;
} else {
console.error("chain closeout error:", err);
finalizeDialogue(closeoutBubbleId, `(错误) ${(err as Error).message}`, "调用失败");
@@ -2903,6 +2957,10 @@ export function useStep2Orchestration(
}
} catch (err) {
console.error("chain orchestration error:", err);
if (isRoundtableRoomFullError(err)) {
handleRoomFull(err);
return;
}
triggerToast(`链条研讨异常: ${(err as Error).message}`);
} finally {
highlightSpeaker(null);
@@ -2928,6 +2986,7 @@ export function useStep2Orchestration(
resolveSeatThreadId,
pauseForHumanValidation,
runOrchestration,
handleRoomFull,
],
);
@@ -3043,6 +3102,9 @@ export function useStep2Orchestration(
leaderRes = await streamMultiAgent({
agentType: "leader",
dAgentThreadId: ids,
draftId: roomScopeRef?.current.draftId ?? undefined,
taskId: roomScopeRef?.current.taskId ?? undefined,
roomSessionId: roomScopeRef?.current.roomSessionId,
agentName: coord,
newMessage: leaderTask,
// 派活轮:传 false,后端只注入各席位摘要;完整交付正文留给末尾收口的 synthesis 轮。
@@ -3076,6 +3138,11 @@ export function useStep2Orchestration(
finishedAllStages = false;
break;
}
finalizeDialogue(
leaderBubbleId,
`(错误) ${(err as Error).message}`,
"调用失败",
);
throw err;
}
activeAbortersRef.current.delete(leaderAborter);
@@ -3166,6 +3233,9 @@ export function useStep2Orchestration(
const specRes = await streamMultiAgent({
agentType: "special",
dAgentThreadId: ids,
draftId: roomScopeRef?.current.draftId ?? undefined,
taskId: roomScopeRef?.current.taskId ?? undefined,
roomSessionId: roomScopeRef?.current.roomSessionId,
agentName: agentId,
displayName: seatName,
newMessage: task,
@@ -3223,6 +3293,8 @@ export function useStep2Orchestration(
if (subAborter.signal.aborted || (err as Error).name === "AbortError") {
finalizeDialogue(bubbleId, "(已停止)", "已停止");
markBatchStatus(agentId, "done");
} else if (isRoundtableRoomFullError(err)) {
throw err;
} else {
console.error(`[dag-special:${agentId}] error:`, err);
finalizeDialogue(bubbleId, `(错误) ${(err as Error).message}`, "调用失败");
@@ -3299,6 +3371,7 @@ export function useStep2Orchestration(
: "各阶段席位已按依赖编排完成交付。请你作为总控,综合各席位的交付:若仍需补充则继续派活,否则直接输出最终方案并收口。",
ids,
coord,
dagInvalidNames.length === 0,
);
return;
} else if (!isStale() && finishedAllStages) {
@@ -3309,6 +3382,10 @@ export function useStep2Orchestration(
}
} catch (err) {
console.error("dag orchestration error:", err);
if (isRoundtableRoomFullError(err)) {
handleRoomFull(err);
return;
}
triggerToast(`依赖编排研讨异常: ${(err as Error).message}`);
} finally {
highlightSpeaker(null);
@@ -3340,6 +3417,7 @@ export function useStep2Orchestration(
resetParallelStreams,
runOrchestration,
pauseForHumanValidation,
handleRoomFull,
],
);
@@ -3395,6 +3473,9 @@ export function useStep2Orchestration(
const specRes = await streamMultiAgent({
agentType: "special",
dAgentThreadId: ids,
draftId: roomScopeRef?.current.draftId ?? undefined,
taskId: roomScopeRef?.current.taskId ?? undefined,
roomSessionId: roomScopeRef?.current.roomSessionId,
agentName: agentId,
displayName: seatName,
newMessage: GATHER_TASK,
@@ -3425,6 +3506,9 @@ export function useStep2Orchestration(
return visible.trim() ? { name: seatName, content: visible } : null;
} catch (err) {
activeAbortersRef.current.delete(subAborter);
if (isRoundtableRoomFullError(err)) {
throw err;
}
// 取数失败不阻断研讨:该席位无资料即可,研讨阶段它仍可自行检索。
finalizeDialogue(bubbleId, `(取数失败) ${(err as Error).message}`, "取数失败");
markBatchStatus(agentId, "done");
@@ -3468,6 +3552,10 @@ export function useStep2Orchestration(
try {
await runGatherPhase(ids);
} catch (err) {
if (isRoundtableRoomFullError(err)) {
handleRoomFull(err);
return;
}
console.warn("[roundtable] 研讨前并行取数阶段失败,跳过取数继续研讨:", err);
}
}
@@ -3486,7 +3574,13 @@ export function useStep2Orchestration(
}
return runOrchestration(seedMessage, ids, coord);
},
[runGatherPhase, runOrchestration, runChainOrchestration, runDagOrchestration],
[
handleRoomFull,
runGatherPhase,
runOrchestration,
runChainOrchestration,
runDagOrchestration,
],
);
// ─── Effects ─────────────────────────────────────────────────────
@@ -3516,10 +3610,14 @@ export function useStep2Orchestration(
setHasConsensus(false);
const coord = newCoordinatorName();
try {
const roomScope = roomScopeRef?.current;
const initRes = await initMultiAgent({
agentNames: roundtableAgentIds,
mainAgentName: coord,
model: selectedModelRef.current || undefined,
draftId: roomScope?.draftId ?? undefined,
taskId: roomScope?.taskId ?? undefined,
roomSessionId: roomScope?.roomSessionId,
onSeatReady: ({ agentName }) => {
if (cancelled) return;
const id = agentName.toLowerCase();
@@ -3549,6 +3647,10 @@ export function useStep2Orchestration(
} catch (err) {
console.error("init multi-agent failed:", err);
if (cancelled) return;
if (isRoundtableRoomFullError(err)) {
handleRoomFull(err);
return;
}
setInitError((err as Error).message);
triggerToast(`初始化失败: ${(err as Error).message}`);
} finally {
@@ -3848,8 +3950,8 @@ export function useStep2Orchestration(
return {
...d,
streaming: false,
content: hasText ? d.content : "(已结束)",
confidence: "已结束",
content: hasText ? d.content : "(上次运行中断)",
confidence: "已中断",
};
}),
);
@@ -45,6 +45,8 @@ interface UseStep3DashboardOptions {
seatDeliveries: Array<{ sender: string; content: string }>;
consensusText: string;
selectedModel: string;
/** Stable room identity; transparent to the Step-3 interaction. */
roomScopeRef?: { current: { draftId: string | null; taskId: string | null; roomSessionId: string } };
/** 当前界面主题 —— 大屏按它取色(light=浅红色 UI 规范 / dark=深蓝色 UI 规范)。 */
themeMode: "light" | "dark";
savedReport?: DraftStep3Snapshot | null;
@@ -119,6 +121,7 @@ export function useStep3Dashboard(options: UseStep3DashboardOptions): UseStep3Da
seatDeliveries,
consensusText,
selectedModel,
roomScopeRef,
themeMode,
savedReport,
onReportSaved,
@@ -303,7 +306,12 @@ export function useStep3Dashboard(options: UseStep3DashboardOptions): UseStep3Da
const { bubbleId, message, aborter } = args;
let threadId = liveThreadRef.current;
if (!threadId) {
const init = await initDashboardThread({ signal: aborter.signal });
const init = await initDashboardThread({
signal: aborter.signal,
draftId: roomScopeRef?.current.draftId ?? undefined,
taskId: roomScopeRef?.current.taskId ?? undefined,
roomSessionId: roomScopeRef?.current.roomSessionId,
});
if (aborter.signal.aborted) return;
threadId = init.threadId;
agentNameRef.current = init.agentName || DASH_AGENT_FALLBACK;
@@ -333,6 +341,9 @@ export function useStep3Dashboard(options: UseStep3DashboardOptions): UseStep3Da
agentType: "special",
agentName: agentNameRef.current,
dAgentThreadId: { [agentNameRef.current]: threadId },
draftId: roomScopeRef?.current.draftId ?? undefined,
taskId: roomScopeRef?.current.taskId ?? undefined,
roomSessionId: roomScopeRef?.current.roomSessionId,
displayName: "大屏绘制",
newMessage: message,
model: selectedModel || undefined,
@@ -62,6 +62,8 @@ interface UseStep3ReportOptions {
seatDeliveries: ReportSeatDelivery[];
consensusText: string;
selectedModel: string;
/** Stable room identity; transparent to the Step-3 interaction. */
roomScopeRef?: { current: { draftId: string | null; taskId: string | null; roomSessionId: string } };
/** 草稿里已存的上次绘制结果 —— 有则进入时恢复展示,不重新绘制。 */
savedReport?: DraftStep3Snapshot | null;
/** 一次绘制成功完成时回调(传出 html/model/时间/收尾语),供上层存草稿。 */
@@ -257,8 +259,15 @@ function reportPhaseLabel(phase: StreamPhase, toolName?: string): string {
export function useStep3Report(
options: UseStep3ReportOptions,
): UseStep3ReportReturn {
const { intentReady, seatDeliveries, consensusText, selectedModel, savedReport, onReportSaved } =
options;
const {
intentReady,
seatDeliveries,
consensusText,
selectedModel,
roomScopeRef,
savedReport,
onReportSaved,
} = options;
// 页面主题:浅色沿用浅红效果,深色让报告智能体按「深蓝 UI 规范」绘制。
const { theme: activeTheme } = useTheme();
@@ -797,6 +806,9 @@ export function useStep3Report(
agentType: "special",
agentName,
dAgentThreadId: { [agentName]: threadId },
draftId: roomScopeRef?.current.draftId ?? undefined,
taskId: roomScopeRef?.current.taskId ?? undefined,
roomSessionId: roomScopeRef?.current.roomSessionId,
displayName: "方案总结",
newMessage: prompt,
model: selectedModel || undefined,
@@ -905,7 +917,12 @@ export function useStep3Report(
bubbleIdRef.current = bubbleId;
try {
const { agentName, threadId } = await initReportThread({ signal: aborter.signal });
const { agentName, threadId } = await initReportThread({
signal: aborter.signal,
draftId: roomScopeRef?.current.draftId ?? undefined,
taskId: roomScopeRef?.current.taskId ?? undefined,
roomSessionId: roomScopeRef?.current.roomSessionId,
});
if (aborter.signal.aborted) return;
liveThreadRef.current = threadId;
agentNameRef.current = agentName;
@@ -991,7 +1008,12 @@ export function useStep3Report(
prompt = buildInterjectPrompt(text, theme);
} else {
setPhase("creating");
const init = await initReportThread({ signal: aborter.signal });
const init = await initReportThread({
signal: aborter.signal,
draftId: roomScopeRef?.current.draftId ?? undefined,
taskId: roomScopeRef?.current.taskId ?? undefined,
roomSessionId: roomScopeRef?.current.roomSessionId,
});
if (aborter.signal.aborted) return;
threadId = init.threadId;
liveThreadRef.current = threadId;
@@ -40,7 +40,7 @@ import {
type Step2Dialogue,
type StubAiMessage,
} from "@/roundtable-planning/hooks/useStep2Orchestration";
import { detectFlowIntent, extractFlowGraph, hasFlowFence, serializeFlowGraph, type FlowGraphData } from "@/roundtable-planning/lib/flow-graph";
import { extractFlowGraph, hasFlowFence, serializeFlowGraph, type FlowGraphData } from "@/roundtable-planning/lib/flow-graph";
import {
classifyFlowIntent,
classifyIngestIntent,
@@ -48,7 +48,22 @@ import {
type FlowIntent,
} from "@/roundtable-planning/api/flow-extract";
import { nowTime } from "@/roundtable-planning/lib/roundtable-constants";
import { readActionDetail } from "@/core/auth/task-deeplink";
import { cbwModelLines, readActionDetail } from "@/core/auth/task-deeplink";
/** xdfx(7BF)总结材料里的行动名称与传播网。其它业务不带;cbwId 为空时名称也不带。 */
function xdfxActionMaterial(businessCode: string | null | undefined): {
actionName: string | null;
cbwId: string | null;
cbwName: string;
} {
if (businessCode !== "7BF") return { actionName: null, cbwId: null, cbwName: "" };
const action = readActionDetail();
return {
actionName: action?.actionName ?? null,
cbwId: action?.cbwId ?? null,
cbwName: action?.cbwName ?? "",
};
}
/** 报告输出文件的固定虚拟路径(恢复历史快照时用它重建 stub)。 */
const SUMMARY_OUTPUT_PATH = "/mnt/user-data/outputs/方案总结报告.md";
@@ -64,6 +79,8 @@ interface UseStep3SummaryOptions {
seatDeliveries: ReportSeatDelivery[];
consensusText: string;
selectedModel: string;
/** Stable room identity; transparent to the Step-3 interaction. */
roomScopeRef?: { current: { draftId: string | null; taskId: string | null; roomSessionId: string } };
/** 业务链写给总控的编排提示 —— 作为最高优先级口径注入总结智能体。 */
coordinatorPrompt?: string | null;
/**
@@ -183,14 +200,20 @@ function buildMaterials(opts: {
coordinatorPrompt?: string | null;
/** xdfx:本次「行动名称」,作为材料抬头喂进总结(报告围绕该行动展开)。 */
actionName?: string | null;
/** xdfx:传播网 id。为 null 时传播网名称也不写入材料。 */
cbwId?: unknown;
/** xdfx:传播网名称。 */
cbwName?: unknown;
}): string {
const { intentReady, seatDeliveries, consensusText, coordinatorPrompt, actionName } = opts;
const { intentReady, seatDeliveries, consensusText, coordinatorPrompt, actionName, cbwId, cbwName } = opts;
const parts: string[] = [];
const an = actionName?.trim();
if (an) {
const cbwLines = cbwModelLines(cbwId, cbwName);
if (an || cbwLines.length > 0) {
parts.push("# 本次行动");
parts.push(an);
if (an) parts.push(an);
parts.push(...cbwLines);
parts.push("");
}
@@ -306,6 +329,8 @@ function buildSummaryPrompt(opts: {
consensusText: string;
coordinatorPrompt?: string | null;
actionName?: string | null;
cbwId?: unknown;
cbwName?: unknown;
flowMode?: boolean;
}): string {
const parts: string[] = [];
@@ -404,6 +429,9 @@ function buildResumeAskPrompt(opts: {
seatDeliveries: ReportSeatDelivery[];
consensusText: string;
coordinatorPrompt?: string | null;
actionName?: string | null;
cbwId?: unknown;
cbwName?: unknown;
previousMd: string;
userMessage: string;
/** 按本轮语境选好的意图引导指令(流程图显式 / 流程图上下文 / 普通语义),追加在消息后。 */
@@ -483,6 +511,7 @@ export function useStep3Summary(
seatDeliveries,
consensusText,
selectedModel,
roomScopeRef,
coordinatorPrompt,
chainLevels,
autoFlow,
@@ -1133,7 +1162,12 @@ export function useStep3Summary(
let threadId = seedThreadId ?? null;
let agentName = SUMMARY_AGENT_NAME;
if (!threadId) {
const init = await initSummaryThread({ signal: aborter.signal });
const init = await initSummaryThread({
signal: aborter.signal,
draftId: roomScopeRef?.current.draftId ?? undefined,
taskId: roomScopeRef?.current.taskId ?? undefined,
roomSessionId: roomScopeRef?.current.roomSessionId,
});
if (aborter.signal.aborted) return;
threadId = init.threadId;
agentName = init.agentName;
@@ -1153,6 +1187,9 @@ export function useStep3Summary(
agentType: "special",
agentName,
dAgentThreadId: { [agentName]: threadId },
draftId: roomScopeRef?.current.draftId ?? undefined,
taskId: roomScopeRef?.current.taskId ?? undefined,
roomSessionId: roomScopeRef?.current.roomSessionId,
displayName: "方案总结报告",
newMessage: prompt,
// 深链接业务码:后端为 summary 单例注入「业务链完整性核对」(核对产出相对业务链完不完整)。
@@ -1429,18 +1466,21 @@ export function useStep3Summary(
});
try {
// 编排提示里明确要求了结构化输出/流程图 → 首轮就走流程图模式(不写 md,直出 flow-json)。
// 但 autoFlow(taskId/深链)模式要「先 md 再结构化输出」,故首轮强制走 md(忽略 detectFlowIntent)。
const flowMode = flowEnabled && !autoFlow && detectFlowIntent(coordinatorPrompt);
// 首轮一律先出 md 报告。2026-10-31 第三步改为「报告完成即结束」——不再在报告后
// 自动续跑结构化流程图(autoFlow 由页面关掉),需要流程图走手动 / 入库路径;原先
// autoFlow=false 时 detectFlowIntent 命中编排提示要求就**直出 flow-json 不写 md** 的
// 「流程图优先」分支随之退役 —— 该分支在实际调用方从未走到过,保留反而会在页面关闭
// autoFlow 后被意外激活(不出报告)。
const flowMode = false;
flowActiveRef.current = flowMode; // 流式结束后会按真实产物校正
const prompt = buildSummaryPrompt({
intentReady,
seatDeliveries,
consensusText,
coordinatorPrompt,
// xdfx(7BF):把本次行动名称喂进总结材料,让报告围绕该行动展开。
actionName:
ingestBusinessCodeRef.current === "7BF" ? readActionDetail()?.actionName ?? null : null,
// xdfx(7BF):把本次行动名称和传播网喂进总结材料,让报告围绕该行动展开。
// cbwId 为 null 时 cbwModelLines 返回空,传播网名称也不写入。
...xdfxActionMaterial(ingestBusinessCodeRef.current),
flowMode,
});
await streamOnce({ bubbleId, prompt, aborter, flowRound: flowMode });
@@ -1567,7 +1607,12 @@ export function useStep3Summary(
const prompt = promptParts.join("\n");
try {
const init = await initStructureThread({ signal: aborter.signal });
const init = await initStructureThread({
signal: aborter.signal,
draftId: roomScopeRef?.current.draftId ?? undefined,
taskId: roomScopeRef?.current.taskId ?? undefined,
roomSessionId: roomScopeRef?.current.roomSessionId,
});
if (ingestRunRef.current !== myRun || aborter.signal.aborted) return;
const threadId = init.threadId;
const agentName = init.agentName;
@@ -1578,6 +1623,9 @@ export function useStep3Summary(
agentType: "special",
agentName,
dAgentThreadId: { [agentName]: threadId },
draftId: roomScopeRef?.current.draftId ?? undefined,
taskId: roomScopeRef?.current.taskId ?? undefined,
roomSessionId: roomScopeRef?.current.roomSessionId,
displayName: "数据入库",
newMessage: prompt,
model: selectedModel || undefined,
@@ -1795,7 +1843,12 @@ export function useStep3Summary(
let threadId = liveThreadRef.current;
if (hasFiles && !threadId) {
setPhase("creating");
const init = await initSummaryThread({ signal: aborter.signal });
const init = await initSummaryThread({
signal: aborter.signal,
draftId: roomScopeRef?.current.draftId ?? undefined,
taskId: roomScopeRef?.current.taskId ?? undefined,
roomSessionId: roomScopeRef?.current.roomSessionId,
});
if (aborter.signal.aborted) return;
threadId = init.threadId;
liveThreadRef.current = threadId;
@@ -1849,6 +1902,7 @@ export function useStep3Summary(
seatDeliveries,
consensusText,
coordinatorPrompt,
...xdfxActionMaterial(ingestBusinessCodeRef.current),
previousMd: currentMdRef.current,
userMessage:
text || "请阅读我上传的参考文件后,据此更新报告或回答。",
@@ -0,0 +1,126 @@
/**
* `buildChainSeatSelection` 存活/名称解析测试。
*
* 重点覆盖「无 candidates」分支:前端选链不再实时拉 /api/agents,席位存活与
* 最新名称来自链条响应自带的读时计算富化字段 `seat.available` / `seat.live_name`
* (undefined available = 旧后端未标注 → 视为存活,与旧版降级语义一致)。
* 传 candidates 的旧分支也一并回归(名称实时优先)。
*/
import assert from "node:assert/strict";
import test from "node:test";
import { buildChainSeatSelection, type BusinessChain, type ChainSeat } from "./business-chain";
import { DEFAULT_SEAT_MODE } from "./seat-mode";
const seat = (agent_id: string, name: string, extra: Partial<ChainSeat> = {}): ChainSeat => ({
agent_id,
name,
description: "",
...extra,
});
const chain = (seats: ChainSeat[], extra: Partial<BusinessChain> = {}): BusinessChain => ({
id: "c1",
title: "测试链",
seats,
...extra,
});
test("新建业务链与选人弹窗共用快速执行模式默认值", () => {
assert.equal(DEFAULT_SEAT_MODE, "flash");
});
test("无 candidates:available 缺省视为存活(旧后端兼容)", () => {
const result = buildChainSeatSelection(chain([seat("a", "A"), seat("b", "B")]));
assert.ok(result);
assert.equal(result.mode, "chain");
assert.deepEqual(
result.agents.map((x) => x.agent_id),
["a", "b"],
);
});
test("无 candidates:available=false 的席位被过滤", () => {
const result = buildChainSeatSelection(
chain([seat("a", "A"), seat("b", "B", { available: true }), seat("gone", "G", { available: false })]),
);
assert.ok(result);
assert.deepEqual(
result.agents.map((x) => x.agent_id),
["a", "b"],
);
});
test("无 candidates:存活不足 2 席返回 null", () => {
const ok = buildChainSeatSelection(
chain([seat("a", "A", { available: true }), seat("gone", "G", { available: false })]),
);
assert.equal(ok, null);
});
test("无 candidates:live_name 优先于落库快照名", () => {
const result = buildChainSeatSelection(
chain([seat("a", "旧名", { live_name: "新名" }), seat("b", "B")]),
);
assert.ok(result);
assert.equal(result.agents[0].name, "新名");
assert.equal(result.agents[1].name, "B");
});
test("无 candidates:live_name 为 null 时回退快照名(空快照名沿旧语义显示为空)", () => {
const result = buildChainSeatSelection(
chain([seat("a", "快照", { live_name: null }), seat("b", "B")]),
);
assert.ok(result);
assert.equal(result.agents[0].name, "快照");
assert.equal(result.agents[1].name, "B");
});
test("无 candidates:席位级 model/skill/humanValidation/seatMode 透传不变", () => {
const result = buildChainSeatSelection(
chain([
seat("a", "A", { model: "glm-4.7", seat_skill_directive: true, human_validation: true, seat_mode: "flash" }),
seat("b", "B"),
]),
);
assert.ok(result);
const [a] = result.agents;
assert.equal(a.model, "glm-4.7");
assert.equal(a.seat_skill_directive, true);
assert.equal(a.human_validation, true);
assert.equal(a.seatMode, "flash");
assert.equal(result.agents[1].model, null);
});
test("无 candidates:分层并行链仍走 dag 且只保留存活席位", () => {
const result = buildChainSeatSelection(
chain(
[seat("a", "A"), seat("b", "B"), seat("c", "C"), seat("gone", "G", { available: false })],
{ stages: [["a", "b", "gone"], ["c"]] },
),
);
assert.ok(result);
assert.equal(result.mode, "dag");
// dag 席位按 stage 展平;gone 被过滤后首阶段仍并行(2 席),保持 dag。
assert.deepEqual(
result.agents.map((x) => x.agent_id),
["a", "b", "c"],
);
});
test("传 candidates:按候选集判存活、实时名优先(旧分支回归)", () => {
const result = buildChainSeatSelection(
chain([seat("a", "旧名"), seat("b", "B"), seat("gone", "G")]),
[
{ agent_id: "a", name: "实时名" },
{ agent_id: "b", name: "B" },
{ agent_id: "other", name: "O" },
],
);
assert.ok(result);
assert.deepEqual(
result.agents.map((x) => x.agent_id),
["a", "b"],
);
assert.equal(result.agents[0].name, "实时名");
});
@@ -67,6 +67,19 @@ export interface ChainSeat {
* 随 `seats` JSON 落库(无需 DB 列)。空 / 缺省 = 未填写。
*/
job_responsibilities?: string | null;
/**
* 席位智能体当前是否可用(**读时计算,不落库**):后端返回链条时用一次批量
* 查询(与 `/api/agents` 同一套可见性过滤 + 功能型内置排除)算好随 seat 附带,
* 前端选链从此不再实时拉智能体列表。undefined = 旧后端未标注 → 视为存活
* (与旧版「agents 拉取失败不判删」的降级语义一致;真被删时 Step 2 init
* 的后端 404 硬校验兜底)。
*/
available?: boolean;
/**
* 席位智能体的最新名称(**读时计算,不落库**,改名同步用)。null / undefined
* = 查不到或旧后端 → 展示回退到 `name` 落库快照。
*/
live_name?: string | null;
}
/** 一条可复用的业务链条(与后端 `/api/roundtable-chains` 记录对应)。 */
@@ -96,7 +109,7 @@ export interface BusinessChain {
coordinatorPrompt?: string | null;
/**
* 默认席位执行模式(快速/思考/专业问答/多智能体)。选入研讨时弹窗默认用它(仍可临时改)。
* 缺省 = 未设,调用方回退 `DEFAULT_SEAT_MODE`(pro)。
* 缺省 = 未设,调用方回退 `DEFAULT_SEAT_MODE`(flash)。
*/
seatMode?: SeatMode;
/**
@@ -108,9 +121,8 @@ export interface BusinessChain {
/** 是否已发布为公共(所有账号可在「公共」筛选查看 / 选入研讨)。 */
isPublic?: boolean;
/**
* 「待审核」标记:true = 已在编辑器点「发布 → 确认审核」提交审核,等待管理员在
* 业务链条列表「待审核」筛选里发布;管理员发布时清回 false 并置 isPublic=true。
* 缺省 / false = 未在审核中(草稿或已发布)。
* 「待审核」标记(历史审核流遗留):现在发布已全部改为直接发布,前端不再产生该状态;
* 存量 true 的链条在列表中点发布即直接发布并清回 false。缺省 / false = 草稿或已发布。
*/
pendingReview?: boolean;
/**
@@ -118,6 +130,12 @@ export interface BusinessChain {
* 停用后管理弹窗仍可见,选链弹窗 / 公共入口不再选用。
*/
enabled?: boolean;
/**
* 管理员目录开关:true = 从所有普通列表(我的/公共/待审核/选链弹窗)隐藏,仅管理员
* 管理视图可见。纯目录开关:单条读取不受影响(已配置的业务映射 / 进行中的研讨继续
* 可用)。缺省 / false = 未隐藏。
*/
hidden?: boolean;
/** 是否当前用户所有(仅本人可编辑 / 删除 / 发布;公共筛选里别人的链条为 false)。 */
isMine?: boolean;
/** 配置者(owner)的可读用户名(后端解析的 email);解析失败时为空。 */
@@ -160,7 +178,7 @@ export interface SeatSelectionResult {
/**
* 席位执行模式(快速/思考/专业问答/多智能体问答)——决定第二步**每个子智能体席位**
* 的推理深度(thinking/reasoning_effort/subagent)。三种编排(recommend/chain/dag)通用。
* 缺省由调用方按 `DEFAULT_SEAT_MODE`(pro)处理。
* 缺省由调用方按 `DEFAULT_SEAT_MODE`(flash)处理。
*/
seatMode?: SeatMode;
/**
@@ -173,6 +191,11 @@ export interface SeatSelectionResult {
/** 业务链条席位数硬约束,必须与后端持久化校验保持一致。 */
export const CHAIN_MIN_SEATS = 2;
export const CHAIN_MAX_SEATS = 20;
/**
* 同一 Stage(并行研讨)的席位上限。stage 内并行、stage 间串行,并行过多会拖垮
* 时延与产出质量;需要更多席位请拆成多个串行 Stage。必须与后端 `_validate_stages` 一致。
*/
export const CHAIN_MAX_PARALLEL = 3;
/** 启停状态:缺省 / undefined 视为启用(存量链条无该字段)。 */
export function isChainEnabled(chain: Pick<BusinessChain, "enabled">): boolean {
@@ -180,24 +203,33 @@ export function isChainEnabled(chain: Pick<BusinessChain, "enabled">): boolean {
}
/**
* 由一条业务链条 + 当前候选智能体,构造 `SeatSelectionResult`。
* 由一条业务链条构造 `SeatSelectionResult`。
*
* 与 `BusinessChainPicker.handleUse` 同源逻辑,抽成纯函数供「自动选链」复用
* (会商自动化串联:从任务页带 chainId 进圆桌时跳过选链弹窗,直接据此进 Step 2):
* - 仅保留候选池里仍存在的存活席位;存活不足 `CHAIN_MIN_SEATS` 返回 null(调用方回退弹窗);
* - 仅保留**存活**席位;存活不足 `CHAIN_MIN_SEATS` 返回 null(调用方回退弹窗);
* - 链条带分层、过滤存活后仍含并行 stage / 任一阶段目标 / 总控提示 → 走 `dag`(默认 fast);
* - 否则走线性 `chain`,席位顺序 = 链条顺序。
*
* `candidates` 为 `{ agent_id, name }` 列表(一般来自 `filterRecommendCandidates(listAgents())`)。
* 存活与名称解析有两条等价来源(**二选一,都不查网**):
* - 不传 `candidates`(**推荐**):用 seat 上后端读时计算的富化字段——存活 =
* `seat.available !== false`(undefined 视为存活),名称 = `live_name ?? name ?? agent_id`。
* `/api/roundtable-chains` 响应自带这两个字段,选链零额外请求(网慢友好)。
* - 传 `candidates`(`{ agent_id, name }` 列表,来自 `filterRecommendCandidates(listAgents())`):
* 兼容旧调用方/测试——按候选集判存活、按实时名优先。
*/
export function buildChainSeatSelection(
chain: BusinessChain,
candidates: ReadonlyArray<{ agent_id: string; name: string }>,
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 existingIds = candidates ? new Set(candidates.map((c) => c.agent_id)) : null;
const liveNameById = candidates
? new Map(candidates.map((c) => [c.agent_id, c.name]))
: null;
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 seatLiveNameById = new Map(chain.seats.map((s) => [s.agent_id, s.live_name ?? null]));
const nameOf = (id: string) =>
liveNameById?.get(id) ?? seatLiveNameById.get(id) ?? seatNameById.get(id) ?? id;
// 席位模型覆盖(链条配置):按 agent_id 取,空/缺省 = 跟随全局。
const modelById = new Map(chain.seats.map((s) => [s.agent_id, s.model ?? null]));
const modelOf = (id: string) => modelById.get(id) ?? null;
@@ -213,7 +245,9 @@ export function buildChainSeatSelection(
const seatModeById = new Map(chain.seats.map((s) => [s.agent_id, s.seat_mode ?? null]));
const seatModeOf = (id: string) => seatModeById.get(id) ?? null;
const survivingSeats = chain.seats.filter((s) => existingIds.has(s.agent_id));
const survivingSeats = chain.seats.filter(
(s) => (existingIds ? existingIds.has(s.agent_id) : s.available !== false),
);
if (survivingSeats.length < CHAIN_MIN_SEATS) return null;
const chainMeta = { id: chain.id, title: chain.title };
@@ -0,0 +1,34 @@
import assert from "node:assert/strict";
import test from "node:test";
import {
isRoundtableCapacityFailure,
roundtableErrorForDisplay,
ROUNDTABLE_ROOM_FULL_MESSAGE,
} from "./capacity-error";
test("recognizes a direct HTTP 429", () => {
assert.equal(isRoundtableCapacityFailure(429, ""), true);
});
test("recognizes a 429 wrapped by the internal run stream gateway", () => {
const detail =
"[502] upstream http://127.0.0.1:8001/api/threads/thread-secret/runs/stream returned HTTP 429: busy";
assert.equal(isRoundtableCapacityFailure(502, detail), true);
assert.equal(roundtableErrorForDisplay(detail, 502), ROUNDTABLE_ROOM_FULL_MESSAGE);
});
test("recognizes local concurrency and worker saturation messages", () => {
assert.equal(
isRoundtableCapacityFailure(502, "This account has reached the concurrency limit for the selected model"),
true,
);
assert.equal(isRoundtableCapacityFailure(502, "执行节点繁忙,请稍后重试"), true);
assert.equal(isRoundtableCapacityFailure(502, "等待执行超时,请稍后重试"), true);
});
test("does not hide an unrelated gateway error", () => {
const detail = "upstream returned HTTP 502: connection refused";
assert.equal(isRoundtableCapacityFailure(502, detail), false);
assert.equal(roundtableErrorForDisplay(detail, 502), detail);
});
@@ -0,0 +1,63 @@
/** 会商容量不足时唯一允许展示给业务用户的文案。 */
export const ROUNDTABLE_ROOM_FULL_MESSAGE = "当前房间已满,请稍后";
/**
* 会商运行过程中遇到的容量错误。
*
* 原始响应只能写入控制台 / 诊断日志,不能放进 message,避免内网地址、thread id
* 等实现细节经现有的 toast / 对话气泡 / 错误面板泄露到页面。
*/
export class RoundtableRoomFullError extends Error {
activeCount: number;
maxRooms: number;
constructor(activeCount = 0, maxRooms = 0) {
super(ROUNDTABLE_ROOM_FULL_MESSAGE);
this.name = "RoundtableRoomFullError";
this.activeCount = activeCount;
this.maxRooms = maxRooms;
}
}
export function isRoundtableRoomFullError(error: unknown): error is RoundtableRoomFullError {
return (
error instanceof RoundtableRoomFullError ||
(error instanceof Error && error.name === "RoundtableRoomFullError")
);
}
/**
* Gateway 会把内部 `/runs/stream` 的 429 包装成 502 或 SSE error 帧,因此不能只看
* 最外层 HTTP 状态。这里同时识别包装后的状态文本和本地并发闸门的稳定错误文案。
*/
export function isRoundtableCapacityFailure(
status: number | null | undefined,
detail: string | null | undefined,
): boolean {
if (status === 429) return true;
const text = (detail ?? "").trim();
if (!text) return false;
if (text === ROUNDTABLE_ROOM_FULL_MESSAGE) return true;
return (
/returned\s+http\s+429\b/i.test(text) ||
/(?:status(?:_code)?|http(?:\s+status)?)\s*["':=]*\s*429\b/i.test(text) ||
/\b429\s+(?:too\s+many\s+requests|resource\s+exhausted)\b/i.test(text) ||
/\btoo\s+many\s+requests\b/i.test(text) ||
/\bconcurrency\s+limit\b/i.test(text) ||
/\bselected\s+model\s+is\s+busy\b/i.test(text) ||
/执行节点繁忙|等待执行超时|并发(?:数|量)?.*(?:上限|限制)|模型繁忙/.test(text)
);
}
/** 页面可展示的错误详情;容量错误永远折叠为统一文案。 */
export function roundtableErrorForDisplay(
detail: string | null | undefined,
status?: number | null,
): string | null {
if (detail == null) return null;
return isRoundtableCapacityFailure(status, detail)
? ROUNDTABLE_ROOM_FULL_MESSAGE
: detail;
}
@@ -113,6 +113,8 @@ export interface StartJobPayload {
* 其 draft_id 指向独立的 task-draft 存储(最终报告写回那里)。
*/
taskId?: string | null;
/** 当前页面这一次实时会商的隐藏并发标识;后台接管时续占同一名额。 */
roomSessionId?: string | null;
/** 任务意图;缺省 seedMessage 时用它作第一轮 leader prompt。 */
intent: string;
/** 有序席位(recommend=选择顺序 / chain=链条顺序)。 */
@@ -0,0 +1,31 @@
import assert from "node:assert/strict";
import test from "node:test";
import { isRoundtableRoomExecutionActive } from "./room-lifecycle";
test("the admitted room remains occupied throughout unfinished Step 2", () => {
assert.equal(
isRoundtableRoomExecutionActive({
currentStep: 2,
hasConsensus: false,
}),
true,
);
});
test("consensus and leaving Step 2 release the room", () => {
assert.equal(
isRoundtableRoomExecutionActive({
currentStep: 2,
hasConsensus: true,
}),
false,
);
assert.equal(
isRoundtableRoomExecutionActive({
currentStep: 3,
hasConsensus: true,
}),
false,
);
});
@@ -0,0 +1,11 @@
export interface RoundtableRoomExecutionState {
currentStep: number;
hasConsensus: boolean;
}
/** An admitted room is retained for the whole unfinished Step-2 session. */
export function isRoundtableRoomExecutionActive(
state: RoundtableRoomExecutionState,
): boolean {
return state.currentStep === 2 && !state.hasConsensus;
}
@@ -9,8 +9,8 @@ import type { IntentSummary } from "@/roundtable-planning/api/intent";
/** 指挥员(人类)所在的固定 seat id。Agent 席位从 2 开始排。 */
export const COMMANDER_SEAT_ID = 1;
/** 编排循环最大轮次。超出后 toast 强停以防死循环。 */
export const MAX_CYCLES = 8;
/** 服务端设置尚未加载或旧服务端缺少字段时的收口轮数默认值。 */
export const DEFAULT_MAX_CYCLES = 8;
/** Step 2 角色面板的一行。 */
export type RoleEntry = {
@@ -18,8 +18,8 @@
export type SeatMode = "flash" | "thinking" | "pro" | "ultra";
/** 默认档位:专业问答(pro)—— 与改造前席位的固定行为(thinking + medium)一致。 */
export const DEFAULT_SEAT_MODE: SeatMode = "pro";
/** 默认档位:快速(flash)—— 新建业务链和初次打开的选人弹窗均从此档位开始。 */
export const DEFAULT_SEAT_MODE: SeatMode = "flash";
/** 席位单轮 run 的派生参数(透传给 `/api/multi-agent/run/stream`,覆盖后端 policy 默认)。 */
export interface SeatRunParams {
@@ -64,10 +64,9 @@ export function renderStepArgs(
);
}
case "web_search":
case "image_search": {
const query = typeof args.query === "string" ? args.query : "";
return query ? <ChainOfThoughtSearchResult>{query}</ChainOfThoughtSearchResult> : null;
}
case "image_search":
// 检索词已经写进步骤标题,和普通对话一样不再另挂一条参数 chip。
return null;
case "web_fetch": {
const url = typeof args.url === "string" ? args.url : "";
return url ? <ChainOfThoughtSearchResult>{url}</ChainOfThoughtSearchResult> : null;
@@ -104,22 +103,9 @@ export function renderStepArgs(
</span>
) : null;
}
default: {
const entries = Object.entries(args).filter(
([, v]) => v !== null && v !== undefined && v !== "",
);
if (entries.length === 0) return null;
return (
<div className="flex flex-wrap gap-1">
{entries.slice(0, 4).map(([k, v]) => (
<ChainOfThoughtSearchResult key={k}>
<span className="opacity-60">{k}:</span>{" "}
{typeof v === "string" ? v : JSON.stringify(v)}
</ChainOfThoughtSearchResult>
))}
</div>
);
}
default:
// grep 等工具与普通对话一致:只显示 description 标题,不展开 pattern/path。
return null;
}
}
@@ -185,8 +171,11 @@ export function getStepDisplay(
case "agent_orchestration":
// 圆桌特有的「派活」工具,主聊天没有;用扳手图标承载。
return { icon: WrenchIcon, label: "派活给子智能体" };
default:
return { icon: WrenchIcon, label: `使用 “${toolName}” 工具` };
default: {
const desc =
typeof args?.description === "string" ? args.description.trim() : "";
return { icon: WrenchIcon, label: desc || `使用 “${toolName}” 工具` };
}
}
}
if (phase === "streaming") {
@@ -0,0 +1,75 @@
import assert from "node:assert/strict";
import test from "node:test";
import { toolStepKey, upsertBubbleSteps, type BubbleToolStep } from "./step-identity.ts";
function step(partial: Partial<BubbleToolStep> & Pick<BubbleToolStep, "key">): BubbleToolStep {
return {
id: partial.id ?? partial.key,
key: partial.key,
label: partial.label ?? partial.key,
ts: partial.ts ?? "16:43:10",
args: partial.args,
};
}
test("one grep call stays one step while its arguments stream in", () => {
const key = toolStepKey("tool_calling", "grep", "call_grep_1");
let steps = upsertBubbleSteps([], step({
key,
args: { description: "Verify" },
}));
steps = upsertBubbleSteps(steps, step({
key,
args: { description: "Verify no dangling", pattern: "truncat" },
}));
steps = upsertBubbleSteps(
steps,
step({ key: "streaming:", label: "正在生成" }),
);
steps = upsertBubbleSteps(steps, step({
key,
args: { pattern: "truncation", path: "/mnt/user-data/outputs/report.md" },
}));
assert.equal(steps.filter((item) => item.key.startsWith("tool_calling:grep")).length, 1);
assert.equal(steps[0]?.args?.pattern, "truncation");
assert.equal(steps[0]?.args?.description, "Verify no dangling");
});
test("two real grep calls stay two steps", () => {
const first = toolStepKey("tool_calling", "grep", "call_a");
const second = toolStepKey("tool_calling", "grep", "call_b");
let steps = upsertBubbleSteps([], step({ key: first, args: { pattern: "one" } }));
steps = upsertBubbleSteps(steps, step({ key: second, args: { pattern: "two" } }));
assert.deepEqual(steps.map((item) => item.args?.pattern), ["one", "two"]);
});
test("a late tool call id adopts only the immediately previous unbound step", () => {
let steps = upsertBubbleSteps([], step({
key: "tool_calling:grep",
args: { description: "Verify" },
}));
steps = upsertBubbleSteps(steps, step({
key: toolStepKey("tool_calling", "grep", "call_late"),
args: { pattern: "done" },
}));
assert.equal(steps.length, 1);
assert.equal(steps[0]?.key, "tool_calling:grep:call_late");
assert.equal(steps[0]?.args?.pattern, "done");
});
test("write_file content is kept from the first chunk and later chunks do not replace it", () => {
const key = toolStepKey("tool_calling", "write_file", "call_w");
let steps = upsertBubbleSteps([], step({
key,
args: { path: "/mnt/user-data/outputs/a.md", content: "part-1" },
}));
steps = upsertBubbleSteps(steps, step({
key,
args: { description: "Write report", content: "part-1-and-more" },
}));
assert.equal(steps.length, 1);
assert.equal(steps[0]?.args?.content, "part-1");
assert.equal(steps[0]?.args?.description, "Write report");
});
@@ -0,0 +1,102 @@
/**
* 会商步骤条与普通对话 `chats/new` 的 ToolCall 用同一条身份:
* 一次工具调用(tool call id)只对应一行,后续参数分片更新这一行。
*/
export interface BubbleToolStep {
id: string;
key: string;
label: string;
ts: string;
args?: Record<string, unknown>;
}
/** 正文类字段只保留第一次,避免每个 content chunk 都改对话 state。 */
const FROZEN_ARG_KEYS = new Set(["content", "new_string", "old_string"]);
export function toolStepKey(
phase: string,
toolName?: string,
toolCallId?: string,
): string {
if (phase === "tool_calling" && toolName && toolCallId) {
return `${phase}:${toolName}:${toolCallId}`;
}
return `${phase}:${toolName ?? ""}`;
}
export function isToolStepKey(key: string, toolName: string): boolean {
return key === `tool_calling:${toolName}` || key.startsWith(`tool_calling:${toolName}:`);
}
function callIdOf(key: string): string | undefined {
const [phase, name, ...rest] = key.split(":");
if (phase !== "tool_calling" || !name || rest.length === 0) return undefined;
return rest.join(":");
}
function toolNameOf(key: string): string {
const [phase, name] = key.split(":");
return phase === "tool_calling" ? (name ?? "") : "";
}
function mergeArgs(
previous: Record<string, unknown> | undefined,
incoming: Record<string, unknown> | undefined,
): Record<string, unknown> | undefined {
if (!incoming) return previous;
const next: Record<string, unknown> = { ...(previous ?? {}) };
for (const [argKey, value] of Object.entries(incoming)) {
if (value === undefined) continue;
if (FROZEN_ARG_KEYS.has(argKey)) {
const current = next[argKey];
if (typeof current === "string" && current.length > 0) continue;
}
next[argKey] = value;
}
return Object.keys(next).length > 0 ? next : undefined;
}
function sameArgs(
left: Record<string, unknown> | undefined,
right: Record<string, unknown> | undefined,
): boolean {
return JSON.stringify(left ?? {}) === JSON.stringify(right ?? {});
}
/**
* 把一帧阶段更新并进已有步骤。
* 同一 tool call id 无论中间是否插入了「正在生成」都会更新原行;
* id 晚到时,只认紧挨着的、还没有 id 的同名工具行。
*/
export function upsertBubbleSteps<T extends BubbleToolStep>(
steps: T[],
incoming: T,
): T[] {
const identName = toolNameOf(incoming.key);
const identId = callIdOf(incoming.key);
let index = steps.findIndex((step) => step.key === incoming.key);
if (index < 0 && identId && identName) {
const last = steps[steps.length - 1];
if (
last &&
last.key === `tool_calling:${identName}` &&
!callIdOf(last.key)
) {
index = steps.length - 1;
}
}
if (index < 0 && !identName) {
const last = steps[steps.length - 1];
if (last && last.key === incoming.key) index = steps.length - 1;
}
if (index >= 0) {
const prev = steps[index]!;
const args = mergeArgs(prev.args, incoming.args);
if (prev.key === incoming.key && sameArgs(prev.args, args)) return steps;
const next = [...steps];
next[index] = { ...prev, key: incoming.key, args };
return next;
}
return [...steps, { ...incoming, args: mergeArgs(undefined, incoming.args) }];
}
@@ -26,6 +26,8 @@ import {
ArrowLeft,
Bot,
ChevronDown,
ChevronLeft,
ChevronRight,
ChevronUp,
Gauge,
GitBranch,
@@ -109,10 +111,10 @@ import {
listChains,
optimizeChainPrompt,
setChainPublic,
submitChainForReview,
updateChain,
} from "@/roundtable-planning/api/chains";
import {
CHAIN_MAX_PARALLEL,
CHAIN_MAX_SEATS,
CHAIN_MIN_SEATS,
chainTagClasses,
@@ -227,9 +229,7 @@ export default function BusinessChainEditorPage() {
const [currentChainId, setCurrentChainId] = useState<string | null>(null);
// 当前编辑链条的发布状态 / 是否本人所有(发布按钮 + 只读保护用)。
const [currentChainPublic, setCurrentChainPublic] = useState(false);
// 「待审核」状态:true = 已提交审核、等待管理员发布(发布按钮变「审核中」)。
const [currentChainPending, setCurrentChainPending] = useState(false);
// 发布审核确认弹窗(发布前选择「确认审核」或「直接发布」)。
// 发布确认弹窗(发布前确认,两个按钮均直接发布)。
const [reviewDialogOpen, setReviewDialogOpen] = useState(false);
const [currentChainMine, setCurrentChainMine] = useState(true);
// 管理员:可编辑 / 发布 / 删除任意账号的链条(与「全部链条」筛选配套)。
@@ -363,7 +363,6 @@ export default function BusinessChainEditorPage() {
const loadChain = useCallback((chain: BusinessChain) => {
setCurrentChainId(chain.id);
setCurrentChainPublic(chain.isPublic ?? false);
setCurrentChainPending(chain.pendingReview ?? false);
setCurrentChainMine(chain.isMine !== false);
setTitle(chain.title);
setDescription(chain.description ?? "");
@@ -377,7 +376,6 @@ export default function BusinessChainEditorPage() {
const startNewChain = useCallback(() => {
setCurrentChainId(null);
setCurrentChainPublic(false);
setCurrentChainPending(false);
setCurrentChainMine(true);
setTitle("");
setDescription("");
@@ -454,7 +452,16 @@ export default function BusinessChainEditorPage() {
}, []);
const mergeSeatToStage = useCallback((agentId: string, targetStageIdx: number) => {
setStageGroups((prev) => moveSeatToStage(prev, agentId, targetStageIdx));
setStageGroups((prev) => {
// 并入 = 跨 stage 移动,目标 stage 满员(并行上限)则拒绝;stage 内移动不受限。
const from = findStageIndexOfSeat(prev, agentId);
const target = prev[targetStageIdx];
if (from !== targetStageIdx && target && target.seats.length >= CHAIN_MAX_PARALLEL) {
toast.warning(`同一 Stage 最多并行 ${CHAIN_MAX_PARALLEL} 个席位,请先拆分或换一个 Stage`);
return prev;
}
return moveSeatToStage(prev, agentId, targetStageIdx);
});
}, []);
const setGoal = useCallback((stageIdx: number, goal: string) => {
@@ -638,6 +645,14 @@ export default function BusinessChainEditorPage() {
toast.warning(`链条最多 ${CHAIN_MAX_SEATS} 个席位`);
return;
}
// 并行上限:拖入已有 stage 时该 stage 满员则拒绝(新建 stage 不受限)。
if (!toNewStage && targetStage >= 0) {
const target = stageGroups[targetStage];
if (target && target.seats.length >= CHAIN_MAX_PARALLEL) {
toast.warning(`同一 Stage 最多并行 ${CHAIN_MAX_PARALLEL} 个席位,请拖到「新建 Stage」区`);
return;
}
}
setStageGroups((prev) =>
toNewStage || targetStage < 0
? addSeatAsNewStage(prev, seat)
@@ -648,6 +663,19 @@ export default function BusinessChainEditorPage() {
if (activeId.startsWith(SEAT_PREFIX)) {
const agentId = activeId.slice(SEAT_PREFIX.length);
// 并行上限:跨 stage 移动时目标 stage 满员则拒绝;stage 内排序 / 拆出新 stage 不受限。
const fromStage = findStageIndexOfSeat(stageGroups, agentId);
const target = stageGroups[targetStage];
if (
!toNewStage &&
targetStage >= 0 &&
fromStage !== targetStage &&
target &&
target.seats.length >= CHAIN_MAX_PARALLEL
) {
toast.warning(`同一 Stage 最多并行 ${CHAIN_MAX_PARALLEL} 个席位,请先拆分或换一个 Stage`);
return;
}
setStageGroups((prev) => {
if (toNewStage) {
// 拖到「新建 Stage」区 = 抽出独立成最后一个 Stage。
@@ -665,7 +693,10 @@ export default function BusinessChainEditorPage() {
// ─── 保存 / 删除 ──────────────────────────────────────────────────────
const seatCountInvalid = seatCount < CHAIN_MIN_SEATS || seatCount > CHAIN_MAX_SEATS;
const hasEmptyStage = stageGroups.some((g) => g.seats.length === 0);
const canSave = title.trim().length > 0 && !seatCountInvalid && !saving;
// 并行上限:legacy 链条可能带超限 stage(拖拽 / 并入已实时拦截,这里兜底保存口)。
const oversizedStageIdx = stageGroups.findIndex((g) => g.seats.length > CHAIN_MAX_PARALLEL);
const canSave =
title.trim().length > 0 && !seatCountInvalid && oversizedStageIdx < 0 && !saving;
const handleSave = useCallback(async () => {
if (!title.trim()) {
@@ -676,6 +707,13 @@ export default function BusinessChainEditorPage() {
toast.warning(`链条席位数须在 ${CHAIN_MIN_SEATS}–${CHAIN_MAX_SEATS} 之间`);
return;
}
const oversized = stageGroups.findIndex((g) => g.seats.length > CHAIN_MAX_PARALLEL);
if (oversized >= 0) {
toast.warning(
`Stage ${oversized + 1} 并行了 ${stageGroups[oversized].seats.length} 个席位,同一 Stage 最多 ${CHAIN_MAX_PARALLEL} 个,请拆分为多个 Stage`,
);
return;
}
setSaving(true);
try {
// 展平 + 折叠:seats 用候选池最新 name/description 覆盖快照;stages 在「全单席位且无
@@ -782,7 +820,7 @@ export default function BusinessChainEditorPage() {
}
}, [currentChainId, title, startNewChain, refreshChains]);
// 发布入口:已发布 → 收回;审核中 → 撤回审核;未发布 → 弹窗选择「确认审核 / 直接发布」。
// 发布入口:已发布 → 收回;未发布(含遗留「审核中」)→ 弹窗直接发布。
const handleTogglePublish = useCallback(async () => {
if (!currentChainId) {
toast.warning("请先保存链条再发布");
@@ -809,61 +847,17 @@ export default function BusinessChainEditorPage() {
}
return;
}
// 审核中 → 撤回审核,回到未发布草稿。
if (currentChainPending) {
if (!window.confirm("该链条正在审核中,确认撤回审核?")) return;
setPublishing(true);
try {
const updated = await updateChain(currentChainId, { pendingReview: false });
if (!updated) {
toast.error("链条已不存在,可能被删除");
startNewChain();
await refreshChains();
return;
}
setCurrentChainPending(updated.pendingReview ?? false);
toast.success("已撤回审核");
await refreshChains();
} catch (err) {
toast.error(`撤回审核失败:${err instanceof Error ? err.message : String(err)}`);
} finally {
setPublishing(false);
}
return;
}
// 未发布 → 弹窗选择审核 / 直接发布。
// 未发布 → 弹窗确认发布(发布同时清除遗留的待审核标记)。
setReviewDialogOpen(true);
}, [currentChainId, currentChainPublic, currentChainPending, startNewChain, refreshChains]);
}, [currentChainId, currentChainPublic, startNewChain, refreshChains]);
// 弹窗「确认审核」:提交进入待审核,等待管理员在业务链条列表「待审核」筛选里发布。
const handleSubmitReview = useCallback(async () => {
// 弹窗「直接发布 / 提交审核」:两个按钮功能一致,立即发布为公共并清除待审核标记;
// 仅成功提示按所点按钮区分(提交审核 → 「提交成功」)。
const handleDirectPublish = useCallback(async (viaReviewButton = false) => {
if (!currentChainId) return;
setPublishing(true);
try {
const updated = await submitChainForReview(currentChainId);
if (!updated) {
toast.error("链条已不存在,可能被删除");
startNewChain();
await refreshChains();
return;
}
setCurrentChainPending(updated.pendingReview ?? true);
setReviewDialogOpen(false);
toast.success("已提交审核,等待管理员在业务链条列表发布");
await refreshChains();
} catch (err) {
toast.error(`提交审核失败:${err instanceof Error ? err.message : String(err)}`);
} finally {
setPublishing(false);
}
}, [currentChainId, startNewChain, refreshChains]);
// 弹窗「直接发布」:保持旧发布行为,立即对所有账号可见。
const handleDirectPublish = useCallback(async () => {
if (!currentChainId) return;
setPublishing(true);
try {
const updated = await setChainPublic(currentChainId, true);
const updated = await updateChain(currentChainId, { isPublic: true, pendingReview: false });
if (!updated) {
toast.error("链条已不存在,可能被删除");
startNewChain();
@@ -872,7 +866,7 @@ export default function BusinessChainEditorPage() {
}
setCurrentChainPublic(updated.isPublic ?? true);
setReviewDialogOpen(false);
toast.success("已发布为公共,所有账号都能查看 / 选用");
toast.success(viaReviewButton ? "提交成功" : "已发布为公共,所有账号都能查看 / 选用");
await refreshChains();
} catch (err) {
toast.error(`发布失败:${err instanceof Error ? err.message : String(err)}`);
@@ -1038,7 +1032,7 @@ export default function BusinessChainEditorPage() {
分层并行调度规则
</div>
<p className="text-[11px] leading-relaxed text-muted-foreground">
处于同一<strong className="font-semibold text-foreground">阶段(Stage)</strong>的席位会被并行下发任务以压缩时延;阶段之间串行,由总控在下一阶段承接并合并上一阶段产出。
处于同一<strong className="font-semibold text-foreground">阶段(Stage)</strong>的席位会被并行下发任务以压缩时延(同一 Stage 最多 <strong className="font-semibold text-foreground">3</strong> 个并行席位,更多请拆成多个 Stage);阶段之间串行,由总控在下一阶段承接并合并上一阶段产出。
</p>
</div>
</div>
@@ -1177,8 +1171,34 @@ export default function BusinessChainEditorPage() {
{/* 右侧操作 */}
<div className="ml-auto flex items-center gap-2">
{/* 发布:未发布 → 弹窗(管理员可选「直接发布 / 确认审核」,普通用户提交审核);
审核中 → 撤回;已发布 → 收回。 */}
<button
type="button"
onClick={() => setStep(1)}
disabled={step === 1}
title={step === 1 ? "当前已是第一步" : "返回链条编排"}
className={cn(
"flex items-center gap-1 border border-border bg-card px-3 py-1.5 text-sm font-medium text-muted-foreground transition hover:bg-muted hover:text-foreground active:scale-[0.98] disabled:cursor-not-allowed disabled:opacity-40 disabled:hover:bg-card disabled:hover:text-muted-foreground",
R_CTRL,
)}
>
<ChevronLeft className="size-4" />
上一步
</button>
<button
type="button"
onClick={() => setStep(2)}
disabled={step === 2}
title={step === 2 ? "当前已是最后一步" : "进入基本信息"}
className={cn(
"flex items-center gap-1 border border-border bg-card px-3 py-1.5 text-sm font-medium text-muted-foreground transition hover:bg-muted hover:text-foreground active:scale-[0.98] disabled:cursor-not-allowed disabled:opacity-40 disabled:hover:bg-card disabled:hover:text-muted-foreground",
R_CTRL,
)}
>
下一步
<ChevronRight className="size-4" />
</button>
{/* 发布:未发布 → 弹窗确认直接发布;已发布 → 收回。 */}
{currentChainId && (currentChainMine || isAdmin) && (
<button
type="button"
@@ -1187,19 +1207,13 @@ export default function BusinessChainEditorPage() {
title={
currentChainPublic
? "已发布为公共,点击收回为私有"
: currentChainPending
? "审核中,点击撤回审核"
: isAdmin
? "发布为公共:可选提交审核(管理员发布)或直接发布"
: "提交审核:由管理员审核后发布为公共"
: "发布为公共:立即对所有账号可见 / 选用"
}
className={cn(
"flex items-center gap-1.5 border px-3 py-1.5 text-sm font-medium transition active:scale-[0.98] disabled:cursor-not-allowed disabled:opacity-60",
currentChainPublic
? "border-emerald-400/50 bg-emerald-500/10 text-emerald-600 hover:bg-emerald-500/15 dark:text-emerald-400"
: currentChainPending
? "border-amber-400/50 bg-amber-400/10 text-amber-600 hover:bg-amber-400/15 dark:text-amber-300"
: "border-border bg-card text-muted-foreground hover:bg-muted hover:text-foreground",
: "border-border bg-card text-muted-foreground hover:bg-muted hover:text-foreground",
R_CTRL,
)}
>
@@ -1208,7 +1222,7 @@ export default function BusinessChainEditorPage() {
) : (
<Globe className="size-4" />
)}
{currentChainPublic ? "已发布" : currentChainPending ? "审核中" : "发布"}
{currentChainPublic ? "已发布" : "发布"}
</button>
)}
<button
@@ -1443,8 +1457,8 @@ export default function BusinessChainEditorPage() {
}}
/>
{/* 发布审核确认弹窗:确认审核 → 进入「待审核」由管理员发布;管理员可选
「直接发布」立即公共可见(普通用户无此权限,只能走审核)。 */}
{/* 发布确认弹窗:「直接发布 / 提交审核」两个按钮功能一致,均立即发布为公共
(所有账号可见 / 选用),并清除遗留的待审核标记。 */}
<Dialog open={reviewDialogOpen} onOpenChange={setReviewDialogOpen}>
<DialogContent className="sm:max-w-md">
<DialogHeader>
@@ -1453,22 +1467,22 @@ export default function BusinessChainEditorPage() {
发布业务链条
</DialogTitle>
<DialogDescription>
{isAdmin
? "是否需要审核?确认审核后该链条将进入「待审核」,由管理员在业务链条列表中发布;直接发布则立即对所有账号可见 / 选用。"
: "提交后该链条将进入「待审核」,由管理员在业务链条列表中审核发布;发布前可随时撤回审核。"}
发布后该链条将立即对所有账号可见 / 选用。
</DialogDescription>
</DialogHeader>
<DialogFooter>
<Button variant="outline" onClick={() => setReviewDialogOpen(false)}>
取消
</Button>
{isAdmin && (
<Button variant="secondary" onClick={handleDirectPublish} disabled={publishing}>
直接发布
</Button>
)}
<Button onClick={handleSubmitReview} disabled={publishing}>
{isAdmin ? "确认审核" : "提交审核"}
<Button
variant="secondary"
onClick={() => void handleDirectPublish(false)}
disabled={publishing}
>
直接发布
</Button>
<Button onClick={() => void handleDirectPublish(true)} disabled={publishing}>
提交审核
</Button>
</DialogFooter>
</DialogContent>
@@ -1830,12 +1844,15 @@ function StageSection({
className={cn(
"border px-1.5 py-0.5 text-[10px] font-semibold",
R_CTRL,
isParallel
? "border-amber-400/40 bg-amber-400/10 text-amber-600 dark:text-amber-300"
: "border-border bg-muted text-muted-foreground",
seats.length > CHAIN_MAX_PARALLEL
? // 超限(legacy 链条):标红提示,保存会被拦截。
"border-destructive/50 bg-destructive/10 text-destructive"
: isParallel
? "border-amber-400/40 bg-amber-400/10 text-amber-600 dark:text-amber-300"
: "border-border bg-muted text-muted-foreground",
)}
>
{isParallel ? `并行 ${seats.length}` : "串行"}
{isParallel ? `并行 ${seats.length}/${CHAIN_MAX_PARALLEL}` : "串行"}
</span>
</div>
<div className="flex items-center gap-0.5">
@@ -8,6 +8,10 @@
* 数据全部来自后端 `/api/roundtable-chains`(`api/chains.ts`),按登录用户隔离:
* - 「设置」→ 进编辑器并切到该链条(带 chainId);「新建链条」→ 进编辑器空白新建。
* - 「发布 / 取消发布」→ `setChainPublic`;「删除」→ `deleteChain`(确认弹窗 + toast)。
* - 管理员目录开关(仅 admin):卡片 / 表格操作区的眼睛按钮 → `setChainHidden`。隐藏后
* 链条从所有普通列表(我的/公共/待审核/选链弹窗)消失,但单条读取不过滤——已配置的
* 业务映射、进行中的研讨、编辑器深链继续可用;仅本管理页(`admin_view=true`)可见可恢复,
* 工具栏的「显示: 全部/显示中/已隐藏」筛选配套(服务端过滤)。
* - 设计稿里后端没有的「选用人气 / 标签」已按真实数据适配(统计卡第 4 张改为「未发布
* 草稿」,卡片不再渲染人气 / 标签空壳)。
*
@@ -32,6 +36,8 @@ import {
ArrowRightIcon,
CalendarIcon,
ChevronDownIcon,
EyeIcon,
EyeOffIcon,
FilePenLineIcon,
GlobeIcon,
LayersIcon,
@@ -69,8 +75,8 @@ import {
approveChainReview,
deleteChain,
listChains,
setChainHidden,
setChainPublic,
submitChainForReview,
type ChainScope,
} from "../api/chains";
import { chainTagClasses, type BusinessChain } from "../lib/business-chain";
@@ -78,6 +84,9 @@ import { getAvatarTypeFor } from "../lib/roundtable-constants";
type SortBy = "updated" | "seats" | "name";
/** 目录筛选(仅管理员配置页):全部 / 仅显示中 / 仅已隐藏(服务端过滤)。 */
type HiddenFilter = "all" | "visible" | "hidden";
/**
* 品牌主操作色(实心按钮 / 激活态)。
* - 浅色:深红 `#CF1322`(hover `#A8071A`)。
@@ -116,31 +125,51 @@ export default function BusinessChainListPage() {
const [search, setSearch] = useState("");
const [sortBy, setSortBy] = useState<SortBy>("updated");
const [layout, setLayout] = useState<"grid" | "list">("grid");
// 管理员的目录筛选(显示中/已隐藏);非管理员恒为 all(后端也从不返回隐藏链条)。
const [hiddenFilter, setHiddenFilter] = useState<HiddenFilter>("all");
const [publishingId, setPublishingId] = useState<string | null>(null);
const [deletingId, setDeletingId] = useState<string | null>(null);
const [hidingId, setHidingId] = useState<string | null>(null);
const [pendingDelete, setPendingDelete] = useState<BusinessChain | 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);
}
}, []);
// 管理员以「管理视图」拉列表(含被隐藏链条,且支持 hidden 筛选);统计源与之一致,
// 否则数字对不上管理页。普通用户不带 admin_view(后端对非管理员也忽略该参数)。
const listOpts = useMemo(
() =>
isAdmin
? {
adminView: true,
hidden:
hiddenFilter === "all" ? undefined : hiddenFilter === "hidden",
}
: {},
[isAdmin, hiddenFilter],
);
const refresh = useCallback(
async (s: ChainScope) => {
setLoading(true);
setError(null);
try {
const list = await listChains(s, listOpts);
setChains(list);
} catch (err) {
setError(err instanceof Error ? err.message : String(err));
} finally {
setLoading(false);
}
},
[listOpts],
);
const loadStats = useCallback(async () => {
try {
setStatChains(await listChains("mine"));
setStatChains(await listChains("mine", listOpts));
} catch {
// 统计失败不阻塞主列表,静默退化(保持上次数值)。
}
}, []);
}, [listOpts]);
useEffect(() => {
let cancelled = false;
@@ -148,7 +177,7 @@ export default function BusinessChainListPage() {
setError(null);
void (async () => {
try {
const list = await listChains(scope);
const list = await listChains(scope, listOpts);
if (!cancelled) setChains(list);
// scope=mine 时主列表即统计源,顺带刷新统计省一次请求。
if (!cancelled && scope === "mine") setStatChains(list);
@@ -161,7 +190,7 @@ export default function BusinessChainListPage() {
return () => {
cancelled = true;
};
}, [scope]);
}, [scope, listOpts]);
// 首挂载时若直接停在 public,也要把统计源拉起来。
useEffect(() => {
@@ -170,17 +199,14 @@ export default function BusinessChainListPage() {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
// ── 操作:发布 / 取消发布 / 提交审核 / 审核发布 ──────────────────────────
// 发布为公共(is_public=true)仅管理员可执行:
// - 「待审核」筛选里 = 管理员审核发布(is_public=true 并清除待审核标记);
// - 管理员在其它筛选里点待审核链条的发布 = 同样走审核发布;
// - 管理员对普通链条 = 常规发布 / 取消发布。
// 普通用户:未发布链条的发布入口 = 提交审核(等待管理员发布,不能自行发布);
// 已发布链条可取消发布(收回为私有)。
// ── 操作:发布 / 取消发布 / 审核发布 ──────────────────────────────────────
// 发布为公共(is_public=true)所有账号可执行,不再区分管理员:
// - 待审核链条(含「待审核」筛选里的)= 直接审核发布(is_public=true 并清除待审核标记);
// - 普通未发布链条 = 常规发布;已发布 = 取消发布(收回为私有)。
const handleTogglePublic = useCallback(
async (chain: BusinessChain) => {
// 审核发布:待审核筛选(仅管理员可达)或管理员点待审核链条。
if (scope === "pending" || (isAdmin && chain.pendingReview)) {
// 审核发布:待审核链条直接发布并清除待审核标记。
if (chain.pendingReview) {
setPublishingId(chain.id);
try {
const updated = await approveChainReview(chain.id);
@@ -199,31 +225,7 @@ export default function BusinessChainListPage() {
}
return;
}
// 普通用户的未发布链条:提交审核,不能直接发布。
if (!isAdmin && !chain.isPublic) {
if (chain.pendingReview) {
toast.info("该链条审核中,请等待管理员发布");
return;
}
setPublishingId(chain.id);
try {
const updated = await submitChainForReview(chain.id);
if (updated) {
await refresh(scope);
await loadStats();
toast.success(`「${chain.title || "未命名链条"}」已提交审核,等待管理员发布`);
} else {
toast.error("链条已不存在,可能被删除");
await refresh(scope);
}
} catch (err) {
toast.error(`提交审核失败:${err instanceof Error ? err.message : String(err)}`);
} finally {
setPublishingId(null);
}
return;
}
// 其余(管理员发布/取消发布,普通用户取消发布)走常规开关。
// 其余(发布 / 取消发布)走常规开关。
setPublishingId(chain.id);
try {
const updated = await setChainPublic(chain.id, !chain.isPublic);
@@ -245,7 +247,7 @@ export default function BusinessChainListPage() {
setPublishingId(null);
}
},
[refresh, scope, loadStats, isAdmin],
[refresh, scope, loadStats],
);
// ── 操作:删除(确认弹窗)─────────────────────────────────────────────────
@@ -267,6 +269,29 @@ export default function BusinessChainListPage() {
}
}, [pendingDelete, refresh, scope, loadStats]);
// ── 操作:管理员隐藏 / 取消隐藏(目录开关,不影响使用)─────────────────────
const handleToggleHidden = useCallback(
async (chain: BusinessChain) => {
const name = chain.title || "未命名链条";
setHidingId(chain.id);
try {
await setChainHidden(chain.id, !chain.hidden);
await refresh(scope);
await loadStats();
toast.success(
chain.hidden
? `已恢复「${name}」的展示`
: `已隐藏「${name}」:选链弹窗等不再展示,本页仍可管理`,
);
} catch (err) {
toast.error(`操作失败:${err instanceof Error ? err.message : String(err)}`);
} finally {
setHidingId(null);
}
},
[refresh, scope, loadStats],
);
// ── 统计(基于「我的链条」全局)──────────────────────────────────────────
const stats = useMemo(() => {
const totalChains = statChains.length;
@@ -417,7 +442,7 @@ export default function BusinessChainListPage() {
))}
</div>
{/* 搜索 + 排序 + 视图切换 */}
{/* 搜索 + 排序 + (管理员)显示筛选 + 视图切换 */}
<div className="flex w-full flex-wrap items-center gap-3 lg:w-auto lg:flex-nowrap">
<div className="relative max-w-sm flex-1 sm:w-64">
<SearchIcon className="pointer-events-none absolute left-3.5 top-1/2 size-4 -translate-y-1/2 text-zinc-400 dark:text-[#4A6491]" />
@@ -439,6 +464,24 @@ export default function BusinessChainListPage() {
)}
</div>
{isAdmin && (
<div className="flex items-center gap-1.5">
<span className="shrink-0 text-xs font-medium text-zinc-400 dark:text-[#6E88B0]">显示:</span>
<div className="relative">
<select
value={hiddenFilter}
onChange={(e) => setHiddenFilter(e.target.value as HiddenFilter)}
className="cursor-pointer select-none appearance-none rounded-xl border-none bg-zinc-100 py-2 pl-3.5 pr-8 text-xs font-semibold text-zinc-700 outline-none hover:bg-zinc-200 dark:bg-[#1A2F5A] dark:text-[#C5CFE0] dark:hover:bg-[#2D4473]"
>
<option value="all">全部</option>
<option value="visible">显示中</option>
<option value="hidden">已隐藏</option>
</select>
<ChevronDownIcon className="pointer-events-none absolute right-3 top-1/2 size-3 -translate-y-1/2 text-zinc-400 dark:text-[#6E88B0]" />
</div>
</div>
)}
<div className="flex items-center gap-1.5">
<span className="shrink-0 text-xs font-medium text-zinc-400 dark:text-[#6E88B0]">排序:</span>
<div className="relative">
@@ -514,10 +557,11 @@ export default function BusinessChainListPage() {
key={chain.id}
chain={chain}
canManage={isAdmin || chain.isMine !== false}
isAdmin={isAdmin}
publishing={publishingId === chain.id}
hiding={hidingId === chain.id}
onSettings={() => goConfigure(chain.id)}
onTogglePublic={() => handleTogglePublic(chain)}
onToggleHidden={isAdmin ? () => handleToggleHidden(chain) : undefined}
onDelete={() => setPendingDelete(chain)}
/>
))}
@@ -528,8 +572,10 @@ export default function BusinessChainListPage() {
chains={visibleChains}
canManage={isAdmin}
publishingId={publishingId}
hidingId={hidingId}
onSettings={(c) => goConfigure(c.id)}
onTogglePublic={handleTogglePublic}
onToggleHidden={isAdmin ? handleToggleHidden : undefined}
onDelete={(c) => setPendingDelete(c)}
/>
)}
@@ -677,7 +723,7 @@ function EmptyState({
{scope === "public"
? "公共链条是其他账号(或你自己)发布出来、所有人可见的链条。去「我的链条」里发布一条试试。"
: scope === "pending"
? "业务链条在编辑器里点「发布 → 确认审核」后会进入这里,由管理员审核发布。"
? "历史提交审核的链条会显示在这里,点发布可直接发布到公共选用库。"
: "业务链条是可复用的有序智能体编排。点右上角「新建链条」去创建第一条。"}
</p>
{scope !== "public" && scope !== "pending" && (
@@ -704,20 +750,23 @@ function EmptyState({
function ChainCard({
chain,
canManage,
isAdmin,
publishing,
hiding,
onSettings,
onTogglePublic,
onToggleHidden,
onDelete,
}: {
chain: BusinessChain;
/** 能否编辑 / 发布 / 删除(本人链条 或 管理员)。 */
canManage: boolean;
/** 当前登录用户是否管理员:发布语义不同(管理员=直接发布/审核发布,普通=提交审核)。 */
isAdmin: boolean;
publishing: boolean;
/** 管理员隐藏开关请求进行中(眼睛按钮转圈)。 */
hiding: boolean;
onSettings: () => void;
onTogglePublic: () => void;
/** 管理员目录开关(隐藏/恢复)。仅 admin 传入;undefined 时不渲染眼睛按钮。 */
onToggleHidden?: () => void;
onDelete: () => void;
}) {
const ownerName = chain.ownerName ? chain.ownerName.split("@")[0] : "";
@@ -729,7 +778,10 @@ function ChainCard({
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, scale: 0.95 }}
transition={{ duration: 0.3 }}
className="group relative flex flex-col overflow-hidden rounded-2xl border border-zinc-100 bg-white pb-4 transition hover:border-zinc-200 hover:shadow-md hover:shadow-zinc-100/50 dark:border-[#1A2F5A] dark:bg-[#122347] dark:hover:border-[#2D4473] dark:hover:shadow-none"
className={cn(
"group relative flex flex-col overflow-hidden rounded-2xl border border-zinc-100 bg-white pb-4 transition hover:border-zinc-200 hover:shadow-md hover:shadow-zinc-100/50 dark:border-[#1A2F5A] dark:bg-[#122347] dark:hover:border-[#2D4473] dark:hover:shadow-none",
chain.hidden && "opacity-60",
)}
>
<div className="flex flex-1 flex-col p-5 pb-2">
{/* 标题行 + 操作 */}
@@ -743,7 +795,14 @@ function ChainCard({
<UsersIcon className="mr-0.5 inline size-3" />
<span>{chain.seats.length} 席位</span>
</span>
{chain.pendingReview ? (
{chain.hidden ? (
<span
title="已被管理员隐藏:除本管理页外不再展示,已配置的映射 / 研讨不受影响"
className="rounded-full border border-zinc-300/60 bg-zinc-100 px-2 py-0.5 text-xs font-semibold text-zinc-500 dark:border-[#2D4473] dark:bg-[#1A2F5A] dark:text-[#6E88B0]"
>
已隐藏
</span>
) : chain.pendingReview ? (
<span className="rounded-full border border-amber-200/60 bg-amber-50 px-2 py-0.5 text-xs font-semibold text-amber-700 dark:border-[#FAAD14]/30 dark:bg-[#FAAD14]/15 dark:text-[#FAAD14]">
待审核
</span>
@@ -778,8 +837,7 @@ function ChainCard({
</div>
{/* 操作按钮:本人链条或管理员可发布 / 设置 / 删除(普通用户看别人的链条只读浏览)。
发布图标语义:管理员=发布/审核发布/取消发布;普通用户=提交审核(未发布)/
取消发布(已发布)/ 审核中(点击仅提示)。 */}
发布图标语义:待审核=审核发布;未发布=发布;已发布=取消发布。 */}
{canManage && (
<div className="flex shrink-0 items-center gap-1 opacity-80 transition-opacity group-hover:opacity-100">
<button
@@ -789,13 +847,9 @@ function ChainCard({
title={
chain.isPublic
? "取消发布"
: isAdmin
? chain.pendingReview
? "审核通过并发布"
: "发布到公共选用库"
: chain.pendingReview
? "审核中,等待管理员发布"
: "提交审核(由管理员审核发布)"
: chain.pendingReview
? "审核通过并发布"
: "发布到公共选用库"
}
className={cn(
"rounded-lg p-1.5 transition disabled:opacity-50",
@@ -810,6 +864,32 @@ function ChainCard({
<SendIcon className="size-4" />
)}
</button>
{onToggleHidden && (
<button
type="button"
onClick={onToggleHidden}
disabled={hiding}
title={
chain.hidden
? "取消隐藏:恢复在选链弹窗等列表中展示"
: "隐藏:除本管理页外不再展示,已配置的映射 / 研讨不受影响"
}
className={cn(
"rounded-lg p-1.5 transition disabled:opacity-50",
chain.hidden
? "text-zinc-500 hover:bg-zinc-50 hover:text-zinc-700 dark:text-[#6E88B0] dark:hover:bg-[#1A2F5A] dark:hover:text-[#C5CFE0]"
: "text-zinc-400 hover:bg-zinc-50 hover:text-zinc-600 dark:text-[#4A6491] dark:hover:bg-[#1A2F5A] dark:hover:text-[#6E88B0]",
)}
>
{hiding ? (
<Loader2Icon className="size-4 animate-spin" />
) : chain.hidden ? (
<EyeIcon className="size-4" />
) : (
<EyeOffIcon className="size-4" />
)}
</button>
)}
<button
type="button"
onClick={onSettings}
@@ -999,16 +1079,21 @@ function ChainTable({
chains,
canManage,
publishingId,
hidingId,
onSettings,
onTogglePublic,
onToggleHidden,
onDelete,
}: {
chains: BusinessChain[];
/** 管理员:可管理任意链条(即使非本人)。 */
canManage: boolean;
publishingId: string | null;
hidingId: string | null;
onSettings: (c: BusinessChain) => void;
onTogglePublic: (c: BusinessChain) => void;
/** 管理员目录开关(隐藏/恢复)。仅 admin 传入;undefined 时不渲染眼睛按钮。 */
onToggleHidden?: (c: BusinessChain) => void;
onDelete: (c: BusinessChain) => void;
}) {
return (
@@ -1032,11 +1117,23 @@ function ChainTable({
return (
<tr
key={chain.id}
className="group transition duration-150 hover:bg-zinc-50/60 dark:hover:bg-[#1A2F5A]/40"
className={cn(
"group transition duration-150 hover:bg-zinc-50/60 dark:hover:bg-[#1A2F5A]/40",
chain.hidden && "opacity-60",
)}
>
<td className="px-6 py-4 align-top">
<div className="flex items-center gap-2 text-sm font-semibold text-zinc-900 transition-colors group-hover:text-[#CF1322] dark:text-[#E8EDF5] dark:group-hover:text-[#FF7875]">
{chain.title || "未命名链条"}
{chain.hidden && (
<span
title="已被管理员隐藏:除本管理页外不再展示,已配置的映射 / 研讨不受影响"
className="inline-flex items-center gap-1 rounded-full bg-zinc-100 px-1.5 py-0.5 text-[9px] font-medium text-zinc-500 dark:bg-[#1A2F5A] dark:text-[#6E88B0]"
>
<EyeOffIcon className="size-2.5" />
已隐藏
</span>
)}
{chain.pendingReview && (
<span className="inline-flex items-center gap-1 rounded-full bg-amber-50 px-1.5 py-0.5 text-[9px] font-medium text-amber-700 dark:bg-[#FAAD14]/15 dark:text-[#FAAD14]">
待审核
@@ -1094,6 +1191,27 @@ function ChainTable({
<SendIcon className="size-4" />
)}
</button>
{onToggleHidden && (
<button
type="button"
onClick={() => onToggleHidden(chain)}
disabled={hidingId === chain.id}
title={
chain.hidden
? "取消隐藏:恢复在选链弹窗等列表中展示"
: "隐藏:除本管理页外不再展示,已配置的映射 / 研讨不受影响"
}
className="rounded-lg p-1.5 text-zinc-400 transition hover:bg-zinc-100 hover:text-zinc-700 disabled:opacity-50 dark:text-[#6E88B0] dark:hover:bg-[#1A2F5A] dark:hover:text-[#C5CFE0]"
>
{hidingId === chain.id ? (
<Loader2Icon className="size-4 animate-spin" />
) : chain.hidden ? (
<EyeIcon className="size-4" />
) : (
<EyeOffIcon className="size-4" />
)}
</button>
)}
<button
type="button"
onClick={() => onSettings(chain)}
@@ -80,6 +80,7 @@ import { desensitize } from "@/lib/desensitize";
import { cn } from "@/lib/utils";
import { useDesensitizeSubtree } from "@/roundtable-planning/lib/use-desensitize-subtree";
import { useModels } from "@/core/models/hooks";
import { useRoundtableRoomLimitSettings } from "@/core/system-settings/hooks";
import { getAvatar, Man1Avatar, RobotAvatar } from "@/roundtable-planning/components/Avatars";
import { ImportRoundtableDraftDialog } from "@/components/workspace/roundtable-draft-share-dialogs";
@@ -97,7 +98,14 @@ import { RecommendAgentsDialog } from "@/roundtable-planning/components/Recommen
import { BusinessChainListDialog } from "@/roundtable-planning/components/BusinessChainListDialog";
import { DispatchChainJobModal } from "@/roundtable-planning/components/DispatchChainJobModal";
import { Step1Panel, type Step1PanelProps } from "@/roundtable-planning/components/Step1Panel";
import { readActionDetail, readCopTaskDetail } from "@/core/auth/task-deeplink";
import {
cbwModelLines,
mapCopTaskTypeLabel,
readActionDetail,
readCopTaskDetail,
readTaskActionStructureFor,
taskActionStructureLines,
} from "@/core/auth/task-deeplink";
import { Step2Panel } from "@/roundtable-planning/components/Step2Panel";
import { Step3Panel } from "@/roundtable-planning/components/Step3Panel";
import type {
@@ -150,11 +158,22 @@ import {
startJob,
startJobKeepalive,
} from "@/roundtable-planning/api/roundtable-jobs";
import {
acquireRoundtableRoom,
heartbeatRoundtableRoom,
releaseRoundtableRoom,
ROUNDTABLE_ROOM_FULL_MESSAGE,
} from "@/roundtable-planning/api/rooms";
import { isRoundtableRoomExecutionActive } from "@/roundtable-planning/lib/room-lifecycle";
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { useRoundtableJobNotifier } from "@/roundtable-planning/components/RoundtableJobNotifier";
import { getChain, listChains } from "@/roundtable-planning/api/chains";
import { useRoundtableDrafts } from "@/roundtable-planning/hooks/useRoundtableDrafts";
import { filterRecommendCandidates } from "@/roundtable-planning/api/recommend";
import { listAgents } from "@/core/agents";
import { listBusinessMappings } from "@/strategy-components/api/business-mapping";
import { emitWujieEvent, isWujieEnv, onWujieEvent, readWujieProps } from "@/core/embed/wujie";
import { collectRoundtableDeliverables } from "@/roundtable-planning/lib/roundtable-deliverables";
@@ -220,6 +239,12 @@ function recordTaskIdOf(prefill: RoundtablePrefill | null): string | null {
return prefill?.actionId ?? prefill?.taskId ?? null;
}
/** One invisible concurrency identity per live page execution. */
function createRoomSessionId(): string {
return globalThis.crypto?.randomUUID?.() ??
`roundtable-${Date.now()}-${Math.random().toString(36).slice(2)}`;
}
/**
* 无界(wujie)抽屉场景:父页面通过 `window.$wujie.props` 注入「任务名称/描述/业务链条」。
* iframe 降级时 props 可能晚于首帧,故再读 hash 路由 query 作兜底(宿主 `appendEmbedQueryToUrl` 写入)。
@@ -351,6 +376,8 @@ export default function RoundtablePlanningPage({
step3HeaderTitle,
/** 独立业务页的工作区品牌区,取代通用步骤导航。 */
headerLeftSlot,
/** 顶栏最左侧附加内容(如深度研究入口的分段切换),不影响通用会商。 */
headerLeadingSlot,
/** 放在历史记录后面的独立业务操作或状态。 */
headerActionAfterHistory,
/** 独立业务页可隐藏通用的“保存草稿”按钮。 */
@@ -417,6 +444,7 @@ export default function RoundtablePlanningPage({
/** 8BF 第三步对话区标题,与第一、二步顶栏同一套样式。 */
step3HeaderTitle?: string;
headerLeftSlot?: ReactNode;
headerLeadingSlot?: ReactNode;
headerActionAfterHistory?: ReactNode;
hideHeaderSaveDraft?: boolean;
newTaskLabel?: string;
@@ -453,6 +481,21 @@ export default function RoundtablePlanningPage({
);
// 8BF 等独立页面可提供专属存储键;原会商仍沿用深链 taskId / 个人草稿语义。
const draftStorageTaskId = storageTaskId ?? recordTaskIdOf(prefillRef.current);
const roomSessionIdRef = useRef(createRoomSessionId());
const roomScopeRef = useRef<{
draftId: string | null;
taskId: string | null;
roomSessionId: string;
}>({
draftId: null,
taskId: null,
roomSessionId: roomSessionIdRef.current,
});
const roomHoldRef = useRef(false);
const roomAcquirePromiseRef = useRef<Promise<boolean> | null>(null);
const roomHandoffRef = useRef(false);
const roomEffectGenRef = useRef(0);
const [roomFull, setRoomFull] = useState(false);
// 由 prefill.businessCode 解析出的「自动选用业务链」结果;有值时「进入研讨」跳过选链弹窗直接进 Step 2。
const [autoChainResult, setAutoChainResult] = useState<SeatSelectionResult | null>(null);
// 固定业务链(8BF 等独立页面)的解析状态。不能只以 autoChainResult 是否为空判断:
@@ -483,8 +526,8 @@ export default function RoundtablePlanningPage({
setLockedChainResolution("loading");
setLockedChainUnavailableReason(null);
setAutoChainLoading(true);
void Promise.all([getChain(lockedChainId), listAgents()])
.then(([chain, agents]) => {
void getChain(lockedChainId)
.then((chain) => {
if (cancelled) return;
if (!chain) {
setAutoChainResult(null);
@@ -492,15 +535,15 @@ export default function RoundtablePlanningPage({
setLockedChainUnavailableReason("已配置的业务链不存在或未发布,请重新选择一条已发布的业务链");
return;
}
const candidates = filterRecommendCandidates(agents);
const result = buildChainSeatSelection(chain, candidates);
// 席位存活与最新名称用链条响应自带的读时计算富化字段(seat.available /
// live_name),不再实时拉智能体列表(慢网下少一个大请求)。
const result = buildChainSeatSelection(chain);
if (!cancelled) {
setAutoChainResult(result);
setLockedChainResolution(result ? "ready" : "unavailable");
if (!result) {
const availableAgentIds = new Set(candidates.map((agent) => agent.agent_id));
const unavailableSeats = chain.seats
.filter((seat) => !availableAgentIds.has(seat.agent_id))
.filter((seat) => seat.available === false)
.map((seat) => seat.name || seat.agent_id);
setLockedChainUnavailableReason(
unavailableSeats.length > 0
@@ -514,7 +557,7 @@ export default function RoundtablePlanningPage({
if (!cancelled) {
setAutoChainResult(null);
setLockedChainResolution("unavailable");
setLockedChainUnavailableReason("读取已配置业务链或智能体失败,请刷新后重试");
setLockedChainUnavailableReason("读取已配置业务链失败,请刷新后重试");
}
})
.finally(() => {
@@ -553,9 +596,12 @@ export default function RoundtablePlanningPage({
const [bootLoadingExpired, setBootLoadingExpired] = useState<boolean>(false);
const { models: availableModels, isLoading: modelsLoading } = useModels();
const { data: roundtableRuntimeLimits } = useRoundtableRoomLimitSettings();
// ─── 顶层导航 / 跨步状态 ─────────────────────────────────────
const [currentStep, setCurrentStep] = useState<number>(1);
const currentStepRef = useRef(currentStep);
currentStepRef.current = currentStep;
const [showToast, setShowToast] = useState<string | null>(null);
const [isRecommendDialogOpen, setIsRecommendDialogOpen] = useState<boolean>(false);
// 「业务链条」按钮 → 打开链条列表弹窗(弹窗里再决定进配置页 / 切到某条链条)。
@@ -780,6 +826,7 @@ export default function RoundtablePlanningPage({
manualIntervention: step2InterventionEnabled ?? false,
seatModes,
gatherFirst,
maxCycles: roundtableRuntimeLimits?.max_cycles,
orchestrationMode,
orchestrationPlan,
dagExecMode,
@@ -787,6 +834,23 @@ export default function RoundtablePlanningPage({
triggerToast,
setRoles,
loadedFromDraftRef: loadedFromDraftRefHolder,
roomScopeRef,
onRoomFull: (message) => {
const heldRoom = roomHoldRef.current;
roomHoldRef.current = false;
const scope = roomScopeRef.current;
if (heldRoom && scope.draftId) {
void releaseRoundtableRoom({
draftId: scope.draftId,
taskId: scope.taskId,
roomSessionId: scope.roomSessionId,
}).catch(() => {});
}
// 运行中的房间租约/容量错误只停止当前流,不得把用户和已有会商记录踢回第一步。
// 用户仍停留在第二步查看具体失败并决定重试或重新发起。
triggerToast(message || ROUNDTABLE_ROOM_FULL_MESSAGE);
setRoomFull(true);
},
});
const step1 = useStep1Intent({
@@ -1177,10 +1241,28 @@ export default function RoundtablePlanningPage({
// 已在本页 → 直接派 `roundtable:open-draft` 事件。两条路径都走 handleLoadDraft。
// 用 ref 持有最新 handleLoadDraft,让下面的 effect 保持「挂载只跑一次」,避免
// handleLoadDraft 身份变化导致重复消费 / 重复加载。
const handleLoadDraftRef = useRef(drafts.handleLoadDraft);
const openHistoryDraft = useCallback(
(id: string) => {
// 查看聊天记录不是进行中的会商:立刻交出房间名额。
if (roomHoldRef.current) {
roomHoldRef.current = false;
const scope = roomScopeRef.current;
if (scope.draftId) {
void releaseRoundtableRoom({
draftId: scope.draftId,
taskId: scope.taskId,
roomSessionId: scope.roomSessionId,
}).catch(() => {});
}
}
return drafts.handleLoadDraft(id);
},
[drafts],
);
const handleLoadDraftRef = useRef(openHistoryDraft);
useEffect(() => {
handleLoadDraftRef.current = drafts.handleLoadDraft;
}, [drafts.handleLoadDraft]);
handleLoadDraftRef.current = openHistoryDraft;
}, [openHistoryDraft]);
useEffect(() => {
const pending = sessionStorage.getItem("roundtable:pending-draft");
@@ -1196,6 +1278,12 @@ export default function RoundtablePlanningPage({
return () => window.removeEventListener("roundtable:open-draft", onOpenDraft);
}, []);
roomScopeRef.current = {
draftId: drafts.currentDraftId,
taskId: draftStorageTaskId ?? null,
roomSessionId: roomSessionIdRef.current,
};
// ─── 角色面板转场 ────────────────────────────────────────
// Step 1: 仅指挥员 + 任务理解智能体两行(状态跟随 intent init)。
// Step 2: 完整席位(loadedFromDraft 时直接 "在线",否则 "正在上线")。
@@ -1244,8 +1332,50 @@ export default function RoundtablePlanningPage({
}, [step2.isParallelRunning]);
// ─── 步骤间转场 handler ───────────────────────────────────
const holdLiveRoom = useCallback(
async (explicitDraftId?: string | null) => {
if (roomHoldRef.current) return true;
if (roomAcquirePromiseRef.current) return roomAcquirePromiseRef.current;
const draftId =
explicitDraftId ??
(await drafts.ensureDraft(1)) ??
drafts.currentDraftId;
if (!draftId) {
triggerToast("会商草稿尚未保存,暂时不能进入第二步");
return false;
}
const taskId = draftStorageTaskId ?? null;
roomSessionIdRef.current = createRoomSessionId();
const roomSessionId = roomSessionIdRef.current;
roomScopeRef.current = { draftId, taskId, roomSessionId };
const acquirePromise = (async () => {
try {
const decision = await acquireRoundtableRoom({ draftId, taskId, roomSessionId });
if (!decision.ok) {
setRoomFull(true);
return false;
}
roomHoldRef.current = true;
return true;
} catch (error) {
triggerToast(
`无法确认会商房间:${error instanceof Error ? error.message : "请稍后再试"}`,
);
return false;
} finally {
roomAcquirePromiseRef.current = null;
}
})();
roomAcquirePromiseRef.current = acquirePromise;
return acquirePromise;
},
[drafts, draftStorageTaskId, triggerToast],
);
const handleConfirmAgents = useCallback(
(result: SeatSelectionResult) => {
void (async () => {
const admitted = await holdLiveRoom();
if (!admitted) return;
const normalized: SelectedAgent[] = result.agents.map(({ agent_id, name }) => ({
agent_id,
// 内置 agent 走 BUILTIN_AGENT_META;非内置用候选池传过来的 name。
@@ -1316,7 +1446,7 @@ export default function RoundtablePlanningPage({
// result.mode 决定 Step 2 编排:recommend = 总控自由派活;chain = 按链条顺序派活;
// dag = 分层并行(来源链条带 stages,携带 result.plan)。
setOrchestrationMode(result.mode);
// 席位执行模式:弹窗未带(旧调用)时回退默认 pro,保证行为可预期。
// 席位执行模式:弹窗未带(旧调用)时回退默认快速,保证行为可预期。
setSeatMode(result.seatMode ?? DEFAULT_SEAT_MODE);
// 会商技能识别强化:取所选业务链条里**每席位**的开关 → {agentId: bool} 映射
// (recommend / 旧调用未带 → 空 {},各席位仅靠其智能体自身开关)。
@@ -1345,16 +1475,18 @@ export default function RoundtablePlanningPage({
? `成功确认!将按业务链条「${result.chain?.title ?? ""}」顺序研讨`
: "成功确认!已切换至第二阶段圆桌研讨系统",
);
})();
},
[buildCurrentStep2Snapshot, drafts, mergeActiveRun, step2, step3Report, triggerToast],
[buildCurrentStep2Snapshot, drafts, holdLiveRoom, mergeActiveRun, step2, step3Report, triggerToast],
);
// 需求 0616 #2:Step1 左栏点击某条业务链 → 仅**勾选**该链(不直接进 Step 2)。
// 复用 autoChainResult 机制:用户在第一步完成意图澄清后,点「进入多智能体研讨」时
// onEnterRoundtable 的 `if (autoChainResult)` 分支会据此跳过选链弹窗、按该链进研讨。
// 再次点击同一条链 = 取消勾选。
// 再次点击同一条链 = 取消勾选。席位存活/名称用链条响应自带的 seat 富化字段,
// **点选零网络请求**(不再实时拉智能体列表,慢网友好)。
const handleSelectChainFromSidebar = useCallback(
async (chain: BusinessChain) => {
(chain: BusinessChain) => {
if (lockBusinessChain) {
triggerToast("当前页面的业务链由管理员统一配置");
return;
@@ -1364,19 +1496,13 @@ export default function RoundtablePlanningPage({
triggerToast(`已取消业务链「${chain.title}」`);
return;
}
try {
const agents = await listAgents().catch(() => []);
const candidates = filterRecommendCandidates(agents);
const result = buildChainSeatSelection(chain, candidates);
if (!result) {
triggerToast("该业务链条暂无法选用(匹配到的席位不足)");
return;
}
setAutoChainResult(result);
triggerToast(`已选择业务链「${chain.title}」,完成第一步澄清后点「进入多智能体研讨」`);
} catch {
triggerToast("选择业务链失败,请重试");
const result = buildChainSeatSelection(chain);
if (!result) {
triggerToast("该业务链条暂无法选用(匹配到的席位不足)");
return;
}
setAutoChainResult(result);
triggerToast(`已选择业务链「${chain.title}」,完成第一步澄清后点「进入多智能体研讨」`);
},
[autoChainResult, lockBusinessChain, triggerToast],
);
@@ -1462,15 +1588,20 @@ export default function RoundtablePlanningPage({
// xdfx(行动分析):除任务名称/描述外,再带上「行动名称」一起交给任务理解智能体。
const actionName = isXdfx ? prefill.actionName?.trim() : "";
// 末尾附上任务 id(taskId),供智能体识别任务;
// xdfx(行动分析)额外附上「行动id(actionId)」。
// xdfx(行动分析)额外附上「行动id(actionId)」;传播网仅在 cbwId 有值时附上。
const taskId = prefill.taskId?.trim();
const actionId = isXdfx ? prefill.actionId?.trim() : "";
const storedAction = isXdfx ? readActionDetail() : null;
const taskTypeLabel = mapCopTaskTypeLabel(readCopTaskDetail()?.taskType);
const text = [
title ? `任务名称:${title}` : "",
goal ? `任务描述:${goal}` : "",
taskTypeLabel ? `任务类型:${taskTypeLabel}` : "",
actionName ? `行动名称:${actionName}` : "",
taskId ? `任务id(taskId)为${taskId}` : "",
actionId ? `行动id(actionId)为${actionId}` : "",
...taskActionStructureLines(actionId ? readTaskActionStructureFor(actionId) : null),
...cbwModelLines(storedAction?.cbwId, storedAction?.cbwName),
]
.filter(Boolean)
.join("\n");
@@ -1479,7 +1610,8 @@ export default function RoundtablePlanningPage({
void step1.sendIntentMessage(text);
}, [currentStep, taskRestoreResolved, step1.intentThreadId, step1.intentReady, step1.sendIntentMessage]);
// C3:据 prefill.businessCode 查业务映射 → 取 chainId → 拉公共链 + 候选智能体 → 构造自动选链结果。
// C3:据 prefill.businessCode 查业务映射 → 取 chainId → 拉公共链(响应自带席位存活/名称
// 富化字段)→ 构造自动选链结果,不实时拉智能体列表。
// 解析成功后「进入研讨」会跳过选链弹窗直接据此进 Step 2;解析失败(未配置 / 链不存在 / 席位不足)
// 静默回退到弹窗手选。
// 不加「已启动」永久闸门 —— StrictMode 的 mount→unmount→remount 会让首次 run 在 cleanup
@@ -1500,13 +1632,10 @@ export default function RoundtablePlanningPage({
chainId = mappings.find((m) => m.businessCode === prefill.businessCode)?.chainId;
}
if (!chainId) return;
const [chain, agents] = await Promise.all([
getChain(chainId),
listAgents().catch(() => []),
]);
const chain = await getChain(chainId);
if (cancelled || !chain) return;
const candidates = filterRecommendCandidates(agents);
const result = buildChainSeatSelection(chain, candidates);
// 席位存活/名称用链条响应自带的读时计算富化字段,不再实时拉智能体列表。
const result = buildChainSeatSelection(chain);
if (!cancelled && result) setAutoChainResult(result);
} catch {
/* 解析失败 → 保持 null,回退弹窗手选 */
@@ -1666,15 +1795,17 @@ export default function RoundtablePlanningPage({
.filter((g) => g.length > 0),
[orchestrationPlan],
);
// 普通会商:Markdown 报告完成后自动续跑结构化流程图;8BF:只完成报告即结束。
// 这个开关由入口显式传入,而不是从业务链/任务状态推断,防止两类会商串行为。
const autoSummaryFlow = hasFullStep3Outputs;
// 2026-10-31:第三步方案总结改为「报告完成即结束」——不再在 Markdown 报告完成后自动
// 续跑结构化流程图(与 8BF report-only 一致)。需要流程图时仍可手动触发(对话要求 /
// 重画 / rwfx-A 入库路径),故 hook 的 flowEnabled 保持开启只为保留这些手动入口。
const autoSummaryFlow = false;
const summaryFlow = useStep3Summary({
intentReady: step1.intentReady,
seatDeliveries: step3SeatDeliveries,
consensusText: step2.lastLeaderContent,
selectedModel,
roomScopeRef,
coordinatorPrompt: orchestrationPlan?.coordinatorPrompt ?? null,
chainLevels,
autoFlow: autoSummaryFlow,
@@ -1700,6 +1831,7 @@ export default function RoundtablePlanningPage({
seatDeliveries: step3SeatDeliveries,
consensusText: step2.lastLeaderContent,
selectedModel,
roomScopeRef,
savedReport: step3Report,
onReportSaved: handleReportSaved,
});
@@ -1713,6 +1845,7 @@ export default function RoundtablePlanningPage({
seatDeliveries: step3SeatDeliveries,
consensusText: step2.lastLeaderContent,
selectedModel,
roomScopeRef,
themeMode: isDark ? "dark" : "light",
savedReport: step3Report,
onReportSaved: handleReportSaved,
@@ -1848,6 +1981,8 @@ export default function RoundtablePlanningPage({
async (jobId: string, draftId: string) => {
stopJobFollow();
step2.stopOrchestration();
const admitted = await holdLiveRoom(draftId);
if (!admitted) return;
// 1. 取消后端作业:避免前后端双跑/抢同一线程(409),线程随后由前端接管续跑。
// executor.cancel 会 task.cancel() 中断在跑的 run,DB 同步置 cancelled。
await cancelJob(jobId, draftStorageTaskId).catch(() => null);
@@ -1861,7 +1996,7 @@ export default function RoundtablePlanningPage({
step2.resumeLiveTakeover();
void drafts.refresh();
},
[stopJobFollow, step2, drafts, setCurrentStep],
[stopJobFollow, step2, drafts, holdLiveRoom],
);
// 卸载兜底:离开页面停止跟随(后台作业本身继续跑)。
useEffect(() => stopJobFollow, [stopJobFollow]);
@@ -1969,6 +2104,7 @@ export default function RoundtablePlanningPage({
const job = await startJob({
draftId: draftId ?? undefined,
taskId: tid ?? undefined, // task 作业:报告写回独立 task-draft 存储、跨用户共享
roomSessionId: roomScopeRef.current.roomSessionId,
intent: buildInitialIntent(),
agents,
model: selectedModel || undefined, // 模型沿用第二步选择
@@ -2031,6 +2167,7 @@ export default function RoundtablePlanningPage({
// 立刻:标记「挂起中」+ 跳回第一步 + 提示(不等接口)。
if (draftId) markPendingSuspend(draftId);
roomHandoffRef.current = true;
resetToStep1();
triggerToast("已转入后台,任务会自动跑完研讨、总结报告与结果绘制;可在「历史记录」查看进度");
@@ -2053,6 +2190,7 @@ export default function RoundtablePlanningPage({
const job = await startJob({
draftId: savedId ?? undefined,
taskId: tid ?? undefined,
roomSessionId: roomScopeRef.current.roomSessionId,
intent,
agents,
model,
@@ -2113,16 +2251,19 @@ export default function RoundtablePlanningPage({
running: step2.isOrchestrating,
// 路由卸载用:可走完整异步链(ensureDraft → 去重 → startJob),fetch 卸载后照常完成。
fire: () => {
roomHandoffRef.current = true;
void startBackgroundJob().catch(() => {});
},
// beforeunload 用:无法 await —— 用 keepalive fetch 同步发出(浏览器保证发完)。
// draftId 取当前已存在的草稿(研讨启动时已 ensureDraft,见下方 effect)。
beacon: () => {
roomHandoffRef.current = true;
const agents = step2.selectedAgents.map((a) => ({ agentId: a.agent_id, name: a.name }));
if (agents.length === 0) return;
startJobKeepalive({
draftId: drafts.currentDraftId ?? undefined,
taskId: draftStorageTaskId ?? undefined,
roomSessionId: roomScopeRef.current.roomSessionId,
intent: buildInitialIntent(),
agents,
model: selectedModel || undefined,
@@ -2138,6 +2279,98 @@ export default function RoundtablePlanningPage({
},
};
});
// 进入第二步后持续续租,暂停、澄清等待和用户继续研讨都沿用最初获准的名额,
// 不再重新走准入。离开第二步、达成共识、连续心跳失败或硬时限到达才释放。
// 后台挂起或关页自动转后台时保留同一把钥匙,让作业继续占用这一个名额。
useEffect(() => {
const isRunningStep2 = isRoundtableRoomExecutionActive({
currentStep,
hasConsensus: step2.hasConsensus,
});
const gen = ++roomEffectGenRef.current;
if (!isRunningStep2) {
if (roomHoldRef.current) {
roomHoldRef.current = false;
const scope = roomScopeRef.current;
if (scope.draftId) {
void releaseRoundtableRoom({
draftId: scope.draftId,
taskId: scope.taskId,
roomSessionId: scope.roomSessionId,
}).catch(() => {});
}
}
return;
}
if (!roomHoldRef.current || drafts.loadedFromDraftRef.current) return;
let consecutiveFailures = 0;
const beat = () => {
if (!roomHoldRef.current || drafts.loadedFromDraftRef.current) return;
const scope = roomScopeRef.current;
const draftId = scope.draftId;
if (!draftId) return;
void heartbeatRoundtableRoom({
draftId,
taskId: scope.taskId,
roomSessionId: scope.roomSessionId,
})
.then((decision) => {
if (decision.ok) {
consecutiveFailures = 0;
return;
}
roomHoldRef.current = false;
step2.stopOrchestration();
step2.setIsRoundTableRunning(false);
triggerToast(
decision.message || "本次会商房间已释放,研讨已停止。记录仍留在当前页。",
);
void releaseRoundtableRoom({
draftId,
taskId: scope.taskId,
roomSessionId: scope.roomSessionId,
}).catch(() => {});
})
.catch(() => {
// 心跳请求失败只能说明本次续租请求没有得到响应,不能据此终止仍在
// 正常流式输出的席位。继续重试;只有服务端明确判定租约已失效时,
// 才在上面的 decision.ok=false 分支停止编排。
consecutiveFailures += 1;
if (consecutiveFailures === 2 && roomHoldRef.current) {
triggerToast("网络连接不稳定,当前会商仍在运行,正在自动重试。");
}
});
};
beat();
const timer = window.setInterval(beat, 15_000);
return () => {
window.clearInterval(timer);
const scope = roomScopeRef.current;
window.setTimeout(() => {
if (roomEffectGenRef.current !== gen) return;
const unmountWhileRunning =
(currentStepRef.current === 2 || currentStepRef.current === 3) &&
autoSuspendRef.current.running;
if (roomHandoffRef.current || unmountWhileRunning) {
roomHandoffRef.current = false;
return;
}
roomHoldRef.current = false;
if (scope.draftId) {
void releaseRoundtableRoom({
draftId: scope.draftId,
taskId: scope.taskId,
roomSessionId: scope.roomSessionId,
}).catch(() => {});
}
}, 0);
};
}, [
currentStep,
step2.hasConsensus,
step2.stopOrchestration,
triggerToast,
]);
// 研讨一启动(真正进入生成)就确保草稿存在:自动挂起 / beforeunload beacon 需要
// draftId 同步可取,历史下拉的「进行中」徽标也按 draftId 关联。ensureDraft 幂等。
useEffect(() => {
@@ -2286,6 +2519,26 @@ export default function RoundtablePlanningPage({
</div>
)}
<Dialog open={roomFull} onOpenChange={setRoomFull}>
<DialogContent className="sm:max-w-md" aria-describedby={undefined}>
<DialogHeader>
<DialogTitle>会商房间已满</DialogTitle>
</DialogHeader>
<p className="text-muted-foreground text-sm leading-6">
{ROUNDTABLE_ROOM_FULL_MESSAGE}
</p>
<div className="flex justify-end">
<button
type="button"
className="rounded-md bg-red-600 px-4 py-2 text-sm text-white"
onClick={() => setRoomFull(false)}
>
知道了
</button>
</div>
</DialogContent>
</Dialog>
<RecommendAgentsDialog
open={isRecommendDialogOpen}
intent={step1.intentReady}
@@ -2314,7 +2567,7 @@ export default function RoundtablePlanningPage({
onOpenChange={setIsImportOpen}
onImported={(draftId) => {
void drafts.refresh();
if (draftId) drafts.handleLoadDraft(draftId);
if (draftId) openHistoryDraft(draftId);
}}
/>
@@ -2345,7 +2598,7 @@ export default function RoundtablePlanningPage({
void takeOverRunningJob(job.id, job.draftId);
return;
}
void drafts.handleLoadDraft(job.draftId);
void openHistoryDraft(job.draftId);
}}
/>
@@ -2367,15 +2620,22 @@ export default function RoundtablePlanningPage({
{/* HEADER */}
<header ref={headerDzRef} className="relative z-[40] flex shrink-0 items-center justify-between gap-4 border-b border-slate-100 bg-white px-6 py-3 shadow-[0_1px_3px_rgba(0,0,0,0.02)] dark:border-border dark:bg-card dark:shadow-none">
{useCustomStep1Chrome ? headerLeftSlot : (
<StepNavigation
currentStep={currentStep}
intentReady={step1.intentReady}
hasConsensus={step2.hasConsensus}
onStepClick={(s) => setCurrentStep(s)}
triggerToast={triggerToast}
/>
)}
<div className="flex min-w-0 items-center gap-3">
{headerLeadingSlot ? (
<div className="w-[240px] shrink-0">
{headerLeadingSlot}
</div>
) : null}
{useCustomStep1Chrome ? headerLeftSlot : (
<StepNavigation
currentStep={currentStep}
intentReady={step1.intentReady}
hasConsensus={step2.hasConsensus}
onStepClick={(s) => setCurrentStep(s)}
triggerToast={triggerToast}
/>
)}
</div>
<div className="flex items-center gap-2">
{toolbarSlot}
@@ -2480,7 +2740,7 @@ export default function RoundtablePlanningPage({
renamingDraftId={drafts.renamingDraftId}
renameDraftValue={drafts.renameDraftValue}
setRenameDraftValue={drafts.setRenameDraftValue}
onLoad={drafts.handleLoadDraft}
onLoad={openHistoryDraft}
onOpen={() => void drafts.refresh()}
onOpenJob={(jobId) => {
drafts.setIsHistoryOpen(false);
@@ -2549,7 +2809,7 @@ export default function RoundtablePlanningPage({
setSeatFilter={setSeatFilter}
selectedChainId={autoChainResult?.chain?.id ?? null}
onSelectChain={handleSelectChainFromSidebar}
onOpenDraft={drafts.handleLoadDraft}
onOpenDraft={openHistoryDraft}
activeDraftId={drafts.currentDraftId}
entryRailTaskId={entryRailTaskId ?? recordTaskIdOf(prefillRef.current)}
historyTaskId={draftStorageTaskId}