fix: 二次 Apply 不再误报 #26/#27,重启等到会话树落地再进页面

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
yangandCursor committed 2026-09-17 13:33:34 +08:00
1 parent 6c88f4d075
commit fd4dfa4e38
11 files changed
+254 -432

No files matched your search

+36 -41
View File
@@ -1,11 +1,3 @@
// dsh-purge 插件入口(小杨)
// 功能(移植自 dsh_purge.py,一个不差):
// 1. 启动自动重洗(autoApplyOnStart)— 解决 npm 升级覆盖 node_modules 后需手动重跑的痛点
// 2. /purge 命令 — status / apply / revert / edit / help
// 2b. /rules 命令 — list / use / create / delete / reset
// 3. 模型工具 — purge_status / purge_apply / purge_revert
// 4. systemPrompt 注入 — 会话强指令 section(兜底,不依赖改文件)
import fs from "node:fs";
import { promises as fsp } from "node:fs";
import path from "node:path";
@@ -35,12 +27,38 @@ const log = (config, ...args) => {
if (config?.verbose) console.log("[dsh-purge]", ...args);
};
let webTreeReady = false;
function watchWebTreeReady(ctx) {
// 必须挂在 connection 上再 await,与官方打印 URL 同一时刻。
// apply() 里立刻 await 会在后续入口尚未入树时提前结束,session.list 仍是空的。
const mark = () => {
webTreeReady = true;
};
if (typeof ctx?.inject !== "function") {
mark();
return;
}
try {
ctx.inject(["connection"], (host) => {
const settled = host.get?.("loader")?.await?.();
if (!settled || typeof settled.then !== "function") {
mark();
return;
}
settled.then(() => {
if (host.get?.("webServer") !== undefined && host.get?.("connection") !== undefined) mark();
}, mark);
});
} catch {
mark();
}
}
function fsExists(fp) {
return fs.existsSync(fp);
}
// ── 文本渲染(无 rich 依赖)───────────────────────────────────────
function line(title, value, ok = null) {
const mark = ok === null ? "·" : ok ? "✓" : "✗";
return `${mark} ${title}: ${value}`;
@@ -88,7 +106,6 @@ function readInjectFile(injectFile) {
}
export function registerPromptSections(ctx, config, injectFile) {
// prompt-inject.md verbatim. No plugin identity card.
ctx.systemPrompt.section({
name: "dsh-purge",
order: GLOBAL_PROMPT_ORDER,
@@ -123,7 +140,6 @@ export function registerPromptSections(ctx, config, injectFile) {
});
}
/** Cap fallback inject read so a huge/corrupt prompt-inject.md cannot blow memory each assemble. */
const INJECT_FALLBACK_MAX_BYTES = 512 * 1024;
function readInjectFallback() {
@@ -150,16 +166,12 @@ function installIdentityOverride(ctx) {
if (typeof ctx.on !== "function") return;
const hook = async (_assembly, _context, next) => {
const assembled = typeof next === "function" ? await next() : _assembly;
// Fallback file read covers Liangshen phase-1 races where purge sections
// were filtered before this hook ran — first turn must still get inject.
return rewritePromptAssembly(assembled, readInjectFallback());
};
// Inner (no prepend): fold inject into persona BEFORE Liangshen phase-1 filter.
// prepend:false 先于 phase-1 滤镜;prepend:true 在滤镜之后再折一次。
try {
ctx.on("system-prompt/assemble", hook, { global: true, prepend: false });
} catch {}
// Outer (prepend): if filter already ran, re-fold from file. Re-register once
// after plugins settle so we stay outermost without stacking three listeners.
ctx.on("system-prompt/assemble", hook, { global: true, prepend: true });
const late = () => {
try {
@@ -170,8 +182,6 @@ function installIdentityOverride(ctx) {
setTimeout(late, 1500);
}
// ── 自动重洗 ──────────────────────────────────────────────────────
const LAUNCHER_SHIM_NAMES = ["dsh.cmd", "dsh.ps1", "dsh"];
function desktopShimNeedsPatch(dirs) {
@@ -204,7 +214,6 @@ async function autoApply(config) {
log(config, "skip auto-apply: plugin root not found");
return "skip:plugin_root_not_found";
}
// No-flash must complete on every start — same pass as UI Apply.
try {
const flash = core.silenceCmdFlash(state.ai_base);
log(config, "cmd-flash:", JSON.stringify(flash));
@@ -240,8 +249,6 @@ async function autoApply(config) {
}
}
// ── 命令处理 ──────────────────────────────────────────────────────
async function handlePurgeCommand(rawInput, config) {
const args = (rawInput || "").trim().split(/\s+/).filter(Boolean);
const sub = (args[0] || "status").toLowerCase();
@@ -442,15 +449,11 @@ async function handleRulesCommand(rawInput) {
}
}
// ── 插件 apply ────────────────────────────────────────────────────
export function apply(ctx, config) {
const cfg = { ...DEFAULTS, ...(config || {}) };
if (!cfg.enabled) return;
log(cfg, "plugin enabled");
// Scrub illegal in-bin *.dshpurge.bak early; still patch Desktop launchers later.
// Windows: force CREATE_NO_WINDOW on every child_process spawn in this host.
try {
const hide = core.ensureHiddenConsole();
log(cfg, "hide-console:", JSON.stringify(hide));
@@ -465,7 +468,6 @@ export function apply(ctx, config) {
console.warn("[dsh-purge] desktop runtime scrub error:", String(e));
}
// 1. 启动自动重洗(异步,不阻塞启动)
setImmediate(() => {
autoApply(cfg).then((r) => log(cfg, "auto-apply:", r));
rules.ensureInitialState(core.findDshHome())
@@ -473,12 +475,10 @@ export function apply(ctx, config) {
.catch((e) => console.warn("[dsh-purge] rules init error:", String(e)));
});
// 2. systemPrompt 注入(操作员提示词放在 persona 之后,避免被 coding agent 盖住)
installIdentityOverride(ctx);
const injectFile = core.findOverrideFile(core.findDshHome());
registerPromptSections(ctx, cfg, injectFile);
// 3. /purge 命令
const commands = ctx.get?.("commands");
if (commands) {
commands.register({
@@ -495,7 +495,6 @@ export function apply(ctx, config) {
});
}
// 4. 模型工具(原始 JSON-Schema ToolDefinition,零 peer 依赖)
if (ctx.tools) {
ctx.tools.register({
name: "purge_status",
@@ -580,7 +579,6 @@ export function apply(ctx, config) {
});
}
// 5. HTTP API(Web UI 设置面板用)
installWebServer(ctx, cfg);
}
@@ -597,15 +595,12 @@ function hostFromRequest(request) {
}
function restartArgv() {
// Always relaunch via node + absolute bin.js — never dsh.cmd (cmd.exe always flashes).
const root = core.findDshBinRoot();
const binJs = root ? path.join(root, "lib", "bin.js") : null;
if (binJs && fs.existsSync(binJs)) {
const args = [binJs];
// Keep profile/subcommand flags from the current process, drop the old entry path.
// 复用当前 argv 的 profile/子命令,入口改走 node + bin.js。
const rest = process.argv.slice(2).filter((arg) => arg !== "--no-open");
// If argv was `node bin.js web ...`, slice(2) is already `web ...`.
// If argv was `node dsh.cmd web` weirdness, ensure `web` is present when we are a web host.
if (!rest.includes("web") && !rest.includes("desktop")) {
const port = Number(process.env.PORT) || 3080;
rest.unshift("web", "--port", String(port));
@@ -628,7 +623,6 @@ function restartArgv() {
}
function scheduleWebRestart(request) {
// Final no-flash pin before exit so the replacement process loads hide-console first.
try {
core.silenceCmdFlash();
} catch {}
@@ -650,13 +644,11 @@ function scheduleWebRestart(request) {
},
});
child.unref();
// Exit only after the helper is detached; apply/restart handlers already finished.
setTimeout(() => process.exit(0), 250);
}
// ── Web UI 设置面板后端(HTTP 路由)──────────────────────────────
function installWebServer(ctx, cfg) {
watchWebTreeReady(ctx);
ctx.inject(["webServer"], (host) => {
host.effect(() => {
host.webServer.register({
@@ -669,11 +661,16 @@ function installWebServer(ctx, cfg) {
return;
}
try {
if (!webTreeReady) {
sendJson(response, 503, { ok: false, ready: false });
return;
}
const state = await core.gatherState();
const patch_names = {};
for (const p of core.ALL_PATCHES) patch_names[String(p.id)] = p.name;
sendJson(response, 200, {
ok: true,
ready: true,
ai_base: state.ai_base,
patches_applied: state.patches_applied,
patches_pending: state.patches_pending,
@@ -714,10 +711,8 @@ function installWebServer(ctx, cfg) {
const report = await core.applyPatches(state.ai_base);
const override = await core.ensureOverrideContent(state.dsh_home, false);
const shim = await core.patchAllShims();
// Apply must finish the no-flash pass before offering restart.
const flash = core.silenceCmdFlash(state.ai_base);
const summary = core.summarizeApplyReport(report);
// Restart when required patches are soft-ok AND (on win32) bin pin is ok/soft.
const complete = summary.failed.length === 0 && flash.ok === true;
sendJson(response, 200, {
ok: true,