@jayyuen66/dsh-dir-prep-organize 0.1.6 → 0.1.8

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.js CHANGED
@@ -7,8 +7,9 @@ window.__ModuleLoader__.load({
7
7
  let exports = module.exports;
8
8
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
9
9
  let react = require("react");
10
+ let zod = require("zod");
10
11
  // node_modules/@jayyuen66/dsh-plugin-shared/dist/record.js
11
- function e(e) {
12
+ function e$1(e) {
12
13
  return typeof e == `object` && !!e && !Array.isArray(e);
13
14
  }
14
15
  // src/templates.ts
@@ -17,18 +18,35 @@ function e(e) {
17
18
  * 为必填(空串表示未设置),保证下拉与设置卡无缺字段分支。 */
18
19
  /** 视觉标记进入下拉前缀的最大字符数。 */
19
20
  const EMOJI_MAX_LENGTH = 12;
21
+ /** 按 Unicode 码点截断:`String#slice` 数的是 UTF-16 码元,会把一个 emoji(代理对)或
22
+ * 组合字符劈成半个,落进模板后显示成空白方块。两个截断点(frontmatter 与设置卡草稿)
23
+ * 共用这一份实现,scripts/gen-defaults-lib.mjs 有同源镜像。 */
24
+ function truncateCodePoints(value, max) {
25
+ const points = Array.from(value);
26
+ return points.length > max ? points.slice(0, max).join("") : value;
27
+ }
28
+ /** id 缺失或与已收集 id 撞名 → 确定性补 `tpl-<index>`(仍撞则追加 `-<index>` 直到唯一)。
29
+ * 只负责取名,不登记 `seen`——登记由调用方在装配条目时按装配顺序做。 */
30
+ function uniqueEntryId(candidate, index, seen) {
31
+ if (candidate !== "" && !seen.has(candidate)) return candidate;
32
+ let id = `tpl-${index}`;
33
+ while (seen.has(id)) id = `${id}-${index}`;
34
+ return id;
35
+ }
20
36
  /**
21
37
  * 导入条目并入现有草稿:与既有 id 碰撞时确定性改写(追加 `-i` 直到唯一)。
22
- * 返回新数组(不改输入),保证 pre-save 阶段 React key 唯一(保存前的 id 去重,
23
- * sanitizeTemplateList 的确定性补 id 只兜底缺失/空,不负责碰撞改写)。
38
+ * 返回新数组(不改输入),保证 pre-save 阶段 React key 唯一。sanitizeTemplateList 对**存量
39
+ * 快照**同样按序号补 id(缺失/空/撞名三档都管),这边要额外做的是避开草稿里已有的 id
40
+ * ——两个入口各管一段,不靠对方兜底。
24
41
  */
25
42
  function mergeImportedTemplates(existing, incoming) {
26
43
  const ids = new Set(existing.map(({ id }) => id));
27
44
  const out = [...existing];
28
45
  for (const { id: baseId, ...rest } of incoming) {
29
- let id = baseId;
30
- if (ids.has(id)) {
31
- id = `${baseId}-i`;
46
+ let id = baseId.trim();
47
+ if (id === "") id = uniqueEntryId("", out.length, ids);
48
+ else if (ids.has(id)) {
49
+ id = `${id}-i`;
32
50
  while (ids.has(id)) id = `${id}i`;
33
51
  }
34
52
  ids.add(id);
@@ -39,31 +57,15 @@ function mergeImportedTemplates(existing, incoming) {
39
57
  }
40
58
  return out;
41
59
  }
42
- /** 任意来源(settings 快照 / 设置卡草稿)→ 合法模板列表(纯函数,测试锁死)。
43
- *
44
- * - 非数组输入 → [](调用方自行决定是否回落 DEFAULT_TEMPLATES);
45
- * - 剔除非对象条目与 name/text trim 后为空的条目;
46
- * - name/text/description/group 一律 trim;emoji trim 后截断至 12 字符;
47
- * - id 缺失或与已收集 id 撞名 → 确定性补 `tpl-<index>`(仍撞则追加
48
- * `-<index>` 直到唯一)——同输入同输出,可测试;
49
- * - 绝不修改输入(深比较测试锁死)。 */
50
60
  /** 字段 → trim 后的 string;非字符串一律 ""。 */
51
61
  function trimField(value) {
52
62
  return typeof value === "string" ? value.trim() : "";
53
63
  }
54
- /** id 缺失或与已收集 id 撞名 → 确定性补 `tpl-<index>`(仍撞则追加 `-<index>` 直到唯一)。
55
- * 只负责取名,不登记 `seen`——登记由调用方在装配条目时按装配顺序做。 */
56
- function uniqueEntryId(candidate, index, seen) {
57
- if (candidate !== "" && !seen.has(candidate)) return candidate;
58
- let id = `tpl-${index}`;
59
- while (seen.has(id)) id = `${id}-${index}`;
60
- return id;
61
- }
62
64
  /** 单条归一化:剔除坏条目/空 name|text;id 缺失或撞名 → 确定性补 tpl-<index>,
63
65
  * 返回 undefined 表示该条应被剔除。 */
64
66
  function normalizeEntry(item, index, seen) {
65
67
  let result;
66
- if (e(item)) {
68
+ if (e$1(item)) {
67
69
  const { id, name, description, text, group, emoji } = item;
68
70
  const nextName = trimField(name);
69
71
  const nextText = trimField(text);
@@ -76,12 +78,19 @@ function normalizeEntry(item, index, seen) {
76
78
  description: trimField(description),
77
79
  text: nextText,
78
80
  group: trimField(group),
79
- emoji: trimField(emoji).slice(0, EMOJI_MAX_LENGTH)
81
+ emoji: truncateCodePoints(trimField(emoji), EMOJI_MAX_LENGTH)
80
82
  };
81
83
  }
82
84
  }
83
85
  return result;
84
86
  }
87
+ /** 任意来源(settings 快照 / 设置卡草稿)→ 合法模板列表(纯函数,测试锁死)。
88
+ *
89
+ * - 非数组输入 → [](调用方自行决定是否回落 DEFAULT_TEMPLATES);
90
+ * - 剔除非对象条目与 name/text trim 后为空的条目;
91
+ * - name/text/description/group 一律 trim;emoji trim 后按码点截断至 12 个字符;
92
+ * - id 缺失与已收集 id 撞名都由 uniqueEntryId 按序号补成唯一(同输入同输出,可测试);
93
+ * - 绝不修改输入(深比较测试锁死)。 */
85
94
  function sanitizeTemplateList(raw) {
86
95
  if (!Array.isArray(raw)) return [];
87
96
  const seen = /* @__PURE__ */ new Set();
@@ -98,12 +107,22 @@ function sanitizeTemplateList(raw) {
98
107
  * - 非数组 → [](未设置 = 一条都不登记,不是"全放行");
99
108
  * - 非字符串 / trim 后为空 → 丢弃(空串在 host 侧 path.resolve 会落到进程 cwd,
100
109
  * 绝不能让它变成一个隐式允许根);
110
+ * - **非绝对路径 → 丢弃**:契约是「额外允许的绝对目录」,相对项会被 host 按它自己的
111
+ * 进程 cwd 解析,等于登记了一条用户没写过、界面上也看不出指向哪里的允许根;
101
112
  * - 去重(同一目录登记两次没有额外语义,界面上也不该出现两行)。 */
113
+ /** 绝对路径形状(与 host 侧 path.isAbsolute 同口径的宽松版:POSIX 根、win32 盘符、UNC)。
114
+ * client 半跑在浏览器里,没有 node:path 可用,故按形状判。 */
115
+ const BACKSLASH = String.fromCodePoint(92);
116
+ const WIN_DRIVE_LETTER = /^[A-Za-z]:$/u;
117
+ function isAbsolutePath(value) {
118
+ const winDrive = WIN_DRIVE_LETTER.test(value.slice(0, 2)) && (value[2] === "/" || value[2] === BACKSLASH);
119
+ return value.startsWith("/") || winDrive || value.startsWith(BACKSLASH + BACKSLASH);
120
+ }
102
121
  function sanitizeAllowRoots(raw) {
103
122
  const out = [];
104
123
  if (Array.isArray(raw)) for (const item of raw) {
105
124
  const root = typeof item === "string" ? item.trim() : "";
106
- if (root !== "" && !out.includes(root)) out.push(root);
125
+ if (root !== "" && isAbsolutePath(root) && !out.includes(root)) out.push(root);
107
126
  }
108
127
  return out;
109
128
  }
@@ -118,6 +137,10 @@ const MAX_TIMER_MS = 2147483647;
118
137
  const ORGANIZE_TIMEOUT_FALLBACK_MS = 12e4;
119
138
  /** 客户端比 host 多等的余量:host 先超时,客户端留一点时间把它的回执读回来。 */
120
139
  const ORGANIZE_TIMEOUT_SLACK_MS = 5e3;
140
+ /** 配置投影值是否可当作毫秒数用(有限且 > 0;两处取表共用同一判据)。 */
141
+ function isUsableTimeoutMs(value) {
142
+ return typeof value === "number" && Number.isFinite(value) && value > 0;
143
+ }
121
144
  /**
122
145
  * `organizeTimeoutMs` 的前端取表。
123
146
  *
@@ -129,7 +152,7 @@ const ORGANIZE_TIMEOUT_SLACK_MS = 5e3;
129
152
  */
130
153
  function rawOrganizeTimeoutMsOf(value) {
131
154
  const raw = value["organizeTimeoutMs"];
132
- return typeof raw === "number" && Number.isFinite(raw) && raw > 0 ? Math.min(Math.max(Math.trunc(raw), 1), MAX_TIMER_MS) : void 0;
155
+ return isUsableTimeoutMs(raw) ? Math.min(Math.max(Math.trunc(raw), 1), MAX_TIMER_MS) : void 0;
133
156
  }
134
157
  /**
135
158
  * 润色请求的客户端超时:host 的润色时限 + 余量,整条结果同样夹进 `[1, MAX_TIMER_MS]`。
@@ -141,7 +164,8 @@ function rawOrganizeTimeoutMsOf(value) {
141
164
  * @returns 可安全交给 setTimeout 的毫秒数
142
165
  */
143
166
  function organizeFetchTimeoutMs(raw) {
144
- return Math.trunc(Math.min(Math.max((typeof raw === "number" && Number.isFinite(raw) && raw > 0 ? raw : ORGANIZE_TIMEOUT_FALLBACK_MS) + ORGANIZE_TIMEOUT_SLACK_MS, 1), MAX_TIMER_MS));
167
+ const base = isUsableTimeoutMs(raw) ? raw : ORGANIZE_TIMEOUT_FALLBACK_MS;
168
+ return Math.trunc(Math.min(Math.max(Math.min(base, 2147478647) + ORGANIZE_TIMEOUT_SLACK_MS, 1), MAX_TIMER_MS));
145
169
  }
146
170
  // src/client-styles.ts
147
171
  const CARD_STYLES = [
@@ -155,7 +179,7 @@ const CARD_STYLES = [
155
179
  ".dpi-btn-err:hover:not(:disabled){border-color:var(--dsw-alias-state-error-primary,currentColor)}",
156
180
  ".dpi-spin{animation:dpi-rotate .8s linear infinite}",
157
181
  "@keyframes dpi-rotate{to{transform:rotate(360deg)}}",
158
- "@media (prefers-reduced-motion:reduce){.dpi-spin{animation:none}.dpi-btn,.dpic-card,.dpic-chevron{transition:none}}",
182
+ "@media (prefers-reduced-motion:reduce){.dpi-spin{animation:none}.dpi-btn{transition:none}}",
159
183
  ".dpi-wrap{position:relative;display:inline-flex;isolation:isolate}",
160
184
  ".dpi-menu{position:absolute;bottom:calc(100% + 6px);right:0;z-index:50;min-width:224px;max-height:340px;overflow-y:auto;background:var(--dsw-menu-surface-fill,transparent);backdrop-filter:var(--dsw-menu-backdrop-filter,none);border:0;border-radius:10px;padding:4px;display:flex;flex-direction:column;gap:2px;box-shadow:var(--dsw-elevation-panel,none)}",
161
185
  ".dpi-item{appearance:none;border:none;background:transparent;color:var(--dsw-alias-label-primary,inherit);font:inherit;font-size:12px;line-height:1.4;text-align:left;border-radius:6px;padding:8px 10px;cursor:pointer;white-space:nowrap}",
@@ -167,50 +191,28 @@ const CARD_STYLES = [
167
191
  ".dpi-split .dpi-caret svg{width:10px;height:10px}",
168
192
  ".dpi-group{padding:2px 0}",
169
193
  ".dpi-grouph{font-size:11px;font-weight:600;color:var(--dsw-alias-label-tertiary,inherit);padding:6px 10px 2px;letter-spacing:.02em}",
170
- ".dpic-card{border:1px solid var(--dsw-alias-border-l2,currentColor);background:var(--dsw-alias-bg-layer-3,transparent);border-radius:12px;list-style:none;transition:border-color .16s,background .16s}",
171
- ".dpic-card:hover{border-color:var(--dsw-alias-label-dimmed,currentColor)}",
172
- ".dpic-card-open{background:var(--dsw-alias-bg-layer-2,transparent);border-color:var(--dsw-alias-label-dimmed,currentColor)}",
173
- ".dpic-header{appearance:none;width:100%;font:inherit;color:inherit;text-align:left;cursor:pointer;background:transparent;border:0;border-radius:12px;align-items:center;gap:12px;padding:14px 16px;display:flex}",
174
- ".dpic-head{flex-direction:column;flex:1;gap:4px;min-width:0;display:flex}",
175
- ".dpic-title{color:var(--dsw-alias-label-primary,inherit);font-size:15px;font-weight:600;line-height:1.4}",
176
- ".dpic-cardsub{color:var(--dsw-alias-label-tertiary,inherit);font-size:13px;line-height:1.5}",
177
- ".dpic-chevron{color:var(--dsw-alias-label-tertiary,inherit);flex:none;transition:transform .16s}",
178
- ".dpic-chevron-open{transform:rotate(180deg)}",
179
- ".dpic-body{border-top:1px solid var(--dsw-alias-border-l2,currentColor);margin:0 16px;padding:8px 0 12px;list-style:none}",
180
194
  ".dpic-row{padding:10px 0;border-bottom:1px dashed var(--dsw-alias-border-l2,currentColor)}",
195
+ ".dpic-name{flex:1;min-width:0}",
196
+ ".dpic-rowhead .dpic-name{width:auto}",
197
+ ".dpic-rowhead .dpic-emoji{width:44px;flex:none;text-align:center}",
198
+ ".dpic-rowhead .dpic-group{width:84px;flex:none}",
199
+ ".dpic-desc{width:100%;margin-top:6px}",
200
+ ".dpic-text{width:100%;margin-top:6px}",
201
+ ".dpic-importpath{flex:1;min-width:0}",
202
+ ".dpic-rowhead .dpic-importpath{width:auto}",
203
+ ".dpic-del{flex:none}",
204
+ ".dpic-toolbar{display:flex;gap:8px;flex-wrap:wrap;padding:8px 0}",
181
205
  ".dpic-rowhead{display:flex;gap:8px;align-items:center}",
182
206
  ".dpic-idx{font-size:12px;color:var(--dsw-alias-label-tertiary,inherit);flex:none;min-width:26px}",
183
- ".dpic-name,.dpic-text,.dpic-emoji,.dpic-group,.dpic-desc,.dpic-importpath{box-sizing:border-box;font:inherit;color:var(--dsw-alias-label-primary,inherit);background:var(--dsw-alias-bg-layer-1,transparent);border:1px solid var(--dsw-alias-border-l2,transparent);border-radius:8px}",
184
- ".dpic-name{flex:1;min-width:0;font-size:12px;padding:6px 8px}",
185
- ".dpic-del{appearance:none;border:1px solid var(--dsw-alias-border-l2,currentColor);background:transparent;color:var(--dsw-alias-label-tertiary,inherit);font:inherit;font-size:12px;border-radius:6px;padding:4px 8px;cursor:pointer;flex:none}",
186
- ".dpic-del:hover:not(:disabled){border-color:var(--dsw-alias-state-error-primary,currentColor);color:var(--dsw-alias-state-error-primary,currentColor)}",
187
- ".dpic-del:disabled{opacity:.55;cursor:not-allowed}",
188
- ".dpic-header:focus-visible,.dpic-del:focus-visible{outline:2px solid var(--dsw-alias-brand-primary,currentColor);outline-offset:1px}",
189
- ".dpic-text{width:100%;font-size:12px;line-height:1.6;padding:8px;margin-top:6px;min-height:96px;resize:vertical}",
190
- ".dpic-name:focus,.dpic-text:focus,.dpic-emoji:focus,.dpic-group:focus,.dpic-desc:focus,.dpic-importpath:focus{outline:none;border-color:var(--dsw-alias-brand-primary,currentColor)}",
191
- ".dpic-name:focus-visible,.dpic-text:focus-visible,.dpic-emoji:focus-visible,.dpic-group:focus-visible,.dpic-desc:focus-visible,.dpic-importpath:focus-visible{outline:2px solid var(--dsw-alias-brand-primary,currentColor);outline-offset:1px}",
192
- ".dpic-emoji{width:44px;flex:none;font-size:13px;text-align:center;padding:6px 4px}",
193
- ".dpic-group{width:84px;flex:none;font-size:12px;padding:6px 8px}",
194
- ".dpic-desc{width:100%;font-size:12px;padding:6px 8px;margin-top:6px}",
195
207
  ".dpic-importrow{padding:12px 0;border-bottom:1px dashed var(--dsw-alias-border-l2,currentColor)}",
196
- ".dpic-importpath{flex:1;min-width:0;font-size:12px;padding:6px 8px}",
197
- ".dpic-foot{display:flex;gap:8px;align-items:center;padding-top:10px;flex-wrap:wrap}",
198
- ".dpic-btn{appearance:none;border:1px solid var(--dsw-alias-border-l2,currentColor);background:var(--dsw-alias-bg-layer-1,transparent);color:var(--dsw-alias-label-primary,inherit);font:inherit;font-size:12px;border-radius:8px;padding:6px 10px;cursor:pointer}",
199
- ".dpic-btn:hover:not(:disabled){border-color:var(--dsw-alias-label-dimmed,currentColor);background:var(--dsw-alias-bg-layer-2,transparent)}",
200
- ".dpic-btn:focus-visible{outline:2px solid var(--dsw-alias-brand-primary,currentColor);outline-offset:1px}",
201
- ".dpic-btn:disabled{opacity:.55;cursor:not-allowed}",
202
- ".dpic-btn-primary{background:var(--dsw-alias-brand-primary,currentColor);border-color:var(--dsw-alias-brand-primary,currentColor);color:var(--dsw-alias-label-primary-foreground,#fff)}",
203
- ".dpic-btn-primary:hover:not(:disabled){background:var(--dsw-alias-brand-primary,currentColor);border-color:var(--dsw-alias-brand-primary,currentColor);filter:brightness(.92)}",
204
- ".dpic-btn-danger{color:var(--dsw-alias-state-error-primary,currentColor)}",
205
- ".dpic-btn-danger:hover:not(:disabled){border-color:var(--dsw-alias-state-error-primary,currentColor)}",
206
208
  ".dpic-hint{font-size:12px;color:var(--dsw-alias-label-tertiary,inherit);line-height:1.5;padding-top:6px}",
207
209
  ".dpic-err{color:var(--dsw-alias-state-error-primary,currentColor)}"
208
210
  ].join("\n");
209
211
  // src/ui-messages.ts
210
212
  const UI_MESSAGES = {
211
213
  zh: {
212
- cardTitle: "模板库(输入框「模板」下拉与「润色」▾ 共用)",
213
- cardDescription: "输入框「模板」下拉与「润色」▾ 角色菜单共用这一份列表,空表即回落到内置精选角色集(生成自插件 agents/ 角色库)。留空点「导入角色」可一键导入内置全部;填路径则按「会话 cwd + 内置角色库 + 下方导入允许目录」放行。编辑后点「保存」生效,重启不丢。",
214
+ rolesSection: "角色库",
215
+ rolesHint: "输入框「模板」下拉与「润色」▾ 角色菜单共用这一份列表,空表即回落到内置精选角色集(生成自插件 agents/ 角色库)。留空点「导入角色」可一键导入内置全部;填路径则按「会话 cwd + 内置角色库 + 下方导入允许目录」放行。编辑后点「保存」生效,重启不丢。",
214
216
  statusReadOnly: "设置源不可写:编辑已禁用;下拉仍按当前列表生效。",
215
217
  statusNotReady: "设置源未就绪:显示当前生效列表,就绪后可编辑。",
216
218
  addTemplate: "+ 新增模板",
@@ -244,6 +246,7 @@ const UI_MESSAGES = {
244
246
  importEmpty: "目录下没有符合条件的角色 .md(需含 name 的 frontmatter)",
245
247
  importAllDone: "已从内置角色库导入全部 {count} 条{skips},编辑后点「保存」生效",
246
248
  importFromDone: "已从 {path} 导入 {count} 条{skips},编辑后点「保存」生效",
249
+ importTruncated: "(回执标记本次导入有内容被上限截断)",
247
250
  importPlaceholder: "留空 = 导入内置全部角色;或填 .md / 目录路径(须在允许根内)",
248
251
  importAriaPath: "角色导入路径",
249
252
  importBtnTitle: "留空 = 一键导入内置全部角色;填路径 = 导入该 .md 或目录下的角色(路径须在允许根内)",
@@ -278,6 +281,7 @@ const UI_MESSAGES = {
278
281
  organizeErrContextFailed: "目录上下文读取失败:{message}",
279
282
  organizeErrModelFailed: "读取模型失败:{message}",
280
283
  organizeErrEmpty: "输入框为空,无内容可润色",
284
+ organizeErrTimeout: "润色请求超时:宿主没有在时限内回报结果",
281
285
  organizeErrUnknownReason: "未知错误",
282
286
  organizeErrUnknown: "润色失败(未知错误)",
283
287
  organizeCaretAria: "选择润色的角色风格",
@@ -287,18 +291,21 @@ const UI_MESSAGES = {
287
291
  organizeNoTemplates: "无模板可选作角色风格",
288
292
  organizeRoleItem: "以「{name}」的风格润色",
289
293
  organizeWriteBackUnavailable: "输入框动作不可用,无法写回",
290
- templatesIdleTitle: "选择一条模板插入输入框(空则填入,非空则空一行追加;按分组展示)",
294
+ organizeWriteBackStale: "输入框内容已变化,润色结果未写回",
295
+ organizeBusyTitle: "输入框正在提交,暂不能润色",
296
+ templatesIdleTitle: "选择一条模板插入光标处(按分组展示)",
291
297
  templatesBrokenTitle: "输入框动作不可用,无法插入",
298
+ templatesBusyTitle: "输入框正在提交,暂不能插入模板",
292
299
  templatesGroupCommon: "通用",
293
300
  templatesAria: "插入模板",
294
- templatesEmptyHint: "无模板:在设置页「模板库」中添加或恢复默认",
301
+ templatesEmptyHint: "无模板:在设置页「角色库」中添加或恢复默认",
295
302
  builtinLoading: "正在载入内置角色模板…",
296
303
  builtinFailed: "内置模板加载失败:{message}",
297
304
  builtinRetry: "重试"
298
305
  },
299
306
  en: {
300
- cardTitle: "Template library (shared by the \"Template\" dropdown and the \"Polish\" ▾ menu)",
301
- cardDescription: "The input-box \"Template\" dropdown and the \"Polish\" ▾ role menu share this one list; an empty list falls back to the built-in curated role set (generated from this plugin's agents/ role library). Leave the path empty and press \"Import roles\" to import the whole built-in library; an explicit path is allowed within \"session cwd + built-in role library + the import allowed directories below\". Press \"Save\" after editing — it survives restarts.",
307
+ rolesSection: "Role library",
308
+ rolesHint: "The input-box \"Template\" dropdown and the \"Polish\" ▾ role menu share this one list; an empty list falls back to the built-in curated role set (generated from this plugin's agents/ role library). Leave the path empty and press \"Import roles\" to import the whole built-in library; an explicit path is allowed within \"session cwd + built-in role library + the import allowed directories below\". Press \"Save\" after editing — it survives restarts.",
302
309
  statusReadOnly: "Settings source is read-only: editing is disabled; the dropdown still uses the current list.",
303
310
  statusNotReady: "Settings source is not ready yet: showing the list currently in effect, editing unlocks once it is ready.",
304
311
  addTemplate: "+ Add template",
@@ -332,6 +339,7 @@ const UI_MESSAGES = {
332
339
  importEmpty: "No qualifying role .md in that directory (frontmatter must contain name)",
333
340
  importAllDone: "Imported all {count} entries from the built-in role library{skips}; press \"Save\" after editing",
334
341
  importFromDone: "Imported {count} entries from {path}{skips}; press \"Save\" after editing",
342
+ importTruncated: " (the reply flagged some content as truncated by a limit)",
335
343
  importPlaceholder: "Empty = import every built-in role; or a .md / directory path (must be inside an allowed root)",
336
344
  importAriaPath: "Role import path",
337
345
  importBtnTitle: "Empty imports the whole built-in role library in one click; a path imports that .md or the roles in that directory (must be inside an allowed root)",
@@ -366,6 +374,7 @@ const UI_MESSAGES = {
366
374
  organizeErrContextFailed: "Failed to read the directory context: {message}",
367
375
  organizeErrModelFailed: "Failed to read the model: {message}",
368
376
  organizeErrEmpty: "The input box is empty; nothing to polish",
377
+ organizeErrTimeout: "Polish request timed out: the host did not reply in time",
369
378
  organizeErrUnknownReason: "unknown error",
370
379
  organizeErrUnknown: "Polish failed (unknown error)",
371
380
  organizeCaretAria: "Choose a role style to polish with",
@@ -375,33 +384,36 @@ const UI_MESSAGES = {
375
384
  organizeNoTemplates: "No templates available as a role style",
376
385
  organizeRoleItem: "Polish in the style of \"{name}\"",
377
386
  organizeWriteBackUnavailable: "Input-box actions unavailable; cannot write back",
378
- templatesIdleTitle: "Pick a template to insert into the input box (an empty draft is filled, a non-empty one gets a blank line plus the template; shown grouped)",
387
+ organizeWriteBackStale: "The input box changed; the polished text was not applied",
388
+ organizeBusyTitle: "The input box is submitting; cannot polish right now",
389
+ templatesIdleTitle: "Pick a template to insert at the caret (shown grouped)",
379
390
  templatesBrokenTitle: "Input-box actions unavailable; cannot insert",
391
+ templatesBusyTitle: "The input box is submitting; cannot insert a template",
380
392
  templatesGroupCommon: "General",
381
393
  templatesAria: "Insert a template",
382
- templatesEmptyHint: "No templates: add or restore defaults under \"Template library\" in the settings page",
394
+ templatesEmptyHint: "No templates: add or restore defaults under \"Role library\" in the settings page",
383
395
  builtinLoading: "Loading built-in role templates…",
384
396
  builtinFailed: "Failed to load built-in templates: {message}",
385
397
  builtinRetry: "Retry"
386
398
  }
387
399
  };
388
400
  // node_modules/@jayyuen66/dsh-plugin-shared/dist/errors.js
389
- function t(e) {
401
+ function t$1(e) {
390
402
  let t = Object.getOwnPropertyDescriptor(e, `message`);
391
403
  return t !== void 0 && `value` in t && typeof t.value == `string` ? t.value : void 0;
392
404
  }
393
- function n(e, r) {
405
+ function n$1(e, r) {
394
406
  if (r.has(e)) return `<circular cause>`;
395
407
  r.add(e);
396
408
  try {
397
409
  if (!(e instanceof Error)) {
398
410
  if (typeof e == `object` && e) {
399
- let n = t(e);
411
+ let n = t$1(e);
400
412
  if (n !== void 0 && n !== ``) return n;
401
413
  }
402
414
  return String(e);
403
415
  }
404
- let i = e.message === `` ? e.name : e.message, a = typeof globalThis.AggregateError == `function` && e instanceof AggregateError && e.errors.length > 0 ? ` [${e.errors.map((e) => n(e, r)).join(`; `)}]` : ``, o = e.cause === void 0 || e.cause === null ? `` : n(e.cause, r);
416
+ let i = e.message === `` ? e.name : e.message, a = typeof globalThis.AggregateError == `function` && e instanceof AggregateError && e.errors.length > 0 ? ` [${e.errors.map((e) => n$1(e, r)).join(`; `)}]` : ``, o = e.cause === void 0 || e.cause === null ? `` : n$1(e.cause, r);
405
417
  return `${i}${a}${o === `` || o === i ? `` : `: ${o}`}`;
406
418
  } catch {
407
419
  return `<unrenderable value>`;
@@ -409,8 +421,174 @@ function n(e, r) {
409
421
  r.delete(e);
410
422
  }
411
423
  }
412
- function r(e) {
413
- return n(e, /* @__PURE__ */ new Set());
424
+ function r$1(e) {
425
+ return n$1(e, /* @__PURE__ */ new Set());
426
+ }
427
+ // node_modules/@jayyuen66/dsh-plugin-shared/dist/card-ui.js
428
+ const c = `
429
+ .dsu-form{display:flex;flex-direction:column}
430
+ .dsu-section{margin-top:24px;padding-top:24px;border-top:.5px solid var(--dsw-alias-border-l1)}
431
+ .dsu-form>.dsu-section:first-child{margin-top:0;padding-top:0;border-top:0}
432
+ .dsu-sectionTitle{margin:0;font-size:15px;font-weight:600;line-height:1.4;color:var(--dsw-alias-label-primary)}
433
+ .dsu-sectionHint{margin:4px 0 0;font-size:12px;line-height:1.5;color:var(--dsw-alias-label-tertiary)}
434
+ .dsu-statusbar{display:flex;flex-wrap:wrap;gap:4px 8px;margin-top:8px;font-size:12px;line-height:1.5;color:var(--dsw-alias-label-tertiary)}
435
+ .dsu-field{display:grid;grid-template-columns:minmax(0,1fr) minmax(240px,360px);column-gap:32px;align-items:center;padding:12px 0;border-top:.5px solid var(--dsw-alias-border-l2)}
436
+ .dsu-fieldMeta{display:flex;flex-direction:column;gap:4px;min-width:0}
437
+ .dsu-labelRow{display:flex;align-items:center;gap:6px;min-width:0}
438
+ .dsu-label{font-size:13px;font-weight:500;line-height:1.5;color:var(--dsw-alias-label-primary)}
439
+ .dsu-labelMono{font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:12px}
440
+ .dsu-hint{margin:0;font-size:12px;line-height:1.5;color:var(--dsw-alias-label-tertiary)}
441
+ .dsu-control{min-width:0;display:flex;align-items:center;gap:8px}
442
+ .dsu-fieldWide{grid-template-columns:minmax(0,1fr);align-items:start}
443
+ .dsu-fieldWide .dsu-control{width:100%;max-width:720px;margin-top:2px}
444
+ .dsu-help{display:inline-flex;align-items:center;gap:6px;min-width:0}
445
+ .dsu-helpBtn{appearance:none;border:0;background:transparent;padding:0;width:16px;height:16px;display:inline-flex;align-items:center;justify-content:center;color:var(--dsw-alias-label-tertiary);cursor:help;border-radius:50%;flex:none}
446
+ .dsu-help:hover .dsu-helpBtn,.dsu-helpBtn:focus-visible{color:var(--dsw-alias-label-primary)}
447
+ .dsu-helpBtn:focus-visible{outline:2px solid var(--dsw-alias-state-business-primary);outline-offset:1px}
448
+ .dsu-tip{position:fixed;z-index:60;box-sizing:border-box;max-width:min(340px,calc(100vw - 16px));max-height:calc(100vh - 16px);overflow:auto;overflow-wrap:anywhere;padding:10px 12px;border-radius:10px;background:var(--dsw-alias-bg-layer-2);border:.5px solid var(--dsw-alias-border-l3);box-shadow:0 12px 32px rgb(0 0 0 / 45%);font-size:12px;line-height:1.6;font-weight:400;color:var(--dsw-alias-label-secondary)}
449
+ .dsu-input{width:100%;height:34px;padding:0 12px;border:.5px solid var(--dsw-alias-border-l4);border-radius:var(--dsw-radius-md);background:var(--dsw-alias-bg-layer-3);color:var(--dsw-alias-label-primary);font:inherit;font-size:13px}
450
+ .dsu-input:focus-visible{outline:none;border-color:var(--dsw-alias-state-business-primary)}
451
+ .dsu-input[aria-invalid="true"]{border-color:var(--dsw-alias-state-error-primary)}
452
+ .dsu-input:disabled{color:var(--dsw-alias-label-tertiary);cursor:default}
453
+ .dsu-input::placeholder{color:var(--dsw-alias-label-tertiary)}
454
+ .dsu-textarea{height:auto;min-height:96px;padding:8px 12px;line-height:1.6;resize:vertical}
455
+ .dsu-mono{font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace}
456
+ .dsu-numberWrap{display:flex;flex-direction:column;gap:4px;width:100%;min-width:0}
457
+ .dsu-number{display:flex;align-items:center;gap:8px;min-width:0}
458
+ .dsu-number .dsu-input{min-width:0}
459
+ .dsu-unit{flex:none;font-size:12px;color:var(--dsw-alias-label-tertiary)}
460
+ .dsu-error{margin:0;font-size:12px;line-height:1.5;color:var(--dsw-alias-state-error-primary)}
461
+ .dsu-switch{appearance:none;width:36px;height:20px;border-radius:999px;border:0;padding:2px;background:var(--dsw-alias-border-l3);display:flex;align-items:center;cursor:pointer;flex:none;transition:background-color .16s}
462
+ .dsu-knob{width:16px;height:16px;border-radius:50%;background:var(--dsw-alias-label-primary);transition:transform .16s,background-color .16s}
463
+ .dsu-switch[aria-checked="true"]{background:var(--dsw-alias-label-primary)}
464
+ .dsu-switch[aria-checked="true"] .dsu-knob{transform:translateX(16px);background:var(--dsw-alias-label-primary-foreground)}
465
+ .dsu-switch:disabled{opacity:.4;cursor:not-allowed}
466
+ .dsu-switch:focus-visible{outline:2px solid var(--dsw-alias-state-business-primary);outline-offset:2px}
467
+ .dsu-selectWrap{position:relative;width:100%;min-width:0}
468
+ .dsu-select{display:flex;align-items:center;justify-content:space-between;gap:8px;text-align:left;cursor:pointer}
469
+ .dsu-select[aria-expanded="true"]{border-color:var(--dsw-alias-state-business-primary)}
470
+ .dsu-selectValue{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
471
+ .dsu-chevron{flex:none;color:var(--dsw-alias-label-tertiary);transition:transform .16s}
472
+ .dsu-select[aria-expanded="true"] .dsu-chevron{transform:rotate(180deg)}
473
+ .dsu-menu{position:fixed;z-index:70;padding:4px;background:var(--dsw-alias-bg-layer-2);border:.5px solid var(--dsw-alias-border-l3);border-radius:12px;box-shadow:0 12px 32px rgb(0 0 0 / 50%);max-height:280px;overflow:auto}
474
+ .dsu-option{appearance:none;border:0;background:transparent;color:var(--dsw-alias-label-primary);font:inherit;font-size:13px;line-height:1.4;width:100%;display:flex;align-items:center;justify-content:space-between;gap:12px;padding:8px 10px;border-radius:8px;cursor:pointer;text-align:left}
475
+ .dsu-option:hover,.dsu-option[data-active="true"]{background:var(--dsw-alias-bg-layer-3)}
476
+ .dsu-option:disabled{color:var(--dsw-alias-label-tertiary);cursor:not-allowed}
477
+ .dsu-option:focus-visible{outline:2px solid var(--dsw-alias-state-business-primary);outline-offset:-2px}
478
+ .dsu-optionGroup{padding:6px 10px 2px;font-size:11px;font-weight:600;color:var(--dsw-alias-label-tertiary)}
479
+ .dsu-check{opacity:0;flex:none}
480
+ .dsu-option[aria-selected="true"] .dsu-check{opacity:1}
481
+ .dsu-savebar{display:flex;align-items:center;gap:8px;padding:12px 0;margin-top:24px;border-top:.5px solid var(--dsw-alias-border-l2);background:var(--dsw-alias-bg-base)}
482
+ .dsu-savebar[data-dirty="true"]{position:sticky;bottom:0;z-index:2;box-shadow:0 -12px 24px rgb(0 0 0 / 35%)}
483
+ .dsu-btn{appearance:none;border:.5px solid var(--dsw-alias-border-l2);background:transparent;color:var(--dsw-alias-label-primary);font:inherit;font-size:13px;line-height:1.5;border-radius:var(--dsw-radius-md);padding:5px 14px;cursor:pointer;transition:background-color .12s,border-color .12s,color .12s,filter .12s}
484
+ .dsu-btn:hover:not(:disabled){background:var(--dsw-alias-bg-layer-2);border-color:var(--dsw-alias-border-l3)}
485
+ .dsu-btn:active:not(:disabled){background:var(--dsw-alias-bg-layer-1)}
486
+ .dsu-btn:focus-visible{outline:2px solid var(--dsw-alias-state-business-primary);outline-offset:1px}
487
+ .dsu-btn:disabled{opacity:.4;cursor:not-allowed}
488
+ .dsu-btnPrimary{background:var(--dsw-alias-label-primary);border-color:var(--dsw-alias-label-primary);color:var(--dsw-alias-bg-layer-3)}
489
+ .dsu-btnPrimary:hover:not(:disabled){background:var(--dsw-alias-label-primary);border-color:var(--dsw-alias-label-primary);filter:brightness(.9)}
490
+ .dsu-btnPrimary:active:not(:disabled){background:var(--dsw-alias-label-primary);border-color:var(--dsw-alias-label-primary);filter:brightness(.84)}
491
+ .dsu-btnDanger{color:var(--dsw-alias-state-error-primary)}
492
+ .dsu-btnDanger:hover:not(:disabled){color:var(--dsw-alias-state-error-primary);border-color:var(--dsw-alias-state-error-primary);background:var(--dsw-alias-bg-layer-2)}
493
+ .dsu-status{margin-left:auto;font-size:12px;color:var(--dsw-alias-label-tertiary)}
494
+ .dsu-statusError{color:var(--dsw-alias-state-error-primary)}
495
+ .dsu-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(200px,100%),1fr));gap:0 24px}
496
+ .dsu-grid>.dsu-field{display:flex;flex-direction:column;align-items:stretch;gap:6px;padding:10px 0;border-top:.5px solid var(--dsw-alias-border-l1)}
497
+ .dsu-grid>.dsu-field .dsu-control{width:100%}
498
+ @media (max-width:640px){
499
+ .dsu-field{grid-template-columns:minmax(0,1fr);align-items:start}
500
+ .dsu-control{width:100%;max-width:720px}
501
+ .dsu-section{margin-top:20px;padding-top:20px}
502
+ }
503
+ @media (prefers-reduced-motion:reduce){
504
+ .dsu-switch,.dsu-knob,.dsu-chevron,.dsu-btn{transition:none}
505
+ }
506
+ `;
507
+ function u(t) {
508
+ return (0, react.createElement)(`div`, { className: `dsu-form` }, t.children);
509
+ }
510
+ function d(t) {
511
+ return (0, react.createElement)(`section`, { className: `dsu-section` }, (0, react.createElement)(`h2`, { className: `dsu-sectionTitle` }, t.title), t.hint === void 0 ? null : (0, react.createElement)(`p`, { className: `dsu-sectionHint` }, t.hint), t.children);
512
+ }
513
+ function S(t) {
514
+ let n = !t.writable || t.busy || !t.dirty, r;
515
+ return r = t.error === null ? t.writable ? t.dirty ? t.dirtyLabel : t.cleanLabel : t.readOnlyLabel : t.error, (0, react.createElement)(`div`, {
516
+ className: `dsu-savebar`,
517
+ "data-dirty": t.dirty
518
+ }, (0, react.createElement)(`button`, {
519
+ type: `button`,
520
+ className: `dsu-btn dsu-btnPrimary`,
521
+ "data-field": `save`,
522
+ disabled: n,
523
+ onClick: t.onSave
524
+ }, t.busy ? t.savingLabel : t.saveLabel), (0, react.createElement)(`button`, {
525
+ type: `button`,
526
+ className: `dsu-btn`,
527
+ "data-field": `discard`,
528
+ disabled: n,
529
+ onClick: t.onDiscard
530
+ }, t.revertLabel), (0, react.createElement)(`span`, { className: t.error === null ? `dsu-status` : `dsu-status dsu-statusError` }, r));
531
+ }
532
+ // src/input-writeback.ts
533
+ /**
534
+ * 输入框异步写回的凭据与判定。
535
+ *
536
+ * 润色结果是整稿替换:发起时记下会话、草稿版本与输入动作面,返回时用**最新一帧**
537
+ * 核对。任一项在途中变了(用户继续编辑、宿主进入提交期、会话被切换、组件重挂成
538
+ * 另一份 facade),结果都不许落地——宁可报「未写回」,也不能覆盖用户后来的输入。
539
+ * 模板走插入语义(captureInsertion + insertText),由宿主按发起的选区做版本校验。
540
+ */
541
+ /** 宿主是否给了整稿替换面(润色结果最后落到 setDraft)。 */
542
+ function hasDraftFace(actions) {
543
+ return actions !== void 0 && typeof actions.setDraft === "function";
544
+ }
545
+ /** 宿主是否给了版本校验插入面(模板走这一对,不整稿覆盖)。 */
546
+ function hasInsertFace(actions) {
547
+ return actions !== void 0 && typeof actions.captureInsertion === "function" && typeof actions.insertText === "function";
548
+ }
549
+ /** 提交期(`phase !== "plain"`)也算失效:发送成功后编辑器会被清空,失败时原稿要留着,
550
+ * 两种情况下在途的润色结果都不该再写进草稿。 */
551
+ function useWriteBack(input, messages) {
552
+ const latest = (0, react.useRef)(input);
553
+ const active = (0, react.useRef)(void 0);
554
+ (0, react.useEffect)(() => {
555
+ latest.current = input;
556
+ const ticket = active.current;
557
+ if (ticket === void 0) return;
558
+ if (ticket.sessionId !== input.sessionId || ticket.actions !== input.actions || input.phase !== "plain") ticket.invalidated = true;
559
+ }, [input]);
560
+ (0, react.useEffect)(() => () => {
561
+ const ticket = active.current;
562
+ if (ticket !== void 0) {
563
+ ticket.invalidated = true;
564
+ active.current = void 0;
565
+ }
566
+ }, []);
567
+ return {
568
+ begin: () => {
569
+ const ticket = {
570
+ sessionId: latest.current.sessionId,
571
+ draftRev: latest.current.draftRev,
572
+ actions: latest.current.actions,
573
+ invalidated: false
574
+ };
575
+ active.current = ticket;
576
+ return ticket;
577
+ },
578
+ finish: (ticket) => {
579
+ if (active.current === ticket) active.current = void 0;
580
+ },
581
+ commit: (content, ticket) => {
582
+ const live = latest.current;
583
+ const { actions } = live;
584
+ if (!hasDraftFace(actions)) throw new Error(messages.unavailable);
585
+ if (ticket.sessionId !== live.sessionId || live.phase !== "plain") throw new Error(messages.stale);
586
+ let liveRev = live.draftRev;
587
+ if (hasInsertFace(actions)) liveRev = actions.captureInsertion().draftRev;
588
+ if (ticket.invalidated || liveRev !== ticket.draftRev) throw new Error(messages.stale);
589
+ actions.setDraft(content);
590
+ }
591
+ };
414
592
  }
415
593
  // src/remote.ts
416
594
  /** Typert Remote 命名空间(client 半这一侧的唯一一枚)。
@@ -421,12 +599,31 @@ function r(e) {
421
599
  const DIR_PREP_NAMESPACE = "dirPrepOrganize";
422
600
  const DIR_PREP_SERVICE_KEY = `remote.${DIR_PREP_NAMESPACE}`;
423
601
  const PACKAGE_NAME = "@jayyuen66/dsh-dir-prep-organize";
602
+ /** strict codec 的统一出口:失败交给 zod 的 `prettifyError`,读到的是一份带字段路径的说明。 */
603
+ function parseOrThrow(schema, value) {
604
+ const parsed = schema.safeParse(value);
605
+ if (!parsed.success) throw new TypeError(zod.z.prettifyError(parsed.error));
606
+ return parsed.data;
607
+ }
608
+ const SESSION_MESSAGE = "session request requires a string sessionId";
609
+ const SESSION_SCHEMA = zod.z.object({ sessionId: zod.z.string({ error: SESSION_MESSAGE }) }, { error: SESSION_MESSAGE });
610
+ const ORGANIZE_MESSAGE = "organize request requires string sessionId, prompt and entriesSummary";
611
+ const ORGANIZE_SCHEMA = zod.z.object({
612
+ sessionId: zod.z.string({ error: ORGANIZE_MESSAGE }),
613
+ prompt: zod.z.string({ error: ORGANIZE_MESSAGE }),
614
+ entriesSummary: zod.z.string({ error: ORGANIZE_MESSAGE }),
615
+ roleText: zod.z.string({ error: "organize request roleText must be a string when present" }).optional()
616
+ }, { error: ORGANIZE_MESSAGE });
617
+ const IMPORT_MESSAGE = "import request requires string path and sessionId";
618
+ const IMPORT_SCHEMA = zod.z.object({
619
+ path: zod.z.string({ error: IMPORT_MESSAGE }),
620
+ sessionId: zod.z.string({ error: IMPORT_MESSAGE })
621
+ }, { error: IMPORT_MESSAGE });
424
622
  const SESSION_CODEC = {
425
623
  mode: "strict",
426
624
  typeSymbol: `${PACKAGE_NAME}#session-request`,
427
625
  create: () => ({ parse(value) {
428
- if (!e(value) || typeof value["sessionId"] !== "string") throw new TypeError("session request requires a string sessionId");
429
- return { sessionId: value["sessionId"] };
626
+ return parseOrThrow(SESSION_SCHEMA, value);
430
627
  } })
431
628
  };
432
629
  const DIR_PREP_DESCRIPTORS = [
@@ -481,14 +678,14 @@ const DIR_PREP_DESCRIPTORS = [
481
678
  mode: "strict",
482
679
  typeSymbol: `${PACKAGE_NAME}#organize-request`,
483
680
  create: () => ({ parse(value) {
484
- if (!e(value) || typeof value["sessionId"] !== "string" || typeof value["prompt"] !== "string" || typeof value["entriesSummary"] !== "string") throw new TypeError("organize request requires string sessionId, prompt and entriesSummary");
485
- const { roleText } = value;
486
- if (roleText !== void 0 && typeof roleText !== "string") throw new TypeError("organize request roleText must be a string when present");
487
- return {
488
- sessionId: value["sessionId"],
489
- prompt: value["prompt"],
490
- entriesSummary: value["entriesSummary"],
491
- ...roleText === void 0 ? {} : { roleText }
681
+ const request = parseOrThrow(ORGANIZE_SCHEMA, value);
682
+ return request.roleText === void 0 ? {
683
+ sessionId: request.sessionId,
684
+ prompt: request.prompt,
685
+ entriesSummary: request.entriesSummary
686
+ } : {
687
+ ...request,
688
+ roleText: request.roleText
492
689
  };
493
690
  } })
494
691
  }
@@ -509,24 +706,20 @@ const DIR_PREP_DESCRIPTORS = [
509
706
  mode: "strict",
510
707
  typeSymbol: `${PACKAGE_NAME}#import-request`,
511
708
  create: () => ({ parse(value) {
512
- if (!e(value) || typeof value["path"] !== "string" || typeof value["sessionId"] !== "string") throw new TypeError("import request requires string path and sessionId");
513
- return {
514
- path: value["path"],
515
- sessionId: value["sessionId"]
516
- };
709
+ return parseOrThrow(IMPORT_SCHEMA, value);
517
710
  } })
518
711
  }
519
712
  }],
520
713
  result: { mode: "src-json" }
521
714
  }
522
715
  ];
523
- const isMounter = (value) => e(value) && typeof value["$mount"] === "function";
524
- const isNamespace = (value) => e(value) && typeof value["defaults"] === "function" && typeof value["context"] === "function" && typeof value["model"] === "function" && typeof value["organize"] === "function" && typeof value["importTemplates"] === "function";
716
+ const isMounter = (value) => e$1(value) && typeof value["$mount"] === "function";
717
+ const isNamespace = (value) => e$1(value) && typeof value["defaults"] === "function" && typeof value["context"] === "function" && typeof value["model"] === "function" && typeof value["organize"] === "function" && typeof value["importTemplates"] === "function";
525
718
  const unwrap = (raw) => {
526
- if (!e(raw) || typeof raw["ok"] !== "boolean") throw new TypeError("Typert Remote 应答不是 RemoteResult:缺少布尔字段 ok");
719
+ if (!e$1(raw) || typeof raw["ok"] !== "boolean") throw new TypeError("Typert Remote 应答不是 RemoteResult:缺少布尔字段 ok");
527
720
  if (!raw["ok"]) {
528
721
  const { error } = raw;
529
- if (!e(error) || typeof error["code"] !== "string" || typeof error["message"] !== "string") throw new TypeError("Typert Remote 应答的 error 分支缺 code/message");
722
+ if (!e$1(error) || typeof error["code"] !== "string" || typeof error["message"] !== "string") throw new TypeError("Typert Remote 应答的 error 分支缺 code/message");
530
723
  throw new Error(`${error["code"]}: ${error["message"]}`);
531
724
  }
532
725
  if (!("value" in raw)) throw new TypeError("Typert Remote 应答的 ok 分支缺 value 字段");
@@ -591,7 +784,7 @@ const CLASS_ROW_HEAD = "dpic-rowhead";
591
784
  const CLASS_IMPORT_PATH = "dpic-importpath";
592
785
  const SLOT_INPUT_RIGHT = "conversation.input.right";
593
786
  function parseDirEntry(raw) {
594
- const { name, isDir, sizeBytes, snippet } = e(raw) ? raw : {};
787
+ const { name, isDir, sizeBytes, snippet } = e$1(raw) ? raw : {};
595
788
  return {
596
789
  name: typeof name === "string" ? name : "",
597
790
  isDir: isDir === true,
@@ -622,7 +815,7 @@ function skipCountsOf(skips) {
622
815
  ];
623
816
  }
624
817
  function parseContextResponse(raw) {
625
- const rec = e(raw) ? raw : {};
818
+ const rec = e$1(raw) ? raw : {};
626
819
  const { ok, truncated, entries } = rec;
627
820
  const parsedEntries = Array.isArray(entries) ? entries.map((entry) => parseDirEntry(entry)) : void 0;
628
821
  return {
@@ -634,7 +827,7 @@ function parseContextResponse(raw) {
634
827
  };
635
828
  }
636
829
  function parseModelResponse(raw) {
637
- const rec = e(raw) ? raw : {};
830
+ const rec = e$1(raw) ? raw : {};
638
831
  return {
639
832
  ok: rec["ok"] === true,
640
833
  ...spreadIfDefined(optionalString(rec, "error"), "error"),
@@ -644,7 +837,7 @@ function parseModelResponse(raw) {
644
837
  };
645
838
  }
646
839
  function parseOrganizeResponse(raw) {
647
- const rec = e(raw) ? raw : {};
840
+ const rec = e$1(raw) ? raw : {};
648
841
  return {
649
842
  ok: rec["ok"] === true,
650
843
  ...spreadIfDefined(optionalString(rec, "error"), "error"),
@@ -672,14 +865,14 @@ function formatImportSkips(t, skips) {
672
865
  return parts.length === 0 ? "" : t("skipSummary", { list: parts.join(t("skipSeparator")) });
673
866
  }
674
867
  function parseImportResponse(raw) {
675
- const { ok, error, count, truncated, skipped, entries } = e(raw) ? raw : {};
868
+ const { ok, error, count, truncated, skipped, entries } = e$1(raw) ? raw : {};
676
869
  const parsedEntries = Array.isArray(entries) ? sanitizeTemplateList(entries) : void 0;
677
870
  return {
678
871
  ok: ok === true,
679
872
  ...typeof error === "string" ? { error } : {},
680
873
  ...typeof count === "number" ? { count } : {},
681
874
  ...truncated === true ? { truncated: true } : {},
682
- ...e(skipped) ? { skipped: parseImportSkips(skipped) } : {},
875
+ ...e$1(skipped) ? { skipped: parseImportSkips(skipped) } : {},
683
876
  ...parsedEntries === void 0 ? {} : { entries: parsedEntries }
684
877
  };
685
878
  }
@@ -730,11 +923,26 @@ function requireReader() {
730
923
  if (dirPrepReader === void 0) throw new Error(`远程读面不可用:宿主网关没有挂上 ${DIR_PREP_NAMESPACE}`);
731
924
  return dirPrepReader;
732
925
  }
926
+ /**
927
+ * 润色链路里由客户端自己产生的错误:messageKey 指向 ui-messages 的键,捕获侧用当前
928
+ * 语言的 t 渲染成 tooltip——把文案直接写进 Error.message 会让英文界面看到硬编码中文。
929
+ * 宿主回执携带的原文(ctxRes.error / modelRes.error)不翻译,作为 {message} 原样带出。
930
+ */
931
+ var LocalizedOrganizeError = class extends Error {
932
+ messageKey;
933
+ params;
934
+ constructor(messageKey, params = {}) {
935
+ super(messageKey);
936
+ this.name = "LocalizedOrganizeError";
937
+ this.messageKey = messageKey;
938
+ this.params = params;
939
+ }
940
+ };
733
941
  /** 客户端超时只影响等待:宿主侧的润色超时仍由它自己的 AbortController 收口。 */
734
942
  async function within(pending, timeoutMs) {
735
943
  const gate = Promise.withResolvers();
736
944
  const timer = setTimeout(() => {
737
- gate.reject(/* @__PURE__ */ new Error("请求超时"));
945
+ gate.reject(new LocalizedOrganizeError("organizeErrTimeout"));
738
946
  }, timeoutMs);
739
947
  try {
740
948
  return await Promise.race([pending, gate.promise]);
@@ -755,7 +963,7 @@ async function loadBuiltinTemplates() {
755
963
  let settled;
756
964
  try {
757
965
  const body = await within(requireReader().defaults(), REMOTE_TIMEOUT_MS);
758
- const payload = e(body) ? body : void 0;
966
+ const payload = e$1(body) ? body : void 0;
759
967
  const okKey = "ok";
760
968
  const templatesKey = "templates";
761
969
  const rawReason = payload?.["error"];
@@ -772,7 +980,7 @@ async function loadBuiltinTemplates() {
772
980
  settled = {
773
981
  phase: "error",
774
982
  list: [],
775
- error: r(error)
983
+ error: r$1(error)
776
984
  };
777
985
  } finally {
778
986
  if (builtinGeneration === generation) builtinInflight = null;
@@ -799,7 +1007,7 @@ function builtinStatusRow(snap, t) {
799
1007
  };
800
1008
  const retryButton = (0, react.createElement)("button", {
801
1009
  type: "button",
802
- className: "dpic-btn",
1010
+ className: "dsu-btn",
803
1011
  "data-field": "dpi-builtin-retry",
804
1012
  onClick: () => {
805
1013
  loadBuiltinTemplates();
@@ -809,21 +1017,6 @@ function builtinStatusRow(snap, t) {
809
1017
  if (!snap.fromSettings && snap.builtinPhase !== "ready") row = snap.builtinPhase === "error" ? (0, react.createElement)("div", attrs, t("builtinFailed", { message: snap.builtinError }), retryButton) : (0, react.createElement)("div", attrs, t("builtinLoading"));
810
1018
  return row;
811
1019
  }
812
- /**
813
- * 润色链路里由客户端自己产生的错误:messageKey 指向 ui-messages 的键,捕获侧用当前
814
- * 语言的 t 渲染成 tooltip——把文案直接写进 Error.message 会让英文界面看到硬编码中文。
815
- * 宿主回执携带的原文(ctxRes.error / modelRes.error)不翻译,作为 {message} 原样带出。
816
- */
817
- var LocalizedOrganizeError = class extends Error {
818
- messageKey;
819
- params;
820
- constructor(messageKey, params = {}) {
821
- super(messageKey);
822
- this.name = "LocalizedOrganizeError";
823
- this.messageKey = messageKey;
824
- this.params = params;
825
- }
826
- };
827
1020
  function assertOrganizeReady(ctxRes, modelRes, prompt, unknownReason) {
828
1021
  if (!ctxRes.ok) throw new LocalizedOrganizeError("organizeErrContextFailed", { message: ctxRes.error ?? unknownReason });
829
1022
  if (!modelRes.ok || modelRes.provider === void 0 || modelRes.model === void 0) throw new LocalizedOrganizeError("organizeErrModelFailed", { message: modelRes.error ?? unknownReason });
@@ -941,11 +1134,6 @@ function rootsPersistError(t, persisted, expected, action) {
941
1134
  });
942
1135
  return message;
943
1136
  }
944
- function applyTemplateToDraft(current, template) {
945
- const base = typeof current === "string" ? current.trimEnd() : "";
946
- if (base.length === 0) return template;
947
- return `${base}\n\n${template}`;
948
- }
949
1137
  /** 菜单项文字:有 emoji 就前缀一个(emoji 是用户自填的视觉标记,空串 = 不显示)。 */
950
1138
  function templateItemLabel(tpl) {
951
1139
  return `${tpl.emoji === "" ? "" : `${tpl.emoji} `}${tpl.name}`;
@@ -963,7 +1151,7 @@ function groupTemplatesBy(templates, t) {
963
1151
  bucket.push(tpl);
964
1152
  buckets.set(key, bucket);
965
1153
  }
966
- return [...buckets.entries()].map(([group, items]) => ({
1154
+ return Array.from(buckets.entries(), ([group, items]) => ({
967
1155
  group,
968
1156
  items
969
1157
  }));
@@ -1075,7 +1263,7 @@ async function runOrganizeClick(args) {
1075
1263
  writeDraft(content);
1076
1264
  } catch (error) {
1077
1265
  if (seq.current !== mySeq) return;
1078
- setFailed(error instanceof LocalizedOrganizeError ? t(error.messageKey, error.params) : r(error));
1266
+ setFailed(error instanceof LocalizedOrganizeError ? t(error.messageKey, error.params) : r$1(error));
1079
1267
  if (flashTimer.current !== null) clearTimeout(flashTimer.current);
1080
1268
  flashTimer.current = setTimeout(() => {
1081
1269
  setFailed(void 0);
@@ -1148,6 +1336,24 @@ function createOrganizeRoleMenu(ui) {
1148
1336
  }
1149
1337
  }, `${tpl.emoji === "" ? "" : `${tpl.emoji} `}${t("organizeRoleItem", { name: tpl.name })}`)));
1150
1338
  }
1339
+ /** 主键的三态外观:失败 > 在途 > 空闲(三者互斥,按同一优先级判)。 */
1340
+ function organizeBadge(failed, loading, t) {
1341
+ if (failed !== void 0) return {
1342
+ icon: (0, react.createElement)(FailIcon),
1343
+ label: t("organizeFailedShort"),
1344
+ state: "error"
1345
+ };
1346
+ if (loading) return {
1347
+ icon: (0, react.createElement)(SpinIcon),
1348
+ label: t("organizeLoading"),
1349
+ state: "loading"
1350
+ };
1351
+ return {
1352
+ icon: (0, react.createElement)(TidyIcon),
1353
+ label: t("organizeIdle"),
1354
+ state: "idle"
1355
+ };
1356
+ }
1151
1357
  function createOrganizeButton() {
1152
1358
  return function OrganizeButton(props) {
1153
1359
  const [loading, setLoading] = (0, react.useState)(false);
@@ -1158,8 +1364,19 @@ function createOrganizeButton() {
1158
1364
  const flashTimer = (0, react.useRef)(null);
1159
1365
  const wrapRef = (0, react.useRef)(null);
1160
1366
  const draft = props.useInput === void 0 ? "" : props.useInput((state) => state.draft) ?? "";
1367
+ const draftRev = props.useInput === void 0 ? 0 : props.useInput((state) => state.draftRev);
1368
+ const phase = props.useInput === void 0 ? "plain" : props.useInput((state) => state.phase);
1161
1369
  const snap = props.useCard((state) => state);
1162
1370
  const { templates } = snap;
1371
+ const writeBack = useWriteBack({
1372
+ sessionId: props.sessionId ?? "",
1373
+ actions: props.inputActions,
1374
+ draftRev,
1375
+ phase
1376
+ }, {
1377
+ unavailable: props.t(NO_WRITE_BACK_TITLE_KEY),
1378
+ stale: props.t("organizeWriteBackStale")
1379
+ });
1163
1380
  useMenuDismiss(menuOpen, wrapRef, () => {
1164
1381
  setMenuOpen(false);
1165
1382
  });
@@ -1168,56 +1385,46 @@ function createOrganizeButton() {
1168
1385
  if (flashTimer.current !== null) clearTimeout(flashTimer.current);
1169
1386
  }, []);
1170
1387
  async function handleOrganize(roleText) {
1171
- await runOrganizeClick({
1172
- t: props.t,
1173
- loading,
1174
- inFlight,
1175
- seq,
1176
- prompt: draft,
1177
- sessionId: props.sessionId ?? "",
1178
- timeoutMs: organizeFetchTimeoutMs(snap.organizeTimeoutMs),
1179
- roleText,
1180
- setLoading,
1181
- setMenuOpen,
1182
- setFailed,
1183
- flashTimer,
1184
- writeDraft: (content) => {
1185
- const actions = props.inputActions;
1186
- if (actions === void 0 || typeof actions.setDraft !== "function") throw new Error(props.t("organizeWriteBackUnavailable"));
1187
- actions.setDraft(content);
1188
- }
1189
- });
1388
+ const ticket = writeBack.begin();
1389
+ try {
1390
+ await runOrganizeClick({
1391
+ t: props.t,
1392
+ loading,
1393
+ inFlight,
1394
+ seq,
1395
+ prompt: draft,
1396
+ sessionId: props.sessionId ?? "",
1397
+ timeoutMs: organizeFetchTimeoutMs(snap.organizeTimeoutMs),
1398
+ roleText,
1399
+ setLoading,
1400
+ setMenuOpen,
1401
+ setFailed,
1402
+ flashTimer,
1403
+ writeDraft: (content) => {
1404
+ writeBack.commit(content, ticket);
1405
+ }
1406
+ });
1407
+ } finally {
1408
+ writeBack.finish(ticket);
1409
+ }
1190
1410
  }
1191
1411
  function openMenu() {
1192
1412
  if (!snap.fromSettings) loadBuiltinTemplates();
1193
1413
  setMenuOpen((prev) => !prev);
1194
1414
  }
1195
- let icon;
1196
- let label;
1197
- let state;
1198
- if (failed !== void 0) {
1199
- icon = (0, react.createElement)(FailIcon);
1200
- label = props.t("organizeFailedShort");
1201
- state = "error";
1202
- } else if (loading) {
1203
- icon = (0, react.createElement)(SpinIcon);
1204
- label = props.t("organizeLoading");
1205
- state = "loading";
1206
- } else {
1207
- icon = (0, react.createElement)(TidyIcon);
1208
- label = props.t("organizeIdle");
1209
- state = "idle";
1210
- }
1211
- const canWrite = props.inputActions !== void 0 && typeof props.inputActions.setDraft === "function";
1415
+ const badge = organizeBadge(failed, loading, props.t);
1416
+ const replaceable = hasDraftFace(props.inputActions);
1417
+ const canWrite = replaceable && phase === "plain";
1212
1418
  let errTitle = props.t("organizeIdleTitle");
1213
1419
  if (failed !== void 0) errTitle = props.t("organizeFailedTitle", { message: failed });
1214
- else if (!canWrite) errTitle = props.t(NO_WRITE_BACK_TITLE_KEY);
1420
+ else if (!replaceable) errTitle = props.t(NO_WRITE_BACK_TITLE_KEY);
1421
+ else if (phase !== "plain") errTitle = props.t("organizeBusyTitle");
1215
1422
  const ui = {
1216
1423
  t: props.t,
1217
1424
  errTitle,
1218
- icon,
1219
- label,
1220
- state,
1425
+ icon: badge.icon,
1426
+ label: badge.label,
1427
+ state: badge.state,
1221
1428
  errClass: failed === void 0 ? "" : " dpi-btn-err",
1222
1429
  directItemLabel: props.t("organizeDirectItem"),
1223
1430
  noTemplatesLabel: props.t("organizeNoTemplates"),
@@ -1239,7 +1446,7 @@ function createTemplateButton() {
1239
1446
  return function TemplateButton(props) {
1240
1447
  const [open, setOpen] = (0, react.useState)(false);
1241
1448
  const wrapRef = (0, react.useRef)(null);
1242
- const draft = props.useInput === void 0 ? "" : props.useInput((state) => state.draft) ?? "";
1449
+ const phase = props.useInput === void 0 ? "plain" : props.useInput((state) => state.phase);
1243
1450
  const snap = props.useCard((state) => state);
1244
1451
  const { templates } = snap;
1245
1452
  useMenuDismiss(open, wrapRef, () => {
@@ -1248,11 +1455,14 @@ function createTemplateButton() {
1248
1455
  function pick(text) {
1249
1456
  setOpen(false);
1250
1457
  const actions = props.inputActions;
1251
- if (actions === void 0 || typeof actions.setDraft !== "function") return;
1252
- actions.setDraft(applyTemplateToDraft(draft, text));
1458
+ if (!hasInsertFace(actions)) return;
1459
+ actions.insertText(text, actions.captureInsertion());
1253
1460
  }
1254
- const canWrite = props.inputActions !== void 0 && typeof props.inputActions.setDraft === "function";
1255
- const title = canWrite ? props.t("templatesIdleTitle") : props.t("templatesBrokenTitle");
1461
+ const insertable = hasInsertFace(props.inputActions);
1462
+ const canWrite = insertable && phase === "plain";
1463
+ let title = props.t("templatesBrokenTitle");
1464
+ if (canWrite) title = props.t("templatesIdleTitle");
1465
+ else if (insertable) title = props.t("templatesBusyTitle");
1256
1466
  const grouped = groupTemplatesBy(templates, props.t);
1257
1467
  const emptyHintLabel = props.t("templatesEmptyHint");
1258
1468
  const builtinRow = builtinStatusRow(snap, props.t);
@@ -1310,7 +1520,7 @@ function createTemplateRowElement(view) {
1310
1520
  const indexMark = (0, react.createElement)("span", { className: "dpic-idx" }, `#${rowNum}`);
1311
1521
  const emojiInput = (0, react.createElement)("input", {
1312
1522
  type: "text",
1313
- className: "dpic-emoji",
1523
+ className: "dpic-emoji dsu-input",
1314
1524
  value: values.emoji,
1315
1525
  placeholder: EMOJI_PLACEHOLDER,
1316
1526
  disabled,
@@ -1323,7 +1533,7 @@ function createTemplateRowElement(view) {
1323
1533
  });
1324
1534
  const nameInput = (0, react.createElement)("input", {
1325
1535
  type: "text",
1326
- className: "dpic-name",
1536
+ className: "dpic-name dsu-input",
1327
1537
  value: values.name,
1328
1538
  placeholder: t("rowPlaceholderName"),
1329
1539
  disabled,
@@ -1335,7 +1545,7 @@ function createTemplateRowElement(view) {
1335
1545
  });
1336
1546
  const groupInput = (0, react.createElement)("input", {
1337
1547
  type: "text",
1338
- className: "dpic-group",
1548
+ className: "dpic-group dsu-input",
1339
1549
  value: values.group,
1340
1550
  placeholder: t("rowPlaceholderGroup"),
1341
1551
  disabled,
@@ -1348,7 +1558,7 @@ function createTemplateRowElement(view) {
1348
1558
  });
1349
1559
  const deleteButton = (0, react.createElement)("button", {
1350
1560
  type: "button",
1351
- className: "dpic-del",
1561
+ className: "dpic-del dsu-btn dsu-btnDanger",
1352
1562
  disabled,
1353
1563
  title: t("rowDeleteTitle"),
1354
1564
  onClick: () => {
@@ -1357,7 +1567,7 @@ function createTemplateRowElement(view) {
1357
1567
  }, t("rowDelete"));
1358
1568
  const descriptionInput = (0, react.createElement)("input", {
1359
1569
  type: "text",
1360
- className: "dpic-desc",
1570
+ className: "dpic-desc dsu-input",
1361
1571
  value: values.description,
1362
1572
  placeholder: t("rowPlaceholderDescription"),
1363
1573
  disabled,
@@ -1368,7 +1578,7 @@ function createTemplateRowElement(view) {
1368
1578
  onBlur: view.onBlur
1369
1579
  });
1370
1580
  const textArea = (0, react.createElement)("textarea", {
1371
- className: "dpic-text",
1581
+ className: "dpic-text dsu-input dsu-textarea dsu-mono",
1372
1582
  value: values.text,
1373
1583
  rows: 6,
1374
1584
  placeholder: t("rowPlaceholderText"),
@@ -1379,7 +1589,7 @@ function createTemplateRowElement(view) {
1379
1589
  },
1380
1590
  onBlur: view.onBlur
1381
1591
  });
1382
- return (0, react.createElement)("li", { className: "dpic-row" }, (0, react.createElement)("div", { className: CLASS_ROW_HEAD }, indexMark, emojiInput, nameInput, groupInput, deleteButton), descriptionInput, textArea);
1592
+ return (0, react.createElement)("div", { className: "dpic-row" }, (0, react.createElement)("div", { className: CLASS_ROW_HEAD }, indexMark, emojiInput, nameInput, groupInput, deleteButton), descriptionInput, textArea);
1383
1593
  }
1384
1594
  function TemplateRow(props) {
1385
1595
  const { t } = props;
@@ -1461,14 +1671,16 @@ function ImportPanel(props) {
1461
1671
  }), REMOTE_TIMEOUT_MS));
1462
1672
  if (!resp.ok || resp.entries === void 0) throw new Error(resp.error ?? t("importFailedUnknown"));
1463
1673
  const usable = resp.entries.length;
1464
- const count = Math.min(resp.count ?? usable, usable);
1674
+ const declared = countField(resp.count);
1675
+ const count = declared === 0 ? usable : Math.min(declared, usable);
1465
1676
  if (count === 0) {
1466
1677
  setImportError(t("importEmpty"));
1467
1678
  return;
1468
1679
  }
1469
1680
  props.onImported(resp.entries);
1470
1681
  setImportPath("");
1471
- const skipNote = formatImportSkips(t, resp.skipped);
1682
+ const truncatedNote = resp.truncated === true ? t("importTruncated") : "";
1683
+ const skipNote = `${formatImportSkips(t, resp.skipped)}${truncatedNote}`;
1472
1684
  setImportMsg(target.length === 0 ? t("importAllDone", {
1473
1685
  count,
1474
1686
  skips: skipNote
@@ -1478,7 +1690,7 @@ function ImportPanel(props) {
1478
1690
  skips: skipNote
1479
1691
  }));
1480
1692
  } catch (error) {
1481
- setImportError(r(error));
1693
+ setImportError(r$1(error));
1482
1694
  } finally {
1483
1695
  setImportBusy(false);
1484
1696
  }
@@ -1486,7 +1698,7 @@ function ImportPanel(props) {
1486
1698
  const canImport = props.editable && !importBusy;
1487
1699
  const importPathInput = (0, react.createElement)("input", {
1488
1700
  type: "text",
1489
- className: CLASS_IMPORT_PATH,
1701
+ className: `${CLASS_IMPORT_PATH} dsu-input`,
1490
1702
  value: importPath,
1491
1703
  placeholder: t("importPlaceholder"),
1492
1704
  disabled: !canImport,
@@ -1500,7 +1712,7 @@ function ImportPanel(props) {
1500
1712
  });
1501
1713
  const importBtn = (0, react.createElement)("button", {
1502
1714
  type: "button",
1503
- className: "dpic-btn",
1715
+ className: "dsu-btn",
1504
1716
  disabled: !canImport,
1505
1717
  title: t("importBtnTitle"),
1506
1718
  onClick: onImport
@@ -1508,7 +1720,7 @@ function ImportPanel(props) {
1508
1720
  const importMsgEl = importMsg === "" ? null : (0, react.createElement)("div", { className: "dpic-hint" }, importMsg);
1509
1721
  const importErrorEl = importError === "" ? null : (0, react.createElement)("div", { className: "dpic-hint dpic-err" }, `${t("importErrorPrefix")}${importError}`);
1510
1722
  const importHintEl = (0, react.createElement)("div", { className: "dpic-hint" }, t("importHint"));
1511
- return (0, react.createElement)("li", { className: "dpic-importrow" }, (0, react.createElement)("div", { className: CLASS_ROW_HEAD }, importPathInput, importBtn), importMsgEl, importErrorEl, importHintEl);
1723
+ return (0, react.createElement)("div", { className: "dpic-importrow" }, (0, react.createElement)("div", { className: CLASS_ROW_HEAD }, importPathInput, importBtn), importMsgEl, importErrorEl, importHintEl);
1512
1724
  }
1513
1725
  function AllowRootsPanel(props) {
1514
1726
  const { t } = props;
@@ -1521,7 +1733,7 @@ function AllowRootsPanel(props) {
1521
1733
  const rowAria = t("rootsAriaRow", { index: index + 1 });
1522
1734
  const rowInput = (0, react.createElement)("input", {
1523
1735
  type: "text",
1524
- className: CLASS_IMPORT_PATH,
1736
+ className: `${CLASS_IMPORT_PATH} dsu-input`,
1525
1737
  value: root,
1526
1738
  placeholder: ROOT_PATH_PLACEHOLDER,
1527
1739
  disabled: props.disabled,
@@ -1533,7 +1745,7 @@ function AllowRootsPanel(props) {
1533
1745
  });
1534
1746
  const rowButton = (0, react.createElement)("button", {
1535
1747
  type: "button",
1536
- className: "dpic-del",
1748
+ className: "dpic-del dsu-btn dsu-btnDanger",
1537
1749
  disabled: props.disabled,
1538
1750
  title: removeTitle,
1539
1751
  onClick: () => {
@@ -1551,7 +1763,7 @@ function AllowRootsPanel(props) {
1551
1763
  const addLabel = t("rootsAdd");
1552
1764
  const addInput = (0, react.createElement)("input", {
1553
1765
  type: "text",
1554
- className: CLASS_IMPORT_PATH,
1766
+ className: `${CLASS_IMPORT_PATH} dsu-input`,
1555
1767
  value: pending,
1556
1768
  placeholder: addPlaceholder,
1557
1769
  disabled: props.disabled,
@@ -1568,7 +1780,7 @@ function AllowRootsPanel(props) {
1568
1780
  });
1569
1781
  const addButton = (0, react.createElement)("button", {
1570
1782
  type: "button",
1571
- className: "dpic-btn",
1783
+ className: "dsu-btn",
1572
1784
  disabled: !canAdd,
1573
1785
  title: addTitle,
1574
1786
  onClick: () => {
@@ -1577,34 +1789,22 @@ function AllowRootsPanel(props) {
1577
1789
  }
1578
1790
  }, addLabel);
1579
1791
  const addRow = (0, react.createElement)("div", { className: CLASS_ROW_HEAD }, addInput, addButton);
1580
- return (0, react.createElement)("li", {
1792
+ return (0, react.createElement)("div", {
1581
1793
  className: "dpic-importrow",
1582
1794
  "data-field": "allow-roots"
1583
1795
  }, (0, react.createElement)("div", { className: "dpic-hint" }, t("rootsHeading")), rows, addRow, (0, react.createElement)("div", { className: "dpic-hint" }, t("rootsHint")));
1584
1796
  }
1585
- function CardFootBar(props) {
1586
- const { foot, editable, anythingDirty, busy, confirmReset } = props;
1587
- return (0, react.createElement)("li", { className: "dpic-foot" }, (0, react.createElement)("button", {
1797
+ /** 工具条:新增角色与恢复默认(保存/撤销交给卡片底部统一的 SaveBar)。 */
1798
+ function CardToolbar(props) {
1799
+ const { foot, editable, busy, confirmReset } = props;
1800
+ return (0, react.createElement)("div", { className: "dpic-toolbar" }, (0, react.createElement)("button", {
1588
1801
  type: "button",
1589
- className: "dpic-btn",
1802
+ className: "dsu-btn",
1590
1803
  disabled: !editable,
1591
1804
  onClick: props.onAdd
1592
1805
  }, foot.add), (0, react.createElement)("button", {
1593
1806
  type: "button",
1594
- className: "dpic-btn dpic-btn-primary",
1595
- "data-field": "save",
1596
- disabled: !editable || !anythingDirty || busy,
1597
- title: anythingDirty ? foot.saveTitleDirty : foot.saveTitleClean,
1598
- onClick: props.onSave
1599
- }, busy ? foot.saving : foot.save), (0, react.createElement)("button", {
1600
- type: "button",
1601
- className: "dpic-btn",
1602
- "data-field": "discard",
1603
- disabled: !editable || !anythingDirty || busy,
1604
- onClick: props.onDiscard
1605
- }, foot.revert), (0, react.createElement)("button", {
1606
- type: "button",
1607
- className: "dpic-btn dpic-btn-danger",
1807
+ className: "dsu-btn dsu-btnDanger",
1608
1808
  disabled: !editable || busy,
1609
1809
  title: foot.resetTitle,
1610
1810
  onClick: props.onReset
@@ -1629,28 +1829,6 @@ function cardStatusHint(snap, t) {
1629
1829
  else hint = t("statusNotReady");
1630
1830
  return hint;
1631
1831
  }
1632
- function createCardHeader(view) {
1633
- const { t, open, setOpen } = view;
1634
- const headTitle = (0, react.createElement)("div", { className: "dpic-title" }, t("cardTitle"));
1635
- const headDesc = (0, react.createElement)("div", { className: "dpic-cardsub" }, t("cardDescription"));
1636
- const headBlock = (0, react.createElement)("div", { className: "dpic-head" }, headTitle, headDesc);
1637
- const chevronPath = (0, react.createElement)("path", svgPathProps("M3 5l4 4 4-4", true));
1638
- const chevron = (0, react.createElement)("svg", {
1639
- width: 14,
1640
- height: 14,
1641
- viewBox: "0 0 14 14",
1642
- "aria-hidden": true,
1643
- className: `dpic-chevron${open ? " dpic-chevron-open" : ""}`
1644
- }, chevronPath);
1645
- return (0, react.createElement)("button", {
1646
- type: "button",
1647
- className: "dpic-header",
1648
- "aria-expanded": open,
1649
- onClick: () => {
1650
- setOpen((prev) => !prev);
1651
- }
1652
- }, headBlock, chevron);
1653
- }
1654
1832
  function createDraftActions(t, draft, rootsDraft, setDraft, setRootsDraft) {
1655
1833
  function onCommit(id, fields) {
1656
1834
  setDraft(draft.map((tpl) => tpl.id === id ? {
@@ -1705,7 +1883,7 @@ function createPersistActions(args) {
1705
1883
  const { t, editable, dirty, rootsDirty, anythingDirty, confirmReset, templates, allowRoots, draft, rootsDraft, set, unset, readBack, setDraft, setDraftFor, setRootsDraft, setBusy, setSaveError, setConfirmReset } = args;
1706
1884
  function reportError(err) {
1707
1885
  console.error("[dir-prep-organize] templates settings write failed:", err);
1708
- setSaveError(r(err));
1886
+ setSaveError(r$1(err));
1709
1887
  }
1710
1888
  async function onSave() {
1711
1889
  if (!editable || !anythingDirty) return;
@@ -1723,8 +1901,8 @@ function createPersistActions(args) {
1723
1901
  verifyRootsPersisted(t, readBack(), nextRoots);
1724
1902
  }
1725
1903
  setBusy(false);
1726
- setDraft(next);
1727
- setRootsDraft(nextRoots);
1904
+ setDraft((prev) => prev === draft ? next : prev);
1905
+ setRootsDraft((prev) => prev === rootsDraft ? nextRoots : prev);
1728
1906
  } catch (error) {
1729
1907
  setBusy(false);
1730
1908
  reportError(error);
@@ -1765,12 +1943,39 @@ function createPersistActions(args) {
1765
1943
  onReset
1766
1944
  };
1767
1945
  }
1768
- /** 展开态正文(状态行 + 模板行表 + 卡底动作条 + 导入面 + 允许目录面 + 底部提示)。 */
1946
+ /** 卡片正文:状态提示 + 工具条 + 角色行表 + 导入面 + 允许目录面 + 保存条。 */
1769
1947
  function createCardBody(view) {
1770
1948
  const { t, statusHint, draft, rootsDraft, foot, editable, anythingDirty, busy, confirmReset, saveError } = view;
1771
1949
  const { onCommit, onDelete, onAdd, onImported, onRootChange, onRootDelete, onRootAdd } = view.draftActions;
1772
1950
  const { onSave, onDiscard, onReset } = view.persistActions;
1773
- return (0, react.createElement)("ul", { className: "dpic-body" }, statusHint === "" ? null : (0, react.createElement)("li", { className: "dpic-hint" }, statusHint), draft.map((tpl, idx) => (0, react.createElement)(TemplateRow, {
1951
+ const footHint = (0, react.createElement)("p", { className: "dpic-hint" }, t("footHint"));
1952
+ const saveBar = (0, react.createElement)(S, {
1953
+ dirty: anythingDirty,
1954
+ busy,
1955
+ writable: editable,
1956
+ error: saveError === "" ? null : `${t("saveFailed")}${saveError}`,
1957
+ saveLabel: t("save"),
1958
+ savingLabel: t("saving"),
1959
+ revertLabel: t("revert"),
1960
+ dirtyLabel: t("saveTitleDirty"),
1961
+ cleanLabel: t("saveTitleClean"),
1962
+ readOnlyLabel: t("statusReadOnly"),
1963
+ onSave: () => {
1964
+ onSave();
1965
+ },
1966
+ onDiscard
1967
+ });
1968
+ return (0, react.createElement)(u, null, statusHint === "" ? null : (0, react.createElement)("p", { className: "dpic-hint" }, statusHint), (0, react.createElement)(d, {
1969
+ title: t("rolesSection"),
1970
+ hint: t("rolesHint")
1971
+ }, (0, react.createElement)(CardToolbar, {
1972
+ foot,
1973
+ editable,
1974
+ busy,
1975
+ confirmReset,
1976
+ onAdd,
1977
+ onReset
1978
+ }), draft.map((tpl, idx) => (0, react.createElement)(TemplateRow, {
1774
1979
  key: tpl.id,
1775
1980
  t,
1776
1981
  index: idx,
@@ -1778,17 +1983,7 @@ function createCardBody(view) {
1778
1983
  disabled: !editable || busy,
1779
1984
  onCommit,
1780
1985
  onDelete
1781
- })), (0, react.createElement)(CardFootBar, {
1782
- foot,
1783
- editable,
1784
- anythingDirty,
1785
- busy,
1786
- confirmReset,
1787
- onAdd,
1788
- onSave,
1789
- onDiscard,
1790
- onReset
1791
- }), (0, react.createElement)(ImportPanel, {
1986
+ })), (0, react.createElement)(ImportPanel, {
1792
1987
  t,
1793
1988
  editable: editable && !busy,
1794
1989
  onImported
@@ -1799,11 +1994,10 @@ function createCardBody(view) {
1799
1994
  onChangeRoot: onRootChange,
1800
1995
  onDeleteRoot: onRootDelete,
1801
1996
  onAddRoot: onRootAdd
1802
- }), (0, react.createElement)("li", { className: "dpic-hint" }, t("footHint")), saveError === "" ? null : (0, react.createElement)("li", { className: "dpic-hint dpic-err" }, `${t("saveFailed")}${saveError}`));
1997
+ }), footHint), saveBar);
1803
1998
  }
1804
1999
  function TemplatesCard(props) {
1805
2000
  const { t } = props;
1806
- const [open, setOpen] = (0, react.useState)(false);
1807
2001
  const [confirmReset, setConfirmReset] = (0, react.useState)(false);
1808
2002
  const [saveError, setSaveError] = (0, react.useState)("");
1809
2003
  const [busy, setBusy] = (0, react.useState)(false);
@@ -1843,34 +2037,7 @@ function TemplatesCard(props) {
1843
2037
  const dirty = JSON.stringify(draft) !== JSON.stringify(templates);
1844
2038
  const rootsDirty = JSON.stringify(sanitizeAllowRoots(rootsDraft)) !== JSON.stringify(snap.allowRoots);
1845
2039
  const anythingDirty = dirty || rootsDirty;
1846
- const draftActions = createDraftActions(t, draft, rootsDraft, setDraft, setRootsDraft);
1847
- const persistActions = createPersistActions({
1848
- t,
1849
- editable,
1850
- dirty,
1851
- rootsDirty,
1852
- anythingDirty,
1853
- confirmReset,
1854
- templates,
1855
- allowRoots: snap.allowRoots,
1856
- draft,
1857
- rootsDraft,
1858
- set: props.set,
1859
- unset: props.unset,
1860
- readBack: props.readBack,
1861
- setDraft,
1862
- setDraftFor,
1863
- setRootsDraft,
1864
- setBusy,
1865
- setSaveError,
1866
- setConfirmReset
1867
- });
1868
- const headerBtn = createCardHeader({
1869
- t,
1870
- open,
1871
- setOpen
1872
- });
1873
- const bodyList = open ? createCardBody({
2040
+ return createCardBody({
1874
2041
  t,
1875
2042
  statusHint,
1876
2043
  draft,
@@ -1881,10 +2048,29 @@ function TemplatesCard(props) {
1881
2048
  busy,
1882
2049
  confirmReset,
1883
2050
  saveError,
1884
- draftActions,
1885
- persistActions
1886
- }) : null;
1887
- return (0, react.createElement)("li", { className: `dpic-card${open ? " dpic-card-open" : ""}` }, headerBtn, bodyList);
2051
+ draftActions: createDraftActions(t, draft, rootsDraft, setDraft, setRootsDraft),
2052
+ persistActions: createPersistActions({
2053
+ t,
2054
+ editable,
2055
+ dirty,
2056
+ rootsDirty,
2057
+ anythingDirty,
2058
+ confirmReset,
2059
+ templates,
2060
+ allowRoots: snap.allowRoots,
2061
+ draft,
2062
+ rootsDraft,
2063
+ set: props.set,
2064
+ unset: props.unset,
2065
+ readBack: props.readBack,
2066
+ setDraft,
2067
+ setDraftFor,
2068
+ setRootsDraft,
2069
+ setBusy,
2070
+ setSaveError,
2071
+ setConfirmReset
2072
+ })
2073
+ });
1888
2074
  }
1889
2075
  const inject = [
1890
2076
  "slots",
@@ -1920,7 +2106,7 @@ function injectDock(ctx, store, t) {
1920
2106
  };
1921
2107
  });
1922
2108
  }
1923
- /** 注入设置页的「模板库」卡(插件自带卡片,宿主不再生成自动表单页)。
2109
+ /** 注入设置页的「角色库」卡(插件自带卡片,宿主不再生成自动表单页)。
1924
2110
  * 这张卡管的就是「模板」下拉与「润色」▾ 共用的那一份列表。
1925
2111
  *
1926
2112
  * scope 作为参数传进来而不是就地取:卡片 inject 闭包里的 set/unset 必须落到
@@ -1950,7 +2136,7 @@ function apply(ctx) {
1950
2136
  ctx.effect(() => {
1951
2137
  const tag = document.createElement("style");
1952
2138
  tag.id = "dir-prep-organize-css";
1953
- tag.textContent = CARD_STYLES;
2139
+ tag.textContent = `${CARD_STYLES}\n${c}`;
1954
2140
  document.head.append(tag);
1955
2141
  return () => {
1956
2142
  tag.remove();
@@ -1964,7 +2150,6 @@ function apply(ctx) {
1964
2150
  injectCard(ctx, store, t, scope);
1965
2151
  }
1966
2152
  exports.apply = apply;
1967
- exports.applyTemplateToDraft = applyTemplateToDraft;
1968
2153
  exports.builtinTemplatesSnapshot = builtinTemplatesSnapshot;
1969
2154
  exports.formatContextSummary = formatContextSummary;
1970
2155
  exports.formatImportSkips = formatImportSkips;