sync update from LAN repo (source master @ c21a2a4a)

This commit is contained in:
gozeros committed 2026-11-10 14:03:50 +08:00
1 parent ea9dcff9c0
commit 66a443e915
140 files changed
+13777 -1040

No files matched your search

@@ -3,8 +3,10 @@ import { getBackendBaseURL } from "@/core/config";
import { OptType, writeYLog } from "@/core/log/y-log";
import {
isRoundtableCapacityFailure,
RoundtableRoomFullError,
isRoundtableBusyFailure,
isRoundtableRoomFullFailure,
roundtableErrorForDisplay,
roundtableRoomFullError,
} from "@/roundtable-planning/lib/capacity-error";
import { resolveAllowMultiple } from "@/roundtable-planning/lib/clarification";
import { reportRoundtableError, stageForRoundtableAgent } from "@/roundtable-planning/api/diagnostics-report";
@@ -12,29 +14,33 @@ import { createInlineReasoningDeltaFormatter } from "@/roundtable-planning/lib/s
export type ThreadIdMap = Record<string, string>;
function roomFullError(
function throwRoundtableRunError(
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;计数仅供诊断,不影响统一提示。
): never {
if (isRoundtableRoomFullFailure(status, rawDetail)) {
throw roundtableRoomFullError(rawDetail, status, context);
}
console.error(`[roundtable-capacity] ${context}`, {
status,
detail: rawDetail,
});
return new RoundtableRoomFullError(activeCount, maxRooms);
throw new Error(
roundtableErrorForDisplay(rawDetail, status) || "会商暂时无法继续,请稍后重试",
);
}
function isClassifiedRoundtableFailure(
status: number | null,
detail: string,
): boolean {
if (status === 409 || status === 429) return true;
if (isRoundtableRoomFullFailure(status, detail) || isRoundtableBusyFailure(status, detail)) {
return true;
}
const displayed = roundtableErrorForDisplay(detail, status);
return displayed != null && displayed !== detail;
}
export interface SeatReadyEvent {
@@ -119,8 +125,8 @@ 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");
if (isClassifiedRoundtableFailure(res.status, text)) {
throwRoundtableRunError(text, res.status, "init HTTP request rejected");
}
throw new Error(`init multi-agent failed (${res.status}): ${text}`);
}
@@ -215,8 +221,8 @@ 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");
if (isClassifiedRoundtableFailure(null, errorDetail)) {
throwRoundtableRunError(errorDetail, null, "init SSE error frame");
}
throw new Error(`init multi-agent failed: ${errorDetail}`);
}
@@ -627,8 +633,8 @@ 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");
if (isClassifiedRoundtableFailure(res.status, text)) {
throwRoundtableRunError(text, res.status, "run/stream HTTP request rejected");
}
throw new Error(`run/stream failed (${res.status}): ${text}`);
}
@@ -998,9 +1004,14 @@ export async function streamMultiAgent(
agentName: req.displayName || req.agentName,
detail: { agentType: req.agentType, framesBeforeError: frameSeq },
});
if (isRoundtableCapacityFailure(null, result.content)) {
const displayed = roundtableErrorForDisplay(result.content);
if (
isRoundtableRoomFullFailure(null, result.content) ||
isRoundtableBusyFailure(null, result.content) ||
(displayed != null && displayed !== result.content)
) {
reported = true;
throw roomFullError(
throwRoundtableRunError(
result.content,
null,
`run/stream SSE error frame (${req.displayName || req.agentName})`,
@@ -5,6 +5,7 @@ export {
isRoundtableCapacityFailure,
isRoundtableRoomFullError,
RoundtableRoomFullError,
roundtableCardFailure,
roundtableErrorForDisplay,
ROUNDTABLE_ROOM_FULL_MESSAGE,
} from "@/roundtable-planning/lib/capacity-error";
@@ -20,9 +20,9 @@ import { OptType, writeYLog } from "@/core/log/y-log";
import { getAvatarTypeFor } from "../lib/roundtable-constants";
import {
isRoundtableCapacityFailure,
RoundtableRoomFullError,
roundtableErrorForDisplay,
ROUNDTABLE_ROOM_FULL_MESSAGE,
RoundtableRoomFullError,
sanitizeRoundtableDialogue,
} from "../lib/capacity-error";
import { reportRoundtableError } from "./diagnostics-report";
import { seatModeToRunParams } from "../lib/seat-mode";
@@ -57,6 +57,15 @@ async function readJson<T>(res: Response, ctx: string): Promise<T> {
logCapacityError(ctx, text);
throw new RoundtableRoomFullError();
}
const displayed = roundtableErrorForDisplay(text, res.status);
if (
res.status === 409 ||
res.status === 429 ||
(displayed != null && displayed !== text)
) {
logCapacityError(ctx, text);
throw new Error(displayed || "会商暂时无法继续,请稍后重试");
}
throw new Error(`${ctx} failed (${res.status}): ${text}`);
}
return (await res.json()) as T;
@@ -84,14 +93,15 @@ function withAvatar(nodes: unknown): DispatchChainNode[] {
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 ?? "");
if (rawError && (isRoundtableCapacityFailure(null, rawError) || roundtableErrorForDisplay(rawError) !== rawError)) {
logCapacityError(id, rawError);
}
const dialogues = Array.isArray(raw.dialogues)
? (raw.dialogues as JobDialogue[]).map((dialogue) => {
if (!isRoundtableCapacityFailure(null, dialogue.content)) return dialogue;
const sanitized = sanitizeRoundtableDialogue(dialogue.content);
if (sanitized === dialogue.content) return dialogue;
logCapacityError(id, dialogue.content);
return { ...dialogue, content: ROUNDTABLE_ROOM_FULL_MESSAGE };
return { ...dialogue, content: sanitized };
})
: [];
return {
@@ -25,7 +25,9 @@ import { Sparkles } from "lucide-react";
import { streamJob } from "@/roundtable-planning/api/roundtable-jobs";
import {
isRoundtableCapacityFailure,
isRoundtableBusyFailure,
isRoundtableRoomFullFailure,
roundtableErrorForDisplay,
ROUNDTABLE_ROOM_FULL_MESSAGE,
} from "@/roundtable-planning/lib/capacity-error";
import type { RoundtableJob } from "@/roundtable-planning/lib/job-types";
@@ -88,10 +90,13 @@ export function RoundtableJobNotifier({ children }: { children: ReactNode }) {
if (job.status === "done") {
setNotice("后台研讨已完成!可在「历史记录」查看结论与报告");
} else if (job.status === "error") {
const displayed = roundtableErrorForDisplay(job.error);
setNotice(
isRoundtableCapacityFailure(null, job.error)
isRoundtableRoomFullFailure(null, job.error)
? ROUNDTABLE_ROOM_FULL_MESSAGE
: "后台任务执行出错,请在「历史记录」中查看",
: isRoundtableBusyFailure(null, job.error) || (displayed && displayed !== job.error)
? displayed || ROUNDTABLE_ROOM_FULL_MESSAGE
: "后台任务执行出错,请在「历史记录」中查看",
);
}
// cancelled:用户主动取消,不提示。
@@ -82,6 +82,10 @@ import type {
Step2Dialogue,
} from "@/roundtable-planning/hooks/useStep2Orchestration";
import { chainToDagPlan } from "@/roundtable-planning/lib/dag-types";
import {
resolveDagMilestoneStates,
resolveLiveDagNodeStates,
} from "@/roundtable-planning/lib/dag-flow-state";
import type { OrchestrationPlan } from "@/roundtable-planning/lib/dag-types";
import type { ChainNodeState } from "@/roundtable-planning/lib/job-types";
import {
@@ -368,61 +372,29 @@ export function Step2Panel(props: Step2PanelProps) {
},
[agentNameToRole],
);
// 有效节点状态(2026-06-13):live 编排时 dagNodeStates 实时推进;**查看聊天记录**
// (加载草稿 hydrate)时它是空的 → 从对话推导——已有「子智能体交付」内容的席位
// 点亮为 done,其余 pending。live 状态优先覆盖推导值(active 实时转圈不受影响)。
const effectiveDagNodeStates = useMemo(() => {
const merged: Record<string, ChainNodeState> = {};
const deliveredNames = new Set(
step2RoundtableDialogues
.filter(
(d) => d.confidence === "子智能体交付" && String(d.content ?? "").trim().length > 0,
)
.map((d) => String(d.sender ?? "")),
);
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, orchestrationMode]);
// 流程图跟当前发言走:席位气泡已经在输出时,节点就是进行中。
// dagNodeStates 里残留的 pending 不能把这个实时状态盖掉,否则总控会一直转圈。
const effectiveDagNodeStates = useMemo(
() =>
resolveLiveDagNodeStates({
agentNameToRole,
dialogues: step2RoundtableDialogues,
dagNodeStates,
parallelBatch,
}),
[dagNodeStates, step2RoundtableDialogues, agentNameToRole, parallelBatch],
);
// 总控 / 共识 / 报告里程碑状态:由有效节点状态 + 编排/共识标志派生。
const { dagCoordinatorState, dagConsensusState } = useMemo(() => {
const states = Object.values(effectiveDagNodeStates);
const anyActive = states.includes("active");
const anyStarted = states.some((s) => s !== "pending");
const allDone = states.length > 0 && states.every((s) => s === "done");
const coordinator: ChainNodeState = anyActive
? "done"
: isOrchestrating
? "active"
: anyStarted
? "done"
: "pending";
const consensus: ChainNodeState = hasConsensus
? "done"
: allDone
? "active"
: "pending";
return { dagCoordinatorState: coordinator, dagConsensusState: consensus };
}, [effectiveDagNodeStates, isOrchestrating, hasConsensus]);
const { dagCoordinatorState, dagConsensusState } = useMemo(
() =>
resolveDagMilestoneStates({
seatStates: effectiveDagNodeStates,
dialogues: step2RoundtableDialogues,
isOrchestrating,
hasConsensus,
}),
[effectiveDagNodeStates, step2RoundtableDialogues, isOrchestrating, hasConsensus],
);
// DAG 流程图小窗开关(2026-06-12:弹窗 → 消息列表右上角竖向小窗,直角连线)。
// DAG 编排一启动自动打开一次;沙箱打开时自动让位关闭;按钮可随时手动开/关。
@@ -22,6 +22,7 @@ import {
} from "@/components/workspace/artifacts";
import {
isRoundtableRoomFullError,
roundtableCardFailure,
type RoundtableRoomFullError,
} from "@/roundtable-planning/api/rooms";
import {
@@ -2356,7 +2357,8 @@ export function useStep2Orchestration(
continue;
}
console.error(`[special:${a.agentId}] error:`, err);
finalizeDialogue(a.bubbleId, `(错误) ${(err as Error).message}`, "调用失败");
const failure = roundtableCardFailure(err);
finalizeDialogue(a.bubbleId, failure.content || "(已停止)", failure.badge);
return { content: "", aborted: false, invalid: true };
}
}
@@ -2438,10 +2440,11 @@ export function useStep2Orchestration(
finalizeDialogue(leaderBubbleId, "(已停止)", "已停止");
break;
}
const failure = roundtableCardFailure(err);
finalizeDialogue(
leaderBubbleId,
`(错误) ${(err as Error).message}`,
"调用失败",
failure.content || "(已停止)",
failure.badge,
);
throw err;
}
@@ -2599,7 +2602,7 @@ export function useStep2Orchestration(
handleRoomFull(err);
return;
}
triggerToast(`研讨异常: ${(err as Error).message}`);
triggerToast(`研讨异常: ${roundtableCardFailure(err).content.replace(/^\(错误\) /, "")}`);
} finally {
highlightSpeaker(null);
clearAllStreamingSpeakers();
@@ -2730,10 +2733,11 @@ export function useStep2Orchestration(
finishedAllSeats = false;
break;
}
const failure = roundtableCardFailure(err);
finalizeDialogue(
leaderBubbleId,
`(错误) ${(err as Error).message}`,
"调用失败",
failure.content || "(已停止)",
failure.badge,
);
throw err;
}
@@ -2838,7 +2842,8 @@ export function useStep2Orchestration(
throw err;
} else {
console.error(`[chain-special:${seat.agent_id}] error:`, err);
finalizeDialogue(subBubbleId, `(错误) ${(err as Error).message}`, "调用失败");
const failure = roundtableCardFailure(err);
finalizeDialogue(subBubbleId, failure.content || "(已停止)", failure.badge);
seatInvalid = true;
}
} finally {
@@ -2949,7 +2954,8 @@ export function useStep2Orchestration(
throw err;
} else {
console.error("chain closeout error:", err);
finalizeDialogue(closeoutBubbleId, `(错误) ${(err as Error).message}`, "调用失败");
const failure = roundtableCardFailure(err);
finalizeDialogue(closeoutBubbleId, failure.content || "(已停止)", failure.badge);
}
} finally {
activeAbortersRef.current.delete(closeoutAborter);
@@ -2961,7 +2967,7 @@ export function useStep2Orchestration(
handleRoomFull(err);
return;
}
triggerToast(`链条研讨异常: ${(err as Error).message}`);
triggerToast(`链条研讨异常: ${roundtableCardFailure(err).content.replace(/^\(错误\) /, "")}`);
} finally {
highlightSpeaker(null);
clearAllStreamingSpeakers();
@@ -3138,10 +3144,11 @@ export function useStep2Orchestration(
finishedAllStages = false;
break;
}
const failure = roundtableCardFailure(err);
finalizeDialogue(
leaderBubbleId,
`(错误) ${(err as Error).message}`,
"调用失败",
failure.content || "(已停止)",
failure.badge,
);
throw err;
}
@@ -3297,7 +3304,8 @@ export function useStep2Orchestration(
throw err;
} else {
console.error(`[dag-special:${agentId}] error:`, err);
finalizeDialogue(bubbleId, `(错误) ${(err as Error).message}`, "调用失败");
const failure = roundtableCardFailure(err);
finalizeDialogue(bubbleId, failure.content || "(已停止)", failure.badge);
markBatchStatus(agentId, "error");
}
return { seatName, invalid: true, content: "" };
@@ -3386,7 +3394,7 @@ export function useStep2Orchestration(
handleRoomFull(err);
return;
}
triggerToast(`依赖编排研讨异常: ${(err as Error).message}`);
triggerToast(`依赖编排研讨异常: ${roundtableCardFailure(err).content.replace(/^\(错误\) /, "")}`);
} finally {
highlightSpeaker(null);
clearAllStreamingSpeakers();
@@ -2,33 +2,108 @@ import assert from "node:assert/strict";
import test from "node:test";
import {
isRoundtableBusyFailure,
isRoundtableCapacityFailure,
roomDecisionMessage,
roundtableCardFailure,
roundtableErrorForDisplay,
RoundtableRoomFullError,
ROUNDTABLE_BUSY_MESSAGE,
ROUNDTABLE_ROOM_FULL_MESSAGE,
} from "./capacity-error";
sanitizeRoundtableDialogue,
} from "./capacity-error.ts";
test("recognizes a direct HTTP 429", () => {
assert.equal(isRoundtableCapacityFailure(429, ""), true);
test("a direct HTTP 429 is model or worker busy, not a full room", () => {
assert.equal(isRoundtableCapacityFailure(429, ""), false);
assert.equal(isRoundtableBusyFailure(429, ""), true);
assert.equal(roundtableErrorForDisplay("", 429), ROUNDTABLE_BUSY_MESSAGE);
});
test("recognizes a 429 wrapped by the internal run stream gateway", () => {
test("a 429 wrapped by the internal run stream stays busy and hides the upstream URL", () => {
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);
assert.equal(isRoundtableCapacityFailure(502, detail), false);
assert.equal(isRoundtableBusyFailure(502, detail), true);
assert.equal(roundtableErrorForDisplay(detail, 502), ROUNDTABLE_BUSY_MESSAGE);
});
test("recognizes local concurrency and worker saturation messages", () => {
test("recognizes local concurrency and worker saturation messages as busy", () => {
const samples = [
"This account has reached the concurrency limit for the selected model",
"执行节点繁忙,请稍后重试",
"等待执行超时,请稍后重试",
"selected model is busy",
];
for (const detail of samples) {
assert.equal(isRoundtableCapacityFailure(502, detail), false);
assert.equal(isRoundtableBusyFailure(502, detail), true);
assert.equal(roundtableErrorForDisplay(detail, 502), ROUNDTABLE_BUSY_MESSAGE);
}
});
test("only the room-full code opens the room-full message", () => {
const detail = JSON.stringify({
detail: { code: "ROUNDTABLE_ROOM_FULL", message: "当前会商房间暂时已满,请稍候片刻后再试。" },
});
assert.equal(isRoundtableCapacityFailure(409, detail), true);
assert.equal(isRoundtableBusyFailure(409, detail), false);
assert.equal(roundtableErrorForDisplay(detail, 409), ROUNDTABLE_ROOM_FULL_MESSAGE);
assert.equal(roomDecisionMessage("ROUNDTABLE_ROOM_FULL"), ROUNDTABLE_ROOM_FULL_MESSAGE);
});
test("lease expiry and max hold keep their own messages", () => {
const lease = JSON.stringify({ code: "ROOM_LEASE_EXPIRED" });
const maxHold = JSON.stringify({ code: "ROOM_MAX_HOLD_EXCEEDED" });
assert.equal(isRoundtableCapacityFailure(409, lease), false);
assert.equal(isRoundtableCapacityFailure(409, maxHold), false);
assert.equal(roundtableErrorForDisplay(lease, 409), roomDecisionMessage("ROOM_LEASE_EXPIRED"));
assert.equal(
isRoundtableCapacityFailure(502, "This account has reached the concurrency limit for the selected model"),
true,
roundtableErrorForDisplay(maxHold, 409),
"本次会商已达到最长占用时间,房间已自动释放。请返回第一步后重新发起。",
);
assert.equal(isRoundtableCapacityFailure(502, "执行节点繁忙,请稍后重试"), true);
assert.equal(isRoundtableCapacityFailure(502, "等待执行超时,请稍后重试"), true);
});
test("a plain HTTP 409 is not treated as a full room", () => {
const detail = "thread already has an active run";
assert.equal(isRoundtableCapacityFailure(409, detail), false);
assert.equal(roundtableErrorForDisplay(detail, 409), detail);
});
test("does not hide an unrelated gateway error", () => {
const detail = "upstream returned HTTP 502: connection refused";
assert.equal(isRoundtableCapacityFailure(502, detail), false);
assert.equal(isRoundtableBusyFailure(502, detail), false);
assert.equal(roundtableErrorForDisplay(detail, 502), detail);
});
test("long seat deliveries that mention concurrency stay intact", () => {
const prose = `${"席位认为当前方案需要同时考虑资源并发和预算限制,建议先完成情报核对,再决定是否扩大行动范围。".repeat(20)}`;
assert.ok(prose.length > 800);
assert.equal(sanitizeRoundtableDialogue(prose), prose);
});
test("coordinator card does not relabel other failures as a full room", () => {
const lease = roundtableCardFailure(
new Error(JSON.stringify({ code: "ROOM_LEASE_EXPIRED" })),
);
assert.equal(lease.roomFull, false);
assert.equal(lease.badge, "调用失败");
assert.equal(lease.content.includes("当前房间已满"), false);
assert.equal(lease.content.includes("会商连接已断开"), true);
const busy = roundtableCardFailure(new Error("执行节点繁忙,请稍后重试"));
assert.equal(busy.badge, "调用失败");
assert.equal(busy.content.includes(ROUNDTABLE_ROOM_FULL_MESSAGE), false);
assert.equal(busy.content.includes(ROUNDTABLE_BUSY_MESSAGE), true);
const full = roundtableCardFailure(new RoundtableRoomFullError());
assert.equal(full.roomFull, true);
assert.equal(full.badge, "已停止");
assert.equal(full.content.includes("调用失败"), false);
assert.equal(full.content.includes(ROUNDTABLE_ROOM_FULL_MESSAGE), false);
});
test("error-shaped dialogue with an upstream address is replaced", () => {
const detail = "[502] upstream http://10.0.0.8/api/threads/abc/runs/stream returned HTTP 500";
assert.equal(sanitizeRoundtableDialogue(detail), "会商暂时无法继续,请稍后重试");
});
@@ -1,8 +1,63 @@
/** 会商容量不足时唯一允许展示给业务用户的文案。 */
/** 会商名额真正用尽时,唯一允许展示给业务用户的文案。 */
export const ROUNDTABLE_ROOM_FULL_MESSAGE = "当前房间已满,请稍后";
/** 模型并发或执行节点忙,不是会商房间名额。 */
export const ROUNDTABLE_BUSY_MESSAGE = "当前模型或执行节点繁忙,请稍后重试";
const GENERIC_ROUNDTABLE_FAILURE = "会商暂时无法继续,请稍后重试";
const ROOM_DECISION_MESSAGES: Record<string, string> = {
ROUNDTABLE_ROOM_FULL: ROUNDTABLE_ROOM_FULL_MESSAGE,
ROOM_LEASE_EXPIRED: "会商连接已断开,请重新恢复研讨。",
ROOM_MAX_HOLD_EXCEEDED:
"本次会商已达到最长占用时间,房间已自动释放。请返回第一步后重新发起。",
ROOM_STORE_UNAVAILABLE: "会商并发服务暂不可用,请稍后再试。",
ROOM_SESSION_REQUIRED: "会商会话标识缺失,请刷新页面后重试。",
DRAFT_REQUIRED: "进入第二步需要先保存会商草稿",
};
export function roomDecisionMessage(code: string | null | undefined): string | null {
if (!code) return null;
return ROOM_DECISION_MESSAGES[code] ?? null;
}
function isBusyText(text: string): boolean {
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)
);
}
function readRoomCode(detail: string): string {
const match = detail.match(/["']code["']\s*:\s*["']([A-Z0-9_]+)["']/);
if (match?.[1]) return match[1];
try {
const body = JSON.parse(detail) as {
code?: unknown;
detail?: { code?: unknown };
};
const code = body.detail?.code ?? body.code;
return typeof code === "string" ? code : "";
} catch {
return "";
}
}
function isRoomFullText(text: string, code: string): boolean {
if (code === "ROUNDTABLE_ROOM_FULL") return true;
return (
text === ROUNDTABLE_ROOM_FULL_MESSAGE ||
text.includes("当前会商房间暂时已满")
);
}
/**
* 会商运行过程中遇到的容量错误。
* 会商运行过程中遇到的名额已满。
*
* 原始响应只能写入控制台 / 诊断日志,不能放进 message,避免内网地址、thread id
* 等实现细节经现有的 toast / 对话气泡 / 错误面板泄露到页面。
@@ -27,37 +82,133 @@ export function isRoundtableRoomFullError(error: unknown): error is RoundtableRo
}
/**
* Gateway 会把内部 `/runs/stream` 的 429 包装成 502 或 SSE error 帧,因此不能只看
* 最外层 HTTP 状态。这里同时识别包装后的状态文本和本地并发闸门的稳定错误文案。
* 总控/席位卡片上的失败展示。
* 名额用尽不写进卡片(由房间弹窗说明,标签也不再是「调用失败」)。
* 租约断开、模型繁忙仍标「调用失败」,但不得改写成房间已满文案。
*/
export function roundtableCardFailure(error: unknown): {
roomFull: boolean;
badge: string;
content: string;
} {
if (isRoundtableRoomFullError(error)) {
return {
roomFull: true,
badge: "已停止",
content: "",
};
}
const raw = error instanceof Error ? error.message : String(error ?? "");
const displayed = roundtableErrorForDisplay(raw);
const message =
displayed && displayed !== ROUNDTABLE_ROOM_FULL_MESSAGE
? displayed
: "会商暂时无法继续,请稍后重试";
return {
roomFull: false,
badge: "调用失败",
content: `(错误) ${message}`,
};
}
/** 只有会商房间名额用尽才返回 true。模型繁忙、租约丢失、最长占用都不是。 */
export function isRoundtableRoomFullFailure(
status: number | null | undefined,
detail: string | null | undefined,
): boolean {
const text = (detail ?? "").trim();
if (!text && status !== 409) return false;
return isRoomFullText(text, readRoomCode(text));
}
/** 模型并发或执行节点忙。调用方不得据此释放会商房间。 */
export function isRoundtableBusyFailure(
status: number | null | undefined,
detail: string | null | undefined,
): boolean {
if (isRoundtableRoomFullFailure(status, detail)) return false;
if (status === 429) return true;
const text = (detail ?? "").trim();
return text ? isBusyText(text) : false;
}
/**
* 旧名保留给调用方。语义收窄为「房间名额已满」,不再把 429 / 节点繁忙算进去。
*/
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)
);
return isRoundtableRoomFullFailure(status, detail);
}
/** 页面可展示的错误详情;容量错误永远折叠为统一文案。 */
function readCounts(detail: string): { activeCount: number; maxRooms: number } {
try {
const body = JSON.parse(detail) as {
detail?: { active_count?: number; max_rooms?: number };
active_count?: number;
max_rooms?: number;
};
return {
activeCount: body.detail?.active_count ?? body.active_count ?? 0,
maxRooms: body.detail?.max_rooms ?? body.max_rooms ?? 0,
};
} catch {
return { activeCount: 0, maxRooms: 0 };
}
}
export function roundtableRoomFullError(
rawDetail: string,
status: number | null,
context: string,
): RoundtableRoomFullError {
const counts = readCounts(rawDetail);
console.error(`[roundtable-capacity] ${context}`, {
status,
detail: rawDetail,
});
return new RoundtableRoomFullError(counts.activeCount, counts.maxRooms);
}
function containsTransportDetail(text: string): boolean {
return /https?:\/\//i.test(text) || /\/api\/threads\//i.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;
if (detail == null && status !== 429) return null;
const text = (detail ?? "").trim();
if (isRoundtableRoomFullFailure(status, text)) return ROUNDTABLE_ROOM_FULL_MESSAGE;
if (isRoundtableBusyFailure(status, text)) return ROUNDTABLE_BUSY_MESSAGE;
if (!text) return detail ?? null;
const code = readRoomCode(text);
const known = ROOM_DECISION_MESSAGES[code];
if (known) return known;
if (containsTransportDetail(text)) return GENERIC_ROUNDTABLE_FAILURE;
return detail;
}
/**
* 只改写明显是错误载荷的短文本。正常席位交付即使提到「并发」「限制」也保持原文。
*/
export function sanitizeRoundtableDialogue(content: string): string {
const text = content.trim();
if (!text) return content;
const errorShaped =
text.length <= 800 ||
/^\[\d{3}\]/.test(text) ||
text.includes("returned HTTP") ||
text.includes("ROUNDTABLE_ROOM_") ||
text.includes("ROOM_LEASE_") ||
text.includes("ROOM_MAX_HOLD_") ||
text.includes("ROOM_STORE_") ||
text.includes("ROOM_SESSION_");
if (!errorShaped) return content;
const display = roundtableErrorForDisplay(text);
if (!display || display === text) return content;
return display;
}
@@ -0,0 +1,50 @@
import assert from "node:assert/strict";
import test from "node:test";
import { resolveDagMilestoneStates, resolveLiveDagNodeStates } from "./dag-flow-state.ts";
const roles = {
"seat-01": { displayName: "测试01" },
"seat-02": { displayName: "测试02" },
};
test("a streaming first seat takes the in-progress marker off the coordinator", () => {
const seats = resolveLiveDagNodeStates({
agentNameToRole: roles,
dialogues: [
{ sender: "总控协调", streaming: false, confidence: "派活说明", content: "派给测试01" },
{ sender: "测试01", streaming: true, confidence: "调度中", content: "" },
],
dagNodeStates: { "seat-01": "pending", "seat-02": "pending" },
parallelBatch: [],
});
assert.equal(seats["seat-01"], "active");
assert.equal(seats["seat-02"], "pending");
const milestones = resolveDagMilestoneStates({
seatStates: seats,
dialogues: [
{ sender: "总控协调", streaming: false },
{ sender: "测试01", streaming: true },
],
isOrchestrating: true,
hasConsensus: false,
});
assert.equal(milestones.coordinator, "done");
});
test("the coordinator stays in progress while it is still the one speaking", () => {
const seats = resolveLiveDagNodeStates({
agentNameToRole: roles,
dialogues: [{ sender: "总控协调", streaming: true, confidence: "派活中", content: "" }],
dagNodeStates: { "seat-01": "pending", "seat-02": "pending" },
parallelBatch: [],
});
const milestones = resolveDagMilestoneStates({
seatStates: seats,
dialogues: [{ sender: "总控协调", streaming: true }],
isOrchestrating: true,
hasConsensus: false,
});
assert.equal(milestones.coordinator, "active");
assert.equal(seats["seat-01"], "pending");
});
@@ -0,0 +1,92 @@
import type { ChainNodeState } from "./job-types.ts";
/** 与 seat-filter 的 COORDINATOR_SENDER 相同。这里单独写出,避免测试去拉前端模块图。 */
const COORDINATOR_SENDER = "总控协调";
export interface DagFlowDialogue {
sender?: string;
streaming?: boolean;
confidence?: string;
content?: string;
}
export interface DagFlowSeatMeta {
displayName: string;
}
/**
* 流程图节点状态。
*
* 实时发言以对话气泡为准:席位气泡已经在流式输出时,节点必须是进行中,
* 不能被一份还停在 pending 的 dagNodeStates 盖回去。总控只在自己发言、
* 且还没有任何席位进行中时保持进行中。
*/
export function resolveLiveDagNodeStates(input: {
agentNameToRole: Record<string, DagFlowSeatMeta>;
dialogues: readonly DagFlowDialogue[];
dagNodeStates: Record<string, ChainNodeState>;
parallelBatch: readonly { agentId: string; status: string }[];
}): Record<string, ChainNodeState> {
const merged: Record<string, ChainNodeState> = {};
const keyOf = (value: string) => value.trim().toLowerCase();
const streamingSenders = new Set(
input.dialogues.filter((d) => d.streaming).map((d) => keyOf(String(d.sender ?? ""))),
);
const deliveredSenders = new Set(
input.dialogues
.filter(
(d) =>
d.confidence === "子智能体交付" && String(d.content ?? "").trim().length > 0,
)
.map((d) => keyOf(String(d.sender ?? ""))),
);
const matches = (agentId: string, displayName: string, senders: Set<string>) =>
senders.has(keyOf(displayName)) || senders.has(keyOf(agentId));
for (const [agentId, meta] of Object.entries(input.agentNameToRole)) {
if (matches(agentId, meta.displayName, deliveredSenders)) {
merged[keyOf(agentId)] = "done";
}
}
for (const seat of input.parallelBatch) {
merged[keyOf(seat.agentId)] = seat.status === "done" ? "done" : "active";
}
for (const [agentId, state] of Object.entries(input.dagNodeStates)) {
const key = keyOf(agentId);
if (state === "pending" && (merged[key] === "active" || merged[key] === "done")) {
continue;
}
merged[key] = state;
}
for (const [agentId, meta] of Object.entries(input.agentNameToRole)) {
if (matches(agentId, meta.displayName, streamingSenders)) {
merged[keyOf(agentId)] = "active";
}
}
return merged;
}
export function resolveDagMilestoneStates(input: {
seatStates: Record<string, ChainNodeState>;
dialogues: readonly DagFlowDialogue[];
isOrchestrating: boolean;
hasConsensus: boolean;
}): { coordinator: ChainNodeState; consensus: ChainNodeState } {
const states = Object.values(input.seatStates);
const anyActive = states.includes("active");
const anyStarted = states.some((state) => state !== "pending");
const coordinatorStreaming = input.dialogues.some(
(d) => d.streaming && String(d.sender ?? "") === COORDINATOR_SENDER,
);
const coordinator: ChainNodeState = anyActive
? "done"
: coordinatorStreaming || (input.isOrchestrating && !anyStarted)
? "active"
: anyStarted
? "done"
: "pending";
const allDone = states.length > 0 && states.every((state) => state === "done");
const consensus: ChainNodeState = input.hasConsensus ? "done" : allDone ? "active" : "pending";
return { coordinator, consensus };
}
@@ -68,6 +68,7 @@ import {
} from "@/components/ui/dialog";
import { getStoredAuth } from "@/core/auth";
import { useRouteNavigate } from "@/core/route-base";
import { usePageDescriptionsSettings } from "@/core/system-settings/hooks";
import { cn } from "@/lib/utils";
import { useDesensitizeSubtree } from "@/roundtable-planning/lib/use-desensitize-subtree";
@@ -101,6 +102,8 @@ export default function BusinessChainListPage() {
const dzRef = useDesensitizeSubtree<HTMLDivElement>();
// 管理员:额外多一个「全部链条」筛选,且可编辑 / 发布 / 删除任意账号的链条。
const isAdmin = getStoredAuth()?.system_role === "admin";
const pageDescriptions = usePageDescriptionsSettings();
const pageDescription = pageDescriptions.data?.business_chains;
// 进入编辑器:带 chainId = 打开并切到该链条;不带 = 空白新建。
// 路径写 workspace base,`useRouteNavigate` 会按当前路由 base 改写。
@@ -333,13 +336,10 @@ export default function BusinessChainListPage() {
<div className="mx-auto flex w-full max-w-7xl flex-col gap-4 md:flex-row md:items-center md:justify-between">
<div className="min-w-0">
<h1 className="flex items-center text-lg font-bold tracking-tight text-zinc-900 dark:text-[#E8EDF5]">
业务链条配置
<span className="ml-2 rounded-md border border-[#CF1322]/30 bg-[#FFF1F0] px-2 py-0.5 text-[10px] font-bold uppercase tracking-wider text-[#CF1322] dark:border-[#A8071A]/40 dark:bg-[#A8071A]/20 dark:text-[#FF7875]">
Orchestrator v2
</span>
{pageDescription?.title || "业务链条配置"}
</h1>
<p className="mt-1 max-w-xl text-xs text-zinc-500 dark:text-[#6E88B0]">
可复用的有序智能体编排。点击卡片「设置」更新节点参数;「发布」后所有账号都能在「公共」里查看 / 选用。
{pageDescription?.description || "可复用的有序智能体编排。点击卡片「设置」更新节点参数;「发布」后所有账号都能在「公共」里查看 / 选用。"}
</p>
</div>
@@ -164,6 +164,10 @@ import {
releaseRoundtableRoom,
ROUNDTABLE_ROOM_FULL_MESSAGE,
} from "@/roundtable-planning/api/rooms";
import {
isRoundtableRoomFullFailure,
roomDecisionMessage,
} from "@/roundtable-planning/lib/capacity-error";
import { isRoundtableRoomExecutionActive } from "@/roundtable-planning/lib/room-lifecycle";
import {
Dialog,
@@ -492,10 +496,13 @@ export default function RoundtablePlanningPage({
roomSessionId: roomSessionIdRef.current,
});
const roomHoldRef = useRef(false);
const roomBlockRef = useRef<string | null>(null);
const roomReleasePromiseRef = useRef<Promise<unknown> | null>(null);
const roomAcquirePromiseRef = useRef<Promise<boolean> | null>(null);
const roomHandoffRef = useRef(false);
const roomEffectGenRef = useRef(0);
const [roomFull, setRoomFull] = useState(false);
const [roomLeaseEpoch, setRoomLeaseEpoch] = useState(0);
// 由 prefill.businessCode 解析出的「自动选用业务链」结果;有值时「进入研讨」跳过选链弹窗直接进 Step 2。
const [autoChainResult, setAutoChainResult] = useState<SeatSelectionResult | null>(null);
// 固定业务链(8BF 等独立页面)的解析状态。不能只以 autoChainResult 是否为空判断:
@@ -1347,14 +1354,30 @@ export default function RoundtablePlanningPage({
const taskId = draftStorageTaskId ?? null;
roomSessionIdRef.current = createRoomSessionId();
const roomSessionId = roomSessionIdRef.current;
roomBlockRef.current = null;
roomScopeRef.current = { draftId, taskId, roomSessionId };
const acquirePromise = (async () => {
try {
const decision = await acquireRoundtableRoom({ draftId, taskId, roomSessionId });
if (!decision.ok) {
setRoomFull(true);
if (decision.code === "ROOM_MAX_HOLD_EXCEEDED") {
roomBlockRef.current = decision.code;
}
if (
decision.code === "ROUNDTABLE_ROOM_FULL" ||
isRoundtableRoomFullFailure(409, decision.message)
) {
setRoomFull(true);
} else {
triggerToast(
decision.message ||
roomDecisionMessage(decision.code) ||
"暂时不能进入第二步",
);
}
return false;
}
roomBlockRef.current = null;
roomHoldRef.current = true;
return true;
} catch (error) {
@@ -1371,6 +1394,85 @@ export default function RoundtablePlanningPage({
},
[drafts, draftStorageTaskId, triggerToast],
);
const reacquireLiveRoom = useCallback(async (force = false) => {
if (!force && roomHoldRef.current) return true;
if (roomBlockRef.current === "ROOM_MAX_HOLD_EXCEEDED") {
roomHoldRef.current = false;
triggerToast(
roomDecisionMessage("ROOM_MAX_HOLD_EXCEEDED") ||
"本次会商已达到最长占用时间,房间已自动释放。请返回第一步后重新发起。",
);
return false;
}
if (roomAcquirePromiseRef.current) return roomAcquirePromiseRef.current;
const pendingRelease = roomReleasePromiseRef.current;
if (pendingRelease) {
try {
await pendingRelease;
} catch {
// 释放是尽力而为,失败也不阻止用户重新占用同一个房间。
}
}
const scope = roomScopeRef.current;
if (!scope.draftId || !scope.roomSessionId) {
triggerToast("会商草稿尚未保存,暂时不能恢复");
return false;
}
const { draftId, taskId, roomSessionId } = scope;
const acquirePromise = (async () => {
try {
const decision = await acquireRoundtableRoom({ draftId, taskId, roomSessionId });
if (!decision.ok) {
roomHoldRef.current = false;
if (decision.code === "ROOM_MAX_HOLD_EXCEEDED") {
roomBlockRef.current = decision.code;
}
if (
decision.code === "ROUNDTABLE_ROOM_FULL" ||
isRoundtableRoomFullFailure(409, decision.message)
) {
setRoomFull(true);
} else {
triggerToast(
decision.message ||
roomDecisionMessage(decision.code) ||
"暂时不能恢复会商",
);
}
return false;
}
roomBlockRef.current = null;
roomHoldRef.current = true;
drafts.loadedFromDraftRef.current = false;
setRoomLeaseEpoch((epoch) => epoch + 1);
return true;
} catch (error) {
roomHoldRef.current = false;
triggerToast(
`无法确认会商房间:${error instanceof Error ? error.message : "请稍后再试"}`,
);
return false;
} finally {
roomAcquirePromiseRef.current = null;
}
})();
roomAcquirePromiseRef.current = acquirePromise;
return acquirePromise;
}, [drafts, triggerToast]);
const resumeLiveRoundtable = useCallback(() => {
void (async () => {
if (roomBlockRef.current === "ROOM_MAX_HOLD_EXCEEDED") {
triggerToast(
roomDecisionMessage("ROOM_MAX_HOLD_EXCEEDED") ||
"本次会商已达到最长占用时间,房间已自动释放。请返回第一步后重新发起。",
);
return;
}
const admitted = await reacquireLiveRoom(true);
if (!admitted) return;
step2.resumeRoundtable();
})();
}, [reacquireLiveRoom, step2, triggerToast]);
const handleConfirmAgents = useCallback(
(result: SeatSelectionResult) => {
void (async () => {
@@ -2320,16 +2422,31 @@ export default function RoundtablePlanningPage({
return;
}
roomHoldRef.current = false;
if (decision.code === "ROOM_MAX_HOLD_EXCEEDED") {
roomBlockRef.current = decision.code;
}
step2.stopOrchestration();
step2.setIsRoundTableRunning(false);
if (
decision.code === "ROUNDTABLE_ROOM_FULL" ||
isRoundtableRoomFullFailure(409, decision.message)
) {
setRoomFull(true);
}
triggerToast(
decision.message || "本次会商房间已释放,研讨已停止。记录仍留在当前页。",
);
void releaseRoundtableRoom({
const releasePromise = releaseRoundtableRoom({
draftId,
taskId: scope.taskId,
roomSessionId: scope.roomSessionId,
}).catch(() => {});
roomReleasePromiseRef.current = releasePromise;
void releasePromise.finally(() => {
if (roomReleasePromiseRef.current === releasePromise) {
roomReleasePromiseRef.current = null;
}
});
})
.catch(() => {
// 心跳请求失败只能说明本次续租请求没有得到响应,不能据此终止仍在
@@ -2369,7 +2486,9 @@ export default function RoundtablePlanningPage({
currentStep,
step2.hasConsensus,
step2.stopOrchestration,
step2.setIsRoundTableRunning,
triggerToast,
roomLeaseEpoch,
]);
// 研讨一启动(真正进入生成)就确保草稿存在:自动挂起 / beforeunload beacon 需要
// draftId 同步可取,历史下拉的「进行中」徽标也按 draftId 关联。ensureDraft 幂等。
@@ -2891,7 +3010,7 @@ export default function RoundtablePlanningPage({
openArtifactFromStep={step2.openArtifactFromStep}
openArtifactPreview={step2.openArtifactPreview}
onPauseRoundtable={step2.pauseRoundtable}
onResumeRoundtable={step2.resumeRoundtable}
onResumeRoundtable={resumeLiveRoundtable}
onHandleInjectToRoundtable={step2.handleInjectToRoundtable}
setClarificationDraft={step2.setClarificationDraft}
setCustomAgentInput={step2.setCustomAgentInput}