@1e0zj/dsh-plugin-mall 0.2.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -234,6 +234,16 @@ node <profile>/node_modules/@1e0zj/dsh-plugin-mall/src/cli.js guard launch --pro
234
234
  (这行会出现在任务日志里)。更新检查读的是 registry 的 `/latest` 端点,
235
235
  不经过该策略,所以两边看到的「最新版本」本就可能不同。
236
236
  首次安装(卡片按钮)不带版本,沿用 pnpm 的策略默认值即可。
237
+ - **启用 / 停用,不必卸载**:已装面板每行一个开关,关掉即刻卸载该插件的
238
+ fiber,重新打开时它、以及因依赖它而挂起的插件都会回来。三层落地:内存用
239
+ `entry.update({disabled})`;持久化改写 profile 的 `cordis.patch.yml`(保留
240
+ 注释),由 dsh 自己的 `watchUserPatches` 事务性重放,所以重启后状态保持;
241
+ 写入前自动备份到 `<profile>/backups/`(留最近 20 份)。
242
+ 市场插件自身不给开关——停用了就没有界面再打开它。用户手写的
243
+ `disabled: !!js …` 条件表达式会被**拒绝接管**并提示手改:那是条件逻辑,
244
+ 两态开关覆盖它等于把条件永久压成固定值。
245
+ (界面类插件的变化需要刷新页面才反映:浏览器那半边靠页面加载时注入的
246
+ 启动清单,后端的开关立即生效,已加载的模块不会自行卸载。)
237
247
  - **一次点击一个任务,日志从第一毫秒开始流**:预检本身就是一个任务,点安装
238
248
  的瞬间就出现在面板里,隔离探针的 pnpm 输出实时写入——而不是让按钮干等几秒
239
249
  再冒出结果。预检通过后由安装任务接管同一条日志、撤掉预检条目,所以面板上
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@1e0zj/dsh-plugin-mall",
3
- "version": "0.2.1",
3
+ "version": "0.3.0",
4
4
  "description": "dsh 插件市场:搜索 GitHub dsh-plugin 话题下的插件仓库,一键安装到本地 dsh profile(agent 工具 + 设置页插件市场 tab)",
5
5
  "type": "module",
6
6
  "main": "src/index.js",
package/src/client.js CHANGED
@@ -66,6 +66,12 @@ window.__ModuleLoader__.load({
66
66
  ".mkt_approveCmd{max-height:none;margin:0}",
67
67
  ".mkt_jobDone{display:flex;align-items:center;gap:8px;flex-wrap:wrap;margin-top:2px}",
68
68
  ".mkt_logBlock{display:flex;flex-direction:column;gap:4px;align-items:flex-start}",
69
+ ".mkt_depOff{opacity:.5;text-decoration:line-through}",
70
+ ".mkt_switch{position:relative;width:34px;height:18px;border-radius:999px;border:1px solid var(--dsw-alias-border-l2);background:var(--dsw-alias-bg-secondary,#e5e7eb);cursor:pointer;padding:0;transition:background .15s,border-color .15s}",
71
+ ".mkt_switch:disabled{opacity:.55;cursor:default}",
72
+ ".mkt_switchOn{background:var(--dsw-alias-state-business-primary,#2b6cb0);border-color:transparent}",
73
+ ".mkt_switchKnob{position:absolute;top:1px;left:1px;width:14px;height:14px;border-radius:50%;background:#fff;transition:transform .15s;box-shadow:0 1px 2px rgba(0,0,0,.25)}",
74
+ ".mkt_switchOn .mkt_switchKnob{transform:translateX(16px)}",
69
75
  ".mkt_issueList{list-style:none;display:flex;flex-direction:column;gap:8px;margin:0;padding:0}",
70
76
  ".mkt_issue{border:1px solid var(--dsw-alias-border-l2);border-radius:8px;padding:8px 10px;background:var(--dsw-alias-bg-secondary,#fff)}",
71
77
  ".mkt_issueBlock{border-color:var(--dsw-alias-state-error-primary)}",
@@ -338,6 +344,8 @@ window.__ModuleLoader__.load({
338
344
  );
339
345
  }
340
346
 
347
+ var MARKET_PACKAGE = "@1e0zj/dsh-plugin-mall";
348
+
341
349
  function jobKindLabel(kind) {
342
350
  if (kind === "dsh-plugin-preflight") return "预检 ";
343
351
  if (kind === "dsh-plugin-uninstall") return "卸载 ";
@@ -462,10 +470,23 @@ window.__ModuleLoader__.load({
462
470
  : h("div", { className: "mkt_depList" }, (installed.deps || []).map(function (dep) {
463
471
  var busy = (props.removing || {})[dep.name] === true;
464
472
  var upd = (props.updates || {})[dep.name];
473
+ var entry = (props.entries || {})[dep.name];
474
+ // 没在装配树里的依赖(普通依赖、或声明了 client 但没挂载的)
475
+ // 没有可切换的东西,不给开关。
476
+ var togglable = entry !== undefined && dep.name !== MARKET_PACKAGE;
477
+ var enabled = entry === undefined ? true : entry.enabled !== false;
478
+ var toggling = (props.toggling || {})[dep.name] === true;
465
479
  return h("div", { key: dep.name, className: "mkt_depRow" },
466
- h("span", { className: "mkt_desc" }, dep.name + "@" + dep.version),
480
+ h("span", { className: "mkt_desc" + (enabled ? "" : " mkt_depOff") }, dep.name + "@" + dep.version),
467
481
  h("span", { className: "mkt_depActions" },
468
- h("span", { className: "mkt_badge" }, kindLabel(dep.kind)),
482
+ h("span", { className: "mkt_badge" }, enabled ? kindLabel(dep.kind) : "已停用"),
483
+ togglable ? h("button", {
484
+ className: "mkt_switch" + (enabled ? " mkt_switchOn" : ""),
485
+ disabled: toggling,
486
+ title: enabled ? "停用(立即生效,不卸载)" : "启用(立即生效)",
487
+ "aria-pressed": enabled ? "true" : "false",
488
+ onClick: function () { props.onToggle(dep.name, !enabled); },
489
+ }, h("span", { className: "mkt_switchKnob" })) : null,
469
490
  upd && upd.hasUpdate ? h("button", {
470
491
  className: "mkt_btn mkt_btnSm",
471
492
  onClick: function () { props.onInstallSpec(dep.name + "@" + upd.latest); },
@@ -506,6 +527,9 @@ window.__ModuleLoader__.load({
506
527
  var _removing = useState({});
507
528
  var removing = _removing[0];
508
529
  var setRemoving = _removing[1];
530
+ var _toggling = useState({});
531
+ var toggling = _toggling[0];
532
+ var setToggling = _toggling[1];
509
533
  var _page = useState(1);
510
534
  var page = _page[0];
511
535
  var setPage = _page[1];
@@ -631,6 +655,26 @@ window.__ModuleLoader__.load({
631
655
  return function () { observer.disconnect(); };
632
656
  }, [loadMore]);
633
657
 
658
+ // 启用/停用:热生效,不重启也不重装——所以成功后只刷新已装列表,
659
+ // 不提示重启,也不动任务面板(它不是一个需要看日志的长任务)。
660
+ var doToggle = useCallback(function (packageName, enabled) {
661
+ setToggling(function (prev) { return Object.assign({}, prev, { [packageName]: true }); });
662
+ setError(null);
663
+ call("togglePlugin", { package: packageName, enabled: enabled }).then(function (value) {
664
+ setInstalled(function (prev) {
665
+ return prev && !prev.error ? Object.assign({}, prev, { entries: value.entries }) : prev;
666
+ });
667
+ }).catch(function (e) {
668
+ setError(errorText(e));
669
+ }).finally(function () {
670
+ setToggling(function (prev) {
671
+ var next = Object.assign({}, prev);
672
+ delete next[packageName];
673
+ return next;
674
+ });
675
+ });
676
+ }, [call]);
677
+
634
678
  var refreshInstalled = useCallback(function () {
635
679
  call("installed", {}).then(function (value) {
636
680
  setInstalled(value);
@@ -828,7 +872,16 @@ window.__ModuleLoader__.load({
828
872
  "只看已验证插件")
829
873
  ),
830
874
  error ? h("div", { className: "mkt_error" }, error) : null,
831
- h(InstalledPanel, { installed: installed, removing: removing, updates: updates, onUninstall: doUninstall, onInstallSpec: preflightAndInstall }),
875
+ h(InstalledPanel, {
876
+ installed: installed,
877
+ removing: removing,
878
+ updates: updates,
879
+ entries: installed && !installed.error ? installed.entries : undefined,
880
+ toggling: toggling,
881
+ onToggle: doToggle,
882
+ onUninstall: doUninstall,
883
+ onInstallSpec: preflightAndInstall,
884
+ }),
832
885
  h(JobsPanel, {
833
886
  jobs: jobs,
834
887
  onClear: function () {
package/src/index.js CHANGED
@@ -24,11 +24,16 @@ import { createRequire } from "node:module";
24
24
  import { tmpdir } from "node:os";
25
25
  import { resolveProfileDir } from "@deepseek-ai/dsh-app-boot";
26
26
  import { repoInfo, searchPlugins, verifyPlugins, cachedRepoManifest, fetchRawFile, preferNpmSpec, npmPackageInfo, compareVersions, assertSafeToInstall, mapLimit, NETWORK_CONCURRENCY } from "./github.js";
27
- import { ensureProfile, listInstalled, normalizeSpec, runInstall, runRemove, assertSafeSpec, resolveRegistry, serializeCanonicalProof } from "./installer.js";
27
+ import { ensureProfile, listInstalled, normalizeSpec, runInstall, runRemove, assertSafeSpec, resolveRegistry, serializeCanonicalProof, persistPluginDisabled } from "./installer.js";
28
28
  import { preflightInstall, inspectRemoteCandidate, recoverProfile } from "./guard.js";
29
29
 
30
30
  export const name = "@1e0zj/dsh-plugin-mall";
31
- export const inject = ["tools", "jobs", "systemPrompt"];
31
+ // `loader` 用来读装配树、并对单个 entry 做热开关(entry.update)。读法照抄
32
+ // 官方的 @deepseek-ai/dsh-host-plugin-inventory —— 它是只读投影
33
+ // ("Read-only Remote projection of current Cordis Loader plugin state"),
34
+ // 写入侧留白,正是这里补的位置。持久化不走 loader(见 togglePlugin 的说明)。
35
+ // loader 必然存在——没有它我们根本加载不了。
36
+ export const inject = ["tools", "jobs", "systemPrompt", "loader"];
32
37
 
33
38
  export const Config = z.object({
34
39
  defaultProfile: z.string().default("web"),
@@ -973,6 +978,53 @@ export function createJobTracker({ producerFactory } = {}) {
973
978
  };
974
979
  }
975
980
 
981
+ /**
982
+ * Group the loader's mounted entries by the package that provides them, so a
983
+ * profile dependency can be shown (and toggled) as one row.
984
+ *
985
+ * One package can insert several rows, so `enabled` means EVERY row of that
986
+ * package is live — a half-disabled package is reported as disabled, and
987
+ * toggling acts on the whole set. Group rows are skipped, mirroring the
988
+ * official read-only projection in @deepseek-ai/dsh-host-plugin-inventory.
989
+ */
990
+ export function loaderEntriesByPackage(ctx) {
991
+ const byPackage = {};
992
+ try {
993
+ for (const entry of ctx.loader.entries()) {
994
+ if (entry.options?.group) continue;
995
+ const moduleName = entry.options?.name;
996
+ if (typeof moduleName !== "string" || moduleName.length === 0) continue;
997
+ const bucket = byPackage[moduleName] ??= { entryIds: [], entries: [], enabled: true };
998
+ // 两个 id 必须分清:
999
+ // entry.id 运行时全路径,父链拼出来的(`include:dsh-at-file`)
1000
+ // entry.options.id 配置文件里写的那个(`dsh-at-file`)
1001
+ // patch 层的 id 定向覆盖按后者匹配(applyEntryPatches 从组装数据建
1002
+ // entryMap,键是各 patch 声明的 id)。拿前者去写 patch,那条覆盖行
1003
+ // 永远匹配不到目标,dsh 只会 warn 一句然后忽略——停用看着成功了,
1004
+ // 重启后插件照常回来。
1005
+ const configId = entry.options?.id;
1006
+ bucket.entryIds.push(entry.id);
1007
+ bucket.entries.push({ id: entry.id, configId, entry });
1008
+ if (entry.disabled) bucket.enabled = false;
1009
+ }
1010
+ } catch {
1011
+ /* loader 读不到就不给开关,安装/卸载照常可用 */
1012
+ }
1013
+ return byPackage;
1014
+ }
1015
+
1016
+ /**
1017
+ * The serializable half of loaderEntriesByPackage — live `entry` objects must
1018
+ * never reach the RPC envelope (they carry the whole fiber graph).
1019
+ */
1020
+ function serializableEntries(byPackage) {
1021
+ const out = {};
1022
+ for (const [moduleName, bucket] of Object.entries(byPackage)) {
1023
+ out[moduleName] = { entryIds: bucket.entryIds, enabled: bucket.enabled };
1024
+ }
1025
+ return out;
1026
+ }
1027
+
976
1028
  /** Render one preflight issue as a compact line for model/error output. */
977
1029
  function renderPreflightIssue(entry) {
978
1030
  const badge = entry.severity === "block" ? "BLOCK" : "WARN";
@@ -1193,7 +1245,60 @@ async function rpcDispatch(ctx, endpoint, payload, config, token, tracker) {
1193
1245
  } catch (error) {
1194
1246
  return rpcFail(new Error(`invalid profile: ${error.message}`));
1195
1247
  }
1196
- return rpcOk(listInstalled(profile));
1248
+ // 带上每个依赖在装配树里的启用状态,浏览器据此渲染开关。
1249
+ return rpcOk({ ...listInstalled(profile), entries: serializableEntries(loaderEntriesByPackage(ctx)) });
1250
+ }
1251
+ case "togglePlugin": {
1252
+ // 启用/停用,三层(同 cynch18/plugin-switch 的做法):
1253
+ // 1. 内存 —— entry.update({disabled}) 立即 dispose/start 对应 fiber
1254
+ // 2. 持久化 —— 文本改写用户的 cordis.patch.yml,由 dsh 自己的
1255
+ // watchUserPatches 事务性重放(启动时若无 HMR 会当场创建一个,
1256
+ // 见 @deepseek-ai/dsh 的 profile-boot:ctx.loader.create(hmr) →
1257
+ // watchUserPatches(profile patch) + watchUserPatches(home patch))
1258
+ // 3. 保险 —— 写前备份到 <profile>/backups/,留最近 20 份
1259
+ // 刻意不用 ctx.loader.update():它的 tree.write() 写的是 cordis.yml,
1260
+ // 那是组装产物;用户的选择该留在自己的 patch 层。
1261
+ const profile = String(payload?.profile ?? defaultProfile).trim();
1262
+ const packageName = String(payload?.package ?? "").trim();
1263
+ const enabled = payload?.enabled === true;
1264
+ if (packageName.length === 0) return rpcFail(new Error("togglePlugin: package name is required"));
1265
+ if (packageName === name) {
1266
+ // 停用市场自己 = 关掉正在操作的这个界面,之后只能手改配置文件才能回来。
1267
+ return rpcFail(new Error("refusing to disable the marketplace itself — you would lose the UI needed to re-enable it"));
1268
+ }
1269
+ let profileDir;
1270
+ try {
1271
+ profileDir = resolveProfileDir(profile);
1272
+ } catch (error) {
1273
+ return rpcFail(new Error(`invalid profile: ${error.message}`));
1274
+ }
1275
+ const targets = loaderEntriesByPackage(ctx)[packageName]?.entries ?? [];
1276
+ if (targets.length === 0) {
1277
+ return rpcFail(new Error(`no loader entry found for ${packageName} — it may not be mounted in this profile`));
1278
+ }
1279
+ // 先持久化:patch 层写不了(!!js 表达式等)就整个放弃,不留下
1280
+ // 「内存里关了、重启又回来」的错位状态。
1281
+ const backups = [];
1282
+ try {
1283
+ for (const target of targets) {
1284
+ // 用 options.id(配置文件里的 id),不是 entry.id(运行时全路径)。
1285
+ if (typeof target.configId !== "string" || target.configId.length === 0) {
1286
+ throw new Error(`${packageName} has a loader entry without a configured id — it cannot be targeted from the patch layer`);
1287
+ }
1288
+ const result = persistPluginDisabled(profileDir, target.configId, !enabled, packageName);
1289
+ if (result.backup !== undefined) backups.push(result.backup);
1290
+ }
1291
+ } catch (error) {
1292
+ return rpcFail(error);
1293
+ }
1294
+ try {
1295
+ for (const target of targets) {
1296
+ await target.entry.update({ disabled: enabled ? undefined : true });
1297
+ }
1298
+ } catch (error) {
1299
+ return rpcFail(new Error(`${packageName} was written to the patch layer but the live toggle failed: ${error.message} — restart dsh to apply it`));
1300
+ }
1301
+ return rpcOk({ package: packageName, enabled, backups, entries: serializableEntries(loaderEntriesByPackage(ctx)) });
1197
1302
  }
1198
1303
  case "preflight": {
1199
1304
  // 预检本身做成 job:点击安装的瞬间任务就出现在面板里,探针的 pnpm
@@ -2235,6 +2340,39 @@ export async function runSelfTests() {
2235
2340
  "tracker rejection fixture 使用注入 producer,不触碰真实 profile",
2236
2341
  producerCalls === 1 && trackerSnapshot.status === "failed" && settledOutcome?.status === "failed",
2237
2342
  );
2343
+
2344
+ // ── 8. 启用/停用:装配树条目按包分组 ─────────────────────────────────
2345
+ // 一个包可以插入多行,所以分组、以及「有一行停用就算整体停用」是这块最
2346
+ // 容易写错的地方;group 行必须跳过(照 dsh-host-plugin-inventory 的读法)。
2347
+ const fakeLoaderCtx = (entries) => ({ loader: { entries: () => entries } });
2348
+ const grouped = loaderEntriesByPackage(fakeLoaderCtx([
2349
+ { id: "e1", options: { name: "dsh-at-file" }, disabled: false },
2350
+ { id: "e2", options: { name: "multi-row" }, disabled: false },
2351
+ { id: "e3", options: { name: "multi-row" }, disabled: true },
2352
+ { id: "g1", options: { name: "some-group", group: true }, disabled: false },
2353
+ { id: "e4", options: {}, disabled: false },
2354
+ ]));
2355
+ check("单行包:分组并标记启用", grouped["dsh-at-file"]?.entryIds.length === 1 && grouped["dsh-at-file"].enabled === true);
2356
+ check("多行包:合并为一项", grouped["multi-row"]?.entryIds.length === 2);
2357
+ check("多行包有一行停用 → 整体判为停用", grouped["multi-row"]?.enabled === false);
2358
+ check("group 行被跳过", grouped["some-group"] === undefined);
2359
+ check("无名条目被跳过", Object.keys(grouped).length === 2);
2360
+ check("loader 抛错时降级为空表,不拖垮已装列表", Object.keys(loaderEntriesByPackage({
2361
+ loader: { entries: () => { throw new Error("loader unavailable"); } },
2362
+ })).length === 0);
2363
+
2364
+ // entry.id 是运行时全路径(父链拼接,`include:dsh-at-file`),
2365
+ // entry.options.id 才是配置文件里的 id(`dsh-at-file`)。patch 层的
2366
+ // id 定向覆盖按后者匹配——用错了那条覆盖行永远命中不了目标,
2367
+ // 停用看着成功、重启后插件照常回来(真实环境踩过)。
2368
+ const prefixed = loaderEntriesByPackage(fakeLoaderCtx([
2369
+ { id: "include:dsh-at-file", options: { id: "dsh-at-file", name: "dsh-at-file" }, disabled: false },
2370
+ ]));
2371
+ check("运行时 id 与配置 id 分别保留", prefixed["dsh-at-file"]?.entries[0].id === "include:dsh-at-file"
2372
+ && prefixed["dsh-at-file"]?.entries[0].configId === "dsh-at-file");
2373
+ check("configId 缺失时可被识别(调用方据此拒绝写 patch)", loaderEntriesByPackage(fakeLoaderCtx([
2374
+ { id: "anon-1", options: { name: "no-id-pkg" }, disabled: false },
2375
+ ]))["no-id-pkg"]?.entries[0].configId === undefined);
2238
2376
  } finally {
2239
2377
  rmSync(root, { recursive: true, force: true });
2240
2378
  }
package/src/installer.js CHANGED
@@ -368,6 +368,134 @@ export function removeClientRow(profileDir, packageName) {
368
368
  return { removed: true, rowId };
369
369
  }
370
370
 
371
+ // ── enable / disable persistence ────────────────────────────────────────────
372
+ //
373
+ // Toggling a plugin is three layers, and only the middle one lives here:
374
+ // 1. memory — `entry.update({disabled})` disposes/starts the fiber (index.js)
375
+ // 2. persistence — rewrite the profile's cordis.patch.yml, replayed
376
+ // transactionally by dsh's own `watchUserPatches` (this file)
377
+ // 3. safety — back the file up before every edit so a bad write is undoable
378
+ //
379
+ // Persistence deliberately does NOT go through `loader.update()` even though
380
+ // that would write for us: its `tree.write()` targets `cordis.yml`, the
381
+ // composed artifact. A user's choice belongs in the patch layer they own, not
382
+ // baked into the thing composition regenerates. Same conclusion as
383
+ // cynch18/plugin-switch, which spells it out in its header comment.
384
+
385
+ /** A patch row's `disabled:` line, when it is a plain literal we may rewrite. */
386
+ const DISABLED_LINE_RE = /^(\s*)disabled\s*:\s*(.*?)\s*$/;
387
+
388
+ /**
389
+ * Text-level edit of one entry's `disabled` in a patch file, preserving every
390
+ * other byte (comments included — users hand-write this file).
391
+ *
392
+ * A profile's patch layer normally starts EMPTY (`[]`): plugins are mounted by
393
+ * the bundle layers, not by the user's file. So "no row for this id" is the
394
+ * common case, not an error — we append an id-targeted override row, which is
395
+ * exactly what the patch layer is for (dsh-app-boot's applyEntryPatches treats
396
+ * a non-insert row as "override these keys on the entry with this id", and
397
+ * warns on a `name` mismatch, so we pass `name` as a guard).
398
+ *
399
+ * @param content - current cordis.patch.yml text.
400
+ * @param entryId - the loader entry id whose row to edit.
401
+ * @param disabled - desired state.
402
+ * @param moduleName - the entry's module name, written alongside a NEW row so
403
+ * dsh can detect a stale patch if the id is ever reused.
404
+ * @returns the new text, or undefined when it already reads that way.
405
+ * @throws when the row's `disabled` is a `!!js` expression.
406
+ */
407
+ export function setPatchRowDisabled(content, entryId, disabled, moduleName) {
408
+ const lines = String(content ?? "").split("\n");
409
+ // 行尾允许跟注释:`- id: at-file # 我的备注` 是用户会写的形状。
410
+ const idPattern = new RegExp(`^(\\s*)-?\\s*id\\s*:\\s*['"]?${entryId.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}['"]?\\s*(?:#.*)?$`);
411
+ const rowIndex = lines.findIndex((line) => idPattern.test(line));
412
+ if (rowIndex === -1) {
413
+ // patch 层里还没有这一条——这是常态(profile 的 patch 层默认是空的 `[]`,
414
+ // 插件由 bundle 层挂载)。追加一条 id 定向覆盖行。
415
+ if (!disabled) return undefined; // 没有覆盖行 = 本来就是启用状态
416
+ const block = moduleName === undefined
417
+ ? `- id: ${entryId}\n disabled: true\n`
418
+ : `- id: ${entryId}\n name: '${moduleName}'\n disabled: true\n`;
419
+ const trimmed = String(content ?? "").trim();
420
+ // 模板是注释 + `[]`,整体替换掉那个空数组;否则在末尾追加。
421
+ if (trimmed.endsWith("[]")) {
422
+ return `${trimmed.slice(0, trimmed.lastIndexOf("[]")).trimEnd()}\n${block}`.replace(/^\n/, "");
423
+ }
424
+ return `${trimmed.length === 0 ? "" : `${trimmed}\n`}${block}`;
425
+ }
426
+ const indent = (idPattern.exec(lines[rowIndex])[1] ?? "").length;
427
+ // 同一条目的后续行:缩进更深,或与 `- id:` 的内容对齐。遇到下一个条目/顶格即止。
428
+ let existing = -1;
429
+ for (let index = rowIndex + 1; index < lines.length; index++) {
430
+ const line = lines[index];
431
+ if (line.trim().length === 0) continue;
432
+ const lead = line.length - line.trimStart().length;
433
+ if (lead <= indent && /^\s*-\s/.test(line)) break; // 下一个条目
434
+ if (lead < indent) break; // 退出该块
435
+ const match = DISABLED_LINE_RE.exec(line);
436
+ if (match !== null) { existing = index; break; }
437
+ }
438
+ if (existing !== -1) {
439
+ const value = DISABLED_LINE_RE.exec(lines[existing])[2];
440
+ // 用户写的是条件逻辑(如「只在 Windows 上停用」)。我们的开关只有两态,
441
+ // 覆盖它等于把条件永久压成固定值,而且用户不会察觉——拒绝接管,让人手改。
442
+ if (value.startsWith("!!js")) {
443
+ throw new Error(`cannot toggle ${entryId}: its "disabled" is a !!js expression — edit cordis.patch.yml by hand`);
444
+ }
445
+ if ((value === "true") === disabled) return undefined; // 已是目标状态
446
+ lines[existing] = lines[existing].replace(DISABLED_LINE_RE, `$1disabled: ${disabled}`);
447
+ return lines.join("\n");
448
+ }
449
+ if (!disabled) return undefined; // 没有 disabled 行本就是启用状态
450
+ // 插在 id 行之后,缩进与 id 的内容列对齐。
451
+ lines.splice(rowIndex + 1, 0, `${" ".repeat(indent + 2)}disabled: true`);
452
+ return lines.join("\n");
453
+ }
454
+
455
+ /** Keep the most recent N backups of a profile file, oldest pruned first. */
456
+ const PATCH_BACKUP_KEEP = 20;
457
+
458
+ /**
459
+ * Snapshot cordis.patch.yml before editing it. The file is hand-editable and
460
+ * carries the user's own rows; a bad automated write must be undoable without
461
+ * reaching for git.
462
+ * @returns the backup path, or undefined when there was nothing to back up.
463
+ */
464
+ export function backupProfilePatch(profileDir) {
465
+ const patchPath = join(profileDir, PROFILE_PATCH_FILENAME);
466
+ if (!existsSync(patchPath)) return undefined;
467
+ const dir = join(profileDir, "backups");
468
+ mkdirSync(dir, { recursive: true });
469
+ const stamp = new Date().toISOString().replace(/[:.]/g, "-");
470
+ const target = join(dir, `cordis.patch.${stamp}.yml`);
471
+ writeFileSync(target, readFileSync(patchPath, "utf8"));
472
+ try {
473
+ const kept = readdirSync(dir).filter((entry) => /^cordis\.patch\..*\.yml$/.test(entry)).sort();
474
+ for (const stale of kept.slice(0, Math.max(0, kept.length - PATCH_BACKUP_KEEP))) {
475
+ rmSync(join(dir, stale), { force: true });
476
+ }
477
+ } catch {
478
+ /* 清理失败不该让切换失败 */
479
+ }
480
+ return target;
481
+ }
482
+
483
+ /**
484
+ * Persist a toggle into the profile's patch layer: back up, edit, write through
485
+ * the checked writer. dsh's own `watchUserPatches` replays the file
486
+ * transactionally, so this is also what makes the change survive a restart.
487
+ * @returns `{changed, backup?}`; `changed:false` means it already read that way.
488
+ */
489
+ export function persistPluginDisabled(profileDir, entryId, disabled, moduleName) {
490
+ const patchPath = join(profileDir, PROFILE_PATCH_FILENAME);
491
+ const content = existsSync(patchPath) ? readFileSync(patchPath, "utf8") : "[]\n";
492
+ const next = setPatchRowDisabled(content, entryId, disabled, moduleName);
493
+ if (next === undefined) return { changed: false };
494
+ const backup = backupProfilePatch(profileDir);
495
+ writePatchChecked(patchPath, next);
496
+ return { changed: true, backup };
497
+ }
498
+
371
499
  // ── build-script allow-listing ──────────────────────────────────────────────
372
500
 
373
501
  /** Extract package names from pnpm's "Ignored build scripts: ..." output. */
@@ -2492,9 +2620,76 @@ async function runTransactionFixtures() {
2492
2620
  return failed;
2493
2621
  }
2494
2622
 
2623
+ /**
2624
+ * The patch-layer edit behind enable/disable. Text surgery on a file users
2625
+ * hand-write, so every shape it can meet is pinned here.
2626
+ */
2627
+ function runToggleFixtures() {
2628
+ let failed = 0;
2629
+ const check = (label, ok, extra = "") => {
2630
+ if (!ok) failed++;
2631
+ console.log(` ${ok ? "PASS" : "FAIL"} ${label}${ok ? "" : ` ${extra}`}`);
2632
+ };
2633
+ // 真实环境里 patch 层默认就是这个样子——注释 + 空数组。插件由 bundle 层
2634
+ // 挂载,用户文件里一条都没有。第一版只测了「行已存在」的情形,于是停用
2635
+ // 被静默跳过、重启后插件又回来了。这组用例先钉死这个场景。
2636
+ const stockTemplate = "# Your patch layer for this dsh profile\n[]\n";
2637
+ const fresh = setPatchRowDisabled(stockTemplate, "at-file", true, "dsh-at-file");
2638
+ check("空 patch 层(模板 [])→ 追加 id 定向覆盖行", /- id: at-file/.test(fresh ?? "") && /disabled: true/.test(fresh ?? ""), JSON.stringify(fresh));
2639
+ check("空 patch 层:替换掉 [] 而不是留着", !/\[\]/.test(fresh ?? ""), JSON.stringify(fresh));
2640
+ check("空 patch 层:保留原有注释", (fresh ?? "").includes("# Your patch layer"));
2641
+ check("新建行带 name 便于 dsh 校验陈旧 patch", /name: 'dsh-at-file'/.test(fresh ?? ""));
2642
+ check("空 patch 层 + 要启用 → 不改动", setPatchRowDisabled(stockTemplate, "at-file", false, "dsh-at-file") === undefined);
2643
+ check("新建的行能被 YAML 解析且是数组", (() => {
2644
+ try { return Array.isArray(load(fresh)); } catch { return false; }
2645
+ })());
2646
+ check("新建行的语义正确(id + disabled)", (() => {
2647
+ try { const doc = load(fresh); return doc[0].id === "at-file" && doc[0].disabled === true; } catch { return false; }
2648
+ })());
2649
+
2650
+ const base = "- id: at-file\n name: dsh-at-file\n";
2651
+
2652
+ const off = setPatchRowDisabled(base, "at-file", true);
2653
+ check("无 disabled 行 → 插入 disabled: true", /^\s{2}disabled: true$/m.test(off ?? ""), JSON.stringify(off));
2654
+ check("插入后其余字节不变", (off ?? "").includes("name: dsh-at-file"));
2655
+
2656
+ const on = setPatchRowDisabled(`- id: at-file\n name: dsh-at-file\n disabled: true\n`, "at-file", false);
2657
+ check("已停用 → 改回 false", /disabled: false/.test(on ?? ""), JSON.stringify(on));
2658
+
2659
+ check("已是目标状态 → 不改动", setPatchRowDisabled(`- id: at-file\n disabled: true\n`, "at-file", true) === undefined);
2660
+ check("本就启用且要启用 → 不改动", setPatchRowDisabled(base, "at-file", false) === undefined);
2661
+ check("条目不在 patch 层 → 追加新行,原有条目不动", (() => {
2662
+ const out = setPatchRowDisabled(base, "other-id", true, "pkg-other");
2663
+ return /- id: other-id/.test(out ?? "") && (out ?? "").includes("- id: at-file");
2664
+ })());
2665
+
2666
+ // 用户写的条件逻辑不能被两态开关压平——必须拒绝并让人手改。
2667
+ let threw = false;
2668
+ try { setPatchRowDisabled(`- id: at-file\n disabled: !!js process.platform === 'win32'\n`, "at-file", false); }
2669
+ catch (error) { threw = /!!js expression/.test(error.message); }
2670
+ check("disabled 是 !!js 表达式 → 拒绝接管", threw);
2671
+
2672
+ // 注释是用户手写的,一个字节都不能动。
2673
+ const commented = "# 我的覆盖\n- id: at-file # 保留这个注释\n name: dsh-at-file\n";
2674
+ const kept = setPatchRowDisabled(commented, "at-file", true);
2675
+ check("注释原样保留", (kept ?? "").includes("# 我的覆盖") && (kept ?? "").includes("# 保留这个注释"));
2676
+
2677
+ // 多条目:只动目标那条,相邻条目不受影响。
2678
+ const multi = "- id: a\n name: pkg-a\n- id: at-file\n name: dsh-at-file\n- id: z\n name: pkg-z\n disabled: true\n";
2679
+ const one = setPatchRowDisabled(multi, "at-file", true);
2680
+ check("多条目:只动目标条目", (one ?? "").split("disabled: true").length - 1 === 2 && (one ?? "").includes("- id: z"));
2681
+ check("多条目:不误伤相邻条目的 disabled", setPatchRowDisabled(multi, "a", true)?.includes("- id: z\n name: pkg-z\n disabled: true") === true);
2682
+
2683
+ check("带引号的 id 也能匹配", setPatchRowDisabled(`- id: '@scope/pkg'\n name: x\n`, "@scope/pkg", true) !== undefined);
2684
+ return failed;
2685
+ }
2686
+
2495
2687
  if (process.argv[1]?.endsWith("installer.js") && process.argv.includes("--self-test")) {
2688
+ console.log("启用/停用 patch 层 fixtures:");
2689
+ const toggleFailed = runToggleFixtures();
2690
+ console.log();
2496
2691
  console.log("allowBuilds 合并 fixtures:");
2497
- const failed = runAllowBuildsFixtures();
2692
+ const failed = runAllowBuildsFixtures() + toggleFailed;
2498
2693
  console.log(`${ALLOW_BUILDS_FIXTURES.length - failed}/${ALLOW_BUILDS_FIXTURES.length} passed`);
2499
2694
  // 实装 pnpm add 的参数/环境(纯函数):peer 自动安装必须关闭,否则
2500
2695
  // marketplace 安装会把 @deepseek-ai 宿主依赖栈拉进 profile;构建脚本必须