@infinity_cheng/dsh-prompt-editor 0.3.1 → 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/README.md CHANGED
@@ -10,7 +10,7 @@
10
10
 
11
11
  它只改草稿——**不发送、不执行**。草稿已经清楚时返回 `UNCHANGED`;检查不通过时保留原文。
12
12
 
13
- > **Phase 1 已完成**:输入框按钮、选区感知、SSE 流式预览、替换/重试/取消、设置页。没有自动发送,也没有自动应用。
13
+ > **Phase 1 已完成**:输入框按钮、选区感知、SSE 流式预览、inline diff、复制、替换/撤销、停止/重试/取消、设置页。没有自动发送,也没有自动应用。
14
14
 
15
15
  ## 为什么不是“提示词扩写器”
16
16
 
@@ -48,11 +48,14 @@ Client 可以热更新,但 Host 的 JavaScript 模块换代必须**完全退
48
48
 
49
49
  1. 在输入框里输入草稿,或选中其中一段。
50
50
  2. 点输入框右侧的「增强」,或在输入框里按 `⌘E` / `Ctrl+E`(`⌘⇧E` / `Ctrl+Shift+E` 也兼容)。
51
- 3. 预览弹窗会流式显示改写结果;左侧是原文,右侧是改写,下面是确定性检查。
51
+ 3. 预览弹窗默认显示 inline diff(删除划线、新增高亮),可切到「对照」看左右原文/改写;下面是确定性检查。
52
+ 4. 弹窗里可以复制结果、停止生成;替换后 8 秒内可以点「撤销」恢复原文。
52
53
  4. 选 `替换选中` / `替换全文` 才写回草稿;`重试` 可换规则重跑,`取消` 不改任何内容。
53
54
  5. 有选区时只替换选区;没有选区时替换全文。替换后仍可用输入框自己的 `Ctrl+Z` 撤销。
54
55
 
55
- 设置入口:**设置 → 提示词增强**。默认规则保存在本浏览器(`localStorage`),profile 的 `defaultMode` 仍是兜底默认值。
56
+ 设置入口:**设置 → 提示词增强**。默认规则和增强模型都写入当前 DSH profile 的插件配置,输入框按钮和 Agent 工具共用同一个值。
57
+
58
+ 默认规则下面可以开启 **使用增强专用模型**:关闭时跟随当前会话模型;开启后固定使用从 DSH 模型目录里选择的 provider/model。
56
59
 
57
60
  含 `@文件`/链接引用块时,**先选中一段不含引用块的文字**再点增强:只替换选区,引用块原样保留。没有选区或选区包含引用块时,会提示重新选择;全文替换含引用块的草稿仍不支持。
58
61
 
@@ -199,6 +202,9 @@ Safari 验证结果。
199
202
  - id: prompt-editor
200
203
  config:
201
204
  defaultMode: intent-first # intent-first | strict
205
+ useCustomModel: false # true 时使用下面的固定模型
206
+ enhanceProvider: '' # 例如 deepseek-official
207
+ enhanceModel: '' # 例如 deepseek-flash
202
208
  maxDraftChars: 20000
203
209
  maxContextChars: 4000
204
210
  llmTimeoutMs: 120000
@@ -214,6 +220,21 @@ Safari 验证结果。
214
220
  - Host + Client 两半;Client 是 lazy-CJS bundle,无独立构建步骤
215
221
  - Client 槽位:`conversation.input.right`、`settings.section`
216
222
 
223
+ ### 0.4.0
224
+
225
+ 合并发布自 0.3.2 之后的所有本地改动:
226
+
227
+ - **设置持久化**:默认规则从 `localStorage` 迁到当前 profile 的 `defaultMode`,按钮和 Agent 工具共用;通过 DSH settings 服务写入,无需重启插件。
228
+ - **增强专用模型**:设置页可从 DSH 模型目录固定 provider/model;关闭时跟随当前会话模型,未选完整模型时回退。
229
+ - **预览体验**:默认「对照」两栏,可切换「差异」inline diff;新增复制结果、生成中停止;替换后 8 秒内可撤销,引用 chip 不会被破坏。
230
+ - **引用块修复**:快捷键触发前缓存选区;修正 chip 的 detect/clipboard 坐标映射,选中普通文字时只发送选区,跨 chip 选区被拦截。
231
+
232
+ ### 0.3.2 引用块修复
233
+
234
+ - 快捷键触发前缓存选区,避免 `⌘E` 先收掉选区。
235
+ - 修正 chip 的 detect/clipboard 坐标映射,正例只发送选区文本,不再截断。
236
+ - 实测:无选区拦截、跨 chip 选区拦截、正例替换后 chip 保留。
237
+
217
238
  ### 0.3.1 快捷键修复
218
239
 
219
240
  - 主快捷键改为 `⌘E` / `Ctrl+E`,避开 Mac 输入法常吞掉的 Shift+字母;`⌘⇧E` / `Ctrl+Shift+E` 仍兼容。
@@ -235,14 +256,13 @@ Safari 验证结果。
235
256
  - 选区验证:只发送选中的字符,按钮显示「替换选中」,替换后只改选区,前后段落不变。
236
257
  - 关闭预览后焦点回到「增强」按钮;Esc 可关闭,Tab 在弹窗内循环。
237
258
  - 规则切换:`strict` 随请求体发送,预览显示 strict 结果。
238
- - 设置页:出现在「设置 → 提示词增强」,切换默认规则写入 `localStorage`。
259
+ - 设置页:出现在「设置 → 提示词增强」,切换默认规则写入 profile 配置。
239
260
  - 真实 Host 路由:无 API Key 时返回结构化 SSE error;有凭据的 Agent 工具链路已在 Desktop 验证。
240
261
 
241
262
  ## 限制
242
263
 
243
264
  - **显式触发**:不会在每次发送时自动改写。
244
265
  - **含引用块全文替换不支持**:可选中不含引用块的一段增强;引用块本身不会被重写或删除。
245
- - **默认规则存在本浏览器**:设置页写 `localStorage`,不是 profile 配置;profile 的 `defaultMode` 仍是兜底。
246
266
  - **一次模型调用**:每次增强会消耗一次模型请求;硬失败时可能重试一次。
247
267
  - **检查是启发式的**:事实提取覆盖 URL、代码、版本、范围、路径、`@引用`、附件标记;不覆盖所有自然语言事实。
248
268
  - **不自动应用**:预览后必须点「替换选中」/「替换全文」。
@@ -251,7 +271,7 @@ Safari 验证结果。
251
271
  ## Roadmap
252
272
 
253
273
  - **Phase 1(已完成)**:输入框按钮 + 流式预览 + 选区感知 + 设置页
254
- - **Phase 2(进行中)**:快捷键、引用块选区增强已完成;模型选择、设置持久化、inline diff 待做
274
+ - **Phase 2(进行中)**:快捷键、引用块选区增强、设置持久化、增强专用模型、inline diff、复制/撤销/停止已完成;多 chip 边界测试、i18n/深色/窄屏、客户端自动化测试待做
255
275
  - **0.1.x**:收紧 React 升级类任务的长度;让 strict 模式在保持简短的同时补上验收信息
256
276
  - **后续**:规则集切换、A/B、团队词汇表、与提示词库插件联动
257
277
 
@@ -272,7 +292,7 @@ node ~/.dsh/skills/dsh-plugin-development/scripts/check-plugin.mjs .
272
292
  npm pack --dry-run --json
273
293
  ```
274
294
 
275
- 当前结构测试 14 项通过:fixtures、规则契约、解析器、校验器、`UNCHANGED`、事实丢失回退、提问回退、占位符/附件回退、完整性提示、工具注册等。
295
+ 当前结构测试 15 项通过:fixtures、规则契约、解析器、校验器、`UNCHANGED`、事实丢失回退、提问回退、占位符/附件回退、完整性提示、工具注册等。
276
296
 
277
297
  ## 许可证
278
298
 
package/client.js CHANGED
@@ -19,7 +19,7 @@ window.__ModuleLoader__.load({
19
19
  })()
20
20
 
21
21
  const NS = 'prompt-editor'
22
- const MODE_KEY = 'dsh-prompt-editor:mode'
22
+ const MODES = ['intent-first', 'strict']
23
23
  const OPEN_TAG = '<enhanced_prompt>'
24
24
  const CLOSE_TAG = '</enhanced_prompt>'
25
25
  const IS_MAC = typeof navigator !== 'undefined' && /Mac|iPhone|iPad/.test(navigator.platform || '')
@@ -59,15 +59,36 @@ window.__ModuleLoader__.load({
59
59
  'dialog.stale': '草稿已变化,请重新打开。',
60
60
  'dialog.warnings': '校验提示',
61
61
  'dialog.close': '关闭',
62
+ 'dialog.view': '显示方式',
63
+ 'dialog.viewDiff': '差异',
64
+ 'dialog.viewSide': '对照',
65
+ 'dialog.diffTitle': '原文 → 改写',
66
+ 'dialog.diffLegend': '删除 / 新增',
67
+ 'dialog.copy': '复制',
68
+ 'dialog.copied': '已复制',
69
+ 'dialog.stop': '停止',
70
+ 'dialog.stopped': '已停止生成',
71
+ 'undo.done': '已替换',
72
+ 'undo.action': '撤销',
73
+ 'undo.close': '关闭撤销提示',
62
74
  'mode.intent-first': '意图优先',
63
75
  'mode.strict': '最小改动',
64
76
  'settings.nav': '提示词增强',
65
77
  'settings.title': '提示词增强',
66
- 'settings.intro': '设置输入框按钮使用的默认规则。规则只影响改写,不会发送消息。',
78
+ 'settings.intro': '默认规则保存到当前 DSH profile,输入框按钮和 Agent 工具共用。',
67
79
  'settings.mode': '默认规则',
68
80
  'settings.modeHint': '意图优先会补全成任务说明;最小改动只消除歧义。',
69
- 'settings.profileDefault': 'Profile 默认:{mode}',
70
- 'settings.local': '保存在本浏览器;Profile 的 defaultMode 仍是兜底默认值。',
81
+ 'settings.profileDefault': 'Profile 配置:{mode}',
82
+ 'settings.persisted': '保存后写入当前 profile 的插件配置,换浏览器或清缓存都不会丢。',
83
+ 'settings.saving': '保存中…',
84
+ 'settings.saveError': '保存失败:{message}',
85
+ 'settings.modelTitle': '增强模型',
86
+ 'settings.modelHint': '关闭时跟随当前会话模型;开启后固定使用下面的模型。',
87
+ 'settings.useCustomModel': '使用增强专用模型',
88
+ 'settings.modelLoading': '正在读取模型…',
89
+ 'settings.modelLoadError': '模型目录读取失败',
90
+ 'settings.modelPlaceholder': '跟随当前会话模型',
91
+ 'settings.modelChoose': '请选择模型',
71
92
  }
72
93
 
73
94
  function makeText(t) {
@@ -88,38 +109,70 @@ window.__ModuleLoader__.load({
88
109
  }
89
110
  }
90
111
 
91
- function readMode() {
92
- try {
93
- return localStorage.getItem(MODE_KEY) === 'strict' ? 'strict' : 'intent-first'
94
- } catch {
95
- return 'intent-first'
96
- }
97
- }
98
-
99
- function writeMode(mode) {
100
- try {
101
- localStorage.setItem(MODE_KEY, mode === 'strict' ? 'strict' : 'intent-first')
102
- } catch {
103
- // Storage may be disabled; the component still keeps its local state.
104
- }
105
- }
106
-
107
112
  /** Show only the prompt body while the model is still emitting its tagged answer. */
108
- /** Chip ranges in draft coordinates; tolerate the old offset/length shape. */
109
- function chipRanges(occurrences) {
110
- return (Array.isArray(occurrences) ? occurrences : [])
113
+ /**
114
+ * Map clipboard-text coordinates (the draft string) to the editor's
115
+ * detect coordinates (a chip is one character) and back. Selection spans
116
+ * and insertText use detect coordinates; the model needs clipboard text.
117
+ */
118
+ function draftSegments(draft, occurrences) {
119
+ const chips = (Array.isArray(occurrences) ? occurrences : [])
111
120
  .map((chip) => {
112
- const start = Number.isFinite(chip?.start) ? chip.start : chip?.offset
113
- const end = Number.isFinite(chip?.end)
114
- ? chip.end
115
- : (Number.isFinite(start) && Number.isFinite(chip?.length) ? start + chip.length : undefined)
116
- return { start, end }
121
+ const offset = Number.isFinite(chip?.offset) ? chip.offset : chip?.start
122
+ const length = Number.isFinite(chip?.length)
123
+ ? chip.length
124
+ : (Number.isFinite(chip?.end) && Number.isFinite(offset) ? chip.end - offset : chip?.clipboardText?.length)
125
+ return { offset, length }
117
126
  })
118
- .filter((chip) => Number.isFinite(chip.start) && Number.isFinite(chip.end) && chip.end > chip.start)
127
+ .filter((chip) => Number.isFinite(chip.offset) && Number.isFinite(chip.length)
128
+ && chip.offset >= 0 && chip.length > 0)
129
+ .sort((a, b) => a.offset - b.offset)
130
+
131
+ const segments = []
132
+ let detectCursor = 0
133
+ let clipCursor = 0
134
+ let shift = 0
135
+ for (const chip of chips) {
136
+ if (chip.offset > clipCursor) {
137
+ const length = chip.offset - clipCursor
138
+ segments.push({
139
+ kind: 'text',
140
+ detectStart: detectCursor,
141
+ detectEnd: detectCursor + length,
142
+ clipStart: clipCursor,
143
+ clipEnd: chip.offset,
144
+ })
145
+ detectCursor += length
146
+ }
147
+ const detectStart = chip.offset - shift
148
+ segments.push({
149
+ kind: 'chip',
150
+ detectStart,
151
+ detectEnd: detectStart + 1,
152
+ clipStart: chip.offset,
153
+ clipEnd: chip.offset + chip.length,
154
+ })
155
+ detectCursor = detectStart + 1
156
+ clipCursor = chip.offset + chip.length
157
+ shift += chip.length - 1
158
+ }
159
+ if (clipCursor < draft.length) {
160
+ const length = draft.length - clipCursor
161
+ segments.push({
162
+ kind: 'text',
163
+ detectStart: detectCursor,
164
+ detectEnd: detectCursor + length,
165
+ clipStart: clipCursor,
166
+ clipEnd: draft.length,
167
+ })
168
+ }
169
+ return segments
119
170
  }
120
171
 
121
- function overlapsChip(chips, span) {
122
- return chips.some((chip) => span.start < chip.end && span.end > chip.start)
172
+ function textSegmentFor(segments, span) {
173
+ return segments.find((segment) => segment.kind === 'text'
174
+ && span.start >= segment.detectStart && span.end <= segment.detectEnd
175
+ && span.end > span.start)
123
176
  }
124
177
 
125
178
  function visibleText(raw) {
@@ -204,9 +257,26 @@ window.__ModuleLoader__.load({
204
257
  .dsh-prompt-editor-btn:disabled{opacity:.45;cursor:default}
205
258
  .dsh-prompt-editor-btnPrimary{border-color:transparent;background:var(--dsw-alias-button-primary-fill,var(--dsw-alias-brand-primary-new-colorprimary-new-color,#2f6fed));color:var(--dsw-alias-label-on-color,#fff)}
206
259
  .dsh-prompt-editor-btnPrimary:hover:not(:disabled){background:var(--dsw-alias-button-primary-fill,var(--dsw-alias-brand-primary-new-colorprimary-new-color,#2f6fed));filter:brightness(1.05)}
260
+ .dsh-prompt-editor-viewToggle{display:inline-flex;padding:2px;border:1px solid var(--dsw-alias-border-l1);border-radius:8px;background:var(--dsw-alias-bg-layer-1)}
261
+ .dsh-prompt-editor-viewToggle button{height:24px;padding:0 8px;border:0;border-radius:6px;background:transparent;color:var(--dsw-alias-label-secondary);font:inherit;font-size:11px;cursor:pointer}
262
+ .dsh-prompt-editor-viewToggle button[aria-pressed="true"]{background:var(--dsw-alias-bg-base);color:var(--dsw-alias-label-primary);box-shadow:0 1px 2px rgba(0,0,0,.12)}
263
+ .dsh-prompt-editor-diffPane{grid-column:1/-1}
264
+ .dsh-prompt-editor-diffHead{display:flex;align-items:center;justify-content:space-between;gap:8px}
265
+ .dsh-prompt-editor-diffLegend{color:var(--dsw-alias-label-secondary);font-size:11px}
266
+ .dsh-prompt-editor-diffPre ins{padding:0 2px;border-radius:3px;background:rgba(46,160,67,.18);color:inherit;text-decoration:none}
267
+ .dsh-prompt-editor-diffPre del{padding:0 2px;border-radius:3px;background:rgba(248,81,73,.16);color:var(--dsw-alias-label-secondary);text-decoration:line-through}
268
+ .dsh-prompt-editor-undoToast{position:fixed;right:24px;bottom:96px;z-index:1000;display:flex;align-items:center;gap:10px;padding:8px 10px 8px 12px;border:1px solid var(--dsw-alias-border-l1);border-radius:10px;background:var(--dsw-alias-bg-base);color:var(--dsw-alias-label-primary);box-shadow:0 8px 30px rgba(0,0,0,.2);font-size:12px}
269
+ .dsh-prompt-editor-undoToast button{height:26px;padding:0 8px;border:1px solid var(--dsw-alias-border-l1);border-radius:7px;background:var(--dsw-alias-bg-layer-1);color:var(--dsw-alias-label-primary);font:inherit;font-size:12px;cursor:pointer}
270
+ .dsh-prompt-editor-undoToast button:hover{background:var(--dsw-alias-interactive-bg-hover)}
271
+ .dsh-prompt-editor-undoToast .dsh-prompt-editor-iconBtn{width:24px;height:24px;border-color:transparent}
207
272
  .dsh-prompt-editor-settings{display:flex;flex-direction:column;gap:10px;max-width:760px}
208
273
  .dsh-prompt-editor-settings h2{margin:0;font-size:14px;line-height:22px;font-weight:600;color:var(--dsw-alias-label-primary)}
209
274
  .dsh-prompt-editor-settings p{margin:0;color:var(--dsw-alias-label-secondary);font-size:12px;line-height:18px}
275
+ .dsh-prompt-editor-settings .dsh-prompt-editor-error{margin:0}
276
+ .dsh-prompt-editor-settingsControl{display:flex;align-items:center;gap:10px;flex-wrap:wrap;justify-content:flex-end}
277
+ .dsh-prompt-editor-settingsModel{max-width:300px}
278
+ .dsh-prompt-editor-checkbox{width:16px;height:16px;margin:0;accent-color:var(--dsw-alias-brand-primary-new-colorprimary-new-color,#2f6fed);cursor:pointer}
279
+ .dsh-prompt-editor-toggle{display:inline-flex;align-items:center;gap:7px;color:var(--dsw-alias-label-primary);font-size:12px;cursor:pointer;user-select:none}
210
280
  .dsh-prompt-editor-settingsRow{display:flex;align-items:center;justify-content:space-between;gap:16px;padding:12px 14px;border:1px solid var(--dsw-alias-border-l1);border-radius:10px;background:var(--dsw-alias-bg-layer-1)}
211
281
  .dsh-prompt-editor-settingsCopy{display:flex;flex-direction:column;gap:2px;min-width:0}
212
282
  .dsh-prompt-editor-settingsTitle{color:var(--dsw-alias-label-primary);font-size:13px;line-height:20px;font-weight:500}
@@ -228,14 +298,109 @@ window.__ModuleLoader__.load({
228
298
  h('path', { d: 'M4 20l4.2-1.1L20 7.1 16.9 4 5.1 15.8 4 20z' }),
229
299
  h('path', { d: 'M14.5 6.5l3 3' }))
230
300
 
231
- function PreviewDialog({ state, text, onClose, onAccept, onRetry, onMode }) {
301
+ function diffTokens(before, after) {
302
+ const tokenize = (value) => value.match(/[\p{Script=Han}]|[A-Za-z0-9_]+|[ \t]+|\n|[^\s]/gu) ?? []
303
+ const a = tokenize(before)
304
+ const b = tokenize(after)
305
+ if (a.length * b.length > 2_500_000) {
306
+ return [
307
+ ...(before === '' ? [] : [{ type: 'del', text: before }]),
308
+ ...(after === '' ? [] : [{ type: 'ins', text: after }]),
309
+ ]
310
+ }
311
+ const width = b.length + 1
312
+ const dp = new Uint32Array((a.length + 1) * width)
313
+ for (let i = a.length - 1; i >= 0; i -= 1) {
314
+ for (let j = b.length - 1; j >= 0; j -= 1) {
315
+ dp[i * width + j] = a[i] === b[j]
316
+ ? dp[(i + 1) * width + j + 1] + 1
317
+ : Math.max(dp[(i + 1) * width + j], dp[i * width + j + 1])
318
+ }
319
+ }
320
+ const ops = []
321
+ let i = 0
322
+ let j = 0
323
+ while (i < a.length && j < b.length) {
324
+ if (a[i] === b[j]) {
325
+ ops.push({ type: 'equal', text: a[i] })
326
+ i += 1
327
+ j += 1
328
+ } else if (dp[(i + 1) * width + j] >= dp[i * width + j + 1]) {
329
+ ops.push({ type: 'del', text: a[i] })
330
+ i += 1
331
+ } else {
332
+ ops.push({ type: 'ins', text: b[j] })
333
+ j += 1
334
+ }
335
+ }
336
+ while (i < a.length) {
337
+ ops.push({ type: 'del', text: a[i] })
338
+ i += 1
339
+ }
340
+ while (j < b.length) {
341
+ ops.push({ type: 'ins', text: b[j] })
342
+ j += 1
343
+ }
344
+ const merged = []
345
+ for (const op of ops) {
346
+ const last = merged[merged.length - 1]
347
+ if (last !== undefined && last.type === op.type) last.text += op.text
348
+ else merged.push({ ...op })
349
+ }
350
+ return merged
351
+ }
352
+
353
+ function InlineDiff({ before, after }) {
354
+ const ops = useMemo(() => diffTokens(before, after), [before, after])
355
+ return h('pre', { className: 'dsh-prompt-editor-pre dsh-prompt-editor-diffPre', tabIndex: 0 },
356
+ ops.map((op, index) => op.type === 'equal'
357
+ ? h('span', { key: index }, op.text)
358
+ : h(op.type === 'del' ? 'del' : 'ins', { key: index }, op.text)))
359
+ }
360
+
361
+ async function copyToClipboard(value) {
362
+ try {
363
+ if (typeof navigator !== 'undefined' && navigator.clipboard?.writeText !== undefined) {
364
+ await navigator.clipboard.writeText(value)
365
+ return true
366
+ }
367
+ } catch {
368
+ // Fall through to the DOM copy path.
369
+ }
370
+ try {
371
+ const area = document.createElement('textarea')
372
+ area.value = value
373
+ area.setAttribute('readonly', '')
374
+ area.style.position = 'fixed'
375
+ area.style.opacity = '0'
376
+ document.body.appendChild(area)
377
+ area.select()
378
+ const ok = document.execCommand('copy')
379
+ area.remove()
380
+ return ok
381
+ } catch {
382
+ return false
383
+ }
384
+ }
385
+
386
+ function PreviewDialog({ state, text, onClose, onAccept, onRetry, onMode, onStop }) {
232
387
  const acceptRef = useRef(null)
233
388
  const cancelRef = useRef(null)
389
+ const stopRef = useRef(null)
234
390
  const dialogRef = useRef(null)
391
+ const copiedTimerRef = useRef(null)
392
+ const [view, setView] = useState('side')
393
+ const [copied, setCopied] = useState(false)
394
+
395
+ useEffect(() => () => clearTimeout(copiedTimerRef.current), [])
235
396
 
236
397
  useEffect(() => {
237
398
  const timer = setTimeout(() => {
238
399
  if (state.loading) {
400
+ if (stopRef.current !== null && stopRef.current.disabled === false) {
401
+ stopRef.current.focus?.()
402
+ return
403
+ }
239
404
  cancelRef.current?.focus?.()
240
405
  return
241
406
  }
@@ -245,25 +410,33 @@ window.__ModuleLoader__.load({
245
410
  target?.focus?.()
246
411
  }, 30)
247
412
  return () => clearTimeout(timer)
248
- }, [state.loading, state.result])
413
+ }, [state.loading, state.result, state.stopped])
414
+
415
+ useEffect(() => {
416
+ setCopied(false)
417
+ }, [state.result])
249
418
 
250
419
  const result = state.result
251
420
  const enhanced = result?.prompt ?? visibleText(state.raw)
252
421
  const fallback = result?.status === 'fallback'
253
422
  const unchanged = result !== null && result.changed === false && !fallback
423
+ const stopped = state.stopped === true
254
424
  const canAccept = result !== null && result.changed === true && !fallback && state.loading !== true
425
+ const canCopy = result !== null && state.loading !== true
255
426
  const warningCount = result?.warnings?.length ?? 0
256
427
  const statusText = state.loading
257
428
  ? text('dialog.loading')
258
- : state.error !== null
259
- ? text('dialog.failed')
260
- : fallback
261
- ? text('dialog.fallback')
262
- : unchanged
263
- ? text('dialog.unchanged')
264
- : result !== null
265
- ? text('dialog.done', { count: warningCount })
266
- : ''
429
+ : stopped
430
+ ? text('dialog.stopped')
431
+ : state.error !== null
432
+ ? text('dialog.failed')
433
+ : fallback
434
+ ? text('dialog.fallback')
435
+ : unchanged
436
+ ? text('dialog.unchanged')
437
+ : result !== null
438
+ ? text('dialog.done', { count: warningCount })
439
+ : ''
267
440
  const acceptLabel = fallback
268
441
  ? text('dialog.fallbackShort')
269
442
  : unchanged
@@ -272,6 +445,64 @@ window.__ModuleLoader__.load({
272
445
  ? text('dialog.replaceSelection')
273
446
  : text('dialog.replaceWhole')
274
447
 
448
+ const copy = async () => {
449
+ if (!canCopy || result === null) return
450
+ const ok = await copyToClipboard(result.prompt)
451
+ if (!ok) return
452
+ setCopied(true)
453
+ clearTimeout(copiedTimerRef.current)
454
+ copiedTimerRef.current = setTimeout(() => setCopied(false), 1500)
455
+ }
456
+
457
+ const viewToggle = h('div', {
458
+ className: 'dsh-prompt-editor-viewToggle',
459
+ role: 'group',
460
+ 'aria-label': text('dialog.view'),
461
+ },
462
+ h('button', {
463
+ type: 'button',
464
+ 'aria-pressed': view === 'side' ? 'true' : 'false',
465
+ onClick: () => setView('side'),
466
+ }, text('dialog.viewSide')),
467
+ h('button', {
468
+ type: 'button',
469
+ 'aria-pressed': view === 'diff' ? 'true' : 'false',
470
+ onClick: () => setView('diff'),
471
+ }, text('dialog.viewDiff')))
472
+
473
+ const loadingPane = h('div', { className: 'dsh-prompt-editor-loading' },
474
+ h('span', { className: 'dsh-prompt-editor-dots' }, text('dialog.loading')))
475
+
476
+ const diffPane = h('section', { className: 'dsh-prompt-editor-pane dsh-prompt-editor-diffPane' },
477
+ h('div', { className: 'dsh-prompt-editor-diffHead' },
478
+ h('h3', { className: 'dsh-prompt-editor-paneTitle' }, text('dialog.diffTitle')),
479
+ h('span', { className: 'dsh-prompt-editor-diffLegend' }, text('dialog.diffLegend'))),
480
+ state.loading && enhanced === ''
481
+ ? loadingPane
482
+ : state.error !== null && result === null && enhanced === ''
483
+ ? h('pre', { className: 'dsh-prompt-editor-pre', tabIndex: 0 }, text('dialog.failed'))
484
+ : enhanced === '' && stopped
485
+ ? h('pre', { className: 'dsh-prompt-editor-pre', tabIndex: 0 }, text('dialog.stopped'))
486
+ : h(InlineDiff, { before: state.source, after: enhanced }))
487
+
488
+ const sidePanes = [
489
+ h('section', { key: 'original', className: 'dsh-prompt-editor-pane' },
490
+ h('h3', { className: 'dsh-prompt-editor-paneTitle' }, text('dialog.original')),
491
+ h('pre', { className: 'dsh-prompt-editor-pre', tabIndex: 0 }, state.source)),
492
+ h('section', { key: 'enhanced', className: 'dsh-prompt-editor-pane' },
493
+ h('h3', { className: 'dsh-prompt-editor-paneTitle' }, text('dialog.enhanced')),
494
+ state.loading && enhanced === ''
495
+ ? loadingPane
496
+ : h('pre', { className: 'dsh-prompt-editor-pre', tabIndex: 0 },
497
+ enhanced !== ''
498
+ ? enhanced
499
+ : state.error !== null
500
+ ? text('dialog.failed')
501
+ : stopped
502
+ ? text('dialog.stopped')
503
+ : (unchanged ? text('dialog.unchanged') : text('dialog.loading')))),
504
+ ]
505
+
275
506
  const dialog = h('div', {
276
507
  className: 'dsh-prompt-editor-overlay',
277
508
  role: 'presentation',
@@ -311,6 +542,7 @@ window.__ModuleLoader__.load({
311
542
  ? text('dialog.selection', { count: state.source.length })
312
543
  : text('dialog.whole'))),
313
544
  h('div', { className: 'dsh-prompt-editor-headActions' },
545
+ viewToggle,
314
546
  h('label', { className: 'dsh-prompt-editor-modeLabel' },
315
547
  text('dialog.mode'),
316
548
  h('select', {
@@ -330,20 +562,7 @@ window.__ModuleLoader__.load({
330
562
  onClick: onClose,
331
563
  }, '×'))),
332
564
  h('div', { className: 'dsh-prompt-editor-body' },
333
- h('section', { className: 'dsh-prompt-editor-pane' },
334
- h('h3', { className: 'dsh-prompt-editor-paneTitle' }, text('dialog.original')),
335
- h('pre', { className: 'dsh-prompt-editor-pre', tabIndex: 0 }, state.source)),
336
- h('section', { className: 'dsh-prompt-editor-pane' },
337
- h('h3', { className: 'dsh-prompt-editor-paneTitle' }, text('dialog.enhanced')),
338
- state.loading && enhanced === ''
339
- ? h('div', { className: 'dsh-prompt-editor-loading' },
340
- h('span', { className: 'dsh-prompt-editor-dots' }, text('dialog.loading')))
341
- : h('pre', { className: 'dsh-prompt-editor-pre', tabIndex: 0 },
342
- enhanced !== ''
343
- ? enhanced
344
- : state.error !== null
345
- ? text('dialog.failed')
346
- : (unchanged ? text('dialog.unchanged') : text('dialog.loading'))))),
565
+ view === 'diff' ? diffPane : sidePanes),
347
566
  result?.warnings?.length > 0
348
567
  ? h('div', { className: 'dsh-prompt-editor-warnings' },
349
568
  h('p', { className: 'dsh-prompt-editor-warningsTitle' }, text('dialog.warnings')),
@@ -366,9 +585,22 @@ window.__ModuleLoader__.load({
366
585
  h('button', {
367
586
  type: 'button',
368
587
  className: 'dsh-prompt-editor-btn',
369
- disabled: state.loading || state.retryable === false,
370
- onClick: onRetry,
371
- }, text('dialog.retry')),
588
+ disabled: !canCopy,
589
+ onClick: () => { void copy() },
590
+ }, copied ? text('dialog.copied') : text('dialog.copy')),
591
+ state.loading
592
+ ? h('button', {
593
+ ref: stopRef,
594
+ type: 'button',
595
+ className: 'dsh-prompt-editor-btn',
596
+ onClick: onStop,
597
+ }, text('dialog.stop'))
598
+ : h('button', {
599
+ type: 'button',
600
+ className: 'dsh-prompt-editor-btn',
601
+ disabled: state.retryable === false,
602
+ onClick: onRetry,
603
+ }, text('dialog.retry')),
372
604
  h('button', {
373
605
  ref: acceptRef,
374
606
  type: 'button',
@@ -390,13 +622,37 @@ window.__ModuleLoader__.load({
390
622
 
391
623
  const [open, setOpen] = useState(false)
392
624
  const [state, setState] = useState(null)
625
+ const [defaultMode, setDefaultMode] = useState('intent-first')
626
+ const [undo, setUndo] = useState(null)
393
627
  const abortRef = useRef(null)
628
+ const undoTimerRef = useRef(null)
394
629
  const mountedRef = useRef(true)
395
630
  const triggerRef = useRef(null)
631
+ const selectionCacheRef = useRef(null)
396
632
 
397
633
  useEffect(() => () => {
398
634
  mountedRef.current = false
399
635
  abortRef.current?.abort()
636
+ clearTimeout(undoTimerRef.current)
637
+ }, [])
638
+
639
+ useEffect(() => {
640
+ let cancelled = false
641
+ fetch('/api/prompt-editor/settings', { credentials: 'same-origin' })
642
+ .then((response) => response.ok ? response.json() : null)
643
+ .then((body) => {
644
+ if (cancelled || body?.ok !== true) return
645
+ if (MODES.includes(body.values?.defaultMode)) setDefaultMode(body.values.defaultMode)
646
+ })
647
+ .catch(() => {})
648
+ const onMode = (event) => {
649
+ if (MODES.includes(event?.detail)) setDefaultMode(event.detail)
650
+ }
651
+ window.addEventListener('dsh-prompt-editor:mode', onMode)
652
+ return () => {
653
+ cancelled = true
654
+ window.removeEventListener('dsh-prompt-editor:mode', onMode)
655
+ }
400
656
  }, [])
401
657
 
402
658
  const close = useCallback(() => {
@@ -423,7 +679,7 @@ window.__ModuleLoader__.load({
423
679
  abortRef.current?.abort()
424
680
  const controller = new AbortController()
425
681
  abortRef.current = controller
426
- setState({ source, span, selected, mode, context, raw: '', result: null, error: null, loading: true, retryable: true })
682
+ setState({ source, span, selected, mode, context, raw: '', result: null, error: null, loading: true, retryable: true, stopped: false })
427
683
  let sawDone = false
428
684
 
429
685
  try {
@@ -457,10 +713,10 @@ window.__ModuleLoader__.load({
457
713
  }
458
714
  if (event.type === 'reset') return { ...previous, raw: '' }
459
715
  if (event.type === 'done') {
460
- return { ...previous, result: event, raw: event.prompt ?? previous.raw, error: null, loading: false }
716
+ return { ...previous, result: event, raw: event.prompt ?? previous.raw, error: null, loading: false, stopped: false }
461
717
  }
462
718
  if (event.type === 'error') {
463
- return { ...previous, error: typeof event.message === 'string' ? event.message : 'unknown error', loading: false }
719
+ return { ...previous, error: typeof event.message === 'string' ? event.message : 'unknown error', loading: false, stopped: false }
464
720
  }
465
721
  return previous
466
722
  })
@@ -481,22 +737,23 @@ window.__ModuleLoader__.load({
481
737
  }
482
738
  }, [props.sessionId, text])
483
739
 
484
- const openDialog = useCallback(() => {
740
+ const openDialog = useCallback((providedSpan) => {
485
741
  if (inputActions === undefined || typeof inputActions.captureInsertion !== 'function') return
486
- let span
487
- try {
488
- span = inputActions.captureInsertion()
489
- } catch {
490
- return
742
+ let span = providedSpan
743
+ if (span === undefined || span === null) {
744
+ try {
745
+ span = inputActions.captureInsertion()
746
+ } catch {
747
+ return
748
+ }
491
749
  }
492
750
  if (span === null || span === undefined || !Number.isFinite(span.start) || !Number.isFinite(span.end)) return
493
751
  if (span.draftRev !== undefined && draftRev !== undefined && span.draftRev !== draftRev) return
494
752
  const selected = span.end > span.start
495
- const source = selected ? draft.slice(span.start, span.end) : draft
496
- if (source.trim() === '') return
497
- const chips = chipRanges(occurrences)
498
- const mode = readMode()
499
- if (chips.length > 0 && !selected) {
753
+ const segments = draftSegments(draft, occurrences)
754
+ const hasChips = segments.some((segment) => segment.kind === 'chip')
755
+ const mode = defaultMode
756
+ if (hasChips && !selected) {
500
757
  setOpen(true)
501
758
  setState({
502
759
  source: draft, span, selected: false, mode, context: undefined, raw: '',
@@ -504,17 +761,49 @@ window.__ModuleLoader__.load({
504
761
  })
505
762
  return
506
763
  }
507
- if (chips.length > 0 && overlapsChip(chips, span)) {
508
- setOpen(true)
509
- setState({
510
- source, span, selected: true, mode, context: undefined, raw: '',
511
- result: null, error: text('dialog.chipsOverlap'), loading: false, retryable: false,
512
- })
513
- return
764
+ let source = draft
765
+ if (selected) {
766
+ const segment = textSegmentFor(segments, span)
767
+ if (hasChips && segment === undefined) {
768
+ setOpen(true)
769
+ setState({
770
+ source: draft.slice(span.start, span.end), span, selected: true, mode, context: undefined, raw: '',
771
+ result: null, error: text('dialog.chipsOverlap'), loading: false, retryable: false,
772
+ })
773
+ return
774
+ }
775
+ source = segment === undefined
776
+ ? draft.slice(span.start, span.end)
777
+ : draft.slice(
778
+ segment.clipStart + (span.start - segment.detectStart),
779
+ segment.clipStart + (span.end - segment.detectStart),
780
+ )
514
781
  }
782
+ if (source.trim() === '') return
515
783
  setOpen(true)
516
- run(source, span, selected, mode, chips.length > 0 ? draft : undefined)
517
- }, [draft, draftRev, inputActions, occurrences, run, text])
784
+ run(source, span, selected, mode, hasChips ? draft : undefined)
785
+ }, [draft, draftRev, defaultMode, inputActions, occurrences, run, text])
786
+
787
+ useEffect(() => {
788
+ if (inputActions === undefined || typeof inputActions.captureInsertion !== 'function') return undefined
789
+ const remember = () => {
790
+ try {
791
+ const span = inputActions.captureInsertion()
792
+ if (span !== null && span !== undefined && span.end > span.start) selectionCacheRef.current = span
793
+ } catch {
794
+ // The editor may be between revisions; keep the last good selection.
795
+ }
796
+ }
797
+ const clear = () => {
798
+ selectionCacheRef.current = null
799
+ }
800
+ document.addEventListener('selectionchange', remember)
801
+ window.addEventListener('pointerdown', clear, true)
802
+ return () => {
803
+ document.removeEventListener('selectionchange', remember)
804
+ window.removeEventListener('pointerdown', clear, true)
805
+ }
806
+ }, [inputActions])
518
807
 
519
808
  useEffect(() => {
520
809
  const onKey = (event) => {
@@ -526,7 +815,18 @@ window.__ModuleLoader__.load({
526
815
  if (target.closest('[contenteditable="true"]') === null
527
816
  && target.closest('.dsh-prompt-editor-trigger') === null) return
528
817
  event.preventDefault()
529
- openDialog()
818
+ let current
819
+ try {
820
+ current = inputActions.captureInsertion()
821
+ } catch {
822
+ current = undefined
823
+ }
824
+ const cached = selectionCacheRef.current
825
+ const span = current !== undefined && current !== null && current.end > current.start
826
+ ? current
827
+ : (cached !== null && cached.draftRev === draftRev ? cached : current)
828
+ selectionCacheRef.current = null
829
+ openDialog(span)
530
830
  }
531
831
  window.addEventListener('keydown', onKey, true)
532
832
  return () => window.removeEventListener('keydown', onKey, true)
@@ -547,10 +847,66 @@ window.__ModuleLoader__.load({
547
847
  } catch {
548
848
  accepted = false
549
849
  }
550
- if (accepted) close()
551
- else setState((previous) => previous === null ? previous : { ...previous, error: text('dialog.stale') })
850
+ if (accepted) {
851
+ let rev
852
+ try {
853
+ rev = inputActions.captureInsertion()?.draftRev
854
+ } catch {
855
+ rev = undefined
856
+ }
857
+ if (Number.isFinite(rev)) {
858
+ clearTimeout(undoTimerRef.current)
859
+ setUndo({
860
+ source: state.source,
861
+ start: span.start,
862
+ length: state.result.prompt.length,
863
+ draftRev: rev,
864
+ })
865
+ undoTimerRef.current = setTimeout(() => setUndo(null), 8000)
866
+ }
867
+ close()
868
+ } else {
869
+ setState((previous) => previous === null ? previous : { ...previous, error: text('dialog.stale') })
870
+ }
552
871
  }, [close, inputActions, state, text])
553
872
 
873
+ const stop = useCallback(() => {
874
+ abortRef.current?.abort()
875
+ abortRef.current = null
876
+ setState((previous) => previous === null ? previous : {
877
+ ...previous,
878
+ loading: false,
879
+ stopped: true,
880
+ error: null,
881
+ retryable: true,
882
+ })
883
+ }, [])
884
+
885
+ const undoReplace = useCallback(() => {
886
+ if (undo === null || inputActions === undefined) return
887
+ let current
888
+ try {
889
+ current = inputActions.captureInsertion()
890
+ } catch {
891
+ return
892
+ }
893
+ clearTimeout(undoTimerRef.current)
894
+ if (current === null || current === undefined || current.draftRev !== undo.draftRev) {
895
+ setUndo(null)
896
+ return
897
+ }
898
+ try {
899
+ inputActions.insertText(undo.source, {
900
+ start: undo.start,
901
+ end: undo.start + undo.length,
902
+ draftRev: current.draftRev,
903
+ })
904
+ } catch {
905
+ // Keep the composer unchanged when the undo span cannot be replaced.
906
+ }
907
+ setUndo(null)
908
+ }, [inputActions, undo])
909
+
554
910
  const retry = useCallback(() => {
555
911
  if (state === null || state.retryable === false) return
556
912
  run(state.source, state.span, state.selected, state.mode, state.context)
@@ -582,14 +938,30 @@ window.__ModuleLoader__.load({
582
938
  title: reason,
583
939
  'aria-label': `${text('button.label')}:${reason}`,
584
940
  onMouseDown: (event) => event.preventDefault(),
585
- onClick: openDialog,
941
+ onClick: () => openDialog(),
586
942
  }, ICON, h('span', null, text('button.label'))),
943
+ undo !== null
944
+ ? h('div', { className: 'dsh-prompt-editor-undoToast', role: 'status' },
945
+ h('span', null, text('undo.done')),
946
+ h('button', { type: 'button', onClick: undoReplace }, text('undo.action')),
947
+ h('button', {
948
+ type: 'button',
949
+ className: 'dsh-prompt-editor-iconBtn',
950
+ 'aria-label': text('undo.close'),
951
+ title: text('undo.close'),
952
+ onClick: () => {
953
+ clearTimeout(undoTimerRef.current)
954
+ setUndo(null)
955
+ },
956
+ }, '×'))
957
+ : null,
587
958
  open && state !== null
588
959
  ? h(PreviewDialog, {
589
960
  state,
590
961
  text,
591
962
  onClose: close,
592
963
  onAccept: accept,
964
+ onStop: stop,
593
965
  onRetry: retry,
594
966
  onMode: changeMode,
595
967
  })
@@ -598,8 +970,17 @@ window.__ModuleLoader__.load({
598
970
 
599
971
  function SettingsPage(props) {
600
972
  const text = useMemo(() => makeText(props.t), [props.t])
601
- const [mode, setMode] = useState(() => readMode())
602
- const [hostMode, setHostMode] = useState(null)
973
+ const [values, setValues] = useState(null)
974
+ const [catalog, setCatalog] = useState({ status: 'loading', groups: [] })
975
+ const [error, setError] = useState(null)
976
+ const [saving, setSaving] = useState(false)
977
+
978
+ const normalize = (raw) => ({
979
+ defaultMode: MODES.includes(raw?.defaultMode) ? raw.defaultMode : 'intent-first',
980
+ useCustomModel: raw?.useCustomModel === true,
981
+ enhanceProvider: typeof raw?.enhanceProvider === 'string' ? raw.enhanceProvider : '',
982
+ enhanceModel: typeof raw?.enhanceModel === 'string' ? raw.enhanceModel : '',
983
+ })
603
984
 
604
985
  useEffect(() => {
605
986
  let cancelled = false
@@ -607,7 +988,7 @@ window.__ModuleLoader__.load({
607
988
  .then((response) => response.ok ? response.json() : null)
608
989
  .then((body) => {
609
990
  if (cancelled || body?.ok !== true) return
610
- setHostMode(body.values?.defaultMode ?? null)
991
+ setValues(normalize(body.values))
611
992
  })
612
993
  .catch(() => {})
613
994
  return () => {
@@ -615,12 +996,85 @@ window.__ModuleLoader__.load({
615
996
  }
616
997
  }, [])
617
998
 
618
- const change = (next) => {
619
- if (next !== 'intent-first' && next !== 'strict') return
620
- setMode(next)
621
- writeMode(next)
999
+ useEffect(() => {
1000
+ let cancelled = false
1001
+ const getRemote = props.getRemote
1002
+ const remote = typeof getRemote === 'function' ? getRemote() : undefined
1003
+ if (remote === undefined || remote === null || typeof remote.modelCatalog !== 'function') {
1004
+ setCatalog({ status: 'error', groups: [] })
1005
+ return undefined
1006
+ }
1007
+ Promise.resolve(remote.modelCatalog())
1008
+ .then((response) => {
1009
+ if (cancelled) return
1010
+ if (response?.ok !== true) throw new Error(response?.error?.message ?? 'catalog unavailable')
1011
+ const groups = (response.value?.groups ?? []).map((group) => ({
1012
+ id: group.id,
1013
+ label: group.name ?? group.label ?? group.id,
1014
+ models: (group.models ?? []).map((model) => ({ id: model.id, name: model.name ?? model.id })),
1015
+ }))
1016
+ setCatalog({ status: 'ready', groups })
1017
+ })
1018
+ .catch(() => {
1019
+ if (!cancelled) setCatalog({ status: 'error', groups: [] })
1020
+ })
1021
+ return () => {
1022
+ cancelled = true
1023
+ }
1024
+ }, [props.getRemote])
1025
+
1026
+ const save = async (patch) => {
1027
+ if (saving) return
1028
+ setSaving(true)
1029
+ setError(null)
1030
+ try {
1031
+ const response = await fetch('/api/prompt-editor/settings', {
1032
+ method: 'POST',
1033
+ credentials: 'same-origin',
1034
+ headers: { 'content-type': 'application/json' },
1035
+ body: JSON.stringify(patch),
1036
+ })
1037
+ let body = null
1038
+ try {
1039
+ body = await response.json()
1040
+ } catch {
1041
+ body = null
1042
+ }
1043
+ if (!response.ok || body?.ok !== true) {
1044
+ throw new Error(body?.error || `HTTP ${response.status}`)
1045
+ }
1046
+ const next = normalize(body.values)
1047
+ setValues(next)
1048
+ if (patch.defaultMode !== undefined) {
1049
+ window.dispatchEvent(new CustomEvent('dsh-prompt-editor:mode', { detail: next.defaultMode }))
1050
+ }
1051
+ } catch (failure) {
1052
+ setError(failure instanceof Error ? failure.message : String(failure))
1053
+ } finally {
1054
+ setSaving(false)
1055
+ }
622
1056
  }
623
1057
 
1058
+ const mode = values?.defaultMode ?? 'intent-first'
1059
+ const useCustomModel = values?.useCustomModel === true
1060
+ const modelValue = values?.enhanceProvider && values?.enhanceModel
1061
+ ? `${values.enhanceProvider}\u0000${values.enhanceModel}`
1062
+ : ''
1063
+ const modelOptions = [
1064
+ h('option', { key: '', value: '' }, catalog.status === 'loading'
1065
+ ? text('settings.modelLoading')
1066
+ : catalog.status === 'error'
1067
+ ? text('settings.modelLoadError')
1068
+ : useCustomModel ? text('settings.modelChoose') : text('settings.modelPlaceholder')),
1069
+ ...catalog.groups.flatMap((group) => group.models.length === 0
1070
+ ? []
1071
+ : [h('optgroup', { key: group.id, label: group.label },
1072
+ ...group.models.map((model) => h('option', {
1073
+ key: `${group.id}/${model.id}`,
1074
+ value: `${group.id}\u0000${model.id}`,
1075
+ }, model.name)))]),
1076
+ ]
1077
+
624
1078
  return h('div', { className: 'dsh-prompt-editor-settings' },
625
1079
  h('style', {}, CSS),
626
1080
  h('h2', null, text('settings.title')),
@@ -632,22 +1086,59 @@ window.__ModuleLoader__.load({
632
1086
  h('select', {
633
1087
  className: 'dsh-prompt-editor-select',
634
1088
  value: mode,
1089
+ disabled: saving || values === null,
635
1090
  'aria-label': text('settings.mode'),
636
- onChange: (event) => change(event.target.value),
1091
+ onChange: (event) => save({ defaultMode: event.target.value }),
637
1092
  },
638
1093
  h('option', { value: 'intent-first' }, text('mode.intent-first')),
639
1094
  h('option', { value: 'strict' }, text('mode.strict')))),
640
- hostMode !== null
1095
+ h('div', { className: 'dsh-prompt-editor-settingsRow' },
1096
+ h('div', { className: 'dsh-prompt-editor-settingsCopy' },
1097
+ h('span', { className: 'dsh-prompt-editor-settingsTitle' }, text('settings.modelTitle')),
1098
+ h('p', { className: 'dsh-prompt-editor-settingsHint' }, text('settings.modelHint')),
1099
+ h('label', { className: 'dsh-prompt-editor-toggle' },
1100
+ h('input', {
1101
+ type: 'checkbox',
1102
+ className: 'dsh-prompt-editor-checkbox',
1103
+ checked: useCustomModel,
1104
+ disabled: saving || values === null,
1105
+ onChange: (event) => save({ useCustomModel: event.target.checked }),
1106
+ }),
1107
+ text('settings.useCustomModel'))),
1108
+ h('div', { className: 'dsh-prompt-editor-settingsControl' },
1109
+ h('select', {
1110
+ className: 'dsh-prompt-editor-select dsh-prompt-editor-settingsModel',
1111
+ value: modelValue,
1112
+ disabled: saving || values === null || !useCustomModel || catalog.status !== 'ready',
1113
+ 'aria-label': text('settings.modelTitle'),
1114
+ onChange: (event) => {
1115
+ const raw = event.target.value
1116
+ if (raw === '') {
1117
+ save({ enhanceProvider: '', enhanceModel: '' })
1118
+ return
1119
+ }
1120
+ const [provider, model] = raw.split('\u0000')
1121
+ save({ enhanceProvider: provider, enhanceModel: model })
1122
+ },
1123
+ }, modelOptions))),
1124
+ values !== null
641
1125
  ? h('p', null, text('settings.profileDefault', {
642
- mode: hostMode === 'strict' ? text('mode.strict') : text('mode.intent-first'),
1126
+ mode: values.defaultMode === 'strict' ? text('mode.strict') : text('mode.intent-first'),
643
1127
  }))
644
1128
  : null,
645
- h('p', null, text('settings.local')))
1129
+ h('p', null, text('settings.persisted')),
1130
+ saving ? h('p', { role: 'status' }, text('settings.saving')) : null,
1131
+ error !== null
1132
+ ? h('p', { role: 'alert', className: 'dsh-prompt-editor-error' }, text('settings.saveError', { message: error }))
1133
+ : null)
646
1134
  }
647
1135
 
648
1136
  return {
649
- inject: ['slots'],
1137
+ inject: ['slots', 'remote', 'remote.session'],
650
1138
  apply(ctx) {
1139
+ const getSessionRemote = () => ctx.remote.session
1140
+ const Settings = (props) => h(SettingsPage, { ...props, getRemote: getSessionRemote })
1141
+
651
1142
  ctx.slots.inject('conversation.input.right', () => ctx.slots.register({
652
1143
  name: 'conversation.input.right',
653
1144
  id: 'prompt-editor',
@@ -661,7 +1152,7 @@ window.__ModuleLoader__.load({
661
1152
  order: 60,
662
1153
  locale: NS,
663
1154
  label: () => FALLBACK['settings.nav'],
664
- }, SettingsPage))
1155
+ }, Settings))
665
1156
  },
666
1157
  }
667
1158
  },
package/index.js CHANGED
@@ -11,7 +11,12 @@ export const inject = ['tools', 'llm', 'agentDefaultModel', 'fs', 'connection']
11
11
 
12
12
  /** User-editable defaults. */
13
13
  export const Config = Schema.object({
14
- defaultMode: Schema.union(MODE_IDS).default('intent-first'),
14
+ // Volatile: the settings service may update it in place; an ordinary field
15
+ // would force a plugin restart on every save.
16
+ defaultMode: Schema.union(MODE_IDS).default('intent-first').extra('volatile', true),
17
+ useCustomModel: Schema.boolean().default(false).extra('volatile', true),
18
+ enhanceProvider: Schema.string().default('').extra('volatile', true),
19
+ enhanceModel: Schema.string().default('').extra('volatile', true),
15
20
  maxDraftChars: Schema.number().default(20000),
16
21
  maxContextChars: Schema.number().default(4000),
17
22
  llmTimeoutMs: Schema.number().default(120000),
@@ -25,7 +30,11 @@ export const Config = Schema.object({
25
30
  * @param {{ defaultMode: string, maxDraftChars: number, maxContextChars: number, llmTimeoutMs: number, maxLengthRatio: number }} config
26
31
  */
27
32
  export function apply(ctx, config) {
28
- if (!MODE_IDS.includes(config.defaultMode)) {
33
+ const initialMode = config.defaultMode !== null && typeof config.defaultMode === 'object'
34
+ && typeof config.defaultMode.get === 'function'
35
+ ? config.defaultMode.get()
36
+ : config.defaultMode
37
+ if (!MODE_IDS.includes(initialMode)) {
29
38
  throw new Error(`defaultMode must be one of: ${MODE_IDS.join(', ')}`)
30
39
  }
31
40
  if (!Number.isSafeInteger(config.maxDraftChars) || config.maxDraftChars < 1000 || config.maxDraftChars > 100000) {
@@ -119,12 +128,9 @@ export function apply(ctx, config) {
119
128
  ctx.effect(
120
129
  () => ctx.connection.fetch.register({
121
130
  path: SETTINGS_PATH,
122
- methods: ['GET'],
131
+ methods: ['GET', 'POST'],
123
132
  requestBody: 'buffered',
124
- fetch: () => Response.json({
125
- ok: true,
126
- values: { defaultMode: config.defaultMode },
127
- }),
133
+ fetch: (request) => handleSettingsRoute(ctx, config, request),
128
134
  }),
129
135
  'prompt-editor: settings route',
130
136
  )
@@ -143,9 +149,142 @@ export function apply(ctx, config) {
143
149
  /** Browser route for the composer button. */
144
150
  const ENHANCE_PATH = '/api/prompt-editor/enhance'
145
151
 
146
- /** Read-only settings route for the settings page. */
152
+ /** Settings route for the settings page. */
147
153
  const SETTINGS_PATH = '/api/prompt-editor/settings'
148
154
 
155
+ /**
156
+ * Live config view. A volatile write mutates the loader entry; the config
157
+ * captured at activation is only the fallback.
158
+ * @param {any} ctx
159
+ * @param {any} config
160
+ */
161
+ function liveConfig(ctx, config) {
162
+ const live = ctx.fiber?.entry?.options?.config
163
+ return live !== null && typeof live === 'object' ? { ...config, ...live } : config
164
+ }
165
+
166
+ /**
167
+ * Resolve the current default mode.
168
+ * @param {any} ctx
169
+ * @param {any} config
170
+ */
171
+ function readRef(value, fallback) {
172
+ return value !== null && typeof value === 'object' && typeof value.get === 'function'
173
+ ? value.get()
174
+ : value ?? fallback
175
+ }
176
+
177
+ function readModeRef(value, fallback) {
178
+ const current = readRef(value, fallback)
179
+ return MODE_IDS.includes(current) ? current : fallback
180
+ }
181
+
182
+ function readSettings(ctx, config) {
183
+ const live = liveConfig(ctx, config)
184
+ return {
185
+ defaultMode: readModeRef(live.defaultMode, readModeRef(config.defaultMode, 'intent-first')),
186
+ useCustomModel: readRef(live.useCustomModel, false) === true,
187
+ enhanceProvider: typeof readRef(live.enhanceProvider, '') === 'string' ? readRef(live.enhanceProvider, '') : '',
188
+ enhanceModel: typeof readRef(live.enhanceModel, '') === 'string' ? readRef(live.enhanceModel, '') : '',
189
+ }
190
+ }
191
+
192
+ function liveDefaultMode(ctx, config) {
193
+ return readSettings(ctx, config).defaultMode
194
+ }
195
+
196
+ /**
197
+ * A custom enhancement model applies only when the switch is on and a full
198
+ * provider/model pair is stored; otherwise the session default is used.
199
+ */
200
+ function resolveModelSelection(ctx, config) {
201
+ const settings = readSettings(ctx, config)
202
+ if (settings.useCustomModel && settings.enhanceProvider !== '' && settings.enhanceModel !== '') {
203
+ return { provider: settings.enhanceProvider, model: settings.enhanceModel }
204
+ }
205
+ return ctx.agentDefaultModel.currentSelection()
206
+ }
207
+
208
+ /**
209
+ * Namespace settings.write() expects: the loader row's short id.
210
+ * @param {any} ctx
211
+ */
212
+ function settingsNamespace(ctx) {
213
+ const shortId = ctx.fiber?.entry?.options?.id
214
+ if (typeof shortId === 'string' && shortId.length > 0) return shortId
215
+ const reported = ctx.get('profileContext')?.entryId
216
+ if (typeof reported === 'string' && reported.length > 0) {
217
+ const parts = reported.split(':')
218
+ return parts[parts.length - 1]
219
+ }
220
+ return undefined
221
+ }
222
+
223
+ /**
224
+ * Read or write the default rule through the profile settings service.
225
+ * @param {any} ctx
226
+ * @param {any} config
227
+ * @param {Request} request
228
+ */
229
+ async function handleSettingsRoute(ctx, config, request) {
230
+ if (request.method === 'GET') {
231
+ return Response.json({ ok: true, values: readSettings(ctx, config) })
232
+ }
233
+
234
+ let payload
235
+ try {
236
+ payload = await request.json()
237
+ } catch {
238
+ return Response.json({ ok: false, error: 'invalid JSON body' }, { status: 400 })
239
+ }
240
+ if (payload === null || typeof payload !== 'object') {
241
+ return Response.json({ ok: false, error: 'invalid settings body' }, { status: 400 })
242
+ }
243
+
244
+ const patch = {}
245
+ if (payload.defaultMode !== undefined) {
246
+ if (!MODE_IDS.includes(payload.defaultMode)) {
247
+ return Response.json({ ok: false, error: `defaultMode must be one of: ${MODE_IDS.join(', ')}` }, { status: 400 })
248
+ }
249
+ patch.defaultMode = payload.defaultMode
250
+ }
251
+ if (payload.useCustomModel !== undefined) {
252
+ if (typeof payload.useCustomModel !== 'boolean') {
253
+ return Response.json({ ok: false, error: 'useCustomModel must be a boolean' }, { status: 400 })
254
+ }
255
+ patch.useCustomModel = payload.useCustomModel
256
+ }
257
+ for (const key of ['enhanceProvider', 'enhanceModel']) {
258
+ if (payload[key] === undefined) continue
259
+ if (typeof payload[key] !== 'string' || payload[key].length > 200) {
260
+ return Response.json({ ok: false, error: `${key} must be a string of at most 200 characters` }, { status: 400 })
261
+ }
262
+ patch[key] = payload[key].trim()
263
+ }
264
+ if (Object.keys(patch).length === 0) {
265
+ return Response.json({ ok: false, error: 'no settings to update' }, { status: 400 })
266
+ }
267
+
268
+ const settings = ctx.get('settings')
269
+ if (settings === undefined || typeof settings.update !== 'function') {
270
+ return Response.json({ ok: false, error: 'settings service is unavailable' }, { status: 503 })
271
+ }
272
+ const ns = settingsNamespace(ctx)
273
+ if (ns === undefined) {
274
+ return Response.json({ ok: false, error: 'cannot locate the plugin settings entry' }, { status: 503 })
275
+ }
276
+
277
+ try {
278
+ await settings.update(ns, patch)
279
+ return Response.json({ ok: true, values: readSettings(ctx, config) })
280
+ } catch (error) {
281
+ return Response.json({
282
+ ok: false,
283
+ error: error instanceof Error ? error.message : String(error),
284
+ }, { status: 500 })
285
+ }
286
+ }
287
+
149
288
  /**
150
289
  * Stream one enhancement to the browser as Server-Sent Events.
151
290
  * `delta` carries raw model text; `done` carries the validated result.
@@ -227,7 +366,7 @@ async function handleEnhanceRoute(ctx, config, request) {
227
366
  export async function enhance(request) {
228
367
  const { ctx, config, signal, onDelta, onReset } = request
229
368
  const draft = normalizeDraft(request.draft, config.maxDraftChars)
230
- const mode = resolveMode(request.mode ?? config.defaultMode)
369
+ const mode = resolveMode(request.mode ?? liveDefaultMode(ctx, config))
231
370
  const language = normalizeLanguage(request.language)
232
371
  const context = (request.context ?? '').trim().slice(0, config.maxContextChars)
233
372
  const baseUser = buildUserMessage({ draft, context, language }) + completenessHint(draft)
@@ -295,7 +434,7 @@ export async function enhance(request) {
295
434
  */
296
435
  async function callModel(request) {
297
436
  const { ctx, config, mode, userMessage, signal, onDelta } = request
298
- const selection = ctx.agentDefaultModel.currentSelection()
437
+ const selection = resolveModelSelection(ctx, config)
299
438
  if (selection?.provider === undefined || selection?.model === undefined) {
300
439
  throw new Error('no default model selection is available')
301
440
  }
package/locale/en.json CHANGED
@@ -32,13 +32,37 @@
32
32
  "done": "Rewrite complete ({count} checks)",
33
33
  "hostMissing": "Host route is not loaded (HTTP 404). Fully quit and reopen DeepSeek Harness so the Host loads 0.2.x.",
34
34
  "chipsSelect": "This draft has reference chips. Select a passage that contains no chip, then enhance.",
35
- "chipsOverlap": "The selection contains a reference chip. Select a passage without chips; chips are preserved."
35
+ "chipsOverlap": "The selection contains a reference chip. Select a passage without chips; chips are preserved.",
36
+ "view": "View",
37
+ "viewDiff": "Diff",
38
+ "viewSide": "Side by side",
39
+ "diffTitle": "Original → rewritten",
40
+ "diffLegend": "removed / added",
41
+ "copy": "Copy",
42
+ "copied": "Copied",
43
+ "stop": "Stop",
44
+ "stopped": "Stopped"
36
45
  },
37
46
  "settings": {
38
47
  "nav": "Prompt editor",
39
48
  "title": "Prompt editor",
40
- "intro": "Choose the default rule for the composer button. It only rewrites; it never sends.",
49
+ "intro": "The default rule is saved in the current DSH profile and shared by the composer button and the Agent tool.",
41
50
  "mode": "Default rule",
42
- "modeHint": "Intent-first expands a thin draft; strict only removes ambiguity."
51
+ "modeHint": "Intent-first expands a thin draft; strict only removes ambiguity.",
52
+ "persisted": "Saved into this profile, so it survives browser changes and cache clears.",
53
+ "saving": "Saving…",
54
+ "saveError": "Save failed: {message}",
55
+ "modelTitle": "Enhancement model",
56
+ "modelHint": "When off, the current session model is used; when on, the model below is fixed.",
57
+ "useCustomModel": "Use a dedicated enhancement model",
58
+ "modelLoading": "Loading models…",
59
+ "modelLoadError": "Could not load the model catalog",
60
+ "modelPlaceholder": "Follow the session model",
61
+ "modelChoose": "Choose a model"
62
+ },
63
+ "undo": {
64
+ "done": "Replaced",
65
+ "action": "Undo",
66
+ "close": "Dismiss undo"
43
67
  }
44
68
  }
package/locale/zh.json CHANGED
@@ -32,13 +32,37 @@
32
32
  "done": "改写完成({count} 条提示)",
33
33
  "hostMissing": "Host 路由未加载(HTTP 404)。请完全退出并重新打开 DeepSeek Harness,让 Host 加载 0.2.x。",
34
34
  "chipsSelect": "草稿含引用块。请先选中一段不含引用块的文字,再点增强。",
35
- "chipsOverlap": "选区包含引用块。请重新选择不含引用块的一段;引用块会原样保留。"
35
+ "chipsOverlap": "选区包含引用块。请重新选择不含引用块的一段;引用块会原样保留。",
36
+ "view": "显示方式",
37
+ "viewDiff": "差异",
38
+ "viewSide": "对照",
39
+ "diffTitle": "原文 → 改写",
40
+ "diffLegend": "删除 / 新增",
41
+ "copy": "复制",
42
+ "copied": "已复制",
43
+ "stop": "停止",
44
+ "stopped": "已停止生成"
36
45
  },
37
46
  "settings": {
38
47
  "nav": "提示词增强",
39
48
  "title": "提示词增强",
40
- "intro": "设置输入框按钮使用的默认规则。规则只影响改写,不会发送消息。",
49
+ "intro": "默认规则保存到当前 DSH profile,输入框按钮和 Agent 工具共用。",
41
50
  "mode": "默认规则",
42
- "modeHint": "意图优先会补全成任务说明;最小改动只消除歧义。"
51
+ "modeHint": "意图优先会补全成任务说明;最小改动只消除歧义。",
52
+ "persisted": "保存后写入当前 profile 的插件配置,换浏览器或清缓存都不会丢。",
53
+ "saving": "保存中…",
54
+ "saveError": "保存失败:{message}",
55
+ "modelTitle": "增强模型",
56
+ "modelHint": "关闭时跟随当前会话模型;开启后固定使用下面的模型。",
57
+ "useCustomModel": "使用增强专用模型",
58
+ "modelLoading": "正在读取模型…",
59
+ "modelLoadError": "模型目录读取失败",
60
+ "modelPlaceholder": "跟随当前会话模型",
61
+ "modelChoose": "请选择模型"
62
+ },
63
+ "undo": {
64
+ "done": "已替换",
65
+ "action": "撤销",
66
+ "close": "关闭撤销提示"
43
67
  }
44
68
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@infinity_cheng/dsh-prompt-editor",
3
- "version": "0.3.1",
3
+ "version": "0.4.0",
4
4
  "description": "Rewrite a rough prompt draft into a clear, executable prompt in DeepSeek Harness: streaming preview, selection-aware replace, and fact-preservation checks.",
5
5
  "icon": "icon.svg",
6
6
  "type": "module",