dsh-prompt-customizer 0.3.0 → 0.4.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/client/client.js CHANGED
@@ -14,7 +14,7 @@ window.__ModuleLoader__.load({
14
14
  unavailable: "当前环境未启用本命名空间。",
15
15
  tabsSections: "提示词",
16
16
  tabsTools: "工具",
17
- tabsPresets: "预设",
17
+ tabsPresets: "配置",
18
18
  tabsPreview: "预览",
19
19
  refresh: "刷新",
20
20
  blockedOff: "未屏蔽",
@@ -44,17 +44,96 @@ window.__ModuleLoader__.load({
44
44
  previewSections: "段",
45
45
  previewTools: "工具预览",
46
46
  previewToolCount: "个工具",
47
- savePreset: "保存当前为预设",
48
- presetName: "预设名称",
47
+ savePreset: "保存当前配置",
48
+ presetName: "配置名称",
49
+ saveAsPresetCard: "存为 agent 预设",
50
+ saveAsPresetHint: "整体复制「{name}」这个预设的组成为新预设(组成文件与伴生脚本一并带走),再把当前定制写进它的覆盖项 —— 新预设出现在顶部编辑目标里。",
51
+ agentPresetName: "新预设名",
52
+ forkSourceDefault: "默认预设",
53
+ saveAsPresetOk: "预设已创建,可在顶部的编辑目标选择器里选到它",
54
+ saveAsPresetFail: "保存预设失败",
49
55
  save: "保存",
50
- importPreset: "导入预设",
56
+ importPreset: "导入配置",
51
57
  import: "导入",
52
58
  apply: "应用",
53
59
  export: "导出",
54
60
  delete: "删除",
55
61
  restore: "还原",
56
62
  active: "使用中",
57
- preset: "预设"
63
+ preset: "预设",
64
+ ioFailed: "导入/导出失败",
65
+ importInvalid: "无效的配置文件",
66
+ targetGlobal: "目标:全局默认",
67
+ targetHint: "选择编辑目标 —— 选中某个 agent 预设后,改动只对该预设生效(字段级覆盖)。",
68
+ broken: "损坏",
69
+ brokenPreset: "该 agent 预设当前无法挂载,仍可编辑其定制(修复预设后自动生效)。",
70
+ phaseBootstrap: "仅引导阶段",
71
+ phaseActive: "晋级后",
72
+ phaseCompaction: "压缩后",
73
+ phaseStageGuide: "引导期",
74
+ phaseStageResident: "常驻期",
75
+ phaseStageControlled: "压缩受控期",
76
+ toolsPartGuide: "引导期工具",
77
+ toolsPartResident: "常驻期工具",
78
+ toolsPartControlled: "压缩受控期工具",
79
+ allToolsTitle: "本系统全部工具",
80
+ sectionsPartGuide: "引导期提示词",
81
+ sectionsPartResident: "常驻期提示词",
82
+ sectionsPartControlled: "压缩受控期提示词",
83
+ allSectionsTitle: "本系统全部提示词",
84
+ toolsFourHint: "三个阶段各一份名单,互不继承:勾选 = 该阶段是否对模型可见;从「全部」拖入某阶段 = 让这一个工具在该阶段出现(若该阶段默认裁掉了它,就加回去);在两个阶段之间拖动 = 复制(源阶段不动,目标阶段多一份,隐藏/启用状态一起带过去);拖回「全部」= 从该阶段拿掉它。每个动作只影响被拖的那一个工具。",
85
+ sectionsFourHint: "拖拽双向:把「全部」里的段拖入上方阶段 = 加入该阶段并默认开启;从阶段拖回「全部」= 从该阶段移除。屏蔽段与普通段完全一样可拖拽 / 编辑,只是不注入模型。",
86
+ dragHint: "拖入 = 让该工具在这个阶段出现",
87
+ phaseShortGuide: "引",
88
+ phaseShortResident: "常",
89
+ phaseShortControlled: "压",
90
+ poolMarksHint: "每个名字后的三个标记 = 该工具在引导期 / 常驻期 / 压缩受控期的状态:绿=该阶段可见(或已加回),灰=该阶段已隐藏,暗=不在该阶段、也没加回。",
91
+ toolAddedTag: "加回",
92
+ toolAdded: "已把「{name}」加回{phase}:该阶段默认裁掉了它,保存后它会重新出现在该阶段(当前预设注册表里有它)。",
93
+ toolNotInRegistry: "「{name}」不在本预设的注册表里(它是别的预设独有的工具),当前预设没有它的定义,加不进来。",
94
+ toolCopied: "已把「{name}」复制到{to}:{from}那份保持不动,隐藏/启用状态一起带过去。",
95
+ toolShown: "「{name}」已在{to}显示。",
96
+ toolHiddenIn: "「{name}」已在{to}隐藏。",
97
+ sectionsTakenOver: "「{name}」段声明了 complete 整段接管(宿主在装配瀑布流之后强制还原为那一条段)。本插件默认的 forceSections 已绕开该机制,段级屏蔽 / 替换 / 注入 / 排序照常生效;此提示只会在 forceSections 关闭或强制覆盖失效时出现,开启 forceSections 即可恢复。",
98
+ sectionsLost: "本插件在该阶段产出的 {emitted} 个段里,只有 {survived} 个进入最终提示词:其余被下游装配规则丢弃,段级定制不会完全生效(工具过滤不受影响)。",
99
+ sectionBlockedStrip: "(本阶段已屏蔽,模型不可见)",
100
+ phaseSuppressed: "被抑制(不在任何阶段的装配中)",
101
+ sectionDynamicNoAdd: "「{name}」是运行时才生成的动态段,没法预先加进某个阶段(它的内容只有装配时才知道)。",
102
+ exportOk: "导出成功",
103
+ exportCancel: "已取消导出",
104
+ exportFail: "导出失败",
105
+ importOk: "导入完成",
106
+ importNone: "没有新增预设(同名已存在或文件为空)",
107
+ importCancel: "已取消导入",
108
+ importFail: "导入失败",
109
+ saveOk: "已保存",
110
+ saveFail: "保存失败",
111
+ discardConfirm: "有未保存的更改,离开将丢弃。确定离开吗?",
112
+ forceTitle: "强制覆盖(forceSections)",
113
+ forceHint: "开启后所有预设的提示词段一律以本插件为准(绕过 complete 整段接管与预设阶段裁段);关闭后退回瀑布流内过滤,预设可能压过定制。「恢复初始状态」会自动关闭它。",
114
+ forceOn: "已开启",
115
+ forceOff: "已关闭",
116
+ envBlockTitle: "环境变量黑名单(envBlocklist)",
117
+ envBlockHint: "系统环境变量(process.env)已全量注册为提示词变量:段文本里写 {{env_键名小写}} 引用(如 {{env_path}});命中黑名单的键不注册——env 里常有密钥,进了提示词就会随请求发给模型。条目支持 * 通配、大小写不敏感。内置变量 {{date}} {{time}} {{datetime}} {{weekday}} {{hostname}} {{platform}} {{arch}} {{username}} {{home}} {{shell}} {{locale}} {{node_version}} 恒可用。",
118
+ envBlockAdd: "键名或通配,如 GITHUB_TOKEN 或 *_KEY*",
119
+ envBlockAddAction: "添加",
120
+ envBlockEmpty: "黑名单为空:所有环境变量都会被注册",
121
+ envVarsTitle: "已注册的提示词变量",
122
+ envVarsHint: "段文本里引用 {{变量名}};引用未注册的名字会让整次渲染报错(宿主严格模式)。",
123
+ importBlockMerge: ",文件中的环境变量黑名单已并入(+{count} 条)",
124
+ resetTitle: "恢复初始状态",
125
+ resetHint: "清空全部定制(屏蔽 / 替换 / 注入 / 排序、阶段工具目录、配置快照、agent 预设覆盖),并关闭 forceSections —— 之后所有 AI 对话不再受本插件影响,与卸载插件等效,无需卸载或重启。此操作不可撤销;要重新启用定制,在上方打开「强制覆盖」开关即可。",
126
+ resetConfirm: "确定清空全部定制并恢复初始状态吗?\n\n将删除:屏蔽名单、段替换、注入段、阶段工具目录、配置快照、agent 预设覆盖;并关闭 forceSections。\n之后所有 AI 对话都不再受本插件影响(与卸载插件等效)。\n此操作不可撤销。",
127
+ resetAction: "清空全部定制",
128
+ resetOk: "已恢复初始状态:所有 AI 对话不再受本插件影响",
129
+ resetFail: "恢复初始状态失败",
130
+ scopeFallback: "该 agent 预设的常驻 scope 未能挂载,以下显示的是全局层内容(并非该预设的原生段与工具)。",
131
+ previewDegraded: "伪会话触发了某个预设插件的异常,本次预览已降级为无会话装配——预设原生的阶段裁剪规则未参与运行。",
132
+ previewFail: "该阶段装配失败(scope 挂载失败或预设插件异常),请切换目标或查看服务日志。",
133
+ phaseVisible: "阶段可见",
134
+ previewToolsHint: "模型实际可见的工具目录(按所选阶段运行预设的全部装配规则,含原生阶段裁剪):",
135
+ previewToolsCount: "注册表",
136
+ saveAsPreset: "存为预设"
58
137
  },
59
138
  en: {
60
139
  nav: "Prompt Customizer",
@@ -92,8 +171,14 @@ window.__ModuleLoader__.load({
92
171
  previewSections: "sections",
93
172
  previewTools: "Tools preview",
94
173
  previewToolCount: "tools",
95
- savePreset: "Save current as preset",
96
- presetName: "Preset name",
174
+ savePreset: "Save current config",
175
+ presetName: "Config name",
176
+ saveAsPresetCard: "Save as agent preset",
177
+ saveAsPresetHint: "Copy the whole \"{name}\" preset into a new one (composition plus its companion scripts), then write the current customization into its override — the new preset shows up in the target selector above.",
178
+ agentPresetName: "New preset name",
179
+ forkSourceDefault: "the default preset",
180
+ saveAsPresetOk: "Preset created — pick it in the target selector above",
181
+ saveAsPresetFail: "Failed to save preset",
97
182
  save: "Save",
98
183
  importPreset: "Import preset",
99
184
  import: "Import",
@@ -102,12 +187,85 @@ window.__ModuleLoader__.load({
102
187
  delete: "Delete",
103
188
  restore: "Restore",
104
189
  active: "Active",
105
- preset: "Preset"
190
+ preset: "Preset",
191
+ ioFailed: "Import/export failed",
192
+ importInvalid: "Invalid preset file",
193
+ targetGlobal: "Target: global default",
194
+ targetHint: "Pick an edit target — changes apply only to the chosen agent preset (field-level override).",
195
+ broken: "broken",
196
+ brokenPreset: "This agent preset cannot mount right now; its customization is still editable and applies once fixed.",
197
+ phaseBootstrap: "Bootstrap only",
198
+ phaseActive: "After promotion",
199
+ phaseCompaction: "Post-compaction",
200
+ phaseStageGuide: "Guide period",
201
+ phaseStageResident: "Resident period",
202
+ phaseStageControlled: "Compaction-controlled period",
203
+ toolsPartGuide: "Guide-period tools",
204
+ toolsPartResident: "Resident-period tools",
205
+ toolsPartControlled: "Compaction-controlled tools",
206
+ allToolsTitle: "All system tools",
207
+ sectionsPartGuide: "Guide-period sections",
208
+ sectionsPartResident: "Resident-period sections",
209
+ sectionsPartControlled: "Compaction-controlled sections",
210
+ allSectionsTitle: "All system sections",
211
+ toolsFourHint: "Each of the three periods keeps its own list, with no inheritance: the checkbox = visible to the model in that period; dragging a tool from \"All\" into a period makes it appear there (if the period trims it by default, it is added back); dragging between two periods copies it (the source is untouched, the target gains one, and the hidden/enabled state carries over); dragging it back to \"All\" removes it from that period. Every action touches only the tool you dragged.",
212
+ sectionsFourHint: "Drag both ways: drop a section from \"All\" onto a period part to enable it there; drag from a part back to \"All\" to remove it from that period. Blocked sections stay fully operable — they are just not injected.",
213
+ dragHint: "Drag in to make this tool appear in this period",
214
+ phaseShortGuide: "G",
215
+ phaseShortResident: "R",
216
+ phaseShortControlled: "C",
217
+ poolMarksHint: "The three marks after each name = this tool’s state in the guide / resident / compaction-controlled periods: green = visible there (or added back), grey = hidden there, dim = not present and not added.",
218
+ toolAddedTag: "added",
219
+ toolAdded: "Added \"{name}\" back to {phase}: the period trims it by default, so it will reappear there once saved (it exists in this preset’s registry).",
220
+ toolNotInRegistry: "\"{name}\" is not in this preset’s registry (it belongs to another preset). There is no definition for it here, so it cannot be added.",
221
+ toolCopied: "Copied \"{name}\" to {to}: the copy in {from} is left untouched, and its hidden/enabled state carries over.",
222
+ toolShown: "\"{name}\" is now visible in {to}.",
223
+ toolHiddenIn: "\"{name}\" is now hidden in {to}.",
224
+ sectionsTakenOver: "The \"{name}\" section declares a complete takeover (the host restores that single section after the assembly waterfall). This plugin’s forceSections (default on) bypasses that mechanism, so section-level blocking / replacement / injection / ordering still applies; this notice only appears when forceSections is off or the override fails — enable it to restore.",
225
+ sectionsLost: "Only {survived} of the {emitted} sections this plugin emitted for this phase reach the final prompt — the rest are dropped by downstream assembly rules, so section-level customization cannot fully apply (tool filtering is unaffected).",
226
+ sectionBlockedStrip: " (blocked in this period; invisible to the model)",
227
+ phaseSuppressed: "Suppressed (absent from every phase assembly)",
228
+ sectionDynamicNoAdd: "\"{name}\" is generated at runtime — it cannot be added to a phase ahead of time (its content is only known during assembly).",
229
+ exportOk: "Exported",
230
+ exportCancel: "Export cancelled",
231
+ exportFail: "Export failed",
232
+ importOk: "Import complete",
233
+ importNone: "Nothing imported (duplicate names or empty file)",
234
+ importCancel: "Import cancelled",
235
+ importFail: "Import failed",
236
+ saveOk: "Saved",
237
+ saveFail: "Save failed",
238
+ discardConfirm: "You have unsaved changes; leaving will discard them. Leave anyway?",
239
+ forceTitle: "Force override (forceSections)",
240
+ forceHint: "When on, every preset’s prompt sections always follow this plugin (bypassing complete takeover and preset phase pruning); when off, filtering falls back to the waterfall, where presets may override your customization. \"Restore initial state\" turns this off automatically.",
241
+ forceOn: "On",
242
+ forceOff: "Off",
243
+ envBlockTitle: "Environment variable blocklist (envBlocklist)",
244
+ envBlockHint: "All system environment variables (process.env) are registered as prompt variables: reference them in section text as {{env_lowercase_key}} (e.g. {{env_path}}); keys hit by the blocklist are not registered — env often carries secrets, and anything in the prompt is sent to the model. Entries support * wildcards, case-insensitive. Built-ins {{date}} {{time}} {{datetime}} {{weekday}} {{hostname}} {{platform}} {{arch}} {{username}} {{home}} {{shell}} {{locale}} {{node_version}} are always available.",
245
+ envBlockAdd: "Key or wildcard, e.g. GITHUB_TOKEN or *_KEY*",
246
+ envBlockAddAction: "Add",
247
+ envBlockEmpty: "Blocklist is empty: every environment variable gets registered",
248
+ envVarsTitle: "Registered prompt variables",
249
+ envVarsHint: "Reference {{name}} in section text; an unregistered name fails the whole render (host strict mode).",
250
+ importBlockMerge: ", the file’s env-variable blocklist was merged in (+{count} entries)",
251
+ resetTitle: "Restore initial state",
252
+ resetHint: "Clears all customization (blocking / replacement / injection / ordering, per-phase tool catalogs, config snapshots, agent-preset overrides) and turns forceSections off — every AI conversation goes back to being unaffected by this plugin, equivalent to uninstalling it, without uninstalling or restarting. This cannot be undone; to re-enable customization, turn the \"Force override\" switch above back on.",
253
+ resetConfirm: "Clear all customization and restore the initial state?\n\nThis will delete: block lists, section replacements, injected sections, per-phase tool catalogs, config snapshots, and agent-preset overrides; forceSections will be turned off.\nAfterwards no AI conversation is affected by this plugin (equivalent to uninstalling).\nThis cannot be undone.",
254
+ resetAction: "Clear all customization",
255
+ resetOk: "Initial state restored: no AI conversation is affected by this plugin anymore",
256
+ resetFail: "Failed to restore initial state",
257
+ scopeFallback: "This agent preset's standing scope could not be mounted; what you see is the global layer (not the preset's native sections/tools).",
258
+ previewDegraded: "A preset plugin threw on the synthetic session; this preview fell back to an agent-less assembly — native phase rules did not run.",
259
+ previewFail: "Assembly for this phase failed (scope mount error or a preset plugin threw); switch target or check the server log.",
260
+ phaseVisible: "visible in phase",
261
+ previewToolsHint: "Tool catalog as the model actually sees it (all assembly rules run for the selected phase, including native phase narrowing):",
262
+ previewToolsCount: "of registry",
263
+ saveAsPreset: "Save as preset"
106
264
  }
107
265
  };
108
266
  //#endregion
109
267
  //#region src/client/styles.ts
110
- /** Inline styles shared by the prompt-customizer panel components. */
268
+ /** 提示词定制面板各组件共享的内联样式(颜色走半透明灰,随宿主主题自然适配)。 */
111
269
  const s = (() => {
112
270
  const flex = {
113
271
  display: "flex",
@@ -331,6 +489,10 @@ window.__ModuleLoader__.load({
331
489
  background: "transparent",
332
490
  color: "inherit"
333
491
  },
492
+ option: {
493
+ backgroundColor: "Canvas",
494
+ color: "CanvasText"
495
+ },
334
496
  muted: {
335
497
  color: "rgba(128,128,128,.75)",
336
498
  fontSize: 12
@@ -339,19 +501,98 @@ window.__ModuleLoader__.load({
339
501
  color: "#f85149",
340
502
  fontSize: 12,
341
503
  marginBottom: 6
504
+ },
505
+ noticeOk: {
506
+ color: "#3fb950",
507
+ fontSize: 12,
508
+ marginBottom: 6
509
+ },
510
+ noticeWarn: {
511
+ color: "#d29922",
512
+ fontSize: 12,
513
+ marginBottom: 6
514
+ },
515
+ groupTitle: {
516
+ display: "flex",
517
+ gap: 8,
518
+ alignItems: "baseline",
519
+ marginTop: 8,
520
+ marginBottom: 2,
521
+ color: "rgba(128,128,128,.9)",
522
+ fontSize: 12
523
+ },
524
+ saveBtn: {
525
+ padding: "4px 12px",
526
+ border: "1px solid rgba(128,128,128,.35)",
527
+ borderRadius: 6,
528
+ background: "transparent",
529
+ cursor: "pointer",
530
+ color: "inherit"
531
+ },
532
+ saveBtnDirty: {
533
+ padding: "4px 12px",
534
+ border: "1px solid #d29922",
535
+ borderRadius: 6,
536
+ background: "rgba(210,153,34,.15)",
537
+ cursor: "pointer",
538
+ color: "inherit"
342
539
  }
343
540
  };
344
541
  })();
345
542
  //#endregion
346
543
  //#region src/client/presets.ts
544
+ /** 快照捕获的阶段 order 空间(always 之外的三个阶段)。 */
545
+ const CAPTURE_PHASES = [
546
+ "bootstrap",
547
+ "active",
548
+ "compaction"
549
+ ];
550
+ /** 把一条有序名字转成相对链(每段记住它的前一段),text / custom 只给 custom 段。 */
551
+ function toChain(names, textOf, customOf, phase) {
552
+ return names.map((name, i) => ({
553
+ name,
554
+ after: i > 0 ? names[i - 1] : void 0,
555
+ text: customOf(name) ? textOf(name) ?? "" : "",
556
+ custom: customOf(name),
557
+ ...phase !== void 0 ? { phase } : {}
558
+ }));
559
+ }
560
+ /**
561
+ * 从当前配置构建预设快照(完整捕获,含每阶段独立设定)。
562
+ *
563
+ * 全局相对链派生自合并后的完整段列表(而不仅是 `cfg.inject`),这样即使保存前
564
+ * 只是屏蔽了几个段(没有重排),预设仍会携带完整的有序集合,应用时才能得到一个
565
+ * 有意义的「激活列表」。在此之上,bootstrap / active / compaction 各再带一条自己
566
+ * 的相对链 —— 数据源就是 UI 逐阶段持久化的注入条目(每阶段独立的 order 空间),
567
+ * 否则阶段化的名单与排序在「导出 → 导入 → 应用」后就丢了。
568
+ */
569
+ function buildPresetData(cfg, merged) {
570
+ const globalNames = merged.map((sec) => sec.name);
571
+ const textOf = new Map(merged.map((sec) => [sec.name, sec.text ?? ""]));
572
+ const customOf = new Map(merged.map((sec) => [sec.name, sec.source === "custom"]));
573
+ const order = toChain(globalNames, (n) => textOf.get(n) ?? "", (n) => customOf.get(n) === true);
574
+ for (const phase of CAPTURE_PHASES) {
575
+ const items = (cfg.inject ?? []).filter((item) => item.phase === phase).sort((a, b) => (a.order ?? 0) - (b.order ?? 0));
576
+ if (items.length === 0) continue;
577
+ order.push(...toChain(items.map((item) => item.name), (n) => items.find((item) => item.name === n)?.text ?? "", (n) => items.find((item) => item.name === n)?.custom === true, phase));
578
+ }
579
+ const data = {
580
+ sections: cfg.sections,
581
+ replace: cfg.replace,
582
+ order,
583
+ tools: cfg.tools
584
+ };
585
+ if ((cfg.sectionsBootstrap ?? []).length > 0) data.sectionsBootstrap = cfg.sectionsBootstrap;
586
+ if ((cfg.sectionsCompaction ?? []).length > 0) data.sectionsCompaction = cfg.sectionsCompaction;
587
+ return data;
588
+ }
347
589
  /**
348
- * Merge the inventory sections with the user's inject list, sorted by order.
349
- * Sections read from the inventory (other plugins) are `system`; sections this
350
- * plugin generated carry a hidden `custom` marker and are `custom`. The source
351
- * is decided by the hidden marker — never by name collisions — so a custom
352
- * section keeps its identity (and its deletability) even when its name happens
353
- * to match an inventory section, and across preset switches. Custom sections
354
- * always render their own text; they can never be "<动态生成>".
590
+ * 把宿主清单段与用户注入列表按 order 合并、排序。
591
+ * 读自清单(其他插件产出)的段标记为 `system`;本插件生成的段带隐藏的
592
+ * `custom` 标记,标记为 `custom`。来源只由隐藏标记决定——绝不靠名字碰撞
593
+ * 判断——因此即使自定义段恰好与某个清单段重名,它也能保住自己的身份
594
+ * (以及可删除性),并在切换预设后依然成立。自定义段始终渲染自己的文本,
595
+ * 永远不会显示为「<动态生成>」。
355
596
  */
356
597
  function mergeSections(inv, cfg, blockedNames) {
357
598
  const map = /* @__PURE__ */ new Map();
@@ -387,21 +628,13 @@ window.__ModuleLoader__.load({
387
628
  }));
388
629
  }
389
630
  /**
390
- * Resolve a preset's relative order into an absolute ordered list (0..n-1).
391
- * Sections with no anchor (or whose anchor is absent) come first in preset
392
- * order; each anchored section is inserted right after its anchor; any
393
- * remaining sections (cycles) are appended.
631
+ * 把一条相对链解析为绝对有序名字(0..n-1)。
632
+ * 没有锚点(或锚点不在本组内)的名字按原始顺序排在最前;每个带锚点的名字
633
+ * 插到其锚点之后;剩余的名字(存在环)追加到末尾。
394
634
  */
395
- function resolveOrder(presetOrder) {
396
- const list = presetOrder ?? [];
635
+ function resolveChain(list) {
397
636
  const afterMap = /* @__PURE__ */ new Map();
398
- const textMap = /* @__PURE__ */ new Map();
399
- const customMap = /* @__PURE__ */ new Map();
400
- for (const sec of list) {
401
- afterMap.set(sec.name, sec.after);
402
- textMap.set(sec.name, sec.text);
403
- customMap.set(sec.name, sec.custom === true);
404
- }
637
+ for (const sec of list) afterMap.set(sec.name, sec.after);
405
638
  const result = [];
406
639
  const placed = /* @__PURE__ */ new Set();
407
640
  for (const sec of list) {
@@ -428,45 +661,56 @@ window.__ModuleLoader__.load({
428
661
  result.push(sec.name);
429
662
  placed.add(sec.name);
430
663
  }
431
- return result.map((name, i) => ({
432
- name,
433
- order: i,
434
- text: textMap.get(name) ?? "",
435
- custom: customMap.get(name)
436
- }));
664
+ return result;
437
665
  }
438
666
  /**
439
- * Build a preset snapshot from the current config. The order list is derived
440
- * from the MERGED section list (not just `cfg.inject`) so that a preset saved
441
- * after only blocking sections (without reordering) still carries the full
442
- * ordered set, and thus a meaningful "active list" when applied.
667
+ * 把快照里的相对顺序解析为注入条目列表。
668
+ *
669
+ * order 条目可以带 `phase`:同名而不同 phase 的多条 = 该段在多个阶段各有自己的
670
+ * 位置(每阶段有独立的 order 空间,与 UI 的 phaseInjectEntries 一致)。无 phase
671
+ * 的条目属于 always 组 —— 也就是旧快照的单一全局序,输出形状与旧实现逐键一致
672
+ * (刻意不写 phase 键,「保存 → 应用 = 不动点」的不变量依赖键形状完全相同)。
443
673
  */
444
- function buildPresetData(cfg, merged) {
445
- const order = merged.map((sec, i) => ({
446
- name: sec.name,
447
- after: i > 0 ? merged[i - 1].name : void 0,
448
- text: sec.source === "custom" ? sec.text ?? "" : "",
449
- custom: sec.source === "custom"
450
- }));
451
- return {
452
- sections: cfg.sections,
453
- replace: cfg.replace,
454
- order,
455
- tools: cfg.tools
456
- };
674
+ function resolveOrder(presetOrder) {
675
+ const list = presetOrder ?? [];
676
+ const groups = /* @__PURE__ */ new Map([["always", []]]);
677
+ for (const sec of list) {
678
+ const phase = sec.phase ?? "always";
679
+ const group = groups.get(phase);
680
+ if (group) group.push(sec);
681
+ else groups.set(phase, [sec]);
682
+ }
683
+ const out = [];
684
+ for (const [phase, members] of groups) {
685
+ const textMap = new Map(members.map((x) => [x.name, x.text ?? ""]));
686
+ const customMap = new Map(members.map((x) => [x.name, x.custom === true]));
687
+ const names = resolveChain(members);
688
+ out.push(...names.map((name, i) => phase === "always" ? {
689
+ name,
690
+ order: i,
691
+ text: textMap.get(name) ?? "",
692
+ custom: customMap.get(name)
693
+ } : {
694
+ name,
695
+ order: i,
696
+ text: textMap.get(name) ?? "",
697
+ custom: customMap.get(name),
698
+ phase
699
+ }));
700
+ }
701
+ return out;
457
702
  }
458
703
  /**
459
- * Compute the config patch when applying a preset:
460
- * - same-name sections are overridden (the order list drives this at runtime)
461
- * - preset sections missing from the current prompt are added
462
- * - current sections NOT in the preset's ordered list are disabled by default
463
- * - only the preset's ACTIVE sections (in the order list but not in its block
464
- * list) are unblocked; the preset's own blocked sections stay blocked.
704
+ * 计算应用预设时的配置补丁:
705
+ * - 同名段被覆盖(顺序列表在运行时驱动这一行为)
706
+ * - 预设中有、当前提示词中没有的段被添加
707
+ * - 当前有、但不在预设有序列表中的段默认被屏蔽
708
+ * - 只有预设的「激活段」(在 order 列表且不在其屏蔽名单中)被解除屏蔽;
709
+ * 预设自己屏蔽的段保持屏蔽。
465
710
  *
466
- * Custom injected sections that exist in the current config but are NOT in the
467
- * preset's ordered list are preserved in the resulting inject list (so they
468
- * stay visible) and disabled (added to the blocked set), rather than silently
469
- * dropped — a preset must not make the user's own injected sections vanish.
711
+ * 当前配置里存在、但不在预设有序列表中的自定义注入段会被保留到结果的
712
+ * inject 列表中(因此仍然可见)并置为禁用(加入屏蔽集合),而不是被静默
713
+ * 丢弃——预设不能让用户自己注入的凭空消失。
470
714
  */
471
715
  function applyPresetData(data, cfg, currentNames) {
472
716
  const presetOrder = data.order ?? [];
@@ -490,7 +734,12 @@ window.__ModuleLoader__.load({
490
734
  for (const name of currentNames) if (!presetNames.has(name)) blocked.add(name);
491
735
  for (const name of activeNames) blocked.delete(name);
492
736
  }
493
- return {
737
+ const keptCatalogs = {};
738
+ const bootstrap = data.tools?.bootstrap !== void 0 ? data.tools.bootstrap : cfg.tools?.bootstrap;
739
+ const compaction = data.tools?.compaction !== void 0 ? data.tools.compaction : cfg.tools?.compaction;
740
+ if (bootstrap !== void 0) keptCatalogs.bootstrap = bootstrap;
741
+ if (compaction !== void 0) keptCatalogs.compaction = compaction;
742
+ const patch = {
494
743
  sections: [...blocked],
495
744
  replace: {
496
745
  ...cfg.replace ?? {},
@@ -499,42 +748,123 @@ window.__ModuleLoader__.load({
499
748
  inject,
500
749
  tools: {
501
750
  exclude: data.tools?.exclude ?? [],
502
- include: data.tools?.include ?? []
751
+ ...keptCatalogs
503
752
  }
504
753
  };
754
+ if (Array.isArray(data.sectionsBootstrap)) patch.sectionsBootstrap = data.sectionsBootstrap;
755
+ if (Array.isArray(data.sectionsCompaction)) patch.sectionsCompaction = data.sectionsCompaction;
756
+ return patch;
505
757
  }
758
+ /** 三个阶段部分的固定展示顺序:引导期 → 常驻期 → 压缩受控期。
759
+ * 恒定全部渲染 —— 预设没有某个阶段时该部分只是空的,绝不隐藏。 */
760
+ const PART_ORDER = [
761
+ "bootstrap",
762
+ "active",
763
+ "compaction"
764
+ ];
506
765
  /**
507
- * Remove a custom (plugin-added) section from the config: it disappears from
508
- * the inject list, is no longer forced into the blocked set, and any replace
509
- * text for it is cleared. The remaining inject entries are re-indexed to a
510
- * contiguous 0..n-1 order (the virtual index model), so removal never leaves
511
- * holes. System sections read from the host inventory cannot be removed this
512
- * way (they would just come back on the next inventory read).
766
+ * 一个阶段部分写回哪一份过滤配置:引导期 → `tools.bootstrap`、压缩受控期 →
767
+ * `tools.compaction`、常驻期 → 静态 `tools.exclude`。三份名单互不继承。
513
768
  */
514
- function removeSection(name, cfg) {
515
- const sections = (cfg.sections ?? []).filter((n) => n !== name);
516
- const inject = (cfg.inject ?? []).filter((item) => item.name !== name).map((item, i) => ({
517
- ...item,
518
- order: i
519
- }));
520
- const replace = { ...cfg.replace ?? {} };
521
- delete replace[name];
769
+ function phaseConfigKey(key) {
770
+ return key === "active" ? "static" : key;
771
+ }
772
+ /**
773
+ * 把一个阶段的 exclude 名单写回整份工具配置,返回新对象(其余阶段原样保留)。
774
+ * 一次拖放可能要同时改两个阶段的名单(搬移 = 源阶段隐藏 + 目标阶段显示),必须
775
+ * 在同一个对象上连续套完再落一次写入 —— 分两次写会各自基于旧 cfg 计算而互相覆盖。
776
+ */
777
+ function withPhaseExclude(tools, key, exclude) {
778
+ const base = tools ?? {};
779
+ const target = phaseConfigKey(key);
780
+ if (target === "bootstrap") return {
781
+ ...base,
782
+ bootstrap: {
783
+ ...base.bootstrap ?? {},
784
+ exclude
785
+ }
786
+ };
787
+ if (target === "compaction") return {
788
+ ...base,
789
+ compaction: {
790
+ ...base.compaction ?? {},
791
+ exclude
792
+ }
793
+ };
522
794
  return {
523
- sections,
524
- inject,
525
- replace
795
+ ...base,
796
+ exclude
797
+ };
798
+ }
799
+ /**
800
+ * 把一个阶段的 add 名单(要加回该阶段的工具)写回整份工具配置,返回新对象。
801
+ * 与 withPhaseExclude 对称:常驻期写静态 `tools.add`,引导期写 `tools.bootstrap.add`,
802
+ * 压缩受控期写 `tools.compaction.add`,其余阶段原样保留。
803
+ */
804
+ function withPhaseAdd(tools, key, add) {
805
+ const base = tools ?? {};
806
+ const target = phaseConfigKey(key);
807
+ if (target === "bootstrap") return {
808
+ ...base,
809
+ bootstrap: {
810
+ ...base.bootstrap ?? {},
811
+ add
812
+ }
813
+ };
814
+ if (target === "compaction") return {
815
+ ...base,
816
+ compaction: {
817
+ ...base.compaction ?? {},
818
+ add
819
+ }
820
+ };
821
+ return {
822
+ ...base,
823
+ add
526
824
  };
527
825
  }
528
- /** Serialize a preset for export (JSON-safe full snapshot). */
529
- function serializePreset(preset) {
826
+ /** 某个工具在当前黑名单配置下是否被隐藏。 */
827
+ function isToolHidden(name, toolsCfg) {
828
+ return (toolsCfg?.exclude ?? []).includes(name);
829
+ }
830
+ /**
831
+ * 编辑目标的「显示视图」:全局目标返回原配置;agent 预设目标把该预设
832
+ * override 的字段叠在全局值之上展示(空缺字段显示全局继承值)。`presets`
833
+ * 与 `activePreset` 永远来自全局 —— 预设快照库本身不分作用域。
834
+ */
835
+ function editView(cfg, target) {
836
+ if (!target) return cfg;
837
+ const ovr = cfg.overrides?.[target] ?? {};
530
838
  return {
531
- name: preset.name,
532
- data: preset.data
839
+ sections: ovr.sections ?? cfg.sections,
840
+ sectionsBootstrap: ovr.sectionsBootstrap ?? cfg.sectionsBootstrap,
841
+ sectionsCompaction: ovr.sectionsCompaction ?? cfg.sectionsCompaction,
842
+ replace: ovr.replace ?? cfg.replace,
843
+ inject: ovr.inject ?? cfg.inject,
844
+ tools: {
845
+ exclude: ovr.tools?.exclude ?? cfg.tools?.exclude,
846
+ add: ovr.tools?.add ?? cfg.tools?.add,
847
+ bootstrap: ovr.tools?.bootstrap ?? cfg.tools?.bootstrap,
848
+ compaction: ovr.tools?.compaction ?? cfg.tools?.compaction
849
+ },
850
+ presets: cfg.presets,
851
+ activePreset: cfg.activePreset
533
852
  };
534
853
  }
535
854
  /**
536
- * Import preset(s): same-name presets are skipped, only distinct names are
537
- * added. Returns a new presets list (or the original if nothing changed).
855
+ * Derive a safe default filename for a preset export. User-entered preset
856
+ * names may contain characters that are illegal in filenames (`/\:*?"<>|`,
857
+ * control chars) — those are replaced; a trailing dot/space is trimmed
858
+ * (invalid on Windows); an empty or all-illegal result falls back to
859
+ * `preset`.
860
+ */
861
+ function presetExportFilename(name) {
862
+ const sanitized = String(name).replace(/[<>:"/\\|?*\u0000-\u001f]/g, "_").trim().replace(/[. ]+$/, "");
863
+ return `${sanitized === "" ? "preset" : sanitized}.json`;
864
+ }
865
+ /**
866
+ * 导入预设:同名的会被跳过,只追加名字不同的预设。返回新的预设列表
867
+ * (若没有任何变更则返回原列表)。
538
868
  */
539
869
  function addImportedPresets(existing, parsed, makeId) {
540
870
  const incoming = Array.isArray(parsed) ? parsed : [parsed];
@@ -546,236 +876,660 @@ window.__ModuleLoader__.load({
546
876
  }));
547
877
  return added.length > 0 ? [...existing, ...added] : existing;
548
878
  }
549
- /** Delete a preset, clearing the active id if it pointed at the removed one. */
879
+ /** 删除某个预设;若它正是当前激活的预设,则同时清除 activeId。 */
550
880
  function removePreset(presets, id, activeId) {
551
881
  return {
552
882
  presets: presets.filter((p) => p.id !== id),
553
883
  activeId: activeId === id ? void 0 : activeId
554
884
  };
555
885
  }
886
+ /** 生成预设 id:时间戳 + 随机段(base36),够用且无需额外依赖。 */
887
+ function genId() {
888
+ return "p_" + Date.now().toString(36) + Math.random().toString(36).slice(2, 7);
889
+ }
890
+ //#endregion
891
+ //#region lib/sectionOps.mjs
892
+ /**
893
+ * 提示词段面板的纯状态逻辑(无 React / 无 IO)。
894
+ * 与 src/client/SectionsTab.tsx 共享同一份实现(浏览器里随 client bundle
895
+ * 打包;node --test 直接 import 本文件跑单测),保证「测试即上线代码」。
896
+ *
897
+ * 阶段模型:引导期(bootstrap)/ 常驻期(active)/ 压缩受控期(compaction)
898
+ * 恒定全部显示(预设没有某个阶段时该部分就是空的),各自拥有独立的注入
899
+ * 名单与 order 空间;屏蔽按「每阶段独立名单」写回(引导期 →
900
+ * sectionsBootstrap,压缩受控期 → sectionsCompaction,常驻期 → 全局 sections)。
901
+ * 入参统一是名义阶段键,不再有「同形折叠组」这种把引导期当常驻期用的形态。
902
+ */
903
+ /** 名义阶段键 → 屏蔽名单写回目标(常驻期用全局 sections)。 */
904
+ function sectionListOf(key) {
905
+ return key === "bootstrap" ? "bootstrap" : key === "compaction" ? "compaction" : "global";
906
+ }
907
+ /** 名义阶段键 → 注入阶段:压缩受控期是独立注入阶段(compaction)。 */
908
+ function injectPhaseOf(key) {
909
+ return key === "bootstrap" ? "bootstrap" : key === "active" ? "active" : "compaction";
910
+ }
911
+ /** 某注入段出现在哪些阶段部分:always 全阶段;bootstrap/compaction/active
912
+ * 仅各自对应的阶段(与服务端 filterInjectByPhase 的三态互相独立一致)。 */
913
+ function acceptsInjectFor(key, phase) {
914
+ if (phase === "always") return true;
915
+ return phase === key;
916
+ }
917
+ /** 该阶段生效的屏蔽名单(全局 + 阶段独立 的 union)。 */
918
+ function deniedNames(cfg, key) {
919
+ const list = sectionListOf(key);
920
+ const phase = list === "bootstrap" ? cfg.sectionsBootstrap ?? [] : list === "compaction" ? cfg.sectionsCompaction ?? [] : [];
921
+ return [...cfg.sections ?? [], ...phase];
922
+ }
923
+ /**
924
+ * 某个阶段部分当前的注入身份(含未保存草稿)。
925
+ *
926
+ * `names` = 本部分可见的注入段名(本阶段专属 + 跨阶段的 always)。post 视图来自
927
+ * 「上次保存」的服务端结果,删除只改草稿,所以 post 独有段必须有 names 背书才
928
+ * 能显示 —— 否则刚删掉的自定义段会以「系统段」复活(身份只认 custom 标记,条目
929
+ * 没了就被判成系统),再经一次重排就被写成 custom:false 空文本,用户填的内容被
930
+ * 抹平。`custom` 只收真正的自定义段,`order` 只收本阶段的草稿序。
931
+ *
932
+ * `text` = 本阶段生效的用户文本:自定义段自带的文本,以及**系统段在本阶段被
933
+ * 替换后的文本**(非空即替换)。系统段的文本必须按阶段存 —— 注入条目本来就带
934
+ * `phase`,服务端按阶段筛选,所以三个阶段各改各的文本互不影响;旧的全局
935
+ * `replace` 字典一份文本对三个阶段同时生效,已不承担界面编辑。
936
+ */
937
+ function injectedAt(cfg, key) {
938
+ const phase = injectPhaseOf(key);
939
+ const names = /* @__PURE__ */ new Set();
940
+ const custom = /* @__PURE__ */ new Set();
941
+ const text = /* @__PURE__ */ new Map();
942
+ const order = /* @__PURE__ */ new Map();
943
+ for (const item of cfg.inject ?? []) {
944
+ if (item === null || typeof item !== "object" || typeof item.name !== "string") continue;
945
+ const itemPhase = item.phase ?? "always";
946
+ if (itemPhase === phase) order.set(item.name, item.order ?? 0);
947
+ if (!acceptsInjectFor(key, itemPhase)) continue;
948
+ names.add(item.name);
949
+ if (item.text && !text.has(item.name)) text.set(item.name, item.text);
950
+ if (item.custom === true) custom.add(item.name);
951
+ }
952
+ return {
953
+ phase,
954
+ names,
955
+ custom,
956
+ text,
957
+ order
958
+ };
959
+ }
960
+ /**
961
+ * 屏蔽/恢复一个段(当前阶段语义):返回需要写盘的字段补丁。
962
+ * - 屏蔽:该阶段名单加入(常驻期直接加入全局 sections)。
963
+ * - 恢复:从该阶段名单与全局名单同时移除(union 语义 —— 否则仍会被另一
964
+ * 份名单挡住,恢复不生效)。
965
+ * 名单无变化时不产出字段(空补丁 = 不写盘),避免把继承值冻结成无意义的
966
+ * 空数组覆盖。
967
+ */
968
+ function blockPatch(cfg, key, name, blocked) {
969
+ const list = sectionListOf(key);
970
+ const g = (cfg.sections ?? []).slice();
971
+ const gi = g.indexOf(name);
972
+ const patch = {};
973
+ if (list === "global") {
974
+ if (blocked) {
975
+ if (gi < 0) {
976
+ g.push(name);
977
+ patch.sections = g;
978
+ }
979
+ } else if (gi >= 0) {
980
+ g.splice(gi, 1);
981
+ patch.sections = g;
982
+ }
983
+ return patch;
984
+ }
985
+ const field = list === "bootstrap" ? "sectionsBootstrap" : "sectionsCompaction";
986
+ const phase = (cfg[field] ?? []).slice();
987
+ const pi = phase.indexOf(name);
988
+ if (blocked) {
989
+ if (pi < 0) {
990
+ phase.push(name);
991
+ patch[field] = phase;
992
+ }
993
+ } else {
994
+ if (pi >= 0) {
995
+ phase.splice(pi, 1);
996
+ patch[field] = phase;
997
+ }
998
+ if (gi >= 0) {
999
+ g.splice(gi, 1);
1000
+ patch.sections = g;
1001
+ }
1002
+ }
1003
+ return patch;
1004
+ }
1005
+ /**
1006
+ * 重排/插入一个阶段的有序行列表:把 dragName 从列表中移除后,插入到
1007
+ * targetName 行之上(pos='above')或之下(pos='below');返回新列表。
1008
+ * 拖入的新段由调用方以 newRow 提供,插入后保留在列表中(其余行保持原样)。
1009
+ */
1010
+ function reorderInsert(rows, dragName, targetName, pos, newRow = null) {
1011
+ const base = rows.filter((row) => row.name !== dragName);
1012
+ const idx = base.findIndex((row) => row.name === targetName);
1013
+ if (idx < 0) return null;
1014
+ const insertAt = Math.max(0, Math.min(pos === "above" ? idx : idx + 1, base.length));
1015
+ const entry = newRow ?? rows.find((row) => row.name === dragName);
1016
+ if (!entry) return null;
1017
+ base.splice(insertAt, 0, entry);
1018
+ return base;
1019
+ }
1020
+ /**
1021
+ * 持久化一个阶段的有序列表(v1 persistOrder 的逐阶段版):把 rows(有序行)
1022
+ * 写成该阶段的注入条目,order = 连续整数(0,1,2,…)——「虚拟 order 决定注入
1023
+ * 顺序」;文本优先级 = 本阶段的用户替换文本(row.override)→ 自定义段自带的
1024
+ * 文本(row.text)→ 空文本(= 仅 order 覆盖,服务端保留原文)。三者缺一不可:
1025
+ * 重排走的就是这个函数,漏掉 override 会让一次拖动把用户在该阶段改的文本抹平。
1026
+ * 其它阶段(含 always)的注入条目原样保留。
1027
+ */
1028
+ function phaseInjectEntries(cfg, key, rows) {
1029
+ const phase = injectPhaseOf(key);
1030
+ const others = (cfg.inject ?? []).filter((item) => (item.phase ?? "always") !== phase);
1031
+ const entries = rows.map((row, i) => ({
1032
+ name: row.name,
1033
+ order: i,
1034
+ text: row.override || (row.custom ? row.text ?? "" : ""),
1035
+ phase,
1036
+ custom: row.custom
1037
+ }));
1038
+ return [...others, ...entries];
1039
+ }
556
1040
  //#endregion
557
1041
  //#region src/client/SectionsTab.tsx
558
- /** Prompt-sections tab: block / replace / inject / reorder prompt sections. */
559
- function SectionsTab({ cfg, inv, scope, t }) {
560
- const replace = cfg.replace ?? {};
561
- const blockedNames = new Set(cfg.sections ?? []);
1042
+ /** 提示词段 Tab:四个部分 —— 引导期 / 常驻期 / 压缩受控期(三个阶段恒定
1043
+ * 显示,预设没有某个阶段时该部分只是空的)+ 本系统全部提示词(只读池)。
1044
+ *
1045
+ * 交互对齐提示词段初版(v1),并修复三类反馈缺失:
1046
+ * - 上三段每行 = 真实进入该阶段装配的段(post 视图,与预览一致 —— 预设
1047
+ * 原生阶段插件裁剪掉的段不显示)∪ 被屏蔽的段 ∪ 配置里的自定义注入段,
1048
+ * 顺序以 base 骨架为底再叠加草稿序;整行可拖拽,拖到某行上方/下方出现
1049
+ * 插入指示线,松手即在该位置重排。
1050
+ * - 被屏蔽的段与普通段一模一样:留在列表原位、一样可操作(拖拽/箭头/替换/
1051
+ * 恢复/删除),随时可互相转换,唯一区别是屏蔽勾选框与「已屏蔽」徽标 ——
1052
+ * 屏蔽只意味着不注入模型,不剥夺任何编辑能力(v1 语义)。屏蔽勾选直接
1053
+ * 绑定当前生效名单(deniedNames = 全局 + 该阶段名单,含未保存草稿),
1054
+ * 点击立即反馈。
1055
+ * - 重排(拖入/箭头)走 `persistPhase`:把该阶段全部行重写为连续整数
1056
+ * 虚拟 order(系统段写空文本 = 仅 order 覆盖,服务端保留原文;custom 段
1057
+ * 保留文本)—— UI 行序叠加同一份 order 立即重排,拖动即时可见。
1058
+ * - 文本编辑(「编辑」/「还原」)同样按阶段生效:写的就是本阶段注入条目的
1059
+ * 文本,三个阶段各改各的、互不影响(服务端让本阶段注入文本优先于全局
1060
+ * replace,否则一份文本会同时改坏三个阶段)。全局 replace 字典自此不再由
1061
+ * 界面写入,只在「还原」时顺带清除遗留条目 —— 新界面没有别的出口能恢复它。
1062
+ * - 拖放搬移保留行对象(system/custom 身份与文本原样带走),绝不重建行 ——
1063
+ * 重建会把系统段误标成 custom 并清空内容。只有从其它部分/全部池拖入的
1064
+ * 新段才构造新行(身份取自拖拽源)。
1065
+ * - 拖放事件在行上处理并 stopPropagation,避免与阶段框二次处理对冲。
1066
+ * - 全部提示词 → 上三段:插入该段到目标位置(已存在则只是移动排序;该段
1067
+ * 在目标阶段被屏蔽则同步解除屏蔽 —— 行立即出现)。上三段 → 全部:从该
1068
+ * 阶段移除 —— custom 段删除注入条目;系统段等价于屏蔽该阶段(系统段是
1069
+ * 装配的一部分,无法真正删除)。
1070
+ * - 解除屏蔽按份额归属分流写入:继承自全局名单的屏蔽直接改全局名单(立即
1071
+ * 写盘通道)—— override 无法表达「比全局更宽松」(空名单回落全局,解除
1072
+ * 会在保存后复现);override 自报名单与阶段名单的份额走目标草稿。
1073
+ * - 每个阶段部分按自己那一阶段的装配结果给出警示:该 scope 有 complete 段
1074
+ * 整段接管最终提示词,或本插件产出的段被下游装配规则丢弃时,明确写出
1075
+ * 「段级定制不会(完全)进入模型看到的提示词」,避免提示词 Tab 与预览 Tab
1076
+ * 各说各话。
1077
+ *
1078
+ * 全部阶段状态逻辑来自 lib/sectionOps.mjs(纯函数,node --test 单测直接
1079
+ * 覆盖同一份代码)。
1080
+ */
1081
+ /** 编辑态的键:段名之外还要带阶段,否则三个部分里同名的行会同时展开编辑器。 */
1082
+ const editKey = (key, name) => `${key}:${name}`;
1083
+ function SectionsTab({ cfg, inv, phases, target, globalSections, ownedSections, t, write, writeGlobalField }) {
562
1084
  const [editing, setEditing] = (0, react.useState)(null);
563
1085
  const [draft, setDraft] = (0, react.useState)("");
564
1086
  const [dragName, setDragName] = (0, react.useState)(null);
1087
+ const [dragSource, setDragSource] = (0, react.useState)(null);
565
1088
  const [dropTarget, setDropTarget] = (0, react.useState)(null);
566
- const merged = mergeSections(inv, cfg, blockedNames);
567
- const toggleBlock = (name, currentlyBlocked) => {
568
- const list = (cfg.sections ?? []).slice();
569
- if (currentlyBlocked) {
570
- const i = list.indexOf(name);
571
- if (i >= 0) list.splice(i, 1);
572
- } else list.push(name);
573
- scope.set("sections", list);
574
- };
575
- const startReplace = (name, original) => {
576
- setEditing(name);
577
- setDraft(replace[name] ?? original);
578
- };
579
- const commitReplace = (name) => {
580
- const next = { ...replace };
581
- if (draft.trim() === "") delete next[name];
582
- else next[name] = draft;
583
- scope.set("replace", next);
584
- setEditing(null);
1089
+ const [notice, setNotice] = (0, react.useState)(null);
1090
+ const scrollRef = (0, react.useRef)({
1091
+ raf: 0,
1092
+ clientY: 0
1093
+ });
1094
+ const stopAutoScroll = () => {
1095
+ if (scrollRef.current.raf !== 0) {
1096
+ cancelAnimationFrame(scrollRef.current.raf);
1097
+ scrollRef.current.raf = 0;
1098
+ }
1099
+ };
1100
+ const autoScrollTick = () => {
1101
+ scrollRef.current.raf = 0;
1102
+ const edge = 48;
1103
+ const y = scrollRef.current.clientY;
1104
+ const inner = window.innerHeight;
1105
+ let node = rootRef.current?.parentElement;
1106
+ while (node !== null && node !== void 0) {
1107
+ if (node.scrollHeight > node.clientHeight) {
1108
+ if (y < edge) node.scrollTop -= Math.max(6, (edge - y) / 2);
1109
+ else if (y > inner - edge) node.scrollTop += Math.max(6, (y - (inner - edge)) / 2);
1110
+ else return;
1111
+ scrollRef.current.raf = requestAnimationFrame(autoScrollTick);
1112
+ return;
1113
+ }
1114
+ node = node.parentElement;
1115
+ }
1116
+ if (y < edge) window.scrollBy({ top: -Math.max(6, (edge - y) / 2) });
1117
+ else if (y > inner - edge) window.scrollBy({ top: Math.max(6, (y - (inner - edge)) / 2) });
1118
+ if (y < edge || y > inner - edge) scrollRef.current.raf = requestAnimationFrame(autoScrollTick);
1119
+ };
1120
+ const rootRef = (0, react.useRef)(null);
1121
+ const rootDragOver = (e) => {
1122
+ if (!dragName) return;
1123
+ scrollRef.current.clientY = e.clientY;
1124
+ if (scrollRef.current.raf === 0) scrollRef.current.raf = requestAnimationFrame(autoScrollTick);
585
1125
  };
586
- const restoreReplace = (name) => {
587
- const next = { ...replace };
588
- delete next[name];
589
- scope.set("replace", next);
1126
+ const parts = PART_ORDER;
1127
+ const partNote = (key) => {
1128
+ const view = phases?.[key];
1129
+ if (view === void 0 || view === null) return null;
1130
+ if (cfg.forceSections !== false) return null;
1131
+ if (view.takenOverBy !== void 0) return (0, react.createElement)("div", { style: s.noticeWarn }, t("sectionsTakenOver", { name: view.takenOverBy }));
1132
+ const lost = view.lostSections;
1133
+ if (lost !== void 0) return (0, react.createElement)("div", { style: s.noticeWarn }, t("sectionsLost", {
1134
+ emitted: lost.emitted,
1135
+ survived: lost.survived
1136
+ }));
1137
+ return null;
590
1138
  };
591
- const persistOrder = (ordered) => {
592
- const list = ordered.map((sec, i) => {
593
- const existing = (cfg.inject ?? []).find((x) => x.name === sec.name);
594
- const isCustom = sec.source === "custom";
1139
+ const rowsOf = (key) => {
1140
+ const replace = cfg.replace ?? {};
1141
+ const view = phases?.[key];
1142
+ const denied = new Set(deniedNames(cfg, key));
1143
+ const postByName = new Map((view?.sections ?? []).map((sec) => [sec.name, sec]));
1144
+ const baseByName = new Map((view?.baseSections ?? []).map((sec) => [sec.name, sec]));
1145
+ const { phase, names: injectedHere, custom: customNames, text, order: phaseOrder } = injectedAt(cfg, key);
1146
+ const names = [];
1147
+ const seen = /* @__PURE__ */ new Set();
1148
+ const push = (name) => {
1149
+ if (!seen.has(name)) {
1150
+ seen.add(name);
1151
+ names.push(name);
1152
+ }
1153
+ };
1154
+ for (const sec of view?.baseSections ?? []) if (postByName.has(sec.name) || denied.has(sec.name) || sec.blocked === true) push(sec.name);
1155
+ for (const name of postByName.keys()) if (baseByName.has(name) || injectedHere.has(name)) push(name);
1156
+ for (const item of cfg.inject ?? []) {
1157
+ if ((item.phase ?? "always") !== phase) continue;
1158
+ if (item.custom === true || text.get(item.name) || baseByName.has(item.name) || postByName.has(item.name)) push(item.name);
1159
+ }
1160
+ for (const name of customNames) push(name);
1161
+ const rows = names.map((name) => {
1162
+ const override = text.get(name) ?? "";
595
1163
  return {
596
- name: sec.name,
597
- order: i,
598
- text: isCustom ? sec.text ?? "" : existing?.text ?? "",
599
- custom: isCustom
1164
+ name,
1165
+ text: postByName.get(name)?.text ?? baseByName.get(name)?.text ?? "",
1166
+ replaced: override !== "" || Object.hasOwn(replace, name),
1167
+ custom: customNames.has(name),
1168
+ override,
1169
+ blocked: denied.has(name)
600
1170
  };
601
1171
  });
602
- scope.set("inject", list);
1172
+ if (phaseOrder.size > 0) {
1173
+ const fallback = new Map(rows.map((row, i) => [row.name, i]));
1174
+ rows.sort((a, b) => (phaseOrder.get(a.name) ?? fallback.get(a.name) ?? 0) - (phaseOrder.get(b.name) ?? fallback.get(b.name) ?? 0));
1175
+ }
1176
+ return rows;
603
1177
  };
604
- const removeCustom = (name) => {
605
- const patch = removeSection(name, cfg);
606
- scope.set("sections", patch.sections);
607
- scope.set("inject", patch.inject);
608
- scope.set("replace", patch.replace);
1178
+ const applyBlock = (key, name, blocked) => {
1179
+ if (blocked || !target) {
1180
+ const patch = blockPatch(cfg, key, name, blocked);
1181
+ for (const [field, value] of Object.entries(patch)) {
1182
+ if (JSON.stringify(value) === JSON.stringify(cfg[field] ?? [])) continue;
1183
+ write(field, value);
1184
+ }
1185
+ return;
1186
+ }
1187
+ const patch = blockPatch(cfg, key, name, false);
1188
+ const effectiveOwned = ownedSections && ownedSections.length > 0 ? ownedSections : void 0;
1189
+ for (const [field, value] of Object.entries(patch)) {
1190
+ if (field === "sections") {
1191
+ if ((globalSections ?? []).includes(name) && (!effectiveOwned || ownedSections.includes(name))) writeGlobalField("sections", (globalSections ?? []).filter((n) => n !== name));
1192
+ if (effectiveOwned?.includes(name)) write("sections", value);
1193
+ continue;
1194
+ }
1195
+ if (JSON.stringify(value) === JSON.stringify(cfg[field] ?? [])) continue;
1196
+ write(field, value);
1197
+ }
1198
+ };
1199
+ const toggleBlocked = (key, name) => applyBlock(key, name, !deniedNames(cfg, key).includes(name));
1200
+ const inBaseOf = (key, name) => (phases?.[key]?.baseSections ?? []).some((sec) => sec.name === name);
1201
+ const persistPhase = (key, rows) => {
1202
+ write("inject", phaseInjectEntries(cfg, key, rows));
609
1203
  };
610
- const moveOrder = (index, dir) => {
1204
+ const moveRow = (key, index, dir) => {
1205
+ const rows = rowsOf(key);
611
1206
  const target = index + dir;
612
- if (target < 0 || target >= merged.length) return;
613
- const next = merged.slice();
1207
+ if (target < 0 || target >= rows.length) return;
1208
+ const next = rows.slice();
614
1209
  const [item] = next.splice(index, 1);
615
1210
  next.splice(target, 0, item);
616
- persistOrder(next);
1211
+ persistPhase(key, next);
1212
+ };
1213
+ const removeFromPart = (key, name) => {
1214
+ const phase = injectPhaseOf(key);
1215
+ write("inject", (cfg.inject ?? []).filter((x) => {
1216
+ if (x.name !== name) return true;
1217
+ const itemPhase = x.phase ?? "always";
1218
+ return !(itemPhase === phase || itemPhase === "always");
1219
+ }));
1220
+ applyBlock(key, name, false);
1221
+ };
1222
+ const startReplace = (key, row) => {
1223
+ setEditing(editKey(key, row.name));
1224
+ setDraft(row.override || row.text);
1225
+ };
1226
+ const commitReplace = (key, row) => {
1227
+ const next = rowsOf(key).map((r) => r.name !== row.name ? r : {
1228
+ ...r,
1229
+ override: draft,
1230
+ text: draft
1231
+ });
1232
+ persistPhase(key, next);
1233
+ setEditing(null);
1234
+ };
1235
+ const restoreReplace = (key, row) => {
1236
+ const next = rowsOf(key).map((r) => r.name !== row.name ? r : {
1237
+ ...r,
1238
+ override: "",
1239
+ text: r.custom ? r.text : ""
1240
+ });
1241
+ persistPhase(key, next);
1242
+ if (!row.custom && Object.hasOwn(cfg.replace ?? {}, row.name)) {
1243
+ const rest = { ...cfg.replace ?? {} };
1244
+ delete rest[row.name];
1245
+ write("replace", rest);
1246
+ }
617
1247
  };
618
- const onDragStart = (e, name) => {
1248
+ const addSection = (name, text, phase) => {
1249
+ const inject = (cfg.inject ?? []).slice();
1250
+ inject.push({
1251
+ name,
1252
+ order: 120 + inject.length,
1253
+ text,
1254
+ phase,
1255
+ custom: true
1256
+ });
1257
+ write("inject", inject);
1258
+ };
1259
+ const startDrag = (e, name, source) => {
619
1260
  setDragName(name);
1261
+ setDragSource(source);
620
1262
  e.dataTransfer.effectAllowed = "move";
621
1263
  try {
622
1264
  e.dataTransfer.setData("text/plain", name);
623
1265
  } catch {}
624
1266
  };
625
- const onDragOver = (e, name) => {
1267
+ const rowDragOver = (e, key, name) => {
626
1268
  if (!dragName || dragName === name) return;
627
1269
  e.preventDefault();
628
1270
  e.dataTransfer.dropEffect = "move";
629
1271
  const rect = e.currentTarget.getBoundingClientRect();
630
1272
  const pos = e.clientY < rect.top + rect.height / 2 ? "above" : "below";
631
1273
  setDropTarget({
1274
+ part: key,
632
1275
  name,
633
1276
  pos
634
1277
  });
635
1278
  };
636
- const onDrop = (e, target) => {
637
- e.preventDefault();
638
- if (!dragName || dragName === target.name) {
639
- setDragName(null);
640
- setDropTarget(null);
1279
+ const carryFor = (key, source, name) => {
1280
+ if (source.kind !== "all" || source.custom) return {
1281
+ text: "",
1282
+ blocked: false
1283
+ };
1284
+ if (inBaseOf(key, name)) return {
1285
+ text: "",
1286
+ blocked: false
1287
+ };
1288
+ if (source.text === "") return {
1289
+ text: "",
1290
+ blocked: true
1291
+ };
1292
+ return {
1293
+ text: source.text,
1294
+ blocked: false
1295
+ };
1296
+ };
1297
+ const insertInto = (key, targetName, pos) => {
1298
+ if (!dragName || !dragSource) return;
1299
+ const carry = carryFor(key, dragSource, dragName);
1300
+ if (carry.blocked) {
1301
+ setNotice(t("sectionDynamicNoAdd", { name: dragName }));
641
1302
  return;
642
1303
  }
643
- const dragged = merged.find((x) => x.name === dragName);
644
- if (!dragged) {
645
- setDragName(null);
646
- setDropTarget(null);
647
- return;
1304
+ const rows = rowsOf(key);
1305
+ const newRow = rows.find((row) => row.name === dragName) ?? {
1306
+ name: dragName,
1307
+ text: dragSource.custom ? dragSource.text : "",
1308
+ replaced: Object.hasOwn(cfg.replace ?? {}, dragName),
1309
+ custom: dragSource.custom,
1310
+ override: carry.text,
1311
+ blocked: false
1312
+ };
1313
+ const next = reorderInsert(rows, dragName, targetName, pos, newRow);
1314
+ if (next === null) return;
1315
+ if (dragSource.kind === "all" && inBaseOf(key, dragName) && deniedNames(cfg, key).includes(dragName)) applyBlock(key, dragName, false);
1316
+ persistPhase(key, next);
1317
+ };
1318
+ const rowDrop = (e, key, name) => {
1319
+ e.preventDefault();
1320
+ e.stopPropagation();
1321
+ if (dragName && dragName !== name) {
1322
+ const pos = dropTarget?.part === key && dropTarget.name === name && dropTarget.pos ? dropTarget.pos : "below";
1323
+ insertInto(key, name, pos);
648
1324
  }
649
- const next = merged.filter((x) => x.name !== dragName);
650
- const idx = next.findIndex((x) => x.name === target.name);
651
- const pos = dropTarget?.name === target.name ? dropTarget.pos : "below";
652
- next.splice(pos === "above" ? idx : idx + 1, 0, dragged);
653
- persistOrder(next);
654
1325
  setDragName(null);
1326
+ setDragSource(null);
655
1327
  setDropTarget(null);
656
1328
  };
657
- const onDragEnd = () => {
1329
+ const partDropEnd = (e, key) => {
1330
+ e.preventDefault();
1331
+ if (dragName && dragSource) {
1332
+ const carry = carryFor(key, dragSource, dragName);
1333
+ if (!carry.blocked) {
1334
+ const rows = rowsOf(key);
1335
+ const existing = rows.find((row) => row.name === dragName);
1336
+ const next = rows.filter((row) => row.name !== dragName);
1337
+ next.push(existing ?? {
1338
+ name: dragName,
1339
+ text: dragSource.custom ? dragSource.text : "",
1340
+ replaced: Object.hasOwn(cfg.replace ?? {}, dragName),
1341
+ custom: dragSource.custom,
1342
+ override: carry.text,
1343
+ blocked: false
1344
+ });
1345
+ if (dragSource.kind === "all" && inBaseOf(key, dragName) && deniedNames(cfg, key).includes(dragName)) applyBlock(key, dragName, false);
1346
+ persistPhase(key, next);
1347
+ } else setNotice(t("sectionDynamicNoAdd", { name: dragName }));
1348
+ }
658
1349
  setDragName(null);
1350
+ setDragSource(null);
659
1351
  setDropTarget(null);
660
1352
  };
661
- const addSection = (name, order, text) => {
662
- const next = merged.slice();
663
- const entry = {
664
- name,
665
- order,
666
- text,
667
- active: true,
668
- replaced: false,
669
- source: "custom"
670
- };
671
- const existing = next.findIndex((x) => x.name === name);
672
- if (existing >= 0) next[existing] = entry;
673
- else {
674
- const idx = next.findIndex((x) => x.order > order);
675
- if (idx < 0) next.push(entry);
676
- else next.splice(idx, 0, entry);
1353
+ const allBoxDrop = (e) => {
1354
+ e.preventDefault();
1355
+ if (dragName && dragSource?.kind === "part" && dragSource.key) {
1356
+ const src = dragSource.key;
1357
+ const row = rowsOf(src).find((r) => r.name === dragName);
1358
+ const addedSystem = !!row && !row.custom && !inBaseOf(src, dragName) && row.override !== "";
1359
+ if (row && !row.custom && !addedSystem) applyBlock(src, dragName, true);
1360
+ else removeFromPart(src, dragName);
677
1361
  }
678
- persistOrder(next);
1362
+ setDragName(null);
1363
+ setDragSource(null);
1364
+ setDropTarget(null);
679
1365
  };
680
- return (0, react.createElement)("div", { style: s.list }, [
681
- merged.length === 0 ? (0, react.createElement)("div", { style: s.muted }, t("empty")) : null,
682
- merged.map((sec, index) => {
683
- const blocked = blockedNames.has(sec.name);
684
- const isEditing = editing === sec.name;
685
- const isDragging = dragName === sec.name;
686
- const isDropTarget = dropTarget?.name === sec.name;
687
- const rowStyle = {
688
- ...s.row,
689
- ...isDragging ? s.rowDragging : {},
690
- ...isDropTarget && dropTarget.pos === "above" ? s.rowDropAbove : {},
691
- ...isDropTarget && dropTarget.pos === "below" ? s.rowDropBelow : {}
692
- };
693
- return (0, react.createElement)("div", {
694
- key: sec.name,
695
- style: rowStyle,
696
- draggable: true,
697
- onDragStart: (e) => onDragStart(e, sec.name),
698
- onDragOver: (e) => onDragOver(e, sec.name),
699
- onDrop: (e) => onDrop(e, sec),
700
- onDragEnd
701
- }, [
702
- (0, react.createElement)("span", {
703
- style: s.dragHandle,
704
- title: t("drag")
705
- }, "⠿"),
706
- (0, react.createElement)("label", { style: s.switchWrap }, [(0, react.createElement)("input", {
707
- type: "checkbox",
708
- checked: blocked,
709
- onChange: () => toggleBlock(sec.name, blocked)
710
- }), (0, react.createElement)("span", { style: blocked ? s.badgeBlocked : s.badgeOk }, blocked ? t("blockedOn") : t("blockedOff"))]),
711
- (0, react.createElement)("div", { style: s.rowBody }, [(0, react.createElement)("div", { style: s.rowTitle }, [
712
- (0, react.createElement)("span", { style: s.code }, sec.name),
713
- (0, react.createElement)("span", { style: s.orderTag }, "#" + index),
714
- (0, react.createElement)("span", { style: sec.source === "custom" ? s.badgeCustom : s.badgeSystem }, sec.source === "custom" ? t("manual") : t("system")),
715
- replace[sec.name] ? (0, react.createElement)("span", { style: s.badgeReplaced }, t("replaced")) : null
716
- ]), isEditing ? (0, react.createElement)("div", { style: s.editBox }, [(0, react.createElement)("textarea", {
717
- style: s.editInput,
718
- value: draft,
719
- onChange: (e) => setDraft(e.target.value),
720
- rows: 3
721
- }), (0, react.createElement)("div", { style: s.injectRow }, [
722
- (0, react.createElement)("button", {
723
- style: s.mini,
724
- onClick: () => commitReplace(sec.name)
725
- }, t("save")),
726
- (0, react.createElement)("button", {
727
- style: s.mini,
728
- onClick: () => setEditing(null)
729
- }, t("clearInput")),
730
- sec.source !== "custom" && replace[sec.name] ? (0, react.createElement)("button", {
731
- style: s.mini,
732
- onClick: () => restoreReplace(sec.name)
733
- }, t("restore")) : null
734
- ])]) : (0, react.createElement)("div", { style: s.preview }, String(replace[sec.name] ?? sec.text ?? "").slice(0, 140) || (sec.source === "custom" ? t("empty") : t("dynamic")))]),
735
- (0, react.createElement)("div", { style: s.arrowCol }, [(0, react.createElement)("button", {
736
- style: s.arrow,
737
- disabled: index === 0,
738
- onClick: () => moveOrder(index, -1),
739
- title: t("moveUp")
740
- }, "↑"), (0, react.createElement)("button", {
741
- style: s.arrow,
742
- disabled: index === merged.length - 1,
743
- onClick: () => moveOrder(index, 1),
744
- title: t("moveDown")
745
- }, "↓")]),
746
- isEditing ? null : (0, react.createElement)("button", {
1366
+ const endDrag = () => {
1367
+ stopAutoScroll();
1368
+ setDragName(null);
1369
+ setDragSource(null);
1370
+ setDropTarget(null);
1371
+ };
1372
+ const partNoun = (key) => key === "bootstrap" ? t("sectionsPartGuide") : key === "compaction" ? t("sectionsPartControlled") : t("sectionsPartResident");
1373
+ const isEditing = (key, row) => editing === editKey(key, row.name);
1374
+ const renderRow = (key, row, index, total) => {
1375
+ const isDragging = dragName === row.name;
1376
+ const isDropTarget = dropTarget?.part === key && dropTarget.name === row.name;
1377
+ const rowStyle = {
1378
+ ...s.row,
1379
+ ...isDragging ? s.rowDragging : {},
1380
+ ...isDropTarget && dropTarget && dropTarget.pos === "above" ? s.rowDropAbove : {},
1381
+ ...isDropTarget && dropTarget && dropTarget.pos === "below" ? s.rowDropBelow : {},
1382
+ cursor: "move"
1383
+ };
1384
+ return (0, react.createElement)("div", {
1385
+ key: row.name,
1386
+ style: rowStyle,
1387
+ draggable: true,
1388
+ onDragStart: (e) => startDrag(e, row.name, {
1389
+ kind: "part",
1390
+ key,
1391
+ text: row.custom ? row.override || row.text : "",
1392
+ custom: row.custom
1393
+ }),
1394
+ onDragOver: (e) => rowDragOver(e, key, row.name),
1395
+ onDrop: (e) => rowDrop(e, key, row.name),
1396
+ onDragEnd: endDrag
1397
+ }, [
1398
+ (0, react.createElement)("span", {
1399
+ style: s.dragHandle,
1400
+ title: t("drag")
1401
+ }, "⠿"),
1402
+ (0, react.createElement)("label", { style: s.switchWrap }, [(0, react.createElement)("input", {
1403
+ type: "checkbox",
1404
+ checked: row.blocked,
1405
+ onChange: () => toggleBlocked(key, row.name)
1406
+ }), (0, react.createElement)("span", { style: row.blocked ? s.badgeBlocked : s.badgeOk }, row.blocked ? t("blockedOn") : t("blockedOff"))]),
1407
+ (0, react.createElement)("div", { style: s.rowBody }, [(0, react.createElement)("div", { style: s.rowTitle }, [
1408
+ (0, react.createElement)("span", { style: s.code }, row.name),
1409
+ (0, react.createElement)("span", { style: s.orderTag }, "#" + index),
1410
+ (0, react.createElement)("span", { style: row.custom ? s.badgeCustom : s.badgeSystem }, row.custom ? t("manual") : t("system")),
1411
+ row.replaced ? (0, react.createElement)("span", { style: s.badgeReplaced }, t("replaced")) : null
1412
+ ]), isEditing(key, row) ? (0, react.createElement)("div", { style: s.editBox }, [(0, react.createElement)("textarea", {
1413
+ style: s.editInput,
1414
+ value: draft,
1415
+ onChange: (e) => setDraft(e.target.value),
1416
+ rows: 3
1417
+ }), (0, react.createElement)("div", { style: s.injectRow }, [
1418
+ (0, react.createElement)("button", {
747
1419
  style: s.mini,
748
- onClick: () => startReplace(sec.name, String(sec.text ?? ""))
749
- }, t("replace")),
750
- !isEditing && sec.source !== "custom" && replace[sec.name] ? (0, react.createElement)("button", {
1420
+ onClick: () => commitReplace(key, row)
1421
+ }, t("save")),
1422
+ (0, react.createElement)("button", {
751
1423
  style: s.mini,
752
- onClick: () => restoreReplace(sec.name)
753
- }, t("restore")) : null,
754
- sec.source === "custom" ? (0, react.createElement)("button", {
1424
+ onClick: () => setDraft("")
1425
+ }, t("clearInput")),
1426
+ !row.custom && (row.override || Object.hasOwn(cfg.replace ?? {}, row.name)) ? (0, react.createElement)("button", {
755
1427
  style: s.mini,
756
- onClick: () => removeCustom(sec.name),
757
- title: t("delete")
758
- }, t("delete")) : null
759
- ]);
760
- }),
761
- (0, react.createElement)("div", { style: s.injectBox }, [(0, react.createElement)("div", { style: s.rowTitle }, t("injectNew")), (0, react.createElement)(InjectForm, {
762
- onAdd: addSection,
763
- t
764
- })])
1428
+ onClick: () => restoreReplace(key, row)
1429
+ }, t("restore")) : null
1430
+ ])]) : (0, react.createElement)("div", { style: s.preview }, String(row.override || row.text || "").slice(0, 140) || (row.custom ? t("empty") : t("dynamic")))]),
1431
+ (0, react.createElement)("div", { style: s.arrowCol }, [(0, react.createElement)("button", {
1432
+ style: s.arrow,
1433
+ disabled: index === 0,
1434
+ onClick: () => moveRow(key, index, -1),
1435
+ title: t("moveUp")
1436
+ }, "↑"), (0, react.createElement)("button", {
1437
+ style: s.arrow,
1438
+ disabled: index === total - 1,
1439
+ onClick: () => moveRow(key, index, 1),
1440
+ title: t("moveDown")
1441
+ }, "↓")]),
1442
+ isEditing(key, row) ? null : (0, react.createElement)("button", {
1443
+ style: s.mini,
1444
+ onClick: () => startReplace(key, row)
1445
+ }, t("replace")),
1446
+ !isEditing(key, row) && !row.custom && (row.override || Object.hasOwn(cfg.replace ?? {}, row.name)) ? (0, react.createElement)("button", {
1447
+ style: s.mini,
1448
+ onClick: () => restoreReplace(key, row)
1449
+ }, t("restore")) : null,
1450
+ row.custom ? (0, react.createElement)("button", {
1451
+ style: s.mini,
1452
+ onClick: () => removeFromPart(key, row.name),
1453
+ title: t("delete")
1454
+ }, t("delete")) : null
1455
+ ]);
1456
+ };
1457
+ const renderPart = (key) => {
1458
+ const rows = rowsOf(key);
1459
+ return (0, react.createElement)("div", {
1460
+ key,
1461
+ style: s.injectBox,
1462
+ onDragOver: (e) => {
1463
+ if (dragName) {
1464
+ e.preventDefault();
1465
+ e.dataTransfer.dropEffect = "move";
1466
+ }
1467
+ },
1468
+ onDrop: (e) => partDropEnd(e, key)
1469
+ }, [
1470
+ (0, react.createElement)("div", { style: s.rowTitle }, [(0, react.createElement)("span", null, partNoun(key)), (0, react.createElement)("span", { style: s.orderTag }, `${t("phaseVisible")} ${rows.length}`)]),
1471
+ partNote(key),
1472
+ rows.map((row, i) => renderRow(key, row, i, rows.length)),
1473
+ (0, react.createElement)(InjectForm, {
1474
+ onAdd: (name, text) => addSection(name, text, injectPhaseOf(key)),
1475
+ lockedPhase: injectPhaseOf(key),
1476
+ t
1477
+ })
1478
+ ]);
1479
+ };
1480
+ return (0, react.createElement)("div", {
1481
+ style: s.list,
1482
+ ref: rootRef,
1483
+ onDragOver: rootDragOver
1484
+ }, [
1485
+ notice ? (0, react.createElement)("div", { style: s.noticeWarn }, notice) : null,
1486
+ parts.map(renderPart),
1487
+ (0, react.createElement)("div", {
1488
+ style: s.injectBox,
1489
+ onDragOver: (e) => {
1490
+ if (dragName) {
1491
+ e.preventDefault();
1492
+ e.dataTransfer.dropEffect = "move";
1493
+ }
1494
+ },
1495
+ onDrop: allBoxDrop
1496
+ }, [
1497
+ (0, react.createElement)("div", { style: s.rowTitle }, [t("allSectionsTitle"), (0, react.createElement)("span", { style: s.orderTag }, `${(inv?.sections ?? []).length}`)]),
1498
+ (0, react.createElement)("div", { style: {
1499
+ ...s.muted,
1500
+ marginBottom: 4
1501
+ } }, t("sectionsFourHint")),
1502
+ (inv?.sections ?? []).length === 0 ? (0, react.createElement)("div", { style: s.muted }, t("empty")) : null,
1503
+ (inv?.sections ?? []).map((sec) => (0, react.createElement)("div", {
1504
+ key: sec.name,
1505
+ style: {
1506
+ ...s.row,
1507
+ cursor: "copy",
1508
+ opacity: .92
1509
+ },
1510
+ draggable: true,
1511
+ onDragStart: (e) => startDrag(e, sec.name, {
1512
+ kind: "all",
1513
+ text: (sec.text ?? "").startsWith("<") || !sec.text ? "" : sec.text,
1514
+ custom: false
1515
+ }),
1516
+ onDragEnd: endDrag
1517
+ }, [(0, react.createElement)("div", { style: s.rowBody }, [(0, react.createElement)("div", { style: s.rowTitle }, (0, react.createElement)("span", { style: s.code }, sec.name)), (0, react.createElement)("div", { style: s.preview }, String(sec.text ?? "").slice(0, 140) || t("dynamic"))])]))
1518
+ ])
765
1519
  ]);
766
1520
  }
767
- function InjectForm({ onAdd, t }) {
1521
+ /** 注入新段表单:阶段部分内联形态,阶段锁定为所在部分。 */
1522
+ function InjectForm({ onAdd, lockedPhase, t }) {
768
1523
  const [name, setName] = (0, react.useState)("");
769
- const [order, setOrder] = (0, react.useState)("120");
770
1524
  const [text, setText] = (0, react.useState)("");
771
1525
  const submit = () => {
772
1526
  if (!name.trim()) return;
773
- onAdd(name.trim(), Number(order) || 120, text);
1527
+ onAdd(name.trim(), text);
774
1528
  setName("");
775
1529
  setText("");
776
- setOrder("120");
777
1530
  };
778
- return (0, react.createElement)("div", {}, [(0, react.createElement)("div", { style: s.injectRow }, [
1531
+ const phaseLabel = lockedPhase === "bootstrap" ? t("phaseStageGuide") : lockedPhase === "compaction" ? t("phaseStageControlled") : t("phaseStageResident");
1532
+ return (0, react.createElement)("div", { style: s.injectRow }, [
779
1533
  (0, react.createElement)("input", {
780
1534
  style: {
781
1535
  ...s.input,
@@ -785,22 +1539,12 @@ window.__ModuleLoader__.load({
785
1539
  value: name,
786
1540
  onChange: (e) => setName(e.target.value)
787
1541
  }),
788
- (0, react.createElement)("input", {
789
- style: {
790
- ...s.input,
791
- width: "12%"
792
- },
793
- type: "number",
794
- placeholder: t("order"),
795
- value: order,
796
- onChange: (e) => setOrder(e.target.value)
797
- }),
798
1542
  (0, react.createElement)("input", {
799
1543
  style: {
800
1544
  ...s.input,
801
1545
  flex: 1
802
1546
  },
803
- placeholder: t("text"),
1547
+ placeholder: `${t("text")}(${phaseLabel})`,
804
1548
  value: text,
805
1549
  onChange: (e) => setText(e.target.value)
806
1550
  }),
@@ -808,63 +1552,442 @@ window.__ModuleLoader__.load({
808
1552
  style: s.mini,
809
1553
  onClick: submit
810
1554
  }, t("add"))
811
- ])]);
1555
+ ]);
812
1556
  }
813
1557
  //#endregion
814
1558
  //#region src/client/ToolsTab.tsx
815
- /** Tools tab: hide tools from the model catalog (blacklist only — check = hide). */
816
- function ToolsTab({ cfg, inv, scope, t }) {
817
- const tools = inv?.tools ?? [];
818
- const exclude = cfg.tools?.exclude ?? [];
819
- const hidden = (name) => exclude.includes(name);
820
- const toggle = (name, currentlyHidden) => {
821
- const next = exclude.slice();
822
- if (currentlyHidden) {
823
- const i = next.indexOf(name);
824
- if (i >= 0) next.splice(i, 1);
825
- } else next.push(name);
826
- scope.set("tools", {
827
- exclude: next,
828
- include: []
1559
+ /** 工具 Tab:四个部分 —— 引导期 / 常驻期 / 压缩受控期(三个阶段恒定显示,
1560
+ * 预设没有某个阶段时该部分只是空的)+ 本系统全部工具(只读池)。
1561
+ * - 上三段每行 = 该阶段进入过滤的目录 ∪ 用户加回的工具(预过滤视图,隐藏后
1562
+ * 仍在列表可反选),勾选 = 该阶段可见 / 隐藏。三份名单互不继承。
1563
+ * - 「加回」:被该阶段默认裁掉、但仍在当前预设注册表里的工具,可以拖进来重新
1564
+ * 出现(写该阶段的 add 名单,装配时从注册表查回 schema 追加)。注册表里根本
1565
+ * 没有的(别的预设独有)加不进来,界面明确说明。
1566
+ * - 全部工具 = 跨预设累积的注册表并集(只读池),每行标出该工具在三个阶段的
1567
+ * 状态;它按定义比任何单一预设都大,所以里面的工具完全可能不在当前预设注册表。
1568
+ * - 拖动:全部 → 某阶段 = 让该工具在这一阶段出现;阶段 → 阶段 = 搬移(源阶段
1569
+ * 隐藏 + 目标阶段显示);上三段 → 全部 = 在该阶段隐藏它。
1570
+ * - 只有黑名单,没有白名单:每个动作只作用于被拖 / 被点的那一个工具,绝不
1571
+ * 因为「拖进了一个工具」而把该阶段其它工具一起关掉。 */
1572
+ function ToolsTab({ cfg, inv, phases, t, write }) {
1573
+ const [dragFrom, setDragFrom] = (0, react.useState)(null);
1574
+ const [draggedName, setDraggedName] = (0, react.useState)(null);
1575
+ const [dropHint, setDropHint] = (0, react.useState)(null);
1576
+ const [notice, setNotice] = (0, react.useState)(null);
1577
+ const excludeOf = (key) => {
1578
+ const tools = cfg.tools ?? {};
1579
+ return (key === "bootstrap" ? tools.bootstrap?.exclude : key === "compaction" ? tools.compaction?.exclude : tools.exclude) ?? [];
1580
+ };
1581
+ const addOf = (key) => {
1582
+ const tools = cfg.tools ?? {};
1583
+ return (key === "bootstrap" ? tools.bootstrap?.add : key === "compaction" ? tools.compaction?.add : tools.add) ?? [];
1584
+ };
1585
+ const writeLists = (key, exclude, add) => {
1586
+ write("tools", withPhaseAdd(withPhaseExclude(cfg.tools ?? {}, key, exclude), key, add));
1587
+ };
1588
+ const catalogOf = (key) => (phases?.[key]?.baseTools ?? []).map((tool) => tool.name);
1589
+ const isInCatalog = (key, name) => catalogOf(key).includes(name);
1590
+ const registry = (() => {
1591
+ const list = PART_ORDER.map((key) => phases?.[key]?.registryTools).find((x) => Array.isArray(x) && x.length > 0) ?? [];
1592
+ return new Set(list);
1593
+ })();
1594
+ const isInRegistry = (name) => registry.has(name);
1595
+ const addToPhase = (key, name, hidden) => {
1596
+ let exclude = excludeOf(key);
1597
+ let add = addOf(key);
1598
+ if (!isInCatalog(key, name) && !add.includes(name)) add = [...add, name];
1599
+ exclude = hidden ? exclude.includes(name) ? exclude : [...exclude, name] : exclude.filter((x) => x !== name);
1600
+ writeLists(key, exclude, add);
1601
+ };
1602
+ const rowsOf = (key) => {
1603
+ const filter = { exclude: excludeOf(key) };
1604
+ const catalog = (phases?.[key]?.baseTools ?? []).map((tool) => ({
1605
+ name: tool.name,
1606
+ description: tool.description ?? "",
1607
+ hidden: isToolHidden(tool.name, filter),
1608
+ added: false
1609
+ }));
1610
+ const names = new Set(catalog.map((row) => row.name));
1611
+ const added = addOf(key).filter((name) => !names.has(name)).map((name) => ({
1612
+ name,
1613
+ description: "",
1614
+ hidden: false,
1615
+ added: true
1616
+ }));
1617
+ return [...catalog, ...added];
1618
+ };
1619
+ const toggleHide = (key, name, currentlyHidden) => {
1620
+ if (currentlyHidden) addToPhase(key, name, false);
1621
+ else {
1622
+ let exclude = excludeOf(key);
1623
+ let add = addOf(key);
1624
+ if (add.includes(name)) add = add.filter((x) => x !== name);
1625
+ else if (!exclude.includes(name)) exclude = [...exclude, name];
1626
+ writeLists(key, exclude, add);
1627
+ }
1628
+ setNotice(null);
1629
+ };
1630
+ const phaseNoun = (key) => key === "bootstrap" ? t("phaseStageGuide") : key === "compaction" ? t("phaseStageControlled") : t("phaseStageResident");
1631
+ const dropOnPart = (dest, name, from) => {
1632
+ if (!isInCatalog(dest, name) && !isInRegistry(name)) {
1633
+ setNotice({
1634
+ kind: "warn",
1635
+ text: t("toolNotInRegistry", { name })
1636
+ });
1637
+ return;
1638
+ }
1639
+ const copied = from.kind === "part" && from.key !== dest;
1640
+ const hidden = copied ? excludeOf(from.key).includes(name) : false;
1641
+ addToPhase(dest, name, hidden);
1642
+ setNotice({
1643
+ kind: "ok",
1644
+ text: copied ? t("toolCopied", {
1645
+ name,
1646
+ from: phaseNoun(from.key),
1647
+ to: phaseNoun(dest)
1648
+ }) : isInCatalog(dest, name) ? t("toolShown", {
1649
+ name,
1650
+ to: phaseNoun(dest)
1651
+ }) : t("toolAdded", {
1652
+ name,
1653
+ phase: phaseNoun(dest)
1654
+ })
829
1655
  });
830
1656
  };
831
- const setAll = (hideAll) => {
832
- scope.set("tools", {
833
- exclude: hideAll ? tools.map((tool) => tool.name) : [],
834
- include: []
1657
+ const dropOnAll = (name, from) => {
1658
+ if (from.kind !== "part") return;
1659
+ const key = from.key;
1660
+ let exclude = excludeOf(key);
1661
+ let add = addOf(key);
1662
+ if (add.includes(name)) add = add.filter((x) => x !== name);
1663
+ else if (!exclude.includes(name)) exclude = [...exclude, name];
1664
+ writeLists(key, exclude, add);
1665
+ setNotice({
1666
+ kind: "ok",
1667
+ text: t("toolHiddenIn", {
1668
+ name,
1669
+ to: phaseNoun(key)
1670
+ })
835
1671
  });
836
1672
  };
837
- return (0, react.createElement)("div", {}, [(0, react.createElement)("div", { style: s.bar }, [(0, react.createElement)("button", {
838
- style: s.mini,
839
- onClick: () => setAll(true)
840
- }, t("selectAll")), (0, react.createElement)("button", {
841
- style: s.mini,
842
- onClick: () => setAll(false)
843
- }, t("selectNone"))]), (0, react.createElement)("div", { style: s.list }, [tools.length === 0 ? (0, react.createElement)("div", { style: s.muted }, t("empty")) : null, tools.map((tool) => {
844
- const isHidden = hidden(tool.name);
1673
+ const visibleCount = (key) => {
1674
+ const rows = rowsOf(key);
1675
+ return `${rows.filter((row) => !row.hidden).length} / ${rows.length}`;
1676
+ };
1677
+ const partNoun = (key) => key === "bootstrap" ? t("toolsPartGuide") : key === "compaction" ? t("toolsPartControlled") : t("toolsPartResident");
1678
+ const startDrag = (e, from, name) => {
1679
+ setDragFrom(from);
1680
+ setDraggedName(name);
1681
+ e.dataTransfer.effectAllowed = "copy";
1682
+ try {
1683
+ e.dataTransfer.setData("text/plain", name);
1684
+ } catch {}
1685
+ };
1686
+ const zoneDragOver = (e, zone) => {
1687
+ if (!dragFrom || !draggedName) return;
1688
+ const same = zone === "all" ? dragFrom.kind === "all" : dragFrom.kind === "part" && dragFrom.key === zone.replace("part:", "");
1689
+ if (zone === "all" && dragFrom.kind === "all") {
1690
+ e.preventDefault();
1691
+ return;
1692
+ }
1693
+ if (same) return;
1694
+ e.preventDefault();
1695
+ e.dataTransfer.dropEffect = "copy";
1696
+ setDropHint(zone);
1697
+ };
1698
+ const zoneDrop = (e, zone) => {
1699
+ e.preventDefault();
1700
+ if (dragFrom && draggedName) {
1701
+ if (zone === "all") dropOnAll(draggedName, dragFrom);
1702
+ else {
1703
+ const dest = zone.replace("part:", "");
1704
+ if (PART_ORDER.includes(dest)) dropOnPart(dest, draggedName, dragFrom);
1705
+ }
1706
+ }
1707
+ setDragFrom(null);
1708
+ setDraggedName(null);
1709
+ setDropHint(null);
1710
+ };
1711
+ const endDrag = () => {
1712
+ setDragFrom(null);
1713
+ setDraggedName(null);
1714
+ setDropHint(null);
1715
+ };
1716
+ const zoneStyle = (zone) => dropHint === zone ? {
1717
+ outline: "2px dashed #7aa7ff",
1718
+ outlineOffset: 2
1719
+ } : void 0;
1720
+ const allTools = (inv?.tools ?? []).map((tool) => ({
1721
+ name: tool.name,
1722
+ description: typeof tool === "string" ? "" : tool.description ?? ""
1723
+ }));
1724
+ const renderPhasePart = (key) => {
1725
+ const rows = rowsOf(key);
1726
+ const zoneKey = `part:${key}`;
845
1727
  return (0, react.createElement)("div", {
846
- key: tool.name,
847
- style: s.row
848
- }, [(0, react.createElement)("label", { style: s.switchWrap }, [(0, react.createElement)("input", {
1728
+ key: zoneKey,
1729
+ style: s.injectBox,
1730
+ onDragOver: (e) => zoneDragOver(e, zoneKey),
1731
+ onDrop: (e) => zoneDrop(e, zoneKey),
1732
+ ...zoneStyle(zoneKey) ?? {}
1733
+ }, [(0, react.createElement)("div", { style: s.rowTitle }, [
1734
+ (0, react.createElement)("span", null, partNoun(key)),
1735
+ (0, react.createElement)("span", { style: s.orderTag }, `${t("phaseVisible")} ${visibleCount(key)}`),
1736
+ rows.length === 0 ? (0, react.createElement)("span", { style: s.muted }, t("dragHint")) : null
1737
+ ]), (0, react.createElement)("div", { style: s.toolWrap }, rows.map((row) => (0, react.createElement)("span", {
1738
+ key: row.name,
1739
+ style: {
1740
+ ...s.toolChip,
1741
+ cursor: "move",
1742
+ display: "inline-flex",
1743
+ alignItems: "center",
1744
+ gap: 4
1745
+ },
1746
+ title: row.description.slice(0, 120),
1747
+ draggable: true,
1748
+ onDragStart: (e) => startDrag(e, {
1749
+ kind: "part",
1750
+ key
1751
+ }, row.name),
1752
+ onDragEnd: endDrag
1753
+ }, [(0, react.createElement)("input", {
849
1754
  type: "checkbox",
850
- checked: isHidden,
851
- onChange: () => toggle(tool.name, isHidden)
852
- }), (0, react.createElement)("span", { style: isHidden ? s.badgeBlocked : s.badgeOk }, isHidden ? t("hiddenOn") : t("hiddenOff"))]), (0, react.createElement)("div", { style: s.rowBody }, [(0, react.createElement)("div", { style: s.rowTitle }, (0, react.createElement)("span", { style: s.code }, tool.name)), (0, react.createElement)("div", { style: s.preview }, String(tool.description ?? "").slice(0, 140))])]);
853
- })])]);
1755
+ checked: !row.hidden,
1756
+ onChange: () => toggleHide(key, row.name, row.hidden),
1757
+ style: {
1758
+ margin: 0,
1759
+ cursor: "pointer"
1760
+ }
1761
+ }), (0, react.createElement)("span", { style: row.hidden ? s.badgeBlocked : s.badgeOk }, row.name)])))]);
1762
+ };
1763
+ return (0, react.createElement)("div", {}, [
1764
+ (0, react.createElement)("div", { style: s.muted }, t("toolsFourHint")),
1765
+ notice ? (0, react.createElement)("div", { style: notice.kind === "ok" ? s.noticeOk : s.noticeWarn }, notice.text) : null,
1766
+ PART_ORDER.map(renderPhasePart),
1767
+ (0, react.createElement)("div", {
1768
+ style: s.injectBox,
1769
+ onDragOver: (e) => zoneDragOver(e, "all"),
1770
+ onDrop: (e) => zoneDrop(e, "all"),
1771
+ ...zoneStyle("all") ?? {}
1772
+ }, [
1773
+ (0, react.createElement)("div", { style: s.rowTitle }, [t("allToolsTitle"), (0, react.createElement)("span", { style: s.orderTag }, `${allTools.length}`)]),
1774
+ allTools.length === 0 ? (0, react.createElement)("div", { style: s.muted }, t("empty")) : null,
1775
+ (0, react.createElement)("div", { style: s.toolWrap }, allTools.map((tool) => (0, react.createElement)("span", {
1776
+ key: tool.name,
1777
+ style: {
1778
+ ...s.toolChip,
1779
+ cursor: "copy"
1780
+ },
1781
+ title: tool.description.slice(0, 120),
1782
+ draggable: true,
1783
+ onDragStart: (e) => startDrag(e, { kind: "all" }, tool.name),
1784
+ onDragEnd: endDrag
1785
+ }, tool.name)))
1786
+ ])
1787
+ ]);
1788
+ }
1789
+ //#endregion
1790
+ //#region src/client/preset-io.ts
1791
+ /** 页面是否运行在 Tauri(v1 标记或 v2 桥)webview 内。 */
1792
+ function isTauriEnv(win) {
1793
+ if (win === null || win === void 0) return false;
1794
+ const w = win;
1795
+ return w.__TAURI_INTERNALS__ !== void 0 || w.__TAURI__ !== void 0;
1796
+ }
1797
+ /** 取可用的 Tauri v2 invoke 桥;不可用时返回 null。 */
1798
+ function invokeOf(win) {
1799
+ if (!isTauriEnv(win)) return null;
1800
+ const internals = win.__TAURI_INTERNALS__;
1801
+ return internals && typeof internals.invoke === "function" ? internals.invoke : null;
1802
+ }
1803
+ const JSON_FILTERS = [{
1804
+ name: "JSON",
1805
+ extensions: ["json"]
1806
+ }];
1807
+ /**
1808
+ * 原生保存对话框 + 写文件。`cancelled` = 用户关闭了对话框(调用方绝不
1809
+ * 得再回退到下载);`unavailable` = 宿主无法提供 dialog/fs 插件(插件
1810
+ * 缺失或被 ACL 拦截),调用方应当回退。
1811
+ */
1812
+ async function tauriSaveText(invoke, defaultName, text) {
1813
+ try {
1814
+ const path = await invoke("plugin:dialog|save", {
1815
+ defaultPath: defaultName,
1816
+ filters: JSON_FILTERS
1817
+ });
1818
+ if (typeof path !== "string" || path === "") return { kind: "cancelled" };
1819
+ await invoke("plugin:fs|write_text_file", {
1820
+ path,
1821
+ contents: text
1822
+ });
1823
+ return { kind: "saved" };
1824
+ } catch {
1825
+ return { kind: "unavailable" };
1826
+ }
1827
+ }
1828
+ /** 原生打开对话框 + 读文件。`cancelled` = 用户关闭了对话框。 */
1829
+ async function tauriOpenText(invoke) {
1830
+ try {
1831
+ const picked = await invoke("plugin:dialog|open", {
1832
+ multiple: false,
1833
+ directory: false,
1834
+ filters: JSON_FILTERS
1835
+ });
1836
+ const path = Array.isArray(picked) ? picked[0] : picked;
1837
+ if (typeof path !== "string" || path === "") return { kind: "cancelled" };
1838
+ const text = await invoke("plugin:fs|read_text_file", { path });
1839
+ if (typeof text !== "string") return { kind: "unavailable" };
1840
+ return {
1841
+ kind: "text",
1842
+ text
1843
+ };
1844
+ } catch {
1845
+ return { kind: "unavailable" };
1846
+ }
1847
+ }
1848
+ /** Web 回退导出:Blob + object URL + <a download> + revoke。 */
1849
+ function webDownload(target, filename, text) {
1850
+ const blob = target.makeBlob(text);
1851
+ const url = target.objectUrl(blob);
1852
+ const anchor = target.makeAnchor();
1853
+ anchor.href = url;
1854
+ anchor.download = filename;
1855
+ anchor.click();
1856
+ target.revoke(url);
1857
+ }
1858
+ /** 把单个预设编码为导出文件的 JSON 格式(单对象格式)。`envBlocklist`
1859
+ * 是全局环境变量黑名单的随行快照:导入端按并集并入(见 PresetsTab)。 */
1860
+ function encodePresetExport(preset, envBlocklist) {
1861
+ return JSON.stringify({
1862
+ name: preset.name,
1863
+ data: preset.data,
1864
+ ...Array.isArray(envBlocklist) ? { envBlocklist } : {}
1865
+ }, null, 2);
1866
+ }
1867
+ /**
1868
+ * 解析导出的预设文件:单个 { name, data } 对象或对象数组。空内容 /
1869
+ * 非法 JSON 抛普通 Error,由调用方给出友好提示;条目级的过滤在
1870
+ * addImportedPresets 里进行。
1871
+ */
1872
+ function decodePresetExport(text) {
1873
+ const trimmed = String(text).trim();
1874
+ if (trimmed === "") throw new Error("EMPTY_EXPORT");
1875
+ return JSON.parse(trimmed);
1876
+ }
1877
+ function browserDownloadTarget() {
1878
+ const g = globalThis;
1879
+ const doc = g.document;
1880
+ const url = g.URL;
1881
+ return {
1882
+ makeAnchor: () => doc.createElement("a"),
1883
+ makeBlob: (text) => new Blob([text], { type: "application/json" }),
1884
+ objectUrl: (blob) => url.createObjectURL(blob),
1885
+ revoke: (u) => url.revokeObjectURL(u)
1886
+ };
1887
+ }
1888
+ /** 为当前 window 构建真实环境(在 Node 里调用也安全)。 */
1889
+ function makeIoEnv(win) {
1890
+ const invoke = invokeOf(win !== void 0 ? win : typeof window !== "undefined" ? window : void 0);
1891
+ const tauri = invoke !== null;
1892
+ return {
1893
+ tauri,
1894
+ saveText: (name, text) => tauri ? tauriSaveText(invoke, name, text) : Promise.resolve({ kind: "unavailable" }),
1895
+ openText: () => tauri ? tauriOpenText(invoke) : Promise.resolve({ kind: "unavailable" }),
1896
+ download: (name, text) => webDownload(browserDownloadTarget(), name, text)
1897
+ };
1898
+ }
1899
+ /**
1900
+ * 导出一个预设:宿主能提供原生对话框时走 tauri 保存(cancelled = 用户
1901
+ * 拒绝,绝不回退下载);否则走 Web 下载。
1902
+ */
1903
+ async function exportPresetFile(preset, io, envBlocklist) {
1904
+ const env = io ?? makeIoEnv();
1905
+ try {
1906
+ const text = encodePresetExport(preset, envBlocklist);
1907
+ const filename = presetExportFilename(preset.name);
1908
+ if (env.tauri) {
1909
+ const out = await env.saveText(filename, text);
1910
+ if (out.kind === "saved") return {
1911
+ ok: true,
1912
+ via: "tauri"
1913
+ };
1914
+ if (out.kind === "cancelled") return {
1915
+ ok: false,
1916
+ via: "tauri",
1917
+ cancelled: true
1918
+ };
1919
+ }
1920
+ env.download(filename, text);
1921
+ return {
1922
+ ok: true,
1923
+ via: "browser"
1924
+ };
1925
+ } catch (e) {
1926
+ return {
1927
+ ok: false,
1928
+ via: "browser",
1929
+ message: e instanceof Error ? e.message : String(e)
1930
+ };
1931
+ }
1932
+ }
1933
+ /**
1934
+ * 经原生 tauri 打开对话框导入一个预设;返回 `unavailable` 时由调用方
1935
+ * 点击自己的隐藏文件输入(Web 回退)。
1936
+ */
1937
+ async function importPresetFile(io) {
1938
+ const env = io ?? makeIoEnv();
1939
+ try {
1940
+ if (env.tauri) {
1941
+ const out = await env.openText();
1942
+ if (out.kind === "text") return {
1943
+ kind: "text",
1944
+ text: out.text,
1945
+ via: "tauri"
1946
+ };
1947
+ if (out.kind === "cancelled") return { kind: "cancelled" };
1948
+ }
1949
+ } catch {}
1950
+ return { kind: "unavailable" };
854
1951
  }
855
1952
  //#endregion
856
1953
  //#region src/client/PresetsTab.tsx
857
- /** Presets tab: save / apply / export / import complete customization snapshots. */
858
- function PresetsTab({ cfg, inv, scope, t }) {
1954
+ /** 配置 Tab:两种「预设」分开 ——
1955
+ * - 保存当前配置:本插件内的配置快照库(config.presets),可应用 / 导出 / 导入,
1956
+ * 不会变成可选的 agent 预设;
1957
+ * - 存为 agent 预设:整体 fork 当前编辑目标的预设目录,并把当前定制写进它的
1958
+ * 覆盖项,新预设随即出现在顶部的编辑目标选择器里。
1959
+ * 导入导出经 preset-io 双端适配:Tauri 2 桌面走原生对话框,Web 走
1960
+ * 下载 / 文件选择;成功 / 失败 / 取消都有面板内消息条提示。 */
1961
+ function PresetsTab({ cfg, inv, phases, t, writePatch, writeGlobal, saveAsPreset, forkSource, onReset, envBlocklist }) {
859
1962
  const presets = cfg.presets ?? [];
860
1963
  const [name, setName] = (0, react.useState)("");
1964
+ const [blockInput, setBlockInput] = (0, react.useState)("");
1965
+ const [agentName, setAgentName] = (0, react.useState)("");
1966
+ const [creating, setCreating] = (0, react.useState)(false);
1967
+ const [notice, setNotice] = (0, react.useState)(null);
861
1968
  const fileRef = (0, react.useRef)(null);
862
- const merged = mergeSections(inv, cfg, new Set(cfg.sections ?? []));
1969
+ const noticeTimer = (0, react.useRef)(null);
1970
+ (0, react.useEffect)(() => () => {
1971
+ if (noticeTimer.current !== null) clearTimeout(noticeTimer.current);
1972
+ }, []);
1973
+ const show = (kind, text) => {
1974
+ if (noticeTimer.current !== null) clearTimeout(noticeTimer.current);
1975
+ setNotice({
1976
+ kind,
1977
+ text
1978
+ });
1979
+ noticeTimer.current = setTimeout(() => setNotice(null), 4e3);
1980
+ };
1981
+ const blockedNames = new Set(cfg.sections ?? []);
1982
+ const assemblyNames = /* @__PURE__ */ new Set();
1983
+ for (const key of PART_ORDER) for (const sec of phases?.[key]?.baseSections ?? []) assemblyNames.add(sec.name);
1984
+ const mergedAll = mergeSections(inv, cfg, blockedNames);
1985
+ const merged = assemblyNames.size === 0 ? mergedAll : mergedAll.filter((sec) => sec.source === "custom" || assemblyNames.has(sec.name));
863
1986
  const currentNames = new Set(merged.map((sec) => sec.name));
864
1987
  const saveCurrent = () => {
865
1988
  const presetName = name.trim() || `${t("preset")} ${presets.length + 1}`;
866
1989
  const data = buildPresetData(cfg, merged);
867
- scope.set("presets", [...presets, {
1990
+ writeGlobal("presets", [...presets, {
868
1991
  id: genId(),
869
1992
  name: presetName,
870
1993
  data
@@ -872,41 +1995,84 @@ window.__ModuleLoader__.load({
872
1995
  setName("");
873
1996
  };
874
1997
  const applyPreset = (preset) => {
875
- const patch = applyPresetData(preset.data, cfg, currentNames);
876
- scope.set("inject", patch.inject);
877
- scope.set("replace", patch.replace);
878
- scope.set("sections", patch.sections);
879
- scope.set("tools", patch.tools);
880
- scope.set("activePreset", preset.id);
1998
+ writePatch(applyPresetData(preset.data, cfg, currentNames));
1999
+ writeGlobal("activePreset", preset.id);
881
2000
  };
882
2001
  const deletePreset = (id) => {
883
2002
  const next = removePreset(presets, id, cfg.activePreset);
884
- scope.set("presets", next.presets);
885
- if (next.activeId === void 0 && cfg.activePreset === id) scope.unset("activePreset");
886
- };
887
- const exportPreset = (preset) => {
888
- const blob = new Blob([JSON.stringify(serializePreset(preset), null, 2)], { type: "application/json" });
889
- const url = URL.createObjectURL(blob);
890
- const a = document.createElement("a");
891
- a.href = url;
892
- a.download = `${preset.name}.json`;
893
- a.click();
894
- URL.revokeObjectURL(url);
2003
+ writeGlobal("presets", next.presets);
2004
+ if (next.activeId === void 0 && cfg.activePreset === id) writeGlobal("activePreset", void 0);
2005
+ };
2006
+ const exportPreset = async (preset) => {
2007
+ try {
2008
+ const res = await exportPresetFile(preset, void 0, envBlocklist);
2009
+ if (res.ok) show("ok", t("exportOk"));
2010
+ else if (res.cancelled) show("ok", t("exportCancel"));
2011
+ else show("error", `${t("exportFail")}${res.message ? ": " + res.message : ""}`);
2012
+ } catch (e) {
2013
+ show("error", `${t("exportFail")}: ${e instanceof Error ? e.message : String(e)}`);
2014
+ }
2015
+ };
2016
+ const importParsed = (text) => {
2017
+ try {
2018
+ const parsed = decodePresetExport(text);
2019
+ const next = addImportedPresets(presets, parsed, genId);
2020
+ const added = next.length - presets.length;
2021
+ const fresh = (parsed !== null && typeof parsed === "object" && !Array.isArray(parsed) && Array.isArray(parsed.envBlocklist) ? (parsed.envBlocklist ?? []).filter((e) => typeof e === "string") : []).filter((e) => !envBlocklist.includes(e));
2022
+ if (fresh.length > 0) writeGlobal("envBlocklist", [...envBlocklist, ...fresh]);
2023
+ const mergedNote = fresh.length > 0 ? t("importBlockMerge", { count: fresh.length }) : "";
2024
+ if (added <= 0) show("ok", t("importNone") + mergedNote);
2025
+ else {
2026
+ writeGlobal("presets", next);
2027
+ show("ok", `${t("importOk")} (+${added})${mergedNote}`);
2028
+ }
2029
+ } catch (e) {
2030
+ show("error", `${t("importFail")}: ${e instanceof Error ? e.message : String(e)}`);
2031
+ }
2032
+ };
2033
+ const importPreset = async () => {
2034
+ try {
2035
+ const res = await importPresetFile();
2036
+ if (res.kind === "text") {
2037
+ importParsed(res.text);
2038
+ return;
2039
+ }
2040
+ if (res.kind === "cancelled") {
2041
+ show("ok", t("importCancel"));
2042
+ return;
2043
+ }
2044
+ fileRef.current?.click();
2045
+ } catch (e) {
2046
+ show("error", `${t("importFail")}: ${e instanceof Error ? e.message : String(e)}`);
2047
+ }
895
2048
  };
896
2049
  const onImportFile = (e) => {
897
2050
  const file = e.target.files?.[0];
2051
+ e.target.value = "";
898
2052
  if (!file) return;
899
2053
  const reader = new FileReader();
900
- reader.onload = () => {
901
- try {
902
- const parsed = JSON.parse(String(reader.result));
903
- scope.set("presets", addImportedPresets(presets, parsed, genId));
904
- } catch {}
905
- };
2054
+ reader.onload = () => importParsed(String(reader.result));
2055
+ reader.onerror = () => show("error", t("importFail"));
906
2056
  reader.readAsText(file);
907
- e.target.value = "";
2057
+ };
2058
+ const createAgentPreset = async () => {
2059
+ const trimmed = agentName.trim();
2060
+ if (trimmed.length === 0 || creating) return;
2061
+ setCreating(true);
2062
+ if (await saveAsPreset(trimmed)) setAgentName("");
2063
+ setCreating(false);
2064
+ };
2065
+ const removeBlockEntry = (entry) => {
2066
+ writeGlobal("envBlocklist", envBlocklist.filter((e) => e !== entry));
2067
+ };
2068
+ const addBlockEntry = () => {
2069
+ const entry = blockInput.trim();
2070
+ setBlockInput("");
2071
+ if (entry === "" || envBlocklist.includes(entry)) return;
2072
+ writeGlobal("envBlocklist", [...envBlocklist, entry]);
908
2073
  };
909
2074
  return (0, react.createElement)("div", { style: s.list }, [
2075
+ notice ? (0, react.createElement)("div", { style: notice.kind === "ok" ? s.noticeOk : s.error }, notice.text) : null,
910
2076
  (0, react.createElement)("div", { style: s.injectBox }, [(0, react.createElement)("div", { style: s.rowTitle }, t("savePreset")), (0, react.createElement)("div", { style: s.injectRow }, [(0, react.createElement)("input", {
911
2077
  style: {
912
2078
  ...s.input,
@@ -919,9 +2085,30 @@ window.__ModuleLoader__.load({
919
2085
  style: s.mini,
920
2086
  onClick: saveCurrent
921
2087
  }, t("save"))])]),
2088
+ (0, react.createElement)("div", { style: s.injectBox }, [
2089
+ (0, react.createElement)("div", { style: s.rowTitle }, t("saveAsPresetCard")),
2090
+ (0, react.createElement)("div", { style: s.muted }, t("saveAsPresetHint", { name: forkSource ?? t("forkSourceDefault") })),
2091
+ (0, react.createElement)("div", { style: s.injectRow }, [(0, react.createElement)("input", {
2092
+ style: {
2093
+ ...s.input,
2094
+ flex: 1
2095
+ },
2096
+ placeholder: t("agentPresetName"),
2097
+ value: agentName,
2098
+ onChange: (e) => setAgentName(e.target.value)
2099
+ }), (0, react.createElement)("button", {
2100
+ style: s.mini,
2101
+ disabled: creating || agentName.trim().length === 0,
2102
+ onClick: () => {
2103
+ createAgentPreset();
2104
+ }
2105
+ }, t("saveAsPreset"))])
2106
+ ]),
922
2107
  (0, react.createElement)("div", { style: s.injectBox }, [(0, react.createElement)("div", { style: s.rowTitle }, t("importPreset")), (0, react.createElement)("div", { style: s.injectRow }, [(0, react.createElement)("button", {
923
2108
  style: s.mini,
924
- onClick: () => fileRef.current?.click()
2109
+ onClick: () => {
2110
+ importPreset();
2111
+ }
925
2112
  }, t("import")), (0, react.createElement)("input", {
926
2113
  ref: fileRef,
927
2114
  type: "file",
@@ -929,6 +2116,79 @@ window.__ModuleLoader__.load({
929
2116
  style: { display: "none" },
930
2117
  onChange: onImportFile
931
2118
  })])]),
2119
+ (0, react.createElement)("div", { style: s.injectBox }, [
2120
+ (0, react.createElement)("div", { style: s.rowTitle }, t("forceTitle")),
2121
+ (0, react.createElement)("div", { style: s.muted }, t("forceHint")),
2122
+ (0, react.createElement)("div", { style: s.injectRow }, [(0, react.createElement)("label", { style: s.switchWrap }, [(0, react.createElement)("input", {
2123
+ type: "checkbox",
2124
+ checked: cfg.forceSections !== false,
2125
+ onChange: (e) => writeGlobal("forceSections", e.target.checked)
2126
+ }), (0, react.createElement)("span", { style: cfg.forceSections !== false ? s.badgeOk : s.badgeBlocked }, cfg.forceSections !== false ? t("forceOn") : t("forceOff"))])])
2127
+ ]),
2128
+ (0, react.createElement)("div", { style: s.injectBox }, [
2129
+ (0, react.createElement)("div", { style: s.rowTitle }, t("envBlockTitle")),
2130
+ (0, react.createElement)("div", { style: s.muted }, t("envBlockHint")),
2131
+ (0, react.createElement)("div", { style: {
2132
+ ...s.toolWrap,
2133
+ marginTop: 6
2134
+ } }, envBlocklist.map((entry) => (0, react.createElement)("span", {
2135
+ key: entry,
2136
+ style: {
2137
+ ...s.toolChip,
2138
+ display: "inline-flex",
2139
+ alignItems: "center",
2140
+ gap: 4
2141
+ }
2142
+ }, [entry, (0, react.createElement)("span", {
2143
+ style: { cursor: "pointer" },
2144
+ title: t("delete"),
2145
+ onClick: () => removeBlockEntry(entry)
2146
+ }, "×")]))),
2147
+ envBlocklist.length === 0 ? (0, react.createElement)("div", { style: s.muted }, t("envBlockEmpty")) : null,
2148
+ (0, react.createElement)("div", { style: {
2149
+ ...s.injectRow,
2150
+ marginTop: 6
2151
+ } }, [(0, react.createElement)("input", {
2152
+ style: {
2153
+ ...s.input,
2154
+ flex: 1
2155
+ },
2156
+ placeholder: t("envBlockAdd"),
2157
+ value: blockInput,
2158
+ onChange: (e) => setBlockInput(e.target.value)
2159
+ }), (0, react.createElement)("button", {
2160
+ style: s.mini,
2161
+ disabled: blockInput.trim() === "",
2162
+ onClick: addBlockEntry
2163
+ }, t("envBlockAddAction"))]),
2164
+ (0, react.createElement)("details", { style: { marginTop: 6 } }, [
2165
+ (0, react.createElement)("summary", { style: {
2166
+ ...s.muted,
2167
+ cursor: "pointer"
2168
+ } }, `${t("envVarsTitle")} (${inv?.variables?.length ?? 0})`),
2169
+ (0, react.createElement)("div", { style: {
2170
+ ...s.muted,
2171
+ marginTop: 4
2172
+ } }, t("envVarsHint")),
2173
+ (0, react.createElement)("div", { style: {
2174
+ ...s.toolWrap,
2175
+ marginTop: 4
2176
+ } }, (inv?.variables ?? []).map((name) => (0, react.createElement)("span", {
2177
+ key: name,
2178
+ style: s.toolChip
2179
+ }, `{{${name}}}`)))
2180
+ ])
2181
+ ]),
2182
+ (0, react.createElement)("div", { style: s.injectBox }, [
2183
+ (0, react.createElement)("div", { style: s.rowTitle }, t("resetTitle")),
2184
+ (0, react.createElement)("div", { style: s.muted }, t("resetHint")),
2185
+ (0, react.createElement)("div", { style: s.injectRow }, [(0, react.createElement)("button", {
2186
+ style: s.mini,
2187
+ onClick: () => {
2188
+ if (window.confirm(t("resetConfirm"))) onReset();
2189
+ }
2190
+ }, t("resetAction"))])
2191
+ ]),
932
2192
  presets.length === 0 ? (0, react.createElement)("div", { style: s.muted }, t("empty")) : null,
933
2193
  presets.map((preset) => {
934
2194
  const active = cfg.activePreset === preset.id;
@@ -943,7 +2203,9 @@ window.__ModuleLoader__.load({
943
2203
  }, t("apply")),
944
2204
  (0, react.createElement)("button", {
945
2205
  style: s.mini,
946
- onClick: () => exportPreset(preset)
2206
+ onClick: () => {
2207
+ exportPreset(preset);
2208
+ }
947
2209
  }, t("export")),
948
2210
  (0, react.createElement)("button", {
949
2211
  style: s.mini,
@@ -953,15 +2215,12 @@ window.__ModuleLoader__.load({
953
2215
  })
954
2216
  ]);
955
2217
  }
956
- function genId() {
957
- return "p_" + Date.now().toString(36) + Math.random().toString(36).slice(2, 7);
958
- }
959
2218
  //#endregion
960
2219
  //#region src/client/PreviewTools.tsx
961
- /** Tools preview: read-only whitelist-style list of the tools the current
962
- * preset will inject (the FINAL model-visible catalog after include/exclude).
963
- * A tool being listed means it is visible — there is no "blocked" state here.
964
- * This view never edits the blacklist/whitelist config. */
2220
+ /** 工具预览:当前定制(黑名单过滤之后)最终对模型可见的工具目录,
2221
+ * 只读、清单式呈现:列出即代表模型看得见 —— 这里没有「已屏蔽」状态。
2222
+ * 本视图绝不修改黑名单配置。 */
2223
+ /** 把字符串形态的条目补全为 { name, description: '' }。 */
965
2224
  function norm(tool) {
966
2225
  return typeof tool === "string" ? {
967
2226
  name: tool,
@@ -980,71 +2239,85 @@ window.__ModuleLoader__.load({
980
2239
  }
981
2240
  //#endregion
982
2241
  //#region src/client/PreviewTab.tsx
983
- /** Preview tab: two read-only sub-tabs — the FINAL assembled system prompt
984
- * after every plugin's filter, and the tools the current preset will inject
985
- * (whitelist-style, after include/exclude). Neither view edits config. */
986
- const PREVIEW_URL = "/api/prompt-customizer/preview";
987
- function PreviewTab({ scope, t, active, refreshId }) {
2242
+ /** 预览 Tab:两个只读子视图 —— 所有插件过滤后的最终装配系统提示词,
2243
+ * 以及当前定制(黑名单过滤之后)将注入的工具目录视图。
2244
+ * 两个视图都不修改配置。预览目标跟随面板顶部的编辑目标(`target`);
2245
+ * 数据直接来自 Panel 并行拉取的三阶段装配(`phases`)—— 与提示词/
2246
+ * 工具 Tab 同源(同一份 base + post 视图),杜绝三个视图数据不一致。
2247
+ * 阶段按钮恒为引导期 / 常驻期 / 压缩受控期三个(与另两个 Tab 同源同形)。 */
2248
+ function PreviewTab({ t, active, refreshId, target, version, phases }) {
988
2249
  const [sub, setSub] = (0, react.useState)("prompt");
989
- const [data, setData] = (0, react.useState)(null);
990
- const [error, setError] = (0, react.useState)(null);
991
- const inFlight = (0, react.useRef)(false);
992
- const load = () => {
993
- if (inFlight.current) return;
994
- inFlight.current = true;
995
- setData(null);
996
- fetch(`${PREVIEW_URL}?t=${Date.now()}`).then((r) => r.json()).then((body) => {
997
- if (body && body.ok === false) throw new Error(body.error ?? "preview failed");
998
- setData(body);
999
- setError(null);
1000
- }).catch((e) => setError(String(e instanceof Error ? e.message : e))).finally(() => {
1001
- inFlight.current = false;
1002
- });
1003
- };
1004
- (0, react.useEffect)(load, []);
1005
- (0, react.useEffect)(() => scope.subscribe(load), [scope]);
1006
- (0, react.useEffect)(() => {
1007
- if (active) load();
1008
- }, [active, refreshId]);
2250
+ const [phase, setPhase] = (0, react.useState)("bootstrap");
2251
+ const data = phases?.[phase] ?? null;
2252
+ const lossNote = data === null || data === void 0 ? null : data.takenOverBy !== void 0 ? t("sectionsTakenOver", { name: data.takenOverBy }) : data.lostSections !== void 0 ? t("sectionsLost", {
2253
+ emitted: data.lostSections.emitted,
2254
+ survived: data.lostSections.survived
2255
+ }) : null;
2256
+ const stageLabel = (p) => p === "bootstrap" ? t("phaseStageGuide") : p === "compaction" ? t("phaseStageControlled") : t("phaseStageResident");
1009
2257
  return (0, react.createElement)("div", { style: s.list }, [
1010
- (0, react.createElement)("div", { style: s.bar }, [(0, react.createElement)("button", {
1011
- style: sub === "prompt" ? s.tabActive : s.tab,
1012
- onClick: () => setSub("prompt")
1013
- }, t("previewPrompt")), (0, react.createElement)("button", {
1014
- style: sub === "tools" ? s.tabActive : s.tab,
1015
- onClick: () => setSub("tools")
1016
- }, t("previewTools"))]),
1017
- error ? (0, react.createElement)("div", { style: s.error }, String(error)) : null,
1018
- data === null && !error ? (0, react.createElement)("div", { style: s.muted }, t("loading")) : null,
1019
- sub === "prompt" ? data ? [(0, react.createElement)("div", { style: s.rowTitle }, [(0, react.createElement)("span", { style: s.muted }, t("previewHint")), (0, react.createElement)("span", { style: s.orderTag }, `${data.sections.length} ${t("previewSections")}`)]), (0, react.createElement)("pre", { style: s.previewText }, data.text || t("empty"))] : null : data ? (0, react.createElement)(PreviewTools, {
2258
+ (0, react.createElement)("div", { style: s.bar }, [
2259
+ (0, react.createElement)("button", {
2260
+ style: sub === "prompt" ? s.tabActive : s.tab,
2261
+ onClick: () => setSub("prompt")
2262
+ }, t("previewPrompt")),
2263
+ (0, react.createElement)("button", {
2264
+ style: sub === "tools" ? s.tabActive : s.tab,
2265
+ onClick: () => setSub("tools")
2266
+ }, t("previewTools")),
2267
+ (0, react.createElement)("div", { style: {
2268
+ marginLeft: "auto",
2269
+ display: "flex",
2270
+ gap: 4
2271
+ } }, PART_ORDER.map((key) => (0, react.createElement)("button", {
2272
+ key,
2273
+ style: phase === key ? s.tabActive : s.tab,
2274
+ onClick: () => setPhase(key)
2275
+ }, stageLabel(key))))
2276
+ ]),
2277
+ lossNote !== null ? (0, react.createElement)("div", { style: s.noticeWarn }, lossNote) : null,
2278
+ data !== null && data.scopeResolved === false ? (0, react.createElement)("div", { style: s.noticeWarn }, t("scopeFallback")) : null,
2279
+ data !== null && data.degraded === true ? (0, react.createElement)("div", { style: s.noticeWarn }, t("previewDegraded")) : null,
2280
+ phases === null ? (0, react.createElement)("div", { style: s.muted }, t("loading")) : null,
2281
+ phases !== null && data === null ? (0, react.createElement)("div", { style: s.error }, t("previewFail")) : null,
2282
+ sub === "prompt" ? data ? [(0, react.createElement)("div", { style: s.rowTitle }, [(0, react.createElement)("span", { style: s.muted }, t("previewHint")), (0, react.createElement)("span", { style: s.orderTag }, `${data.sections.length} ${t("previewSections")}`)]), (0, react.createElement)("pre", { style: s.previewText }, data.text || t("empty"))] : null : data ? [(0, react.createElement)("div", { style: s.rowTitle }, [(0, react.createElement)("span", { style: s.muted }, t("previewToolsHint")), (0, react.createElement)("span", { style: s.orderTag }, `${data.tools.length} / ${data.registryTotal ?? "?"} ${t("previewToolsCount")}`)]), (0, react.createElement)(PreviewTools, {
1020
2283
  tools: data.tools,
1021
2284
  t
1022
- }) : null
2285
+ })] : null
1023
2286
  ]);
1024
2287
  }
1025
2288
  //#endregion
1026
2289
  //#region src/client/index.ts
1027
2290
  /**
1028
- * dsh-prompt-customizer — browser half (TypeScript source).
2291
+ * dsh-prompt-customizer — 浏览器端(TypeScript 源码)。
1029
2292
  *
1030
- * Registers a "提示词定制" settings section (sidebar entry) and a plugin
1031
- * settings card. The panel fetches the effective section / tool inventory
1032
- * from the host `/api/prompt-customizer/inventory` and lets the user block,
1033
- * replace, inject prompt sections and hide tools. All writes go through the
1034
- * bound settings scope (`prompt-customizer` namespace) and apply live.
2293
+ * 注册一个「提示词定制」设置分区(侧边栏入口)及插件设置卡片。面板从宿主
2294
+ * 的 `/api/prompt-customizer/inventory` 拉取当前生效的段 / 工具清单,让用户
2295
+ * 屏蔽、替换、注入提示词段并隐藏工具。所有写入都走绑定的设置作用域
2296
+ * (`prompt-customizer` 命名空间),实时生效。
1035
2297
  *
1036
- * Built by tsdown into the __ModuleLoader__ factory bundle at client/client.js;
1037
- * the only external is the loader module table's react entry.
2298
+ * 由 tsdown 打包为 client/client.js(__ModuleLoader__ factory bundle);
2299
+ * 唯一的外部依赖是 loader 模块表中的 react 入口。
1038
2300
  */
1039
2301
  const NS = "prompt-customizer";
1040
2302
  const INVENTORY_URL = "/api/prompt-customizer/inventory";
2303
+ const CONFIG_SET_URL = "/api/prompt-customizer/config/set";
2304
+ const CONFIG_UNSET_URL = "/api/prompt-customizer/config/unset";
2305
+ const CONFIG_APPLY_URL = "/api/prompt-customizer/config/apply";
2306
+ const CONFIG_RESET_URL = "/api/prompt-customizer/config/reset";
2307
+ const PRESETS_CREATE_URL = "/api/prompt-customizer/presets";
2308
+ const PREVIEW_URL = "/api/prompt-customizer/preview";
2309
+ /** 三套名义装配的共享布局:顺序固定,refresh 按此并行拉取。 */
2310
+ const VIEW_KEYS = [
2311
+ "bootstrap",
2312
+ "compaction",
2313
+ "active"
2314
+ ];
1041
2315
  const name = "prompt-customizer";
1042
2316
  const inject = ["slots", "locale"];
1043
2317
  function apply(ctx) {
1044
2318
  ctx.effect(() => ctx.locale.register(NS, DICT), "prompt-customizer: locale");
1045
2319
  const t = ctx.locale.bind(NS);
1046
- ctx.inject(["settingsScope"], (scoped) => {
1047
- const scope = scoped.settingsScope.bind({ namespace: NS });
2320
+ ctx.inject(["slots"], (scoped) => {
1048
2321
  scoped.slots.inject("settings.section", () => scoped.slots.register({
1049
2322
  name: "settings.section",
1050
2323
  id: "prompt-customizer",
@@ -1052,81 +2325,275 @@ window.__ModuleLoader__.load({
1052
2325
  label: () => t("nav"),
1053
2326
  locale: NS,
1054
2327
  inject: () => ({ t })
1055
- }, () => (0, react.createElement)(Panel, {
1056
- scope,
1057
- t
1058
- })));
2328
+ }, () => (0, react.createElement)(Panel, { t })));
1059
2329
  });
1060
2330
  }
1061
- function Panel({ scope, t }) {
1062
- const [snap, setSnap] = (0, react.useState)(() => scope.getSnapshot());
2331
+ function Panel({ t }) {
2332
+ const [cfg, setCfg] = (0, react.useState)(null);
1063
2333
  const [inv, setInv] = (0, react.useState)(null);
2334
+ const [phases, setPhases] = (0, react.useState)(null);
2335
+ const [agentPresets, setAgentPresets] = (0, react.useState)([]);
1064
2336
  const [tab, setTab] = (0, react.useState)("sections");
1065
2337
  const [error, setError] = (0, react.useState)(null);
1066
2338
  const [refreshId, setRefreshId] = (0, react.useState)(0);
1067
- (0, react.useEffect)(() => scope.subscribe(() => setSnap(scope.getSnapshot())), [scope]);
2339
+ const [target, setTarget] = (0, react.useState)(void 0);
2340
+ const [version, setVersion] = (0, react.useState)(0);
2341
+ const [draft, setDraft] = (0, react.useState)(null);
2342
+ const [saving, setSaving] = (0, react.useState)(false);
2343
+ const [flash, setFlash] = (0, react.useState)(null);
2344
+ const [flashKind, setFlashKind] = (0, react.useState)("ok");
2345
+ const flashTimer = (0, react.useRef)(null);
2346
+ const load = () => {
2347
+ fetch(`/api/prompt-customizer/config?t=${Date.now()}`).then((r) => r.json()).then((body) => {
2348
+ if (body?.ok !== true) throw new Error(body?.error ?? "config failed");
2349
+ setCfg(body.config);
2350
+ setError(null);
2351
+ }).catch((e) => setError(String(e instanceof Error ? e.message : e)));
2352
+ };
2353
+ (0, react.useEffect)(load, []);
1068
2354
  const refresh = () => {
1069
- fetch(INVENTORY_URL).then((r) => r.json()).then((data) => {
1070
- setInv(data);
2355
+ const qs = target ? `?scope=${encodeURIComponent(target)}` : "";
2356
+ const params = (phase) => `${qs}${qs ? "&" : "?"}phase=${phase}&t=${Date.now()}`;
2357
+ const grab = (phase) => fetch(PREVIEW_URL + params(phase)).then((r) => r.json()).then((body) => body?.ok === false ? null : body).catch(() => null);
2358
+ Promise.all([...VIEW_KEYS.map(grab), fetch(INVENTORY_URL).then((r) => r.json())]).then(([boot, comp, act, inventoryData]) => {
2359
+ setPhases({
2360
+ bootstrap: boot,
2361
+ compaction: comp,
2362
+ active: act
2363
+ });
2364
+ setInv(inventoryData);
1071
2365
  setError(null);
1072
2366
  setRefreshId((n) => n + 1);
1073
2367
  }).catch((e) => setError(String(e instanceof Error ? e.message : e)));
1074
2368
  };
1075
- (0, react.useEffect)(refresh, []);
1076
- if (snap.status !== "ready" && snap.value === void 0) return (0, react.createElement)("div", { style: s.muted }, t("loading"));
1077
- const cfg = snap.value && typeof snap.value === "object" ? snap.value : {
1078
- sections: [],
1079
- replace: {},
1080
- inject: [],
1081
- tools: {
1082
- exclude: [],
1083
- include: []
2369
+ (0, react.useEffect)(refresh, [target, version]);
2370
+ const fetchPresets = () => {
2371
+ fetch(`/api/prompt-customizer/agent-presets?t=${Date.now()}`).then((r) => r.json()).then((body) => setAgentPresets(Array.isArray(body?.presets) ? body.presets : [])).catch(() => setAgentPresets([]));
2372
+ };
2373
+ (0, react.useEffect)(() => {
2374
+ fetchPresets();
2375
+ }, []);
2376
+ if (cfg === null) return (0, react.createElement)("div", { style: s.muted }, t("loading"));
2377
+ const showFlash = (text, kind = "ok") => {
2378
+ if (flashTimer.current !== null) clearTimeout(flashTimer.current);
2379
+ setFlash(text);
2380
+ setFlashKind(kind);
2381
+ flashTimer.current = setTimeout(() => setFlash(null), 3200);
2382
+ };
2383
+ const base = editView(cfg, target);
2384
+ const view = draft ? {
2385
+ ...base,
2386
+ sections: draft.sections ?? base.sections,
2387
+ sectionsBootstrap: draft.sectionsBootstrap ?? base.sectionsBootstrap,
2388
+ sectionsCompaction: draft.sectionsCompaction ?? base.sectionsCompaction,
2389
+ replace: draft.replace ?? base.replace,
2390
+ inject: draft.inject ?? base.inject,
2391
+ tools: draft.tools ?? base.tools
2392
+ } : base;
2393
+ const writeField = (field, value) => {
2394
+ fetch(value === void 0 ? CONFIG_UNSET_URL : CONFIG_SET_URL, {
2395
+ method: "POST",
2396
+ headers: { "content-type": "application/json" },
2397
+ body: JSON.stringify({
2398
+ field,
2399
+ value
2400
+ })
2401
+ }).then((r) => r.json()).then((body) => {
2402
+ if (body?.ok !== true) throw new Error(body?.error ?? "write failed");
2403
+ setCfg(body.config);
2404
+ setError(null);
2405
+ setVersion((n) => n + 1);
2406
+ }).catch((e) => setError(String(e instanceof Error ? e.message : e)));
2407
+ };
2408
+ const edit = (field, value) => {
2409
+ setDraft((d) => ({
2410
+ ...d ?? { dirty: false },
2411
+ [field]: value,
2412
+ dirty: true
2413
+ }));
2414
+ };
2415
+ const save = () => {
2416
+ if (draft === null || saving) return;
2417
+ const EDITED_FIELDS = [
2418
+ "sections",
2419
+ "sectionsBootstrap",
2420
+ "sectionsCompaction",
2421
+ "replace",
2422
+ "inject",
2423
+ "tools"
2424
+ ];
2425
+ const patch = {};
2426
+ for (const field of EDITED_FIELDS) if (Object.hasOwn(draft, field)) patch[field] = draft[field];
2427
+ setSaving(true);
2428
+ fetch(CONFIG_APPLY_URL, {
2429
+ method: "POST",
2430
+ headers: { "content-type": "application/json" },
2431
+ body: JSON.stringify({
2432
+ target,
2433
+ patch
2434
+ })
2435
+ }).then((r) => r.json()).then((body) => {
2436
+ if (body?.ok !== true) throw new Error(body?.error ?? "save failed");
2437
+ setCfg(body.config);
2438
+ setDraft(null);
2439
+ setError(null);
2440
+ setVersion((n) => n + 1);
2441
+ showFlash(t("saveOk"));
2442
+ }).catch((e) => setError(`${t("saveFail")}: ${e instanceof Error ? e.message : String(e)}`)).finally(() => setSaving(false));
2443
+ };
2444
+ const writePatch = (patch) => {
2445
+ fetch(CONFIG_APPLY_URL, {
2446
+ method: "POST",
2447
+ headers: { "content-type": "application/json" },
2448
+ body: JSON.stringify({
2449
+ target,
2450
+ patch
2451
+ })
2452
+ }).then((r) => r.json()).then((body) => {
2453
+ if (body?.ok !== true) throw new Error(body?.error ?? "apply failed");
2454
+ setCfg(body.config);
2455
+ setError(null);
2456
+ setVersion((n) => n + 1);
2457
+ }).catch((e) => setError(String(e instanceof Error ? e.message : e)));
2458
+ };
2459
+ const writeGlobal = writeField;
2460
+ const writeGlobalField = writeField;
2461
+ const resetAll = () => {
2462
+ fetch(CONFIG_RESET_URL, {
2463
+ method: "POST",
2464
+ headers: { "content-type": "application/json" }
2465
+ }).then((r) => r.json()).then((body) => {
2466
+ if (body?.ok !== true) throw new Error(body?.error ?? "reset failed");
2467
+ setCfg(body.config);
2468
+ setDraft(null);
2469
+ setError(null);
2470
+ setVersion((n) => n + 1);
2471
+ showFlash(t("resetOk"));
2472
+ }).catch((e) => setError(`${t("resetFail")}: ${e instanceof Error ? e.message : String(e)}`));
2473
+ };
2474
+ const switchTab = (next) => {
2475
+ if ((tab === "sections" || tab === "tools") && (next === "presets" || next === "preview")) {
2476
+ if (draft?.dirty && !window.confirm(t("discardConfirm"))) return;
2477
+ setDraft(null);
1084
2478
  }
2479
+ setTab(next);
2480
+ };
2481
+ const switchTarget = (next) => {
2482
+ if (draft?.dirty && !window.confirm(t("discardConfirm"))) return;
2483
+ setDraft(null);
2484
+ setTarget(next);
2485
+ };
2486
+ const saveAsPreset = (presetName) => {
2487
+ const name = presetName.trim();
2488
+ if (name.length === 0) return Promise.resolve(false);
2489
+ return fetch(PRESETS_CREATE_URL, {
2490
+ method: "POST",
2491
+ headers: { "content-type": "application/json" },
2492
+ body: JSON.stringify({
2493
+ name,
2494
+ from: target,
2495
+ config: {
2496
+ sections: view.sections ?? [],
2497
+ sectionsBootstrap: view.sectionsBootstrap ?? [],
2498
+ sectionsCompaction: view.sectionsCompaction ?? [],
2499
+ replace: view.replace ?? {},
2500
+ inject: view.inject ?? [],
2501
+ tools: view.tools ?? {}
2502
+ }
2503
+ })
2504
+ }).then((r) => r.json()).then((body) => {
2505
+ if (body?.ok !== true) throw new Error(body?.error ?? t("saveAsPresetFail"));
2506
+ load();
2507
+ fetchPresets();
2508
+ showFlash(t("saveAsPresetOk"), "ok");
2509
+ return true;
2510
+ }).catch((e) => {
2511
+ showFlash(`${t("saveAsPresetFail")}:${String(e instanceof Error ? e.message : e)}`, "err");
2512
+ return false;
2513
+ });
1085
2514
  };
1086
2515
  return (0, react.createElement)("div", { style: s.root }, [
1087
2516
  (0, react.createElement)("div", { style: s.bar }, [
1088
2517
  (0, react.createElement)("button", {
1089
2518
  style: tab === "sections" ? s.tabActive : s.tab,
1090
- onClick: () => setTab("sections")
2519
+ onClick: () => switchTab("sections")
1091
2520
  }, t("tabsSections")),
1092
2521
  (0, react.createElement)("button", {
1093
2522
  style: tab === "tools" ? s.tabActive : s.tab,
1094
- onClick: () => setTab("tools")
2523
+ onClick: () => switchTab("tools")
1095
2524
  }, t("tabsTools")),
1096
2525
  (0, react.createElement)("button", {
1097
2526
  style: tab === "presets" ? s.tabActive : s.tab,
1098
- onClick: () => setTab("presets")
2527
+ onClick: () => switchTab("presets")
1099
2528
  }, t("tabsPresets")),
1100
2529
  (0, react.createElement)("button", {
1101
2530
  style: tab === "preview" ? s.tabActive : s.tab,
1102
- onClick: () => setTab("preview")
2531
+ onClick: () => switchTab("preview")
1103
2532
  }, t("tabsPreview")),
2533
+ (0, react.createElement)("select", {
2534
+ style: {
2535
+ ...s.input,
2536
+ marginLeft: 6
2537
+ },
2538
+ value: target ?? "",
2539
+ onChange: (e) => switchTarget(e.target.value || void 0),
2540
+ title: t("targetHint")
2541
+ }, [(0, react.createElement)("option", {
2542
+ value: "",
2543
+ style: s.option
2544
+ }, t("targetGlobal")), ...agentPresets.map((p) => (0, react.createElement)("option", {
2545
+ key: p.id,
2546
+ value: p.id,
2547
+ style: s.option
2548
+ }, `${p.name}${p.broken ? ` (${t("broken")})` : ""}`))]),
2549
+ (0, react.createElement)("button", {
2550
+ style: draft?.dirty ? s.saveBtnDirty : s.saveBtn,
2551
+ disabled: !draft?.dirty || saving,
2552
+ onClick: save
2553
+ }, t("save")),
1104
2554
  (0, react.createElement)("button", {
1105
2555
  style: s.refresh,
1106
2556
  onClick: refresh
1107
2557
  }, t("refresh"))
1108
2558
  ]),
1109
2559
  error ? (0, react.createElement)("div", { style: s.error }, String(error)) : null,
2560
+ flash ? (0, react.createElement)("div", { style: flashKind === "err" ? s.error : s.noticeOk }, flash) : null,
2561
+ target && agentPresets.find((p) => p.id === target)?.broken ? (0, react.createElement)("div", { style: s.error }, t("brokenPreset")) : null,
2562
+ inv?.scopeResolved === false ? (0, react.createElement)("div", { style: s.noticeWarn }, t("scopeFallback")) : null,
1110
2563
  tab === "sections" ? (0, react.createElement)(SectionsTab, {
1111
- cfg,
2564
+ cfg: view,
1112
2565
  inv,
1113
- scope,
1114
- t
2566
+ phases,
2567
+ target,
2568
+ globalSections: cfg.sections,
2569
+ ownedSections: target ? cfg.overrides?.[target]?.sections : void 0,
2570
+ t,
2571
+ write: edit,
2572
+ writeGlobalField
1115
2573
  }) : tab === "tools" ? (0, react.createElement)(ToolsTab, {
1116
- cfg,
2574
+ cfg: view,
1117
2575
  inv,
1118
- scope,
1119
- t
2576
+ phases,
2577
+ t,
2578
+ write: edit
1120
2579
  }) : tab === "presets" ? (0, react.createElement)(PresetsTab, {
1121
- cfg,
2580
+ cfg: view,
1122
2581
  inv,
1123
- scope,
1124
- t
2582
+ phases,
2583
+ t,
2584
+ writePatch,
2585
+ writeGlobal,
2586
+ saveAsPreset,
2587
+ forkSource: target ? agentPresets.find((p) => p.id === target)?.name ?? target : void 0,
2588
+ onReset: resetAll,
2589
+ envBlocklist: cfg.envBlocklist ?? []
1125
2590
  }) : (0, react.createElement)(PreviewTab, {
1126
- scope,
1127
2591
  t,
1128
2592
  active: tab === "preview",
1129
- refreshId
2593
+ refreshId,
2594
+ target,
2595
+ version,
2596
+ phases
1130
2597
  })
1131
2598
  ]);
1132
2599
  }