From f9386d77d63d09dd057acc7d3c1f9bdcc4656bf3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=AB=E6=88=91=E5=B0=8F=E6=9D=A8=E5=90=8C=E5=AD=A6?= Date: Sun, 20 Sep 2026 16:46:01 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E5=8F=91=E5=B8=83=201.1.11=EF=BC=8C?= =?UTF-8?q?=E6=AD=A3=E5=BC=8F/=E6=B5=8B=E8=AF=95=E5=88=86=E6=A0=8F?= =?UTF-8?q?=E5=88=87=E6=8D=A2=EF=BC=88=E4=B8=8D=E5=90=AB=20Skill=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Cursor --- README.md | 7 +- README.zh-CN.md | 7 +- client.js | 245 +++++++++++++++++++----- lib/index.js | 6 +- lib/update.js | 493 ++++++++++++++++++++++++++++++++++++++++++------ package.json | 2 +- 6 files changed, 658 insertions(+), 102 deletions(-) diff --git a/README.md b/README.md index ee045de..c6d58cb 100644 --- a/README.md +++ b/README.md @@ -651,7 +651,7 @@ dsh-purge --edit purge_status purge_apply purge_revert ``` -Patched packages load only after a restart. Apply does not restart by itself. +Patched packages load only after a restart. Apply does not restart by itself. Under the patch title, **Stable** and **Beta** sit in two columns, each with its own version list. The composer **Undo** button drops the last turn and puts the last user sentence back in the input. On the main agent you can rewind once or the whole last round (including subagents). After rewind, send only what is in the box now. `/rewind` does the same. @@ -745,6 +745,11 @@ If nothing is found, set `DSH_BASE` / `DSH_DESKTOP_INSTALL`. No files are change ## Changelog +### 1.1.11 + +- Settings splits Stable / Beta into two columns so you can switch and roll back; 1.1.10 can reach this by Check update +- Skill import is not in this release (it stays on the beta channel) + ### 1.1.10 - Saving or applying with both the prompt and the rule set empty is blocked and shows a dialog diff --git a/README.zh-CN.md b/README.zh-CN.md index 07fd11a..b24fce7 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -651,7 +651,7 @@ dsh-purge --edit purge_status purge_apply purge_revert ``` -设置页「应用」完成后需要重启才会加载已改的包文件。点「重启」才会重启,不会自动重启。 +设置页「应用」完成后需要重启才会加载已改的包文件。点「重启」才会重启,不会自动重启。补丁标题下正式版和测试版左右分栏,各自选版本、各自切换。 输入框旁的「回退」会丢掉最近一轮对话,并把上一句填回输入框;聊天里 `/rewind` 同样可用。 @@ -732,6 +732,11 @@ prompt-inject.md 有内容? ──是──> 原样写入 dsh-purge systemPrompt ## 更新记录 +### 1.1.11 + +- 设置页正式版 / 测试版左右分栏,可切换并回退;1.1.10 点检测更新即可升到此版本 +- 不含 Skill 导入(该能力仍在测试通道) + ### 1.1.10 - 提示词和规则集都空时不能保存或应用,弹窗要求先添加提示词 diff --git a/client.js b/client.js index 2cde99d..3b3f866 100644 --- a/client.js +++ b/client.js @@ -163,16 +163,33 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => { "btn.checkUpdate.busy": "检测中…", "btn.doUpdate": "更新", "btn.doUpdate.busy": "更新中…", + "channel.title": "通道", + "channel.stable": "正式版", + "channel.beta": "测试版", + "channel.useStable": "切换到正式版", + "channel.useBeta": "切换到测试版", + "channel.now": "当前通道", + "channel.other": "可切换", "update.checking": "正在检测更新…", "update.applying": "正在更新…", + "update.switching": "正在切换版本…", "update.latest": "已是最新({version})", "update.available": "有新版本 {remote},当前 {local}", + "update.pinned": "已固定在 {version},通道最新是 {remote}", "update.done": "已更新到 {version},请重启", + "update.switched": "已切换到 {version},请重启", "update.autoDone": "已自动更新到 {version},请重启", "update.dirty": "有新版本,本地有改动未自动覆盖", "update.fail": "更新失败: {error}", "update.timeout": "检测超时,请再点一次检测更新", "update.needRestart": "检测接口未加载,请先重启 dsh 再点检测更新", + "update.noBeta": "还没有测试版", + "update.switch": "切换到此版本", + "update.pick": "选择版本", + "update.tip": "最新", + "update.current": "当前", + "update.confirmSwitch": "切换到 {version}?之后可再切回另一通道或其它版本。本地未提交的插件改动不会保留。", + "update.confirmChannel": "切换到{version}?会按该通道重新安装插件,本地未提交的插件改动不会保留。", "metric.version": "版本", "action.apply": "应用", "action.revert": "还原", @@ -334,16 +351,33 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => { "btn.checkUpdate.busy": "Checking…", "btn.doUpdate": "Update", "btn.doUpdate.busy": "Updating…", + "channel.title": "Channel", + "channel.stable": "Stable", + "channel.beta": "Beta", + "channel.useStable": "Switch to stable", + "channel.useBeta": "Switch to beta", + "channel.now": "Current channel", + "channel.other": "Available", "update.checking": "Checking for updates…", "update.applying": "Updating…", + "update.switching": "Switching version…", "update.latest": "Up to date ({version})", "update.available": "Update {remote} available (now {local})", + "update.pinned": "Pinned at {version}; channel latest is {remote}", "update.done": "Updated to {version}. Restart to apply.", + "update.switched": "Switched to {version}. Restart to apply.", "update.autoDone": "Auto-updated to {version}. Restart to apply.", "update.dirty": "Update available; local edits were not overwritten.", "update.fail": "Update failed: {error}", "update.timeout": "Check timed out. Click Check update again.", "update.needRestart": "Update API is not loaded. Restart dsh, then check again.", + "update.noBeta": "No beta build yet", + "update.switch": "Switch to this version", + "update.pick": "Select version", + "update.tip": "latest", + "update.current": "current", + "update.confirmSwitch": "Switch to {version}? You can switch back later. Uncommitted plugin edits will not be kept.", + "update.confirmChannel": "Switch to {version}? The plugin will be reinstalled from that channel. Uncommitted plugin edits will not be kept.", "metric.version": "Version", "action.apply": "Apply", "action.revert": "Restore", @@ -521,6 +555,23 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => { .dshp-cr-row label{display:inline-flex;align-items:center;gap:6px;color:var(--dshp-ink)} .dshp-cr-num{width:64px;min-width:64px;height:28px;padding:0 8px} .dshp-cr-text{width:120px;min-width:88px;height:28px;padding:0 8px} +.dshp-ver{width:100%;min-width:0;max-width:none;height:34px;padding:0 10px;font-size:12px} +.dshp-lanes{display:grid;grid-template-columns:1fr 1fr;gap:1px;margin:0 0 16px;background:var(--dshp-line);border:1px solid var(--dshp-line);border-radius:8px;overflow:hidden} +.dshp-lane{display:flex;flex-direction:column;gap:0;min-width:0;padding:14px 14px 12px;background:var(--dshp-paper);transition:background .2s var(--dshp-ease)} +.dshp-lane.is-on{background:var(--dshp-bg)} +.dshp-lane-kicker{margin:0 0 4px;font-family:var(--dshp-mono);font-size:10px;letter-spacing:.16em;text-transform:uppercase;color:var(--dshp-mute)} +.dshp-lane.is-on .dshp-lane-kicker{color:var(--dshp-accent)} +.dshp-lane.is-beta .dshp-lane-kicker{color:var(--dshp-warn)} +.dshp-lane.is-on.is-beta .dshp-lane-kicker{color:var(--dshp-warn)} +.dshp-lane-h{display:flex;align-items:baseline;gap:10px;margin:0 0 12px;padding-bottom:10px;border-bottom:1px solid var(--dshp-line)} +.dshp-lane-h strong{font-family:var(--dshp-display);font-size:18px;font-weight:500;letter-spacing:.02em} +.dshp-lane-ver{margin-left:auto;font-family:var(--dshp-mono);font-size:12px;color:var(--dshp-mute);white-space:nowrap} +.dshp-lane-ops{display:flex;flex-direction:column;gap:8px} +.dshp-lane-ops .dshp-btn{width:100%} +.dshp-rel{margin:0 0 14px} +.dshp-rel .dshp-notice{display:block;margin-top:8px;min-height:16px} +@media (max-width:640px){.dshp-lanes{grid-template-columns:1fr}} +@media (prefers-reduced-motion:reduce){.dshp-lane{transition:none}} .dshp-area{min-height:220px;resize:vertical} .dshp-field:focus,.dshp-area:focus{outline:none;border-color:var(--dshp-accent);box-shadow:0 0 0 3px var(--dshp-accent-soft)} .dshp-field:disabled,.dshp-area:disabled{opacity:.5} @@ -609,7 +660,7 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => { function PatchGroups({ state }) { const t = useT(); - const [open, setOpen] = useState({ prompt: true, code: true, engine: true, tools: false, compat: true }); + const [open, setOpen] = useState({}); if (!state || !state.patch_status) return h("div", { className: "dshp-skel", style: { height: 120 } }); return PATCH_GROUPS.map((group) => { const rows = group.ids.map((id) => { @@ -762,9 +813,22 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => { const [notice, setNotice] = useState({ kind: "idle", text: "" }); const [updateNotice, setUpdateNotice] = useState({ kind: "idle", text: "" }); const [updateInfo, setUpdateInfo] = useState(null); - const [canApplyUpdate, setCanApplyUpdate] = useState(false); + const [channel, setChannel] = useState("stable"); + const [pick, setPick] = useState({ stable: "", beta: "" }); const actionTicket = useRef(0); + const syncPicks = (d) => { + const versions = (d && d.versions) || []; + const next = { stable: "", beta: "" }; + for (const id of ["stable", "beta"]) { + const list = versions.filter((item) => item.channel === id); + const cur = list.find((item) => item.current); + const latest = list.find((item) => item.latest); + next[id] = (cur || latest || {}).ref || ""; + } + setPick(next); + }; + const updateErrorText = (tr, e) => { const msg = String((e && e.message) || e || ""); if (msg === "timeout" || /aborted|abort|超时/i.test(msg)) return tr("update.timeout"); @@ -772,41 +836,78 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => { return tr("update.fail", { error: msg }); }; + const applyUpdateInfo = useCallback((d, tr, kind) => { + if (d.channel) setChannel(d.channel); + setUpdateInfo(d); + syncPicks(d); + const version = d.localVersion || d.localSha || "—"; + const remote = d.remoteVersion || d.remoteSha || "—"; + let text = tr("update.latest", { version }); + if (d.hasUpdate) text = tr("update.available", { remote, local: version }); + if (d.pinned && d.hasUpdate) text = tr("update.pinned", { version, remote }); + if (kind === "switched") text = tr("update.switched", { version: d.localVersion || d.remoteVersion || "—" }); + if (kind === "done") text = tr("update.done", { version: d.localVersion || d.remoteVersion || "—" }); + if (d.error) text = d.error; + setUpdateNotice({ kind: d.ok === false || d.error ? "error" : "ok", text }); + }, []); + const checkUpdate = useCallback(() => { setUpdateBusy(true); const tr = tRef.current; setUpdateNotice({ kind: "ok", text: tr("update.checking") }); apiJson("/dsh-purge/update") .then((d) => { - if (!d || !d.ok) throw new Error((d && d.error) || "check failed"); - setUpdateInfo(d); - setCanApplyUpdate(Boolean(d.hasUpdate)); - setUpdateNotice({ - kind: "ok", - text: d.hasUpdate - ? tr("update.available", { remote: d.remoteVersion || d.remoteSha, local: d.localVersion || d.localSha }) - : tr("update.latest", { version: d.localVersion || d.localSha || "—" }), - }); + if (!d || (!d.ok && !d.channel)) throw new Error((d && d.error) || "check failed"); + applyUpdateInfo(d, tr); }) .catch((e) => setUpdateNotice({ kind: "error", text: updateErrorText(tr, e) })) .finally(() => setUpdateBusy(false)); - }, []); + }, [applyUpdateInfo]); - const doUpdate = useCallback(() => { + const postUpdate = useCallback((body, kind) => { setUpdateBusy(true); const tr = tRef.current; - setUpdateNotice({ kind: "ok", text: tr("update.applying") }); - apiJson("/dsh-purge/update", { method: "POST", headers: { "content-type": "application/json" }, body: "{}" }) + setUpdateNotice({ kind: "ok", text: kind === "switched" || kind === "channel" ? tr("update.switching") : tr("update.applying") }); + return apiJson("/dsh-purge/update", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify(body || {}), + }) .then((d) => { - if (!d || !d.ok) throw new Error((d && d.error) || "update failed"); - setUpdateInfo(d); - setCanApplyUpdate(false); - setUpdateNotice({ kind: "ok", text: tr("update.done", { version: d.localVersion || d.remoteVersion || "—" }) }); + if (!d || (d.ok === false && d.error)) throw new Error((d && d.error) || "update failed"); + applyUpdateInfo(d, tr, kind === "channel" ? "switched" : kind); if (d.applied || d.needRestart) setAskRestart(true); + return d; + }) + .catch((e) => { + setUpdateNotice({ kind: "error", text: updateErrorText(tr, e) }); + throw e; }) - .catch((e) => setUpdateNotice({ kind: "error", text: updateErrorText(tr, e) })) .finally(() => setUpdateBusy(false)); - }, []); + }, [applyUpdateInfo]); + + const doUpdate = useCallback((id) => { + const lane = id === "beta" ? "beta" : "stable"; + postUpdate({ op: "apply", ref: lane === "beta" ? "beta" : "master", channel: lane }, "done").catch(() => {}); + }, [postUpdate]); + + const changeChannel = useCallback((next) => { + if (!next) return; + const tr = tRef.current; + if (!window.confirm(tr("update.confirmChannel", { version: tr("channel." + next) }))) return; + postUpdate({ op: "channel", channel: next }, "channel").catch(() => {}); + }, [postUpdate]); + + const switchSelected = useCallback((id) => { + const tr = tRef.current; + const ref = pick[id]; + const versions = ((updateInfo && updateInfo.versions) || []).filter((item) => item.channel === id); + const hit = versions.find((item) => item.ref === ref); + const label = (hit && (hit.label || hit.version)) || ref; + if (!ref) return; + if (!window.confirm(tr("update.confirmSwitch", { version: label }))) return; + postUpdate({ op: "switch", ref }, "switched").catch(() => {}); + }, [pick, postUpdate, updateInfo]); const loadAll = useCallback(() => { const tr = tRef.current; @@ -814,7 +915,8 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => { .then((d) => { if (d && d.ok) { setState(d); - if (d.update && d.update.ok && !d.update.error && !d.update.hasUpdate) setUpdateInfo(d.update); + if (d.channel) setChannel(d.channel); + if (d.update && d.update.ok && !d.update.error) setUpdateInfo(d.update); } else { setState({ ok: false, patches_total: 0, patches_applied: 0, patch_status: {}, shim_cmd: "n/a", shim_ps1: "n/a", shim_bin: "n/a", has_backup: false }); setNotice({ kind: "error", text: tr("err.status", { error: (d && d.error) || "bad response" }) }); @@ -824,6 +926,14 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => { setState({ ok: false, patches_total: 0, patches_applied: 0, patch_status: {}, shim_cmd: "n/a", shim_ps1: "n/a", shim_bin: "n/a", has_backup: false }); setNotice({ kind: "error", text: tr("err.status", { error: e.message }) }); }); + apiJson("/dsh-purge/update") + .then((d) => { + if (!d) return; + if (d.channel) setChannel(d.channel); + setUpdateInfo(d); + syncPicks(d); + }) + .catch(() => {}); apiJson("/dsh-purge/override") .then((d) => { if (d && d.ok) { @@ -1040,30 +1150,81 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => { const pct = total ? Math.round((settled / total) * 100) : 0; const hostSurface = hostSurfaceOf(s); - const localVer = (s && s.plugin_version) || (updateInfo && updateInfo.localVersion) || ""; - const remoteVer = updateInfo && (updateInfo.remoteVersion || updateInfo.remoteSha) || ""; - const remoteSha = updateInfo && updateInfo.remoteSha || ""; - const sameVer = remoteVer && localVer && remoteVer === localVer; - const versionText = canApplyUpdate && remoteVer - ? (sameVer && remoteSha ? "v" + remoteVer + " · " + remoteSha : "v" + remoteVer) - : (localVer ? "v" + localVer : ""); - const updateBtnLabel = updateBusy - ? (canApplyUpdate ? t("btn.doUpdate.busy") : t("btn.checkUpdate.busy")) - : (canApplyUpdate ? t("btn.doUpdate") : t("btn.checkUpdate")); + const versions = (updateInfo && updateInfo.versions) || []; + const channelNow = (updateInfo && updateInfo.channel) || channel || "stable"; + const renderLane = (id) => { + const lane = (updateInfo && updateInfo.lanes && updateInfo.lanes[id]) || {}; + const list = versions.filter((item) => item.channel === id); + const selectedRef = pick[id] || ""; + const hit = list.find((item) => item.ref === selectedRef) || list.find((item) => item.current) || list.find((item) => item.latest); + const onLane = channelNow === id; + const noBeta = id === "beta" && updateInfo && updateInfo.hasBeta === false && !list.length; + const pickedOther = Boolean(hit && selectedRef && !hit.current); + let actionLabel = t("btn.checkUpdate"); + let actionKind; + let actionClick = checkUpdate; + let actionDisabled = updateBusy || Boolean(noBeta); + if (noBeta) { + actionLabel = t("update.noBeta"); + actionClick = () => {}; + } else if (pickedOther) { + actionLabel = t("update.switch"); + actionKind = "primary"; + actionClick = () => switchSelected(id); + } else if (!onLane) { + actionLabel = id === "beta" ? t("channel.useBeta") : t("channel.useStable"); + actionKind = "primary"; + actionClick = () => changeChannel(id); + } else if (lane.hasUpdate) { + actionLabel = t("btn.doUpdate"); + actionKind = "primary"; + actionClick = () => doUpdate(id); + } + if (updateBusy) { + if (pickedOther || !onLane) actionLabel = t("update.switching"); + else if (lane.hasUpdate && onLane) actionLabel = t("btn.doUpdate.busy"); + else actionLabel = t("btn.checkUpdate.busy"); + } + const verText = lane.version ? "v" + lane.version : (hit && hit.version ? "v" + hit.version : "—"); + return h("div", { + className: "dshp-lane" + (onLane ? " is-on" : "") + (id === "beta" ? " is-beta" : ""), + "aria-label": t("channel." + id), + }, + h("p", { className: "dshp-lane-kicker" }, onLane ? t("channel.now") : t("channel.other")), + h("div", { className: "dshp-lane-h" }, + h("strong", null, t("channel." + id)), + h("span", { className: "dshp-lane-ver" }, verText), + ), + h("div", { className: "dshp-lane-ops" }, + h("select", { + className: "dshp-field dshp-ver", + value: selectedRef || (hit && hit.ref) || "", + disabled: updateBusy || !list.length, + onChange: (e) => setPick((prev) => Object.assign({}, prev, { [id]: e.target.value })), + "aria-label": t("update.pick"), + }, + list.length + ? list.map((item) => h("option", { + key: item.ref + (item.sha || ""), + value: item.ref, + }, (item.version ? "v" + item.version : item.label) + (item.current ? " · " + t("update.current") : item.latest ? " · " + t("update.tip") : ""))) + : h("option", { value: "" }, noBeta ? t("update.noBeta") : t("update.pick")), + ), + h(Btn, { kind: actionKind, disabled: actionDisabled, onClick: actionClick }, actionLabel), + ), + ); + }; return h("section", { className: "dshp-panel", "aria-label": t("purge.title") }, h("div", { className: "dshp-head" }, h("h3", { className: "dshp-title" }, t("purge.title")), - h("div", { className: "dshp-row", style: { margin: 0, flex: 1, justifyContent: "flex-end" } }, - h("span", { className: "dshp-pill" }, t("surface." + hostSurface)), - versionText ? h("span", { className: "dshp-pill" + (canApplyUpdate ? " is-wait" : "") }, versionText) : null, - h(Btn, { - tiny: true, - kind: canApplyUpdate ? "primary" : undefined, - disabled: updateBusy, - onClick: canApplyUpdate ? doUpdate : checkUpdate, - }, updateBtnLabel), - noticeNode(updateNotice), + h("span", { className: "dshp-pill" }, t("surface." + hostSurface)), + ), + h("div", { className: "dshp-rel" }, + h("div", { className: "dshp-lanes" }, + renderLane("stable"), + renderLane("beta"), ), + noticeNode(updateNotice), ), s ? h("div", { className: "dshp-metrics" }, h("div", { className: "dshp-metric" }, diff --git a/lib/index.js b/lib/index.js index 3d38719..ef760d8 100644 --- a/lib/index.js +++ b/lib/index.js @@ -744,6 +744,7 @@ function installWebServer(ctx, cfg) { dsh_home: state.dsh_home, plugin_version: updater.localVersion(), update: updater.lastUpdateResult(), + ...updater.channelPublic(), }); } catch (e) { sendJson(response, 500, { ok: false, error: String(e) }); @@ -908,10 +909,7 @@ function installWebServer(ctx, cfg) { if (request.method === "POST") { try { const body = await readJsonBody(request); - const result = body && body.auto - ? await updater.autoUpdateIfNeeded() - : await updater.applyUpdate(); - sendJson(response, 200, result); + sendJson(response, 200, await updater.handleUpdateOp(body || {})); } catch (e) { sendJson(response, 500, { ok: false, error: String(e) }); } diff --git a/lib/update.js b/lib/update.js index 0e2d710..01876b4 100644 --- a/lib/update.js +++ b/lib/update.js @@ -9,11 +9,14 @@ import { adapterFor, detectSurface } from "./surface.js"; import { cliInvocation } from "./desktop.js"; const REPO = "YuJunZhiXue/dsh-purge"; -const BRANCH = "master"; -const ZIP_URL = `https://github.com/${REPO}/archive/refs/heads/${BRANCH}.zip`; -export const TARBALL_URL = `https://github.com/${REPO}/archive/refs/heads/${BRANCH}.tar.gz`; -const GITHUB_SPEC = `github:${REPO}#${BRANCH}`; +const STABLE_REF = "master"; +const BETA_REF = "beta"; +export const TARBALL_URL = `https://github.com/${REPO}/archive/refs/heads/${STABLE_REF}.tar.gz`; const PLUGIN_ROOT = path.resolve(fileURLToPath(new URL(".", import.meta.url)), ".."); +const CHANNELS = { + stable: { id: "stable", ref: STABLE_REF, label: "正式版" }, + beta: { id: "beta", ref: BETA_REF, label: "测试版" }, +}; const COPY_NAMES = [ "lib", "bin", @@ -47,10 +50,107 @@ export function localVersion() { } } +function channelStatePath() { + return path.join(findDshHome(), "dsh-purge", "channel.json"); +} + +function historyPath() { + return path.join(findDshHome(), "dsh-purge", "version-history.json"); +} + function stampPath() { return path.join(findDshHome(), "dsh-purge", "installed-rev"); } +export function normalizeChannel(value) { + return String(value || "").toLowerCase() === "beta" ? "beta" : "stable"; +} + +function isBetaName(name) { + return /(?:^|[-._])(beta|rc|pre|preview|test)(?:\d|$|[-._])/i.test(String(name || "")); +} + +function splitVersion(raw) { + const text = String(raw || "").trim().replace(/^v/i, ""); + const cut = text.split("-"); + const core = String(cut[0] || "").split(".").map((n) => parseInt(n, 10) || 0); + return { core: [core[0] || 0, core[1] || 0, core[2] || 0], pre: cut.slice(1).join("-") }; +} + +export function versionIsNewer(remote, local) { + if (!remote) return false; + if (!local) return true; + if (String(remote) === String(local)) return false; + const a = splitVersion(remote); + const b = splitVersion(local); + for (let i = 0; i < 3; i += 1) { + if (a.core[i] !== b.core[i]) return a.core[i] > b.core[i]; + } + if (a.pre && !b.pre) return false; + if (!a.pre && b.pre) return true; + return a.pre > b.pre; +} + +export function readChannelState() { + const raw = readJson(channelStatePath()) || {}; + return { + channel: normalizeChannel(raw.channel), + pin: typeof raw.pin === "string" ? raw.pin.trim() : "", + }; +} + +function writeChannelState(next) { + const state = { + channel: normalizeChannel(next?.channel), + pin: typeof next?.pin === "string" ? next.pin.trim() : "", + }; + fs.mkdirSync(path.dirname(channelStatePath()), { recursive: true }); + fs.writeFileSync(channelStatePath(), `${JSON.stringify(state, null, 2)}\n`, "utf8"); + return state; +} + +export function channelPublic(state = readChannelState()) { + const meta = CHANNELS[state.channel] || CHANNELS.stable; + return { + channel: meta.id, + channelLabel: meta.label, + pin: state.pin || "", + }; +} + +function currentChannelRef(state = readChannelState()) { + return (CHANNELS[state.channel] || CHANNELS.stable).ref; +} + +function readHistory() { + const raw = readJson(historyPath()); + return Array.isArray(raw) ? raw : []; +} + +function pushHistory(entry) { + const next = [entry, ...readHistory().filter((item) => item && item.ref !== entry.ref)].slice(0, 20); + fs.mkdirSync(path.dirname(historyPath()), { recursive: true }); + fs.writeFileSync(historyPath(), `${JSON.stringify(next, null, 2)}\n`, "utf8"); +} + +function archiveZipUrl(ref) { + const value = String(ref || STABLE_REF); + if (/^[0-9a-f]{40}$/i.test(value)) return `https://github.com/${REPO}/archive/${value}.zip`; + if (/^v?\d/.test(value)) return `https://github.com/${REPO}/archive/refs/tags/${encodeURIComponent(value)}.zip`; + return `https://github.com/${REPO}/archive/refs/heads/${encodeURIComponent(value)}.zip`; +} + +function archiveTarballUrl(ref) { + const value = String(ref || STABLE_REF); + if (/^[0-9a-f]{40}$/i.test(value)) return `https://github.com/${REPO}/archive/${value}.tar.gz`; + if (/^v?\d/.test(value)) return `https://github.com/${REPO}/archive/refs/tags/${encodeURIComponent(value)}.tar.gz`; + return `https://github.com/${REPO}/archive/refs/heads/${encodeURIComponent(value)}.tar.gz`; +} + +function githubSpec(ref) { + return `github:${REPO}#${ref || STABLE_REF}`; +} + function readStamp() { try { return fs.readFileSync(stampPath(), "utf8").trim(); @@ -205,15 +305,15 @@ export function runDshPlugin(profile, args) { }); } -export function pluginAddSpec(spec) { +export function pluginAddSpec(spec, ref = currentChannelRef()) { const s = String(spec || ""); - if (/\.(zip|tgz|tar\.gz)(\b|$)/i.test(s) || /^https?:\/\//i.test(s)) return TARBALL_URL; - if (/^github:/i.test(s) || /github\.com\/.+\.git/i.test(s)) return GITHUB_SPEC; + if (/\.(zip|tgz|tar\.gz)(\b|$)/i.test(s) || /^https?:\/\//i.test(s)) return archiveTarballUrl(ref); + if (/^github:/i.test(s) || /github\.com\/.+\.git/i.test(s)) return githubSpec(ref); return ""; } -function dshReinstall(profile, spec) { - const addSpec = pluginAddSpec(spec); +function dshReinstall(profile, spec, ref = currentChannelRef()) { + const addSpec = pluginAddSpec(spec, ref); if (addSpec) { runDshPlugin(profile, ["add", "--force", addSpec]); return; @@ -221,7 +321,7 @@ function dshReinstall(profile, spec) { try { runDshPlugin(profile, ["update", "dsh-purge"]); } catch { - runDshPlugin(profile, ["add", "--force", TARBALL_URL]); + runDshPlugin(profile, ["add", "--force", archiveTarballUrl(ref)]); } } @@ -312,8 +412,8 @@ function versionFromPackageText(text) { return pkg && pkg.version ? String(pkg.version) : ""; } -async function remotePackageVersion(sha = "") { - const ref = sha || BRANCH; +async function remotePackageVersion(sha = "", fallbackRef = STABLE_REF) { + const ref = sha || fallbackRef; const urls = [ sha ? `https://cdn.jsdelivr.net/gh/${REPO}@${sha}/package.json` : "", `https://raw.githubusercontent.com/${REPO}/${ref}/package.json`, @@ -340,11 +440,12 @@ async function remotePackageVersion(sha = "") { return ""; } -async function remoteHeadSha() { - const fromApi = fetchJson(`https://api.github.com/repos/${REPO}/commits/${BRANCH}`) +async function remoteHeadSha(ref = STABLE_REF) { + const target = encodeURIComponent(ref || STABLE_REF); + const fromApi = fetchJson(`https://api.github.com/repos/${REPO}/commits/${target}`) .then((data) => (data?.sha ? String(data.sha) : "")) .catch(() => ""); - const fromAtom = fetchText(`https://github.com/${REPO}/commits/${BRANCH}.atom`) + const fromAtom = fetchText(`https://github.com/${REPO}/commits/${ref}.atom`) .then((atom) => { const hit = atom.match(/tag:github\.com,2008:Grit::Commit\/([0-9a-f]{40})<\/id>/); return hit ? hit[1] : ""; @@ -354,31 +455,212 @@ async function remoteHeadSha() { return apiSha || atomSha || ""; } -export async function checkUpdate() { +function versionLabel(version, channel, sha = "") { + const ver = String(version || "").replace(/^v/, "") || (sha ? String(sha).slice(0, 7) : ""); + const mark = channel === "beta" ? "测试" : "正式"; + return ver ? `${ver}(${mark})` : mark; +} + +function rememberVersion(item, seen) { + if (!item || !item.ref) return null; + const key = `${item.sha || ""}|${item.ref}`.toLowerCase(); + if (seen.has(key)) return null; + seen.add(key); + return item; +} + +function markCurrent(versions, state, localVer, localSha) { + return (versions || []).map((item) => ({ + ...item, + shaShort: item.shaShort || (item.sha ? String(item.sha).slice(0, 7) : ""), + current: Boolean( + (localSha && item.sha && sameRev(localSha, item.sha)) + || (state.pin && item.ref === state.pin) + || (!state.pin && item.latest && item.channel === state.channel && item.version && item.version === localVer) + || (!state.pin && item.version && item.version === localVer && item.channel === (isBetaName(localVer) ? "beta" : "stable")), + ), + })); +} + +async function listGithubTags() { + try { + const rows = await fetchJson(`https://api.github.com/repos/${REPO}/tags?per_page=50`); + if (!Array.isArray(rows)) return []; + return rows.map((row) => { + const name = String(row?.name || "").trim(); + if (!name || !/^v?\d+\.\d+/.test(name)) return null; + const sha = row?.commit?.sha ? String(row.commit.sha) : ""; + const channel = isBetaName(name) ? "beta" : "stable"; + return { + id: name, + ref: name, + sha, + version: name.replace(/^v/, ""), + channel, + label: versionLabel(name, channel, sha), + kind: "tag", + }; + }).filter(Boolean); + } catch { + return []; + } +} + +async function listRemoteVersions() { + const state = readChannelState(); + const seen = new Set(); + const out = []; + const add = (item) => { + const next = rememberVersion(item, seen); + if (next) out.push(next); + }; + + const [stableSha, betaSha, tags] = await Promise.all([ + remoteHeadSha(STABLE_REF), + remoteHeadSha(BETA_REF), + listGithubTags(), + ]); + + if (stableSha) { + const version = await remotePackageVersion(stableSha, STABLE_REF).catch(() => ""); + add({ + id: STABLE_REF, + ref: STABLE_REF, + sha: stableSha, + version: version || "", + channel: "stable", + label: `${versionLabel(version, "stable", stableSha)} · 最新`, + kind: "head", + latest: true, + }); + } + if (betaSha) { + const version = await remotePackageVersion(betaSha, BETA_REF).catch(() => ""); + add({ + id: BETA_REF, + ref: BETA_REF, + sha: betaSha, + version: version || "", + channel: "beta", + label: `${versionLabel(version, "beta", betaSha)} · 最新`, + kind: "head", + latest: true, + }); + } + for (const tag of tags) add(tag); + for (const item of readHistory()) { + if (!item || !item.ref) continue; + add({ + ...item, + label: item.label || versionLabel(item.version, item.channel, item.sha), + kind: item.kind || "history", + }); + } + const localVer = localVersion(); - const remoteSha = await remoteHeadSha(); - const remoteVer = await remotePackageVersion(remoteSha); - if (!remoteSha && !remoteVer) throw new Error("无法读取 GitHub master"); + const localSha = (gitOk() ? gitHead(PLUGIN_ROOT) : "") || readStamp(); + return { + versions: markCurrent(out, state, localVer, localSha), + hasBeta: Boolean(betaSha || out.some((item) => item.channel === "beta" && item.kind === "tag")), + stableSha, + betaSha, + }; +} + +function alignChannelState(state, listed, localRev, localVer) { + if (state.pin) return state; + if (listed.betaSha && localRev && sameRev(localRev, listed.betaSha) && state.channel !== "beta") { + return writeChannelState({ channel: "beta", pin: "" }); + } + if (listed.stableSha && localRev && sameRev(localRev, listed.stableSha) && state.channel !== "stable") { + return writeChannelState({ channel: "stable", pin: "" }); + } + if (!localRev && localVer) { + const inferred = isBetaName(localVer) ? "beta" : "stable"; + if (inferred !== state.channel) return writeChannelState({ channel: inferred, pin: "" }); + } + return state; +} + +function describeLane(id, listed, state, localVer, localRev) { + const sha = id === "beta" ? listed.betaSha : listed.stableSha; + const versions = listed.versions.filter((item) => item.channel === id); + const latest = versions.find((item) => item.latest); + const version = latest?.version || ""; + const onLane = state.channel === id; + const matchesHead = Boolean(localRev && sha && sameRev(localRev, sha)); + const current = versions.some((item) => item.current) || matchesHead + || Boolean(onLane && version && localVer && version === localVer && !state.pin); + let hasUpdate = false; + if (onLane && state.pin) { + hasUpdate = Boolean(sha && localRev && !sameRev(localRev, sha)); + } else if (onLane && sha && localRev) { + hasUpdate = !sameRev(localRev, sha) || versionIsNewer(version, localVer); + } else if (onLane && versionIsNewer(version, localVer)) { + hasUpdate = true; + } + return { + id, + ref: CHANNELS[id].ref, + version, + sha: sha ? String(sha).slice(0, 7) : "", + current, + hasUpdate, + hasRemote: Boolean(sha || versions.length), + }; +} + +function lanesOf(listed, state, localVer, localRev) { + return { + stable: describeLane("stable", listed, state, localVer, localRev), + beta: describeLane("beta", listed, state, localVer, localRev), + }; +} + +export async function checkUpdate() { + let state = readChannelState(); + const localVer = localVersion(); + const listed = await listRemoteVersions(); const gitSha = gitOk() ? gitHead(PLUGIN_ROOT) : ""; const stamp = readStamp(); const localRev = gitSha || stamp; - let hasUpdate = false; - if (remoteSha && localRev) { - hasUpdate = !sameRev(localRev, remoteSha); - } else if (remoteVer && localVer && remoteVer !== localVer) { - hasUpdate = true; - } else if (remoteSha && !localRev) { - // zip / dsh 安装没有 stamp,按有更新处理,拉一次与 master 对齐。 - hasUpdate = true; + state = alignChannelState(state, listed, localRev, localVer); + listed.versions = markCurrent(listed.versions, state, localVer, localRev); + const channelRef = currentChannelRef(state); + const lanes = lanesOf(listed, state, localVer, localRev); + const lane = lanes[state.channel] || lanes.stable; + if (!lane.hasRemote && state.channel === "beta") { + return rememberUpdate({ + ok: true, + hasUpdate: false, + hasBeta: false, + error: "还没有测试版", + localVersion: localVer, + remoteVersion: "", + localSha: localRev ? localRev.slice(0, 7) : "", + remoteSha: "", + updateTarget: channelRef, + via: detectVia(), + versions: listed.versions, + lanes, + ...channelPublic(state), + }); } + if (!lanes.stable.hasRemote) throw new Error("无法读取 GitHub master"); const result = { ok: true, - hasUpdate, + hasUpdate: Boolean(lane.hasUpdate), + hasBeta: listed.hasBeta, + updateTarget: channelRef, + pinned: Boolean(state.pin), localVersion: localVer, - remoteVersion: remoteVer || (remoteSha ? remoteSha.slice(0, 7) : ""), + remoteVersion: lane.version || lane.sha, localSha: localRev ? localRev.slice(0, 7) : "", - remoteSha: remoteSha ? remoteSha.slice(0, 7) : "", + remoteSha: lane.sha, via: detectVia(), + versions: listed.versions, + lanes, + ...channelPublic(state), }; rememberUpdate(result); return result; @@ -422,21 +704,31 @@ function runGit(dir, args, timeout = 20000) { } } -function gitPull(dir) { +function gitResetTo(dir, ref, { force = false } = {}) { + if (!force && gitTrackedDirty(dir)) { + throw new Error("本地插件文件有未提交改动,未覆盖"); + } + const target = String(ref || STABLE_REF); try { - runGit(dir, ["pull", "--ff-only", "origin", BRANCH], 60000); - return; - } catch (pullErr) { + runGit(dir, ["fetch", "origin", "--tags"], 60000); + } catch { + runGit(dir, ["fetch", "origin", "--tags", target], 60000); + } + if (target === STABLE_REF || target === BETA_REF) { try { - runGit(dir, ["fetch", "origin", BRANCH], 60000); - runGit(dir, ["reset", "--hard", `origin/${BRANCH}`], 60000); + runGit(dir, ["checkout", "-B", target, `origin/${target}`]); + return; + } catch { + runGit(dir, ["reset", "--hard", `origin/${target}`]); return; - } catch (resetErr) { - throw new Error( - `git 更新失败(${dir}):${String(resetErr.message || resetErr).slice(0, 240)};${String(pullErr.message || pullErr).slice(0, 160)}`, - ); } } + try { + runGit(dir, ["fetch", "origin", "--tags", target], 60000); + } catch { + // 上面已经 fetch 过全部分支。 + } + runGit(dir, ["reset", "--hard", target]); } function extractZip(zip, dest) { @@ -457,12 +749,12 @@ function extractZip(zip, dest) { ); } -async function overlayFromZip(dests) { +async function overlayFromZip(dests, ref = STABLE_REF) { const unique = [...new Set(dests.filter(Boolean).map((d) => realPath(d)))]; if (!unique.length) return; const tmp = await fsp.mkdtemp(path.join(os.tmpdir(), "dsh-purge-upd-")); - const zip = path.join(tmp, "master.zip"); - const res = await fetchRes(ZIP_URL, 45000); + const zip = path.join(tmp, "plugin.zip"); + const res = await fetchRes(archiveZipUrl(ref), 45000); await fsp.writeFile(zip, Buffer.from(await res.arrayBuffer())); extractZip(zip, tmp); const names = await fsp.readdir(tmp); @@ -473,8 +765,16 @@ async function overlayFromZip(dests) { for (const dest of unique) { for (const name of COPY_NAMES) { const from = path.join(unpacked, name); + const to = path.join(dest, name); if (!fs.existsSync(from)) continue; - await fsp.cp(from, path.join(dest, name), { recursive: true, force: true }); + if (name === "lib" || name === "docs" || name === "bin") { + try { + await fsp.rm(to, { recursive: true, force: true }); + } catch { + // 目录被占用时改为覆盖写入。 + } + } + await fsp.cp(from, to, { recursive: true, force: true }); } } try { @@ -484,23 +784,31 @@ async function overlayFromZip(dests) { } } -export async function applyUpdate(jobs = planUpdates()) { +export async function applyUpdate(jobs = planUpdates(), options = {}) { + if (!Array.isArray(jobs)) { + options = jobs && typeof jobs === "object" ? jobs : {}; + jobs = planUpdates(); + } + const state = readChannelState(); + const ref = String(options.ref || currentChannelRef(state) || STABLE_REF); + const force = options.force !== false; const zipDirs = []; const vias = new Set(); for (const job of jobs) { if (job.kind === "git") { try { - gitPull(job.dir); + gitResetTo(job.dir, ref, { force }); vias.add("git"); continue; - } catch { + } catch (e) { + if (!force && /未提交改动/.test(String(e && e.message))) throw e; zipDirs.push(job.dir); } continue; } if (job.kind === "dsh") { try { - dshReinstall(job.profile, job.spec); + dshReinstall(job.profile, job.spec, ref); vias.add("dsh"); continue; } catch { @@ -511,29 +819,102 @@ export async function applyUpdate(jobs = planUpdates()) { } } if (zipDirs.length) { - await overlayFromZip(zipDirs); + await overlayFromZip(zipDirs, ref); vias.add("zip"); } - const sha = (await remoteHeadSha()) || (gitOk() ? gitHead(PLUGIN_ROOT) : ""); + const sha = (await remoteHeadSha(ref)) || (gitOk() ? gitHead(PLUGIN_ROOT) : ""); if (sha) writeStamp(sha); const via = vias.size > 1 ? "mixed" : [...vias][0] || detectVia(); + const pin = options.pin === false ? "" : (options.pin || state.pin || ""); + const channel = normalizeChannel(options.channel || state.channel); + const saved = writeChannelState({ channel, pin }); + const localVer = localVersion(); + pushHistory({ + ref, + sha: sha || "", + version: localVer, + channel, + label: versionLabel(localVer, channel, sha), + at: new Date().toISOString(), + }); + const listed = await listRemoteVersions().catch(() => ({ versions: [], hasBeta: saved.channel === "beta" })); return rememberUpdate({ ok: true, applied: true, hasUpdate: false, - localVersion: localVersion(), - remoteVersion: localVersion(), + hasBeta: listed.hasBeta, + pinned: Boolean(saved.pin), + localVersion: localVer, + remoteVersion: localVer, localSha: sha ? String(sha).slice(0, 7) : "", remoteSha: sha ? String(sha).slice(0, 7) : "", needRestart: true, via, + versions: listed.versions, + lanes: lanesOf(listed, saved, localVer, sha), + ...channelPublic(saved), }); } +export async function switchChannel(channel, { apply = true } = {}) { + const next = normalizeChannel(channel); + if (next === "beta") { + const betaSha = await remoteHeadSha(BETA_REF); + const tags = await listGithubTags(); + const hasBeta = Boolean(betaSha || tags.some((item) => item.channel === "beta")); + if (!hasBeta) { + return rememberUpdate({ + ok: false, + error: "还没有测试版", + hasBeta: false, + ...channelPublic(), + versions: [], + lanes: { stable: { id: "stable", hasRemote: true }, beta: { id: "beta", hasRemote: false } }, + }); + } + if (!betaSha && apply) { + const tag = tags.find((item) => item.channel === "beta"); + if (tag) return applyUpdate(planUpdates(), { ref: tag.ref, channel: "beta", pin: false, force: true }); + } + } + if (!apply) { + writeChannelState({ channel: next, pin: "" }); + return checkUpdate(); + } + return applyUpdate(planUpdates(), { ref: CHANNELS[next].ref, channel: next, pin: false, force: true }); +} + +export async function switchVersion(ref) { + const target = String(ref || "").trim(); + if (!target) throw new Error("请选择要回退的版本"); + const listed = await listRemoteVersions(); + const hit = listed.versions.find((item) => item.ref === target || item.id === target || item.version === target || item.sha === target); + const resolved = hit?.ref || target; + const channel = hit?.channel || readChannelState().channel; + const pin = hit?.latest ? "" : resolved; + return applyUpdate(planUpdates(), { ref: resolved, channel, pin, force: true }); +} + +export async function handleUpdateOp(body = {}) { + const op = String(body.op || (body.auto ? "auto" : "apply")).toLowerCase(); + if (op === "check" || op === "status" || op === "versions") return checkUpdate(); + if (op === "channel") return switchChannel(body.channel, { apply: body.apply !== false }); + if (op === "switch" || op === "rollback") return switchVersion(body.ref || body.version || body.id); + if (op === "auto") return autoUpdateIfNeeded(); + const state = readChannelState(); + const ref = body.ref || currentChannelRef(state); + const channel = body.channel || (ref === BETA_REF ? "beta" : ref === STABLE_REF ? "stable" : state.channel); + return applyUpdate(planUpdates(), { ref, channel, pin: false, force: true }); +} + export async function autoUpdateIfNeeded() { try { const check = await checkUpdate(); + if (check.pinned) return rememberUpdate({ ...check, auto: true, skipped: "pinned" }); if (!check.hasUpdate) return rememberUpdate({ ...check, auto: true, skipped: "latest" }); + if (check.updateTarget === BETA_REF && readChannelState().channel !== "beta") { + return rememberUpdate({ ...check, auto: true, skipped: "beta" }); + } const jobs = planUpdates(); const dirtyGit = jobs.filter((j) => j.kind === "git" && gitTrackedDirty(j.dir)); const runnable = jobs.filter((j) => !(j.kind === "git" && gitTrackedDirty(j.dir))); @@ -545,7 +926,12 @@ export async function autoUpdateIfNeeded() { error: "本地插件文件有未提交改动,未自动覆盖", }); } - const applied = await applyUpdate(runnable); + const applied = await applyUpdate(runnable, { + ref: currentChannelRef(), + channel: readChannelState().channel, + pin: false, + force: false, + }); return rememberUpdate({ ...applied, auto: true }); } catch (e) { return rememberUpdate({ @@ -553,6 +939,7 @@ export async function autoUpdateIfNeeded() { auto: true, hasUpdate: false, error: String(e && e.message ? e.message : e), + ...channelPublic(), }); } } diff --git a/package.json b/package.json index 5743b76..398ec4e 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "dsh-purge", - "version": "1.1.10", + "version": "1.1.11", "description": "DeepSeek Harness 网络安全红队工具:本机官方 Harness 受控评测与清洗,不同模型可换不同提示词;默认提示词面向国模「小码酱」。求 Star ⭐", "type": "module", "main": "lib/index.js",