dsh-oh-my-token 0.0.1 → 0.0.2

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
@@ -23,11 +23,514 @@ window.__ModuleLoader__.load({
23
23
  const STATE_ENDPOINT = '/dsh-oh-my-token/state';
24
24
  const STATS_ENDPOINT = '/dsh-oh-my-token/stats';
25
25
  const PROMPT_ENDPOINT = '/dsh-oh-my-token/prompt';
26
+ const EDIT_ENDPOINT = '/dsh-oh-my-token/edit';
27
+
28
+ // ── In-chat change marks ──────────────────────────────────────────────
29
+ //
30
+ // The model never reads the words the prose step removes, but the person
31
+ // should still see what was cut. Every request's record carries the text it
32
+ // produced; the same text is what the chat displays, so a message can be
33
+ // matched back to its record and the removed words drawn where they were:
34
+ // red and struck through, with any replacement in green.
35
+
36
+ /** Text produced by a recorded change -> its diff segments. */
37
+ const diffByText = new Map();
38
+
39
+ /** Set by `apply`: re-registers the rule so rendered messages re-evaluate. */
40
+ let nudgeDiffRules = null;
41
+
42
+ /** Memoized removals per message text; cleared when the record grows. */
43
+ const removalCache = new Map();
44
+
45
+ /** @returns {boolean} whether anything new was remembered. */
46
+ function rememberDiffs(recent) {
47
+ if (!Array.isArray(recent)) return false;
48
+ let added = false;
49
+ for (const entry of recent) {
50
+ if (typeof entry?.after !== 'string' || entry.after === '') continue;
51
+ if (!Array.isArray(entry.diff)) continue;
52
+ if (diffByText.has(entry.after)) continue;
53
+ diffByText.set(entry.after, entry.diff);
54
+ added = true;
55
+ }
56
+ // A long-lived tab would otherwise keep every message it ever saw.
57
+ while (diffByText.size > 400) diffByText.delete(diffByText.keys().next().value);
58
+ if (added) removalCache.clear();
59
+ return added;
60
+ }
61
+
62
+ /**
63
+ * Chat-written edits keyed by the text they replace: the message still shows
64
+ * that text, so its diff is drawn where it will change on the next request.
65
+ * @returns {boolean} whether anything new was remembered.
66
+ */
67
+ function rememberEdits(list) {
68
+ if (!Array.isArray(list)) return false;
69
+ let added = false;
70
+ for (const entry of list) {
71
+ if (typeof entry?.from !== 'string' || entry.from === '') continue;
72
+ if (!Array.isArray(entry.segments)) continue;
73
+ diffByText.set(entry.from, entry.segments);
74
+ added = true;
75
+ }
76
+ if (added) removalCache.clear();
77
+ return added;
78
+ }
79
+
80
+ /**
81
+ * Where the automatic step cut words out of a message.
82
+ *
83
+ * A record is one changed line, so only a whole line of the body may match
84
+ * it: a sentence quoted inside the reasoning trace is not that line and
85
+ * stays untouched. Each removal hangs on the character next to it, so the
86
+ * mark lands in place without swallowing the text around it.
87
+ */
88
+ function removalsOf(text) {
89
+ const cached = removalCache.get(text);
90
+ if (cached !== undefined) return cached;
91
+ if (diffByText.size === 0) {
92
+ removalCache.set(text, null);
93
+ return null;
94
+ }
95
+ const out = [];
96
+ const whole = diffByText.get(text) ?? diffByText.get(text.trim());
97
+ if (whole !== undefined) {
98
+ collectRemovals(whole, 0, out);
99
+ } else {
100
+ for (const span of lineSpans(text)) {
101
+ const segments = diffByText.get(text.slice(span.start, span.end));
102
+ if (segments !== undefined) collectRemovals(segments, span.start, out);
103
+ }
104
+ }
105
+ if (out.length === 0) {
106
+ removalCache.set(text, null);
107
+ return null;
108
+ }
109
+ out.sort((left, right) => left.start - right.start);
110
+ removalCache.set(text, out);
111
+ while (removalCache.size > 200) removalCache.delete(removalCache.keys().next().value);
112
+ return out;
113
+ }
114
+
115
+ /** One diff's removals, moved to their offsets in the surrounding body. */
116
+ function collectRemovals(segments, base, out) {
117
+ let offset = base;
118
+ let pending = null;
119
+ for (const segment of segments) {
120
+ const value = typeof segment?.text === 'string' ? segment.text : '';
121
+ if (segment?.kind === 'del') {
122
+ if (pending === null) pending = { removed: value, added: '', start: offset };
123
+ else pending.removed += value;
124
+ continue;
125
+ }
126
+ if (segment?.kind === 'add') {
127
+ if (pending !== null) pending.added += value;
128
+ continue;
129
+ }
130
+ if (value === '') continue;
131
+ if (pending !== null) {
132
+ pending.start = offset;
133
+ out.push(pending);
134
+ pending = null;
135
+ }
136
+ offset += value.length;
137
+ }
138
+ if (pending !== null) {
139
+ // A removal at the very end hangs on the character before it.
140
+ pending.start = Math.max(base, offset - 1);
141
+ pending.trailing = true;
142
+ out.push(pending);
143
+ }
144
+ }
145
+
146
+ /** Each non-empty trimmed line of a body, with its offsets in that body. */
147
+ function lineSpans(text) {
148
+ const spans = [];
149
+ let start = 0;
150
+ for (const line of text.split('\n')) {
151
+ const trimmed = line.trim();
152
+ if (trimmed !== '') {
153
+ const lead = line.length - line.trimStart().length;
154
+ spans.push({ start: start + lead, end: start + lead + trimmed.length });
155
+ }
156
+ start += line.length + 1;
157
+ }
158
+ return spans;
159
+ }
160
+
161
+ /**
162
+ * A reply's body is rendered as markdown by the harness, so it has no text
163
+ * hook. Its finished DOM is decorated instead: the words the request drops
164
+ * are put back where they were, red and struck through. A re-render
165
+ * replaces that DOM, and the observer decorates the new copy.
166
+ */
167
+ const MARK_ATTR = 'data-oh-my-token-mark';
168
+ const MARKED_ATTR = 'data-oh-my-token-marked';
169
+ const RED_CSS = 'color:var(--dsw-alias-state-error-primary);text-decoration:line-through;background:rgba(239,68,68,.16);border-radius:3px';
170
+ const GREEN_CSS = 'color:var(--dsw-alias-state-success-primary);font-weight:600;background:rgba(34,197,94,.18);border-radius:3px';
171
+
172
+ /** The body's text and each text node's offset in it. */
173
+ function bodyText(root) {
174
+ const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, {
175
+ acceptNode: (node) => (node.parentElement?.closest(`[${MARK_ATTR}]`) !== null
176
+ ? NodeFilter.FILTER_REJECT
177
+ : NodeFilter.FILTER_ACCEPT),
178
+ });
179
+ const nodes = [];
180
+ let text = '';
181
+ for (let node = walker.nextNode(); node !== null; node = walker.nextNode()) {
182
+ const value = node.nodeValue ?? '';
183
+ if (value === '') continue;
184
+ nodes.push({ node, start: text.length });
185
+ text += value;
186
+ }
187
+ return { text, nodes };
188
+ }
189
+
190
+ /** One text node rebuilt with its removals marked. */
191
+ function markedFragment(value, removals) {
192
+ const fragment = document.createDocumentFragment();
193
+ let cursor = 0;
194
+ for (const removal of removals) {
195
+ if (removal.local < cursor) continue;
196
+ if (removal.local > cursor) fragment.appendChild(document.createTextNode(value.slice(cursor, removal.local)));
197
+ const anchor = value.slice(removal.local, removal.local + 1);
198
+ const removed = document.createElement('span');
199
+ removed.setAttribute(MARK_ATTR, '1');
200
+ removed.style.cssText = RED_CSS;
201
+ removed.textContent = removal.removed;
202
+ const addedNode = () => {
203
+ if (removal.added === '') return null;
204
+ const added = document.createElement('span');
205
+ added.setAttribute(MARK_ATTR, '1');
206
+ added.style.cssText = GREEN_CSS;
207
+ added.textContent = removal.added;
208
+ return added;
209
+ };
210
+ if (removal.trailing === true) {
211
+ fragment.appendChild(document.createTextNode(anchor));
212
+ fragment.appendChild(removed);
213
+ const added = addedNode();
214
+ if (added !== null) fragment.appendChild(added);
215
+ } else {
216
+ fragment.appendChild(removed);
217
+ const added = addedNode();
218
+ if (added !== null) fragment.appendChild(added);
219
+ fragment.appendChild(document.createTextNode(anchor));
220
+ }
221
+ cursor = removal.local + 1;
222
+ }
223
+ if (cursor < value.length) fragment.appendChild(document.createTextNode(value.slice(cursor)));
224
+ return fragment;
225
+ }
226
+
227
+ /** The flow items of the newest turn — the part that is still live. */
228
+ function liveItems() {
229
+ const items = [...document.querySelectorAll('[data-chat-flow-key]')];
230
+ let best = -1;
231
+ for (const item of items) {
232
+ const turn = Number(item.getAttribute('data-chat-turn'));
233
+ if (Number.isFinite(turn) && turn > best) best = turn;
234
+ }
235
+ if (best < 0) return [];
236
+ return items.filter((item) => Number(item.getAttribute('data-chat-turn')) === best);
237
+ }
238
+
239
+ /**
240
+ * Decorate the live turn only: a turn that has moved on is already
241
+ * compressed, so it keeps neither marks nor an edit control and stops
242
+ * paying for them.
243
+ *
244
+ * The reasoning trace is skipped on purpose: the plugin never changes it
245
+ * (its bytes are signed), so a sentence quoted there must not be marked.
246
+ */
247
+ function decorateChat() {
248
+ if (typeof document === 'undefined') return false;
249
+ const items = liveItems();
250
+ const live = new Set(items);
251
+ setLiveTurn(items.reduce((max, item) => Math.max(max, Number(item.getAttribute('data-chat-turn')) || 0), -1));
252
+
253
+ // Drop our marks outside the live turn. Running this every pass is cheap
254
+ // and self-limiting: once nothing matches, it mutates nothing.
255
+ for (const mark of document.querySelectorAll(`[${MARK_ATTR}]`)) {
256
+ const item = mark.closest('[data-chat-flow-key]');
257
+ if (item === null || !live.has(item)) mark.remove();
258
+ }
259
+ for (const root of document.querySelectorAll(`[${MARKED_ATTR}]`)) {
260
+ const item = root.closest('[data-chat-flow-key]');
261
+ if (item === null || !live.has(item)) root.removeAttribute(MARKED_ATTR);
262
+ }
263
+
264
+ if (diffByText.size > 0) {
265
+ for (const item of items) {
266
+ for (const root of item.querySelectorAll('[data-text-interaction-source]')) {
267
+ if (root.hasAttribute(MARKED_ATTR)) continue;
268
+ if (root.closest('[data-variant="think"]') !== null) continue;
269
+ const { text, nodes } = bodyText(root);
270
+ if (text === '' || nodes.length === 0) continue;
271
+ const removals = removalsOf(text);
272
+ if (removals === null) continue;
273
+ const groups = new Map();
274
+ for (const removal of removals) {
275
+ let hit = null;
276
+ for (const entry of nodes) {
277
+ if (entry.start > removal.start) break;
278
+ hit = entry;
279
+ }
280
+ if (hit === null) continue;
281
+ const local = removal.start - hit.start;
282
+ const value = hit.node.nodeValue ?? '';
283
+ if (local < 0 || local >= value.length) continue;
284
+ if (!groups.has(hit.node)) groups.set(hit.node, []);
285
+ groups.get(hit.node).push({ ...removal, local });
286
+ }
287
+ let changed = false;
288
+ for (const [node, list] of groups) {
289
+ const parent = node.parentNode;
290
+ if (parent === null) continue;
291
+ list.sort((left, right) => left.local - right.local);
292
+ parent.replaceChild(markedFragment(node.nodeValue ?? '', list), node);
293
+ changed = true;
294
+ }
295
+ if (changed) root.setAttribute(MARKED_ATTR, '1');
296
+ }
297
+ }
298
+ }
299
+
300
+ return false;
301
+ }
302
+
303
+ /** The newest turn number, published so a message control can hide itself. */
304
+ const liveTurnListeners = new Set();
305
+ let liveTurnNow = -1;
306
+ function setLiveTurn(turn) {
307
+ if (turn === liveTurnNow) return;
308
+ liveTurnNow = turn;
309
+ for (const listener of liveTurnListeners) listener();
310
+ }
311
+ const liveTurnStore = {
312
+ subscribe: (listener) => {
313
+ liveTurnListeners.add(listener);
314
+ return () => liveTurnListeners.delete(listener);
315
+ },
316
+ getSnapshot: () => liveTurnNow,
317
+ };
318
+
319
+ /** One 改写 control plus its editor, rendered by the harness itself. */
320
+ function EditControl(props) {
321
+ const liveTurn = React.useSyncExternalStore(liveTurnStore.subscribe, liveTurnStore.getSnapshot);
322
+ const [turn, setTurn] = React.useState(null);
323
+ const [open, setOpen] = React.useState(false);
324
+ const [draft, setDraft] = React.useState('');
325
+ const [status, setStatus] = React.useState('');
326
+ const [text, setText] = React.useState('');
327
+ const anchor = React.useRef(null);
328
+
329
+ React.useLayoutEffect(() => {
330
+ const item = anchor.current?.closest('[data-chat-flow-key]') ?? null;
331
+ const next = item === null ? null : Number(item.getAttribute('data-chat-turn'));
332
+ if (!Object.is(turn, next)) setTurn(next);
333
+ });
334
+
335
+ /**
336
+ * The element that renders this message's text. A reply's 改写 lives in
337
+ * the turn-tail node, whose own subtree holds no body, so the search falls
338
+ * back to the nearest preceding rendered text block.
339
+ */
340
+ const readBody = () => {
341
+ const ref = anchor.current;
342
+ if (ref === null) return null;
343
+ const item = ref.closest('[data-chat-flow-key]');
344
+ const direct = item?.querySelector('[data-message-bubble], [data-text-interaction-source]');
345
+ if (direct !== null && direct !== undefined) return direct;
346
+ for (let node = item?.previousElementSibling ?? null, step = 0; node !== null && step < 8; step += 1) {
347
+ const found = node.matches('[data-text-interaction-source]')
348
+ ? node
349
+ : node.querySelector('[data-text-interaction-source]');
350
+ if (found !== null && found !== undefined) return found;
351
+ node = node.previousElementSibling;
352
+ }
353
+ // Last resort: the nearest rendered text block before the control.
354
+ let best = null;
355
+ for (const element of document.querySelectorAll('[data-text-interaction-source]')) {
356
+ if ((element.compareDocumentPosition(ref) & Node.DOCUMENT_POSITION_FOLLOWING) === 0) break;
357
+ best = element;
358
+ }
359
+ return best;
360
+ };
361
+
362
+ /** The message text as the chat shows it, which is what the host holds. */
363
+ const readShown = () => {
364
+ const body = readBody();
365
+ return body === null ? '' : bodyText(body).text;
366
+ };
367
+
368
+ // No look-up and no message id: the edit names the text it replaces, so it
369
+ // works on the first try after a restart too.
370
+ const openEditor = () => {
371
+ const shown = readShown();
372
+ if (shown.trim() === '') {
373
+ setStatus('这条消息没有可改写的文本');
374
+ return;
375
+ }
376
+ setText(shown);
377
+ setDraft(shown);
378
+ setStatus('');
379
+ setOpen(true);
380
+ };
381
+
382
+ const save = async () => {
383
+ if (text === '') return;
384
+ setStatus('保存中…');
385
+ try {
386
+ const response = await fetch(EDIT_ENDPOINT, {
387
+ method: 'POST',
388
+ headers: { 'content-type': 'application/json' },
389
+ body: JSON.stringify({ items: [{ from: text, text: draft }] }),
390
+ });
391
+ if (!response.ok) throw new Error(`HTTP ${response.status}`);
392
+ const body = await response.json();
393
+ if (rememberEdits(body?.editDiffs) && nudgeDiffRules !== null) nudgeDiffRules();
394
+ setOpen(false);
395
+ setStatus('已改写 · 只在下一次请求生效');
396
+ } catch (failure) {
397
+ setStatus(`保存失败:${String(failure?.message ?? failure)}`);
398
+ }
399
+ };
400
+
401
+ React.useEffect(() => {
402
+ if (status === '') return undefined;
403
+ const timer = setTimeout(() => setStatus(''), 4000);
404
+ return () => clearTimeout(timer);
405
+ }, [status]);
406
+
407
+ // A turn that has moved on is compressed; rewriting it would change
408
+ // nothing the next request carries, so the control stays hidden. It is
409
+ // hidden with CSS, never unmounted: the anchor must survive so the turn
410
+ // number stays readable (unmounting it loops the renderer).
411
+ const hidden = turn !== null && Number.isFinite(turn) && liveTurn !== -1 && turn !== liveTurn;
412
+
413
+ return h('span', {
414
+ ref: anchor,
415
+ style: { display: hidden ? 'none' : 'inline-flex', alignItems: 'center', gap: '6px', marginLeft: '6px' },
416
+ },
417
+ h('button', {
418
+ type: 'button',
419
+ onClick: openEditor,
420
+ title: '改写这条消息:只影响下一次请求,不动历史',
421
+ style: {
422
+ font: 'inherit', fontSize: '11px', lineHeight: '16px', padding: '1px 7px',
423
+ borderRadius: '5px', cursor: 'pointer',
424
+ border: '1px solid var(--dsw-alias-border-l1)', background: 'transparent',
425
+ color: 'var(--dsw-alias-label-secondary)',
426
+ },
427
+ }, '改写'),
428
+ status === '' ? null : h('span', { style: { fontSize: '10px', color: 'var(--dsw-alias-label-secondary)' } }, status),
429
+ open ? h('div', {
430
+ style: {
431
+ position: 'fixed', inset: '0', zIndex: 60, display: 'grid', placeItems: 'center',
432
+ background: 'rgba(0, 0, 0, 0.35)',
433
+ },
434
+ onClick: (event) => { if (event.target === event.currentTarget) setOpen(false); },
435
+ }, h('div', {
436
+ style: {
437
+ width: 'min(560px, 90vw)', padding: '14px 16px', borderRadius: '12px',
438
+ border: '1px solid var(--dsw-alias-border-l1)',
439
+ background: 'var(--dsw-alias-bg-layer-2)', boxShadow: '0 12px 32px rgba(0,0,0,.35)',
440
+ display: 'flex', flexDirection: 'column', gap: '10px',
441
+ },
442
+ },
443
+ h('div', { style: { fontSize: '12px', fontWeight: 600 } }, '改写这条消息'),
444
+ h('div', { style: { fontSize: '11px', color: 'var(--dsw-alias-label-secondary)' } },
445
+ '只写进下一次请求;磁盘上的历史不动,点取消即放弃。'),
446
+ h('textarea', {
447
+ value: draft,
448
+ rows: 8,
449
+ onChange: (event) => setDraft(event.target.value),
450
+ style: {
451
+ width: '100%', boxSizing: 'border-box', font: 'inherit', fontSize: '12px',
452
+ lineHeight: '18px', padding: '8px 10px', borderRadius: '8px', resize: 'vertical',
453
+ border: '1px solid var(--dsw-alias-border-l1)',
454
+ background: 'var(--dsw-alias-bg-layer-1)', color: 'var(--dsw-alias-label-primary)',
455
+ },
456
+ }),
457
+ status === '' ? null : h('div', { style: { fontSize: '11px', color: 'var(--dsw-alias-label-secondary)' } }, status),
458
+ h('div', { style: { display: 'flex', justifyContent: 'flex-end', gap: '8px' } },
459
+ h('button', {
460
+ type: 'button',
461
+ onClick: () => setOpen(false),
462
+ style: {
463
+ font: 'inherit', fontSize: '11px', padding: '4px 10px', borderRadius: '6px',
464
+ border: '1px solid var(--dsw-alias-border-l1)', background: 'transparent',
465
+ color: 'var(--dsw-alias-label-primary)', cursor: 'pointer',
466
+ },
467
+ }, '取消'),
468
+ h('button', {
469
+ type: 'button',
470
+ onClick: save,
471
+ style: {
472
+ font: 'inherit', fontSize: '11px', padding: '4px 10px', borderRadius: '6px',
473
+ border: '1px solid var(--dsw-alias-brand-primary)',
474
+ background: 'var(--dsw-alias-brand-primary)', color: 'var(--dsw-alias-bg-base)',
475
+ cursor: 'pointer',
476
+ },
477
+ }, '保存改写')),
478
+ )) : null);
479
+ }
480
+
481
+ /** Every slot this plugin registers is keyed by this one id. */
482
+ const DIFF_RULE_ID = 'oh-my-token';
483
+
484
+ /**
485
+ * Plain-language strength presets: one pick sets the budgets and the
486
+ * min-rewrite thresholds. Choosing one saves it straight away; touching a
487
+ * raw number below drops into "custom".
488
+ */
489
+ const PRESETS = {
490
+ gentle: {
491
+ budgets: { default: 9000, read: 18000, grep: 9000, bash: 6000 },
492
+ minChars: 1200,
493
+ minGain: 0.1,
494
+ },
495
+ default: {
496
+ budgets: { default: 6000, read: 12000, grep: 6000, bash: 4000 },
497
+ minChars: 800,
498
+ minGain: 0.05,
499
+ },
500
+ aggressive: {
501
+ budgets: { default: 3000, read: 6000, grep: 3000, bash: 2000 },
502
+ minChars: 400,
503
+ minGain: 0.02,
504
+ },
505
+ };
506
+
507
+ /** Which preset (if any) the live config matches, else 'custom'. */
508
+ function presetOf(config) {
509
+ for (const [name, preset] of Object.entries(PRESETS)) {
510
+ if (preset.budgets.default === config?.budgets?.default
511
+ && preset.budgets.read === config?.budgets?.read
512
+ && preset.budgets.grep === config?.budgets?.grep
513
+ && preset.budgets.bash === config?.budgets?.bash
514
+ && preset.minChars === config?.minChars
515
+ && preset.minGain === config?.minGain) {
516
+ return name;
517
+ }
518
+ }
519
+ return 'custom';
520
+ }
26
521
 
27
522
  const TEXT = {
28
523
  nav: '省 Token',
29
524
  title: '省 Token 管理',
30
525
  subtitle: '在工具结果写入会话之前决定它进多少。只在这一处改写,历史保持追加,前缀缓存不受影响。',
526
+ tabs: {
527
+ overview: '概览',
528
+ compression: '压缩',
529
+ prose: '散文',
530
+ chat: '对话',
531
+ prompt: '提示词',
532
+ about: '关于',
533
+ },
31
534
  failed: '无法连接插件',
32
535
  refresh: '刷新',
33
536
  reset: '清除历史累计',
@@ -52,16 +555,25 @@ window.__ModuleLoader__.load({
52
555
  switchesHint: '改动立即生效,无需重启。',
53
556
  filters: '命令输出过滤',
54
557
  retrieval: '检索式读取',
55
- prose: '句末标点',
558
+ prose: '散文整理(标点 / 规则)',
56
559
  proseHint: '只对判定为散文的行生效。代码、diff、路径、URL、版本号一律不动。',
57
560
  scopes: {
58
561
  off: '关闭',
59
562
  filtered: '仅散文输出',
60
563
  all: '所有散文',
61
564
  },
62
- systemPrompt: '系统提示词',
63
- systemPromptHint: '把提示词拆成若干小段(卡片),从上到下按顺序拼到现有系统提示词末尾,保存后下一次请求生效。',
64
- systemPromptVariables: '{{变量}}:{{provider}} 会替换为当前模型供应商、{{model}} 替换为当前模型名;写其他写法不替换,保持字面量,也不会因此报错。',
565
+ prompt: '完整提示词',
566
+ promptHint: '这里显示实际发给模型的系统提示词:核心提示词 + 各插件注册的段落,按真实顺序拼接,变量已替换。点「获取」重新读取。',
567
+ promptFetch: '获取提示词',
568
+ promptRefreshing: '读取中…',
569
+ promptCopy: '复制全文',
570
+ promptCopied: '已复制',
571
+ promptStats: (sections, chars) => `${sections} 段 · ${chars} 字符`,
572
+ promptNone: '还没有发出过请求。先随便对话一句,插件会记下那次真正发给模型的提示词,再点「获取」。',
573
+ promptEmpty: '没有读到提示词(宿主未注册系统提示词服务)。',
574
+ aboutHint: 'DeepSeek Harness 原生省 Token 插件:命令输出过滤、结构压缩、检索式读取、散文整理、对话改写、提示词查看。纯 JS,无外部二进制、无额外服务。',
575
+ aboutOpen: '★ 打开 GitHub 仓库',
576
+ aboutLicense: 'MIT 许可 · 版本来自 package.json',
65
577
  advanced: '高级配置',
66
578
  advancedHint: '数字与枚举项改完点「保存配置」;开关立即生效。',
67
579
  saveConfig: '保存配置',
@@ -87,32 +599,50 @@ window.__ModuleLoader__.load({
87
599
  'retrieval.maxGrepMatches': 'grep 匹配上限',
88
600
  logEvery: '每 N 次打印日志',
89
601
  },
90
- systemPromptPlaceholder: '写下这一段的提示词…',
91
- addSegment: '添加一小段',
92
- moveUp: '上移',
93
- moveDown: '下移',
94
- removeSegment: '删除这一段',
95
- emptySegments: '还没有任何段落。点击「添加一小段」开始。',
96
- saveSystemPrompt: '保存系统提示词',
97
- restoreSystemPrompt: '恢复默认提示词',
98
- nothingToRead: '没有读到当前生效的系统提示词(服务端未返回内容)。',
99
- modes: {
602
+ nothingToRead: '没有读到当前生效的系统提示词(服务端未返回内容)。', modes: {
100
603
  pytest: ['pytest 结果', '通过时只留一行结论;失败时保留 FAILED、断言与摘要'],
101
604
  git: ['git 输出', 'status 干净时折叠成一行,diff 只留文件头和变更行'],
102
605
  tsc: ['tsc 输出', '只保留 error TS 开头的行与总数,告警丢弃'],
103
606
  packageManager: ['包管理器安装', '成功时只留摘要行,失败时只留错误行'],
104
607
  generic: ['通用清理', '任意命令都安全:ANSI、回车重绘、重复行、进度条'],
105
- rtk: ['RTK 风格压缩', '命令过滤器未命中时,再按结构压缩 git 输出、构建日志、grep/find/ls/tree 等'],
608
+ rtk: ['RTK 风格压缩', '命令过滤器未命中时,再按结构压缩 git、构建、eslint、cargo/go 测试、grep/find/ls/tree 等'],
106
609
  readOutline: ['大文件大纲', '超过行数阈值且没给 offset/limit 的 read 只返回符号大纲'],
107
610
  grepCap: ['搜索结果截断', '匹配过多时只留前 N 条并说明剩余数量'],
108
- proseStrip: ['删除句末标点', '删除散文行、你的输入与助手回复末尾的句号/逗号;代码、URL、路径、版本号不动'],
109
- politenessStrip: ['删除客套词', '删除散文行、你的输入与助手回复里的「谢谢」「请」「please」「thanks」等客套词;代码、URL、路径、版本号不动'],
110
- systemPrompt: ['修改系统提示词', '把若干小段分段拼接到系统提示词末尾'],
611
+ proseStrip: ['标点整理', '段首标点删去;挨着的两个标点只留一个(逗号+句号留句号);句末连续的 . , 。 , 删掉;省略号不动'],
111
612
  },
112
613
  file: '配置目录',
113
614
  none: '未找到配置目录,改动不会落盘',
114
615
  generated: '更新时间',
115
616
  note: 'Token 数按 Harness 显示上下文时的同一套估算口径(4 字符 ≈ 1 token)折算;只统计被移除的字符。',
617
+ preset: '压缩力度',
618
+ presetHint: '一键设置字符上限与最小改写阈值;想精调再展开下面「高级数字」。',
619
+ presets: {
620
+ gentle: '省着压(留更多内容)',
621
+ default: '默认',
622
+ aggressive: '狠压(最省 token)',
623
+ custom: '自定义(手动调过)',
624
+ },
625
+ presetApply: '应用',
626
+ rawSettings: '高级数字(原始配置)',
627
+ words: '规则:词语删除 / 替换',
628
+ wordsHint: '每行一条规则:左边的词在散文行里被删掉,右边非空则替换成它。内置规则含「谢谢 / 请 / please / thanks」以及「啊 / 呀 / 吧 / 呢 / 嘛 / 哦」等语气词——语气词只在句尾或标点前删,所以「酒吧」「网吧」「毛呢」不会被拆。代码、URL、路径、版本号不参与。',
629
+ wordLabel: '词',
630
+ replaceLabel: '替换为空 = 删除',
631
+ addWord: '加一个词',
632
+ saveWords: '保存词表',
633
+ editTitle: '对话内容编辑',
634
+ editHint: '改写最近消息的内容。你的改写只在下次请求发给模型,磁盘上的历史原样不动。',
635
+ roleUser: '你',
636
+ roleAssistant: '模型',
637
+ editNow: '编辑',
638
+ editSaving: '保存改写',
639
+ editRestore: '恢复原内容',
640
+ editCancel: '取消',
641
+ editEmpty: '还没有可编辑的消息,对话几句后这里会列出最近的内容。',
642
+ notes: '自动变换记录',
643
+ notesHint: '最近自动删改的原文:红字划线 = 删掉,绿字 = 替换或新增。',
644
+ notesEmpty: '还没有变换记录。',
645
+ notesAgo: (seconds) => (seconds < 60 ? `${seconds} 秒前` : `${Math.floor(seconds / 60)} 分钟前`),
116
646
  };
117
647
 
118
648
  /** A finite, non-negative number from any wire value. */
@@ -205,55 +735,6 @@ window.__ModuleLoader__.load({
205
735
  );
206
736
  }
207
737
 
208
- /** One prompt segment card: its text, and the move/remove controls. */
209
- function SegmentCard(props) {
210
- const { segment, index, count, text, disabled, onText, onMove, onRemove } = props;
211
- const control = (label, onClick, off, warning) => h('button', {
212
- type: 'button',
213
- disabled: disabled || off,
214
- onClick,
215
- style: {
216
- padding: '2px 6px', borderRadius: '5px', font: 'inherit',
217
- border: '1px solid var(--dsw-alias-border-l1)',
218
- background: 'var(--dsw-alias-bg-layer-1)',
219
- color: warning ? 'var(--dsw-alias-state-error-primary)' : 'var(--dsw-alias-label-primary)',
220
- fontSize: '11px', lineHeight: '15px',
221
- cursor: disabled || off ? 'default' : 'pointer',
222
- opacity: disabled || off ? 0.5 : 1,
223
- },
224
- }, label);
225
- return h('div', {
226
- style: {
227
- padding: '7px 9px', borderRadius: '8px',
228
- border: '1px solid var(--dsw-alias-border-l1)',
229
- background: 'var(--dsw-alias-bg-layer-1)',
230
- },
231
- },
232
- h('div', { style: { display: 'flex', alignItems: 'center', gap: '6px', marginBottom: '4px' } },
233
- h('span', {
234
- style: { fontSize: '10px', color: 'var(--dsw-alias-label-secondary)' },
235
- }, `${index + 1}/${count}`),
236
- h('div', { style: { flex: '1 1 auto' } }),
237
- control(text.moveUp, () => onMove(-1), index === 0),
238
- control(text.moveDown, () => onMove(1), index === count - 1),
239
- control(text.removeSegment, onRemove, false, true),
240
- ),
241
- h('textarea', {
242
- value: segment.text ?? '',
243
- onChange: (event) => onText(event.target.value),
244
- placeholder: text.systemPromptPlaceholder,
245
- maxLength: 8000,
246
- rows: 3,
247
- disabled,
248
- style: {
249
- width: '100%', boxSizing: 'border-box', padding: '7px',
250
- borderRadius: '6px', border: '1px solid var(--dsw-alias-border-l1)',
251
- background: 'transparent', color: 'var(--dsw-alias-label-primary)',
252
- font: 'inherit', fontSize: '12px', lineHeight: '18px', resize: 'vertical',
253
- },
254
- }));
255
- }
256
-
257
738
  /** One bordered card. */
258
739
  function Card(props) {
259
740
  return h('div', {
@@ -288,9 +769,51 @@ window.__ModuleLoader__.load({
288
769
  );
289
770
  }
290
771
 
772
+ /**
773
+ * One recorded change, shown the way a Git diff shows a changed line:
774
+ * removed text struck through in red, added text in green.
775
+ */
776
+ function DiffLine(props) {
777
+ const { segments, notes } = props;
778
+ if (!Array.isArray(segments) || segments.length === 0) {
779
+ return h('div', { style: { fontSize: '11px', color: 'var(--dsw-alias-label-secondary)' } },
780
+ Array.isArray(notes) ? notes.join('、') : '');
781
+ }
782
+ return h('div', {
783
+ style: {
784
+ fontSize: '12px', lineHeight: '18px', fontFamily: 'inherit',
785
+ overflowWrap: 'anywhere', whiteSpace: 'pre-wrap',
786
+ maxHeight: '76px', overflowY: 'auto',
787
+ },
788
+ }, segments.map((segment, index) => {
789
+ if (segment?.kind === 'del') {
790
+ return h('span', {
791
+ key: index,
792
+ style: {
793
+ color: 'var(--dsw-alias-state-error-primary)',
794
+ textDecoration: 'line-through',
795
+ background: 'rgba(239, 68, 68, 0.18)',
796
+ borderRadius: '3px',
797
+ },
798
+ }, String(segment.text));
799
+ }
800
+ if (segment?.kind === 'add') {
801
+ return h('span', {
802
+ key: index,
803
+ style: {
804
+ color: 'var(--dsw-alias-state-success-primary)',
805
+ fontWeight: 600,
806
+ background: 'rgba(34, 197, 94, 0.2)',
807
+ borderRadius: '3px',
808
+ },
809
+ }, String(segment.text));
810
+ }
811
+ return h('span', { key: index, style: { color: 'var(--dsw-alias-label-primary)' } }, String(segment?.text ?? ''));
812
+ }));
813
+ }
814
+
291
815
  /** A share bar for the saved ratio. */
292
- function Bar(props) {
293
- const ratio = Math.min(1, number(props.ratio));
816
+ function Bar(props) { const ratio = Math.min(1, number(props.ratio));
294
817
  return h('div', {
295
818
  style: {
296
819
  height: '4px', borderRadius: '2px', marginTop: '8px',
@@ -338,21 +861,38 @@ window.__ModuleLoader__.load({
338
861
  );
339
862
  }
340
863
 
864
+ /** One horizontal input, the size the page uses everywhere. */
865
+ const inputStyle = {
866
+ padding: '3px 6px', borderRadius: '5px', border: '1px solid var(--dsw-alias-border-l1)',
867
+ background: 'transparent', color: 'var(--dsw-alias-label-primary)', font: 'inherit', fontSize: '12px',
868
+ flex: '1 1 120px', minWidth: 80,
869
+ };
870
+
341
871
  /** The settings page. */
342
872
  function SavingsPage() {
343
873
  const text = TEXT;
344
874
  const [state, setState] = React.useState(null);
345
875
  const [error, setError] = React.useState('');
876
+ const [tab, setTab] = React.useState('overview');
346
877
  const [busy, setBusy] = React.useState('');
347
878
  const [confirming, setConfirming] = React.useState(false);
348
- const [spDraft, setSpDraft] = React.useState(null);
879
+ const [prompt, setPrompt] = React.useState(null);
880
+ const [promptBusy, setPromptBusy] = React.useState(false);
881
+ const [promptCopied, setPromptCopied] = React.useState(false);
349
882
  const [cfgDraft, setCfgDraft] = React.useState(null);
883
+ const [wordsDraft, setWordsDraft] = React.useState(null);
884
+ const [editItems, setEditItems] = React.useState(null);
885
+ const [editDraft, setEditDraft] = React.useState({});
886
+ const [editBusy, setEditBusy] = React.useState('');
350
887
 
351
888
  const load = React.useCallback(async () => {
352
889
  try {
353
890
  const response = await fetch(STATE_ENDPOINT, { headers: { accept: 'application/json' } });
354
891
  if (!response.ok) throw new Error(`HTTP ${response.status}`);
355
- setState(await response.json());
892
+ const body = await response.json();
893
+ const changed = rememberDiffs(body?.recent) || rememberEdits(body?.editDiffs);
894
+ if (changed && nudgeDiffRules !== null) nudgeDiffRules();
895
+ setState(body);
356
896
  setError('');
357
897
  } catch (failure) {
358
898
  setError(`${text.failed}: ${String(failure?.message ?? failure)}`);
@@ -360,19 +900,26 @@ window.__ModuleLoader__.load({
360
900
  }, [text]);
361
901
 
362
902
  React.useEffect(() => { load(); }, [load]);
363
- React.useEffect(() => {
364
- if (spDraft === null && Array.isArray(state?.systemPrompt?.segments)) {
365
- // Loaded cards may predate the id-bearing editor; give every card a
366
- // stable key so reorder/edit/remove target the right one.
367
- setSpDraft({ segments: state.systemPrompt.segments.map((segment, index) => ({
368
- ...segment,
369
- id: segment.id ?? `seg-${index}-${Date.now().toString(36)}`,
370
- })) });
371
- }
372
- }, [state, spDraft]);
373
903
  React.useEffect(() => {
374
904
  if (cfgDraft === null && state?.config) setCfgDraft(state.config);
375
905
  }, [state, cfgDraft]);
906
+ React.useEffect(() => {
907
+ const words = state?.config?.prose?.politenessWords;
908
+ if (wordsDraft === null && Array.isArray(words)) {
909
+ setWordsDraft(words.map((entry) => ({ word: entry.word, replace: entry.replace ?? '' })));
910
+ }
911
+ }, [state, wordsDraft]);
912
+ /** Load the editable conversation messages. */
913
+ const loadEdits = React.useCallback(async () => {
914
+ try {
915
+ const response = await fetch(EDIT_ENDPOINT, { headers: { accept: 'application/json' } });
916
+ if (!response.ok) return;
917
+ setEditItems(response.json ? (await response.json()).items : []);
918
+ } catch {
919
+ /* the page still works when the route is absent (older host) */
920
+ }
921
+ }, []);
922
+ React.useEffect(() => { loadEdits(); }, [loadEdits]);
376
923
  React.useEffect(() => {
377
924
  const timer = setInterval(() => { load(); }, 5000);
378
925
  return () => { clearInterval(timer); };
@@ -382,14 +929,13 @@ window.__ModuleLoader__.load({
382
929
  * Send one patch and adopt the Host's answer. The switch moves at once
383
930
  * and reverts on failure, so the page never disagrees with the policy.
384
931
  */
385
- const commit = async (patch, proseScope, systemPrompt) => {
932
+ const commit = async (patch, proseScope) => {
386
933
  const previous = state;
387
934
  setState((current) => {
388
935
  if (current === null) return current;
389
936
  return {
390
937
  ...current,
391
938
  proseScope: proseScope === undefined ? current.proseScope : proseScope,
392
- systemPrompt: systemPrompt === undefined ? current.systemPrompt : systemPrompt,
393
939
  modes: current.modes.map((mode) => (Object.hasOwn(patch, mode.id) ? { ...mode, on: patch[mode.id] } : mode)),
394
940
  };
395
941
  });
@@ -400,7 +946,6 @@ window.__ModuleLoader__.load({
400
946
  body: JSON.stringify({
401
947
  modes: patch,
402
948
  ...(proseScope === undefined ? {} : { proseScope }),
403
- ...(systemPrompt === undefined ? {} : { systemPrompt }),
404
949
  }),
405
950
  });
406
951
  if (!response.ok) throw new Error(`HTTP ${response.status}`);
@@ -431,56 +976,36 @@ window.__ModuleLoader__.load({
431
976
  }
432
977
  };
433
978
 
434
- const saveSystemPrompt = async () => {
435
- setBusy('systemPrompt');
436
- try {
437
- await commit({}, undefined, { segments: (spDraft?.segments ?? []).map((segment) => ({ text: segment.text ?? '' })) });
438
- } finally {
439
- setBusy('');
440
- }
441
- };
442
-
443
- /** A fresh segment id; short enough for section names, unique enough for a page. */
444
- const nextSegmentId = () => `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 7)}`;
445
-
446
- /** Patch the draft's segments array for the card column. */
447
- const patchSegments = (update) => setSpDraft((draft) => ({ segments: update(draft?.segments ?? []) }));
448
-
449
- const addSegment = () => patchSegments((segments) => [...segments, { id: nextSegmentId(), text: '' }]);
450
- const setSegmentText = (index, text) => patchSegments((segments) =>
451
- segments.map((segment, i) => (i === index ? { ...segment, text } : segment)));
452
- const removeSegment = (index) => patchSegments((segments) => segments.filter((_, i) => i !== index));
453
- const moveSegment = (index, delta) => patchSegments((segments) => {
454
- const target = index + delta;
455
- if (index < 0 || index >= segments.length || target < 0 || target >= segments.length) return segments;
456
- const next = segments.slice();
457
- const [segment] = next.splice(index, 1);
458
- next.splice(target, 0, segment);
459
- return next;
460
- });
461
-
462
- /** Read the currently effective default prompt and split it into cards. */
463
- const restoreSystemPrompt = async () => {
464
- setBusy('systemPrompt');
979
+ /** Read the prompt the next request will actually carry. */
980
+ const readPrompt = async () => {
981
+ setPromptBusy(true);
465
982
  try {
466
983
  const response = await fetch(PROMPT_ENDPOINT, { headers: { accept: 'application/json' } });
467
984
  if (!response.ok) throw new Error(`HTTP ${response.status}`);
468
985
  const body = await response.json();
469
- const prompt = typeof body?.prompt === 'string' ? body.prompt : '';
470
- if (prompt === '') {
471
- setError(text.nothingToRead);
472
- return;
473
- }
474
- const segments = prompt.split(/\n{2,}/)
475
- .map((text) => text.trim())
476
- .filter((text) => text !== '')
477
- .map((text) => ({ id: nextSegmentId(), text }));
478
- setSpDraft({ segments });
986
+ setPrompt({
987
+ text: typeof body?.prompt === 'string' ? body.prompt : '',
988
+ sections: typeof body?.sections === 'number' ? body.sections : 0,
989
+ none: body?.source === 'none',
990
+ });
991
+ setPromptCopied(false);
479
992
  setError('');
480
993
  } catch (failure) {
481
994
  setError(`${text.failed}: ${String(failure?.message ?? failure)}`);
482
995
  } finally {
483
- setBusy('');
996
+ setPromptBusy(false);
997
+ }
998
+ };
999
+
1000
+ /** Copy the whole prompt; a blocked clipboard falls back to selecting it. */
1001
+ const copyPrompt = async () => {
1002
+ const value = prompt?.text ?? '';
1003
+ if (value === '') return;
1004
+ try {
1005
+ await navigator.clipboard.writeText(value);
1006
+ setPromptCopied(true);
1007
+ } catch {
1008
+ setError('复制被浏览器拒绝,请手动选中文本复制');
484
1009
  }
485
1010
  };
486
1011
 
@@ -544,6 +1069,67 @@ window.__ModuleLoader__.load({
544
1069
  }
545
1070
  };
546
1071
 
1072
+ /** One preset pick saves the whole strength in one call. */
1073
+ const applyPreset = async (name) => {
1074
+ if (!(name in PRESETS)) return;
1075
+ setBusy('preset');
1076
+ try {
1077
+ const body = await postState({ config: PRESETS[name] });
1078
+ setCfgDraft(body.config);
1079
+ } catch (failure) {
1080
+ setError(`${text.failed}: ${String(failure?.message ?? failure)}`);
1081
+ } finally {
1082
+ setBusy('');
1083
+ }
1084
+ };
1085
+
1086
+ const setWordRow = (index, key, value) => setWordsDraft((rows) =>
1087
+ (rows ?? []).map((entry, i) => (i === index ? { ...entry, [key]: value } : entry)));
1088
+ const addWordRow = () => setWordsDraft((rows) => [...(rows ?? []), { word: '', replace: '' }]);
1089
+ const removeWordRow = (index) => setWordsDraft((rows) => (rows ?? []).filter((_, i) => i !== index));
1090
+
1091
+ /** Persist the word list through the config channel (it is a config field). */
1092
+ const saveWords = async () => {
1093
+ setBusy('words');
1094
+ try {
1095
+ const words = (wordsDraft ?? [])
1096
+ .filter((entry) => entry.word !== '')
1097
+ .map((entry) => (entry.replace !== '' ? { word: entry.word, replace: entry.replace } : { word: entry.word }));
1098
+ const body = await postState({ config: { prose: { politenessWords: words } } });
1099
+ const saved = body?.config?.prose?.politenessWords;
1100
+ if (Array.isArray(saved)) setWordsDraft(saved.map((entry) => ({ word: entry.word, replace: entry.replace ?? '' })));
1101
+ } catch (failure) {
1102
+ setError(`${text.failed}: ${String(failure?.message ?? failure)}`);
1103
+ } finally {
1104
+ setBusy('');
1105
+ }
1106
+ };
1107
+
1108
+ /** Save one conversation edit (or restore it with a null text). */
1109
+ const commitEdit = async (id, value) => {
1110
+ setEditBusy(id);
1111
+ try {
1112
+ const response = await fetch(EDIT_ENDPOINT, {
1113
+ method: 'POST',
1114
+ headers: { 'content-type': 'application/json' },
1115
+ body: JSON.stringify({ items: [{ id, text: value }] }),
1116
+ });
1117
+ if (!response.ok) throw new Error(`HTTP ${response.status}`);
1118
+ const body = await response.json();
1119
+ setEditItems(body.items);
1120
+ setEditDraft((draft) => {
1121
+ const next = { ...draft };
1122
+ delete next[id];
1123
+ return next;
1124
+ });
1125
+ setError('');
1126
+ } catch (failure) {
1127
+ setError(`${text.failed}: ${String(failure?.message ?? failure)}`);
1128
+ } finally {
1129
+ setEditBusy('');
1130
+ }
1131
+ };
1132
+
547
1133
  const toggleEnabled = async () => {
548
1134
  setBusy('enabled');
549
1135
  try {
@@ -572,12 +1158,10 @@ window.__ModuleLoader__.load({
572
1158
 
573
1159
  const modes = Array.isArray(state?.modes) ? state.modes : [];
574
1160
  const modeOf = (id) => modes.find((mode) => mode.id === id)?.on === true;
575
- const proseOn = modeOf('proseStrip') || modeOf('politenessStrip');
576
1161
  const cumulative = state?.cumulative ?? {};
577
1162
  const session = state?.session ?? {};
578
1163
  const tools = Array.isArray(cumulative.tools) ? cumulative.tools : [];
579
1164
  const scopes = Array.isArray(state?.scopes) ? state.scopes : ['off', 'filtered', 'all'];
580
- const spSegments = Array.isArray(spDraft?.segments) ? spDraft.segments : [];
581
1165
 
582
1166
  const group = (title, ids) => h(Card, null,
583
1167
  h('div', { style: { fontSize: '12px', fontWeight: 600, marginBottom: '6px' } }, title),
@@ -587,6 +1171,15 @@ window.__ModuleLoader__.load({
587
1171
  }))),
588
1172
  );
589
1173
 
1174
+ /**
1175
+ * One tab's content. `display: contents` keeps the cards as direct
1176
+ * children of the column, so the gap stays even; an inactive tab is
1177
+ * hidden without unmounting what the drafts are attached to.
1178
+ */
1179
+ const pane = (id, children) => h('div', {
1180
+ style: { display: tab === id ? 'contents' : 'none' },
1181
+ }, children);
1182
+
590
1183
  return h('div', {
591
1184
  style: {
592
1185
  display: 'flex', flexDirection: 'column', gap: '12px',
@@ -600,6 +1193,22 @@ window.__ModuleLoader__.load({
600
1193
  style: { marginTop: '2px', fontSize: '11px', lineHeight: '16px', color: 'var(--dsw-alias-label-secondary)' },
601
1194
  }, text.subtitle),
602
1195
  ),
1196
+ h('div', { style: { display: 'flex', flexWrap: 'wrap', gap: '2px', padding: '3px', borderRadius: '9px', border: '1px solid var(--dsw-alias-border-l1)', background: 'var(--dsw-alias-bg-layer-1)' } },
1197
+ Object.entries(text.tabs).map(([id, label]) => h('button', {
1198
+ key: id,
1199
+ type: 'button',
1200
+ role: 'tab',
1201
+ 'aria-selected': tab === id ? 'true' : 'false',
1202
+ 'data-tab': id,
1203
+ onClick: () => setTab(id),
1204
+ style: {
1205
+ padding: '4px 11px', borderRadius: '7px', font: 'inherit', fontSize: '12px', lineHeight: '18px',
1206
+ border: `1px solid ${tab === id ? 'var(--dsw-alias-brand-primary)' : 'transparent'}`,
1207
+ background: tab === id ? 'var(--dsw-alias-bg-layer-2)' : 'transparent',
1208
+ color: tab === id ? 'var(--dsw-alias-label-primary)' : 'var(--dsw-alias-label-secondary)',
1209
+ cursor: 'pointer',
1210
+ },
1211
+ }, label))),
603
1212
  error !== '' ? h('div', {
604
1213
  style: {
605
1214
  padding: '6px 9px', borderRadius: '6px', fontSize: '11px',
@@ -607,6 +1216,7 @@ window.__ModuleLoader__.load({
607
1216
  border: '1px solid var(--dsw-alias-state-error-primary)',
608
1217
  },
609
1218
  }, error) : null,
1219
+ pane('overview', [
610
1220
  h(Card, null,
611
1221
  h('div', { style: { fontSize: '11px', color: 'var(--dsw-alias-label-secondary)' } }, text.hero),
612
1222
  h('div', {
@@ -623,6 +1233,8 @@ window.__ModuleLoader__.load({
623
1233
  h(ScopeCard, { title: text.session, summary: session, text }),
624
1234
  h(ScopeCard, { title: text.cumulative, summary: cumulative, text }),
625
1235
  ),
1236
+ ]),
1237
+ pane('compression', [
626
1238
  h(Card, null,
627
1239
  h('div', { style: { display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', gap: '8px' } },
628
1240
  h('span', { style: { fontSize: '12px', fontWeight: 600 } }, text.advanced),
@@ -633,36 +1245,61 @@ window.__ModuleLoader__.load({
633
1245
  disabled: busy === 'enabled', onToggle: toggleEnabled,
634
1246
  }),
635
1247
  h('span', { style: { fontSize: '11px', color: 'var(--dsw-alias-label-secondary)' } }, text.enabledHint)),
636
- h('div', { style: { display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(150px, 1fr))', gap: '6px', marginTop: '8px' } },
637
- CFG_FIELDS.map(([path, step]) => h('label', {
638
- key: path,
639
- style: { display: 'flex', flexDirection: 'column', gap: '2px', fontSize: '11px', color: 'var(--dsw-alias-label-secondary)' },
640
- },
641
- text.fields[path] ?? path,
642
- h('input', {
643
- type: 'number', value: cfgGet(path) ?? '', step, min: 0, disabled: busy === 'config',
644
- onChange: (event) => cfgSet(path, event.target.value === '' ? '' : Number(event.target.value)),
1248
+ h('div', { style: { display: 'flex', alignItems: 'center', gap: '8px', marginTop: '8px' } },
1249
+ h('span', { style: { fontSize: '11px', color: 'var(--dsw-alias-label-secondary)' } }, text.preset),
1250
+ h('select', {
1251
+ value: presetOf(cfgDraft ?? state?.config),
1252
+ disabled: busy === 'preset',
1253
+ onChange: (event) => {
1254
+ if (event.target.value !== 'custom') applyPreset(event.target.value);
1255
+ },
645
1256
  style: {
646
1257
  padding: '3px 6px', borderRadius: '5px', border: '1px solid var(--dsw-alias-border-l1)',
647
1258
  background: 'transparent', color: 'var(--dsw-alias-label-primary)', font: 'inherit', fontSize: '12px',
648
1259
  },
649
- })))),
650
- h('label', { style: { display: 'flex', flexDirection: 'column', gap: '2px', fontSize: '11px', color: 'var(--dsw-alias-label-secondary)', marginTop: '8px' } },
651
- text.recovery,
652
- h('select', {
653
- value: cfgGet('recovery') ?? 'spill', disabled: busy === 'config',
654
- onChange: (event) => cfgSet('recovery', event.target.value),
655
- style: {
656
- padding: '3px 6px', borderRadius: '5px', border: '1px solid var(--dsw-alias-border-l1)',
657
- background: 'transparent', color: 'var(--dsw-alias-label-primary)', font: 'inherit', fontSize: '12px', maxWidth: '260px',
1260
+ }, ['gentle', 'default', 'aggressive', 'custom'].map((name) => h('option', {
1261
+ key: name,
1262
+ value: name,
1263
+ }, text.presets[name] ?? name))),
1264
+ h('span', { style: { fontSize: '10px', color: 'var(--dsw-alias-label-secondary)' } }, text.presetHint)),
1265
+ h('details', { style: { marginTop: '8px' } },
1266
+ h('summary', {
1267
+ style: { fontSize: '11px', color: 'var(--dsw-alias-label-secondary)', cursor: 'pointer' },
1268
+ }, text.rawSettings),
1269
+ h('div', { style: { display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(150px, 1fr))', gap: '6px', marginTop: '8px' } },
1270
+ CFG_FIELDS.map(([path, step]) => h('label', {
1271
+ key: path,
1272
+ style: { display: 'flex', flexDirection: 'column', gap: '2px', fontSize: '11px', color: 'var(--dsw-alias-label-secondary)' },
658
1273
  },
659
- }, Object.entries(text.recoveryOptions).map(([value, label]) => h('option', { key: value, value }, label)))),
660
- h('div', { style: { display: 'flex', alignItems: 'center', gap: '8px', marginTop: '8px', flexWrap: 'wrap' } },
661
- button(text.saveConfig, saveConfig, busy === 'config' || cfgDraft === null),
662
- h('span', { style: { fontSize: '11px', color: 'var(--dsw-alias-label-secondary)' } }, text.recoveryHint)),
1274
+ text.fields[path] ?? path,
1275
+ h('input', {
1276
+ type: 'number', value: cfgGet(path) ?? '', step, min: 0, disabled: busy === 'config',
1277
+ onChange: (event) => cfgSet(path, event.target.value === '' ? '' : Number(event.target.value)),
1278
+ style: {
1279
+ padding: '3px 6px', borderRadius: '5px', border: '1px solid var(--dsw-alias-border-l1)',
1280
+ background: 'transparent', color: 'var(--dsw-alias-label-primary)', font: 'inherit', fontSize: '12px',
1281
+ },
1282
+ }))),
1283
+ h('label', { style: { display: 'flex', flexDirection: 'column', gap: '2px', fontSize: '11px', color: 'var(--dsw-alias-label-secondary)', marginTop: '8px' } },
1284
+ text.recovery,
1285
+ h('select', {
1286
+ value: cfgGet('recovery') ?? 'spill', disabled: busy === 'config',
1287
+ onChange: (event) => cfgSet('recovery', event.target.value),
1288
+ style: {
1289
+ padding: '3px 6px', borderRadius: '5px', border: '1px solid var(--dsw-alias-border-l1)',
1290
+ background: 'transparent', color: 'var(--dsw-alias-label-primary)', font: 'inherit', fontSize: '12px', maxWidth: '260px',
1291
+ },
1292
+ }, Object.entries(text.recoveryOptions).map(([value, label]) => h('option', { key: value, value }, label)))),
1293
+ h('div', { style: { display: 'flex', alignItems: 'center', gap: '8px', marginTop: '8px' } },
1294
+ button(text.saveConfig, saveConfig, busy === 'config' || cfgDraft === null),
1295
+ h('span', { style: { fontSize: '11px', color: 'var(--dsw-alias-label-secondary)' } }, text.recoveryHint)),
1296
+ ),
1297
+ ),
663
1298
  ),
664
1299
  group(text.filters, ['pytest', 'git', 'tsc', 'packageManager', 'generic', 'rtk']),
665
1300
  group(text.retrieval, ['readOutline', 'grepCap']),
1301
+ ]),
1302
+ pane('prose', [
666
1303
  h(Card, null,
667
1304
  h('div', {
668
1305
  style: { display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', gap: '8px' },
@@ -674,9 +1311,6 @@ window.__ModuleLoader__.load({
674
1311
  h(ModeRow, {
675
1312
  id: 'proseStrip', on: modeOf('proseStrip'), text, busy, onToggle: toggle,
676
1313
  }),
677
- h(ModeRow, {
678
- id: 'politenessStrip', on: modeOf('politenessStrip'), text, busy, onToggle: toggle,
679
- }),
680
1314
  ),
681
1315
  h('div', { style: { display: 'flex', gap: '6px', flexWrap: 'wrap', marginTop: '6px' } },
682
1316
  scopes.map((scope) => {
@@ -687,7 +1321,7 @@ window.__ModuleLoader__.load({
687
1321
  role: 'radio',
688
1322
  'aria-checked': on ? 'true' : 'false',
689
1323
  'data-scope': scope,
690
- disabled: !proseOn || busy === 'scope',
1324
+ disabled: busy === 'scope',
691
1325
  onClick: () => setScope(scope),
692
1326
  style: {
693
1327
  padding: '3px 9px', borderRadius: '999px',
@@ -695,12 +1329,57 @@ window.__ModuleLoader__.load({
695
1329
  background: on ? 'var(--dsw-alias-bg-layer-1)' : 'transparent',
696
1330
  color: on ? 'var(--dsw-alias-label-primary)' : 'var(--dsw-alias-label-secondary)',
697
1331
  fontSize: '11px', lineHeight: '16px', font: 'inherit',
698
- cursor: proseOn ? 'pointer' : 'default',
699
- opacity: proseOn ? 1 : 0.55,
1332
+ cursor: 'pointer',
1333
+ opacity: 1,
700
1334
  },
701
1335
  }, text.scopes[scope] ?? scope);
702
1336
  }),
703
1337
  ),
1338
+ h('div', { style: { marginTop: '10px', paddingTop: '10px', borderTop: '1px solid var(--dsw-alias-border-l1)' } },
1339
+ h('div', { style: { display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', gap: '8px' } },
1340
+ h('span', { style: { fontSize: '12px', fontWeight: 600 } }, text.words),
1341
+ h('span', { style: { fontSize: '10px', color: 'var(--dsw-alias-label-secondary)' } }, text.wordsHint)),
1342
+ (wordsDraft ?? []).length === 0
1343
+ ? h('div', { style: { fontSize: '11px', color: 'var(--dsw-alias-label-secondary)', margin: '6px 0' } }, text.emptySegments)
1344
+ : h('div', { style: { display: 'flex', flexDirection: 'column', gap: '4px', marginTop: '6px' } },
1345
+ (wordsDraft ?? []).map((entry, index) => h('div', {
1346
+ key: index,
1347
+ style: { display: 'flex', gap: '6px', alignItems: 'center' },
1348
+ },
1349
+ h('input', {
1350
+ value: entry.word,
1351
+ placeholder: text.wordLabel,
1352
+ maxLength: 40,
1353
+ disabled: busy === 'words',
1354
+ onChange: (event) => setWordRow(index, 'word', event.target.value),
1355
+ style: inputStyle,
1356
+ }),
1357
+ h('input', {
1358
+ value: entry.replace,
1359
+ placeholder: text.replaceLabel,
1360
+ maxLength: 60,
1361
+ disabled: busy === 'words',
1362
+ onChange: (event) => setWordRow(index, 'replace', event.target.value),
1363
+ style: inputStyle,
1364
+ }),
1365
+ h('button', {
1366
+ type: 'button',
1367
+ onClick: () => removeWordRow(index),
1368
+ disabled: busy === 'words',
1369
+ style: {
1370
+ padding: '2px 6px', borderRadius: '5px', fontSize: '11px',
1371
+ border: '1px solid var(--dsw-alias-border-l1)',
1372
+ background: 'var(--dsw-alias-bg-layer-1)',
1373
+ color: 'var(--dsw-alias-state-error-primary)',
1374
+ cursor: 'pointer',
1375
+ },
1376
+ }, '×'),
1377
+ ))),
1378
+ h('div', { style: { display: 'flex', gap: '8px', marginTop: '6px', flexWrap: 'wrap' } },
1379
+ button(text.addWord, addWordRow, busy === 'words'),
1380
+ button(text.saveWords, saveWords, busy === 'words' || (wordsDraft ?? []).every((entry) => entry.word === '' && entry.replace === '')),
1381
+ ),
1382
+ ),
704
1383
  h('div', {
705
1384
  style: {
706
1385
  marginTop: '6px', fontSize: '11px', lineHeight: '16px',
@@ -708,44 +1387,132 @@ window.__ModuleLoader__.load({
708
1387
  },
709
1388
  }, text.proseHint),
710
1389
  ),
1390
+ ]),
1391
+ pane('chat', [
711
1392
  h(Card, null,
712
- h('div', { style: { fontSize: '12px', fontWeight: 600, marginBottom: '6px' } }, text.systemPrompt),
713
- h(ModeRow, { id: 'systemPrompt', on: modeOf('systemPrompt'), text, busy, onToggle: toggle }),
714
- h('div', { style: { display: 'flex', flexDirection: 'column', gap: '6px', marginTop: '6px' } },
715
- spSegments.length === 0
716
- ? h('div', {
717
- style: { fontSize: '11px', lineHeight: '16px', color: 'var(--dsw-alias-label-secondary)' },
718
- }, text.emptySegments)
719
- : spSegments.map((segment, index) => h(SegmentCard, {
720
- key: segment.id ?? index,
721
- segment,
722
- index,
723
- count: spSegments.length,
724
- text,
725
- disabled: !modeOf('systemPrompt'),
726
- onText: (value) => setSegmentText(index, value),
727
- onMove: (delta) => moveSegment(index, delta),
728
- onRemove: () => removeSegment(index),
729
- })),
730
- ),
731
- h('div', { style: { display: 'flex', alignItems: 'center', gap: '8px', marginTop: '6px', flexWrap: 'wrap' } },
732
- button(text.addSegment, () => { addSegment(); }, !modeOf('systemPrompt') || busy === 'systemPrompt'),
733
- button(text.saveSystemPrompt, () => { saveSystemPrompt(); }, !modeOf('systemPrompt') || busy === 'systemPrompt'),
734
- button(text.restoreSystemPrompt, () => { restoreSystemPrompt(); }, !modeOf('systemPrompt') || busy !== ''),
735
- ),
1393
+ h('div', { style: { display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', gap: '8px', marginBottom: '6px' } },
1394
+ h('span', { style: { fontSize: '12px', fontWeight: 600 } }, text.editTitle),
1395
+ h('span', { style: { fontSize: '10px', color: 'var(--dsw-alias-label-secondary)' } }, text.editHint)),
1396
+ editItems === null || editItems.length === 0
1397
+ ? h('div', { style: { fontSize: '11px', lineHeight: '16px', color: 'var(--dsw-alias-label-secondary)' } }, text.editEmpty)
1398
+ : h('div', { style: { display: 'flex', flexDirection: 'column', gap: '6px' } },
1399
+ editItems.map((item) => {
1400
+ const drafting = editDraft[item.id] !== undefined;
1401
+ return h('div', {
1402
+ key: item.id,
1403
+ style: {
1404
+ padding: '7px 9px', borderRadius: '8px',
1405
+ border: item.edited ? '1px solid var(--dsw-alias-brand-primary)' : '1px solid var(--dsw-alias-border-l1)',
1406
+ background: 'var(--dsw-alias-bg-layer-1)',
1407
+ },
1408
+ },
1409
+ h('div', { style: { display: 'flex', alignItems: 'center', gap: '6px', marginBottom: '4px' } },
1410
+ h('span', {
1411
+ style: {
1412
+ fontSize: '10px', padding: '1px 6px', borderRadius: '999px',
1413
+ border: '1px solid var(--dsw-alias-border-l1)',
1414
+ color: item.role === 'user' ? 'var(--dsw-alias-label-primary)' : 'var(--dsw-alias-label-secondary)',
1415
+ },
1416
+ }, item.role === 'user' ? text.roleUser : text.roleAssistant),
1417
+ item.edited ? h('span', { style: { fontSize: '10px', color: 'var(--dsw-alias-state-success-primary)' } }, '· edited') : null,
1418
+ h('div', { style: { flex: '1 1 auto', minWidth: 0 } }),
1419
+ !drafting ? button(text.editNow, () => setEditDraft((draft) => ({ ...draft, [item.id]: item.text })), false) : null,
1420
+ ),
1421
+ drafting
1422
+ ? h('textarea', {
1423
+ value: editDraft[item.id],
1424
+ maxLength: 20000,
1425
+ rows: 3,
1426
+ onChange: (event) => setEditDraft((draft) => ({ ...draft, [item.id]: event.target.value })),
1427
+ style: {
1428
+ ...inputStyle, width: '100%', resize: 'vertical', flex: '1 1 auto',
1429
+ },
1430
+ })
1431
+ : h('div', {
1432
+ style: {
1433
+ fontSize: '11px', lineHeight: '16px', color: 'var(--dsw-alias-label-secondary)',
1434
+ whiteSpace: 'pre-wrap', overflowWrap: 'anywhere',
1435
+ },
1436
+ }, item.text),
1437
+ h('div', { style: { display: 'flex', gap: '6px', marginTop: '6px' } },
1438
+ drafting
1439
+ ? button(text.editSaving, () => { commitEdit(item.id, editDraft[item.id].trim() === '' ? null : editDraft[item.id]); }, editBusy === item.id)
1440
+ : null,
1441
+ drafting
1442
+ ? button(text.editCancel, () => setEditDraft((draft) => { const next = { ...draft }; delete next[item.id]; return next; }), editBusy === item.id)
1443
+ : null,
1444
+ item.edited && !drafting
1445
+ ? button(text.editRestore, () => commitEdit(item.id, null), editBusy === item.id)
1446
+ : null),
1447
+ );
1448
+ }),
1449
+ ),
1450
+ ),
1451
+ h(Card, null,
1452
+ h('div', { style: { display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', gap: '8px', marginBottom: '6px' } },
1453
+ h('span', { style: { fontSize: '12px', fontWeight: 600 } }, text.notes),
1454
+ h('span', { style: { fontSize: '10px', color: 'var(--dsw-alias-label-secondary)' } }, text.notesHint)),
1455
+ (Array.isArray(state?.recent) && state.recent.length > 0)
1456
+ ? h('div', { style: { display: 'flex', flexDirection: 'column', gap: '6px' } },
1457
+ state.recent.slice(0, 20).map((entry, index) => h('div', {
1458
+ key: index,
1459
+ style: {
1460
+ padding: '5px 8px', borderRadius: '6px', minWidth: 0,
1461
+ border: '1px solid var(--dsw-alias-border-l1)',
1462
+ background: 'var(--dsw-alias-bg-layer-1)',
1463
+ },
1464
+ },
1465
+ h('div', {
1466
+ style: {
1467
+ display: 'flex', gap: '8px', fontSize: '10px', lineHeight: '14px',
1468
+ marginBottom: '2px', color: 'var(--dsw-alias-label-secondary)',
1469
+ },
1470
+ },
1471
+ h('span', { style: { fontWeight: 600, color: 'var(--dsw-alias-label-primary)' } }, entry.label),
1472
+ h('span', null, text.notesAgo(Math.max(0, (Date.now() - entry.at) / 1000)))),
1473
+ h(DiffLine, { segments: entry.diff, notes: entry.notes }),
1474
+ )),
1475
+ )
1476
+ : h('div', { style: { fontSize: '11px', color: 'var(--dsw-alias-label-secondary)' } }, text.notesEmpty),
1477
+ ),
1478
+ ]),
1479
+ pane('prompt', [
1480
+ h(Card, null,
1481
+ h('div', { style: { display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', gap: '8px', marginBottom: '6px' } },
1482
+ h('span', { style: { fontSize: '12px', fontWeight: 600 } }, text.prompt),
1483
+ h('span', { style: { fontSize: '10px', color: 'var(--dsw-alias-label-secondary)' } },
1484
+ prompt === null ? '' : text.promptStats(prompt.sections, prompt.text.length))),
1485
+ h('div', { style: { display: 'flex', alignItems: 'center', gap: '8px', flexWrap: 'wrap' } },
1486
+ button(promptBusy ? text.promptRefreshing : text.promptFetch, () => { readPrompt(); }, promptBusy),
1487
+ prompt === null || prompt.text === ''
1488
+ ? null
1489
+ : button(promptCopied ? text.promptCopied : text.promptCopy, () => { copyPrompt(); }, false)),
1490
+ prompt === null
1491
+ ? h('div', { style: { marginTop: '6px', fontSize: '11px', lineHeight: '16px', color: 'var(--dsw-alias-label-secondary)' } }, text.promptHint)
1492
+ : prompt.none === true
1493
+ ? h('div', { style: { marginTop: '6px', fontSize: '11px', lineHeight: '16px', color: 'var(--dsw-alias-label-secondary)' } }, text.promptNone)
1494
+ : prompt.text === ''
1495
+ ? h('div', { style: { marginTop: '6px', fontSize: '11px', color: 'var(--dsw-alias-label-secondary)' } }, text.promptEmpty)
1496
+ : h('pre', {
1497
+ style: {
1498
+ margin: '8px 0 0', padding: '8px 10px', borderRadius: '8px',
1499
+ border: '1px solid var(--dsw-alias-border-l1)',
1500
+ background: 'var(--dsw-alias-bg-layer-1)',
1501
+ color: 'var(--dsw-alias-label-primary)',
1502
+ font: 'inherit', fontSize: '11px', lineHeight: '17px',
1503
+ whiteSpace: 'pre-wrap', overflowWrap: 'anywhere',
1504
+ maxHeight: '320px', overflowY: 'auto',
1505
+ },
1506
+ }, prompt.text),
736
1507
  h('div', {
737
1508
  style: {
738
1509
  marginTop: '6px', fontSize: '11px', lineHeight: '16px',
739
1510
  color: 'var(--dsw-alias-label-secondary)',
740
1511
  },
741
- }, text.systemPromptHint),
742
- h('div', {
743
- style: {
744
- marginTop: '3px', fontSize: '11px', lineHeight: '16px',
745
- color: 'var(--dsw-alias-label-secondary)',
746
- },
747
- }, text.systemPromptVariables),
1512
+ }, text.promptHint),
748
1513
  ),
1514
+ ]),
1515
+ pane('overview', [
749
1516
  h(Card, null,
750
1517
  h('div', { style: { fontSize: '12px', fontWeight: 600, marginBottom: '4px' } }, text.byTool),
751
1518
  tools.length === 0
@@ -800,18 +1567,117 @@ window.__ModuleLoader__.load({
800
1567
  : button(text.reset, () => { setConfirming(true); }, busy === 'reset' || state === null),
801
1568
  ),
802
1569
  ),
1570
+ ]),
1571
+ pane('about', [
1572
+ h(Card, null,
1573
+ h('div', { style: { display: 'flex', alignItems: 'baseline', gap: '10px', flexWrap: 'wrap' } },
1574
+ h('span', { style: { fontSize: '16px', fontWeight: 600 } }, 'Oh My Token'),
1575
+ h('span', {
1576
+ style: { fontSize: '11px', fontVariantNumeric: 'tabular-nums', color: 'var(--dsw-alias-label-secondary)' },
1577
+ }, `v${state?.version || '—'}`)),
1578
+ h('div', {
1579
+ style: { marginTop: '4px', fontSize: '11px', color: 'var(--dsw-alias-label-secondary)' },
1580
+ }, 'dsh-oh-my-token · MIT'),
1581
+ h('div', {
1582
+ style: { marginTop: '8px', fontSize: '11px', lineHeight: '17px', color: 'var(--dsw-alias-label-secondary)' },
1583
+ }, text.aboutHint),
1584
+ h('div', { style: { marginTop: '12px', display: 'flex', gap: '8px', flexWrap: 'wrap' } },
1585
+ h('a', {
1586
+ href: state?.repo ?? 'https://github.com/dtyg123/dsh-oh-my-token',
1587
+ target: '_blank',
1588
+ rel: 'noreferrer noopener',
1589
+ style: {
1590
+ display: 'inline-flex', alignItems: 'center', gap: '4px', padding: '4px 12px',
1591
+ borderRadius: '6px', textDecoration: 'none', font: 'inherit', fontSize: '11px',
1592
+ lineHeight: '18px', border: '1px solid var(--dsw-alias-brand-primary)',
1593
+ background: 'var(--dsw-alias-brand-primary)', color: 'var(--dsw-alias-bg-base)',
1594
+ },
1595
+ }, text.aboutOpen)),
1596
+ h('div', {
1597
+ style: { marginTop: '8px', fontSize: '10px', color: 'var(--dsw-alias-label-secondary)' },
1598
+ }, text.aboutLicense),
1599
+ ),
1600
+ ]),
803
1601
  );
804
1602
  }
805
1603
 
806
1604
  return {
807
1605
  inject: ['slots'],
808
1606
  apply(ctx) {
1607
+ // Messages and replies are decorated in their finished DOM; the pass is
1608
+ // a no-op when nothing matches.
1609
+ let decorateNow = () => {};
1610
+ if (typeof document !== 'undefined' && typeof MutationObserver !== 'undefined') {
1611
+ let scheduled = 0;
1612
+ let applying = false;
1613
+ decorateNow = () => {
1614
+ applying = true;
1615
+ try {
1616
+ decorateChat();
1617
+ } finally {
1618
+ applying = false;
1619
+ }
1620
+ };
1621
+ const schedule = () => {
1622
+ if (applying || scheduled !== 0) return;
1623
+ scheduled = setTimeout(() => {
1624
+ scheduled = 0;
1625
+ decorateNow();
1626
+ }, 120);
1627
+ };
1628
+ const observer = new MutationObserver(schedule);
1629
+ observer.observe(document.body, { childList: true, subtree: true, characterData: true });
1630
+ ctx.effect(() => () => {
1631
+ observer.disconnect();
1632
+ if (scheduled !== 0) clearTimeout(scheduled);
1633
+ });
1634
+ decorateNow();
1635
+ }
1636
+ nudgeDiffRules = () => { decorateNow(); };
1637
+
1638
+ // Keep the message → change map warm even while the settings page is
1639
+ // closed, because the chat renders messages at any time.
1640
+ const refreshDiffs = () => {
1641
+ fetch(STATE_ENDPOINT, { headers: { accept: 'application/json' } })
1642
+ .then((response) => (response.ok ? response.json() : null))
1643
+ .then((body) => {
1644
+ const changed = rememberDiffs(body?.recent) || rememberEdits(body?.editDiffs);
1645
+ if (changed) decorateNow();
1646
+ })
1647
+ .catch(() => {});
1648
+ };
1649
+ refreshDiffs();
1650
+ const timer = setInterval(refreshDiffs, 3000);
1651
+ ctx.effect(() => () => {
1652
+ clearInterval(timer);
1653
+ });
1654
+
809
1655
  ctx.slots.inject('settings.section', () => ctx.slots.register({
810
1656
  name: 'settings.section',
811
1657
  id: 'dsh-oh-my-token',
812
1658
  order: 61,
813
1659
  label: () => TEXT.nav,
814
1660
  }, SavingsPage));
1661
+
1662
+ // 改写 lives in the harness's own message slots, so its reconciler owns
1663
+ // the DOM. A slot option this harness rejects must never take the
1664
+ // plugin (and the rest of the UI) down with it.
1665
+ const tryRegister = (name, options) => {
1666
+ ctx.slots.inject(name, () => {
1667
+ try {
1668
+ return ctx.slots.register({ ...options, name }, EditControl);
1669
+ } catch (error) {
1670
+ console.warn('oh-my-token: slot', name, String(error?.message ?? error));
1671
+ return () => {};
1672
+ }
1673
+ });
1674
+ };
1675
+ // `conversation.chat.user.before` is a chain slot: it elects one entry
1676
+ // through a pure selector, and only for a real user row.
1677
+ tryRegister('conversation.chat.user.before', {
1678
+ select: (owner) => (owner?.kind === 'user' ? { edit: true } : null),
1679
+ });
1680
+ tryRegister('conversation.chat.assistant-actions', { id: DIFF_RULE_ID });
815
1681
  },
816
1682
  };
817
1683
  },