1337 lines
62 KiB
JavaScript
1337 lines
62 KiB
JavaScript
window.__ModuleLoader__.load({
|
||
id: "dsh-sansheng-liubu-panel",
|
||
factory: (require) => {
|
||
var module = { exports: {} };
|
||
var exports = module.exports;
|
||
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
||
|
||
const React = require("react");
|
||
const h = React.createElement;
|
||
|
||
// #region 常量与纯函数(与 lib/model.js 保持一致,客户端 bundle 需自包含)
|
||
const PANEL_ID = "sansheng-liubu";
|
||
const SANSENG_TAB_ID = PANEL_ID + "-tab";
|
||
const SANSENG_TAB_KIND = "sansheng";
|
||
|
||
const ROLE_IDS = ["lead", "zhongshu", "menxia", "shangshu", "gongbu", "libu", "bingbu"];
|
||
const ROLE_LABELS = {
|
||
lead: "丞相",
|
||
zhongshu: "中书省",
|
||
menxia: "门下省",
|
||
shangshu: "尚书省",
|
||
gongbu: "工部",
|
||
libu: "礼部",
|
||
bingbu: "兵部",
|
||
};
|
||
const ROLE_MARKS = {
|
||
lead: "丞",
|
||
zhongshu: "中",
|
||
menxia: "门",
|
||
shangshu: "尚",
|
||
gongbu: "工",
|
||
libu: "礼",
|
||
bingbu: "兵",
|
||
};
|
||
const ROLE_DUTIES = {
|
||
lead: "统筹全局、向用户汇报、最终交付",
|
||
zhongshu: "拟案规划,拆解任务与验收标准",
|
||
menxia: "审议准奏与交付验收,可否决",
|
||
shangshu: "派工调度,合成各部门成果",
|
||
gongbu: "编码与工程实现",
|
||
libu: "文档、汇报与可视化产出",
|
||
bingbu: "调试、测试与问题定位",
|
||
};
|
||
const ROW_OF = { lead: 0, zhongshu: 1, shangshu: 1, menxia: 1, gongbu: 2, libu: 2, bingbu: 2 };
|
||
const COLUMN_OF = { zhongshu: 0, shangshu: 1, menxia: 2, gongbu: 0, libu: 1, bingbu: 2 };
|
||
const STATUS_LABELS = {
|
||
running: "运行中",
|
||
inactive: "空闲",
|
||
provisioning: "创建中",
|
||
failed: "失败",
|
||
absent: "未设官",
|
||
};
|
||
const TASK_LABELS = { pending: "待办", in_progress: "执行中", completed: "已完成" };
|
||
const EFFORT_LABELS = { minimal: "极低", low: "低", medium: "中", high: "高", max: "最高", xhigh: "极高" };
|
||
|
||
function roleLabel(role) {
|
||
return ROLE_LABELS[role] || "成员";
|
||
}
|
||
|
||
function roleMark(role) {
|
||
return ROLE_MARKS[role] || "员";
|
||
}
|
||
|
||
function modelLabel(model) {
|
||
if (typeof model === "string") return model;
|
||
if (!model || typeof model !== "object") return "";
|
||
if (typeof model.name === "string") return model.name;
|
||
if (typeof model.model === "string") return model.model;
|
||
if (typeof model.id === "string") return model.id;
|
||
return "";
|
||
}
|
||
|
||
function effortLabel(effort) {
|
||
if (typeof effort !== "string") return "";
|
||
return EFFORT_LABELS[effort] || effort;
|
||
}
|
||
|
||
function shortText(value, limit) {
|
||
const text = String(value === undefined || value === null ? "" : value).replace(/\s+/g, " ").trim();
|
||
const max = limit || 120;
|
||
return text.length <= max ? text : text.slice(0, max - 1) + "…";
|
||
}
|
||
|
||
function arrangeRoster(team) {
|
||
const members = Array.isArray(team && team.members) ? team.members : [];
|
||
const byRole = new Map();
|
||
for (const member of members) {
|
||
if (member && typeof member.name === "string") byRole.set(member.name, member);
|
||
}
|
||
return ROLE_IDS.map((role) => {
|
||
const member = byRole.get(role);
|
||
return {
|
||
role,
|
||
label: ROLE_LABELS[role],
|
||
mark: ROLE_MARKS[role],
|
||
duty: ROLE_DUTIES[role],
|
||
row: ROW_OF[role],
|
||
column: COLUMN_OF[role],
|
||
id: member && member.id,
|
||
member,
|
||
present: member !== undefined,
|
||
};
|
||
});
|
||
}
|
||
|
||
function memberStatus(member, running, summaryRunning) {
|
||
if (member === undefined || member === null) return "absent";
|
||
if (member.phase === "failed") return "failed";
|
||
if (member.phase === "provisioning") return "provisioning";
|
||
return running === true || summaryRunning === true ? "running" : "idle";
|
||
}
|
||
|
||
function bucketsOf(tasks) {
|
||
const buckets = { pending: [], in_progress: [], completed: [] };
|
||
for (const task of Array.isArray(tasks) ? tasks : []) {
|
||
const key = task && task.status;
|
||
if (key === "pending" || key === "in_progress" || key === "completed") buckets[key].push(task);
|
||
else buckets.pending.push(task);
|
||
}
|
||
return buckets;
|
||
}
|
||
|
||
/** 归属某部门的任务;ownerName 可能是角色 id 也可能是中文名。 */
|
||
function tasksOfRole(tasks, role) {
|
||
const list = Array.isArray(tasks) ? tasks : Array.isArray(tasks && tasks.tasks) ? tasks.tasks : [];
|
||
return list.filter((task) => task && (task.ownerName === role || task.ownerName === roleLabel(role)));
|
||
}
|
||
|
||
function statusSummary(seat, team, running, summaryRunning) {
|
||
const status = memberStatus(seat && seat.member, running, summaryRunning);
|
||
const owned = seat ? tasksOfRole(team, seat.role) : [];
|
||
const buckets = bucketsOf(owned);
|
||
return {
|
||
status,
|
||
statusLabel: STATUS_LABELS[status] || status,
|
||
owned,
|
||
runningCount: buckets.in_progress.length,
|
||
pendingCount: buckets.pending.length,
|
||
completedCount: buckets.completed.length,
|
||
};
|
||
}
|
||
|
||
function modelOptions(catalog) {
|
||
const options = [];
|
||
const groups = Array.isArray(catalog && catalog.groups) ? catalog.groups : [];
|
||
for (const group of groups) {
|
||
const provider = group && (group.id || group.provider);
|
||
const models = Array.isArray(group && group.models) ? group.models : [];
|
||
for (const model of models) {
|
||
if (!provider || !model || !model.id) continue;
|
||
const efforts = Array.isArray(model.reasoning && model.reasoning.efforts)
|
||
? model.reasoning.efforts.map((effort) => ({ id: effort.id, name: effort.name || effortLabel(effort.id) }))
|
||
: [];
|
||
options.push({
|
||
provider,
|
||
model: model.id,
|
||
rowId: provider + "/" + model.id,
|
||
label: model.name || model.id,
|
||
efforts,
|
||
defaultEffort: model.reasoning && model.reasoning.defaultEffort,
|
||
});
|
||
}
|
||
}
|
||
return options;
|
||
}
|
||
|
||
function findModelOption(options, current) {
|
||
if (!current || !current.provider || !current.model) return undefined;
|
||
return options.find((option) => option.provider === current.provider && option.model === current.model);
|
||
}
|
||
|
||
function modelSwitchPlan(current, next, addressesSubagent) {
|
||
if (addressesSubagent === true) {
|
||
return { ok: false, reason: "子会话不能单独更换模型;请在丞相会话中设置,或新建会话时选择" };
|
||
}
|
||
if (!next || !next.provider || !next.model) return { ok: false, reason: "未选择模型" };
|
||
const effort = next.reasoningEffort === undefined ? undefined : next.reasoningEffort;
|
||
if (current && current.provider === next.provider && current.model === next.model && (current.reasoningEffort || undefined) === effort) {
|
||
return { ok: false, reason: "与当前设置相同" };
|
||
}
|
||
const payload = { provider: next.provider, model: next.model };
|
||
if (effort !== undefined) payload.reasoningEffort = effort;
|
||
return { ok: true, payload };
|
||
}
|
||
|
||
function decreeText(role, text, team) {
|
||
const body = String(text === undefined || text === null ? "" : text).trim();
|
||
if (body === "") return "";
|
||
const active = (Array.isArray(team && team.tasks) ? team.tasks : [])
|
||
.filter((task) => task && task.status === "in_progress")
|
||
.map((task) => task.subject || task.title || task.id)
|
||
.filter(Boolean);
|
||
const context = active.length > 0 ? "\n(当前在办:" + active.join(";") + ")" : "";
|
||
return "【丞相下旨 · " + roleLabel(role) + "】\n" + body + context;
|
||
}
|
||
|
||
/** 从 TextBlock 数组里拼出纯文本(Chat 的 content/root 结构在不同节点上略有差异)。 */
|
||
function textOfBlocks(blocks) {
|
||
if (!Array.isArray(blocks)) return "";
|
||
return blocks
|
||
.filter((block) => block && (block.kind === "text" || block.type === "text"))
|
||
.map((block) => block.text)
|
||
.filter((text) => typeof text === "string")
|
||
.join("\n")
|
||
.trim();
|
||
}
|
||
|
||
/** 按 anchorSeq 排序后取最近一条用户输入与最近一条助手文本。 */
|
||
function lastExchange(nodes) {
|
||
const list = (Array.isArray(nodes) ? nodes : []).filter(Boolean);
|
||
const ordered = list.slice().sort((left, right) => {
|
||
const a = Number(left.anchorSeq ?? 0);
|
||
const b = Number(right.anchorSeq ?? 0);
|
||
return a === b ? 0 : a < b ? -1 : 1;
|
||
});
|
||
let lastUser = "";
|
||
let lastAssistant = "";
|
||
for (const node of ordered) {
|
||
const data = node.data || {};
|
||
if (node.kind === "user") {
|
||
const text = textOfBlocks(data.content);
|
||
if (text !== "") lastUser = shortText(text, 180);
|
||
} else if (node.kind === "assistant" || node.kind === "assistant-step") {
|
||
const text = textOfBlocks(data.blocks) || textOfBlocks(data.root && data.root.blocks) || (typeof data.root === "string" ? data.root : "");
|
||
if (text !== "") lastAssistant = shortText(text, 220);
|
||
}
|
||
}
|
||
return { lastUser, lastAssistant };
|
||
}
|
||
// #endregion
|
||
|
||
/** 由 apply() 建立,向 main 槽条目传递 uiWorkspace(root 槽拿不到会话级服务)。 */
|
||
let WorkspaceContext = null;
|
||
|
||
// #region 样式
|
||
const css = `
|
||
.sl-toggle{appearance:none;border:0;background:0 0;color:var(--dsw-alias-label-tertiary,#8a8f98);font:inherit;font-size:12px;display:inline-flex;align-items:center;gap:6px;padding:3px 7px;border-radius:6px;cursor:pointer;min-height:28px}
|
||
.sl-toggle:hover,.sl-toggle:focus-visible{color:var(--dsw-alias-label-primary,#1f2329);background:var(--dsw-alias-bg-layer-2,rgba(127,127,127,.08))}
|
||
.sl-toggle.active{color:var(--dsw-alias-label-primary,#1f2329);background:var(--dsw-alias-bg-layer-2,rgba(127,127,127,.12))}
|
||
.sl-toggle-mark{font-size:10px;letter-spacing:.06em;padding:1px 4px;border-radius:4px;border:1px solid currentColor;opacity:.8}
|
||
.sl-pinrow{display:flex;align-items:center;gap:10px;width:100%;appearance:none;border:0;background:0 0;color:var(--dsw-alias-label-primary,#1f2329);font:inherit;font-size:12px;padding:6px 10px;border-radius:6px;cursor:pointer;text-align:left}
|
||
.sl-pinrow:hover,.sl-pinrow:focus-visible{background:var(--dsw-alias-interactive-bg-hover,rgba(127,127,127,.1))}
|
||
.sl-pinrow.active{color:var(--dsw-alias-label-primary,#1f2329);font-weight:600}
|
||
.sl-pinrow-label{flex:1}
|
||
.sl-pinrow-hint{color:var(--dsw-alias-label-caption,#9aa0a6);font-size:11px}
|
||
.sl-root{display:flex;flex-direction:column;height:100%;min-height:0;background:var(--dsw-alias-bg-layer-1,#fff);color:var(--dsw-alias-label-primary,#1f2329);font-size:13px;line-height:20px}
|
||
.sl-crash{display:flex;flex-direction:column;gap:8px;margin:24px;padding:18px 20px;border:1px solid #e5484d;border-radius:10px;background:#fff5f5;color:#8b1a1d;font-size:13px;line-height:20px;white-space:normal}
|
||
.sl-crash strong{font-size:14px}
|
||
.sl-crash pre{margin:0;padding:10px 12px;border-radius:6px;background:rgba(127,127,127,.08);font-size:12px;line-height:18px;white-space:pre-wrap;word-break:break-all;overflow:auto;max-height:240px}
|
||
.sl-crash p{margin:0;color:var(--dsw-alias-label-tertiary,#8a8f98);font-size:12px}
|
||
.sl-head{display:flex;align-items:center;gap:10px;padding:10px 16px;border-bottom:1px solid var(--dsw-alias-border-l1,rgba(127,127,127,.14));flex:none}
|
||
.sl-head h1{margin:0;font-size:14px;font-weight:600;letter-spacing:.02em}
|
||
.sl-head small{color:var(--dsw-alias-label-tertiary,#8a8f98);font-size:11px}
|
||
.sl-head .sl-spacer{flex:1}
|
||
.sl-head button,.sl-btn{appearance:none;border:1px solid var(--dsw-alias-border-l2,rgba(127,127,127,.24));background:var(--dsw-alias-bg-layer-2,rgba(127,127,127,.06));color:inherit;font:inherit;font-size:12px;padding:3px 10px;border-radius:7px;cursor:pointer}
|
||
.sl-head button:hover,.sl-btn:hover{background:var(--dsw-alias-bg-layer-3,rgba(127,127,127,.12))}
|
||
.sl-btn[disabled]{opacity:.5;cursor:default}
|
||
.sl-btn.primary{background:var(--dsw-alias-state-business-primary,#3b82f6);border-color:transparent;color:#fff}
|
||
.sl-body{flex:1;min-height:0;display:flex}
|
||
.sl-left{flex:1;min-width:0;display:flex;flex-direction:column;border-right:1px solid var(--dsw-alias-border-l1,rgba(127,127,127,.14))}
|
||
.sl-right{width:392px;min-width:300px;max-width:46%;display:flex;flex-direction:column;min-height:0;overflow-y:auto}
|
||
@media (max-width:980px){.sl-body{flex-direction:column}.sl-right{width:auto;max-width:none;border-top:1px solid var(--dsw-alias-border-l1,rgba(127,127,127,.14))}.sl-left{border-right:0}}
|
||
.sl-conv{flex:1;min-height:0;display:flex;flex-direction:column;padding:18px 20px;gap:10px;overflow-y:auto}
|
||
.sl-conv h2{margin:0;font-size:15px;font-weight:600}
|
||
.sl-conv p{margin:0;color:var(--dsw-alias-label-secondary,#5b616b);font-size:12px;line-height:19px}
|
||
.sl-conv .sl-quote{margin:0;padding:9px 11px;border-left:3px solid var(--dsw-alias-border-l3,rgba(127,127,127,.35));background:var(--dsw-alias-bg-layer-2,rgba(127,127,127,.05));border-radius:0 8px 8px 0;color:var(--dsw-alias-label-secondary,#5b616b);font-size:12px;line-height:19px;white-space:pre-wrap;word-break:break-word}
|
||
.sl-conv .sl-actions{display:flex;gap:8px;flex-wrap:wrap;margin-top:4px}
|
||
.sl-map{padding:14px 16px 16px;flex:none}
|
||
.sl-row{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:8px;margin-bottom:16px;position:relative}
|
||
.sl-row.row0{grid-template-columns:1fr}
|
||
.sl-row.row0 .sl-node{max-width:none;margin:0 auto;width:min(260px,100%)}
|
||
.sl-row.row1,.sl-row.row2{grid-template-columns:repeat(3,minmax(0,1fr))}
|
||
.sl-row.row2{gap:8px}
|
||
.sl-link{height:12px;margin:0 auto 4px;width:1px;background:var(--dsw-alias-border-l3,rgba(127,127,127,.35))}
|
||
.sl-node{position:relative;display:flex;flex-direction:column;gap:2px;padding:8px 9px;border:1px solid var(--dsw-alias-border-l2,rgba(127,127,127,.2));border-radius:10px;background:var(--dsw-alias-bg-layer-2,rgba(127,127,127,.05));cursor:pointer;text-align:left;color:inherit;font:inherit;min-width:0;transition:border-color .12s,box-shadow .12s,transform .12s}
|
||
.sl-node:hover{transform:translateY(-1px);border-color:var(--dsw-alias-border-l3,rgba(127,127,127,.4))}
|
||
.sl-node[aria-selected="true"]{border-color:color-mix(in srgb,var(--dsw-alias-state-business-primary,#3b82f6) 55%,transparent);box-shadow:inset 0 0 0 1px color-mix(in srgb,var(--dsw-alias-state-business-primary,#3b82f6) 28%,transparent)}
|
||
.sl-node.is-absent{opacity:.62;border-style:dashed}
|
||
.sl-node-top{display:flex;align-items:center;gap:6px;min-width:0}
|
||
.sl-mark{flex:none;width:20px;height:20px;border-radius:6px;display:inline-flex;align-items:center;justify-content:center;font-size:11px;font-weight:600;background:var(--dsw-alias-bg-layer-3,rgba(127,127,127,.14));color:var(--dsw-alias-label-secondary,#5b616b)}
|
||
.sl-node[aria-selected="true"] .sl-mark{background:color-mix(in srgb,var(--dsw-alias-state-business-primary,#3b82f6) 18%,transparent);color:var(--dsw-alias-state-business-primary,#3b82f6)}
|
||
.sl-name{font-weight:600;font-size:12px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
||
.sl-meta{display:flex;align-items:center;gap:5px;font-size:10px;line-height:15px;color:var(--dsw-alias-label-tertiary,#8a8f98);min-width:0}
|
||
.sl-meta span{white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
||
.sl-dot{width:6px;height:6px;border-radius:50%;flex:none;background:var(--dsw-alias-label-tertiary,#9ca3af)}
|
||
.sl-dot.running{background:#22c55e;box-shadow:0 0 0 2px color-mix(in srgb,#22c55e 20%,transparent)}
|
||
.sl-dot.warning{background:#f59e0b}
|
||
.sl-dot.error{background:#ef4444}
|
||
.sl-dot.absent{background:transparent;border:1px solid var(--dsw-alias-label-tertiary,#9ca3af)}
|
||
.sl-tasks{display:flex;gap:3px;margin-top:2px;flex-wrap:wrap}
|
||
.sl-chip{padding:0 5px;border-radius:5px;font-size:10px;line-height:15px;background:var(--dsw-alias-bg-layer-3,rgba(127,127,127,.12));color:var(--dsw-alias-label-tertiary,#8a8f98)}
|
||
.sl-chip.run{background:color-mix(in srgb,#22c55e 16%,transparent);color:#15803d}
|
||
.sl-chip.done{background:color-mix(in srgb,#3b82f6 14%,transparent);color:#1d4ed8}
|
||
.sl-detail{flex:none;border-top:1px solid var(--dsw-alias-border-l1,rgba(127,127,127,.14));padding:12px 16px 16px;display:flex;flex-direction:column;gap:8px}
|
||
.sl-detail-head{display:flex;align-items:center;gap:8px}
|
||
.sl-detail-head strong{font-size:13px}
|
||
.sl-detail-head small{color:var(--dsw-alias-label-tertiary,#8a8f98);font-size:11px}
|
||
.sl-field{display:flex;flex-direction:column;gap:4px}
|
||
.sl-field label{font-size:11px;color:var(--dsw-alias-label-tertiary,#8a8f98)}
|
||
.sl-field select,.sl-field textarea{font:inherit;font-size:12px;color:inherit;background:var(--dsw-alias-bg-layer-2,rgba(127,127,127,.06));border:1px solid var(--dsw-alias-border-l2,rgba(127,127,127,.24));border-radius:7px;padding:5px 7px;min-width:0}
|
||
.sl-field textarea{resize:vertical;min-height:56px;line-height:18px}
|
||
.sl-field-row{display:flex;gap:6px}
|
||
.sl-field-row select{flex:1;min-width:0}
|
||
.sl-hint{color:var(--dsw-alias-label-tertiary,#8a8f98);font-size:11px;line-height:17px}
|
||
.sl-error{color:var(--dsw-alias-state-error-primary,#dc2626);font-size:11px;line-height:17px}
|
||
.sl-ok{color:#15803d;font-size:11px;line-height:17px}
|
||
.sl-section-title{display:flex;align-items:center;gap:8px;padding:10px 16px 4px;font-size:11px;font-weight:600;letter-spacing:.04em;color:var(--dsw-alias-label-tertiary,#8a8f98);text-transform:uppercase}
|
||
.sl-section-title span{margin-left:auto;font-weight:500;text-transform:none;letter-spacing:0}
|
||
.sl-tash{list-style:none;margin:0;padding:0 16px 10px;display:flex;flex-direction:column;gap:4px}
|
||
.sl-tash li{display:flex;align-items:center;gap:6px;font-size:11px;line-height:17px;color:var(--dsw-alias-label-secondary,#5b616b);min-width:0}
|
||
.sl-tash li b{font-weight:500;color:var(--dsw-alias-label-primary,#1f2329);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;min-width:0;flex:1}
|
||
.sl-tash li em{font-style:normal;color:var(--dsw-alias-label-tertiary,#8a8f98);flex:none}
|
||
.sl-main-shell{display:flex;flex-direction:column;height:100%;min-height:0}
|
||
.sl-main-head{display:flex;align-items:center;gap:8px;padding:8px 16px;border-bottom:1px solid var(--dsw-alias-border-l1,rgba(127,127,127,.14));font-size:13px;flex:0 0 auto}
|
||
.sl-main-head-hint{font-size:11px;color:var(--dsw-alias-label-tertiary,#8a8f98)}
|
||
.sl-main-head-spacer{flex:1}
|
||
.sl-main-body{flex:1;min-height:0;overflow:auto;display:flex;flex-direction:column}
|
||
.sl-dock{display:inline-flex;align-items:center;gap:6px;min-width:0}
|
||
.sl-dock button{appearance:none;border:1px solid var(--dsw-alias-border-l2,rgba(127,127,127,.24));background:var(--dsw-alias-bg-layer-2,rgba(127,127,127,.06));color:inherit;font:inherit;font-size:12px;padding:3px 10px;border-radius:7px;cursor:pointer}
|
||
.sl-dock-error{color:var(--dsw-alias-state-error-primary,#dc2626);font-size:11px}
|
||
.sl-env-note{margin:0;padding:8px 10px;border:1px dashed var(--dsw-alias-border-l3,rgba(127,127,127,.35));border-radius:8px;color:var(--dsw-alias-label-secondary,#5b616b);font-size:11px;line-height:17px}
|
||
.sl-tab-title{display:flex;align-items:center;gap:6px;min-width:0}
|
||
.sl-tab-mark{width:18px;height:18px;border-radius:5px;display:inline-flex;align-items:center;justify-content:center;font-size:9px;font-weight:600;background:var(--dsw-alias-bg-layer-3,rgba(127,127,127,.14));color:var(--dsw-alias-label-secondary,#5b616b)}
|
||
.sl-compact{padding:0}
|
||
.sl-compact .sl-head{display:none}
|
||
.sl-compact .sl-left{display:none}
|
||
.sl-compact .sl-body{flex-direction:column}
|
||
.sl-compact .sl-right{width:auto;max-width:none;min-width:0;border-top:0;flex:1}
|
||
`;
|
||
const cssId = "dsh-sansheng-liubu-panel/panel.css";
|
||
if (typeof document !== "undefined" && document.querySelector("style[data-plugin-css=" + JSON.stringify(cssId) + "]") === null) {
|
||
const tag = document.createElement("style");
|
||
tag.dataset.plugin = "dsh-sansheng-liubu-panel";
|
||
tag.dataset.pluginCss = cssId;
|
||
tag.textContent = css;
|
||
document.head.appendChild(tag);
|
||
}
|
||
// #endregion
|
||
|
||
// #region 小部件
|
||
function Dot(props) {
|
||
const status = props.status || "inactive";
|
||
const tone = status === "running" ? "running" : status === "failed" ? "error" : status === "provisioning" ? "warning" : status === "absent" ? "absent" : "";
|
||
return h("span", { className: "sl-dot" + (tone ? " " + tone : ""), "aria-hidden": "true" });
|
||
}
|
||
|
||
function SeatCard(props) {
|
||
const { seat, selected, onSelect, status, counts, lastText, model } = props;
|
||
const cls = ["sl-node"];
|
||
if (!seat.present) cls.push("is-absent");
|
||
return h("button", {
|
||
type: "button",
|
||
className: cls.join(" "),
|
||
"aria-selected": selected ? "true" : "false",
|
||
"data-role": seat.role,
|
||
title: seat.duty,
|
||
onClick: () => onSelect(seat.role),
|
||
children: [
|
||
h("span", { className: "sl-node-top" }, [
|
||
h("span", { className: "sl-mark", "aria-hidden": "true", children: seat.mark }),
|
||
h("span", { className: "sl-name", children: seat.label }),
|
||
]),
|
||
h("span", { className: "sl-meta" }, [
|
||
h(Dot, { status }),
|
||
h("span", { children: STATUS_LABELS[status] || status }),
|
||
model ? h("span", { children: "· " + model }) : null,
|
||
]),
|
||
lastText ? h("span", { className: "sl-meta" }, [h("span", { children: lastText })]) : null,
|
||
(counts.runningCount || counts.pendingCount || counts.completedCount)
|
||
? h("span", { className: "sl-tasks" }, [
|
||
counts.runningCount ? h("span", { className: "sl-chip run", children: "执行 " + counts.runningCount }) : null,
|
||
counts.pendingCount ? h("span", { className: "sl-chip", children: "待办 " + counts.pendingCount }) : null,
|
||
counts.completedCount ? h("span", { className: "sl-chip done", children: "完成 " + counts.completedCount }) : null,
|
||
])
|
||
: null,
|
||
],
|
||
});
|
||
}
|
||
// #endregion
|
||
|
||
// #region 主面板
|
||
function SanshengPanel(props) {
|
||
const host = props.host;
|
||
const tabSessionId = props.sessionId;
|
||
const compact = props.compact === true;
|
||
// 直接订阅宿主服务层 store,不调用 slot 注入的会话级 hook(root 级 main 槽下不可用)。
|
||
const sessions = useStoreSnapshot(host.sessionsStore, EMPTY_SESSIONS) || EMPTY_SESSIONS;
|
||
const statuses = useStoreSnapshot(host.statusStore, undefined);
|
||
const activePanelId = useStoreSnapshot(host.panelStore, {}).activePanelId;
|
||
const projections = sessions.projectionsBySession || {};
|
||
|
||
// main 面板是 root 级槽:拿不到会话级 props,用户正在看哪个会话只能从
|
||
// uiWorkspace 的选中记录(持久化在 dsh.sessions.current)读。
|
||
const selection = useWorkspaceSelection();
|
||
const pickedId = host.getSelectedSession ? host.getSelectedSession() : undefined;
|
||
const focusedSessionId = tabSessionId || pickedId || selection.sessionId;
|
||
const activeAddress = selection.subagentAddress || (focusedSessionId ? subagentAddressOf(sessions, focusedSessionId) : undefined);
|
||
const leadSessionId = (activeAddress && activeAddress.parentSessionId) || focusedSessionId;
|
||
const team = leadSessionId && projections[leadSessionId]
|
||
? projections[leadSessionId].values.agentTeam
|
||
: undefined;
|
||
const seats = React.useMemo(() => arrangeRoster(team), [team]);
|
||
const buckets = React.useMemo(() => bucketsOf(team && team.tasks), [team]);
|
||
|
||
const [selectedRole, setSelectedRole] = React.useState("lead");
|
||
const seat = seats.find((entry) => entry.role === selectedRole) || seats[0];
|
||
|
||
const runningOf = (id) => {
|
||
if (!id) return undefined;
|
||
const fromStatus = statuses && typeof statuses.get === "function" ? statuses.get(id) : undefined;
|
||
if (fromStatus && typeof fromStatus.running === "boolean") return fromStatus.running;
|
||
const fromList = sessions.byId[id];
|
||
return fromList ? fromList.running : undefined;
|
||
};
|
||
|
||
const seatState = (entry) => {
|
||
const status = memberStatus(entry.member, runningOf(entry.id), undefined);
|
||
const owned = tasksOfRole(team, entry.role);
|
||
const ownBuckets = bucketsOf(owned);
|
||
const running = status === "running";
|
||
const recent = entry.id ? host.recentText(entry.id) : "";
|
||
const model = entry.id ? host.memberModel(entry.id) : "";
|
||
const lastText = recent ? recent : (owned.length > 0 ? owned[owned.length - 1].subject || "" : "");
|
||
return {
|
||
status,
|
||
counts: {
|
||
runningCount: ownBuckets.in_progress.length,
|
||
pendingCount: ownBuckets.pending.length,
|
||
completedCount: ownBuckets.completed.length,
|
||
},
|
||
lastText: shortText(lastText, 40),
|
||
model,
|
||
running,
|
||
};
|
||
};
|
||
|
||
const rows = [0, 1, 2].map((rowIndex) => seats.filter((entry) => entry.row === rowIndex));
|
||
|
||
const seatInfo = seat ? seatState(seat) : { status: "absent", counts: {}, lastText: "", model: "" };
|
||
|
||
// —— 图下配置区 ——
|
||
const [presets, setPresets] = React.useState({ status: "idle", options: [], error: null });
|
||
const [catalog, setCatalog] = React.useState({ status: "idle", options: [], error: null, current: undefined, subagent: false });
|
||
const [draftModel, setDraftModel] = React.useState("");
|
||
const [draftEffort, setDraftEffort] = React.useState("");
|
||
const [draftPreset, setDraftPreset] = React.useState("");
|
||
const [notice, setNotice] = React.useState(null);
|
||
const [busy, setBusy] = React.useState(false);
|
||
const [decree, setDecree] = React.useState("");
|
||
|
||
const targetId = seat && seat.id ? seat.id : seat && seat.role === "lead" ? leadSessionId : undefined;
|
||
|
||
React.useEffect(() => {
|
||
if (presets.status !== "idle") return undefined;
|
||
let alive = true;
|
||
setPresets({ status: "loading", options: [], error: null });
|
||
host.loadPresets().then((result) => {
|
||
if (!alive) return;
|
||
setPresets({ status: "ready", options: result.options, error: result.error });
|
||
}, (error) => {
|
||
if (alive) setPresets({ status: "error", options: [], error: String(error && error.message || error) });
|
||
});
|
||
return () => { alive = false; };
|
||
}, [presets.status]);
|
||
|
||
React.useEffect(() => {
|
||
if (catalog.status === "loading") return undefined;
|
||
if (!targetId) { setCatalog({ status: "idle", options: [], error: null, current: undefined, subagent: false }); return undefined; }
|
||
let alive = true;
|
||
setCatalog((prev) => ({ ...prev, status: "loading", error: null }));
|
||
host.loadCatalog(targetId).then((result) => {
|
||
if (!alive) return;
|
||
setCatalog({ status: "ready", options: result.options, current: result.current, error: result.error, subagent: result.subagent });
|
||
setDraftModel(result.current ? result.current.provider + "/" + result.current.model : "");
|
||
setDraftEffort((result.current && result.current.reasoningEffort) || "");
|
||
}, (error) => {
|
||
if (alive) setCatalog({ status: "error", options: [], error: String(error && error.message || error), current: undefined, subagent: false });
|
||
});
|
||
return () => { alive = false; };
|
||
}, [targetId]);
|
||
|
||
const presetForSeat = seat && seat.id && sessions.byId[seat.id] && sessions.byId[seat.id].projectionValues
|
||
? sessions.byId[seat.id].projectionValues.agentPreset
|
||
: undefined;
|
||
|
||
React.useEffect(() => {
|
||
setDraftPreset(typeof presetForSeat === "string" ? presetForSeat : "");
|
||
}, [presetForSeat, targetId]);
|
||
|
||
const chosenOption = catalog.options.find((option) => option.rowId === draftModel);
|
||
|
||
const applyModel = () => {
|
||
if (!chosenOption || !seat || !seat.id) return;
|
||
const plan = modelSwitchPlan(catalog.current, {
|
||
provider: chosenOption.provider,
|
||
model: chosenOption.model,
|
||
reasoningEffort: draftEffort || undefined,
|
||
}, catalog.subagent);
|
||
if (!plan.ok) { setNotice({ kind: "error", text: plan.reason }); return; }
|
||
setBusy(true);
|
||
host.selectModel(seat.id, plan.payload).then((result) => {
|
||
setBusy(false);
|
||
if (result.ok) {
|
||
setNotice({ kind: "ok", text: "已切换到 " + chosenOption.label });
|
||
setCatalog((prev) => ({ ...prev, current: plan.payload }));
|
||
} else {
|
||
setNotice({ kind: "error", text: result.error });
|
||
}
|
||
});
|
||
};
|
||
|
||
const applyPreset = () => {
|
||
if (!seat || !seat.id || !draftPreset) return;
|
||
setBusy(true);
|
||
host.selectPreset(seat.id, draftPreset).then((result) => {
|
||
setBusy(false);
|
||
if (result.ok) {
|
||
setNotice({ kind: "ok", text: "已切换 Agent 预设" });
|
||
host.refresh(seat.id);
|
||
} else {
|
||
setNotice({ kind: "error", text: result.error });
|
||
}
|
||
});
|
||
};
|
||
|
||
const sendDecree = () => {
|
||
const target = seat && seat.role === "lead" ? leadSessionId : (seat && seat.id);
|
||
const text = decreeText(seat.role, decree, team);
|
||
if (!text || !target) return;
|
||
setBusy(true);
|
||
host.sendPrompt(target, text).then((result) => {
|
||
setBusy(false);
|
||
if (result.ok) {
|
||
setNotice({ kind: "ok", text: "已投递到" + roleLabel(seat.role) });
|
||
setDecree("");
|
||
} else {
|
||
setNotice({ kind: "error", text: result.error });
|
||
}
|
||
});
|
||
};
|
||
|
||
const hasAnySession = Array.isArray(sessions.ids) ? sessions.ids.length > 0 : Object.keys(sessions.byId || {}).length > 0;
|
||
const openMainConversation = () => {
|
||
const result = host.openConversation();
|
||
if (result && result.ok === false) setNotice({ kind: "error", text: result.error });
|
||
};
|
||
|
||
// —— 左侧主对话区 ——
|
||
const leadRecent = leadSessionId ? host.recentText(leadSessionId) : "";
|
||
const fallbackRecent = React.useMemo(() => {
|
||
const lines = [];
|
||
for (const entry of [1, 2]) {
|
||
for (const task of buckets.in_progress) lines.push(task);
|
||
}
|
||
return lines;
|
||
}, [team]);
|
||
const inboxText = shortText(leadRecent || "", 400);
|
||
|
||
return h("div", { className: compact ? "sl-root sl-compact" : "sl-root", "data-sansheng-panel": "true", "data-sansheng-compact": compact ? "1" : "0" }, [
|
||
h("div", { className: "sl-head" }, [
|
||
h("h1", { children: "三省六部" }),
|
||
h("small", { children: team === undefined ? "尚未组建朝班" : "在朝 " + team.members.length + " 人 · 任务 " + (Array.isArray(team.tasks) ? team.tasks.length : 0) }),
|
||
h("span", { className: "sl-spacer" }),
|
||
h("button", {
|
||
type: "button",
|
||
onClick: openMainConversation,
|
||
children: "回到丞相对话",
|
||
}),
|
||
]),
|
||
h("div", { className: "sl-body" }, [
|
||
h("div", { className: "sl-left" }, [
|
||
h("div", { className: "sl-conv" }, [
|
||
h("h2", { children: "主对话" }),
|
||
h("p", { children: "对话本体由 DSH 的会话面板承载,这里保留朝堂视角:左侧查看丞相最近进展,需要完整上下文时点“回到丞相对话”。" }),
|
||
inboxText
|
||
? h("div", { className: "sl-quote", "data-last-user": "true", children: inboxText })
|
||
: h("div", { className: "sl-quote", children: hasAnySession ? (team === undefined ? "还没有朝班。先在对话里让丞相组建三省六部,成员就会出现在右侧朝堂图上。" : "丞相暂无新的发言。") : "当前实例还没有会话,暂时无法组建朝班。" }),
|
||
hasAnySession ? null : h("div", { className: "sl-env-note", "data-sansheng-empty": "1", children: "当前实例还没有任何会话:点「打开主对话」只会切回宿主的空白新会话页。" }),
|
||
h("div", { className: "sl-actions" }, [
|
||
h("button", { type: "button", className: "sl-btn primary", onClick: openMainConversation, children: "打开主对话" }),
|
||
team === undefined
|
||
? h("button", {
|
||
type: "button",
|
||
className: "sl-btn",
|
||
onClick: () => {
|
||
host.startFormation().then((result) => {
|
||
setNotice({ kind: result.ok ? "ok" : "error", text: result.ok ? result.text : result.error });
|
||
});
|
||
},
|
||
children: "让丞相组建朝班",
|
||
})
|
||
: null,
|
||
]),
|
||
h("div", { className: "sl-section-title" }, [
|
||
h("span", { children: "在办任务" }),
|
||
h("span", { children: "执行 " + buckets.in_progress.length + " / 待办 " + buckets.pending.length }),
|
||
]),
|
||
h("ul", { className: "sl-tash" }, buckets.in_progress.concat(buckets.pending).slice(0, 8).map((task) => h("li", { key: task.id, title: task.description || "" }, [
|
||
h(Dot, { status: task.status === "in_progress" ? "running" : "provisioning" }),
|
||
h("b", { children: task.subject || task.title || task.id }),
|
||
h("em", { children: roleLabel(task.ownerName) }),
|
||
]))),
|
||
buckets.in_progress.length + buckets.pending.length === 0
|
||
? h("p", { children: "共享任务板上暂时没有进行中的任务。" })
|
||
: null,
|
||
]),
|
||
]),
|
||
h("div", { className: "sl-right" }, [
|
||
h("div", { className: "sl-map" }, rows.map((rowSeats, rowIndex) => h(React.Fragment, { key: "row" + rowIndex }, [
|
||
rowIndex > 0 ? h("div", { className: "sl-link", "aria-hidden": "true" }) : null,
|
||
h("div", { className: "sl-row row" + rowIndex }, rowSeats.map((entry) => {
|
||
const info = seatState(entry);
|
||
return h(SeatCard, {
|
||
key: entry.role,
|
||
seat: entry,
|
||
selected: entry.role === selectedRole,
|
||
status: info.status,
|
||
counts: info.counts,
|
||
lastText: info.lastText,
|
||
model: info.model,
|
||
onSelect: (role) => { setSelectedRole(role); setNotice(null); },
|
||
});
|
||
})),
|
||
]))),
|
||
h("div", { className: "sl-detail" }, [
|
||
h("div", { className: "sl-detail-head" }, [
|
||
h("strong", { children: seat ? seat.label : "成员" }),
|
||
h("small", { children: seat ? seat.duty : "" }),
|
||
h("span", { className: "sl-spacer", style: { flex: 1 } }),
|
||
seat && seat.id ? h("button", {
|
||
type: "button",
|
||
className: "sl-btn",
|
||
onClick: () => host.openSession(seat.id),
|
||
children: "切到该部门会话",
|
||
}) : null,
|
||
]),
|
||
seat && !seat.present ? h("div", { className: "sl-hint", children: "该部门尚未设立。让丞相按流程组建后再配置。" }) : null,
|
||
seat && seat.present ? h("div", { className: "sl-field" }, [
|
||
h("label", { children: "Agent 预设" }),
|
||
h("div", { className: "sl-field-row" }, [
|
||
h("select", {
|
||
value: draftPreset,
|
||
onChange: (event) => setDraftPreset(event.target.value),
|
||
children: [
|
||
h("option", { value: "", children: presets.status === "loading" ? "读取中…" : "(未设置)" }),
|
||
...presets.options.map((option) => h("option", { key: option.id, value: option.id, children: option.name })),
|
||
],
|
||
}),
|
||
h("button", {
|
||
type: "button",
|
||
className: "sl-btn",
|
||
disabled: busy || !draftPreset || catalog.subagent,
|
||
onClick: applyPreset,
|
||
children: "应用",
|
||
}),
|
||
]),
|
||
presets.error ? h("div", { className: "sl-error", children: presets.error }) : null,
|
||
]) : null,
|
||
seat && seat.present ? h("div", { className: "sl-field" }, [
|
||
h("label", { children: "联动模型 · 推理等级" }),
|
||
h("div", { className: "sl-field-row" }, [
|
||
h("select", {
|
||
value: draftModel,
|
||
onChange: (event) => {
|
||
setDraftModel(event.target.value);
|
||
const option = catalog.options.find((entry) => entry.rowId === event.target.value);
|
||
setDraftEffort(option && option.defaultEffort ? option.defaultEffort : "");
|
||
},
|
||
children: [
|
||
h("option", { value: "", children: catalog.status === "loading" ? "读取中…" : "(未设置)" }),
|
||
...catalog.options.map((option) => h("option", { key: option.rowId, value: option.rowId, children: option.label + " · " + option.provider })),
|
||
],
|
||
}),
|
||
h("select", {
|
||
value: draftEffort,
|
||
onChange: (event) => setDraftEffort(event.target.value),
|
||
style: { maxWidth: 92 },
|
||
children: [
|
||
h("option", { value: "", children: "默认" }),
|
||
...(chosenOption ? chosenOption.efforts : []).map((effort) => h("option", { key: effort.id, value: effort.id, children: effort.name })),
|
||
],
|
||
}),
|
||
]),
|
||
h("div", { className: "sl-field-row" }, [
|
||
h("button", {
|
||
type: "button",
|
||
className: "sl-btn",
|
||
disabled: busy || !chosenOption || catalog.subagent,
|
||
onClick: applyModel,
|
||
children: "应用模型",
|
||
}),
|
||
h("span", { className: "sl-hint", children: catalog.subagent ? "子会话沿用丞相模型" : "当前:" + (catalog.current ? modelLabel(catalog.current) : "未设置") }),
|
||
]),
|
||
catalog.error ? h("div", { className: "sl-error", children: catalog.error }) : null,
|
||
]) : null,
|
||
seat && seat.present ? h("div", { className: "sl-field" }, [
|
||
h("label", { children: "下旨给" + (seat ? seat.label : "") }),
|
||
h("textarea", {
|
||
value: decree,
|
||
placeholder: "直接下达指令,丞相会把它转成该部门的任务",
|
||
onChange: (event) => setDecree(event.target.value),
|
||
}),
|
||
h("div", { className: "sl-field-row" }, [
|
||
h("button", {
|
||
type: "button",
|
||
className: "sl-btn primary",
|
||
disabled: busy || decree.trim() === "",
|
||
onClick: sendDecree,
|
||
children: "下旨",
|
||
}),
|
||
h("span", { className: "sl-hint", children: "投递到该部门会话,受三省六部流程约束" }),
|
||
]),
|
||
]) : null,
|
||
notice ? h("div", { className: notice.kind === "ok" ? "sl-ok" : "sl-error", role: "status", children: notice.text }) : null,
|
||
]),
|
||
]),
|
||
]),
|
||
]);
|
||
}
|
||
// #endregion
|
||
// #region 宿主适配
|
||
function createHost(ctx) {
|
||
const sessions = ctx.sessions;
|
||
const conversations = new WeakMap();
|
||
let selectedSessionId;
|
||
|
||
/** layout 服务用可选查找:直接读 ctx.layout 会命中 inject 声明守卫。 */
|
||
const layoutService = () => {
|
||
try {
|
||
if (typeof ctx.get === "function") {
|
||
const service = ctx.get("layout");
|
||
if (service) return service;
|
||
}
|
||
} catch (error) { /* 退回直接读 */ }
|
||
try { return ctx.layout; } catch (error) { return undefined; }
|
||
};
|
||
const panelStore = (() => {
|
||
const service = layoutService();
|
||
return service && service.panelInfo ? service.panelInfo : undefined;
|
||
})();
|
||
const sessionsStore = sessions && sessions.list;
|
||
const statusStore = (() => {
|
||
const candidates = [];
|
||
if (sessions && sessions.statuses) candidates.push(sessions.statuses);
|
||
try {
|
||
if (typeof ctx.get === "function") {
|
||
const service = ctx.get("sessionStatus");
|
||
if (service) candidates.push(service);
|
||
}
|
||
} catch (error) { /* 忽略:拿不到时由 byId.running 兜底 */ }
|
||
return candidates.find((item) => item && typeof item.getSnapshot === "function" && typeof item.subscribe === "function");
|
||
})();
|
||
|
||
/** 当前中央面板 id:null 表示正在看会话本体。 */
|
||
const currentPanelId = () => {
|
||
if (!panelStore || typeof panelStore.getSnapshot !== "function") return null;
|
||
try {
|
||
const info = panelStore.getSnapshot();
|
||
return info ? info.activePanelId : null;
|
||
} catch (error) { return null; }
|
||
};
|
||
|
||
const bindingOf = (sessionId) => {
|
||
try { return sessions.binding(sessionId); } catch (error) { return undefined; }
|
||
};
|
||
|
||
/** 会话的对话快照(uiConversation 绑定按会话缓存,重复创建会丢掉已归并的节点)。 */
|
||
const conversationOf = (sessionId) => {
|
||
let service;
|
||
try { service = ctx.uiConversation; } catch (error) { return undefined; }
|
||
if (!service) return undefined;
|
||
const binding = bindingOf(sessionId);
|
||
if (!binding) return undefined;
|
||
let target = conversations.get(binding);
|
||
if (target === undefined) {
|
||
try {
|
||
const conversation = service.binding(binding);
|
||
target = conversation && conversation.target ? conversation.target("chat") : undefined;
|
||
} catch (error) {
|
||
target = undefined;
|
||
}
|
||
conversations.set(binding, target);
|
||
}
|
||
return target;
|
||
};
|
||
|
||
/** 取会话最近一条助手/用户文本:chat 快照的 nodes 是按 key 索引的只读集合。 */
|
||
const recentOf = (sessionId) => {
|
||
const target = conversationOf(sessionId);
|
||
if (!target) return "";
|
||
let snapshot;
|
||
try { snapshot = target.getSnapshot(); } catch (error) { return ""; }
|
||
const nodes = snapshot && snapshot.nodes;
|
||
if (!nodes || typeof nodes.values !== "function") return "";
|
||
const exchange = lastExchange(Array.from(nodes.values()));
|
||
return exchange.lastAssistant || exchange.lastUser;
|
||
};
|
||
|
||
/** 没有选中记录时,退回最近活跃的那个会话(整页版常用)。 */
|
||
const newestSessionId = () => {
|
||
try {
|
||
const list = sessionsStore && typeof sessionsStore.getSnapshot === "function" ? sessionsStore.getSnapshot() : undefined;
|
||
const byId = list && list.byId ? list.byId : {};
|
||
let best;
|
||
for (const key of Object.keys(byId)) {
|
||
const item = byId[key];
|
||
if (!item || item.blank === true) continue;
|
||
const at = typeof item.updatedAt === "number" ? item.updatedAt : Date.parse(item.updatedAt || "");
|
||
const score = Number.isFinite(at) ? at : 0;
|
||
if (!best || score > best.score) best = { id: item.id || key, score };
|
||
}
|
||
return best ? best.id : undefined;
|
||
} catch (error) { return undefined; }
|
||
};
|
||
|
||
/** 主视图当前选中的会话:以 uiWorkspace 的选中记录为准(面板是 root 级槽)。 */
|
||
const currentSession = () => {
|
||
try {
|
||
const saved = ctx.uiWorkspace && ctx.uiWorkspace.selection ? ctx.uiWorkspace.selection.getSnapshot() : undefined;
|
||
if (saved && saved.subagentAddress) return saved.subagentAddress.childSessionId;
|
||
if (saved && saved.sessionId) return saved.sessionId;
|
||
} catch (error) { /* 忽略:退回面板传入的选中 */ }
|
||
return selectedSessionId || newestSessionId();
|
||
};
|
||
|
||
const presetsRemote = () => {
|
||
try {
|
||
const remote = ctx.remote;
|
||
if (!remote) return undefined;
|
||
const presets = remote.agentPresets;
|
||
return presets && typeof presets.list === "function" ? presets : undefined;
|
||
} catch (error) { return undefined; }
|
||
};
|
||
|
||
const modelDirectoryOf = (sessionId) => {
|
||
let service;
|
||
try { service = ctx.modelDirectories || (typeof ctx.get === "function" ? ctx.get("modelDirectories") : undefined); } catch (error) { return undefined; }
|
||
if (!service || typeof service.directoryFor !== "function") return undefined;
|
||
try { return service.directoryFor(sessionId); } catch (error) { return undefined; }
|
||
};
|
||
|
||
const sidebarNav = () => {
|
||
const candidates = [];
|
||
try { if (typeof ctx.get === "function") candidates.push(ctx.get("sidebarRight")); } catch (error) { /* 忽略 */ }
|
||
try { candidates.push(ctx.sidebarRight); } catch (error) { /* 忽略 */ }
|
||
return candidates.find((item) => item && (typeof item.openTabIn === "function" || typeof item.openTab === "function"));
|
||
};
|
||
|
||
const openSanshengTab = (sessionId) => {
|
||
const nav = sidebarNav();
|
||
const target = sessionId || currentSession();
|
||
if (!target) {
|
||
return { ok: false, error: "当前还没有打开任何会话,右侧栏页签是会话级的;先新建或打开一个会话再停靠。" };
|
||
}
|
||
try {
|
||
const service = layoutService();
|
||
if (service && typeof service.selectPanel === "function") service.selectPanel(null);
|
||
} catch (error) { /* 忽略:右栏可能已经可见 */ }
|
||
|
||
const better = betterSidebarOf(ctx);
|
||
if (better && typeof better.openTab === "function") {
|
||
try {
|
||
better.openTab({ type: SANSENG_TAB_ID }, { sessionId: target });
|
||
return { ok: true, text: "朝堂已停靠到右侧栏" };
|
||
} catch (error) { /* 落到宿主原生右侧栏 */ }
|
||
}
|
||
|
||
let opened = false;
|
||
const attempt = (left) => {
|
||
try {
|
||
if (nav && typeof nav.openTabIn === "function") nav.openTabIn(target, SANSENG_TAB_KIND);
|
||
else if (nav && typeof nav.openTab === "function") nav.openTab(SANSENG_TAB_KIND);
|
||
opened = true;
|
||
} catch (error) {
|
||
opened = false;
|
||
}
|
||
if (opened || left <= 0) return;
|
||
setTimeout(() => attempt(left - 1), 60);
|
||
};
|
||
if (nav) attempt(8);
|
||
if (!nav) return { ok: false, error: "当前宿主没有右侧栏服务(sidebarRight),无法停靠到侧栏;整页形式仍可使用。" };
|
||
return { ok: true, text: "朝堂已停靠到右侧栏" };
|
||
};
|
||
|
||
return {
|
||
sessionsStore,
|
||
statusStore,
|
||
panelStore,
|
||
getSelectedSession: currentSession,
|
||
setSelected(sessionId) {
|
||
selectedSessionId = sessionId;
|
||
},
|
||
currentPanelId,
|
||
selectPanel(panelId) {
|
||
const service = layoutService();
|
||
if (!service || typeof service.selectPanel !== "function") return false;
|
||
try { service.selectPanel(panelId); return true; } catch (error) { return false; }
|
||
},
|
||
togglePanel() {
|
||
return this.selectPanel(currentPanelId() === PANEL_ID ? null : PANEL_ID);
|
||
},
|
||
openSanshengTab,
|
||
memberModel(sessionId) {
|
||
const binding = bindingOf(sessionId);
|
||
if (!binding) return "";
|
||
try {
|
||
const face = binding.session.projections.faceOf("modelSelection");
|
||
const snapshot = face.getSnapshot();
|
||
return modelLabel(snapshot && snapshot.next ? snapshot.next.model || snapshot.next : snapshot);
|
||
} catch (error) { return ""; }
|
||
},
|
||
recentText(sessionId) {
|
||
if (!sessionId) return "";
|
||
try { return recentOf(sessionId); } catch (error) { return ""; }
|
||
},
|
||
openConversation() {
|
||
const target = currentSession();
|
||
if (!target) {
|
||
return {
|
||
ok: false,
|
||
error: "当前实例还没有任何会话,没有主对话可打开;「打开主对话」本来只是切回宿主自带的对话视图。",
|
||
};
|
||
}
|
||
try {
|
||
ctx.uiWorkspace.openSession(target);
|
||
} catch (error) {
|
||
return { ok: false, error: "打开会话失败:" + String(error && error.message || error) };
|
||
}
|
||
const service = layoutService();
|
||
if (service && typeof service.selectPanel === "function") {
|
||
try { service.selectPanel(null); } catch (error) { /* 忽略 */ }
|
||
}
|
||
return { ok: true };
|
||
},
|
||
openSession(sessionId) {
|
||
let summary;
|
||
try { summary = sessions.list.getSnapshot().byId[sessionId]; } catch (error) { summary = undefined; }
|
||
const address = summary && summary.subagent && summary.subagent.address;
|
||
const parent = address && address.parentSessionId;
|
||
try {
|
||
if (parent && parent !== sessionId) {
|
||
ctx.uiWorkspace.openSession({ parentSessionId: parent, childSessionId: sessionId, mode: "continuable" });
|
||
} else {
|
||
ctx.uiWorkspace.openSession(sessionId);
|
||
}
|
||
} catch (error) {
|
||
return false;
|
||
}
|
||
const service = layoutService();
|
||
if (service && typeof service.selectPanel === "function") {
|
||
try { service.selectPanel(null); } catch (error) { /* 忽略 */ }
|
||
}
|
||
return true;
|
||
},
|
||
loadPresets() {
|
||
const remote = presetsRemote();
|
||
if (!remote) return Promise.resolve({ options: [], error: "当前宿主未提供 Agent 预设接口" });
|
||
return Promise.resolve()
|
||
.then(() => remote.list())
|
||
.then((result) => {
|
||
if (!result || !result.ok) return { options: [], error: result && result.error ? result.error.message : "读取预设失败" };
|
||
const presets = result.value && Array.isArray(result.value.presets) ? result.value.presets : [];
|
||
return { options: presets.map((preset) => ({ id: preset.id, name: preset.name || preset.id })), error: null };
|
||
}, (error) => ({ options: [], error: "读取预设失败:" + String(error && error.message || error) }));
|
||
},
|
||
loadCatalog(sessionId) {
|
||
const directory = modelDirectoryOf(sessionId);
|
||
if (!directory) return Promise.resolve({ options: [], current: undefined, error: "当前宿主未提供模型目录", subagent: false });
|
||
return Promise.resolve()
|
||
.then(() => directory.load())
|
||
.then(() => {
|
||
const snapshot = directory.store.getSnapshot();
|
||
return {
|
||
options: modelOptions(snapshot),
|
||
current: snapshot.current,
|
||
error: snapshot.error || null,
|
||
subagent: typeof sessions.subagentAddress === "function" ? sessions.subagentAddress(sessionId) !== undefined : false,
|
||
};
|
||
}, (error) => ({ options: [], current: undefined, error: String(error && error.message || error), subagent: false }));
|
||
},
|
||
selectModel(sessionId, payload) {
|
||
const directory = modelDirectoryOf(sessionId);
|
||
if (!directory) return Promise.resolve({ ok: false, error: "当前宿主未提供模型目录" });
|
||
return Promise.resolve()
|
||
.then(() => directory.select(payload))
|
||
.then(() => {
|
||
const snapshot = directory.store.getSnapshot();
|
||
return snapshot.error ? { ok: false, error: snapshot.error } : { ok: true };
|
||
}, (error) => ({ ok: false, error: String(error && error.message || error) }));
|
||
},
|
||
selectPreset(sessionId, presetId) {
|
||
const remote = presetsRemote();
|
||
if (!remote || typeof remote.select !== "function") return Promise.resolve({ ok: false, error: "当前宿主未提供 Agent 预设接口" });
|
||
return Promise.resolve()
|
||
.then(() => remote.select(sessionId, presetId))
|
||
.then((result) => (result && result.ok ? { ok: true } : { ok: false, error: result && result.error ? result.error.message : "应用预设失败" }),
|
||
(error) => ({ ok: false, error: String(error && error.message || error) }));
|
||
},
|
||
refresh(sessionId) {
|
||
const binding = bindingOf(sessionId);
|
||
if (binding && binding.session && binding.session.projections && typeof binding.session.projections.faceOf === "function") {
|
||
try { binding.session.projections.faceOf("agentPreset").getSnapshot(); } catch (error) { /* 忽略 */ }
|
||
}
|
||
if (typeof sessions.refreshProjections === "function") {
|
||
try { sessions.refreshProjections(sessionId).catch(() => {}); } catch (error) { /* 忽略 */ }
|
||
}
|
||
},
|
||
sendPrompt(sessionId, text) {
|
||
const binding = bindingOf(sessionId);
|
||
if (!binding) return Promise.resolve({ ok: false, error: "该部门还没有可用的会话" });
|
||
return Promise.resolve()
|
||
.then(() => binding.session.prompt([{ type: "text", text }], "queue"))
|
||
.then((result) => (result && result.ok ? { ok: true } : { ok: false, error: result && result.error ? result.error.message : "投递失败" }),
|
||
(error) => ({ ok: false, error: String(error && error.message || error) }));
|
||
},
|
||
startFormation() {
|
||
const lead = currentSession();
|
||
if (!lead) return Promise.resolve({ ok: false, error: "没有可用会话" });
|
||
const binding = bindingOf(lead);
|
||
if (!binding) return Promise.resolve({ ok: false, error: "没有可用会话" });
|
||
return Promise.resolve()
|
||
.then(() => binding.session.prompt([{ type: "text", text: FORMATION_PROMPT }], "queue"))
|
||
.then((result) => (result && result.ok ? { ok: true, text: "已请丞相组建朝班" } : { ok: false, error: result && result.error ? result.error.message : "投递失败" }),
|
||
(error) => ({ ok: false, error: String(error && error.message || error) }));
|
||
},
|
||
};
|
||
}
|
||
|
||
const FORMATION_PROMPT = [
|
||
"【上朝】按三省六部流程组建朝班:",
|
||
"1. 立即创建 zhongshu(中书省)、menxia(门下省)、shangshu(尚书省)三个成员。",
|
||
"2. 在共享任务板建立“中书拟案 → 门下审议 → 尚书派工”依赖链,写清各任务 writeScopes。",
|
||
"3. 门下准奏后再由尚书创建 gongbu/libu/bingbu 并派工。",
|
||
"4. 每阶段完成后向我汇报,我确认后再进入下一阶段。",
|
||
].join("\\n");
|
||
|
||
function SidebarIcon(props) {
|
||
const size = props.size || 18;
|
||
return h("svg", {
|
||
width: size,
|
||
height: size,
|
||
viewBox: "0 0 24 24",
|
||
fill: "none",
|
||
"aria-hidden": "true",
|
||
style: { display: "block" },
|
||
children: [
|
||
h("path", { d: "M4 9h16l-1.4 10.2a2 2 0 0 1-2 1.8H7.4a2 2 0 0 1-2-1.8Z", stroke: "currentColor", strokeWidth: 1.6, strokeLinejoin: "round" }),
|
||
h("path", { d: "M8.5 9V6.6A2.6 2.6 0 0 1 11.1 4h1.8a2.6 2.6 0 0 1 2.6 2.6V9", stroke: "currentColor", strokeWidth: 1.6, strokeLinecap: "round" }),
|
||
h("path", { d: "M9 13.6h6", stroke: "currentColor", strokeWidth: 1.6, strokeLinecap: "round" }),
|
||
],
|
||
});
|
||
}
|
||
|
||
const EMPTY_SESSIONS = { byId: {}, projectionsBySession: {}, ids: [], phase: "ready" };
|
||
|
||
/**
|
||
* 订阅宿主 store 的快照。main 是 root 级槽,自带的会话级 hook 在 root 作用域下不可靠,
|
||
* 面板改为直接订阅服务层 store:数据与会话页同源,且不依赖 slot 注入的 hook。
|
||
* 用 useState + useEffect + subscribe,而不是 useSyncExternalStore:
|
||
* 宿主 store 的 getSnapshot 不保证每次返回同一引用,避免无限重渲染。
|
||
*/
|
||
function useStoreSnapshot(store, fallback) {
|
||
const read = () => {
|
||
if (!store || typeof store.getSnapshot !== "function") return fallback;
|
||
try { return store.getSnapshot() || fallback; } catch (error) { return fallback; }
|
||
};
|
||
const [snapshot, setSnapshot] = React.useState(read);
|
||
React.useEffect(() => {
|
||
if (!store || typeof store.subscribe !== "function") return undefined;
|
||
try { return store.subscribe(() => setSnapshot(read())); } catch (error) { return undefined; }
|
||
}, [store]);
|
||
return snapshot;
|
||
}
|
||
|
||
/** 面板级错误兜底:任何渲染异常都显示成可见的诊断块,而不是让宿主隔离成空白。 */
|
||
class PanelBoundary extends React.Component {
|
||
constructor(props) {
|
||
super(props);
|
||
this.state = { error: null };
|
||
}
|
||
static getDerivedStateFromError(error) {
|
||
return { error };
|
||
}
|
||
componentDidCatch(error) {
|
||
if (typeof console !== "undefined" && typeof console.error === "function") {
|
||
console.error("[三省六部] 面板渲染失败:", error);
|
||
}
|
||
}
|
||
render() {
|
||
const error = this.state.error;
|
||
if (!error) return this.props.children;
|
||
const message = error && error.message ? error.message : String(error);
|
||
return h("div", { className: "sl-crash", role: "alert" }, [
|
||
h("strong", { children: "三省六部面板渲染失败" }),
|
||
h("pre", { children: message }),
|
||
h("p", { children: "请把上面这段信息发给开发者;界面其余部分不受影响。" }),
|
||
]);
|
||
}
|
||
}
|
||
|
||
/** 主视图选中记录:uiWorkspace 把 {sessionId, subagentAddress} 持久化在 dsh.sessions.current。 */
|
||
function useWorkspaceSelection() {
|
||
const workspace = React.useContext(WorkspaceContext);
|
||
const read = () => {
|
||
if (!workspace || !workspace.selection) return {};
|
||
try { return workspace.selection.getSnapshot() || {}; } catch (error) { return {}; }
|
||
};
|
||
const [selection, setSelection] = React.useState(read);
|
||
React.useEffect(() => {
|
||
if (!workspace || !workspace.selection || typeof workspace.selection.subscribe !== "function") return undefined;
|
||
try { return workspace.selection.subscribe(() => setSelection(read())); } catch (error) { return undefined; }
|
||
}, [workspace]);
|
||
return selection;
|
||
}
|
||
|
||
/** 会话若自身就是被寻址的子代理,返回它的地址;否则 undefined。 */
|
||
function subagentAddressOf(sessions, sessionId) {
|
||
const summary = sessions.byId ? sessions.byId[sessionId] : undefined;
|
||
const direct = summary && summary.subagent && summary.subagent.address;
|
||
if (direct) return direct;
|
||
const bySession = sessions.projectionsBySession || {};
|
||
for (const parentId of Object.keys(bySession)) {
|
||
const parent = bySession[parentId];
|
||
const list = parent && parent.values ? parent.values.subagentCatalog : undefined;
|
||
if (Array.isArray(list) && list.some((entry) => entry && entry.id === sessionId)) {
|
||
return { parentSessionId: parentId, childSessionId: sessionId };
|
||
}
|
||
}
|
||
return undefined;
|
||
}
|
||
|
||
// #region 次要入口(会话头开关 / 侧栏置顶行 / 右侧栏页签)
|
||
function SanshengToggle(props) {
|
||
const host = props.host;
|
||
const info = useStoreSnapshot(host && host.panelStore, {}) || {};
|
||
const open = info.activePanelId === PANEL_ID;
|
||
return h("button", {
|
||
type: "button",
|
||
className: "sl-toggle" + (open ? " active" : ""),
|
||
"data-sansheng-toggle": open ? "open" : "closed",
|
||
title: "三省六部:把朝堂停靠到右侧栏,主对话留在中央",
|
||
onClick: () => {
|
||
const result = host.openSanshengTab();
|
||
if (result && result.ok === false) host.togglePanel();
|
||
},
|
||
}, [
|
||
h("span", { key: "mark", className: "sl-toggle-mark", children: "三省" }),
|
||
h("span", { key: "label", children: open ? "收起朝堂" : "三省六部" }),
|
||
]);
|
||
}
|
||
|
||
function SanshengPinRow(props) {
|
||
const entries = Array.isArray(props.entries) ? props.entries : [];
|
||
const entry = entries.find((item) => item && item.id === PANEL_ID);
|
||
if (!entry) return null;
|
||
const pinned = entry.pinned === true;
|
||
return h("div", {
|
||
className: "sl-pinrow" + (entry.active ? " active" : ""),
|
||
"data-sansheng-pin": pinned ? "pinned" : "floating",
|
||
onClick: () => {
|
||
if (typeof props.onOpen === "function") props.onOpen(PANEL_ID);
|
||
if (typeof props.onDismiss === "function") props.onDismiss();
|
||
},
|
||
onContextMenu: (event) => {
|
||
event.preventDefault();
|
||
if (typeof props.onPinnedChange === "function") props.onPinnedChange(PANEL_ID, !pinned);
|
||
},
|
||
}, [
|
||
h("span", { key: "icon", className: "sl-pinrow-icon" }, h(SidebarIcon, { size: 16 })),
|
||
h("span", { key: "label", className: "sl-pinrow-label", children: "三省六部" }),
|
||
h("span", { key: "hint", className: "sl-pinrow-hint", children: pinned ? "已置顶" : "右键置顶" }),
|
||
]);
|
||
}
|
||
|
||
function SanshengTabTitle() {
|
||
return h("div", { className: "sl-tab-title", "data-sansheng-tab-title": "1" }, [
|
||
h("span", { key: "mark", className: "sl-tab-mark", children: "三省" }),
|
||
h("span", { key: "label", children: "朝堂" }),
|
||
]);
|
||
}
|
||
|
||
function SanshengTabBody(props) {
|
||
const host = props.host;
|
||
const sessionId = props.sessionId;
|
||
React.useEffect(() => {
|
||
if (sessionId && host.setSelected) host.setSelected(sessionId);
|
||
}, [sessionId]);
|
||
return h(PanelBoundary, null, h(SanshengPanel, { ...props, host, compact: true }));
|
||
}
|
||
|
||
function DockButton(props) {
|
||
const host = props.host;
|
||
const [notice, setNotice] = React.useState(null);
|
||
return h("span", { className: "sl-dock" }, [
|
||
h("button", {
|
||
key: "btn",
|
||
type: "button",
|
||
"data-sansheng-dock": "1",
|
||
onClick: () => {
|
||
const result = host.openSanshengTab();
|
||
if (result && result.ok === false) setNotice(result.error);
|
||
else setNotice(null);
|
||
},
|
||
children: "停靠右侧栏",
|
||
}),
|
||
notice ? h("span", { key: "err", className: "sl-dock-error", children: notice }) : null,
|
||
]);
|
||
}
|
||
|
||
/** better-sidebar 是可选的:没装时不要写进 inject,否则插件会被 park。 */
|
||
function betterSidebarOf(ctx) {
|
||
const candidates = [];
|
||
try { if (typeof ctx.get === "function") candidates.push(ctx.get("betterSidebar")); } catch (error) { /* 忽略 */ }
|
||
try { candidates.push(ctx.betterSidebar); } catch (error) { /* 忽略 */ }
|
||
return candidates.find((item) => item && typeof item.registerTab === "function");
|
||
}
|
||
// #endregion
|
||
|
||
function apply(ctx) {
|
||
// main 面板是 root 级槽,拿不到会话级 props:把 uiWorkspace 的选中记录
|
||
// 放进 React context 供面板读取,并把同一引用交给 host 做导航。
|
||
WorkspaceContext = React.createContext(undefined);
|
||
const workspace = ctx.uiWorkspace;
|
||
const host = createHost(ctx);
|
||
|
||
ctx.slots.inject("sidebar.panellist", () => ctx.slots.register({
|
||
name: "sidebar.panellist",
|
||
id: PANEL_ID,
|
||
order: -5,
|
||
label: () => "三省六部",
|
||
}, SidebarIcon));
|
||
|
||
ctx.slots.inject("sidebar.panellist.actions", () => ctx.slots.register({
|
||
name: "sidebar.panellist.actions",
|
||
id: PANEL_ID + ":pin",
|
||
order: -50,
|
||
}, (props) => h(SanshengPinRow, props)));
|
||
|
||
ctx.slots.inject("conversation.session.header.actions", () => ctx.slots.register({
|
||
name: "conversation.session.header.actions",
|
||
id: PANEL_ID + ":toggle",
|
||
order: 40,
|
||
}, (props) => h(SanshengToggle, { ...props, host })));
|
||
|
||
// 整页入口:始终可见的页头 + 面板主体。
|
||
ctx.slots.inject("main", () => ctx.slots.register({
|
||
name: "main",
|
||
key: PANEL_ID,
|
||
}, (props) => h("div", { className: "sl-main-shell", "data-sansheng-main": "1" }, [
|
||
h("div", { key: "head", className: "sl-main-head" }, [
|
||
h("strong", { key: "title", children: "三省六部 · 朝堂" }),
|
||
h("span", { key: "hint", className: "sl-main-head-hint", children: "v0.3" }),
|
||
h("span", { key: "spacer", className: "sl-main-head-spacer" }),
|
||
h(DockButton, { key: "dock", host }),
|
||
]),
|
||
h("div", { key: "body", className: "sl-main-body" },
|
||
h(WorkspaceContext.Provider, { value: workspace },
|
||
h(PanelBoundary, null, h(SanshengPanel, { ...props, host })))),
|
||
])));
|
||
|
||
// 右侧栏回退:宿主自带 sidebarRight(better-sidebar 存在时不注册,避免两处同名页签)。
|
||
const better = betterSidebarOf(ctx);
|
||
if (better) {
|
||
ctx.effect(() => better.registerTab({
|
||
id: SANSENG_TAB_ID,
|
||
title: "三省六部",
|
||
description: "朝堂成员图、任务与配置;对话本体留在中央",
|
||
order: 5,
|
||
single: true,
|
||
component: (props) => h(PanelBoundary, null, h(SanshengPanel, {
|
||
host,
|
||
sessionId: props && props.scope ? props.scope.sessionId : undefined,
|
||
compact: true,
|
||
})),
|
||
}), "三省六部: better-sidebar 页签");
|
||
} else {
|
||
try {
|
||
ctx.effect(() => {
|
||
try {
|
||
return ctx.sidebarRightTabs.register({
|
||
id: SANSENG_TAB_ID,
|
||
kind: SANSENG_TAB_KIND,
|
||
priority: "builtin",
|
||
title: () => "三省六部",
|
||
});
|
||
} catch (error) {
|
||
if (typeof console !== "undefined" && console.warn) console.warn("[三省六部] 右侧栏 tab 类型注册失败:", error);
|
||
return () => {};
|
||
}
|
||
}, "三省六部: 右侧栏 tab 类型");
|
||
} catch (error) { /* 老宿主没有该服务:整页形式仍可用 */ }
|
||
}
|
||
|
||
ctx.slots.inject("sidebar.right.pane.tab", () => ctx.slots.register({
|
||
name: "sidebar.right.pane.tab",
|
||
key: SANSENG_TAB_ID,
|
||
}, (props) => h(SanshengTabBody, { ...props, host })));
|
||
|
||
ctx.slots.inject("sidebar.right.pane.tab.title", () => ctx.slots.register({
|
||
name: "sidebar.right.pane.tab.title",
|
||
key: SANSENG_TAB_ID,
|
||
}, () => h(SanshengTabTitle, null)));
|
||
}
|
||
|
||
exports.apply = apply;
|
||
exports.inject = ["slots", "sessions", "uiWorkspace", "uiConversation", "modelDirectories", "remote", "remote.agentPresets", "sidebarRightTabs", "sidebarRight"];
|
||
exports.SanshengPanel = SanshengPanel;
|
||
exports.SidebarIcon = SidebarIcon;
|
||
exports.PANEL_ID = PANEL_ID;
|
||
exports.SANSENG_TAB_ID = SANSENG_TAB_ID;
|
||
exports.SANSENG_TAB_KIND = SANSENG_TAB_KIND;
|
||
exports.createHost = createHost;
|
||
exports.__test = {
|
||
PANEL_ID,
|
||
SANSENG_TAB_ID,
|
||
SANSENG_TAB_KIND,
|
||
ROLE_IDS,
|
||
roleLabel,
|
||
roleMark,
|
||
modelLabel,
|
||
effortLabel,
|
||
arrangeRoster,
|
||
memberStatus,
|
||
tasksOfRole,
|
||
statusSummary,
|
||
modelOptions,
|
||
findModelOption,
|
||
modelSwitchPlan,
|
||
decreeText,
|
||
lastExchange,
|
||
shortText,
|
||
bucketsOf,
|
||
};
|
||
return module.exports;
|
||
},
|
||
});
|