diff --git a/README.md b/README.md index afc33b2..23866f3 100644 --- a/README.md +++ b/README.md @@ -9,8 +9,11 @@ 同步云端技能中心与本机技能目录。 当前版本 **0.10.1**,含宿主端与浏览器端两部分:宿主端负责活动上报、 -记忆工具注册与技能同步,`client/index.js` 提供「设置 → 插件 → 云端记忆」 -配置卡片。 +记忆工具注册与技能同步。浏览器 UI 有三个入口: + +- 左侧栏 **Brain** 展示全局运行状态,管理全局记忆与部门。 +- Better Sidebar 的 **项目记忆** 使用当前会话的项目目录,管理该项目的记忆、文档与部门。 +- **设置 → 云端记忆** 提供完整配置,包括连接与上报、技能管理和 MCP 管理。 ## 它做什么 @@ -21,7 +24,7 @@ | 失败重试 | 网络错误与 5xx 进入待重试队列(上限 200 条),每 30 秒补发一次;4xx 不重试。切换账号或换服务地址后,旧队列条目会被丢弃,不会发到新账号。 | | 记忆工具 | `memory_search`、`memory_read`、`memory_add`、`memory_list`、`memory_projects` 五个工具实时读写云端记忆库。 | | 技能同步 | 云端技能中心 ↔ 本机技能目录双向同步,冲突按内容与时间自动取较新(详见「技能同步」)。 | -| 配置页 | `GET /dsh-brain` 提供完整配置界面(本 profile 关闭了原生设置页,所以自带页面)。 | +| 配置页 | 设置中的「云端记忆」提供完整配置,另有独立页面 `GET /dsh-brain`。 | **上传范围(如实说明)**:活动上报只上传上表 6 个元数据字段,不含提示词 正文。**可选的摘要功能**(`summaryToken`)开启时,会把结束回合的对话文本 @@ -46,7 +49,7 @@ - 共享服务(设置、客户端、同步引擎)由进程级内核统一构造,关掉再开不会 重复实例;设置持久化在 `$DSH_HOME/dsh-brain.json`(侧车文件为权威, 插件行的 config 只作首次种子)。 -- 根导出 `.` 仍是兼容组合器:老的单行 profile 升级后行为不变。 +- UI 子插件以包根名 `dsh-brain` 注册,供 DSH 发现浏览器端入口;该子插件行传入 `entry: ui`。旧的单行 profile 继续通过根导出加载全部子插件。 - 0.11.0 起第五个子插件行 id 从 `dsh-brain-settings-ui` 改为 `dsh-brain-ui`(package exports 保留 `./settings-ui` 别名指向同一入口)。若 profile 里还留有旧 id 的禁用/配置行,请到「设置 → 插件」对 `dsh-brain-ui` 重新设置;插件不会自动改写宿主配置文件。 ## 安装 @@ -57,8 +60,8 @@ dsh plugin --profile desktop add dsh-brain ``` 装好后确认 profile 的 `package.json` 依赖里有 `dsh-brain`。重启 DSH,在 -「设置 → 插件 → 云端记忆」里配置(备用入口: -`http://127.0.0.1:<当次端口>/dsh-brain`,旧 `/cloud-memory` 路由保留为别名)。 +「设置 → 云端记忆」里配置。也可从插件详情的配置入口或 +`http://127.0.0.1:<当次端口>/dsh-brain` 使用完整配置,旧 `/cloud-memory` 路由保留为别名。 > `baseUrl` 默认是占位符 `https://your-memory-host/api/longmemory`。 > **首次使用必须先把它改成你自己的 LongMemory 服务地址**(配置页里填, diff --git a/client/index.js b/client/index.js index 21d61ed..0e44f7c 100644 --- a/client/index.js +++ b/client/index.js @@ -482,20 +482,20 @@ window.__ModuleLoader__.load({ } }; // src-client/components.tsx - const h$14 = react.createElement; + const h$13 = react.createElement; function Pill$1(props) { var tone = styles[props.tone] === void 0 ? styles.muted : styles[props.tone]; - return h$14("span", { style: Object.assign({}, styles.pill, tone) }, h$14("span", { style: { opacity: .75 } }, props.label), h$14("span", { style: { fontWeight: 600 } }, String(props.value))); + return h$13("span", { style: Object.assign({}, styles.pill, tone) }, h$13("span", { style: { opacity: .75 } }, props.label), h$13("span", { style: { fontWeight: 600 } }, String(props.value))); } function Banner(props) { var tone = styles[props.tone] === void 0 ? styles.muted : styles[props.tone]; - return h$14("div", { + return h$13("div", { style: Object.assign({}, styles.banner, tone), role: props.role }, props.children); } function Field(props) { - return h$14("label", { style: styles.field }, h$14("span", { style: styles.label }, props.label), h$14("input", { + return h$13("label", { style: styles.field }, h$13("span", { style: styles.label }, props.label), h$13("input", { style: styles.input, type: props.type === void 0 ? "text" : props.type, value: props.value, @@ -506,7 +506,7 @@ window.__ModuleLoader__.load({ onChange: function(event) { props.onChange(event.target.value); } - }), props.hint === void 0 ? null : h$14("span", { style: styles.hint }, props.hint)); + }), props.hint === void 0 ? null : h$13("span", { style: styles.hint }, props.hint)); } function Btn(props) { var base = props.variant === "primary" ? styles.buttonPrimary : props.variant === "danger" ? styles.buttonDanger : props.variant === "small" ? styles.buttonSmall : styles.button; @@ -514,7 +514,7 @@ window.__ModuleLoader__.load({ opacity: .45, cursor: "not-allowed" }) : base; - return h$14("button", { + return h$13("button", { type: "button", style, disabled: props.disabled === true, @@ -527,7 +527,7 @@ window.__ModuleLoader__.load({ opacity: .45, cursor: "not-allowed" } : null); - return h$14("button", { + return h$13("button", { type: "button", style, disabled: props.disabled === true, @@ -537,13 +537,13 @@ window.__ModuleLoader__.load({ }, props.glyph); } function Switch(props) { - return h$14("div", { + return h$13("div", { style: styles.tabs, role: "tablist", "aria-label": props.ariaLabel }, props.options.map(function(option) { var active = option.value === props.value; - return h$14("button", { + return h$13("button", { key: option.value, type: "button", role: "tab", @@ -558,7 +558,7 @@ window.__ModuleLoader__.load({ function Toggle(props) { var on = props.checked === true; var disabled = props.disabled === true; - return h$14("button", { + return h$13("button", { type: "button", role: "switch", "aria-checked": on, @@ -581,7 +581,7 @@ window.__ModuleLoader__.load({ transition: "background 120ms ease" }, onClick: disabled ? void 0 : props.onChange - }, h$14("span", { style: { + }, h$13("span", { style: { width: "16px", height: "16px", borderRadius: "999px", @@ -591,7 +591,7 @@ window.__ModuleLoader__.load({ } })); } function Section(props) { - return h$14("div", { style: styles.section }, h$14("div", { style: styles.sectionHead }, h$14("h4", { style: styles.sectionTitle }, props.title), props.aside === void 0 ? null : h$14("div", { style: styles.actions }, props.aside)), props.hint === void 0 ? null : h$14("p", { style: styles.hint }, props.hint), props.children); + return h$13("div", { style: styles.section }, h$13("div", { style: styles.sectionHead }, h$13("h4", { style: styles.sectionTitle }, props.title), props.aside === void 0 ? null : h$13("div", { style: styles.actions }, props.aside)), props.hint === void 0 ? null : h$13("p", { style: styles.hint }, props.hint), props.children); } function CardBoundary(props) { react.Component.call(this, props); @@ -603,7 +603,7 @@ window.__ModuleLoader__.load({ return { failure }; }; CardBoundary.prototype.render = function() { - if (this.state.failure !== null) return h$14("div", { style: Object.assign({}, styles.root) }, h$14("div", { style: Object.assign({}, styles.banner, styles.bad) }, "云端记忆设置卡渲染失败:" + messageOf(this.state.failure)), h$14("p", { style: styles.hint }, "插件本身仍在运行,可改用 /dsh-brain 页面配置。")); + if (this.state.failure !== null) return h$13("div", { style: Object.assign({}, styles.root) }, h$13("div", { style: Object.assign({}, styles.banner, styles.bad) }, "云端记忆设置卡渲染失败:" + messageOf(this.state.failure)), h$13("p", { style: styles.hint }, "插件本身仍在运行,可改用 /dsh-brain 页面配置。")); return this.props.children; }; // src-client/format.ts @@ -728,7 +728,7 @@ window.__ModuleLoader__.load({ return "HTTP " + String(result.status) + (result.error === void 0 ? "" : ":" + result.error); } // src-client/sections/MarketSection.tsx - const h$13 = react.createElement; + const h$12 = react.createElement; function MarketSection(props) { var capabilities = props.capabilities || {}; var tuple = react.useState({ @@ -910,31 +910,31 @@ window.__ModuleLoader__.load({ }); }); } - if (!available) return h$13(Section, { + if (!available) return h$12(Section, { title: "技能市场", hint: "本版没有配置经验证的市场来源。" - }, h$13("p", { style: styles.hint }, "能力缺口:capabilities.features.skillsMarketplace = false,因此不显示任何搜索框或示例条目。")); + }, h$12("p", { style: styles.hint }, "能力缺口:capabilities.features.skillsMarketplace = false,因此不显示任何搜索框或示例条目。")); var providerLabel = state.provider; if (state.providers !== null) state.providers.forEach(function(provider) { if (provider.id === state.provider) providerLabel = provider.label; }); var resultRows = state.entries.map(function(entry) { - return h$13("div", { + return h$12("div", { key: entry.id, style: styles.row - }, h$13("div", { style: styles.rowHead }, h$13("span", { style: styles.rowTitle }, entry.name), h$13("div", { style: styles.pills }, entry.version === void 0 ? null : h$13(Pill$1, { + }, h$12("div", { style: styles.rowHead }, h$12("span", { style: styles.rowTitle }, entry.name), h$12("div", { style: styles.pills }, entry.version === void 0 ? null : h$12(Pill$1, { label: "版本", value: String(entry.version), tone: "muted" - }), h$13(Pill$1, { + }), h$12(Pill$1, { label: "技能", value: (entry.skills || []).length, tone: "muted" - }), entry.author === void 0 ? null : h$13(Pill$1, { + }), entry.author === void 0 ? null : h$12(Pill$1, { label: "作者", value: String(entry.author), tone: "muted" - }))), h$13("p", { style: styles.hint }, entry.description === "" ? "(无描述)" : entry.description), h$13("div", { style: styles.actions }, h$13(Btn, { + }))), h$12("p", { style: styles.hint }, entry.description === "" ? "(无描述)" : entry.description), h$12("div", { style: styles.actions }, h$12(Btn, { label: "查看详情", variant: "small", disabled: state.busy !== "", @@ -946,16 +946,16 @@ window.__ModuleLoader__.load({ var detailBox = null; if (state.detail !== null) { var details = Array.isArray(state.detail.skillDetails) ? state.detail.skillDetails : []; - detailBox = h$13("div", { style: styles.nested }, h$13("p", { style: styles.hint }, "来源:" + String(state.detail.sourceRepo) + " · " + (state.detail.description || "")), h$13("div", { style: { + detailBox = h$12("div", { style: styles.nested }, h$12("p", { style: styles.hint }, "来源:" + String(state.detail.sourceRepo) + " · " + (state.detail.description || "")), h$12("div", { style: { display: "flex", flexDirection: "column", gap: "4px" } }, details.map(function(skill) { - return h$13("div", { + return h$12("div", { key: skill.folder, style: styles.rowHead - }, h$13("span", { style: styles.rowTitle }, skill.name === void 0 ? skill.folder : skill.name), h$13("span", { style: styles.hint }, skill.ok === false ? "(无法读取 SKILL.md)" : String(skill.description || ""))); - })), h$13("div", { style: styles.actions }, h$13(Btn, { + }, h$12("span", { style: styles.rowTitle }, skill.name === void 0 ? skill.folder : skill.name), h$12("span", { style: styles.hint }, skill.ok === false ? "(无法读取 SKILL.md)" : String(skill.description || ""))); + })), h$12("div", { style: styles.actions }, h$12(Btn, { variant: "primary", label: state.busy === "plan" ? "拉取中…" : "拉取安装计划", disabled: state.busy !== "", @@ -965,71 +965,71 @@ window.__ModuleLoader__.load({ var planBox = null; if (state.plan !== null) { var candidates = Array.isArray(state.plan.candidates) ? state.plan.candidates : []; - planBox = h$13("div", { style: styles.nested }, h$13("p", { style: styles.hint }, "已固定提交:" + (state.plan.commit === void 0 ? "克隆时记录实际提交" : String(state.plan.commit).slice(0, 12)) + ";只安装勾选项,冲突项默认不勾,不执行仓库脚本。"), candidates.length === 0 ? h$13("p", { style: styles.hint }, "该条目没有可安装的技能。") : null, h$13("div", { style: { + planBox = h$12("div", { style: styles.nested }, h$12("p", { style: styles.hint }, "已固定提交:" + (state.plan.commit === void 0 ? "克隆时记录实际提交" : String(state.plan.commit).slice(0, 12)) + ";只安装勾选项,冲突项默认不勾,不执行仓库脚本。"), candidates.length === 0 ? h$12("p", { style: styles.hint }, "该条目没有可安装的技能。") : null, h$12("div", { style: { display: "flex", flexDirection: "column", gap: "6px" } }, candidates.map(function(candidate) { - return h$13("label", { + return h$12("label", { key: candidate.folder, style: styles.checkboxRow - }, h$13("input", { + }, h$12("input", { type: "checkbox", checked: state.selected[candidate.folder] === true, disabled: candidate.conflict === true || candidate.problem !== void 0, onChange: function() { toggleFolder(candidate.folder); } - }), h$13("span", null, candidate.folder + " · " + String(candidate.files) + " 个文件 · " + formatBytes(candidate.bytes) + (candidate.conflict === true ? " · 已存在,跳过" : "") + (candidate.problem === void 0 ? "" : " · " + candidate.problem))); - })), h$13("div", { style: styles.actions }, h$13(Btn, { + }), h$12("span", null, candidate.folder + " · " + String(candidate.files) + " 个文件 · " + formatBytes(candidate.bytes) + (candidate.conflict === true ? " · 已存在,跳过" : "") + (candidate.problem === void 0 ? "" : " · " + candidate.problem))); + })), h$12("div", { style: styles.actions }, h$12(Btn, { variant: "primary", label: state.busy === "commit" ? "安装中…" : "安装选中", disabled: state.busy !== "", onClick: commitPlan }))); } - return h$13(Section, { + return h$12(Section, { title: "技能市场", hint: "来自经验证的公开市场清单;安装走暂存计划、只装勾选项并固定提交。" - }, h$13("div", { style: { + }, h$12("div", { style: { display: "flex", flexDirection: "column", gap: "10px" - } }, h$13("div", { style: styles.pills }, h$13(Pill$1, { + } }, h$12("div", { style: styles.pills }, h$12(Pill$1, { label: "来源", value: String(providerLabel || "未配置"), tone: "muted" - }), state.providers === null ? null : h$13(Pill$1, { + }), state.providers === null ? null : h$12(Pill$1, { label: "已接入", value: state.providers.length, tone: "ok" - })), h$13("div", { style: { + })), h$12("div", { style: { display: "flex", gap: "8px", alignItems: "flex-end", flexWrap: "wrap" - } }, h$13("div", { style: { + } }, h$12("div", { style: { flex: "1 1 220px", minWidth: 0 - } }, h$13(Field, { + } }, h$12(Field, { label: "搜索市场", value: state.query, placeholder: "例如 xlsx / pdf / design", onChange: function(value) { patch({ query: value }); } - })), h$13(Btn, { + })), h$12(Btn, { variant: "primary", label: state.busy === "search" ? "搜索中…" : "搜索", disabled: state.busy !== "", onClick: function() { search(false); } - })), state.error === null ? null : h$13(Banner, { tone: "bad" }, state.error), state.notice === null ? null : h$13(Banner, { tone: state.notice.tone }, state.notice.text), state.status === "ready" && state.entries.length === 0 ? h$13("p", { style: styles.hint }, "没有匹配的市场条目。") : null, h$13("div", { style: { + })), state.error === null ? null : h$12(Banner, { tone: "bad" }, state.error), state.notice === null ? null : h$12(Banner, { tone: state.notice.tone }, state.notice.text), state.status === "ready" && state.entries.length === 0 ? h$12("p", { style: styles.hint }, "没有匹配的市场条目。") : null, h$12("div", { style: { display: "flex", flexDirection: "column", gap: "8px" - } }, resultRows), state.nextCursor === null ? null : h$13("div", { style: styles.actions }, h$13(Btn, { + } }, resultRows), state.nextCursor === null ? null : h$12("div", { style: styles.actions }, h$12(Btn, { label: "加载更多", variant: "small", disabled: state.busy !== "", @@ -1039,7 +1039,7 @@ window.__ModuleLoader__.load({ })), detailBox, planBox)); } // src-client/sections/SyncResolveSection.tsx - const h$12 = react.createElement; + const h$11 = react.createElement; function SyncResolveSection(props) { var tuple = react.useState({ status: "idle", @@ -1205,23 +1205,23 @@ window.__ModuleLoader__.load({ var data = state.data; var stats = data === null || data === void 0 ? null : data.stats; var conflicts = data === null || data === void 0 || !Array.isArray(data.conflicts) ? [] : data.conflicts; - var statPills = stats === null ? h$12("p", { style: styles.hint }, "同步引擎未启用或尚未运行。") : h$12("div", { style: styles.pills }, h$12(Pill$1, { + var statPills = stats === null ? h$11("p", { style: styles.hint }, "同步引擎未启用或尚未运行。") : h$11("div", { style: styles.pills }, h$11(Pill$1, { label: "运行中", value: stats.running === true ? "是" : "否", tone: stats.running === true ? "warn" : "muted" - }), h$12(Pill$1, { + }), h$11(Pill$1, { label: "上次运行", value: formatIso(stats.lastRunAt), tone: "muted" - }), h$12(Pill$1, { + }), h$11(Pill$1, { label: "上传", value: (stats.uploaded || []).length, tone: "muted" - }), h$12(Pill$1, { + }), h$11(Pill$1, { label: "下载", value: (stats.downloaded || []).length, tone: "muted" - }), h$12(Pill$1, { + }), h$11(Pill$1, { label: "冲突", value: conflicts.length, tone: conflicts.length > 0 ? "warn" : "muted" @@ -1229,36 +1229,36 @@ window.__ModuleLoader__.load({ var conflictRows = conflicts.map(function(conflict) { var local = conflict.local || {}; var cloud = conflict.cloud; - return h$12("div", { + return h$11("div", { key: conflict.name, style: styles.row - }, h$12("div", { style: styles.rowHead }, h$12("span", { style: styles.rowTitle }, conflict.name), h$12("div", { style: styles.pills }, h$12(Pill$1, { + }, h$11("div", { style: styles.rowHead }, h$11("span", { style: styles.rowTitle }, conflict.name), h$11("div", { style: styles.pills }, h$11(Pill$1, { label: "原因", value: String(conflict.reason), tone: "warn" - }), h$12(Pill$1, { + }), h$11(Pill$1, { label: "本地", value: local.exists === true ? local.files + " 文件" : "缺失", tone: local.exists === true ? "muted" : "bad" - }), h$12(Pill$1, { + }), h$11(Pill$1, { label: "云端", value: cloud === null ? "无" : "rev " + String(cloud.revision === void 0 ? "?" : cloud.revision), tone: cloud === null ? "muted" : "ok" - }))), h$12("p", { style: styles.hint }, conflict.note), h$12("div", { style: styles.actions }, h$12(Btn, { + }))), h$11("p", { style: styles.hint }, conflict.note), h$11("div", { style: styles.actions }, h$11(Btn, { label: "保留本地", variant: "small", disabled: state.busy !== "" || conflict.canKeepLocal !== true, onClick: function() { resolve(conflict.name, "keep_local", conflict.conflictId); } - }), h$12(Btn, { + }), h$11(Btn, { label: "采用云端", variant: "small", disabled: state.busy !== "" || conflict.canTakeCloud !== true, onClick: function() { resolve(conflict.name, "take_cloud", conflict.conflictId); } - }), h$12(Btn, { + }), h$11(Btn, { label: "手动合并", variant: "small", disabled: state.busy !== "", @@ -1268,7 +1268,7 @@ window.__ModuleLoader__.load({ }))); }); var batchRow = null; - if (conflicts.length > 0) batchRow = h$12("div", { style: styles.actions }, h$12(Btn, { + if (conflicts.length > 0) batchRow = h$11("div", { style: styles.actions }, h$11(Btn, { label: "全部保留本地", variant: "small", disabled: state.busy !== "" || !conflicts.some(function(item) { @@ -1280,7 +1280,7 @@ window.__ModuleLoader__.load({ notice: null }); } - }), h$12(Btn, { + }), h$11(Btn, { label: "全部采用云端", variant: "small", disabled: state.busy !== "" || !conflicts.some(function(item) { @@ -1296,14 +1296,14 @@ window.__ModuleLoader__.load({ var confirmAllRow = null; if (state.pendingAll !== null && conflicts.length > 0) { var pendingText = state.pendingAll === "keep_local" ? "把全部本地版本上传为新版本" : "用云端版本覆盖全部本地(覆盖前自动备份)"; - confirmAllRow = h$12("div", { style: styles.nested }, h$12("p", { style: styles.hint }, "确认" + pendingText + "?共 " + conflicts.length + " 项。"), h$12("div", { style: styles.actions }, h$12(Btn, { + confirmAllRow = h$11("div", { style: styles.nested }, h$11("p", { style: styles.hint }, "确认" + pendingText + "?共 " + conflicts.length + " 项。"), h$11("div", { style: styles.actions }, h$11(Btn, { variant: "primary", label: state.busy === "all:keep_local" || state.busy === "all:take_cloud" ? "处理中…" : "确认批量", disabled: state.busy !== "", onClick: function() { resolveAll(state.pendingAll); } - }), h$12(Btn, { + }), h$11(Btn, { variant: "small", label: "取消", disabled: state.busy !== "", @@ -1312,27 +1312,27 @@ window.__ModuleLoader__.load({ } }))); } - return h$12(Section, { + return h$11(Section, { title: "云端同步与冲突", hint: "同步先比内容与更新时间:一致直接认领,不同则自动采用较新的一边(覆盖云端前先备份本地);只有时间相同/缺失或目录结构不支持时才逐项询问,也可用批量按钮一次处理。", - aside: h$12(Btn, { + aside: h$11(Btn, { label: state.busy === "run" ? "同步中…" : "立即同步", variant: "small", disabled: state.busy !== "", onClick: runNow }) - }, h$12("div", { style: { + }, h$11("div", { style: { display: "flex", flexDirection: "column", gap: "10px" - } }, state.error === null ? null : h$12(Banner, { tone: "bad" }, state.error), state.notice === null ? null : h$12(Banner, { tone: state.notice.tone }, state.notice.text), statPills, batchRow, confirmAllRow, conflicts.length === 0 ? h$12("p", { style: styles.hint }, "当前没有待处理冲突。") : h$12("div", { style: { + } }, state.error === null ? null : h$11(Banner, { tone: "bad" }, state.error), state.notice === null ? null : h$11(Banner, { tone: state.notice.tone }, state.notice.text), statPills, batchRow, confirmAllRow, conflicts.length === 0 ? h$11("p", { style: styles.hint }, "当前没有待处理冲突。") : h$11("div", { style: { display: "flex", flexDirection: "column", gap: "8px" } }, conflictRows))); } // src-client/sections/McpCustomSection.tsx - const h$11 = react.createElement; + const h$10 = react.createElement; function McpCustomSection(props) { var open = react.useState(false); var tuple = react.useState({ @@ -1446,10 +1446,10 @@ window.__ModuleLoader__.load({ if (ok && typeof props.onChanged === "function") props.onChanged(); }); } - return h$11(Section, { + return h$10(Section, { title: "新增 / 导入连接", hint: "HTTP 与 stdio 都由宿主校验并保存凭据;本卡不回显已有密钥。stdio 的启动命令由你显式填写,云端不会执行任何本机命令。", - aside: h$11(Btn, { + aside: h$10(Btn, { label: open[0] ? "收起" : "展开", ariaLabel: "展开新增连接", variant: "small", @@ -1457,90 +1457,90 @@ window.__ModuleLoader__.load({ open[1](!open[0]); } }) - }, open[0] ? h$11("div", { style: { + }, open[0] ? h$10("div", { style: { display: "flex", flexDirection: "column", gap: "10px" - } }, h$11("div", { style: styles.grid }, h$11(Field, { + } }, h$10("div", { style: styles.grid }, h$10(Field, { label: "名称", value: s.name, onChange: function(v) { patch({ name: v }); } - }), h$11(Field, { + }), h$10(Field, { label: "Server 名(可选)", value: s.serverName, onChange: function(v) { patch({ serverName: v }); } - }), h$11("div", { style: styles.field }, h$11("span", { style: styles.label }, "传输方式"), h$11("select", { + }), h$10("div", { style: styles.field }, h$10("span", { style: styles.label }, "传输方式"), h$10("select", { value: s.transport, style: styles.input, onChange: function(e) { patch({ transport: e.target.value }); } - }, h$11("option", { value: "streamable-http" }, "Streamable HTTP"), h$11("option", { value: "stdio" }, "stdio(本机进程)")))), s.transport === "stdio" ? h$11("div", { style: styles.grid }, h$11(Field, { + }, h$10("option", { value: "streamable-http" }, "Streamable HTTP"), h$10("option", { value: "stdio" }, "stdio(本机进程)")))), s.transport === "stdio" ? h$10("div", { style: styles.grid }, h$10(Field, { label: "启动命令", value: s.command, placeholder: "npx / uvx / 本机可执行文件", onChange: function(v) { patch({ command: v }); } - }), h$11(Field, { + }), h$10(Field, { label: "参数(空格分隔)", value: s.args, onChange: function(v) { patch({ args: v }); } - }), h$11(Field, { + }), h$10(Field, { label: "工作目录(可选)", value: s.cwd, onChange: function(v) { patch({ cwd: v }); } - })) : h$11("div", { style: { + })) : h$10("div", { style: { display: "flex", flexDirection: "column", gap: "10px" - } }, h$11(Field, { + } }, h$10(Field, { label: "URL", value: s.url, placeholder: "https://…", onChange: function(v) { patch({ url: v }); } - }), h$11("div", { style: styles.grid }, h$11("div", { style: styles.field }, h$11("span", { style: styles.label }, "鉴权"), h$11("select", { + }), h$10("div", { style: styles.grid }, h$10("div", { style: styles.field }, h$10("span", { style: styles.label }, "鉴权"), h$10("select", { value: s.authMode, style: styles.input, onChange: function(e) { patch({ authMode: e.target.value }); } - }, h$11("option", { value: "none" }, "无"), h$11("option", { value: "bearer" }, "Bearer Token"), h$11("option", { value: "api-key" }, "API Key"))), s.authMode === "bearer" ? h$11(Field, { + }, h$10("option", { value: "none" }, "无"), h$10("option", { value: "bearer" }, "Bearer Token"), h$10("option", { value: "api-key" }, "API Key"))), s.authMode === "bearer" ? h$10(Field, { label: "Bearer Token", type: "password", value: s.bearerToken, onChange: function(v) { patch({ bearerToken: v }); } - }) : null, s.authMode === "api-key" ? h$11(Field, { + }) : null, s.authMode === "api-key" ? h$10(Field, { label: "API Key 头", value: s.apiKeyHeader, onChange: function(v) { patch({ apiKeyHeader: v }); } - }) : null, s.authMode === "api-key" ? h$11(Field, { + }) : null, s.authMode === "api-key" ? h$10(Field, { label: "API Key 值", type: "password", value: s.apiKeyValue, onChange: function(v) { patch({ apiKeyValue: v }); } - }) : null)), h$11("div", { style: styles.actions }, h$11(Btn, { + }) : null)), h$10("div", { style: styles.actions }, h$10(Btn, { variant: "primary", label: s.busy === "configure" ? "保存中…" : "校验并保存连接", disabled: s.busy !== "", onClick: submit - })), h$11("p", { style: styles.hint }, "或粘贴 mcpServers JSON 批量导入:"), h$11("textarea", { + })), h$10("p", { style: styles.hint }, "或粘贴 mcpServers JSON 批量导入:"), h$10("textarea", { value: s.importJson, rows: 5, style: Object.assign({}, styles.input, { @@ -1551,14 +1551,14 @@ window.__ModuleLoader__.load({ onChange: function(e) { patch({ importJson: e.target.value }); } - }), h$11("div", { style: styles.actions }, h$11(Btn, { + }), h$10("div", { style: styles.actions }, h$10(Btn, { label: s.busy === "import" ? "导入中…" : "导入 JSON", disabled: s.busy !== "", onClick: importJson - })), s.notice === null ? null : h$11(Banner, { tone: s.notice.tone }, s.notice.text)) : null); + })), s.notice === null ? null : h$10(Banner, { tone: s.notice.tone }, s.notice.text)) : null); } // src-client/sections/McpConfigSection.tsx - const h$10 = react.createElement; + const h$9 = react.createElement; function McpConfigSection(props) { var items = Array.isArray(props.items) ? props.items : []; var open = react.useState(false); @@ -1728,10 +1728,10 @@ window.__ModuleLoader__.load({ }); } var gov = s.gov; - return h$10(Section, { + return h$9(Section, { title: "连接配置、范围与治理", hint: "配置编辑使用宿主的保留标记合并,空输入不会清空已有密钥;作用域与策略都带 revision 预览后再提交。", - aside: h$10(Btn, { + aside: h$9(Btn, { label: open[0] ? "收起" : "展开", ariaLabel: "展开连接配置", variant: "small", @@ -1739,11 +1739,11 @@ window.__ModuleLoader__.load({ open[1](!open[0]); } }) - }, open[0] ? h$10("div", { style: { + }, open[0] ? h$9("div", { style: { display: "flex", flexDirection: "column", gap: "12px" - } }, itemSelect(items, s.key, choose), s.key === "" ? h$10("p", { style: styles.hint }, "选择一条连接后可编辑配置、调整范围或设置治理策略。") : h$10("div", { style: styles.nested }, h$10("p", { style: styles.hint }, "可编辑配置(保留标记 表示保留原密钥):"), h$10("textarea", { + } }, itemSelect(items, s.key, choose), s.key === "" ? h$9("p", { style: styles.hint }, "选择一条连接后可编辑配置、调整范围或设置治理策略。") : h$9("div", { style: styles.nested }, h$9("p", { style: styles.hint }, "可编辑配置(保留标记 表示保留原密钥):"), h$9("textarea", { value: s.json, rows: 8, style: Object.assign({}, styles.input, { @@ -1753,88 +1753,88 @@ window.__ModuleLoader__.load({ onChange: function(e) { patch({ json: e.target.value }); } - }), h$10("div", { style: styles.actions }, h$10(Btn, { + }), h$9("div", { style: styles.actions }, h$9(Btn, { variant: "primary", label: s.busy === "save" ? "保存中…" : "保存配置", disabled: s.busy !== "" || s.json === "", onClick: save - })), h$10("p", { style: styles.hint }, "作用域(目标范围 + mode=move,凭据不复制):"), h$10("div", { style: styles.grid }, h$10("div", { style: styles.field }, h$10("span", { style: styles.label }, "目标范围"), h$10("select", { + })), h$9("p", { style: styles.hint }, "作用域(目标范围 + mode=move,凭据不复制):"), h$9("div", { style: styles.grid }, h$9("div", { style: styles.field }, h$9("span", { style: styles.label }, "目标范围"), h$9("select", { value: s.targetScope, style: styles.input, onChange: function(e) { patch({ targetScope: e.target.value }); } - }, h$10("option", { value: "global" }, "全局"), h$10("option", { value: "project" }, "指定工作区"))), s.targetScope === "project" ? h$10(Field, { + }, h$9("option", { value: "global" }, "全局"), h$9("option", { value: "project" }, "指定工作区"))), s.targetScope === "project" ? h$9(Field, { label: "工作区 id", value: s.workspaceId, onChange: function(v) { patch({ workspaceId: v }); } - }) : null), h$10("div", { style: styles.actions }, h$10(Btn, { + }) : null), h$9("div", { style: styles.actions }, h$9(Btn, { label: s.busy === "scope-preview" ? "预览中…" : "预览作用域", disabled: s.busy !== "", onClick: previewScope - }), s.scopePreview === null ? null : h$10(Btn, { + }), s.scopePreview === null ? null : h$9(Btn, { variant: "primary", label: s.busy === "scope-apply" ? "应用中…" : "应用作用域(rev " + String(s.scopePreview.baseRevision) + ")", disabled: s.busy !== "" || s.scopePreview.canApply !== true, onClick: applyScope - })), s.scopePreview === null ? null : h$10("p", { style: styles.hint }, "影响:" + String(s.scopePreview.impact === void 0 ? "" : JSON.stringify(s.scopePreview.impact)) + ";可应用:" + (s.scopePreview.canApply === true ? "是" : "否") + ";凭据复制:否"), h$10("p", { style: styles.hint }, "治理(当前 connection 级):"), gov === null ? h$10("p", { style: styles.hint }, "治理文档未读取。") : h$10("div", { style: styles.pills }, h$10(Pill$1, { + })), s.scopePreview === null ? null : h$9("p", { style: styles.hint }, "影响:" + String(s.scopePreview.impact === void 0 ? "" : JSON.stringify(s.scopePreview.impact)) + ";可应用:" + (s.scopePreview.canApply === true ? "是" : "否") + ";凭据复制:否"), h$9("p", { style: styles.hint }, "治理(当前 connection 级):"), gov === null ? h$9("p", { style: styles.hint }, "治理文档未读取。") : h$9("div", { style: styles.pills }, h$9(Pill$1, { label: "revision", value: gov.revision, tone: "muted" - }), h$10(Pill$1, { + }), h$9(Pill$1, { label: "规则", value: (gov.rules || []).length, tone: "muted" - }), h$10(Pill$1, { + }), h$9(Pill$1, { label: "优先级", value: String(gov.precedenceLabel || "—"), tone: "muted" - })), h$10("div", { style: styles.actions }, h$10(Btn, { + })), h$9("div", { style: styles.actions }, h$9(Btn, { label: "预览 allow", variant: "small", disabled: s.busy !== "" || selected === null, onClick: function() { previewPolicy("allow"); } - }), h$10(Btn, { + }), h$9(Btn, { label: "预览 deny", variant: "small", disabled: s.busy !== "" || selected === null, onClick: function() { previewPolicy("deny"); } - }), h$10(Btn, { + }), h$9(Btn, { label: "预览 inherit", variant: "small", disabled: s.busy !== "" || selected === null, onClick: function() { previewPolicy("inherit"); } - }), s.policyPreview === null ? null : h$10(Btn, { + }), s.policyPreview === null ? null : h$9(Btn, { variant: "primary", label: s.busy === "policy-apply" ? "应用中…" : "应用策略(rev " + String(s.policyPreview.baseRevision) + ")", disabled: s.busy !== "", onClick: applyPolicy - }))), s.notice === null ? null : h$10(Banner, { tone: s.notice.tone }, s.notice.text)) : null); + }))), s.notice === null ? null : h$9(Banner, { tone: s.notice.tone }, s.notice.text)) : null); } function itemSelect(items, value, onChange) { - return h$10("div", { style: styles.field }, h$10("span", { style: styles.label }, "连接"), h$10("select", { + return h$9("div", { style: styles.field }, h$9("span", { style: styles.label }, "连接"), h$9("select", { value, style: styles.input, onChange: function(e) { onChange(e.target.value); } - }, h$10("option", { value: "" }, "选择连接…"), items.map(function(item) { - return h$10("option", { + }, h$9("option", { value: "" }, "选择连接…"), items.map(function(item) { + return h$9("option", { key: item.key, value: item.key }, String(item.name || item.key) + "(" + String(item.transport || "") + ")"); }))); } // src-client/sections/ImportSection.tsx - const h$9 = react.createElement; + const h$8 = react.createElement; function ImportSection(props) { var onImported = props && typeof props.onImported === "function" ? props.onImported : null; var tuple = react.useState({ @@ -2016,17 +2016,17 @@ window.__ModuleLoader__.load({ load(); }); } - if (!s.expanded) return h$9("div", { style: { + if (!s.expanded) return h$8("div", { style: { display: "flex", alignItems: "center", justifyContent: "space-between", gap: "8px", flexWrap: "wrap" - } }, h$9(Btn, { + } }, h$8(Btn, { label: "从其他软件导入", ariaLabel: "从其他软件导入", onClick: openPanel - }), s.notice === null ? null : h$9(Banner, { tone: s.notice.tone }, s.notice.text)); + }), s.notice === null ? null : h$8(Banner, { tone: s.notice.tone }, s.notice.text)); function describe(skill) { var text = String(skill.description === void 0 || skill.description === null ? "" : skill.description).trim(); if (/^[>|][+-]?$/.test(text)) return ""; @@ -2041,15 +2041,15 @@ window.__ModuleLoader__.load({ var selectable = visible.filter(function(entry) { return !importedYet(entry.skill); }); - return h$9("div", { + return h$8("div", { key: source.id, style: styles.row - }, h$9("div", { style: styles.rowHead }, h$9("span", { style: { + }, h$8("div", { style: styles.rowHead }, h$8("span", { style: { display: "inline-flex", alignItems: "center", gap: "8px", minWidth: 0 - } }, h$9("span", { style: styles.sourceGlyph }, String(source.label).slice(0, 1)), h$9("span", { style: styles.sourceTitle }, String(source.label)), h$9("span", { style: styles.hint }, source.exists ? String(all.length) + " 个技能" + (needle === "" ? "" : " · 匹配 " + String(visible.length)) + " · 可导入 " + String(selectable.length) : "未安装")), source.exists ? h$9("div", { style: styles.actions }, h$9(Btn, { + } }, h$8("span", { style: styles.sourceGlyph }, String(source.label).slice(0, 1)), h$8("span", { style: styles.sourceTitle }, String(source.label)), h$8("span", { style: styles.hint }, source.exists ? String(all.length) + " 个技能" + (needle === "" ? "" : " · 匹配 " + String(visible.length)) + " · 可导入 " + String(selectable.length) : "未安装")), source.exists ? h$8("div", { style: styles.actions }, h$8(Btn, { label: "全选本来源(" + String(selectable.length) + ")", ariaLabel: "全选本来源 " + String(source.label), variant: "small", @@ -2057,13 +2057,13 @@ window.__ModuleLoader__.load({ onClick: function() { chooseMany(visible, true); } - }), h$9(Btn, { + }), h$8(Btn, { label: open ? "收起" : "展开", variant: "small", onClick: function() { toggleSource(source.id); } - })) : null), h$9("span", { style: styles.mono }, String(source.root)), !source.exists || !open ? null : visible.length === 0 ? h$9("p", { style: styles.hint }, needle === "" ? "这个来源里还没有技能。" : "没有匹配「" + s.search + "」的技能。") : h$9("div", { style: { + })) : null), h$8("span", { style: styles.mono }, String(source.root)), !source.exists || !open ? null : visible.length === 0 ? h$8("p", { style: styles.hint }, needle === "" ? "这个来源里还没有技能。" : "没有匹配「" + s.search + "」的技能。") : h$8("div", { style: { display: "flex", flexDirection: "column", gap: "2px", @@ -2072,10 +2072,10 @@ window.__ModuleLoader__.load({ } }, visible.map(function(entry) { var skill = entry.skill; var has = importedYet(skill); - return h$9("label", { + return h$8("label", { key: String(skill.folder), style: styles.checkboxRow - }, h$9("input", { + }, h$8("input", { type: "checkbox", checked: has || isChosen(entry), disabled: has || s.busy !== "", @@ -2083,54 +2083,54 @@ window.__ModuleLoader__.load({ onChange: function(event) { chooseMany([entry], event.target.checked === true); } - }), h$9("span", { style: { + }), h$8("span", { style: { minWidth: 0, flex: "1 1 auto" - } }, h$9("span", { style: styles.rowTitle }, String(skill.name)), describe(skill) === "" ? null : h$9("span", { style: Object.assign({}, styles.hint, styles.clamp1) }, describe(skill))), has ? h$9(Pill$1, { + } }, h$8("span", { style: styles.rowTitle }, String(skill.name)), describe(skill) === "" ? null : h$8("span", { style: Object.assign({}, styles.hint, styles.clamp1) }, describe(skill))), has ? h$8(Pill$1, { label: "DSH", value: "已导入", tone: "muted" }) : null); }))); }); - return h$9(Section, { + return h$8(Section, { title: "从其他软件导入", hint: "把其他软件技能目录里的技能复制一份到 DSH,原目录不动;同名技能不能重复导入。", - aside: h$9("div", { style: styles.actions }, h$9(Btn, { + aside: h$8("div", { style: styles.actions }, h$8(Btn, { label: "刷新", variant: "small", onClick: load - }), h$9(Btn, { + }), h$8(Btn, { label: "收起", variant: "small", onClick: closePanel })) - }, s.status === "loading" ? h$9("p", { style: styles.hint }, "正在读取来源…") : others.length === 0 ? h$9("p", { style: styles.hint }, "没有检测到其他软件的技能目录。") : h$9("div", { style: styles.root }, h$9("div", { style: styles.pills }, h$9(Pill$1, { + }, s.status === "loading" ? h$8("p", { style: styles.hint }, "正在读取来源…") : others.length === 0 ? h$8("p", { style: styles.hint }, "没有检测到其他软件的技能目录。") : h$8("div", { style: styles.root }, h$8("div", { style: styles.pills }, h$8(Pill$1, { label: "来源", value: String(others.length), tone: "muted" - }), h$9(Pill$1, { + }), h$8(Pill$1, { label: "可导入", value: String(candidates.length - alreadyCount), tone: "muted" - }), s.search === "" ? null : h$9(Pill$1, { + }), s.search === "" ? null : h$8(Pill$1, { label: "匹配", value: String(matches.length), tone: matches.length === 0 ? "muted" : "ok" - }), h$9(Pill$1, { + }), h$8(Pill$1, { label: "已选", value: String(chosenEntries.length), tone: chosenEntries.length === 0 ? "muted" : "ok" - }), alreadyCount === 0 ? null : h$9(Pill$1, { + }), alreadyCount === 0 ? null : h$8(Pill$1, { label: "已在 DSH", value: String(alreadyCount), tone: "muted" - })), h$9("div", { style: { + })), h$8("div", { style: { display: "flex", gap: "8px", alignItems: "center", flexWrap: "wrap" - } }, h$9("input", { + } }, h$8("input", { type: "search", style: Object.assign({}, styles.input, { flex: "1 1 220px", @@ -2142,13 +2142,13 @@ window.__ModuleLoader__.load({ onChange: function(event) { patch({ search: event.target.value }); } - }), s.search === "" ? null : h$9(Btn, { + }), s.search === "" ? null : h$8(Btn, { label: "清空搜索", variant: "small", onClick: function() { patch({ search: "" }); } - })), h$9("div", { style: Object.assign({}, styles.actions, { flexWrap: "wrap" }) }, h$9(Btn, { + })), h$8("div", { style: Object.assign({}, styles.actions, { flexWrap: "wrap" }) }, h$8(Btn, { label: "全选匹配可导入(" + String(importable.length) + ")", ariaLabel: "全选匹配可导入", variant: "small", @@ -2156,7 +2156,7 @@ window.__ModuleLoader__.load({ onClick: function() { chooseMany(importable, true); } - }), h$9(Btn, { + }), h$8(Btn, { label: "全选全部(" + String(candidates.length - alreadyCount) + ")", ariaLabel: "全选全部", variant: "small", @@ -2166,7 +2166,7 @@ window.__ModuleLoader__.load({ return !importedYet(entry.skill); }), true); } - }), h$9(Btn, { + }), h$8(Btn, { label: "清空已选", ariaLabel: "清空已选", variant: "small", @@ -2174,20 +2174,20 @@ window.__ModuleLoader__.load({ onClick: function() { patch({ selection: [] }); } - }), h$9(Btn, { + }), h$8(Btn, { variant: "primary", label: s.busy === "batch" ? "导入中…" : "导入所选(" + String(chosenEntries.length) + ")", ariaLabel: "导入所选", disabled: s.busy !== "" || chosenEntries.length === 0, onClick: importSelected - })), s.progress === null ? null : h$9("p", { style: styles.hint }, "正在导入:" + String(s.progress.done) + " / " + String(s.progress.total)), h$9("div", { style: { + })), s.progress === null ? null : h$8("p", { style: styles.hint }, "正在导入:" + String(s.progress.done) + " / " + String(s.progress.total)), h$8("div", { style: { display: "flex", flexDirection: "column", gap: "10px" - } }, blocks)), s.notice === null ? null : h$9(Banner, { tone: s.notice.tone }, s.notice.text)); + } }, blocks)), s.notice === null ? null : h$8(Banner, { tone: s.notice.tone }, s.notice.text)); } // src-client/SettingsCard.tsx - const h$8 = react.createElement; + const h$7 = react.createElement; function findCheck(source, id) { if (source === null || source === void 0 || !Array.isArray(source.checks)) return void 0; for (var index = 0; index < source.checks.length; index += 1) if (source.checks[index] !== null && typeof source.checks[index] === "object" && source.checks[index].id === id) return source.checks[index]; @@ -2935,13 +2935,13 @@ window.__ModuleLoader__.load({ return probeMcp(); }); } - if (error !== null && snapshot === null) return h$8("div", { style: styles.root }, h$8(Banner, { tone: "bad" }, error), h$8("div", { style: styles.actions }, h$8(Btn, { + if (error !== null && snapshot === null) return h$7("div", { style: styles.root }, h$7(Banner, { tone: "bad" }, error), h$7("div", { style: styles.actions }, h$7(Btn, { label: "重新加载", onClick: function() { load(false); } }))); - if (snapshot === null || draft === null) return h$8("div", { style: styles.root }, h$8("p", { style: styles.hint }, "正在读取云端记忆插件状态…")); + if (snapshot === null || draft === null) return h$7("div", { style: styles.root }, h$7("p", { style: styles.hint }, "正在读取云端记忆插件状态…")); var reporter = snapshot.reporter === void 0 || snapshot.reporter === null ? {} : snapshot.reporter; var tokens = snapshot.tokens === void 0 || snapshot.tokens === null ? { activity: {}, @@ -2980,10 +2980,10 @@ window.__ModuleLoader__.load({ tone: "bad", text: "不可达" }; - var header = h$8("div", { + var header = h$7("div", { style: styles.section, key: "header" - }, h$8("div", { style: styles.sectionHead }, h$8("h4", { style: styles.sectionTitle }, h$8("span", { style: { + }, h$7("div", { style: styles.sectionHead }, h$7("h4", { style: styles.sectionTitle }, h$7("span", { style: { display: "inline-block", width: "9px", height: "9px", @@ -2991,32 +2991,32 @@ window.__ModuleLoader__.load({ background: "linear-gradient(135deg, #6366f1, #8b5cf6)", marginRight: "8px", verticalAlign: "1px" - } }), "云端记忆 · v" + String(caps.version === void 0 ? "—" : caps.version)), h$8("div", { style: styles.pills }, h$8(Pill$1, { + } }), "云端记忆 · v" + String(caps.version === void 0 ? "—" : caps.version)), h$7("div", { style: styles.pills }, h$7(Pill$1, { label: "连接", value: connectivity.text, tone: connectivity.tone - }), h$8(Pill$1, { + }), h$7(Pill$1, { label: "最后检查", value: checkedAt, tone: "muted" - }), dirty ? h$8(Pill$1, { + }), dirty ? h$7(Pill$1, { label: "草稿", value: "未保存", tone: "warn" - }) : null)), h$8("div", { style: styles.pills }, h$8(Pill$1, { + }) : null)), h$7("div", { style: styles.pills }, h$7(Pill$1, { label: "已上报", value: reporter.recorded === void 0 ? 0 : reporter.recorded, tone: "ok" - }), h$8(Pill$1, { + }), h$7(Pill$1, { label: "待重试", value: reporter.queued === void 0 ? 0 : reporter.queued, tone: reporter.queued > 0 ? "warn" : "muted" - }), h$8(Pill$1, { + }), h$7(Pill$1, { label: "失败", value: reporter.failed === void 0 ? 0 : reporter.failed, tone: reporter.failed > 0 ? "bad" : "muted" }))); - var tabBar = h$8(Switch, { + var tabBar = h$7(Switch, { key: "tabs", ariaLabel: "云端记忆管理页签", value: tab, @@ -3036,7 +3036,7 @@ window.__ModuleLoader__.load({ } ] }); - var noticeBox = notice === null ? null : h$8(Banner, { + var noticeBox = notice === null ? null : h$7(Banner, { tone: notice.tone, role: "status", key: "notice" @@ -3044,13 +3044,13 @@ window.__ModuleLoader__.load({ var connectionTab = null; if (tab === "connection") { var changedOrigin = draft.baseUrlConfigured && draft.baseUrlOrigin !== "" && String(draft.baseUrl) !== "" && String(draft.baseUrl).indexOf(draft.baseUrlOrigin) !== 0; - connectionTab = h$8("div", { + connectionTab = h$7("div", { style: styles.root, key: "connection" - }, h$8(Section, { + }, h$7(Section, { title: "身份验证", hint: "两种方式最终更新同一组配置;切换不会清除任何一种方式已保存的凭据,也不会自动发起请求。", - aside: h$8(Switch, { + aside: h$7(Switch, { ariaLabel: "身份验证方式", value: identity, onChange: switchIdentity, @@ -3062,7 +3062,7 @@ window.__ModuleLoader__.load({ label: "手动令牌" }] }) - }, identity === "account" ? h$8("div", { style: styles.nested }, h$8("p", { style: styles.hint }, "用云端面板的普通用户账号登录,插件会用一次性会话换取活动与记忆令牌并写入本机。密码只在这一次请求里使用:不保存、不写日志、不回显。"), h$8("div", { style: styles.grid }, h$8(Field, { + }, identity === "account" ? h$7("div", { style: styles.nested }, h$7("p", { style: styles.hint }, "用云端面板的普通用户账号登录,插件会用一次性会话换取活动与记忆令牌并写入本机。密码只在这一次请求里使用:不保存、不写日志、不回显。"), h$7("div", { style: styles.grid }, h$7(Field, { label: "用户名", value: loginDraft.username, placeholder: "云端面板的账号", @@ -3071,7 +3071,7 @@ window.__ModuleLoader__.load({ return Object.assign({}, previous, { username: value }); }); } - }), h$8(Field, { + }), h$7(Field, { label: "密码", type: "password", value: loginDraft.password, @@ -3082,12 +3082,12 @@ window.__ModuleLoader__.load({ return Object.assign({}, previous, { password: value }); }); } - })), h$8("div", { style: styles.actions }, h$8(Btn, { + })), h$7("div", { style: styles.actions }, h$7(Btn, { variant: "primary", label: busy === "login" ? "登录中…" : "登录并获取令牌", disabled: busy !== "", onClick: login - }), loginResult === null ? null : h$8("span", { style: styles.hint }, "当前账号:" + String(loginResult.user !== void 0 && loginResult.user !== null && loginResult.user.username !== void 0 ? loginResult.user.username : "未知") + (loginResult.warning === void 0 ? "" : "(" + String(loginResult.warning) + ")")))) : h$8("div", { style: styles.nested }, h$8("p", { style: styles.hint }, "三个令牌各有独立权限:activity:write 只用于上报,memory:write 同时允许检索与写入,summary:write 用于自动摘要(可选)。空值表示不修改;清除是独立动作。"), h$8("div", { style: styles.grid }, h$8(Field, { + }), loginResult === null ? null : h$7("span", { style: styles.hint }, "当前账号:" + String(loginResult.user !== void 0 && loginResult.user !== null && loginResult.user.username !== void 0 ? loginResult.user.username : "未知") + (loginResult.warning === void 0 ? "" : "(" + String(loginResult.warning) + ")")))) : h$7("div", { style: styles.nested }, h$7("p", { style: styles.hint }, "三个令牌各有独立权限:activity:write 只用于上报,memory:write 同时允许检索与写入,summary:write 用于自动摘要(可选)。空值表示不修改;清除是独立动作。"), h$7("div", { style: styles.grid }, h$7(Field, { label: "活动上报令牌(activity:write)", type: "password", value: tokenDraft.activity, @@ -3096,7 +3096,7 @@ window.__ModuleLoader__.load({ onChange: function(value) { patchTokens({ activity: value }); } - }), h$8(Field, { + }), h$7(Field, { label: "记忆读写令牌(memory:write)", type: "password", value: tokenDraft.memory, @@ -3105,7 +3105,7 @@ window.__ModuleLoader__.load({ onChange: function(value) { patchTokens({ memory: value }); } - }), h$8(Field, { + }), h$7(Field, { label: "摘要令牌(summary:write,可选)", type: "password", value: tokenDraft.summary, @@ -3114,31 +3114,31 @@ window.__ModuleLoader__.load({ onChange: function(value) { patchTokens({ summary: value }); } - })), h$8("div", { style: styles.actions }, h$8(Btn, { + })), h$7("div", { style: styles.actions }, h$7(Btn, { label: "清除上报令牌", variant: "small", disabled: activityToken.configured !== true || busy !== "", onClick: function() { clearToken("activity"); } - }), h$8(Btn, { + }), h$7(Btn, { label: "清除记忆令牌", variant: "small", disabled: memoryToken.configured !== true || busy !== "", onClick: function() { clearToken("memory"); } - }), h$8(Btn, { + }), h$7(Btn, { label: "清除摘要令牌", variant: "small", disabled: summaryToken.configured !== true || busy !== "", onClick: function() { clearToken("summary"); } - })))), h$8(Section, { + })))), h$7(Section, { title: "服务地址", hint: "账号登录会把密码发到该地址:仅接受 HTTPS(本机回环除外)。不同 origin 不会复用旧令牌。" - }, h$8(Field, { + }, h$7(Field, { label: "服务地址(baseUrl)", value: draft.baseUrl, placeholder: "https://<你的域名>/api/longmemory", @@ -3146,57 +3146,57 @@ window.__ModuleLoader__.load({ onChange: function(value) { patchDraft({ baseUrl: value }); } - }), advanced ? h$8("div", { style: styles.nested }, h$8("div", { style: styles.grid }, h$8(Field, { + }), advanced ? h$7("div", { style: styles.nested }, h$7("div", { style: styles.grid }, h$7(Field, { label: "客户端标识(client_id)", value: draft.clientId, onChange: function(value) { patchDraft({ clientId: value }); } - }), h$8(Field, { + }), h$7(Field, { label: "请求超时(毫秒)", type: "number", value: draft.requestTimeoutMs, onChange: function(value) { patchDraft({ requestTimeoutMs: value }); } - })), h$8("div", { style: styles.checkboxRow }, h$8("input", { + })), h$7("div", { style: styles.checkboxRow }, h$7("input", { type: "checkbox", checked: draft.enabled, id: "dsh-brain-enabled", onChange: function(event) { patchDraft({ enabled: event.target.checked }); } - }), h$8("label", { + }), h$7("label", { htmlFor: "dsh-brain-enabled", style: styles.label - }, "启用每轮活动上报(只上报时间戳、会话 id 与状态,不上传对话内容)")), h$8("div", { style: styles.checkboxRow }, h$8("input", { + }, "启用每轮活动上报(只上报时间戳、会话 id 与状态,不上传对话内容)")), h$7("div", { style: styles.checkboxRow }, h$7("input", { type: "checkbox", checked: draft.summaryEnabled, id: "dsh-brain-summary", onChange: function(event) { patchDraft({ summaryEnabled: event.target.checked }); } - }), h$8("label", { + }), h$7("label", { htmlFor: "dsh-brain-summary", style: styles.label - }, "启用自动摘要(会把该轮对话文本上传为待确认提案;与上面的元数据上报是两件事)")), h$8("div", { style: styles.checkboxRow }, h$8("input", { + }, "启用自动摘要(会把该轮对话文本上传为待确认提案;与上面的元数据上报是两件事)")), h$7("div", { style: styles.checkboxRow }, h$7("input", { type: "checkbox", checked: draft.activityEnabled, id: "dsh-brain-activity", onChange: function(event) { patchDraft({ activityEnabled: event.target.checked }); } - }), h$8("label", { + }), h$7("label", { htmlFor: "dsh-brain-activity", style: styles.label - }, "启用活动上报(细粒度开关;未显式设置时跟随总开关)"))) : h$8("div", { style: styles.actions }, h$8(Btn, { + }, "启用活动上报(细粒度开关;未显式设置时跟随总开关)"))) : h$7("div", { style: styles.actions }, h$7(Btn, { label: "高级设置", variant: "small", onClick: toggleAdvanced - }))), h$8(Section, { + }))), h$7(Section, { title: "记忆配置", hint: "只影响记忆工具:开关未显式设置时跟随总开关,检索上限只限制单次返回条数。" - }, h$8("div", { style: styles.grid }, h$8(Field, { + }, h$7("div", { style: styles.grid }, h$7(Field, { label: "单次搜索返回上限(defaultK)", type: "number", value: draft.defaultK, @@ -3204,20 +3204,20 @@ window.__ModuleLoader__.load({ onChange: function(value) { patchDraft({ defaultK: value }); } - })), h$8("div", { style: styles.checkboxRow }, h$8("input", { + })), h$7("div", { style: styles.checkboxRow }, h$7("input", { type: "checkbox", checked: draft.memoryEnabled, id: "dsh-brain-memory-enabled", onChange: function(event) { patchDraft({ memoryEnabled: event.target.checked }); } - }), h$8("label", { + }), h$7("label", { htmlFor: "dsh-brain-memory-enabled", style: styles.label - }, "启用记忆工具(memory_search / memory_read / memory_add)"))), features.skillsSync === false ? h$8("div", null) : h$8("div", null, h$8(Section, { + }, "启用记忆工具(memory_search / memory_read / memory_add)"))), features.skillsSync === false ? h$7("div", null) : h$7("div", null, h$7(Section, { title: "Skill 同步", hint: "同步由后台定时执行,这里只保存开关与目录;目录留空使用默认位置。" - }, h$8(Field, { + }, h$7(Field, { label: "技能目录(skillsDir,可选)", value: draft.skillsDir, placeholder: "默认 $DSH_HOME/skills", @@ -3225,52 +3225,52 @@ window.__ModuleLoader__.load({ onChange: function(value) { patchDraft({ skillsDir: value }); } - }), h$8("div", { style: styles.checkboxRow }, h$8("input", { + }), h$7("div", { style: styles.checkboxRow }, h$7("input", { type: "checkbox", checked: draft.skillsSyncEnabled, id: "dsh-brain-skills-sync", onChange: function(event) { patchDraft({ skillsSyncEnabled: event.target.checked }); } - }), h$8("label", { + }), h$7("label", { htmlFor: "dsh-brain-skills-sync", style: styles.label - }, "启用云端技能同步(下载云端技能库、上传本机新技能)")))), h$8(Section, { + }, "启用云端技能同步(下载云端技能库、上传本机新技能)")))), h$7(Section, { title: "连接与权限检查", - aside: h$8("div", { style: styles.actions }, h$8(Btn, { + aside: h$7("div", { style: styles.actions }, h$7(Btn, { variant: "primary", label: busy === "save" ? "保存中…" : "保存", disabled: busy !== "", onClick: save - }), h$8(Btn, { + }), h$7(Btn, { label: busy === "test" ? "测试中…" : "测试连接", disabled: busy !== "", onClick: test - }), h$8(Btn, { + }), h$7(Btn, { label: "重试上报队列", disabled: busy !== "" || reporter.queued === void 0 || reporter.queued === 0, onClick: flush })) - }, checkSource === null ? h$8("p", { style: styles.hint }, "还没有检查记录。点「测试连接」做一次只读检查:网络 → 活动权限 → 记忆权限 → 摘要权限。") : h$8("div", { style: styles.pills }, (checkSource.checks || []).map(function(check) { - return h$8(Pill$1, { + }, checkSource === null ? h$7("p", { style: styles.hint }, "还没有检查记录。点「测试连接」做一次只读检查:网络 → 活动权限 → 记忆权限 → 摘要权限。") : h$7("div", { style: styles.pills }, (checkSource.checks || []).map(function(check) { + return h$7(Pill$1, { key: String(check.id), label: String(check.label === void 0 ? check.id : check.label), value: CHECK_LABELS[check.state] === void 0 ? String(check.state) : CHECK_LABELS[check.state], tone: CHECK_TONES[check.state] === void 0 ? "muted" : CHECK_TONES[check.state] }); - })), checkSource === null ? null : h$8("div", { style: { + })), checkSource === null ? null : h$7("div", { style: { display: "flex", flexDirection: "column", gap: "6px" } }, (checkSource.checks || []).map(function(check) { - return h$8("div", { + return h$7("div", { key: "detail-" + String(check.id), style: Object.assign({}, styles.banner, styles[CHECK_TONES[check.state]] === void 0 ? styles.muted : styles[CHECK_TONES[check.state]]) }, String(check.label === void 0 ? check.id : check.label) + ":" + String(check.message)); - })), h$8("p", { style: styles.hint }, "鉴权通过只代表令牌有效,不代表已经成功写入一条上报;两者在下面分开显示。")), h$8(Section, { title: "最近上报" }, recent.length === 0 ? h$8("p", { style: styles.hint }, "还没有记录。发一条消息让它跑完一轮,这里就会出现一条。") : h$8("table", { style: styles.table }, h$8("thead", null, h$8("tr", null, h$8("th", { style: styles.th }, "时间"), h$8("th", { style: styles.th }, "结果"), h$8("th", { style: styles.th }, "turn_id"))), h$8("tbody", null, recent.map(function(row, index) { + })), h$7("p", { style: styles.hint }, "鉴权通过只代表令牌有效,不代表已经成功写入一条上报;两者在下面分开显示。")), h$7(Section, { title: "最近上报" }, recent.length === 0 ? h$7("p", { style: styles.hint }, "还没有记录。发一条消息让它跑完一轮,这里就会出现一条。") : h$7("table", { style: styles.table }, h$7("thead", null, h$7("tr", null, h$7("th", { style: styles.th }, "时间"), h$7("th", { style: styles.th }, "结果"), h$7("th", { style: styles.th }, "turn_id"))), h$7("tbody", null, recent.map(function(row, index) { var outcome = String(row.outcome === void 0 ? "" : row.outcome); - return h$8("tr", { key: String(row.turnId) + ":" + String(index) }, h$8("td", { style: styles.td }, formatTime(row.at)), h$8("td", { style: styles.td }, h$8("span", { style: Object.assign({}, styles.pill, styles[OUTCOME_TONES[outcome]] === void 0 ? styles.muted : styles[OUTCOME_TONES[outcome]]) }, OUTCOME_LABELS[outcome] === void 0 ? outcome : OUTCOME_LABELS[outcome])), h$8("td", { style: Object.assign({}, styles.td, styles.mono) }, String(row.turnId === void 0 ? "" : row.turnId))); - }))), reporter.lastError === void 0 ? null : h$8("p", { style: styles.hint }, "最近一次错误:" + String(reporter.lastError))), h$8("p", { style: styles.hint }, "配置保存在 " + String(snapshot.settingsPath === void 0 ? "本机配置文件" : snapshot.settingsPath) + "。页面地址 /dsh-brain 仍然可用。")); + return h$7("tr", { key: String(row.turnId) + ":" + String(index) }, h$7("td", { style: styles.td }, formatTime(row.at)), h$7("td", { style: styles.td }, h$7("span", { style: Object.assign({}, styles.pill, styles[OUTCOME_TONES[outcome]] === void 0 ? styles.muted : styles[OUTCOME_TONES[outcome]]) }, OUTCOME_LABELS[outcome] === void 0 ? outcome : OUTCOME_LABELS[outcome])), h$7("td", { style: Object.assign({}, styles.td, styles.mono) }, String(row.turnId === void 0 ? "" : row.turnId))); + }))), reporter.lastError === void 0 ? null : h$7("p", { style: styles.hint }, "最近一次错误:" + String(reporter.lastError))), h$7("p", { style: styles.hint }, "配置保存在 " + String(snapshot.settingsPath === void 0 ? "本机配置文件" : snapshot.settingsPath) + "。页面地址 /dsh-brain 仍然可用。")); } var skillsTab = null; if (tab === "skills") { @@ -3291,31 +3291,31 @@ window.__ModuleLoader__.load({ var detailBox = null; if (skills.detail !== null) { var detail = skills.detail.data; - detailBox = h$8("div", { style: styles.row }, h$8("div", { style: styles.rowHead }, h$8("span", { style: styles.rowTitle }, "详情:" + String(skills.detail.folder)), h$8(Btn, { + detailBox = h$7("div", { style: styles.row }, h$7("div", { style: styles.rowHead }, h$7("span", { style: styles.rowTitle }, "详情:" + String(skills.detail.folder)), h$7(Btn, { label: "关闭", variant: "small", onClick: function() { patchSkills({ detail: null }); } - })), detail === null ? h$8("p", { style: styles.hint }, skills.detail.error === null ? "正在读取…" : String(skills.detail.error)) : h$8("div", { style: styles.nested }, h$8("div", { style: styles.grid }, h$8(Field, { + })), detail === null ? h$7("p", { style: styles.hint }, skills.detail.error === null ? "正在读取…" : String(skills.detail.error)) : h$7("div", { style: styles.nested }, h$7("div", { style: styles.grid }, h$7(Field, { label: "目录", value: String(detail.dir), onChange: function() {} - }), h$8(Field, { + }), h$7(Field, { label: "SKILL.md 哈希", value: String(detail.skill !== void 0 ? detail.skill.skillSha256 : ""), onChange: function() {} - })), h$8("p", { style: styles.hint }, "文件:" + String(Array.isArray(detail.files) ? detail.files.length : 0) + " 个,共 " + formatBytes(detail.totalBytes) + (detail.truncated ? "(SKILL.md 过长,已截断显示)" : "")), h$8("pre", { style: styles.code }, String(detail.skillMd === void 0 ? "" : detail.skillMd)), h$8("p", { style: styles.hint }, "文件清单:" + (Array.isArray(detail.files) ? detail.files.map(function(file) { + })), h$7("p", { style: styles.hint }, "文件:" + String(Array.isArray(detail.files) ? detail.files.length : 0) + " 个,共 " + formatBytes(detail.totalBytes) + (detail.truncated ? "(SKILL.md 过长,已截断显示)" : "")), h$7("pre", { style: styles.code }, String(detail.skillMd === void 0 ? "" : detail.skillMd)), h$7("p", { style: styles.hint }, "文件清单:" + (Array.isArray(detail.files) ? detail.files.map(function(file) { return String(file.path) + (file.script ? "(脚本)" : ""); }).join("、") : "")))); } var uninstallBox = null; - if (skills.uninstall !== null) uninstallBox = h$8("div", { style: Object.assign({}, styles.row, styles.warn) }, h$8("div", { style: styles.rowHead }, h$8("span", { style: styles.rowTitle }, "卸载确认:" + String(skills.uninstall.folder))), h$8("p", { style: styles.hint }, "将实际删除:" + String(skills.uninstall.dir) + ";影响:" + String(skills.uninstall.files) + " 个文件 / " + formatBytes(skills.uninstall.bytes) + (Array.isArray(skills.uninstall.scripts) && skills.uninstall.scripts.length > 0 ? ";含脚本:" + skills.uninstall.scripts.join("、") : "")), h$8("p", { style: styles.hint }, String(skills.uninstall.note)), h$8("div", { style: styles.actions }, h$8(Btn, { + if (skills.uninstall !== null) uninstallBox = h$7("div", { style: Object.assign({}, styles.row, styles.warn) }, h$7("div", { style: styles.rowHead }, h$7("span", { style: styles.rowTitle }, "卸载确认:" + String(skills.uninstall.folder))), h$7("p", { style: styles.hint }, "将实际删除:" + String(skills.uninstall.dir) + ";影响:" + String(skills.uninstall.files) + " 个文件 / " + formatBytes(skills.uninstall.bytes) + (Array.isArray(skills.uninstall.scripts) && skills.uninstall.scripts.length > 0 ? ";含脚本:" + skills.uninstall.scripts.join("、") : "")), h$7("p", { style: styles.hint }, String(skills.uninstall.note)), h$7("div", { style: styles.actions }, h$7(Btn, { variant: "danger", label: tree.busy === "uninstall" ? "删除中…" : "确认删除(不可恢复)", disabled: tree.busy !== "", onClick: confirmUninstall - }), h$8(Btn, { + }), h$7(Btn, { label: "取消", disabled: tree.busy !== "", onClick: function() { @@ -3325,17 +3325,17 @@ window.__ModuleLoader__.load({ var planBox = null; if (skills.plan !== null) { var candidates = Array.isArray(skills.plan.candidates) ? skills.plan.candidates : []; - planBox = h$8("div", { style: styles.row }, h$8("div", { style: styles.rowHead }, h$8("span", { style: styles.rowTitle }, "安装预览:" + String(skills.plan.url))), h$8("p", { style: styles.hint }, "计划 " + String(skills.plan.planId) + " 有效到 " + formatTime(skills.plan.expiresAt) + "。默认不勾选冲突项;只安装勾选的技能,来源中的安装脚本不会执行。"), h$8("div", { style: { + planBox = h$7("div", { style: styles.row }, h$7("div", { style: styles.rowHead }, h$7("span", { style: styles.rowTitle }, "安装预览:" + String(skills.plan.url))), h$7("p", { style: styles.hint }, "计划 " + String(skills.plan.planId) + " 有效到 " + formatTime(skills.plan.expiresAt) + "。默认不勾选冲突项;只安装勾选的技能,来源中的安装脚本不会执行。"), h$7("div", { style: { display: "flex", flexDirection: "column", gap: "6px" } }, candidates.map(function(candidate) { var selected = skills.selection.indexOf(candidate.folder) >= 0; var blocked = candidate.conflict === true || candidate.problem !== void 0; - return h$8("label", { + return h$7("label", { key: String(candidate.id), style: styles.checkboxRow - }, h$8("input", { + }, h$7("input", { type: "checkbox", checked: selected, disabled: blocked, @@ -3346,13 +3346,13 @@ window.__ModuleLoader__.load({ if (!event.target.checked && at >= 0) next.splice(at, 1); patchSkills({ selection: next }); } - }), h$8("span", { style: { minWidth: 0 } }, h$8("span", { style: { fontWeight: 600 } }, String(candidate.name)), h$8("span", { style: styles.hint }, " · " + String(candidate.folder) + " · " + String(candidate.files) + " 个文件 · " + formatBytes(candidate.bytes) + (candidate.conflict === true ? " · 已存在(" + String(candidate.conflictLocation === "holding" ? "已停用目录" : "技能目录") + "),不覆盖" : "") + (candidate.problem === void 0 ? "" : " · " + String(candidate.problem)) + (Array.isArray(candidate.scripts) && candidate.scripts.length > 0 ? " · 含脚本:" + candidate.scripts.join("、") : "")))); - })), h$8("div", { style: styles.actions }, h$8(Btn, { + }), h$7("span", { style: { minWidth: 0 } }, h$7("span", { style: { fontWeight: 600 } }, String(candidate.name)), h$7("span", { style: styles.hint }, " · " + String(candidate.folder) + " · " + String(candidate.files) + " 个文件 · " + formatBytes(candidate.bytes) + (candidate.conflict === true ? " · 已存在(" + String(candidate.conflictLocation === "holding" ? "已停用目录" : "技能目录") + "),不覆盖" : "") + (candidate.problem === void 0 ? "" : " · " + String(candidate.problem)) + (Array.isArray(candidate.scripts) && candidate.scripts.length > 0 ? " · 含脚本:" + candidate.scripts.join("、") : "")))); + })), h$7("div", { style: styles.actions }, h$7(Btn, { variant: "primary", label: tree.busy === "commit" ? "安装中…" : "安装所选(" + String(skills.selection.length) + ")", disabled: tree.busy !== "" || skills.selection.length === 0, onClick: commitInstall - }), h$8(Btn, { + }), h$7(Btn, { label: "放弃计划", variant: "small", disabled: tree.busy !== "", @@ -3400,24 +3400,24 @@ window.__ModuleLoader__.load({ }); setSelection(next); } - assignBox = h$8("div", { style: styles.row }, h$8("div", { style: styles.rowHead }, h$8("span", { style: styles.rowTitle }, "加入分类:" + String(assignGroup === void 0 ? "" : assignGroup.name)), h$8("div", { style: styles.pills }, h$8(Pill$1, { + assignBox = h$7("div", { style: styles.row }, h$7("div", { style: styles.rowHead }, h$7("span", { style: styles.rowTitle }, "加入分类:" + String(assignGroup === void 0 ? "" : assignGroup.name)), h$7("div", { style: styles.pills }, h$7(Pill$1, { label: "可分配", value: String(assignable.length), tone: "muted" - }), h$8(Pill$1, { + }), h$7(Pill$1, { label: "匹配", value: String(filteredAssignable.length), tone: filteredAssignable.length === 0 ? "muted" : "ok" - }), h$8(Pill$1, { + }), h$7(Pill$1, { label: "已选", value: String(selectedCount), tone: selectedCount === 0 ? "muted" : "ok" - }))), h$8("p", { style: styles.hint }, "先搜索再勾选,或直接「全选匹配结果」一次性加入;一个技能只会属于一个分类,取消勾选即回到「未分类」。"), h$8("div", { style: { + }))), h$7("p", { style: styles.hint }, "先搜索再勾选,或直接「全选匹配结果」一次性加入;一个技能只会属于一个分类,取消勾选即回到「未分类」。"), h$7("div", { style: { display: "flex", gap: "8px", alignItems: "center", flexWrap: "wrap" - } }, h$8("input", { + } }, h$7("input", { type: "search", style: Object.assign({}, styles.input, { flex: "1 1 200px", @@ -3430,41 +3430,41 @@ window.__ModuleLoader__.load({ onChange: function(event) { setSelectionFilter(event.target.value); } - }), assignSearch !== "" ? h$8(Btn, { + }), assignSearch !== "" ? h$7(Btn, { label: "清空搜索", variant: "small", onClick: function() { setSelectionFilter(""); } - }) : null), h$8("div", { style: Object.assign({}, styles.actions, { flexWrap: "wrap" }) }, h$8(Btn, { + }) : null), h$7("div", { style: Object.assign({}, styles.actions, { flexWrap: "wrap" }) }, h$7(Btn, { label: "全选匹配结果(" + String(filteredAssignable.length) + ")", variant: "small", disabled: tree.busy !== "" || filteredAssignable.length === 0, onClick: function() { selectMany(filteredAssignable, true); } - }), h$8(Btn, { + }), h$7(Btn, { label: "全选全部(" + String(assignable.length) + ")", variant: "small", disabled: tree.busy !== "" || assignable.length === 0 || selectedCount === assignable.length, onClick: function() { selectMany(assignable, true); } - }), h$8(Btn, { + }), h$7(Btn, { label: "取消勾选匹配项(" + String(matchedSelected) + ")", variant: "small", disabled: tree.busy !== "" || matchedSelected === 0, onClick: function() { selectMany(filteredAssignable, false); } - }), h$8(Btn, { + }), h$7(Btn, { label: "清空已选", variant: "small", disabled: tree.busy !== "" || selectedCount === 0, onClick: function() { setSelection([]); } - })), filteredAssignable.length === 0 ? h$8("p", { style: styles.hint }, assignable.length === 0 ? "当前来源还没有可分配的技能。" : "没有匹配「" + assignSearch + "」的技能。换个关键词,或点「清空搜索」看全部。") : h$8("div", { style: { + })), filteredAssignable.length === 0 ? h$7("p", { style: styles.hint }, assignable.length === 0 ? "当前来源还没有可分配的技能。" : "没有匹配「" + assignSearch + "」的技能。换个关键词,或点「清空搜索」看全部。") : h$7("div", { style: { display: "flex", flexDirection: "column", gap: "4px", @@ -3472,24 +3472,24 @@ window.__ModuleLoader__.load({ overflow: "auto" } }, filteredAssignable.map(function(skill) { var checked = tree.assign.selection.indexOf(skill.folder) >= 0; - return h$8("label", { + return h$7("label", { key: String(skill.folder), style: styles.checkboxRow - }, h$8("input", { + }, h$7("input", { type: "checkbox", checked, onChange: function(event) { selectMany([skill], event.target.checked === true); } - }), h$8("span", { style: { minWidth: 0 } }, String(skill.name) + " ", h$8("span", { style: styles.hint }, "· " + String(skill.folder) + (skill.description ? " · " + String(skill.description) : "")))); - })), h$8("div", { style: styles.actions }, h$8(Btn, { + }), h$7("span", { style: { minWidth: 0 } }, String(skill.name) + " ", h$7("span", { style: styles.hint }, "· " + String(skill.folder) + (skill.description ? " · " + String(skill.description) : "")))); + })), h$7("div", { style: styles.actions }, h$7(Btn, { variant: "primary", label: "保存分类(" + String(selectedCount) + ")", disabled: tree.busy !== "", onClick: function() { saveAssign(); } - }), h$8(Btn, { + }), h$7(Btn, { label: "取消", disabled: tree.busy !== "", onClick: function() { @@ -3499,10 +3499,10 @@ window.__ModuleLoader__.load({ } var renderSkillRow = function(source, skill) { var writable = source.writable === true; - return h$8("div", { + return h$7("div", { key: String(source.id) + ":" + String(skill.folder), style: styles.skillRow - }, h$8("div", { + }, h$7("div", { style: { display: "flex", alignItems: "baseline", @@ -3515,12 +3515,12 @@ window.__ModuleLoader__.load({ onClick: writable ? function() { openDetail(skill.folder); } : void 0 - }, h$8("span", { style: Object.assign({}, styles.rowTitle, { flex: "0 0 auto" }) }, String(skill.name)), skill.description === "" ? null : h$8("span", { style: Object.assign({}, styles.hint, styles.clamp1, { minWidth: 0 }) }, String(skill.description))), h$8("div", { style: { + }, h$7("span", { style: Object.assign({}, styles.rowTitle, { flex: "0 0 auto" }) }, String(skill.name)), skill.description === "" ? null : h$7("span", { style: Object.assign({}, styles.hint, styles.clamp1, { minWidth: 0 }) }, String(skill.description))), h$7("div", { style: { display: "flex", alignItems: "center", gap: "6px", flex: "0 0 auto" - } }, skill.enabledEditable !== true ? h$8("span", { style: styles.hint }, "只读") : null, writable ? h$8(IconBtn, { + } }, skill.enabledEditable !== true ? h$7("span", { style: styles.hint }, "只读") : null, writable ? h$7(IconBtn, { glyph: "🗑", danger: true, ariaLabel: "卸载 " + String(skill.name), @@ -3528,7 +3528,7 @@ window.__ModuleLoader__.load({ onClick: function() { planUninstall(skill.folder); } - }) : null, skill.enabledEditable !== true ? null : h$8(Toggle, { + }) : null, skill.enabledEditable !== true ? null : h$7(Toggle, { checked: skill.enabled === true, disabled: tree.busy !== "", label: "技能 " + String(skill.name) + " 启停", @@ -3544,52 +3544,52 @@ window.__ModuleLoader__.load({ var confirming = tree.confirm === renameKey; var assigning = tree.assign !== null && tree.assign.sourceId === source.id && tree.assign.groupId === group.id; var groupSkills = group.visible === void 0 ? group.skills || [] : group.visible; - return h$8("div", { + return h$7("div", { key: renameKey, style: styles.groupRow - }, h$8("div", { style: styles.rowHead }, h$8("div", { style: { + }, h$7("div", { style: styles.rowHead }, h$7("div", { style: { display: "flex", alignItems: "center", gap: "6px", minWidth: 0, flexWrap: "wrap" - } }, h$8(Btn, { + } }, h$7(Btn, { label: open ? "▾" : "▸", variant: "small", ariaLabel: "展开或收起 " + String(group.name), onClick: function() { patchTree({ openGroups: Object.assign({}, tree.openGroups, { [renameKey]: !open }) }); } - }), h$8("span", { style: styles.folderGlyph }, "📁"), renaming ? h$8("input", { + }), h$7("span", { style: styles.folderGlyph }, "📁"), renaming ? h$7("input", { style: Object.assign({}, styles.input, { width: "160px" }), value: tree.edit.value, autoFocus: true, onChange: function(event) { patchTree({ edit: Object.assign({}, tree.edit, { value: event.target.value }) }); } - }) : h$8("span", { style: styles.rowTitle }, String(group.name)), h$8("span", { style: styles.hint }, String(group.total) + " 项 · " + String(group.enabledCount) + "/" + String(group.total) + " 启用"), group.cardOnly === true ? h$8(Pill$1, { + }) : h$7("span", { style: styles.rowTitle }, String(group.name)), h$7("span", { style: styles.hint }, String(group.total) + " 项 · " + String(group.enabledCount) + "/" + String(group.total) + " 启用"), group.cardOnly === true ? h$7(Pill$1, { label: "开关", value: "仅本卡", tone: "muted" - }) : null), h$8("div", { style: styles.actions }, renaming ? h$8(Btn, { + }) : null), h$7("div", { style: styles.actions }, renaming ? h$7(Btn, { label: "保存", variant: "small", disabled: tree.busy !== "", onClick: saveRename - }) : h$8(IconBtn, { + }) : h$7(IconBtn, { glyph: "+", ariaLabel: "把技能加入 " + String(group.name), disabled: tree.busy !== "" || group.id === "unassigned", onClick: function() { openAssign(source, group); } - }), renaming ? h$8(Btn, { + }), renaming ? h$7(Btn, { label: "取消", variant: "small", onClick: function() { patchTree({ edit: null }); } - }) : h$8(IconBtn, { + }) : h$7(IconBtn, { glyph: "✎", ariaLabel: "重命名 " + String(group.name), disabled: tree.busy !== "" || group.id === "unassigned", @@ -3602,14 +3602,14 @@ window.__ModuleLoader__.load({ value: String(group.name) } }); } - }), confirming ? h$8(Btn, { + }), confirming ? h$7(Btn, { label: "确认删除分类", variant: "danger", disabled: tree.busy !== "", onClick: function() { deleteGroup(source.id, group.id); } - }) : h$8(IconBtn, { + }) : h$7(IconBtn, { glyph: "🗑", danger: true, ariaLabel: "删除分类 " + String(group.name) + "(技能回到未分类)", @@ -3621,45 +3621,45 @@ window.__ModuleLoader__.load({ text: "删除分类只删除分组记录,里面的技能会回到「未分类」,文件不会被删除。再点一次确认。" }); } - }), group.enabledEditable === false ? null : h$8(Toggle, { + }), group.enabledEditable === false ? null : h$7(Toggle, { checked: group.enabled !== false, disabled: tree.busy !== "", label: "分类 " + String(group.name) + " 启停", onChange: function() { toggleGroup(source.id, group.id, group.enabled === false); } - }))), assigning ? h$8("div", { style: styles.nested }, assignBox) : null, open ? h$8("div", { style: styles.nested }, groupSkills.length === 0 ? assigning ? null : h$8("p", { style: styles.hint }, group.id === "unassigned" ? "没有未分类的技能。" : "这个分类还没有技能,点「+」加入。") : groupSkills.map(function(skill) { + }))), assigning ? h$7("div", { style: styles.nested }, assignBox) : null, open ? h$7("div", { style: styles.nested }, groupSkills.length === 0 ? assigning ? null : h$7("p", { style: styles.hint }, group.id === "unassigned" ? "没有未分类的技能。" : "这个分类还没有技能,点「+」加入。") : groupSkills.map(function(skill) { return renderSkillRow(source, skill); })) : null); }; var dshSource = treeSources.find(function(src) { return src.writable === true; }); - skillsTab = h$8("div", { + skillsTab = h$7("div", { style: styles.root, key: "skills" - }, h$8(ImportSection, { onImported: function() { + }, h$7(ImportSection, { onImported: function() { loadTree(); loadSkills(); - } }), h$8(Section, { + } }), h$7(Section, { title: "技能文件夹", hint: "按软件来源分组;展开来源与分类查看技能。" - }, dshSource === void 0 ? null : h$8("div", { style: styles.statsBar }, h$8("span", { style: styles.stat }, h$8("span", { style: styles.statNum }, String(dshSource.total || 0)), h$8("span", { style: styles.hint }, "个技能")), h$8("span", { style: styles.stat }, h$8("span", { style: styles.statNum }, String(dshSource.enabledCount || 0)), h$8("span", { style: styles.hint }, "个已启用")), h$8("span", { style: styles.statLast }, h$8("span", { style: styles.statNum }, String((dshSource.total || 0) - (dshSource.enabledCount || 0))), h$8("span", { style: styles.hint }, "个已停用"))), h$8("div", { style: { + }, dshSource === void 0 ? null : h$7("div", { style: styles.statsBar }, h$7("span", { style: styles.stat }, h$7("span", { style: styles.statNum }, String(dshSource.total || 0)), h$7("span", { style: styles.hint }, "个技能")), h$7("span", { style: styles.stat }, h$7("span", { style: styles.statNum }, String(dshSource.enabledCount || 0)), h$7("span", { style: styles.hint }, "个已启用")), h$7("span", { style: styles.statLast }, h$7("span", { style: styles.statNum }, String((dshSource.total || 0) - (dshSource.enabledCount || 0))), h$7("span", { style: styles.hint }, "个已停用"))), h$7("div", { style: { display: "flex", gap: "8px", alignItems: "flex-end", flexWrap: "wrap" - } }, h$8("div", { style: { + } }, h$7("div", { style: { flex: "1 1 220px", minWidth: 0 - } }, h$8(Field, { + } }, h$7(Field, { label: "搜索", value: skills.search, placeholder: "按名称、目录或描述筛选", onChange: function(value) { patchSkills({ search: value }); } - })), h$8(Btn, { + })), h$7(Btn, { label: tree.status === "loading" ? "刷新中…" : "刷新", variant: "small", disabled: tree.status === "loading", @@ -3667,18 +3667,18 @@ window.__ModuleLoader__.load({ loadTree(); loadSkills(); } - })), tree.error === null ? null : h$8(Banner, { tone: "bad" }, tree.error), tree.status === "loading" && tree.data === null ? h$8("p", { style: styles.hint }, "正在读取技能来源…") : null, tree.status === "ready" && treeSources.length === 0 ? h$8("p", { style: styles.hint }, "没有探测到任何技能来源。") : null, dshSource === void 0 ? null : h$8("div", { style: { + })), tree.error === null ? null : h$7(Banner, { tone: "bad" }, tree.error), tree.status === "loading" && tree.data === null ? h$7("p", { style: styles.hint }, "正在读取技能来源…") : null, tree.status === "ready" && treeSources.length === 0 ? h$7("p", { style: styles.hint }, "没有探测到任何技能来源。") : null, dshSource === void 0 ? null : h$7("div", { style: { display: "flex", flexDirection: "column", gap: "2px" } }, visibleGroupsOf(dshSource).map(function(group) { return renderGroup(dshSource, group); - }), tree.edit !== null && tree.edit.kind === "create" && tree.edit.sourceId === dshSource.id ? h$8("div", { style: Object.assign({}, styles.row, { + }), tree.edit !== null && tree.edit.kind === "create" && tree.edit.sourceId === dshSource.id ? h$7("div", { style: Object.assign({}, styles.row, { flexDirection: "row", alignItems: "center", flexWrap: "wrap", marginTop: "6px" - }) }, h$8("input", { + }) }, h$7("input", { style: Object.assign({}, styles.input, { width: "180px" }), placeholder: "分类名称,例如 QQ-Skill", value: tree.edit.value, @@ -3686,17 +3686,17 @@ window.__ModuleLoader__.load({ onChange: function(event) { patchTree({ edit: Object.assign({}, tree.edit, { value: event.target.value }) }); } - }), h$8(Btn, { + }), h$7(Btn, { label: "创建分类", variant: "primary", disabled: tree.busy !== "", onClick: createGroup - }), h$8(Btn, { + }), h$7(Btn, { label: "取消", onClick: function() { patchTree({ edit: null }); } - })) : h$8("div", { style: { marginTop: "6px" } }, h$8(Btn, { + })) : h$7("div", { style: { marginTop: "6px" } }, h$7(Btn, { label: "+ 新建分类", variant: "small", disabled: tree.busy !== "", @@ -3707,28 +3707,28 @@ window.__ModuleLoader__.load({ value: "" } }); } - }))), tree.data !== null && tree.data.note !== void 0 ? h$8("p", { style: styles.hint }, String(tree.data.note)) : null), detailBox, uninstallBox, h$8(Section, { + }))), tree.data !== null && tree.data.note !== void 0 ? h$7("p", { style: styles.hint }, String(tree.data.note)) : null), detailBox, uninstallBox, h$7(Section, { title: "从 Git 仓库安装", hint: "先克隆到隔离暂存目录并列出候选技能,确认后才写入 DSH 技能目录;不执行仓库里的任何脚本,符号链接不会跟随。仓库地址只接受 https:// 或 file://。" - }, h$8("div", { style: styles.grid }, h$8(Field, { + }, h$7("div", { style: styles.grid }, h$7(Field, { label: "仓库地址", value: skills.installUrl, placeholder: "https://github.com//.git", onChange: function(value) { patchSkills({ installUrl: value }); } - })), h$8("div", { style: styles.actions }, h$8(Btn, { + })), h$7("div", { style: styles.actions }, h$7(Btn, { variant: "primary", label: skills.busy === "plan" ? "拉取中…" : "拉取并预览", disabled: skills.busy !== "", onClick: prepareInstall - })), planBox), h$8(MarketSection, { + })), planBox), h$7(MarketSection, { capabilities: caps, onInstalled: function() { loadTree(); loadSkills(); } - }), h$8(SyncResolveSection, { onResolved: function() { + }), h$7(SyncResolveSection, { onResolved: function() { loadSkills(); } })); } @@ -3783,49 +3783,49 @@ window.__ModuleLoader__.load({ return mcpChosen.indexOf(item.key) >= 0; }).length; var bridgeBox = null; - if (mcp.status === "missing") bridgeBox = h$8(Banner, { tone: "warn" }, "MCP 管理当前不可用:没有探测到宿主 dsh-mcp-connector 的公开接口(" + MCP_BRIDGE + ")。" + (mcp.error === null ? "" : "原因:" + String(mcp.error)) + "。自定义 MCP Server 的权威位置仍是「设置 → 插件配置 → MCP 服务器配置」,本卡不会修改它的托管配置。"); - mcpTab = h$8("div", { + if (mcp.status === "missing") bridgeBox = h$7(Banner, { tone: "warn" }, "MCP 管理当前不可用:没有探测到宿主 dsh-mcp-connector 的公开接口(" + MCP_BRIDGE + ")。" + (mcp.error === null ? "" : "原因:" + String(mcp.error)) + "。自定义 MCP Server 的权威位置仍是「设置 → 插件配置 → MCP 服务器配置」,本卡不会修改它的托管配置。"); + mcpTab = h$7("div", { style: styles.root, key: "mcp" - }, h$8(Section, { + }, h$7(Section, { title: "我的连接", hint: "数据来自宿主 dsh-mcp-connector 插件(同一 origin 的公开接口);本卡不保存任何 MCP 凭据,也不回显启动命令与密钥。", - aside: h$8(Btn, { + aside: h$7(Btn, { label: mcp.status === "probe" ? "探测中…" : "重新探测", variant: "small", disabled: mcp.busy !== "", onClick: probeMcp }) - }, bridgeBox, mcp.status === "ok" && items.length === 0 ? h$8("p", { style: styles.hint }, "宿主还没有登记任何 MCP 连接。") : null, mcp.status === "ok" && items.length > 0 ? h$8("div", { style: { + }, bridgeBox, mcp.status === "ok" && items.length === 0 ? h$7("p", { style: styles.hint }, "宿主还没有登记任何 MCP 连接。") : null, mcp.status === "ok" && items.length > 0 ? h$7("div", { style: { display: "flex", flexDirection: "column", gap: "8px" - } }, h$8("div", { style: styles.pills }, h$8(Pill$1, { + } }, h$7("div", { style: styles.pills }, h$7(Pill$1, { label: "共", value: String(items.length), tone: "muted" - }), h$8(Pill$1, { + }), h$7(Pill$1, { label: "匹配", value: String(visibleItems.length), tone: visibleItems.length === 0 ? "muted" : "ok" - }), h$8(Pill$1, { + }), h$7(Pill$1, { label: "已选", value: String(mcpChosen.length), tone: mcpChosen.length === 0 ? "muted" : "ok" - }), h$8(Pill$1, { + }), h$7(Pill$1, { label: "已连接", value: String(mcpCounts.connected), tone: "ok" - }), h$8(Pill$1, { + }), h$7(Pill$1, { label: "异常", value: String(mcpCounts.problem), tone: mcpCounts.problem === 0 ? "muted" : "warn" - })), h$8("div", { style: { + })), h$7("div", { style: { display: "flex", gap: "8px", alignItems: "center", flexWrap: "wrap" - } }, h$8("input", { + } }, h$7("input", { type: "search", style: Object.assign({}, styles.input, { flex: "1 1 220px", @@ -3837,37 +3837,37 @@ window.__ModuleLoader__.load({ onChange: function(event) { patchMcp({ search: event.target.value }); } - }), mcpSearch !== "" ? h$8(Btn, { + }), mcpSearch !== "" ? h$7(Btn, { label: "清空搜索", variant: "small", onClick: function() { patchMcp({ search: "" }); } - }) : null), h$8("div", { style: Object.assign({}, styles.actions, { flexWrap: "wrap" }) }, h$8(Btn, { + }) : null), h$7("div", { style: Object.assign({}, styles.actions, { flexWrap: "wrap" }) }, h$7(Btn, { label: "筛选:全部(" + String(items.length) + ")", variant: mcpFilter === "all" ? "primary" : "small", onClick: function() { patchMcp({ filter: "all" }); } - }), h$8(Btn, { + }), h$7(Btn, { label: "已连接(" + String(mcpCounts.connected) + ")", variant: mcpFilter === "connected" ? "primary" : "small", onClick: function() { patchMcp({ filter: "connected" }); } - }), h$8(Btn, { + }), h$7(Btn, { label: "已停用(" + String(mcpCounts.disabled) + ")", variant: mcpFilter === "disabled" ? "primary" : "small", onClick: function() { patchMcp({ filter: "disabled" }); } - }), h$8(Btn, { + }), h$7(Btn, { label: "异常(" + String(mcpCounts.problem) + ")", variant: mcpFilter === "problem" ? "primary" : "small", onClick: function() { patchMcp({ filter: "problem" }); } - })), h$8("div", { style: Object.assign({}, styles.actions, { flexWrap: "wrap" }) }, h$8(Btn, { + })), h$7("div", { style: Object.assign({}, styles.actions, { flexWrap: "wrap" }) }, h$7(Btn, { label: "全选匹配结果(" + String(visibleItems.length) + ")", ariaLabel: "全选匹配结果", variant: "small", @@ -3875,7 +3875,7 @@ window.__ModuleLoader__.load({ onClick: function() { selectMcpMany(visibleItems, true); } - }), h$8(Btn, { + }), h$7(Btn, { label: "全选全部(" + String(items.length) + ")", ariaLabel: "全选全部", variant: "small", @@ -3883,7 +3883,7 @@ window.__ModuleLoader__.load({ onClick: function() { selectMcpMany(items, true); } - }), h$8(Btn, { + }), h$7(Btn, { label: "取消勾选匹配项(" + String(matchedSelected) + ")", ariaLabel: "取消勾选匹配项", variant: "small", @@ -3891,7 +3891,7 @@ window.__ModuleLoader__.load({ onClick: function() { selectMcpMany(visibleItems, false); } - }), h$8(Btn, { + }), h$7(Btn, { label: "清空已选", ariaLabel: "清空已选", variant: "small", @@ -3902,7 +3902,7 @@ window.__ModuleLoader__.load({ confirmBulk: false }); } - })), mcpChosen.length === 0 ? h$8("p", { style: styles.hint }, "勾选左侧连接后,这里会出现批量健康检查、启停、重连与移除。") : h$8("div", { style: Object.assign({}, styles.actions, { flexWrap: "wrap" }) }, h$8("span", { style: styles.hint }, "批量操作(已选 " + String(mcpChosen.length) + "):"), h$8(Btn, { + })), mcpChosen.length === 0 ? h$7("p", { style: styles.hint }, "勾选左侧连接后,这里会出现批量健康检查、启停、重连与移除。") : h$7("div", { style: Object.assign({}, styles.actions, { flexWrap: "wrap" }) }, h$7("span", { style: styles.hint }, "批量操作(已选 " + String(mcpChosen.length) + "):"), h$7(Btn, { label: "健康检查", ariaLabel: "批量健康检查", variant: "small", @@ -3912,7 +3912,7 @@ window.__ModuleLoader__.load({ return { connectorId: item.connectorId }; }); } - }), h$8(Btn, { + }), h$7(Btn, { label: "启用", ariaLabel: "批量启用", variant: "small", @@ -3925,7 +3925,7 @@ window.__ModuleLoader__.load({ }; }); } - }), h$8(Btn, { + }), h$7(Btn, { label: "停用", ariaLabel: "批量停用", variant: "small", @@ -3938,7 +3938,7 @@ window.__ModuleLoader__.load({ }; }); } - }), h$8(Btn, { + }), h$7(Btn, { label: "重连", ariaLabel: "批量重连", variant: "small", @@ -3948,7 +3948,7 @@ window.__ModuleLoader__.load({ return { key: item.key }; }); } - }), mcp.confirmBulk === true ? h$8(Btn, { + }), mcp.confirmBulk === true ? h$7(Btn, { label: "确认移除(" + String(mcpChosen.length) + ")", ariaLabel: "确认批量移除", variant: "danger", @@ -3958,7 +3958,7 @@ window.__ModuleLoader__.load({ return { key: item.key }; }); } - }) : h$8(Btn, { + }) : h$7(Btn, { label: "移除…", ariaLabel: "批量移除", variant: "small", @@ -3970,64 +3970,64 @@ window.__ModuleLoader__.load({ text: "批量移除会断开所选 " + String(mcpChosen.length) + " 条连接定义;再点一次「确认移除」才执行。" }); } - })), mcpBulk === null ? null : h$8("p", { style: styles.hint }, String(mcpBulk.label) + " 进行中:" + String(mcpBulk.done) + " / " + String(mcpBulk.total)), visibleItems.length === 0 ? h$8("p", { style: styles.hint }, "没有匹配「" + mcpSearch + "」的连接。换个关键词或切回「全部」筛选。") : null, visibleItems.map(function(item) { + })), mcpBulk === null ? null : h$7("p", { style: styles.hint }, String(mcpBulk.label) + " 进行中:" + String(mcpBulk.done) + " / " + String(mcpBulk.total)), visibleItems.length === 0 ? h$7("p", { style: styles.hint }, "没有匹配「" + mcpSearch + "」的连接。换个关键词或切回「全部」筛选。") : null, visibleItems.map(function(item) { var state = stateOf(item); var tools = mcp.tools[item.key]; var details = mcp.details === null || mcp.details === void 0 ? {} : mcp.details; var open = details[item.key] === true; var label = String(item.name === void 0 ? item.key : item.name); - return h$8("div", { + return h$7("div", { key: String(item.key), style: styles.row - }, h$8("div", { style: styles.rowHead }, h$8("label", { style: { + }, h$7("div", { style: styles.rowHead }, h$7("label", { style: { display: "inline-flex", alignItems: "center", gap: "8px", minWidth: 0, flex: "1 1 auto" - } }, h$8("input", { + } }, h$7("input", { type: "checkbox", checked: mcpChosen.indexOf(item.key) >= 0, "aria-label": "选择连接 " + label, onChange: function(event) { selectMcpMany([item], event.target.checked === true); } - }), h$8("span", { style: styles.rowTitle }, label), h$8(Pill$1, { + }), h$7("span", { style: styles.rowTitle }, label), h$7(Pill$1, { label: "状态", value: MCP_STATE_LABELS[state] === void 0 ? state : MCP_STATE_LABELS[state], tone: state === "connected" ? "ok" : state === "disabled" ? "muted" : "warn" - }), h$8(Pill$1, { + }), h$7(Pill$1, { label: "传输", value: String(item.transport === void 0 ? "—" : item.transport), tone: "muted" - })), h$8(Btn, { + })), h$7(Btn, { label: open ? "收起" : "详情", ariaLabel: (open ? "收起详情 " : "详情 ") + label, variant: "small", onClick: function() { patchMcp({ details: Object.assign({}, details, { [String(item.key)]: !open }) }); } - })), open ? h$8("div", { style: { + })), open ? h$7("div", { style: { display: "flex", flexDirection: "column", gap: "6px" - } }, h$8("div", { style: styles.pills }, h$8(Pill$1, { + } }, h$7("div", { style: styles.pills }, h$7(Pill$1, { label: "鉴权", value: String(item.authMode === void 0 ? "none" : item.authMode), tone: "muted" - }), h$8(Pill$1, { + }), h$7(Pill$1, { label: "注入", value: String(item.injectionLabel === void 0 ? "—" : item.injectionLabel), tone: "muted" - }), h$8(Pill$1, { + }), h$7(Pill$1, { label: "范围", value: item.scope === void 0 || item.scope === null ? "未知" : String(item.scope.visibility === void 0 ? JSON.stringify(item.scope) : item.scope.visibility), tone: "muted" - }), h$8(Pill$1, { + }), h$7(Pill$1, { label: "健康检查", value: formatIso(item.healthCheckedAt), tone: "muted" - })), item.lastError === null || item.lastError === void 0 ? null : h$8("p", { style: styles.hint }, "最近错误:" + String(item.lastError)), h$8("div", { style: styles.actions }, h$8(Btn, { + })), item.lastError === null || item.lastError === void 0 ? null : h$7("p", { style: styles.hint }, "最近错误:" + String(item.lastError)), h$7("div", { style: styles.actions }, h$7(Btn, { label: "健康检查", ariaLabel: "健康检查 " + label, variant: "small", @@ -4037,7 +4037,7 @@ window.__ModuleLoader__.load({ probeMcp(); }); } - }), h$8(Btn, { + }), h$7(Btn, { label: "工具列表", ariaLabel: "工具列表 " + label, variant: "small", @@ -4045,7 +4045,7 @@ window.__ModuleLoader__.load({ onClick: function() { loadTools(item); } - }), h$8(Btn, { + }), h$7(Btn, { label: item.enabled === false ? "启用" : "停用", ariaLabel: "启停 " + label, variant: "small", @@ -4058,7 +4058,7 @@ window.__ModuleLoader__.load({ probeMcp(); }); } - }), h$8(Btn, { + }), h$7(Btn, { label: "重连", ariaLabel: "重连 " + label, variant: "small", @@ -4068,7 +4068,7 @@ window.__ModuleLoader__.load({ probeMcp(); }); } - }), mcp.confirm === item.key ? h$8(Btn, { + }), mcp.confirm === item.key ? h$7(Btn, { label: "确认移除", ariaLabel: "确认移除 " + label, variant: "danger", @@ -4079,7 +4079,7 @@ window.__ModuleLoader__.load({ probeMcp(); }); } - }) : h$8(Btn, { + }) : h$7(Btn, { label: "移除连接…", ariaLabel: "移除连接 " + label, variant: "small", @@ -4091,75 +4091,15 @@ window.__ModuleLoader__.load({ text: "再次点击「确认移除」才会断开该连接定义。" }); } - })), tools === void 0 ? null : h$8("p", { style: styles.hint }, "工具缓存(" + formatTime(tools.at) + "):" + (tools.items.length === 0 ? "空" : tools.items.map(function(tool) { + })), tools === void 0 ? null : h$7("p", { style: styles.hint }, "工具缓存(" + formatTime(tools.at) + "):" + (tools.items.length === 0 ? "空" : tools.items.map(function(tool) { return String(tool.name === void 0 ? tool : tool.name); }).join("、")))) : null); - }), h$8("p", { style: styles.hint }, "工具可见不等于业务可调用:连接状态与工具缓存分开显示。")) : null), h$8(McpCustomSection, { onChanged: probeMcp }), h$8(McpConfigSection, { + }), h$7("p", { style: styles.hint }, "工具可见不等于业务可调用:连接状态与工具缓存分开显示。")) : null), h$7(McpCustomSection, { onChanged: probeMcp }), h$7(McpConfigSection, { items, onChanged: probeMcp })); } - return h$8("div", { style: styles.root }, header, tabBar, noticeBox, error === null ? null : h$8(Banner, { tone: "bad" }, error), tab === "connection" ? connectionTab : tab === "skills" ? skillsTab : mcpTab); - } - // src-client/SettingsSummaryCard.tsx - const h$7 = react.createElement; - function SettingsSummaryCard(props) { - const [status, setStatus] = react.useState(null); - const [error, setError] = react.useState(null); - react.useEffect(() => { - let cancelled = false; - const load = () => { - request(API.status).then((result) => { - if (cancelled) return; - if (result.status === 200 && result.body !== null && result.body.ok === true) { - setStatus(result.body); - setError(null); - } else setError("读取状态失败(HTTP " + String(result.status) + ")"); - }, (failure) => { - if (!cancelled) setError(messageOf(failure)); - }); - }; - load(); - const timer = setInterval(load, 15e3); - return () => { - cancelled = true; - clearInterval(timer); - }; - }, []); - function openPanel() { - const ctx = props.ctx; - const layout = ctx === void 0 || ctx === null ? void 0 : ctx.layout; - if (layout !== void 0 && layout !== null && typeof layout.selectPanel === "function") { - layout.selectPanel("dsh-brain"); - return; - } - if (typeof window !== "undefined" && typeof window.open === "function") window.open("/dsh-brain"); - } - const settings = status?.settings ?? {}; - return h$7("div", { - style: styles.root, - "data-dsh-plugin": "dsh-brain" - }, h$7("div", { style: styles.sectionHead }, h$7("h4", { style: styles.sectionTitle }, "云端记忆"), h$7("div", { style: styles.actions }, h$7(Btn, { - variant: "primary", - label: "打开总面板", - onClick: openPanel - }))), h$7("p", { style: styles.hint }, "设置与连接内容已收进左侧栏 Brain 总面板的「连接与上报」页签。这里保留状态摘要和快捷入口。"), error === null ? null : h$7(Banner, { tone: "bad" }, error), status === null ? h$7("p", { style: styles.hint }, "正在读取状态…") : h$7("div", { style: styles.pills }, h$7(Pill$1, { - label: "服务", - value: settings.baseUrlConfigured === false ? "未配置" : "已配置", - tone: settings.baseUrlConfigured === false ? "warn" : "ok" - }), h$7(Pill$1, { - label: "上报", - value: settings.activityEnabled === true ? "开" : "关", - tone: settings.activityEnabled === true ? "ok" : "muted" - }), h$7(Pill$1, { - label: "记忆", - value: settings.memoryEnabled === true ? "开" : "关", - tone: settings.memoryEnabled === true ? "ok" : "muted" - }), h$7(Pill$1, { - label: "本地记忆", - value: settings.localMemoryEnabled === false ? "关" : "开", - tone: settings.localMemoryEnabled === false ? "muted" : "ok" - }))); + return h$7("div", { style: styles.root }, header, tabBar, noticeBox, error === null ? null : h$7(Banner, { tone: "bad" }, error), tab === "connection" ? connectionTab : tab === "skills" ? skillsTab : mcpTab); } // src-client/panel/brain-icon.tsx const BRAIN_ICON_PATHS = [ @@ -4191,7 +4131,7 @@ window.__ModuleLoader__.load({ }))); } // \0dsh-brain-css:src-client/panel/BrainPanel.module.css.mjs - const css$1 = "/* Adapted from dsh-mnemon MnemonWorkspace.dshbrain_1xedgey.dshbrain_holtzx (MIT), see vendor/dsh-mnemon/LICENSE. */\n.dshbrain_1y11fqi {\n box-sizing: border-box;\n position: relative;\n z-index: 2;\n display: flex;\n width: 100%;\n height: 100%;\n min-width: 0;\n min-height: 0;\n overflow: hidden;\n flex: 1 1 auto;\n padding-block-start: var(--dsh-frame-top-clearance, 0px);\n}\n\n.dshbrain_1y11fqi > * {\n min-width: 0;\n flex: 1 1 auto;\n}\n\n.dshbrain_131vunv {\n position: absolute;\n inset: 0 0 auto;\n height: var(--dsh-frame-top-clearance, 0px);\n}\n\n.dshbrain_oyvdy4 {\n display: flex;\n flex-direction: column;\n gap: 14px;\n padding: 18px 20px 24px;\n overflow: auto;\n font-size: 13px;\n line-height: 1.55;\n color: var(--dsw-alias-label-primary, inherit);\n}\n\n.dshbrain_of3f1r {\n display: flex;\n align-items: flex-start;\n justify-content: space-between;\n gap: 12px;\n flex-wrap: wrap;\n}\n\n.dshbrain_vnw8w9 {\n display: flex;\n flex-direction: column;\n gap: 2px;\n min-width: 0;\n}\n\n.dshbrain_g8fis8 {\n margin: 0;\n font-size: 16px;\n font-weight: 650;\n letter-spacing: 0.01em;\n}\n\n.dshbrain_1milhhm {\n margin: 0;\n font-size: 11.5px;\n opacity: 0.58;\n}\n\n.dshbrain_xnx8bm {\n display: flex;\n gap: 4px;\n padding: 3px;\n border-radius: 13px;\n border: 1px solid var(--dsw-alias-border-subtle, rgba(127,127,127,0.22));\n background: var(--dsw-alias-bg-subtle, rgba(127,127,127,0.06));\n flex-wrap: wrap;\n}\n\n.dshbrain_7mndvh {\n flex: 1 1 auto;\n min-width: 88px;\n font: inherit;\n font-size: 12.5px;\n padding: 7px 12px;\n border-radius: 10px;\n border: 1px solid transparent;\n background: transparent;\n color: inherit;\n cursor: pointer;\n white-space: nowrap;\n}\n\n.dshbrain_rvx7lj {\n border: 1px solid var(--dsw-alias-border-subtle, rgba(127,127,127,0.30));\n background: var(--dsw-alias-interactive-bg-hover, rgba(127,127,127,0.14));\n box-shadow: 0 1px 3px rgba(0,0,0,0.10);\n font-weight: 600;\n}\n\n.dshbrain_1rfmkcf {\n display: flex;\n flex-direction: column;\n gap: 12px;\n min-width: 0;\n}\n\n.dshbrain_1wofcsb {\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n gap: 8px;\n padding: 48px 16px;\n border: 1px dashed var(--dsw-alias-border-subtle, rgba(127,127,127,0.30));\n border-radius: 16px;\n opacity: 0.65;\n}\n\n.dshbrain_3omakb {\n margin: 0;\n font-size: 14px;\n font-weight: 600;\n}\n\n.dshbrain_j3tuu2 {\n margin: 0;\n font-size: 12px;\n}\n\n.dshbrain_c36neh {\n display: flex;\n flex-direction: column;\n gap: 12px;\n}\n\n.dshbrain_1a7ley4 {\n display: flex;\n flex-direction: column;\n gap: 10px;\n border: 1px solid var(--dsw-alias-border-subtle, rgba(127,127,127,0.22));\n border-radius: 16px;\n padding: 16px 18px;\n min-width: 0;\n}\n\n.dshbrain_1f1qv8u {\n display: flex;\n align-items: center;\n justify-content: space-between;\n gap: 10px;\n flex-wrap: wrap;\n}\n\n.dshbrain_1t5691m {\n margin: 0;\n font-size: 13.5px;\n font-weight: 650;\n}\n\n.dshbrain_updgou {\n display: flex;\n flex-wrap: wrap;\n gap: 8px;\n}\n\n.dshbrain_xwrsl5 {\n display: inline-flex;\n align-items: center;\n gap: 6px;\n padding: 3px 10px;\n border-radius: 999px;\n border: 1px solid var(--dsw-alias-border-subtle, rgba(127,127,127,0.35));\n font-size: 12px;\n white-space: nowrap;\n}\n\n.dshbrain_mvsf69 {\n opacity: 0.75;\n}\n\n.dshbrain_1xby9uu {\n font-weight: 600;\n}\n\n.dshbrain_1bzyta0 { border-color: rgba(22,163,74,0.55); background: rgba(22,163,74,0.12); }\n.dshbrain_1hx5ob5 { border-color: rgba(220,38,38,0.55); background: rgba(220,38,38,0.12); }\n.dshbrain_amukxq { border-color: rgba(217,119,6,0.55); background: rgba(217,119,6,0.12); }\n.dshbrain_uf6ztt { }\n\n.dshbrain_1vi102j {\n margin: 0;\n font-size: 11.5px;\n opacity: 0.58;\n}\n\n.dshbrain_qmj948 {\n padding: 10px 13px;\n border-radius: 11px;\n border: 1px solid rgba(220,38,38,0.55);\n background: rgba(220,38,38,0.12);\n font-size: 12.5px;\n}\n\n.dshbrain_1ex8b80 {\n display: flex;\n align-items: baseline;\n flex-wrap: wrap;\n}\n\n.dshbrain_1048ygk {\n display: inline-flex;\n align-items: baseline;\n gap: 6px;\n padding-right: 18px;\n margin-right: 18px;\n border-right: 1px solid var(--dsw-alias-border-subtle, rgba(127,127,127,0.20));\n}\n\n.dshbrain_1bvujjo {\n display: inline-flex;\n align-items: baseline;\n gap: 6px;\n}\n\n.dshbrain_d75ahw {\n font-size: 17px;\n font-weight: 700;\n}\n"; + const css$1 = "/* Adapted from dsh-mnemon MnemonWorkspace.dshbrain_1xedgey.dshbrain_holtzx (MIT), see vendor/dsh-mnemon/LICENSE. */\n.dshbrain_1y11fqi {\n box-sizing: border-box;\n position: relative;\n z-index: 2;\n display: flex;\n width: 100%;\n height: 100%;\n min-width: 0;\n min-height: 0;\n overflow: hidden;\n flex: 1 1 auto;\n padding-block-start: var(--dsh-frame-top-clearance, 0px);\n}\n\n.dshbrain_1y11fqi > * {\n min-width: 0;\n flex: 1 1 auto;\n}\n\n.dshbrain_131vunv {\n position: absolute;\n inset: 0 0 auto;\n height: var(--dsh-frame-top-clearance, 0px);\n}\n\n.dshbrain_oyvdy4 {\n display: flex;\n flex-direction: column;\n gap: 14px;\n padding: 18px 20px 24px;\n overflow: auto;\n font-size: 13px;\n line-height: 1.55;\n color: var(--dsw-alias-label-primary, inherit);\n}\n\n.dshbrain_of3f1r {\n display: flex;\n align-items: flex-start;\n justify-content: space-between;\n gap: 12px;\n flex-wrap: wrap;\n}\n\n.dshbrain_vnw8w9 {\n display: flex;\n flex-direction: column;\n gap: 2px;\n min-width: 0;\n}\n\n.dshbrain_g8fis8 {\n margin: 0;\n font-size: 16px;\n font-weight: 650;\n letter-spacing: 0.01em;\n}\n\n.dshbrain_1milhhm {\n margin: 0;\n font-size: 11.5px;\n opacity: 0.58;\n}\n\n.dshbrain_xnx8bm {\n display: flex;\n gap: 4px;\n padding: 3px;\n border-radius: 13px;\n border: 1px solid var(--dsw-alias-border-subtle, rgba(127,127,127,0.22));\n background: var(--dsw-alias-bg-subtle, rgba(127,127,127,0.06));\n flex-wrap: wrap;\n}\n\n.dshbrain_7mndvh {\n flex: 1 1 auto;\n min-width: 88px;\n font: inherit;\n font-size: 12.5px;\n padding: 7px 12px;\n border-radius: 10px;\n border: 1px solid transparent;\n background: transparent;\n color: inherit;\n cursor: pointer;\n white-space: nowrap;\n}\n\n.dshbrain_rvx7lj {\n border: 1px solid var(--dsw-alias-border-subtle, rgba(127,127,127,0.30));\n background: var(--dsw-alias-interactive-bg-hover, rgba(127,127,127,0.14));\n box-shadow: 0 1px 3px rgba(0,0,0,0.10);\n font-weight: 600;\n}\n\n.dshbrain_1rfmkcf {\n display: flex;\n flex-direction: column;\n gap: 12px;\n min-width: 0;\n}\n\n.dshbrain_c36neh {\n display: flex;\n flex-direction: column;\n gap: 12px;\n}\n\n.dshbrain_1a7ley4 {\n display: flex;\n flex-direction: column;\n gap: 10px;\n border: 1px solid var(--dsw-alias-border-subtle, rgba(127,127,127,0.22));\n border-radius: 16px;\n padding: 16px 18px;\n min-width: 0;\n}\n\n.dshbrain_1f1qv8u {\n display: flex;\n align-items: center;\n justify-content: space-between;\n gap: 10px;\n flex-wrap: wrap;\n}\n\n.dshbrain_1t5691m {\n margin: 0;\n font-size: 13.5px;\n font-weight: 650;\n}\n\n.dshbrain_updgou {\n display: flex;\n flex-wrap: wrap;\n gap: 8px;\n}\n\n.dshbrain_xwrsl5 {\n display: inline-flex;\n align-items: center;\n gap: 6px;\n padding: 3px 10px;\n border-radius: 999px;\n border: 1px solid var(--dsw-alias-border-subtle, rgba(127,127,127,0.35));\n font-size: 12px;\n white-space: nowrap;\n}\n\n.dshbrain_mvsf69 {\n opacity: 0.75;\n}\n\n.dshbrain_1xby9uu {\n font-weight: 600;\n}\n\n.dshbrain_1bzyta0 { border-color: rgba(22,163,74,0.55); background: rgba(22,163,74,0.12); }\n.dshbrain_1hx5ob5 { border-color: rgba(220,38,38,0.55); background: rgba(220,38,38,0.12); }\n.dshbrain_amukxq { border-color: rgba(217,119,6,0.55); background: rgba(217,119,6,0.12); }\n.dshbrain_uf6ztt { }\n\n.dshbrain_1vi102j {\n margin: 0;\n font-size: 11.5px;\n opacity: 0.58;\n}\n\n.dshbrain_qmj948 {\n padding: 10px 13px;\n border-radius: 11px;\n border: 1px solid rgba(220,38,38,0.55);\n background: rgba(220,38,38,0.12);\n font-size: 12.5px;\n}\n\n.dshbrain_1ex8b80 {\n display: flex;\n align-items: baseline;\n flex-wrap: wrap;\n}\n\n.dshbrain_1048ygk {\n display: inline-flex;\n align-items: baseline;\n gap: 6px;\n padding-right: 18px;\n margin-right: 18px;\n border-right: 1px solid var(--dsw-alias-border-subtle, rgba(127,127,127,0.20));\n}\n\n.dshbrain_1bvujjo {\n display: inline-flex;\n align-items: baseline;\n gap: 6px;\n}\n\n.dshbrain_d75ahw {\n font-size: 17px;\n font-weight: 700;\n}\n"; const tagId$1 = "src-client/panel/BrainPanel.module.css"; if (typeof document !== "undefined" && typeof document.querySelector === "function" && typeof document.createElement === "function") { let tag = document.querySelector("style[data-plugin-css=" + JSON.stringify(tagId$1) + "]"); @@ -4216,9 +4156,6 @@ window.__ModuleLoader__.load({ "tab": "dshbrain_7mndvh", "tabActive": "dshbrain_rvx7lj", "content": "dshbrain_1rfmkcf", - "placeholder": "dshbrain_1wofcsb", - "placeholderTitle": "dshbrain_3omakb", - "placeholderHint": "dshbrain_j3tuu2", "overviewGrid": "dshbrain_c36neh", "card": "dshbrain_1a7ley4", "cardHead": "dshbrain_1f1qv8u", @@ -4269,7 +4206,7 @@ window.__ModuleLoader__.load({ const [statusResult, capabilitiesResult, memoryResult] = await Promise.all([ request(API.status), request(API.capabilities), - request("/dsh-brain/local-memory/status") + request("/dsh-brain/local-memory/status?scope=global") ]); if (cancelled) return; if (statusResult.status === 200 && statusResult.body !== null && statusResult.body.ok === true) { @@ -4324,7 +4261,7 @@ window.__ModuleLoader__.load({ label: "诊断日志", value: settings.diagnosticsEnabled === false ? "关" : "开", tone: settings.diagnosticsEnabled === false ? "muted" : "ok" - })), h$5("p", { className: BrainPanel_module_css_default.hint }, "诊断日志位置:$DSH_HOME/brain/logs(全局)与 <项目>/.dsh/brain/logs(项目)"), status?.lastCheck === null || status?.lastCheck === void 0 ? null : h$5("p", { className: BrainPanel_module_css_default.hint }, "最近检查:" + formatTime(status.lastCheck.at) + " · " + String(status.lastCheck.status ?? ""))), h$5(Card, { title: "五个 bundle 开关态" }, h$5("div", { className: BrainPanel_module_css_default.pills }, bundleKeys.map((key) => h$5(Pill, { + })), h$5("p", { className: BrainPanel_module_css_default.hint }, "全局诊断日志:$DSH_HOME/brain/logs"), status?.lastCheck === null || status?.lastCheck === void 0 ? null : h$5("p", { className: BrainPanel_module_css_default.hint }, "最近检查:" + formatTime(status.lastCheck.at) + " · " + String(status.lastCheck.status ?? ""))), h$5(Card, { title: "五个 bundle 开关态" }, h$5("div", { className: BrainPanel_module_css_default.pills }, bundleKeys.map((key) => h$5(Pill, { key, label: BUNDLE_LABELS[key] ?? key, value: bundles[key] === true ? "启用" : bundles[key] === false ? "停用" : "未知", @@ -4337,10 +4274,6 @@ window.__ModuleLoader__.load({ label: "全局空间", value: memorySpaces.global === null || memorySpaces.global === void 0 ? "未创建" : "就绪", tone: memorySpaces.global === null || memorySpaces.global === void 0 ? "muted" : "ok" - }), h$5(Pill, { - label: "项目空间", - value: memorySpaces.project === null || memorySpaces.project === void 0 ? "未创建" : "就绪", - tone: memorySpaces.project === null || memorySpaces.project === void 0 ? "muted" : "ok" }), h$5(Pill, { label: "云同步", value: memory?.cloudSyncEnabled === true ? "开" : "关", @@ -4398,40 +4331,26 @@ window.__ModuleLoader__.load({ }; } // src-client/panel/workspace.ts - function resolveWorkspace(ctx) { - try { - const sessions = ctx !== void 0 && ctx !== null && typeof ctx.get === "function" ? ctx.get("sessions") : void 0; - if (sessions === void 0 || sessions === null) return void 0; - const current = typeof sessions.current === "function" ? sessions.current() : sessions.current; - const candidates = [ - current?.cwd, - current?.header?.cwd, - current?.session?.cwd, - current?.session?.header?.cwd, - typeof sessions.cwd === "function" ? sessions.cwd() : void 0 - ]; - for (const candidate of candidates) if (typeof candidate === "string" && candidate.trim() !== "") return candidate; - } catch {} - } - function workspaceQuery(workspace) { - return workspace === void 0 ? "" : "?workspace=" + encodeURIComponent(workspace); + function scopeParams(scope) { + const params = new URLSearchParams({ scope: scope.scope }); + if (scope.scope === "project") params.set("workspace", scope.workspace); + return params; } // src-client/panel/MemoryTab.tsx const h$4 = react.createElement; const PAGE_SIZE = 50; - function workspaceSuffix(workspace) { - return workspace === void 0 ? "" : "&workspace=" + encodeURIComponent(workspace); - } function MemoryTab(props) { const active = props.active !== false; - const workspace = props.workspace; + const project = props.scope === "project"; + const scope = scopeParams(props); + const scopeLabel = project ? "项目" : "全局"; const [offset, setOffset] = react.useState(0); const [search, setSearch] = react.useState(""); const [notice, setNotice] = react.useState(null); const [pendingForget, setPendingForget] = react.useState(null); const [busy, setBusy] = react.useState(""); const status = useApi(async () => { - const result = await request("/dsh-brain/local-memory/status" + workspaceQuery(workspace)); + const result = await request("/dsh-brain/local-memory/status?" + scope.toString()); if (result.status !== 200 || result.body === null || result.body.ok !== true) throw new Error(bodyError(result, "读取本地记忆状态失败")); return result.body; }, { @@ -4439,18 +4358,19 @@ window.__ModuleLoader__.load({ pollMs: 15e3 }); const memories = useApi(async () => { - const result = await request("/dsh-brain/local-memory/memories?limit=" + String(PAGE_SIZE) + "&offset=" + String(offset) + workspaceSuffix(workspace)); + const result = await request("/dsh-brain/local-memory/memories?limit=" + String(PAGE_SIZE) + "&offset=" + String(offset) + "&" + scope.toString()); if (result.status !== 200 || result.body === null || result.body.ok !== true) throw new Error(bodyError(result, "读取记忆列表失败")); return result.body; }, { visible: active, + pollMs: project ? 3e4 : void 0, deps: [offset] }); const documents = useApi(async () => { - const result = await request("/dsh-brain/local-memory/documents" + workspaceQuery(workspace)); + const result = await request("/dsh-brain/local-memory/documents?" + scope.toString()); if (result.status !== 200 || result.body === null || result.body.ok !== true) throw new Error(bodyError(result, "读取文档列表失败")); return result.body; - }, { visible: active }); + }, { visible: active && project }); const items = Array.isArray(memories.data?.items) ? memories.data.items : []; const needle = String(search).trim().toLowerCase(); const filtered = needle === "" ? items : items.filter((item) => { @@ -4468,7 +4388,7 @@ window.__ModuleLoader__.load({ const result = await postJson("/dsh-brain/local-memory/forget", { id: item.id, expectedRevision: item.revision, - workspace + ...Object.fromEntries(scope) }); if (result.status !== 200 || result.body === null || result.body.ok !== true) setNotice({ tone: "bad", @@ -4491,46 +4411,28 @@ window.__ModuleLoader__.load({ setBusy(""); } }; - const spaces = status.data?.spaces ?? {}; - const globalSpace = spaces.global; - const projectSpace = spaces.project; + const space = status.data?.spaces?.[props.scope]; + const root = project ? status.data?.projectRoot : status.data?.globalRoot; return h$4("div", { style: { display: "flex", flexDirection: "column", gap: "12px" } }, status.error === null ? null : h$4(Banner, { tone: "bad" }, status.error), h$4(Section, { - title: "本地记忆空间", - hint: "全局空间与当前项目空间都由本机文件保存;云同步只影响上报,不改变本地存储。", + title: scopeLabel + "记忆空间", aside: h$4(Btn, { label: "刷新", variant: "small", onClick: () => { status.reload(); memories.reload(); - documents.reload(); + if (project) documents.reload(); } }) - }, h$4("div", { style: styles.pills }, h$4(Pill$1, { - label: "provider", - value: status.data?.provider ?? "—", - tone: "muted" - }), h$4(Pill$1, { - label: "全局空间", - value: globalSpace === null || globalSpace === void 0 ? "未创建" : globalSpace.name ?? globalSpace.id ?? "就绪", - tone: globalSpace === null || globalSpace === void 0 ? "muted" : "ok" - }), h$4(Pill$1, { - label: "项目空间", - value: projectSpace === null || projectSpace === void 0 ? "未创建" : projectSpace.name ?? projectSpace.id ?? "就绪", - tone: projectSpace === null || projectSpace === void 0 ? "muted" : "ok" - }), h$4(Pill$1, { - label: "本地记忆", - value: status.data?.localMemoryEnabled === false ? "关" : "开", - tone: status.data?.localMemoryEnabled === false ? "bad" : "ok" - }), h$4(Pill$1, { - label: "云同步", - value: status.data?.cloudSyncEnabled === true ? "开" : "关", - tone: status.data?.cloudSyncEnabled === true ? "ok" : "muted" - })), status.data?.globalRoot === void 0 ? null : h$4("p", { style: styles.hint }, "全局:" + String(status.data.globalRoot) + (status.data?.projectRoot === void 0 ? "" : " · 项目:" + String(status.data.projectRoot)))), h$4(Section, { + }, h$4(Pill$1, { + label: "空间状态", + value: status.status === "loading" ? "读取中" : space?.name ?? (space ? "就绪" : "未创建"), + tone: space ? "ok" : "muted" + }), root === void 0 ? null : h$4("p", { style: styles.hint }, String(root))), h$4(Section, { title: "记忆条目(" + String(total) + ")", hint: "只显示当前页;搜索只在当前页内过滤。删除需要二次确认并带 revision 校验。", aside: h$4("div", { style: styles.actions }, h$4(Field, { @@ -4594,7 +4496,7 @@ window.__ModuleLoader__.load({ variant: "small", disabled: offset + PAGE_SIZE >= total || memories.status === "loading", onClick: () => setOffset(offset + PAGE_SIZE) - }))), h$4(Section, { + }))), project ? h$4(Section, { title: "文档(只读)", hint: "项目文档由本地记忆库维护;这里只展示标题与摘要。" }, documents.error === null ? null : h$4(Banner, { tone: "bad" }, documents.error), (documents.data?.documents ?? []).length === 0 ? h$4("p", { style: styles.hint }, "当前项目还没有文档。") : h$4("div", { style: { @@ -4612,14 +4514,13 @@ window.__ModuleLoader__.load({ label: "更新", value: formatIso(doc.updatedAt), tone: "muted" - }))), h$4("div", { style: styles.clamp2 }, String(doc.content ?? ""))))))); + }))), h$4("div", { style: styles.clamp2 }, String(doc.content ?? "")))))) : null); } // src-client/panel/DepartmentTab.tsx const h$3 = react.createElement; const EMPTY_CREATE = { name: "", role: "", - scope: "project", skills: "", allowedTools: "", readGlobal: true, @@ -4635,7 +4536,8 @@ window.__ModuleLoader__.load({ }; function DepartmentTab(props) { const active = props.active !== false; - const workspace = resolveWorkspace(props.ctx); + const scope = scopeParams(props); + const scopeLabel = props.scope === "global" ? "全局" : "项目"; const [notice, setNotice] = react.useState(null); const [busy, setBusy] = react.useState(""); const [form, setForm] = react.useState({ ...EMPTY_CREATE }); @@ -4651,7 +4553,7 @@ window.__ModuleLoader__.load({ const [recallHits, setRecallHits] = react.useState([]); const [recallBusy, setRecallBusy] = react.useState(false); const list = useApi(async () => { - const result = await request(ENDPOINTS.list + workspaceQuery(workspace)); + const result = await request(ENDPOINTS.list + "?" + scope.toString()); if (result.status !== 200 || result.body === null || result.body.ok !== true) throw new Error(bodyError(result, "读取部门列表失败")); return result.body; }, { @@ -4695,12 +4597,11 @@ window.__ModuleLoader__.load({ const result = await postJson(ENDPOINTS.create, { name: String(form.name).trim(), role: String(form.role).trim() || void 0, - scope: form.scope, skills: String(form.skills).split(/[,,\s]+/).filter((value) => value !== ""), allowedTools: String(form.allowedTools).split(/[,,\s]+/).filter((value) => value !== ""), readGlobal: form.readGlobal === true, readProject: form.readProject === true, - workspace + ...Object.fromEntries(scope) }); if (result.status !== 200 || result.body === null || result.body.ok !== true) { handleFailure(result, "创建部门失败"); @@ -4727,7 +4628,7 @@ window.__ModuleLoader__.load({ const payload = { id: selected.id, expectedRevision: selected.revision, - workspace + ...Object.fromEntries(scope) }; if (action === "update") { payload.role = detail.role; @@ -4768,7 +4669,7 @@ window.__ModuleLoader__.load({ setRecallBusy(true); setRecallHits([]); try { - const result = await request(ENDPOINTS.recall + "?id=" + encodeURIComponent(recallId) + "&query=" + encodeURIComponent(recallQuery) + "&k=" + encodeURIComponent(recallK) + (workspace === void 0 ? "" : "&workspace=" + encodeURIComponent(workspace))); + const result = await request(ENDPOINTS.recall + "?id=" + encodeURIComponent(recallId) + "&query=" + encodeURIComponent(recallQuery) + "&k=" + encodeURIComponent(recallK) + "&" + scope.toString()); if (result.status !== 200 || result.body === null || result.body.ok !== true) { handleFailure(result, "召回失败"); return; @@ -4788,8 +4689,7 @@ window.__ModuleLoader__.load({ flexDirection: "column", gap: "12px" } }, notice === null ? null : h$3(Banner, { tone: notice.tone }, notice.text), list.error === null ? null : h$3(Banner, { tone: "bad" }, list.error), h$3(Section, { - title: "部门列表", - hint: "部门是本机可复用的工作身份;列表显示 scope、状态、当前任务与 revision。", + title: scopeLabel + "部门列表", aside: h$3(Btn, { label: "刷新", variant: "small", @@ -4860,7 +4760,7 @@ window.__ModuleLoader__.load({ mutate("disable"); } })), h$3("p", { style: styles.hint }, "创建于 " + formatIso(item.createdAt) + " · 更新于 " + formatIso(item.updatedAt))) : null)))), h$3(Section, { - title: "创建部门", + title: "创建" + scopeLabel + "部门", hint: "同名部门会幂等复用,不会覆盖原角色。" }, h$3("div", { style: styles.grid }, h$3(Field, { label: "名称", @@ -4876,14 +4776,7 @@ window.__ModuleLoader__.load({ ...form, role: value }) - }), h$3("div", { style: styles.field }, h$3("span", { style: styles.label }, "范围"), h$3("select", { - value: form.scope, - style: styles.input, - onChange: (event) => setForm({ - ...form, - scope: event.target.value - }) - }, h$3("option", { value: "project" }, "项目"), h$3("option", { value: "global" }, "全局"))), h$3(Field, { + }), h$3(Field, { label: "技能(逗号分隔)", value: form.skills, onChange: (value) => setForm({ @@ -4962,7 +4855,7 @@ window.__ModuleLoader__.load({ } // src-client/panel/BrainPanel.tsx const h$2 = react.createElement; - const TABS = [ + const TABS$1 = [ { id: "overview", label: "概览" @@ -4974,23 +4867,8 @@ window.__ModuleLoader__.load({ { id: "departments", label: "部门" - }, - { - id: "skills", - label: "技能" - }, - { - id: "mcp", - label: "MCP" - }, - { - id: "connection", - label: "连接与上报" } ]; - function Placeholder(props) { - return h$2("div", { className: BrainPanel_module_css_default.placeholder }, h$2("h3", { className: BrainPanel_module_css_default.placeholderTitle }, props.title), h$2("p", { className: BrainPanel_module_css_default.placeholderHint }, "即将上线")); - } function BrainPanel(props) { const [tab, setTab] = react.useState("overview"); const panelId = props.panelId ?? "dsh-brain"; @@ -4998,20 +4876,14 @@ window.__ModuleLoader__.load({ const active = usePanelInfo === void 0 ? true : usePanelInfo((info) => info.activePanelId === panelId); let content; if (tab === "overview") content = h$2(Overview, { active }); - else if (tab === "connection") content = h$2(SettingsCard, null); - else if (tab === "memory") { - const workspace = resolveWorkspace(props.ctx); - content = h$2(MemoryTab, { - key: workspace ?? "", - workspace, - active - }); - } else if (tab === "departments") content = h$2(DepartmentTab, { - ctx: props.ctx, + else if (tab === "memory") content = h$2(MemoryTab, { + scope: "global", + active + }); + else content = h$2(DepartmentTab, { + scope: "global", active }); - else if (tab === "skills") content = h$2(Placeholder, { title: "技能" }); - else content = h$2(Placeholder, { title: "MCP" }); return h$2("div", { className: BrainPanel_module_css_default.nativeWorkspace, "data-dsh-plugin": "dsh-brain", @@ -5020,11 +4892,11 @@ window.__ModuleLoader__.load({ className: BrainPanel_module_css_default.windowDragBand, "data-window-drag": true, "aria-hidden": "true" - }), h$2("div", { className: BrainPanel_module_css_default.panelInner }, h$2("div", { className: BrainPanel_module_css_default.header }, h$2("div", { className: BrainPanel_module_css_default.titleBlock }, h$2("h3", { className: BrainPanel_module_css_default.title }, "Brain"), h$2("p", { className: BrainPanel_module_css_default.subtitle }, "本地记忆、部门与连接的总面板"))), h$2("div", { + }), h$2("div", { className: BrainPanel_module_css_default.panelInner }, h$2("div", { className: BrainPanel_module_css_default.header }, h$2("div", { className: BrainPanel_module_css_default.titleBlock }, h$2("h3", { className: BrainPanel_module_css_default.title }, "Brain"), h$2("p", { className: BrainPanel_module_css_default.subtitle }, "全局记忆、部门与运行状态"))), h$2("div", { className: BrainPanel_module_css_default.tabBar, role: "tablist", "aria-label": "Brain 面板页签" - }, TABS.map((item) => h$2("button", { + }, TABS$1.map((item) => h$2("button", { key: item.id, type: "button", role: "tab", @@ -5057,7 +4929,6 @@ window.__ModuleLoader__.load({ const usePanelInfo = makeUsePanelInfo(ctx, PANEL_ID); const panel = (props) => react.createElement(BrainPanel, { ...props, - ctx, panelId: PANEL_ID, usePanelInfo }); @@ -5098,7 +4969,7 @@ window.__ModuleLoader__.load({ }; } // \0dsh-brain-css:src-client/sidebar/ProjectMemory.module.css.mjs - const css = "/* Adapted from dsh-mnemon MnemonWorkspace.dshbrain_6gleqm.dshbrain_tp0sjt (MIT), see vendor/dsh-mnemon/LICENSE. */\n.dshbrain_ty34oh {\n display: flex;\n width: 100%;\n height: 100%;\n min-width: 0;\n min-height: 0;\n overflow: hidden;\n flex: 1 1 auto;\n color: var(--dsw-alias-label-primary, inherit);\n}\n\n.dshbrain_5jq582 {\n display: flex;\n flex-direction: column;\n gap: 10px;\n width: 100%;\n min-width: 0;\n padding: 12px;\n overflow: auto;\n font-size: 12.5px;\n line-height: 1.5;\n}\n\n.dshbrain_1h1jxwb {\n display: flex;\n align-items: flex-start;\n justify-content: space-between;\n gap: 8px;\n flex-wrap: wrap;\n}\n\n.dshbrain_y21ms {\n margin: 0;\n font-size: 13.5px;\n font-weight: 650;\n}\n\n.dshbrain_11or5iu {\n margin: 0;\n font-size: 12.5px;\n font-weight: 600;\n}\n\n.dshbrain_1feix73 {\n margin: 0;\n font-size: 11.5px;\n opacity: 0.58;\n}\n\n.dshbrain_21cgfy {\n display: flex;\n flex-direction: column;\n gap: 8px;\n}\n\n.dshbrain_1qwoelq {\n display: flex;\n flex-direction: column;\n gap: 5px;\n border: 1px solid var(--dsw-alias-border-subtle, rgba(127,127,127,0.18));\n border-radius: 10px;\n padding: 8px 10px;\n min-width: 0;\n}\n\n.dshbrain_8p16nn {\n display: flex;\n flex-wrap: wrap;\n gap: 6px;\n}\n\n.dshbrain_gp5jh {\n display: -webkit-box;\n -webkit-line-clamp: 3;\n -webkit-box-orient: vertical;\n overflow: hidden;\n overflow-wrap: anywhere;\n}\n\n.dshbrain_11ef887 {\n height: 1px;\n background: var(--dsw-alias-border-subtle, rgba(127,127,127,0.18));\n margin: 2px 0;\n}\n\n.dshbrain_mkopal {\n display: flex;\n flex-direction: column;\n gap: 8px;\n}\n"; + const css = "/* Adapted from dsh-mnemon MnemonWorkspace.dshbrain_6gleqm.dshbrain_tp0sjt (MIT), see vendor/dsh-mnemon/LICENSE. */\n.dshbrain_ty34oh {\n display: flex;\n width: 100%;\n height: 100%;\n min-width: 0;\n min-height: 0;\n overflow: hidden;\n flex: 1 1 auto;\n color: var(--dsw-alias-label-primary, inherit);\n}\n\n.dshbrain_5jq582 {\n display: flex;\n flex-direction: column;\n gap: 10px;\n width: 100%;\n min-width: 0;\n padding: 12px;\n overflow: auto;\n font-size: 12.5px;\n line-height: 1.5;\n}\n\n.dshbrain_1i1598j,\n.dshbrain_1feix73 {\n margin: 0;\n color: var(--dsw-alias-label-secondary, inherit);\n overflow-wrap: anywhere;\n}\n"; const tagId = "src-client/sidebar/ProjectMemory.module.css"; if (typeof document !== "undefined" && typeof document.querySelector === "function" && typeof document.createElement === "function") { let tag = document.querySelector("style[data-plugin-css=" + JSON.stringify(tagId) + "]"); @@ -5114,155 +4985,62 @@ window.__ModuleLoader__.load({ "css": "dshbrain_tp0sjt", "betterSidebarSeat": "dshbrain_ty34oh", "inner": "dshbrain_5jq582", - "header": "dshbrain_1h1jxwb", - "title": "dshbrain_y21ms", - "subtitle": "dshbrain_11or5iu", - "hint": "dshbrain_1feix73", - "list": "dshbrain_21cgfy", - "row": "dshbrain_1qwoelq", - "rowMeta": "dshbrain_8p16nn", - "rowText": "dshbrain_gp5jh", - "divider": "dshbrain_11ef887", - "recallRow": "dshbrain_mkopal" + "workspace": "dshbrain_1i1598j", + "hint": "dshbrain_1feix73" }; // src-client/sidebar/ProjectMemoryView.tsx const h$1 = react.createElement; - function openTotalPanel(ctx) { - const layout = ctx === void 0 || ctx === null ? void 0 : ctx.layout; - if (layout !== void 0 && layout !== null && typeof layout.selectPanel === "function") { - layout.selectPanel("dsh-brain"); - return; - } - if (typeof window !== "undefined" && typeof window.open === "function") window.open("/dsh-brain"); - } + const TABS = [{ + id: "memory", + label: "记忆与文档" + }, { + id: "departments", + label: "部门" + }]; function ProjectMemoryView(props) { - const visible = props.visible !== false; - const workspace = props.scope?.cwd; - const [search, setSearch] = react.useState(""); - const [recallId, setRecallId] = react.useState(""); - const [recallQuery, setRecallQuery] = react.useState(""); - const [recallHits, setRecallHits] = react.useState([]); - const [recallBusy, setRecallBusy] = react.useState(false); - const [notice, setNotice] = react.useState(null); - const status = useApi(async () => { - const result = await request("/dsh-brain/local-memory/status" + workspaceQuery(workspace)); - if (result.status !== 200 || result.body === null || result.body.ok !== true) throw new Error(bodyError(result, "读取本地记忆状态失败")); - return result.body; - }, { - visible, - pollMs: 15e3 - }); - const memories = useApi(async () => { - const result = await request("/dsh-brain/local-memory/memories?limit=50&offset=0" + (workspace === void 0 ? "" : "&workspace=" + encodeURIComponent(workspace))); - if (result.status !== 200 || result.body === null || result.body.ok !== true) throw new Error(bodyError(result, "读取记忆列表失败")); - return result.body; - }, { - visible, - pollMs: 3e4 - }); - const departments = useApi(async () => { - const result = await request("/dsh-brain/departments/list" + (workspace === void 0 ? "" : "?workspace=" + encodeURIComponent(workspace))); - if (result.status !== 200 || result.body === null || result.body.ok !== true) throw new Error(bodyError(result, "读取部门列表失败")); - return result.body; - }, { visible }); - const items = Array.isArray(memories.data?.items) ? memories.data.items : []; - const needle = String(search).trim().toLowerCase(); - const filtered = needle === "" ? items : items.filter((item) => String(item.content ?? "").toLowerCase().indexOf(needle) >= 0); - const departmentList = Array.isArray(departments.data?.departments) ? departments.data.departments : []; - const spaces = status.data?.spaces ?? {}; - const recall = async () => { - if (recallId === "") { - setNotice({ - tone: "warn", - text: "请选择部门。" - }); - return; - } - setRecallBusy(true); - setRecallHits([]); - try { - const result = await request("/dsh-brain/departments/recall?id=" + encodeURIComponent(recallId) + "&query=" + encodeURIComponent(recallQuery) + "&k=5" + (workspace === void 0 ? "" : "&workspace=" + encodeURIComponent(workspace))); - if (result.status !== 200 || result.body === null || result.body.ok !== true) { - setNotice({ - tone: "bad", - text: bodyError(result, "召回失败") - }); - return; - } - setRecallHits(Array.isArray(result.body.hits) ? result.body.hits : []); - } catch (failure) { - setNotice({ - tone: "bad", - text: messageOf(failure) - }); - } finally { - setRecallBusy(false); - } - }; + const [tab, setTab] = react.useState("memory"); + const { sessionId } = props; + const directory = useApi(async () => { + const result = await postJson("/sidebar/api/session.cwd", { sessionId }); + const value = result.body?.value; + const cwd = typeof value?.cwd === "string" ? value.cwd.trim() : ""; + if (result.status !== 200 || result.body?.ok !== true || value?.sessionId !== sessionId || cwd === "") throw new Error("无法确认当前会话的项目目录。"); + return cwd; + }, { visible: props.visible !== false && sessionId !== void 0 }); + const workspace = directory.error === null ? directory.data ?? void 0 : void 0; return h$1("div", { className: ProjectMemory_module_css_default.betterSidebarSeat, "data-dsh-plugin": "dsh-brain", "data-dsh-part": "better-sidebar-memory" - }, h$1("div", { className: ProjectMemory_module_css_default.inner }, h$1("div", { className: ProjectMemory_module_css_default.header }, h$1("div", null, h$1("h4", { className: ProjectMemory_module_css_default.title }, "项目记忆"), h$1("p", { className: ProjectMemory_module_css_default.hint }, "当前会话项目的本地记忆(只读)")), h$1(Btn, { - label: "去总面板", + }, h$1("div", { className: ProjectMemory_module_css_default.inner }, workspace === void 0 ? h$1("div", null, h$1("p", { className: ProjectMemory_module_css_default.hint }, directory.error ?? "等待当前会话的项目目录。"), directory.error === null ? null : h$1(Btn, { + label: "重试", variant: "small", - onClick: () => openTotalPanel(props.ctx) - })), status.error === null ? null : h$1(Banner, { tone: "bad" }, status.error), h$1("div", { style: styles.pills }, h$1(Pill$1, { - label: "全局空间", - value: spaces.global === null || spaces.global === void 0 ? "未创建" : "就绪", - tone: spaces.global === null || spaces.global === void 0 ? "muted" : "ok" - }), h$1(Pill$1, { - label: "项目空间", - value: spaces.project === null || spaces.project === void 0 ? "未创建" : "就绪", - tone: spaces.project === null || spaces.project === void 0 ? "muted" : "ok" - }), h$1(Pill$1, { - label: "条目", - value: memories.data?.total ?? 0, - tone: "muted" - })), h$1(Field, { - label: "搜索记忆", - value: search, - onChange: setSearch - }), notice === null ? null : h$1(Banner, { tone: notice.tone }, notice.text), memories.error === null ? null : h$1(Banner, { tone: "bad" }, memories.error), filtered.length === 0 ? h$1("p", { className: ProjectMemory_module_css_default.hint }, "没有匹配的记忆条目。") : h$1("div", { className: ProjectMemory_module_css_default.list }, filtered.map((item) => h$1("div", { + onClick: directory.reload + })) : h$1(react.Fragment, null, h$1("p", { + className: ProjectMemory_module_css_default.workspace, + title: workspace + }, workspace), h$1("div", { + className: BrainPanel_module_css_default.tabBar, + role: "tablist", + "aria-label": "项目记忆页签" + }, TABS.map((item) => h$1("button", { key: item.id, - className: ProjectMemory_module_css_default.row - }, h$1("div", { className: ProjectMemory_module_css_default.rowMeta }, h$1(Pill$1, { - label: "scope", - value: item.scope ?? "—", - tone: "muted" - }), item.category === void 0 ? null : h$1(Pill$1, { - label: "分类", - value: item.category, - tone: "muted" - }), h$1(Pill$1, { - label: "更新", - value: formatIso(item.updatedAt), - tone: "muted" - })), h$1("div", { className: ProjectMemory_module_css_default.rowText }, String(item.content ?? ""))))), h$1("div", { className: ProjectMemory_module_css_default.divider }), h$1("h5", { className: ProjectMemory_module_css_default.subtitle }, "部门召回"), h$1("div", { className: ProjectMemory_module_css_default.recallRow }, h$1("select", { - className: styles.input, - value: recallId, - onChange: (event) => setRecallId(event.target.value) - }, h$1("option", { value: "" }, "选择部门…"), departmentList.map((item) => h$1("option", { - key: item.id, - value: item.id - }, String(item.name)))), h$1(Field, { - label: "查询", - value: recallQuery, - onChange: setRecallQuery - }), h$1(Btn, { - label: recallBusy ? "召回中…" : "召回", - disabled: recallBusy, - onClick: () => { - recall(); - } - })), recallHits.length === 0 ? null : h$1("div", { className: ProjectMemory_module_css_default.list }, recallHits.map((hit, index) => h$1("div", { - key: String(index), - className: ProjectMemory_module_css_default.row - }, h$1("div", { className: ProjectMemory_module_css_default.rowMeta }, h$1(Pill$1, { - label: "来源", - value: hit.origin ?? "—", - tone: "muted" - })), h$1("div", { className: ProjectMemory_module_css_default.rowText }, String(hit.contentSnippet ?? hit.content ?? ""))))))); + type: "button", + role: "tab", + "aria-selected": tab === item.id, + className: tab === item.id ? BrainPanel_module_css_default.tab + " " + BrainPanel_module_css_default.tabActive : BrainPanel_module_css_default.tab, + onClick: () => setTab(item.id) + }, item.label))), tab === "memory" ? h$1(MemoryTab, { + scope: "project", + workspace, + key: workspace, + active: props.visible + }) : h$1(DepartmentTab, { + scope: "project", + workspace, + key: workspace, + active: props.visible + })))); } // src-client/sidebar/register.ts const BETTER_SIDEBAR_TAB_ID = "dsh-brain:memory"; @@ -5281,16 +5059,19 @@ window.__ModuleLoader__.load({ dispose: service.registerTab({ id: BETTER_SIDEBAR_TAB_ID, title: () => "项目记忆", - description: "当前会话项目的本地记忆:空间/条目/搜索/部门召回", + description: "查看和管理当前项目的记忆、文档与部门", icon: (size) => react.createElement(BrainIcon, { size }), order: 60, single: true, - component: ({ scope, visible }) => react.createElement(ProjectMemoryView, { - key: scope?.cwd ?? "", - ctx, - scope, - visible - }) + component: ({ scope, visible }) => { + const cwd = scope?.cwd?.trim(); + const sessionId = cwd ? scope?.sessionId?.trim() || void 0 : void 0; + return react.createElement(ProjectMemoryView, { + key: JSON.stringify([sessionId, cwd]), + sessionId, + visible + }); + } }) }; }; @@ -5318,9 +5099,6 @@ window.__ModuleLoader__.load({ const h = react.createElement; const inject = ["slots"]; function apply(ctx) { - const summaryCard = function() { - return h(CardBoundary, null, h(SettingsSummaryCard, { ctx })); - }; const configCard = function() { return h(CardBoundary, null, h(SettingsCard, null)); }; @@ -5344,7 +5122,7 @@ window.__ModuleLoader__.load({ label: function() { return "云端记忆"; } - }, summaryCard); + }, configCard); try { if (typeof ctx.effect === "function") ctx.effect(() => registerBrainPanel(ctx), "dsh-brain: panel"); else registerBrainPanel(ctx); diff --git a/cordis.patch.yml b/cordis.patch.yml index b44667e..09553e1 100644 --- a/cordis.patch.yml +++ b/cordis.patch.yml @@ -33,4 +33,7 @@ - id: dsh-brain-mcp name: dsh-brain/mcp - id: dsh-brain-ui - name: dsh-brain/ui + # DSH discovers browser bundles from bare package names. + name: dsh-brain + config: + entry: ui diff --git a/lib/index.js b/lib/index.js index 59456fe..d5cd968 100644 --- a/lib/index.js +++ b/lib/index.js @@ -7,8 +7,12 @@ import * as ui from "./entries/ui.js"; export const name = 'dsh-brain'; /** Services required before `apply` runs. */ export const inject = ['webServer']; -/** Register the plugin with the host: all five sub-entries at once. */ +/** Mount the discoverable UI row or the legacy all-in-one plugin. */ export function apply(ctx, config) { + if (config !== null && typeof config === 'object' && 'entry' in config && config.entry === 'ui') { + ui.apply(ctx, config); + return; + } cloudsync.apply(ctx, config); memory.apply(ctx, config); skills.apply(ctx, config); diff --git a/lib/local-memory/departments/manager.js b/lib/local-memory/departments/manager.js index 601679c..aa07fac 100644 --- a/lib/local-memory/departments/manager.js +++ b/lib/local-memory/departments/manager.js @@ -47,8 +47,10 @@ export class DepartmentManager { return global; return (await this.registry('project').read()).departments.find((item) => item.id === id); } - async required(id) { - const department = await this.find(id); + async required(id, scope) { + const department = scope === undefined + ? await this.find(id) + : (await this.registry(scope).read()).departments.find((item) => item.id === id && item.scope === scope); if (department === undefined) throw new Error('department_not_found'); return department; @@ -88,8 +90,8 @@ export class DepartmentManager { const files = await Promise.all(scopes.map((item) => this.registry(item).read())); return files.flatMap((file) => file.departments).sort((a, b) => b.updatedAt.localeCompare(a.updatedAt) || a.id.localeCompare(b.id)); } - async update(id, patch, expectedRevision) { - const current = await this.required(id); + async update(id, patch, expectedRevision, scope) { + const current = await this.required(id, scope); if (expectedRevision !== undefined && current.revision !== expectedRevision) throw new Error('revision_conflict'); if (patch.role !== undefined && containsSecret(patch.role)) @@ -162,8 +164,8 @@ export class DepartmentManager { }); return { ...reference, hostSessionId: externalId }; } - async checkpoint(id, input, expectedRevision) { - const current = await this.required(id); + async checkpoint(id, input, expectedRevision, scope) { + const current = await this.required(id, scope); if (expectedRevision !== undefined && current.revision !== expectedRevision) throw new Error('revision_conflict'); const currentTask = input.currentTask === undefined ? undefined : text(input.currentTask, 4000); @@ -204,12 +206,17 @@ export class DepartmentManager { }); } /** Private first on equal scores; project/global are opt-in and the total result count stays bounded. */ - async recall(id, query, k = 5, workspace) { - const department = await this.required(id); + async recall(id, query, k = 5, workspace, scope) { + const department = await this.required(id, scope); const limit = limitOf(k); const privateHits = await this.store(department).search(query, limit); const shared = []; - if (department.memory.readProject && department.memory.readGlobal) { + if (scope !== undefined) { + const readShared = scope === 'global' ? department.memory.readGlobal : department.memory.readProject; + if (readShared) + shared.push(...await this.memory.searchHits(query, limit, workspace, undefined, scope)); + } + else if (department.memory.readProject && department.memory.readGlobal) { shared.push(...await this.memory.searchHits(query, limit * 2, workspace)); } else if (department.memory.readGlobal) { @@ -234,8 +241,8 @@ export class DepartmentManager { }).slice(0, limit); } /** Disable without deleting private memories or allowing automatic session recovery. */ - async disable(id, expectedRevision) { - const current = await this.required(id); + async disable(id, expectedRevision, scope) { + const current = await this.required(id, scope); if (expectedRevision !== undefined && current.revision !== expectedRevision) throw new Error('revision_conflict'); const store = this.store(current); diff --git a/lib/local-memory/manager.js b/lib/local-memory/manager.js index 981add1..77ddea7 100644 --- a/lib/local-memory/manager.js +++ b/lib/local-memory/manager.js @@ -107,6 +107,9 @@ export class LocalMemoryManager { get projectRoot() { return this.projectRootFor(); } get globalStore() { return new JsonMemoryStore(join(this.globalRoot, 'runtime'), 'global', 'global'); } projectStoreFor(workspace) { return new JsonMemoryStore(join(this.projectRootFor(workspace), 'memory-space'), 'project', projectIdFor(this.projectRootFor(workspace))); } + scopedStore(scope, workspace) { + return scope === 'global' ? this.globalStore : this.projectStoreFor(workspace); + } async storeFor(scope, workspace) { if (scope === 'global') return this.globalStore; @@ -251,21 +254,24 @@ export class LocalMemoryManager { return false; seen.add(record.id); return true; }) .sort((a, b) => b.score - a.score || b.record.updatedAt.localeCompare(a.record.updatedAt)); } - async searchHits(query, k = this.settingsOf().localMemoryK ?? 5, workspace, projectId) { + async searchHits(query, k = this.settingsOf().localMemoryK ?? 5, workspace, projectId, scope) { const startedAt = Date.now(); - const hits = await this.collectHits(query, workspace, projectId); const limit = Math.max(1, Math.min(100, Math.trunc(k))); - const result = hits.slice(0, limit); + const result = scope === undefined + ? (await this.collectHits(query, workspace, projectId)).slice(0, limit) + : await this.scopedStore(scope, workspace).search(query, limit); const sources = {}; for (const hit of result) sources[hit.record.scope] = (sources[hit.record.scope] ?? 0) + 1; - this.loggerOf?.log({ event: 'memory.search', scope: 'project', workspace: this.workspacePath(workspace), detail: { query, k: limit, hits: result.length, sources, durationMs: Date.now() - startedAt } }); + this.loggerOf?.log({ event: 'memory.search', scope: scope ?? 'project', workspace: scope === 'global' ? undefined : this.workspacePath(workspace), detail: { query, k: limit, hits: result.length, sources, durationMs: Date.now() - startedAt } }); return result; } async search(query, k = this.settingsOf().localMemoryK ?? 5, workspace, projectId) { return (await this.searchHits(query, k, workspace, projectId)).map((hit) => hit.record); } async list(options = {}, workspace, projectId) { + if (options.scope !== undefined) + return this.scopedStore(options.scope, workspace).list(options); const projectStore = await this.ensureProject(workspace); const records = [...(await this.globalStore.records()), ...(await projectStore.records())]; const scoped = records.filter((record) => { @@ -283,19 +289,24 @@ export class LocalMemoryManager { const limit = Math.max(1, Math.min(1000, Math.trunc(options.limit ?? 50))); return { items: ordered.slice(offset, offset + limit), total: ordered.length }; } - async forget(id, expectedRevision, workspace) { - const globalRecord = await this.globalStore.read(id); - await this.markProjectionDirty(); - if (globalRecord !== undefined) { - const removed = await this.globalStore.forget(id, expectedRevision); - await this.tryRegenerateProjections(); - this.loggerOf?.log({ event: 'memory.forget', scope: 'global', detail: { recordId: id, revision: removed.revision } }); - return removed; + async forget(id, expectedRevision, workspace, scope) { + const targetScope = scope ?? ((await this.globalStore.read(id)) === undefined ? 'project' : 'global'); + const scopedStore = scope === undefined ? undefined : this.scopedStore(scope, workspace); + if (scopedStore !== undefined) { + const record = await scopedStore.read(id); + if (record === undefined) + throw new Error('memory_not_found'); + if (expectedRevision !== undefined && record.revision !== expectedRevision) + throw new Error('revision_conflict'); } - const store = await this.ensureProject(workspace); + // The runtime projections are built exclusively from the global store. + if (scope !== 'project') + await this.markProjectionDirty(); + const store = scopedStore ?? await this.storeFor(targetScope, workspace); const removed = await store.forget(id, expectedRevision); - await this.tryRegenerateProjections(); - this.loggerOf?.log({ event: 'memory.forget', scope: 'project', workspace: this.workspacePath(workspace), detail: { recordId: id, revision: removed.revision } }); + if (scope !== 'project') + await this.tryRegenerateProjections(); + this.loggerOf?.log({ event: 'memory.forget', scope: targetScope, workspace: targetScope === 'project' ? this.workspacePath(workspace) : undefined, detail: { recordId: id, revision: removed.revision } }); return removed; } async projects(workspace) { @@ -317,11 +328,21 @@ export class LocalMemoryManager { throw new Error('local_documents_unavailable'); return documents.add(input); } - async storageStatus(workspace) { - const projectRoot = this.projectRootFor(workspace); - const global = await this.globalStore.spaceMeta(); - const project = await this.projectStoreFor(workspace).spaceMeta(); - return { provider: 'local', globalRoot: this.globalRoot, projectRoot, spaces: { global: global ?? null, project: project ?? null }, cloudSyncEnabled: this.settingsOf().cloudMemoryEnabled === true, localMemoryEnabled: this.settingsOf().localMemoryEnabled !== false }; + async storageStatus(workspace, scope) { + const projectRoot = scope === 'global' ? undefined : this.projectRootFor(workspace); + const global = scope === 'project' ? undefined : await this.globalStore.spaceMeta(); + const project = scope === 'global' ? undefined : await this.projectStoreFor(workspace).spaceMeta(); + return { + provider: 'local', + ...(scope === 'project' ? {} : { globalRoot: this.globalRoot }), + ...(projectRoot === undefined ? {} : { projectRoot }), + spaces: { + ...(scope === 'project' ? {} : { global: global ?? null }), + ...(scope === 'global' ? {} : { project: project ?? null }), + }, + cloudSyncEnabled: this.settingsOf().cloudMemoryEnabled === true, + localMemoryEnabled: this.settingsOf().localMemoryEnabled !== false, + }; } /** Return the compact per-turn projection used by the system prompt. */ projectionText(limit = 2000) { diff --git a/lib/routes.js b/lib/routes.js index 873abdb..8ed7eca 100644 --- a/lib/routes.js +++ b/lib/routes.js @@ -168,12 +168,28 @@ async function serveLocalMemory(deps, req, res) { const marker = '/local-memory'; const markerAt = url.pathname.indexOf(marker); const suffix = markerAt < 0 ? '' : url.pathname.slice(markerAt + marker.length); - if (suffix === '' || suffix === '/' || suffix === '/status') { + if (suffix === '' || suffix === '/' || suffix === '/status' || suffix === '/memories') { if (req.method !== 'GET') { fail(res, 405, 'method-not-allowed'); return; } - json(res, 200, { ok: true, ...(await manager.storageStatus(workspace)) }); + const scope = url.searchParams.get('scope') ?? undefined; + if (scope !== undefined && scope !== 'global' && scope !== 'project') { + fail(res, 400, 'invalid-scope'); + return; + } + if (scope === 'project' && workspace === undefined) { + fail(res, 400, 'workspace-required'); + return; + } + if (suffix !== '/memories') { + json(res, 200, { ok: true, ...(await manager.storageStatus(workspace, scope)) }); + return; + } + const limit = Math.max(1, Math.min(1000, Number.parseInt(url.searchParams.get('limit') ?? '50', 10) || 50)); + const offset = Math.max(0, Number.parseInt(url.searchParams.get('offset') ?? '0', 10) || 0); + const page = await manager.list({ limit, offset, scope }, workspace); + json(res, 200, { ok: true, total: page.total, items: page.items.map((record) => ({ id: record.id, scope: record.scope, content: record.content, category: record.category, tags: record.tags, source: record.source, revision: record.revision, updatedAt: record.updatedAt })) }); return; } if (suffix === '/spaces') { @@ -189,18 +205,16 @@ async function serveLocalMemory(deps, req, res) { fail(res, 405, 'method-not-allowed'); return; } - json(res, 200, { ok: true, documents: await manager.documents(workspace) }); - return; - } - if (suffix === '/memories') { - if (req.method !== 'GET') { - fail(res, 405, 'method-not-allowed'); + const scope = url.searchParams.get('scope'); + if (scope !== null && scope !== 'project') { + fail(res, 400, 'invalid-scope'); return; } - const limit = Math.max(1, Math.min(1000, Number.parseInt(url.searchParams.get('limit') ?? '50', 10) || 50)); - const offset = Math.max(0, Number.parseInt(url.searchParams.get('offset') ?? '0', 10) || 0); - const page = await manager.list({ limit, offset }, workspace); - json(res, 200, { ok: true, total: page.total, items: page.items.map((record) => ({ id: record.id, scope: record.scope, content: record.content, category: record.category, tags: record.tags, source: record.source, revision: record.revision, updatedAt: record.updatedAt })) }); + if (scope === 'project' && workspace === undefined) { + fail(res, 400, 'workspace-required'); + return; + } + json(res, 200, { ok: true, documents: await manager.documents(workspace) }); return; } if (suffix === '/forget') { @@ -232,7 +246,31 @@ async function serveLocalMemory(deps, req, res) { } const expectedRevision = typeof input.expectedRevision === 'number' && Number.isFinite(input.expectedRevision) ? Math.trunc(input.expectedRevision) : undefined; const targetWorkspace = typeof input.workspace === 'string' ? input.workspace.trim() || undefined : undefined; - json(res, 200, { ok: true, record: await manager.forget(id, expectedRevision, targetWorkspace) }); + const scope = input.scope; + if (scope !== undefined && scope !== 'global' && scope !== 'project') { + fail(res, 400, 'invalid-scope'); + return; + } + if (scope === 'project' && targetWorkspace === undefined) { + fail(res, 400, 'workspace-required'); + return; + } + try { + json(res, 200, { ok: true, record: await manager.forget(id, expectedRevision, targetWorkspace, scope) }); + } + catch (error) { + if (scope === undefined || !(error instanceof Error)) + throw error; + if (error.message === 'memory_not_found') { + fail(res, 404, error.message); + return; + } + if (error.message === 'revision_conflict') { + fail(res, 409, error.message); + return; + } + throw error; + } return; } if (suffix === '/search') { diff --git a/lib/settings-ui/departments-routes.js b/lib/settings-ui/departments-routes.js index 596ec45..2ccf767 100644 --- a/lib/settings-ui/departments-routes.js +++ b/lib/settings-ui/departments-routes.js @@ -7,6 +7,8 @@ function errorStatus(message) { return 409; if (message === 'department_disabled') return 409; + if (message === 'invalid-scope' || message === 'workspace-required') + return 400; if (message === 'department_required_field' || message === 'department_invalid_host' || message === 'secret_not_allowed') return 400; return undefined; @@ -37,6 +39,15 @@ async function bodyObject(req, res) { } function stringField(value) { return typeof value === 'string' ? value : undefined; } function revisionField(value) { return typeof value === 'number' && Number.isFinite(value) ? Math.trunc(value) : undefined; } +function requestScope(value, workspace) { + if (value === undefined) + return undefined; + if (value !== 'global' && value !== 'project') + throw new Error('invalid-scope'); + if (value === 'project' && workspace === undefined) + throw new Error('workspace-required'); + return value; +} export async function serveDepartments(deps, req, res) { const manager = deps.departments; if (manager === undefined) { @@ -48,6 +59,7 @@ export async function serveDepartments(deps, req, res) { return; } const withWorkspace = (workspace, job) => deps.localMemory === undefined ? job() : deps.localMemory.withWorkspace(workspace, job); + const withScope = (scope, workspace, job) => scope === undefined ? withWorkspace(workspace, job) : manager.memory.withWorkspace(scope === 'project' ? workspace : undefined, job); const url = new URL(req.url ?? '/', 'http://localhost'); const marker = '/departments'; const at = url.pathname.indexOf(marker); @@ -112,6 +124,7 @@ export async function serveDepartments(deps, req, res) { return; } const expectedRevision = revisionField(body.expectedRevision); + const scope = suffix === '/resume' ? undefined : requestScope(body.scope, workspace); if (suffix === '/update') { const patch = { ...(stringField(body.name) === undefined ? {} : { name: stringField(body.name) }), @@ -121,11 +134,11 @@ export async function serveDepartments(deps, req, res) { ...(typeof body.readGlobal === 'boolean' ? { readGlobal: body.readGlobal } : {}), ...(typeof body.readProject === 'boolean' ? { readProject: body.readProject } : {}), }; - json(res, 200, { ok: true, department: await withWorkspace(workspace, () => manager.update(id, patch, expectedRevision)) }); + json(res, 200, { ok: true, department: await withScope(scope, workspace, () => manager.update(id, patch, expectedRevision, scope)) }); return; } if (suffix === '/disable') { - json(res, 200, { ok: true, department: await withWorkspace(workspace, () => manager.disable(id, expectedRevision)) }); + json(res, 200, { ok: true, department: await withScope(scope, workspace, () => manager.disable(id, expectedRevision, scope)) }); return; } if (suffix === '/checkpoint') { @@ -133,7 +146,7 @@ export async function serveDepartments(deps, req, res) { ...(stringField(body.currentTask) === undefined ? {} : { currentTask: stringField(body.currentTask) }), ...(stringField(body.handoff) === undefined ? {} : { handoff: stringField(body.handoff) }), }; - json(res, 200, { ok: true, department: await withWorkspace(workspace, () => manager.checkpoint(id, input, expectedRevision)) }); + json(res, 200, { ok: true, department: await withScope(scope, workspace, () => manager.checkpoint(id, input, expectedRevision, scope)) }); return; } const host = stringField(body.host)?.trim() || 'dsh'; @@ -158,7 +171,8 @@ export async function serveDepartments(deps, req, res) { const requested = Number.parseInt(url.searchParams.get('k') ?? '5', 10); const k = Number.isFinite(requested) ? Math.max(1, Math.min(5, requested)) : 5; const workspace = url.searchParams.get('workspace')?.trim() || undefined; - const hits = await withWorkspace(workspace, () => manager.recall(id, query, k, workspace)); + const scope = requestScope(url.searchParams.get('scope') ?? undefined, workspace); + const hits = await withScope(scope, workspace, () => manager.recall(id, query, k, workspace, scope)); json(res, 200, { ok: true, hits: hits.map((hit) => ({ ...hit, content: hit.record.content, contentSnippet: departmentSnippet(hit.record.content) })) }); return; } diff --git a/src-client/SettingsSummaryCard.tsx b/src-client/SettingsSummaryCard.tsx deleted file mode 100644 index 1192afa..0000000 --- a/src-client/SettingsSummaryCard.tsx +++ /dev/null @@ -1,64 +0,0 @@ -// Slim settings card: status summary + a jump into the Brain total panel. -import * as React from 'react' -import { API, request, messageOf } from './api' -import { styles } from './styles' -import { Pill, Banner, Btn } from './components' - -const h = React.createElement - -export function SettingsSummaryCard(props: { ctx?: any }): any { - const [status, setStatus] = React.useState(null) - const [error, setError] = React.useState(null) - - React.useEffect(() => { - let cancelled = false - const load = (): void => { - request(API.status).then( - (result) => { - if (cancelled) return - if (result.status === 200 && result.body !== null && result.body.ok === true) { - setStatus(result.body) - setError(null) - } else { - setError('读取状态失败(HTTP ' + String(result.status) + ')') - } - }, - (failure) => { if (!cancelled) setError(messageOf(failure)) }, - ) - } - load() - const timer = setInterval(load, 15000) - return () => { - cancelled = true - clearInterval(timer) - } - }, []) - - function openPanel(): void { - const ctx = props.ctx - const layout = ctx === undefined || ctx === null ? undefined : ctx.layout - if (layout !== undefined && layout !== null && typeof layout.selectPanel === 'function') { - layout.selectPanel('dsh-brain') - return - } - if (typeof window !== 'undefined' && typeof window.open === 'function') window.open('/dsh-brain') - } - - const settings = status?.settings ?? {} - return h('div', { style: styles.root, 'data-dsh-plugin': 'dsh-brain' }, - h('div', { style: styles.sectionHead }, - h('h4', { style: styles.sectionTitle }, '云端记忆'), - h('div', { style: styles.actions }, - h(Btn, { variant: 'primary', label: '打开总面板', onClick: openPanel }), - ), - ), - h('p', { style: styles.hint }, '设置与连接内容已收进左侧栏 Brain 总面板的「连接与上报」页签。这里保留状态摘要和快捷入口。'), - error === null ? null : h(Banner, { tone: 'bad' }, error), - status === null ? h('p', { style: styles.hint }, '正在读取状态…') : h('div', { style: styles.pills }, - h(Pill, { label: '服务', value: settings.baseUrlConfigured === false ? '未配置' : '已配置', tone: settings.baseUrlConfigured === false ? 'warn' : 'ok' }), - h(Pill, { label: '上报', value: settings.activityEnabled === true ? '开' : '关', tone: settings.activityEnabled === true ? 'ok' : 'muted' }), - h(Pill, { label: '记忆', value: settings.memoryEnabled === true ? '开' : '关', tone: settings.memoryEnabled === true ? 'ok' : 'muted' }), - h(Pill, { label: '本地记忆', value: settings.localMemoryEnabled === false ? '关' : '开', tone: settings.localMemoryEnabled === false ? 'muted' : 'ok' }), - ), - ) -} diff --git a/src-client/index.ts b/src-client/index.ts index 21718a9..90df7af 100644 --- a/src-client/index.ts +++ b/src-client/index.ts @@ -3,7 +3,6 @@ import * as React from 'react' import { messageOf } from './api' import { CardBoundary } from './components' import { SettingsCard } from './SettingsCard' -import { SettingsSummaryCard } from './SettingsSummaryCard' import { registerBrainPanel } from './panel/register' import { mountBrainSidebarTab } from './sidebar/register' @@ -12,11 +11,6 @@ const h = React.createElement export const inject = ['slots'] export function apply(ctx: any): void { - const summaryCard = function () { - return h(CardBoundary as any, null, h(SettingsSummaryCard as any, { ctx })) - } - // The plugin bundle config page keeps the full settings card; the generic - // settings section is now only the status summary with a jump button. const configCard = function () { return h(CardBoundary as any, null, h(SettingsCard as any, null)) } @@ -40,7 +34,7 @@ export function apply(ctx: any): void { label: function () { return '云端记忆' }, - }, summaryCard) + }, configCard) try { if (typeof ctx.effect === 'function') ctx.effect(() => registerBrainPanel(ctx), 'dsh-brain: panel') diff --git a/src-client/panel/BrainPanel.module.css b/src-client/panel/BrainPanel.module.css index e044d8d..c907154 100644 --- a/src-client/panel/BrainPanel.module.css +++ b/src-client/panel/BrainPanel.module.css @@ -101,29 +101,6 @@ min-width: 0; } -.placeholder { - display: flex; - flex-direction: column; - align-items: center; - justify-content: center; - gap: 8px; - padding: 48px 16px; - border: 1px dashed var(--dsw-alias-border-subtle, rgba(127,127,127,0.30)); - border-radius: 16px; - opacity: 0.65; -} - -.placeholderTitle { - margin: 0; - font-size: 14px; - font-weight: 600; -} - -.placeholderHint { - margin: 0; - font-size: 12px; -} - .overviewGrid { display: flex; flex-direction: column; diff --git a/src-client/panel/BrainPanel.tsx b/src-client/panel/BrainPanel.tsx index 6a25d8f..28a6abc 100644 --- a/src-client/panel/BrainPanel.tsx +++ b/src-client/panel/BrainPanel.tsx @@ -3,8 +3,6 @@ import * as React from 'react' import { Overview } from './Overview' import { MemoryTab } from './MemoryTab' import { DepartmentTab } from './DepartmentTab' -import { resolveWorkspace } from './workspace' -import { SettingsCard } from '../SettingsCard' import styles from './BrainPanel.module.css' const h = React.createElement @@ -13,40 +11,24 @@ const TABS = [ { id: 'overview', label: '概览' }, { id: 'memory', label: '记忆' }, { id: 'departments', label: '部门' }, - { id: 'skills', label: '技能' }, - { id: 'mcp', label: 'MCP' }, - { id: 'connection', label: '连接与上报' }, ] as const -function Placeholder(props: { title: string }): any { - return h('div', { className: styles.placeholder }, - h('h3', { className: styles.placeholderTitle }, props.title), - h('p', { className: styles.placeholderHint }, '即将上线'), - ) -} - -export function BrainPanel(props: { ctx?: any; panelId?: string; usePanelInfo?: any }): any { +export function BrainPanel(props: { panelId?: string; usePanelInfo?: any }): any { const [tab, setTab] = React.useState('overview') const panelId = props.panelId ?? 'dsh-brain' const usePanelInfo = props.usePanelInfo const active = usePanelInfo === undefined ? true : usePanelInfo((info: { activePanelId: string | null }) => info.activePanelId === panelId) let content: any if (tab === 'overview') content = h(Overview, { active }) - else if (tab === 'connection') content = h(SettingsCard, null) - else if (tab === 'memory') { - const workspace = resolveWorkspace(props.ctx) - content = h(MemoryTab, { key: workspace ?? '', workspace, active }) - } - else if (tab === 'departments') content = h(DepartmentTab, { ctx: props.ctx, active }) - else if (tab === 'skills') content = h(Placeholder, { title: '技能' }) - else content = h(Placeholder, { title: 'MCP' }) + else if (tab === 'memory') content = h(MemoryTab, { scope: 'global', active }) + else content = h(DepartmentTab, { scope: 'global', active }) return h('div', { className: styles.nativeWorkspace, 'data-dsh-plugin': 'dsh-brain', 'data-dsh-part': 'brain-panel' }, h('div', { className: styles.windowDragBand, 'data-window-drag': true, 'aria-hidden': 'true' }), h('div', { className: styles.panelInner }, h('div', { className: styles.header }, h('div', { className: styles.titleBlock }, h('h3', { className: styles.title }, 'Brain'), - h('p', { className: styles.subtitle }, '本地记忆、部门与连接的总面板'), + h('p', { className: styles.subtitle }, '全局记忆、部门与运行状态'), ), ), h('div', { className: styles.tabBar, role: 'tablist', 'aria-label': 'Brain 面板页签' }, diff --git a/src-client/panel/DepartmentTab.tsx b/src-client/panel/DepartmentTab.tsx index fcfbdab..349e00f 100644 --- a/src-client/panel/DepartmentTab.tsx +++ b/src-client/panel/DepartmentTab.tsx @@ -5,11 +5,11 @@ import { formatIso } from '../format' import { styles } from '../styles' import { Banner, Btn, Field, Pill, Section } from '../components' import { useApi } from './useApi' -import { resolveWorkspace, workspaceQuery } from './workspace' +import { scopeParams, type BrainScope } from './workspace' const h = React.createElement -const EMPTY_CREATE = { name: '', role: '', scope: 'project', skills: '', allowedTools: '', readGlobal: true, readProject: true } +const EMPTY_CREATE = { name: '', role: '', skills: '', allowedTools: '', readGlobal: true, readProject: true } const ENDPOINTS = { list: '/dsh-brain/departments/list', @@ -20,9 +20,10 @@ const ENDPOINTS = { recall: '/dsh-brain/departments/recall', } as const -export function DepartmentTab(props: { ctx?: any; active?: boolean }): any { +export function DepartmentTab(props: BrainScope & { active?: boolean }): any { const active = props.active !== false - const workspace = resolveWorkspace(props.ctx) + const scope = scopeParams(props) + const scopeLabel = props.scope === 'global' ? '全局' : '项目' const [notice, setNotice] = React.useState(null) const [busy, setBusy] = React.useState('') const [form, setForm] = React.useState({ ...EMPTY_CREATE }) @@ -35,7 +36,7 @@ export function DepartmentTab(props: { ctx?: any; active?: boolean }): any { const [recallBusy, setRecallBusy] = React.useState(false) const list = useApi(async () => { - const result = await request(ENDPOINTS.list + workspaceQuery(workspace)) + const result = await request(ENDPOINTS.list + '?' + scope.toString()) if (result.status !== 200 || result.body === null || result.body.ok !== true) throw new Error(bodyError(result, '读取部门列表失败')) return result.body }, { visible: active, pollMs: 15000 }) @@ -66,12 +67,11 @@ export function DepartmentTab(props: { ctx?: any; active?: boolean }): any { const result = await postJson(ENDPOINTS.create, { name: String(form.name).trim(), role: String(form.role).trim() || undefined, - scope: form.scope, skills: String(form.skills).split(/[,,\s]+/).filter((value) => value !== ''), allowedTools: String(form.allowedTools).split(/[,,\s]+/).filter((value) => value !== ''), readGlobal: form.readGlobal === true, readProject: form.readProject === true, - workspace, + ...Object.fromEntries(scope), }) if (result.status !== 200 || result.body === null || result.body.ok !== true) { handleFailure(result, '创建部门失败'); return } setNotice({ tone: 'ok', text: result.body.created === false ? '同名部门已存在,已复用。' : '部门已创建。' }) @@ -87,7 +87,7 @@ export function DepartmentTab(props: { ctx?: any; active?: boolean }): any { const mutate = async (action: 'update' | 'disable' | 'checkpoint'): Promise => { if (selected === undefined) return setBusy(action) - const payload: any = { id: selected.id, expectedRevision: selected.revision, workspace } + const payload: any = { id: selected.id, expectedRevision: selected.revision, ...Object.fromEntries(scope) } if (action === 'update') { payload.role = detail.role; payload.name = selected.name } if (action === 'checkpoint') { payload.currentTask = detail.currentTask; payload.handoff = detail.handoff } try { @@ -107,7 +107,7 @@ export function DepartmentTab(props: { ctx?: any; active?: boolean }): any { setRecallBusy(true) setRecallHits([]) try { - const query = ENDPOINTS.recall + '?id=' + encodeURIComponent(recallId) + '&query=' + encodeURIComponent(recallQuery) + '&k=' + encodeURIComponent(recallK) + (workspace === undefined ? '' : '&workspace=' + encodeURIComponent(workspace)) + const query = ENDPOINTS.recall + '?id=' + encodeURIComponent(recallId) + '&query=' + encodeURIComponent(recallQuery) + '&k=' + encodeURIComponent(recallK) + '&' + scope.toString() const result = await request(query) if (result.status !== 200 || result.body === null || result.body.ok !== true) { handleFailure(result, '召回失败'); return } setRecallHits(Array.isArray(result.body.hits) ? result.body.hits : []) @@ -121,7 +121,7 @@ export function DepartmentTab(props: { ctx?: any; active?: boolean }): any { return h('div', { style: { display: 'flex', flexDirection: 'column', gap: '12px' } }, notice === null ? null : h(Banner, { tone: notice.tone }, notice.text), list.error === null ? null : h(Banner, { tone: 'bad' }, list.error), - h(Section, { title: '部门列表', hint: '部门是本机可复用的工作身份;列表显示 scope、状态、当前任务与 revision。', aside: h(Btn, { label: '刷新', variant: 'small', onClick: () => list.reload() }) }, + h(Section, { title: scopeLabel + '部门列表', aside: h(Btn, { label: '刷新', variant: 'small', onClick: () => list.reload() }) }, departments.length === 0 ? h('p', { style: styles.hint }, '还没有部门。可在下方创建。') : h('div', { style: { display: 'flex', flexDirection: 'column', gap: '8px' } }, departments.map((item) => h('div', { key: item.id, style: styles.row }, h('div', { style: styles.rowHead }, @@ -152,17 +152,10 @@ export function DepartmentTab(props: { ctx?: any; active?: boolean }): any { )), ), ), - h(Section, { title: '创建部门', hint: '同名部门会幂等复用,不会覆盖原角色。' }, + h(Section, { title: '创建' + scopeLabel + '部门', hint: '同名部门会幂等复用,不会覆盖原角色。' }, h('div', { style: styles.grid }, h(Field, { label: '名称', value: form.name, onChange: (value) => setForm({ ...form, name: value }) }), h(Field, { label: '角色', value: form.role, onChange: (value) => setForm({ ...form, role: value }) }), - h('div', { style: styles.field }, - h('span', { style: styles.label }, '范围'), - h('select', { value: form.scope, style: styles.input, onChange: (event) => setForm({ ...form, scope: event.target.value }) }, - h('option', { value: 'project' }, '项目'), - h('option', { value: 'global' }, '全局'), - ), - ), h(Field, { label: '技能(逗号分隔)', value: form.skills, onChange: (value) => setForm({ ...form, skills: value }) }), h(Field, { label: '允许工具(逗号分隔)', value: form.allowedTools, onChange: (value) => setForm({ ...form, allowedTools: value }) }), ), diff --git a/src-client/panel/MemoryTab.tsx b/src-client/panel/MemoryTab.tsx index eca1358..b658060 100644 --- a/src-client/panel/MemoryTab.tsx +++ b/src-client/panel/MemoryTab.tsx @@ -1,22 +1,20 @@ // Memory tab: local-memory spaces, paged memory list, read-only documents, forget. import * as React from 'react' -import { API, request, postJson, bodyError, messageOf } from '../api' -import { formatIso, formatTime } from '../format' +import { request, postJson, bodyError, messageOf } from '../api' +import { formatIso } from '../format' import { styles } from '../styles' import { Banner, Btn, Field, Pill, Section } from '../components' import { useApi } from './useApi' -import { workspaceQuery } from './workspace' +import { scopeParams, type BrainScope } from './workspace' const h = React.createElement const PAGE_SIZE = 50 -function workspaceSuffix(workspace: string | undefined): string { - return workspace === undefined ? '' : '&workspace=' + encodeURIComponent(workspace) -} - -export function MemoryTab(props: { workspace?: string; active?: boolean }): any { +export function MemoryTab(props: BrainScope & { active?: boolean }): any { const active = props.active !== false - const workspace = props.workspace + const project = props.scope === 'project' + const scope = scopeParams(props) + const scopeLabel = project ? '项目' : '全局' const [offset, setOffset] = React.useState(0) const [search, setSearch] = React.useState('') const [notice, setNotice] = React.useState(null) @@ -24,22 +22,22 @@ export function MemoryTab(props: { workspace?: string; active?: boolean }): any const [busy, setBusy] = React.useState('') const status = useApi(async () => { - const result = await request('/dsh-brain/local-memory/status' + workspaceQuery(workspace)) + const result = await request('/dsh-brain/local-memory/status' + '?' + scope.toString()) if (result.status !== 200 || result.body === null || result.body.ok !== true) throw new Error(bodyError(result, '读取本地记忆状态失败')) return result.body }, { visible: active, pollMs: 15000 }) const memories = useApi(async () => { - const result = await request('/dsh-brain/local-memory/memories?limit=' + String(PAGE_SIZE) + '&offset=' + String(offset) + workspaceSuffix(workspace)) + const result = await request('/dsh-brain/local-memory/memories?limit=' + String(PAGE_SIZE) + '&offset=' + String(offset) + '&' + scope.toString()) if (result.status !== 200 || result.body === null || result.body.ok !== true) throw new Error(bodyError(result, '读取记忆列表失败')) return result.body - }, { visible: active, deps: [offset] }) + }, { visible: active, pollMs: project ? 30000 : undefined, deps: [offset] }) const documents = useApi(async () => { - const result = await request('/dsh-brain/local-memory/documents' + workspaceQuery(workspace)) + const result = await request('/dsh-brain/local-memory/documents' + '?' + scope.toString()) if (result.status !== 200 || result.body === null || result.body.ok !== true) throw new Error(bodyError(result, '读取文档列表失败')) return result.body - }, { visible: active }) + }, { visible: active && project }) const items: any[] = Array.isArray(memories.data?.items) ? memories.data!.items : [] const needle = String(search).trim().toLowerCase() @@ -52,7 +50,7 @@ export function MemoryTab(props: { workspace?: string; active?: boolean }): any const forget = async (item: any): Promise => { setBusy(item.id) try { - const result = await postJson('/dsh-brain/local-memory/forget', { id: item.id, expectedRevision: item.revision, workspace }) + const result = await postJson('/dsh-brain/local-memory/forget', { id: item.id, expectedRevision: item.revision, ...Object.fromEntries(scope) }) if (result.status !== 200 || result.body === null || result.body.ok !== true) { setNotice({ tone: 'bad', text: bodyError(result, '删除失败') }) } else { @@ -67,21 +65,14 @@ export function MemoryTab(props: { workspace?: string; active?: boolean }): any } } - const spaces = status.data?.spaces ?? {} - const globalSpace = spaces.global - const projectSpace = spaces.project + const space = status.data?.spaces?.[props.scope] + const root = project ? status.data?.projectRoot : status.data?.globalRoot return h('div', { style: { display: 'flex', flexDirection: 'column', gap: '12px' } }, status.error === null ? null : h(Banner, { tone: 'bad' }, status.error), - h(Section, { title: '本地记忆空间', hint: '全局空间与当前项目空间都由本机文件保存;云同步只影响上报,不改变本地存储。', aside: h(Btn, { label: '刷新', variant: 'small', onClick: () => { status.reload(); memories.reload(); documents.reload() } }) }, - h('div', { style: styles.pills }, - h(Pill, { label: 'provider', value: status.data?.provider ?? '—', tone: 'muted' }), - h(Pill, { label: '全局空间', value: globalSpace === null || globalSpace === undefined ? '未创建' : (globalSpace.name ?? globalSpace.id ?? '就绪'), tone: globalSpace === null || globalSpace === undefined ? 'muted' : 'ok' }), - h(Pill, { label: '项目空间', value: projectSpace === null || projectSpace === undefined ? '未创建' : (projectSpace.name ?? projectSpace.id ?? '就绪'), tone: projectSpace === null || projectSpace === undefined ? 'muted' : 'ok' }), - h(Pill, { label: '本地记忆', value: status.data?.localMemoryEnabled === false ? '关' : '开', tone: status.data?.localMemoryEnabled === false ? 'bad' : 'ok' }), - h(Pill, { label: '云同步', value: status.data?.cloudSyncEnabled === true ? '开' : '关', tone: status.data?.cloudSyncEnabled === true ? 'ok' : 'muted' }), - ), - status.data?.globalRoot === undefined ? null : h('p', { style: styles.hint }, '全局:' + String(status.data.globalRoot) + (status.data?.projectRoot === undefined ? '' : ' · 项目:' + String(status.data.projectRoot))), + h(Section, { title: scopeLabel + '记忆空间', aside: h(Btn, { label: '刷新', variant: 'small', onClick: () => { status.reload(); memories.reload(); if (project) documents.reload() } }) }, + h(Pill, { label: '空间状态', value: status.status === 'loading' ? '读取中' : space?.name ?? (space ? '就绪' : '未创建'), tone: space ? 'ok' : 'muted' }), + root === undefined ? null : h('p', { style: styles.hint }, String(root)), ), h(Section, { title: '记忆条目(' + String(total) + ')', hint: '只显示当前页;搜索只在当前页内过滤。删除需要二次确认并带 revision 校验。', aside: h('div', { style: styles.actions }, h(Field, { label: '搜索当前页', value: search, onChange: setSearch }), @@ -120,7 +111,7 @@ export function MemoryTab(props: { workspace?: string; active?: boolean }): any h(Btn, { label: '下一页', variant: 'small', disabled: offset + PAGE_SIZE >= total || memories.status === 'loading', onClick: () => setOffset(offset + PAGE_SIZE) }), ), ), - h(Section, { title: '文档(只读)', hint: '项目文档由本地记忆库维护;这里只展示标题与摘要。' }, + project ? h(Section, { title: '文档(只读)', hint: '项目文档由本地记忆库维护;这里只展示标题与摘要。' }, documents.error === null ? null : h(Banner, { tone: 'bad' }, documents.error), (documents.data?.documents ?? []).length === 0 ? h('p', { style: styles.hint }, '当前项目还没有文档。') : h('div', { style: { display: 'flex', flexDirection: 'column', gap: '8px' } }, (documents.data?.documents ?? []).map((doc: any) => h('div', { key: doc.id, style: styles.row }, @@ -134,6 +125,6 @@ export function MemoryTab(props: { workspace?: string; active?: boolean }): any h('div', { style: styles.clamp2 }, String(doc.content ?? '')), )), ), - ), + ) : null, ) } diff --git a/src-client/panel/Overview.tsx b/src-client/panel/Overview.tsx index 0906466..0d50095 100644 --- a/src-client/panel/Overview.tsx +++ b/src-client/panel/Overview.tsx @@ -45,7 +45,7 @@ export function Overview(props: { active?: boolean }): any { const [statusResult, capabilitiesResult, memoryResult] = await Promise.all([ request(API.status), request(API.capabilities), - request('/dsh-brain/local-memory/status'), + request('/dsh-brain/local-memory/status?scope=global'), ]) if (cancelled) return if (statusResult.status === 200 && statusResult.body !== null && statusResult.body.ok === true) { @@ -87,7 +87,7 @@ export function Overview(props: { active?: boolean }): any { h(Pill, { label: '记忆', value: settings.memoryEnabled === true ? '开' : '关', tone: settings.memoryEnabled === true ? 'ok' : 'muted' }), h(Pill, { label: '诊断日志', value: settings.diagnosticsEnabled === false ? '关' : '开', tone: settings.diagnosticsEnabled === false ? 'muted' : 'ok' }), ), - h('p', { className: styles.hint }, '诊断日志位置:$DSH_HOME/brain/logs(全局)与 <项目>/.dsh/brain/logs(项目)'), + h('p', { className: styles.hint }, '全局诊断日志:$DSH_HOME/brain/logs'), status?.lastCheck === null || status?.lastCheck === undefined ? null : h('p', { className: styles.hint }, '最近检查:' + formatTime(status.lastCheck.at) + ' · ' + String(status.lastCheck.status ?? '')), ), h(Card, { title: '五个 bundle 开关态' }, @@ -99,7 +99,6 @@ export function Overview(props: { active?: boolean }): any { h('div', { className: styles.pills }, h(Pill, { label: '状态', value: memory === null ? '不可用' : '已启用', tone: memory === null ? 'warn' : 'ok' }), h(Pill, { label: '全局空间', value: memorySpaces.global === null || memorySpaces.global === undefined ? '未创建' : '就绪', tone: memorySpaces.global === null || memorySpaces.global === undefined ? 'muted' : 'ok' }), - h(Pill, { label: '项目空间', value: memorySpaces.project === null || memorySpaces.project === undefined ? '未创建' : '就绪', tone: memorySpaces.project === null || memorySpaces.project === undefined ? 'muted' : 'ok' }), h(Pill, { label: '云同步', value: memory?.cloudSyncEnabled === true ? '开' : '关', tone: memory?.cloudSyncEnabled === true ? 'ok' : 'muted' }), ), memory === null ? h('p', { className: styles.hint }, '本地记忆状态路由不可用;启用「本地记忆」后此处会显示空间状态。') : null, diff --git a/src-client/panel/register.ts b/src-client/panel/register.ts index 17abe55..18481a1 100644 --- a/src-client/panel/register.ts +++ b/src-client/panel/register.ts @@ -44,7 +44,7 @@ export function registerBrainPanel(ctx: any): () => void { stopNative = ctx.slots.inject('main', () => ctx.slots.inject('sidebar.panellist', () => { const usePanelInfo = makeUsePanelInfo(ctx, PANEL_ID) - const panel = (props: any) => React.createElement(BrainPanel, { ...props, ctx, panelId: PANEL_ID, usePanelInfo }) + const panel = (props: any) => React.createElement(BrainPanel, { ...props, panelId: PANEL_ID, usePanelInfo }) const icon = (props: any) => React.createElement(BrainIcon, { size: props?.size ?? 18 }) const stopMain = ctx.slots.register({ name: 'main', key: PANEL_ID, inject: () => ({ panelId: PANEL_ID }) }, panel as never) let stopIcon: (() => void) | undefined diff --git a/src-client/panel/workspace.ts b/src-client/panel/workspace.ts index 496f307..26c8c59 100644 --- a/src-client/panel/workspace.ts +++ b/src-client/panel/workspace.ts @@ -1,26 +1,7 @@ -// Resolve the active session workspace from the optional host sessions face. -// The probe is deliberately defensive: the panel must work without the service. -export function resolveWorkspace(ctx: any): string | undefined { - try { - const sessions = ctx !== undefined && ctx !== null && typeof ctx.get === 'function' ? ctx.get('sessions') : undefined - if (sessions === undefined || sessions === null) return undefined - const current = typeof sessions.current === 'function' ? sessions.current() : sessions.current - const candidates = [ - current?.cwd, - current?.header?.cwd, - current?.session?.cwd, - current?.session?.header?.cwd, - typeof sessions.cwd === 'function' ? sessions.cwd() : undefined, - ] - for (const candidate of candidates) { - if (typeof candidate === 'string' && candidate.trim() !== '') return candidate - } - } catch { - /* no sessions face -> omit the workspace argument */ - } - return undefined -} +export type BrainScope = { scope: 'global' } | { scope: 'project'; workspace: string } -export function workspaceQuery(workspace: string | undefined): string { - return workspace === undefined ? '' : '?workspace=' + encodeURIComponent(workspace) +export function scopeParams(scope: BrainScope): URLSearchParams { + const params = new URLSearchParams({ scope: scope.scope }) + if (scope.scope === 'project') params.set('workspace', scope.workspace) + return params } diff --git a/src-client/sidebar/ProjectMemory.module.css b/src-client/sidebar/ProjectMemory.module.css index 30743e4..2a31c26 100644 --- a/src-client/sidebar/ProjectMemory.module.css +++ b/src-client/sidebar/ProjectMemory.module.css @@ -22,70 +22,9 @@ line-height: 1.5; } -.header { - display: flex; - align-items: flex-start; - justify-content: space-between; - gap: 8px; - flex-wrap: wrap; -} - -.title { - margin: 0; - font-size: 13.5px; - font-weight: 650; -} - -.subtitle { - margin: 0; - font-size: 12.5px; - font-weight: 600; -} - +.workspace, .hint { margin: 0; - font-size: 11.5px; - opacity: 0.58; -} - -.list { - display: flex; - flex-direction: column; - gap: 8px; -} - -.row { - display: flex; - flex-direction: column; - gap: 5px; - border: 1px solid var(--dsw-alias-border-subtle, rgba(127,127,127,0.18)); - border-radius: 10px; - padding: 8px 10px; - min-width: 0; -} - -.rowMeta { - display: flex; - flex-wrap: wrap; - gap: 6px; -} - -.rowText { - display: -webkit-box; - -webkit-line-clamp: 3; - -webkit-box-orient: vertical; - overflow: hidden; + color: var(--dsw-alias-label-secondary, inherit); overflow-wrap: anywhere; } - -.divider { - height: 1px; - background: var(--dsw-alias-border-subtle, rgba(127,127,127,0.18)); - margin: 2px 0; -} - -.recallRow { - display: flex; - flex-direction: column; - gap: 8px; -} diff --git a/src-client/sidebar/ProjectMemoryView.tsx b/src-client/sidebar/ProjectMemoryView.tsx index 7eabc4d..ad7aa51 100644 --- a/src-client/sidebar/ProjectMemoryView.tsx +++ b/src-client/sidebar/ProjectMemoryView.tsx @@ -1,122 +1,51 @@ -// Read-only project-memory view for the better-sidebar tab. import * as React from 'react' -import { request, bodyError, messageOf } from '../api' -import { formatIso } from '../format' -import { styles } from '../styles' -import { Banner, Btn, Field, Pill } from '../components' +import { postJson } from '../api' +import { Btn } from '../components' import { useApi } from '../panel/useApi' -import { workspaceQuery } from '../panel/workspace' -import styles2 from './ProjectMemory.module.css' +import { DepartmentTab } from '../panel/DepartmentTab' +import { MemoryTab } from '../panel/MemoryTab' +import panel from '../panel/BrainPanel.module.css' +import styles from './ProjectMemory.module.css' const h = React.createElement +const TABS = [ + { id: 'memory', label: '记忆与文档' }, + { id: 'departments', label: '部门' }, +] as const -function openTotalPanel(ctx: any): void { - const layout = ctx === undefined || ctx === null ? undefined : ctx.layout - if (layout !== undefined && layout !== null && typeof layout.selectPanel === 'function') { - layout.selectPanel('dsh-brain') - return - } - if (typeof window !== 'undefined' && typeof window.open === 'function') window.open('/dsh-brain') -} - -export function ProjectMemoryView(props: { ctx?: any; scope?: { cwd?: string; sessionId?: string }; visible?: boolean }): any { - const visible = props.visible !== false - const workspace = props.scope?.cwd - const [search, setSearch] = React.useState('') - const [recallId, setRecallId] = React.useState('') - const [recallQuery, setRecallQuery] = React.useState('') - const [recallHits, setRecallHits] = React.useState([]) - const [recallBusy, setRecallBusy] = React.useState(false) - const [notice, setNotice] = React.useState(null) - - const status = useApi(async () => { - const result = await request('/dsh-brain/local-memory/status' + workspaceQuery(workspace)) - if (result.status !== 200 || result.body === null || result.body.ok !== true) throw new Error(bodyError(result, '读取本地记忆状态失败')) - return result.body - }, { visible, pollMs: 15000 }) - - const memories = useApi(async () => { - const suffix = workspace === undefined ? '' : '&workspace=' + encodeURIComponent(workspace) - const result = await request('/dsh-brain/local-memory/memories?limit=50&offset=0' + suffix) - if (result.status !== 200 || result.body === null || result.body.ok !== true) throw new Error(bodyError(result, '读取记忆列表失败')) - return result.body - }, { visible, pollMs: 30000 }) - - const departments = useApi(async () => { - const suffix = workspace === undefined ? '' : '?workspace=' + encodeURIComponent(workspace) - const result = await request('/dsh-brain/departments/list' + suffix) - if (result.status !== 200 || result.body === null || result.body.ok !== true) throw new Error(bodyError(result, '读取部门列表失败')) - return result.body - }, { visible }) - - const items: any[] = Array.isArray(memories.data?.items) ? memories.data!.items : [] - const needle = String(search).trim().toLowerCase() - const filtered = needle === '' ? items : items.filter((item) => String(item.content ?? '').toLowerCase().indexOf(needle) >= 0) - const departmentList: any[] = Array.isArray(departments.data?.departments) ? departments.data!.departments : [] - const spaces = status.data?.spaces ?? {} - - const recall = async (): Promise => { - if (recallId === '') { setNotice({ tone: 'warn', text: '请选择部门。' }); return } - setRecallBusy(true) - setRecallHits([]) - try { - const query = '/dsh-brain/departments/recall?id=' + encodeURIComponent(recallId) + '&query=' + encodeURIComponent(recallQuery) + '&k=5' + (workspace === undefined ? '' : '&workspace=' + encodeURIComponent(workspace)) - const result = await request(query) - if (result.status !== 200 || result.body === null || result.body.ok !== true) { - setNotice({ tone: 'bad', text: bodyError(result, '召回失败') }) - return - } - setRecallHits(Array.isArray(result.body.hits) ? result.body.hits : []) - } catch (failure) { - setNotice({ tone: 'bad', text: messageOf(failure) }) - } finally { - setRecallBusy(false) +export function ProjectMemoryView(props: { sessionId?: string; visible?: boolean }): any { + const [tab, setTab] = React.useState<(typeof TABS)[number]['id']>('memory') + const { sessionId } = props + const directory = useApi(async () => { + const result = await postJson('/sidebar/api/session.cwd', { sessionId }) + const value = result.body?.value + const cwd = typeof value?.cwd === 'string' ? value.cwd.trim() : '' + if (result.status !== 200 || result.body?.ok !== true || value?.sessionId !== sessionId || cwd === '') { + throw new Error('无法确认当前会话的项目目录。') } - } - - return h('div', { className: styles2.betterSidebarSeat, 'data-dsh-plugin': 'dsh-brain', 'data-dsh-part': 'better-sidebar-memory' }, - h('div', { className: styles2.inner }, - h('div', { className: styles2.header }, - h('div', null, - h('h4', { className: styles2.title }, '项目记忆'), - h('p', { className: styles2.hint }, '当前会话项目的本地记忆(只读)'), + return cwd + }, { visible: props.visible !== false && sessionId !== undefined }) + const workspace = directory.error === null ? directory.data ?? undefined : undefined + return h('div', { className: styles.betterSidebarSeat, 'data-dsh-plugin': 'dsh-brain', 'data-dsh-part': 'better-sidebar-memory' }, + h('div', { className: styles.inner }, + workspace === undefined ? h('div', null, + h('p', { className: styles.hint }, directory.error ?? '等待当前会话的项目目录。'), + directory.error === null ? null : h(Btn, { label: '重试', variant: 'small', onClick: directory.reload }), + ) : h(React.Fragment, null, + h('p', { className: styles.workspace, title: workspace }, workspace), + h('div', { className: panel.tabBar, role: 'tablist', 'aria-label': '项目记忆页签' }, + TABS.map((item) => h('button', { + key: item.id, + type: 'button', + role: 'tab', + 'aria-selected': tab === item.id, + className: tab === item.id ? panel.tab + ' ' + panel.tabActive : panel.tab, + onClick: () => setTab(item.id), + }, item.label)), ), - h(Btn, { label: '去总面板', variant: 'small', onClick: () => openTotalPanel(props.ctx) }), - ), - status.error === null ? null : h(Banner, { tone: 'bad' }, status.error), - h('div', { style: styles.pills }, - h(Pill, { label: '全局空间', value: spaces.global === null || spaces.global === undefined ? '未创建' : '就绪', tone: spaces.global === null || spaces.global === undefined ? 'muted' : 'ok' }), - h(Pill, { label: '项目空间', value: spaces.project === null || spaces.project === undefined ? '未创建' : '就绪', tone: spaces.project === null || spaces.project === undefined ? 'muted' : 'ok' }), - h(Pill, { label: '条目', value: memories.data?.total ?? 0, tone: 'muted' }), - ), - h(Field, { label: '搜索记忆', value: search, onChange: setSearch }), - notice === null ? null : h(Banner, { tone: notice.tone }, notice.text), - memories.error === null ? null : h(Banner, { tone: 'bad' }, memories.error), - filtered.length === 0 ? h('p', { className: styles2.hint }, '没有匹配的记忆条目。') : h('div', { className: styles2.list }, - filtered.map((item) => h('div', { key: item.id, className: styles2.row }, - h('div', { className: styles2.rowMeta }, - h(Pill, { label: 'scope', value: item.scope ?? '—', tone: 'muted' }), - item.category === undefined ? null : h(Pill, { label: '分类', value: item.category, tone: 'muted' }), - h(Pill, { label: '更新', value: formatIso(item.updatedAt), tone: 'muted' }), - ), - h('div', { className: styles2.rowText }, String(item.content ?? '')), - )), - ), - h('div', { className: styles2.divider }), - h('h5', { className: styles2.subtitle }, '部门召回'), - h('div', { className: styles2.recallRow }, - h('select', { className: styles.input, value: recallId, onChange: (event) => setRecallId(event.target.value) }, - h('option', { value: '' }, '选择部门…'), - departmentList.map((item) => h('option', { key: item.id, value: item.id }, String(item.name))), - ), - h(Field, { label: '查询', value: recallQuery, onChange: setRecallQuery }), - h(Btn, { label: recallBusy ? '召回中…' : '召回', disabled: recallBusy, onClick: () => { void recall() } }), - ), - recallHits.length === 0 ? null : h('div', { className: styles2.list }, - recallHits.map((hit: any, index: number) => h('div', { key: String(index), className: styles2.row }, - h('div', { className: styles2.rowMeta }, h(Pill, { label: '来源', value: hit.origin ?? '—', tone: 'muted' })), - h('div', { className: styles2.rowText }, String(hit.contentSnippet ?? hit.content ?? '')), - )), + tab === 'memory' + ? h(MemoryTab, { scope: 'project', workspace, key: workspace, active: props.visible }) + : h(DepartmentTab, { scope: 'project', workspace, key: workspace, active: props.visible }), ), ), ) diff --git a/src-client/sidebar/register.ts b/src-client/sidebar/register.ts index b9d92fc..f5c29f6 100644 --- a/src-client/sidebar/register.ts +++ b/src-client/sidebar/register.ts @@ -41,11 +41,17 @@ export function mountBrainSidebarTab(ctx: any): () => void { const dispose = service.registerTab({ id: BETTER_SIDEBAR_TAB_ID, title: () => '项目记忆', - description: '当前会话项目的本地记忆:空间/条目/搜索/部门召回', + description: '查看和管理当前项目的记忆、文档与部门', icon: (size: number) => React.createElement(BrainIcon, { size }), order: 60, single: true, - component: ({ scope, visible }: BetterSidebarTabProps) => React.createElement(ProjectMemoryView, { key: scope?.cwd ?? '', ctx, scope, visible }), + component: ({ scope, visible }: BetterSidebarTabProps) => { + const cwd = scope?.cwd?.trim() + const sessionId = cwd ? scope?.sessionId?.trim() || undefined : undefined + // Better Sidebar can first publish the saved directory before resolving a live worktree. + // Recheck with the host on mount and whenever the sidebar changes its directory hint. + return React.createElement(ProjectMemoryView, { key: JSON.stringify([sessionId, cwd]), sessionId, visible }) + }, }) current = { service, dispose } } diff --git a/src/index.ts b/src/index.ts index 4a25ca9..0c95856 100644 --- a/src/index.ts +++ b/src/index.ts @@ -24,8 +24,12 @@ export const name = 'dsh-brain' /** Services required before `apply` runs. */ export const inject = ['webServer'] -/** Register the plugin with the host: all five sub-entries at once. */ +/** Mount the discoverable UI row or the legacy all-in-one plugin. */ export function apply(ctx: CloudMemoryContext, config: unknown): void { + if (config !== null && typeof config === 'object' && 'entry' in config && config.entry === 'ui') { + ui.apply(ctx, config) + return + } cloudsync.apply(ctx, config) memory.apply(ctx, config) skills.apply(ctx, config) diff --git a/src/local-memory/departments/manager.ts b/src/local-memory/departments/manager.ts index ab7641a..e368660 100644 --- a/src/local-memory/departments/manager.ts +++ b/src/local-memory/departments/manager.ts @@ -50,8 +50,10 @@ export class DepartmentManager { if (global !== undefined) return global return (await this.registry('project').read()).departments.find((item) => item.id === id) } - private async required(id: string): Promise { - const department = await this.find(id) + private async required(id: string, scope?: DepartmentScope): Promise { + const department = scope === undefined + ? await this.find(id) + : (await this.registry(scope).read()).departments.find((item) => item.id === id && item.scope === scope) if (department === undefined) throw new Error('department_not_found') return department } @@ -91,8 +93,8 @@ export class DepartmentManager { return files.flatMap((file) => file.departments).sort((a, b) => b.updatedAt.localeCompare(a.updatedAt) || a.id.localeCompare(b.id)) } - async update(id: string, patch: DepartmentUpdateInput, expectedRevision?: number): Promise { - const current = await this.required(id) + async update(id: string, patch: DepartmentUpdateInput, expectedRevision?: number, scope?: DepartmentScope): Promise { + const current = await this.required(id, scope) if (expectedRevision !== undefined && current.revision !== expectedRevision) throw new Error('revision_conflict') if (patch.role !== undefined && containsSecret(patch.role)) throw new Error('secret_not_allowed') return this.registry(current.scope).update(async (file) => { @@ -156,8 +158,8 @@ export class DepartmentManager { return { ...reference, hostSessionId: externalId } } - async checkpoint(id: string, input: { currentTask?: string; handoff?: string }, expectedRevision?: number): Promise { - const current = await this.required(id) + async checkpoint(id: string, input: { currentTask?: string; handoff?: string }, expectedRevision?: number, scope?: DepartmentScope): Promise { + const current = await this.required(id, scope) if (expectedRevision !== undefined && current.revision !== expectedRevision) throw new Error('revision_conflict') const currentTask = input.currentTask === undefined ? undefined : text(input.currentTask, 4000) const handoff = input.handoff === undefined ? undefined : text(input.handoff, 20000) @@ -192,12 +194,15 @@ export class DepartmentManager { } /** Private first on equal scores; project/global are opt-in and the total result count stays bounded. */ - async recall(id: string, query: string, k = 5, workspace?: string): Promise { - const department = await this.required(id) + async recall(id: string, query: string, k = 5, workspace?: string, scope?: DepartmentScope): Promise { + const department = await this.required(id, scope) const limit = limitOf(k) const privateHits = await this.store(department).search(query, limit) const shared: LocalMemorySearchHit[] = [] - if (department.memory.readProject && department.memory.readGlobal) { + if (scope !== undefined) { + const readShared = scope === 'global' ? department.memory.readGlobal : department.memory.readProject + if (readShared) shared.push(...await this.memory.searchHits(query, limit, workspace, undefined, scope)) + } else if (department.memory.readProject && department.memory.readGlobal) { shared.push(...await this.memory.searchHits(query, limit * 2, workspace)) } else if (department.memory.readGlobal) { shared.push(...await this.memory.searchHits(query, limit, workspace, 'global')) @@ -220,8 +225,8 @@ export class DepartmentManager { } /** Disable without deleting private memories or allowing automatic session recovery. */ - async disable(id: string, expectedRevision?: number): Promise { - const current = await this.required(id) + async disable(id: string, expectedRevision?: number, scope?: DepartmentScope): Promise { + const current = await this.required(id, scope) if (expectedRevision !== undefined && current.revision !== expectedRevision) throw new Error('revision_conflict') const store = this.store(current) if (await store.spaceMeta() !== undefined) await store.setActive(false) diff --git a/src/local-memory/manager.ts b/src/local-memory/manager.ts index faa2713..1d8af10 100644 --- a/src/local-memory/manager.ts +++ b/src/local-memory/manager.ts @@ -107,6 +107,9 @@ export class LocalMemoryManager { get projectRoot(): string { return this.projectRootFor() } private get globalStore(): JsonMemoryStore { return new JsonMemoryStore(join(this.globalRoot, 'runtime'), 'global', 'global') } private projectStoreFor(workspace?: string): JsonMemoryStore { return new JsonMemoryStore(join(this.projectRootFor(workspace), 'memory-space'), 'project', projectIdFor(this.projectRootFor(workspace))) } + private scopedStore(scope: LocalMemoryScope, workspace?: string): JsonMemoryStore { + return scope === 'global' ? this.globalStore : this.projectStoreFor(workspace) + } private async storeFor(scope: LocalMemoryScope, workspace?: string): Promise { if (scope === 'global') return this.globalStore return this.ensureProject(workspace) @@ -223,20 +226,22 @@ export class LocalMemoryManager { return scoped.filter(({ record }) => { if (seen.has(record.id)) return false; seen.add(record.id); return true }) .sort((a, b) => b.score - a.score || b.record.updatedAt.localeCompare(a.record.updatedAt)) } - async searchHits(query: string, k = this.settingsOf().localMemoryK ?? 5, workspace?: string, projectId?: string): Promise<{ record: LocalMemoryRecord; score: number }[]> { + async searchHits(query: string, k = this.settingsOf().localMemoryK ?? 5, workspace?: string, projectId?: string, scope?: LocalMemoryScope): Promise<{ record: LocalMemoryRecord; score: number }[]> { const startedAt = Date.now() - const hits = await this.collectHits(query, workspace, projectId) const limit = Math.max(1, Math.min(100, Math.trunc(k))) - const result = hits.slice(0, limit) + const result = scope === undefined + ? (await this.collectHits(query, workspace, projectId)).slice(0, limit) + : await this.scopedStore(scope, workspace).search(query, limit) const sources: Record = {} for (const hit of result) sources[hit.record.scope] = (sources[hit.record.scope] ?? 0) + 1 - this.loggerOf?.log({ event: 'memory.search', scope: 'project', workspace: this.workspacePath(workspace), detail: { query, k: limit, hits: result.length, sources, durationMs: Date.now() - startedAt } }) + this.loggerOf?.log({ event: 'memory.search', scope: scope ?? 'project', workspace: scope === 'global' ? undefined : this.workspacePath(workspace), detail: { query, k: limit, hits: result.length, sources, durationMs: Date.now() - startedAt } }) return result } async search(query: string, k = this.settingsOf().localMemoryK ?? 5, workspace?: string, projectId?: string): Promise { return (await this.searchHits(query, k, workspace, projectId)).map((hit) => hit.record) } - async list(options: { limit?: number; offset?: number } = {}, workspace?: string, projectId?: string): Promise<{ items: LocalMemoryRecord[]; total: number }> { + async list(options: { limit?: number; offset?: number; scope?: LocalMemoryScope } = {}, workspace?: string, projectId?: string): Promise<{ items: LocalMemoryRecord[]; total: number }> { + if (options.scope !== undefined) return this.scopedStore(options.scope, workspace).list(options) const projectStore = await this.ensureProject(workspace) const records = [...(await this.globalStore.records()), ...(await projectStore.records())] const scoped = records.filter((record) => { @@ -251,19 +256,20 @@ export class LocalMemoryManager { const limit = Math.max(1, Math.min(1000, Math.trunc(options.limit ?? 50))) return { items: ordered.slice(offset, offset + limit), total: ordered.length } } - async forget(id: string, expectedRevision?: number, workspace?: string): Promise { - const globalRecord = await this.globalStore.read(id) - await this.markProjectionDirty() - if (globalRecord !== undefined) { - const removed = await this.globalStore.forget(id, expectedRevision) - await this.tryRegenerateProjections() - this.loggerOf?.log({ event: 'memory.forget', scope: 'global', detail: { recordId: id, revision: removed.revision } }) - return removed + async forget(id: string, expectedRevision?: number, workspace?: string, scope?: LocalMemoryScope): Promise { + const targetScope = scope ?? ((await this.globalStore.read(id)) === undefined ? 'project' : 'global') + const scopedStore = scope === undefined ? undefined : this.scopedStore(scope, workspace) + if (scopedStore !== undefined) { + const record = await scopedStore.read(id) + if (record === undefined) throw new Error('memory_not_found') + if (expectedRevision !== undefined && record.revision !== expectedRevision) throw new Error('revision_conflict') } - const store = await this.ensureProject(workspace) + // The runtime projections are built exclusively from the global store. + if (scope !== 'project') await this.markProjectionDirty() + const store = scopedStore ?? await this.storeFor(targetScope, workspace) const removed = await store.forget(id, expectedRevision) - await this.tryRegenerateProjections() - this.loggerOf?.log({ event: 'memory.forget', scope: 'project', workspace: this.workspacePath(workspace), detail: { recordId: id, revision: removed.revision } }) + if (scope !== 'project') await this.tryRegenerateProjections() + this.loggerOf?.log({ event: 'memory.forget', scope: targetScope, workspace: targetScope === 'project' ? this.workspacePath(workspace) : undefined, detail: { recordId: id, revision: removed.revision } }) return removed } async projects(workspace?: string): Promise<{ id: string; name: string }[]> { @@ -284,11 +290,21 @@ export class LocalMemoryManager { if (documents === undefined) throw new Error('local_documents_unavailable') return documents.add(input) } - async storageStatus(workspace?: string): Promise> { - const projectRoot = this.projectRootFor(workspace) - const global = await this.globalStore.spaceMeta() - const project = await this.projectStoreFor(workspace).spaceMeta() - return { provider: 'local', globalRoot: this.globalRoot, projectRoot, spaces: { global: global ?? null, project: project ?? null }, cloudSyncEnabled: this.settingsOf().cloudMemoryEnabled === true, localMemoryEnabled: this.settingsOf().localMemoryEnabled !== false } + async storageStatus(workspace?: string, scope?: LocalMemoryScope): Promise> { + const projectRoot = scope === 'global' ? undefined : this.projectRootFor(workspace) + const global = scope === 'project' ? undefined : await this.globalStore.spaceMeta() + const project = scope === 'global' ? undefined : await this.projectStoreFor(workspace).spaceMeta() + return { + provider: 'local', + ...(scope === 'project' ? {} : { globalRoot: this.globalRoot }), + ...(projectRoot === undefined ? {} : { projectRoot }), + spaces: { + ...(scope === 'project' ? {} : { global: global ?? null }), + ...(scope === 'global' ? {} : { project: project ?? null }), + }, + cloudSyncEnabled: this.settingsOf().cloudMemoryEnabled === true, + localMemoryEnabled: this.settingsOf().localMemoryEnabled !== false, + } } /** Return the compact per-turn projection used by the system prompt. */ projectionText(limit = 2000): string { diff --git a/src/routes.ts b/src/routes.ts index 28a69c1..eb71033 100644 --- a/src/routes.ts +++ b/src/routes.ts @@ -266,9 +266,19 @@ async function serveLocalMemory(deps: RouteDeps, req: IncomingMessage, res: Serv const marker = '/local-memory' const markerAt = url.pathname.indexOf(marker) const suffix = markerAt < 0 ? '' : url.pathname.slice(markerAt + marker.length) - if (suffix === '' || suffix === '/' || suffix === '/status') { + if (suffix === '' || suffix === '/' || suffix === '/status' || suffix === '/memories') { if (req.method !== 'GET') { fail(res, 405, 'method-not-allowed'); return } - json(res, 200, { ok: true, ...(await manager.storageStatus(workspace)) }) + const scope = url.searchParams.get('scope') ?? undefined + if (scope !== undefined && scope !== 'global' && scope !== 'project') { fail(res, 400, 'invalid-scope'); return } + if (scope === 'project' && workspace === undefined) { fail(res, 400, 'workspace-required'); return } + if (suffix !== '/memories') { + json(res, 200, { ok: true, ...(await manager.storageStatus(workspace, scope)) }) + return + } + const limit = Math.max(1, Math.min(1000, Number.parseInt(url.searchParams.get('limit') ?? '50', 10) || 50)) + const offset = Math.max(0, Number.parseInt(url.searchParams.get('offset') ?? '0', 10) || 0) + const page = await manager.list({ limit, offset, scope }, workspace) + json(res, 200, { ok: true, total: page.total, items: page.items.map((record) => ({ id: record.id, scope: record.scope, content: record.content, category: record.category, tags: record.tags, source: record.source, revision: record.revision, updatedAt: record.updatedAt })) }) return } if (suffix === '/spaces') { @@ -278,17 +288,12 @@ async function serveLocalMemory(deps: RouteDeps, req: IncomingMessage, res: Serv } if (suffix === '/documents') { if (req.method !== 'GET') { fail(res, 405, 'method-not-allowed'); return } + const scope = url.searchParams.get('scope') + if (scope !== null && scope !== 'project') { fail(res, 400, 'invalid-scope'); return } + if (scope === 'project' && workspace === undefined) { fail(res, 400, 'workspace-required'); return } json(res, 200, { ok: true, documents: await manager.documents(workspace) }) return } - if (suffix === '/memories') { - if (req.method !== 'GET') { fail(res, 405, 'method-not-allowed'); return } - const limit = Math.max(1, Math.min(1000, Number.parseInt(url.searchParams.get('limit') ?? '50', 10) || 50)) - const offset = Math.max(0, Number.parseInt(url.searchParams.get('offset') ?? '0', 10) || 0) - const page = await manager.list({ limit, offset }, workspace) - json(res, 200, { ok: true, total: page.total, items: page.items.map((record) => ({ id: record.id, scope: record.scope, content: record.content, category: record.category, tags: record.tags, source: record.source, revision: record.revision, updatedAt: record.updatedAt })) }) - return - } if (suffix === '/forget') { if (req.method !== 'POST') { fail(res, 405, 'method-not-allowed'); return } if (!sameOrigin(req)) { fail(res, 403, 'origin-rejected'); return } @@ -300,7 +305,17 @@ async function serveLocalMemory(deps: RouteDeps, req: IncomingMessage, res: Serv if (id === '') { fail(res, 400, 'id-required'); return } const expectedRevision = typeof input.expectedRevision === 'number' && Number.isFinite(input.expectedRevision) ? Math.trunc(input.expectedRevision) : undefined const targetWorkspace = typeof input.workspace === 'string' ? input.workspace.trim() || undefined : undefined - json(res, 200, { ok: true, record: await manager.forget(id, expectedRevision, targetWorkspace) }) + const scope = input.scope + if (scope !== undefined && scope !== 'global' && scope !== 'project') { fail(res, 400, 'invalid-scope'); return } + if (scope === 'project' && targetWorkspace === undefined) { fail(res, 400, 'workspace-required'); return } + try { + json(res, 200, { ok: true, record: await manager.forget(id, expectedRevision, targetWorkspace, scope) }) + } catch (error) { + if (scope === undefined || !(error instanceof Error)) throw error + if (error.message === 'memory_not_found') { fail(res, 404, error.message); return } + if (error.message === 'revision_conflict') { fail(res, 409, error.message); return } + throw error + } return } if (suffix === '/search') { diff --git a/src/settings-ui/departments-routes.ts b/src/settings-ui/departments-routes.ts index 3454664..73156c6 100644 --- a/src/settings-ui/departments-routes.ts +++ b/src/settings-ui/departments-routes.ts @@ -10,7 +10,7 @@ import type { SettingsStore } from '../store.ts' import type { DepartmentManager } from '../local-memory/departments/index.ts' import type { LocalMemoryManager } from '../local-memory/manager.ts' import { departmentSnippet } from '../memory/departments-tools.ts' -import type { DepartmentCreateInput, DepartmentUpdateInput } from '../local-memory/departments/types.ts' +import type { DepartmentCreateInput, DepartmentScope, DepartmentUpdateInput } from '../local-memory/departments/types.ts' import { fail, json, readBody, sameOrigin } from '../http.ts' export interface DepartmentRouteDeps { @@ -23,6 +23,7 @@ function errorStatus(message: string): number | undefined { if (message === 'department_not_found') return 404 if (message === 'revision_conflict') return 409 if (message === 'department_disabled') return 409 + if (message === 'invalid-scope' || message === 'workspace-required') return 400 if (message === 'department_required_field' || message === 'department_invalid_host' || message === 'secret_not_allowed') return 400 return undefined } @@ -47,12 +48,21 @@ async function bodyObject(req: IncomingMessage, res: ServerResponse): Promise { const manager = deps.departments if (manager === undefined) { fail(res, 503, 'departments-unavailable'); return } if (deps.store.settings().localMemoryEnabled === false) { fail(res, 503, 'local-memory-disabled'); return } const withWorkspace = (workspace: string | undefined, job: () => Promise): Promise => deps.localMemory === undefined ? job() : deps.localMemory.withWorkspace(workspace, job) + const withScope = (scope: DepartmentScope | undefined, workspace: string | undefined, job: () => Promise): Promise => + scope === undefined ? withWorkspace(workspace, job) : manager.memory.withWorkspace(scope === 'project' ? workspace : undefined, job) const url = new URL(req.url ?? '/', 'http://localhost') const marker = '/departments' const at = url.pathname.indexOf(marker) @@ -92,6 +102,7 @@ export async function serveDepartments(deps: DepartmentRouteDeps, req: IncomingM const id = stringField(body.id)?.trim() ?? '' if (id === '') { fail(res, 400, 'id-required'); return } const expectedRevision = revisionField(body.expectedRevision) + const scope = suffix === '/resume' ? undefined : requestScope(body.scope, workspace) if (suffix === '/update') { const patch: DepartmentUpdateInput = { ...(stringField(body.name) === undefined ? {} : { name: stringField(body.name) }), @@ -101,16 +112,16 @@ export async function serveDepartments(deps: DepartmentRouteDeps, req: IncomingM ...(typeof body.readGlobal === 'boolean' ? { readGlobal: body.readGlobal } : {}), ...(typeof body.readProject === 'boolean' ? { readProject: body.readProject } : {}), } - json(res, 200, { ok: true, department: await withWorkspace(workspace, () => manager.update(id, patch, expectedRevision)) }) + json(res, 200, { ok: true, department: await withScope(scope, workspace, () => manager.update(id, patch, expectedRevision, scope)) }) return } - if (suffix === '/disable') { json(res, 200, { ok: true, department: await withWorkspace(workspace, () => manager.disable(id, expectedRevision)) }); return } + if (suffix === '/disable') { json(res, 200, { ok: true, department: await withScope(scope, workspace, () => manager.disable(id, expectedRevision, scope)) }); return } if (suffix === '/checkpoint') { const input: { currentTask?: string; handoff?: string } = { ...(stringField(body.currentTask) === undefined ? {} : { currentTask: stringField(body.currentTask) }), ...(stringField(body.handoff) === undefined ? {} : { handoff: stringField(body.handoff) }), } - json(res, 200, { ok: true, department: await withWorkspace(workspace, () => manager.checkpoint(id, input, expectedRevision)) }) + json(res, 200, { ok: true, department: await withScope(scope, workspace, () => manager.checkpoint(id, input, expectedRevision, scope)) }) return } const host = stringField(body.host)?.trim() || 'dsh' @@ -129,7 +140,8 @@ export async function serveDepartments(deps: DepartmentRouteDeps, req: IncomingM const requested = Number.parseInt(url.searchParams.get('k') ?? '5', 10) const k = Number.isFinite(requested) ? Math.max(1, Math.min(5, requested)) : 5 const workspace = url.searchParams.get('workspace')?.trim() || undefined - const hits = await withWorkspace(workspace, () => manager.recall(id, query, k, workspace)) + const scope = requestScope(url.searchParams.get('scope') ?? undefined, workspace) + const hits = await withScope(scope, workspace, () => manager.recall(id, query, k, workspace, scope)) json(res, 200, { ok: true, hits: hits.map((hit) => ({ ...hit, content: hit.record.content, contentSnippet: departmentSnippet(hit.record.content) })) }) return } diff --git a/verify-client-build.mjs b/verify-client-build.mjs index fa2cf27..66b0b4f 100644 --- a/verify-client-build.mjs +++ b/verify-client-build.mjs @@ -166,19 +166,19 @@ if (existsSync(legacyFile)) { console.log('SKIP legacy comparison (artifacts/analysis/client-legacy.js missing)') } -// Keep the static request checks local to each consumer, so the presence of a -// workspace parameter elsewhere in the bundle cannot satisfy them. -const memoryTab = readFileSync(new URL('./src-client/panel/MemoryTab.tsx', import.meta.url), 'utf8') +// Each surface must pass an explicit scope to both management tabs. +const layout = readFileSync(new URL('./src-client/panel/BrainPanel.tsx', import.meta.url), 'utf8') const sidebar = readFileSync(new URL('./src-client/sidebar/ProjectMemoryView.tsx', import.meta.url), 'utf8') -check('memory tab scopes status, memories and documents to the active workspace', - memoryTab.includes("request('/dsh-brain/local-memory/status' + workspaceQuery(workspace))") && - memoryTab.includes("'&offset=' + String(offset) + workspaceSuffix(workspace)") && - memoryTab.includes("request('/dsh-brain/local-memory/documents' + workspaceQuery(workspace))")) -check('sidebar scopes status and memories to its workspace', - sidebar.includes('props.scope?.cwd') && - sidebar.includes("request('/dsh-brain/local-memory/status' + workspaceQuery(workspace))") && - sidebar.includes("'&workspace=' + encodeURIComponent(workspace)") && - sidebar.includes("request('/dsh-brain/local-memory/memories?limit=50&offset=0' + suffix)")) +const patch = readFileSync(new URL('./cordis.patch.yml', import.meta.url), 'utf8') +check('global panel binds both tabs to global data', + layout.includes("h(MemoryTab, { scope: 'global', active })") && layout.includes("h(DepartmentTab, { scope: 'global', active })")) +check('project tab waits for its workspace and scopes both tabs to it', + sidebar.includes("postJson('/sidebar/api/session.cwd', { sessionId })") && sidebar.includes('value?.sessionId !== sessionId') && + sidebar.includes('workspace === undefined ?') && sidebar.includes("h(MemoryTab, { scope: 'project', workspace,") && sidebar.includes("h(DepartmentTab, { scope: 'project', workspace,")) +check('the UI loader row mounts at the package root for browser discovery', + /id: dsh-brain-ui\r?\n(?: *#[^\r\n]*\r?\n)* *name: dsh-brain\r?\n *config:\r?\n *entry: ui(?:\r?\n|$)/.test(patch)) +check('settings section mounts the full plugin config form', + bySeat['settings.section']?.component === bySeat['plugins.bundle.config']?.component && typeof bySeat['settings.section']?.component === 'function') const root = await mkdtemp(join(tmpdir(), 'brain-ui-workspace-')) try { @@ -206,11 +206,15 @@ try { return response.json() } const [defaultPage, scopedPage, status, documents] = await Promise.all([ - getJson('/memories'), getJson('/memories' + workspace), getJson('/status' + workspace), getJson('/documents' + workspace), + getJson('/memories'), getJson('/memories' + workspace), getJson('/status' + workspace), getJson('/documents' + workspace + '&scope=project'), ]) check('omitting workspace still lists the default project', defaultPage.total === 1 && defaultPage.items[0]?.id === a.record.id) check('workspace query lists only the selected project fixture', scopedPage.total === 1 && scopedPage.items[0]?.id === b.record.id) check('status and documents read the selected project', status.projectRoot === projectBrainRoot(projectB) && documents.documents[0]?.id === documentB.id) + const invalidDocuments = await Promise.all([ + fetch(base + '/documents?scope=project'), fetch(base + '/documents' + workspace + '&scope=global'), + ]) + check('explicit document scope requires a project workspace', invalidDocuments.every(({ status }) => status === 400)) const forget = await fetch(base + '/forget', { method: 'POST', headers: { origin, 'content-type': 'application/json' }, body: JSON.stringify({ id: b.record.id, expectedRevision: b.record.revision, workspace: projectB }), diff --git a/verify-departments-wiring.mjs b/verify-departments-wiring.mjs index fa29ba8..e62d621 100644 --- a/verify-departments-wiring.mjs +++ b/verify-departments-wiring.mjs @@ -82,6 +82,97 @@ const missingName = await request(server, 'POST', '/dsh-brain/departments/create check('POST create rejects missing name', missingName.status === 400 && missingName.body?.error === 'name-required') const stale = await request(server, 'POST', '/dsh-brain/departments/update', { id: sameOrigin.body.department.id, expectedRevision: 0, role: 'stale' }, 'http://127.0.0.1:' + server.address().port) check('POST update maps revision conflict to 409', stale.status === 409 && stale.body?.error === 'revision_conflict') +// Explicit UI scopes and legacy callers share the same route table. +const memoryRoute = '/dsh-brain/local-memory' +const departmentRoute = '/dsh-brain/departments' +const workspaceA = '&workspace=' + encodeURIComponent(dualA) +const workspaceB = '&workspace=' + encodeURIComponent(dualB) +const globalMemory = (await kernel.localMemory.remember({ content: 'boundary alpha beta global shared', scope: 'global' })).record +const projectMemory = (await kernel.localMemory.withWorkspace(dualA, () => kernel.localMemory.remember({ content: 'boundary alpha project shared' }))).record +const legacyProjectMemory = (await (await kernel.localMemory.ensureProject(dualA)).add({ content: 'boundary project legacy record' })).record +const otherProjectMemory = (await kernel.localMemory.withWorkspace(dualB, () => kernel.localMemory.remember({ content: 'boundary alpha beta other workspace' }))).record +const globalStatus = await request(server, 'GET', memoryRoute + '/status?scope=global' + workspaceA) +const projectStatus = await request(server, 'GET', memoryRoute + '/status?scope=project' + workspaceA) +const combinedStatus = await request(server, 'GET', memoryRoute + '/status?' + workspaceA.slice(1)) +check('memory status returns only the requested space and root with legacy flags', + globalStatus.status === 200 && globalStatus.body.globalRoot === kernel.localMemory.globalRoot && !('projectRoot' in globalStatus.body) && + Object.keys(globalStatus.body.spaces).join() === 'global' && globalStatus.body.spaces.global.scope === 'global' && + projectStatus.status === 200 && projectStatus.body.projectRoot === join(dualA, '.dsh', 'brain') && !('globalRoot' in projectStatus.body) && + Object.keys(projectStatus.body.spaces).join() === 'project' && projectStatus.body.spaces.project.scope === 'project' && + [globalStatus, projectStatus].every(({ body }) => body.localMemoryEnabled === combinedStatus.body.localMemoryEnabled && body.cloudSyncEnabled === combinedStatus.body.cloudSyncEnabled) && + Object.keys(combinedStatus.body.spaces).sort().join() === 'global,project') +const memoryPages = await Promise.all([ + request(server, 'GET', memoryRoute + '/memories?scope=global&limit=1' + workspaceA), + request(server, 'GET', memoryRoute + '/memories?scope=project&limit=1' + workspaceA), + request(server, 'GET', memoryRoute + '/memories?scope=project&limit=1&offset=1' + workspaceA), + request(server, 'GET', memoryRoute + '/memories?' + workspaceA.slice(1)), +]) +const [globalPage, projectFirst, projectSecond, combinedPage] = memoryPages.map(({ body }) => body) +check('memory pagination uses one store and includes legacy project records without projectId', + memoryPages.every(({ status }) => status === 200) && globalPage.total === 1 && globalPage.items[0]?.id === globalMemory.id && + projectFirst.total === 2 && projectSecond.total === 2 && projectFirst.items.length === 1 && projectSecond.items.length === 1 && + [projectFirst.items[0]?.id, projectSecond.items[0]?.id].sort().join() === [projectMemory.id, legacyProjectMemory.id].sort().join() && + legacyProjectMemory.projectId === undefined && combinedPage.total === 3 && combinedPage.items.some((item) => item.id === globalMemory.id)) +for (const path of ['/status', '/memories']) { + const missing = await request(server, 'GET', memoryRoute + path + '?scope=project') + const blank = await request(server, 'GET', memoryRoute + path + '?scope=project&workspace=%20') + const invalid = await request(server, 'GET', memoryRoute + path + '?scope=other') + check('memory ' + path + ' validates explicit scope and workspace', + [missing, blank].every(({ status, body }) => status === 400 && body?.error === 'workspace-required') && invalid.status === 400 && invalid.body?.error === 'invalid-scope') +} +const forget = (body) => request(server, 'POST', memoryRoute + '/forget', body) +const blockedForgets = await Promise.all([ + forget({ scope: 'global', workspace: dualA, id: projectMemory.id }), + forget({ scope: 'project', workspace: dualA, id: globalMemory.id }), + forget({ scope: 'project', workspace: dualA, id: otherProjectMemory.id }), +]) +const missingForget = await forget({ scope: 'project', workspace: ' ', id: projectMemory.id }) +check('scoped forget cannot fall through to another store', blockedForgets.every(({ status, body }) => status === 404 && body?.error === 'memory_not_found') && missingForget.status === 400 && missingForget.body?.error === 'workspace-required') +const projectDepartment = httpA.body.department +const globalDepartment = sameOrigin.body.department +await rememberTool.execute({ departmentId: projectDepartment.id, content: 'boundary alpha project private' }, { workspace: dualA }) +await rememberTool.execute({ departmentId: globalDepartment.id, content: 'boundary global private' }, { workspace: dualA }) +const recall = (id, params = '') => request(server, 'GET', departmentRoute + '/recall?query=boundary+alpha+beta&id=' + id + params) +const projectRecall = await recall(projectDepartment.id, '&scope=project' + workspaceA) +const scopedGlobalRecall = await recall(globalDepartment.id, '&scope=global' + workspaceA) +const legacyRecall = await recall(projectDepartment.id, workspaceA) +check('scoped recall ranks private records with same-scope shared memory and legacy recall still spans scopes', + projectRecall.status === 200 && projectRecall.body.hits.map((hit) => hit.origin).join() === 'department,project,project' && + scopedGlobalRecall.status === 200 && scopedGlobalRecall.body.hits.map((hit) => hit.origin).sort().join() === 'department,global' && + legacyRecall.status === 200 && legacyRecall.body.hits[0]?.origin === 'global') +const projectFirstHit = await request(server, 'GET', departmentRoute + '/recall?k=1&query=boundary+alpha+beta&id=' + projectDepartment.id + '&scope=project' + workspaceA) +check('scoped recall selects the same-scope candidates before limiting', projectFirstHit.status === 200 && projectFirstHit.body.hits[0]?.origin === 'department') +const blockedRecalls = await Promise.all([ + recall(projectDepartment.id, '&scope=global' + workspaceA), + recall(globalDepartment.id, '&scope=project' + workspaceA), + recall(projectDepartment.id, '&scope=project' + workspaceB), +]) +const missingRecall = await recall(projectDepartment.id, '&scope=project') +check('scoped recall requires the matching department scope and workspace', blockedRecalls.every(({ status, body }) => status === 404 && body?.error === 'department_not_found') && missingRecall.status === 400 && missingRecall.body?.error === 'workspace-required') +const mutate = (action, body) => request(server, 'POST', departmentRoute + '/' + action, body) +for (const action of ['update', 'checkpoint', 'disable']) { + const missing = await mutate(action, { scope: 'project', id: projectDepartment.id }) + const wrongScope = await mutate(action, { scope: 'project', workspace: dualA, id: globalDepartment.id }) + const wrongWorkspace = await mutate(action, { scope: 'project', workspace: dualB, id: projectDepartment.id }) + check('department ' + action + ' requires the matching scope and workspace', + missing.status === 400 && missing.body?.error === 'workspace-required' && + [wrongScope, wrongWorkspace].every(({ status, body }) => status === 404 && body?.error === 'department_not_found')) +} +const updatedProject = await mutate('update', { scope: 'project', workspace: dualA, id: projectDepartment.id, readProject: false }) +const privateProject = await recall(projectDepartment.id, '&scope=project' + workspaceA) +const updatedGlobal = await mutate('update', { scope: 'global', id: globalDepartment.id, readGlobal: false }) +const privateGlobal = await recall(globalDepartment.id, '&scope=global' + workspaceA) +check('scoped recall honors the same-scope read policy even when the other scope is enabled', + updatedProject.status === 200 && updatedGlobal.status === 200 && [privateProject, privateGlobal].every(({ status, body }) => status === 200 && body.hits.map((hit) => hit.origin).join() === 'department')) +const scopedCheckpoint = await mutate('checkpoint', { scope: 'project', workspace: dualA, id: projectDepartment.id, currentTask: 'scoped checkpoint' }) +const scopedDisable = await mutate('disable', { scope: 'global', id: globalDepartment.id }) +check('scoped checkpoint and disable update the selected department', scopedCheckpoint.status === 200 && scopedCheckpoint.body.department.currentTask === 'scoped checkpoint' && scopedDisable.status === 200 && scopedDisable.body.department.active === false) +const legacyProjectList = await request(server, 'GET', departmentRoute + '/list?scope=project') +check('legacy department project list keeps its default workspace', legacyProjectList.status === 200 && Array.isArray(legacyProjectList.body.departments)) +const staleForget = await forget({ scope: 'global', id: globalMemory.id, expectedRevision: 0 }) +const projectForget = await forget({ scope: 'project', workspace: dualA, id: legacyProjectMemory.id, expectedRevision: legacyProjectMemory.revision }) +const legacyForget = await forget({ id: globalMemory.id, workspace: dualB }) +check('scoped forget checks the revision and legacy forget still finds a global memory', staleForget.status === 409 && projectForget.status === 200 && projectForget.body.record.id === legacyProjectMemory.id && legacyForget.status === 200 && legacyForget.body.record.id === globalMemory.id) const legacyRoutes = legacyAliases(createCoreRoutes(kernel.routeDeps())) const legacyServer = http.createServer((req, res) => { const path = (req.url || '/').split('?')[0]; const route = legacyRoutes.find((candidate) => candidate.kind === 'prefix' ? path === candidate.path || path.startsWith(candidate.path + '/') : path === candidate.path); if (route) void route.handler(req, res); else { res.writeHead(404); res.end() } }) await new Promise((resolve) => legacyServer.listen(0, '127.0.0.1', resolve)) diff --git a/verify-plugin-entry.mjs b/verify-plugin-entry.mjs index 8740280..dbcb522 100644 --- a/verify-plugin-entry.mjs +++ b/verify-plugin-entry.mjs @@ -161,6 +161,13 @@ check('deactivating mcp and cloudsync gates the tab and sync flags', && withoutMcpOrSync.capabilities.features.syncResolve === false, JSON.stringify(withoutMcpOrSync.capabilities.features)) +// The bundle patch mounts the UI through the bare package name for browser discovery. +resetBrainKernel() +const rootUi = fakeCtx() +root.apply(rootUi.ctx, { ...SEED, entry: 'ui' }) +check('package root UI mode mounts only the UI entry', rootUi.tools.length === 0 + && JSON.stringify(rootUi.routes.map((route) => `${route.kind}:${route.path}`)) === JSON.stringify(uiPaths)) + // --- compat root ------------------------------------------------------------- resetBrainKernel() const rootHost = fakeCtx()