@240xu/dsh-message-ops 0.24.0 → 0.47.1

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/src/client.js CHANGED
@@ -1,17 +1,19 @@
1
1
  /* global window, document, fetch, navigator */
2
2
  /**
3
- * dsh-message-ops 客户端:会话头部按钮 + 共享操作对话框 + 侧栏行菜单项。
4
- * 一个对话框承载回滚 / 删除 / 分支三种操作;日志 append-only,遮蔽可恢复。
5
- * 结构照抄 @huanlin/dsh-plugin-session-delete。事故复盘见 README「历史事故记录」#1。
3
+ * dsh-message-ops 客户端 —— **生成文件,勿直接编辑**。
4
+ *
5
+ * 源片段:src/client/*.js(按文件名排序,拼接进同一个 factory 闭包)。
6
+ * 重新生成:npm run build:client(prepack 自动执行)。
7
+ *
8
+ * 结构:会话头部按钮 + 操作面板 + 用户消息动作行(回撤 / 编辑)+ 恢复贴条;
9
+ * 日志 append-only,回撤靠 surface replace 遮蔽、恢复靠重放。
6
10
  */
7
11
  window.__ModuleLoader__.load({
8
12
  id: '@240xu/dsh-message-ops',
9
13
  factory: require => {
14
+ // ══ 00-core · 常量 / 小工具 / 消息读缓存 ══
10
15
  const React = require('react')
11
- const { useCallback, useEffect, useRef, useState } = React
12
- // 0.24.0:不再 require('@deepseek-ai/dsh-client-ui-primitives') 的 Modal ——
13
- // 唯一使用者 OpsDialog 已删;面板/编辑框都是自绘浮层。
14
-
16
+ const { useCallback, useEffect, useMemo, useRef, useState } = React
15
17
  const SLOT = 'conversation.session.header.actions'
16
18
  const ROW_ID = 'message-ops'
17
19
  const OVERLAY_SLOT = 'shell.overlay'
@@ -19,23 +21,111 @@ window.__ModuleLoader__.load({
19
21
  const INPUT_DOCK_ID = 'message-ops-revert-dock'
20
22
  const DIALOG_ID = 'message-ops-dialog'
21
23
  const EVENT = 'dsh-message-ops:open'
24
+ /**
25
+ * 宿主 CSS-module hash(**单点**,审计 §3.1)。
26
+ *
27
+ * ⚠️ 这是本插件跨版本最脆的一处依赖:这些类名是宿主 CSS module 编译产物,
28
+ * **每个版本都可能变**(README 事故:0.9.0 写死 `Sixlwa_*` 前缀 → 宿主换成
29
+ * `EvIC1a_*` → 锚点集为空 → 按钮拿不到 seq → 点击必失败;`_flowItem` 当兜底
30
+ * → 把官方 turn-tail 当用户消息挂回滚按钮)。现在写法已修正为
31
+ * 「**稳定属性 `data-chat-flow-kind` 优先 + hash-immune 后缀 `_userRow` 兜底**」,
32
+ * 全 hash 只在宿主确实提供、且无法用稳定属性表达的地方用。
33
+ *
34
+ * 新增候选**只加这里**,不许在各调用点各写一份 —— 否则宿主一升级,
35
+ * 4 处漏 1 处 = 「一半按钮挂得上、一半挂不上」。
36
+ * 只收录**真有消费点**的 hash:`Sixlwa_userStack`/`EvIC1a_flowItem`/`TS9iAW_*`
37
+ * 在本文件没有任何全 hash 消费(前两者靠 `_userStack`/`_flowItem` 后缀与稳定属性,
38
+ * 后者宿主换过一轮、我们根本没碰 TurnTailNodeView),收进来就是新的死配置。
39
+ */
40
+ const HOST_CLS = {
41
+ actions: 'xzv4MW_actions', // MessageIconActions.module.css(官方用户消息动作行)
42
+ userRow: 'Sixlwa_userRow', // MessageItem.module.css(用户消息容器)
43
+ }
22
44
  // 0.5.2(P2):回滚/恢复成功后广播 → RevertDock 重拉标记(否则 dock 只在切会话时刷新)
23
45
  const CHANGED_EVENT = 'dsh-message-ops:changed'
24
- // 0.9.7(P4):messageId→seq 索引失效(dataSig 变化)—— 已挂载的
25
- // MsgSlotActions 靠它重跑解析 effect,否则「新 AI 消息旁没有按钮」。
26
- const SEQ_INDEX_EVENT = 'dsh-message-ops:seq-index'
27
- // 0.9.7(P0-2 读合并):一次写操作会同时触发 150/700/1600ms 三连 +
46
+ // 0.33.3:会话切换广播(dock 渲染时发现 sessionId 变化 → 面板据此关闭,
47
+ // 避免界面上已是新会话、面板还在对旧会话执行 revert/delete)。
48
+ const SESSION_EVENT = 'dsh-message-ops:session-changed'
49
+ // 0.9.7(P0-2 读合并):一次写操作会同时触发「写后立即一次刷新」+
28
50
  // RevertDock 的 CHANGED 重拉 + openSession 后 MO 调度的 scan(5~6 次 GET)。
29
- // 同一会话在此窗口内的请求共享同一个 promise;窗口**必须 < 1600ms**,
30
- // 否则「视图重建后重算隐藏」的 1600ms 兜底会被上一次响应吞掉。
51
+ // 同一会话在此窗口内的请求共享同一个 promise。
52
+ // 0.25.0(手感):尾随兜底刷新由 __refreshSurface 的 300ms 防抖承担,且它拉取前
53
+ // 会先 invalidateMessagesMemo() 强制走真网络 —— 所以本窗口值不再与刷新时机挂钩。
31
54
  const MSG_COALESCE_MS = 1000
55
+ // 0.39.3:读路径统一超时口径(原来只有写路径走 fetchWithTimeout,后端挂起时
56
+ // 列表/搜索/详情/回收站会永久 loading)。测试可调小(client-cov 审计 P3-3)。
57
+ var __readTimeoutMs = 15000
58
+ var setReadTimeoutForTests = ms => {
59
+ __readTimeoutMs = Number.isSafeInteger(ms) && ms > 0 ? ms : 15000
60
+ }
61
+ var getReadTimeoutForTests = () => __readTimeoutMs
32
62
  var __messagesMemo = { url: null, at: 0, p: null, settled: false }
33
63
  var invalidateMessagesMemo = () => {
34
64
  __messagesMemo = { url: null, at: 0, p: null, settled: false }
35
65
  }
66
+
67
+ /**
68
+ * 统一读 `/api/message-ops/*` 响应体(审计 §2.4 单点)。
69
+ *
70
+ * 改前有**三套**写法:`res.json().catch(() => null)`(6 处)、
71
+ * `.catch(() => ({}))`(2 处)、`try { ... } catch {}`(2 处)。其中
72
+ * `catch(() => null)` 把「服务端返回非 JSON 的 500 页面」与「返回了 JSON 但
73
+ * `ok:false`」压成同一个 `null` → 真正的 `data.error` 丢了 → 写操作
74
+ * (revert / restore)的用户可见文案坍缩成 `HTTP 500`,看不到「会话正在运行」
75
+ * 这类真原因。
76
+ *
77
+ * 本函数**只负责读**:恒返回对象(解析失败 / 空 body = `{}`),**绝不抛、绝不
78
+ * null** —— 调用方才能统一按 `data.error || 'HTTP ' + status` 拼文案。
79
+ * 成功判定统一走 `ok`(HTTP 2xx **且** 业务 `data.ok === true`,服务端所有
80
+ * 路由成功都回 `{ ok: true, ... }`)。
81
+ *
82
+ * ⚠️ 它**不**替代 fetch、不判 409、不碰 AbortController —— `setTarget(running:true)`
83
+ * 这类组件语义分支仍留在各调用点(审计 §6.1:万能 `fetchOpsJson` 不值得抽)。
84
+ *
85
+ * @returns {Promise<{ok: boolean, status: number, data: object}>}
86
+ */
87
+ var readOpsJson = async res => {
88
+ let data = null
89
+ try {
90
+ data = await res.json()
91
+ } catch {
92
+ /* 非 JSON 响应(网关 HTML 500 页 / 空 body):按空对象处理,别丢 round-trip */
93
+ }
94
+ if (!data || typeof data !== 'object') data = {}
95
+ return { ok: res.ok === true && data.ok === true, status: Number(res.status) || 0, data }
96
+ }
97
+
98
+ /**
99
+ * 把任意 catch 值转成用户可读文案(审计 §3.4 单点:原先同一表达式写 13 遍)。
100
+ *
101
+ * @param reason - catch 到的任意值(Error / string / undefined)
102
+ * @param prefix - 前置文案(通常是 `t('errorPrefix')` / `t('panel.loadFail')`)
103
+ */
104
+ var errText = (reason, prefix) => String(prefix || '') + (reason && reason.message ? reason.message : String(reason))
105
+
106
+ /** 统一失败出口:服务端文案优先,退 `HTTP <status>`(`status` 为 0 时退 `?`)。 */
107
+ // 0.38.0:必须把 HTTP 状态挂在错误对象上 —— 调用方(dock 的 409/404 分支)
108
+ // 靠 `reason.status` 判别「标记已失效 / 会话已不存在」。旧实现只留 message,
109
+ // 于是 0.36.2 的「404 摘行并隐藏」永远走不到(实测:dock 留着一个点了就报错的死行)。
110
+ var opsError = (status, data) => {
111
+ const err = new Error((data && data.error) || 'HTTP ' + (status || '?'))
112
+ if (Number.isFinite(status)) err.status = status
113
+ if (data && typeof data === 'object') err.data = data
114
+ return err
115
+ }
36
116
  const SYNTHETIC_TURN_STYLE_ID = 'dsh-message-ops-synthetic-turn-hide'
37
- const syncSyntheticTurnStyle = messages => {
117
+ // 0.32.2:turn 号每个会话都从 1 起,旧的全局规则没有会话维度 —— 切会话后
118
+ // 在新会话首次取数前,旧规则会把 B 的同号 turn-process 行误藏。sid 变化即
119
+ // 丢弃旧规则,再由调用方按新会话数据重算。
120
+ let syntheticStyleSid = null
121
+ const syncSyntheticTurnStyle = (messages, sid) => {
38
122
  if (typeof document === 'undefined' || !document.head) return
123
+ const key = String(sid || '')
124
+ if (key !== syntheticStyleSid) {
125
+ syntheticStyleSid = key
126
+ const stale = document.getElementById(SYNTHETIC_TURN_STYLE_ID)
127
+ if (stale) stale.remove()
128
+ }
39
129
  const turns = new Set()
40
130
  for (const m of messages || []) {
41
131
  if (m && m.syntheticTurn === true && Number.isSafeInteger(m.turn)) turns.add(m.turn)
@@ -54,9 +144,113 @@ window.__ModuleLoader__.load({
54
144
  .map(turn => '[data-chat-flow-kind="turn-process"][data-chat-turn="' + turn + '"]{display:none!important}')
55
145
  .join('\n')
56
146
  }
147
+ /**
148
+ * 0.25.0(手感)面板全文取数层:缓存 + 尾随防抖 + 单飞。
149
+ *
150
+ * 改前:面板 `pick` 每选中一条就直连一次 `GET /api/message-ops/text`,
151
+ * 无缓存、无防抖 —— 用 ↑/↓ 连续划过列表时按条发请求(服务端每条都要
152
+ * 解析一次会话日志),而用户真正停下来看的只有最后那一条;回看同一
153
+ * seq 也照样重打一遍。
154
+ * 改后:① 命中过的 `sid|seq` 零请求;② 150ms 尾随防抖,快速划过时只发
155
+ * 停下来的那一条;③ 同 key 在途请求共享同一个 promise(不重复发)。
156
+ *
157
+ * 失效:`emitChanged()`(任何写操作后全文都可能变)清空整张表;缓存键
158
+ * 带 sessionId,切会话天然隔离。**只缓存成功拿到的非空全文** —— 失败
159
+ * 不缓存,否则一次网络抖动会把详情永久钉在 snippet 上(MED-5 红线:
160
+ * snippet 不许冒充原文,失败时由调用方回退并保持「这不是全文」的语义)。
161
+ *
162
+ * 0.46.0(client-cov P3-1):返回值除「全文 / null(真失败)」外,多了两个
163
+ * **非失败终态哨兵**:被 `clearPanelTextCache()` 作废(写操作后原文可能已变)
164
+ * 与读请求超时。旧实现把作废也收成 `null`,于是「一次请求都没发」的详情区
165
+ * 会误报「原文读取失败」。用哨兵而不是 `AbortError` 的原因:超时本身就是
166
+ * `AbortError`,取消若也用同一个错误名就无法再区分(超时文案必须保留)。
167
+ */
168
+ const PANEL_TEXT_DEBOUNCE_MS = 150
169
+ const PANEL_TEXT_CANCELLED = Object.freeze({ cancelled: true })
170
+ const PANEL_TEXT_TIMEOUT = Object.freeze({ timeout: true })
171
+ var __panelTextCache = new Map()
172
+ /** key → 单飞项(含 promise 与结算函数);防抖窗口内也登记,取消时按此结算。 */
173
+ var __panelTextInflight = new Map()
174
+ /** 最近一次尚未发出请求的防抖项;被更新的一次选择取代时以 null 收尾。 */
175
+ var __panelTextPending = null
176
+ /** 从单飞表摘掉自己(可能已被 clear 清空,或被同 key 的新请求取代)。 */
177
+ const dropPanelTextEntry = (key, entry) => {
178
+ if (__panelTextInflight.get(key) === entry) __panelTextInflight.delete(key)
179
+ }
180
+ const clearPanelTextCache = () => {
181
+ __panelTextCache.clear()
182
+ const dropped = Array.from(__panelTextInflight.values())
183
+ __panelTextInflight.clear()
184
+ if (__panelTextPending) {
185
+ clearTimeout(__panelTextPending.timer)
186
+ __panelTextPending = null
187
+ }
188
+ // 写操作作废在途请求:结算为「已取消」而不是 null(null 在调用点代表真失败)。
189
+ for (const entry of dropped) entry.cancel()
190
+ }
191
+ var loadPanelText = (sessionId, seq) => {
192
+ const sid = String(sessionId == null ? '' : sessionId)
193
+ if (!sid || seq == null) return Promise.resolve(null)
194
+ const key = sid + '|' + String(seq)
195
+ const hit = __panelTextCache.get(key)
196
+ if (hit != null) return Promise.resolve(hit)
197
+ const inflight = __panelTextInflight.get(key)
198
+ if (inflight) return inflight.promise
199
+ // 尾随防抖:被更新的一次选择取代时,上一次的 promise 以 null 收尾
200
+ // (调用方本来就按 detailReq 竞态序号丢弃过期结果;这不算「取消」,否则
201
+ // 每次划动都会触发一次重取)。同时撤回单飞登记,失败态不许占坑。
202
+ if (__panelTextPending) {
203
+ const prev = __panelTextPending
204
+ __panelTextPending = null
205
+ clearTimeout(prev.timer)
206
+ prev.discard()
207
+ }
208
+ let settle = null
209
+ const entry = {
210
+ settled: false,
211
+ promise: new Promise(resolve => {
212
+ settle = resolve
213
+ }),
214
+ settle(outcome) {
215
+ if (this.settled) return
216
+ this.settled = true
217
+ dropPanelTextEntry(key, this)
218
+ settle(outcome)
219
+ },
220
+ discard() {
221
+ this.settle(null)
222
+ },
223
+ cancel() {
224
+ this.settle(PANEL_TEXT_CANCELLED)
225
+ },
226
+ }
227
+ __panelTextInflight.set(key, entry)
228
+ const timer = setTimeout(() => {
229
+ __panelTextPending = null
230
+ const url = '/api/message-ops/text?sessionId=' + encodeURIComponent(sid) + '&seq=' + encodeURIComponent(seq)
231
+ fetchWithTimeout(url, undefined, __readTimeoutMs)
232
+ .then(readOpsJson)
233
+ .then(r => {
234
+ if (!r.ok) throw opsError(r.status, r.data)
235
+ const full = typeof r.data.text === 'string' && r.data.text !== '' ? r.data.text : null
236
+ // 已被作废的请求晚到也不许回填缓存:那份全文可能是写操作前的旧数据。
237
+ if (full != null && !entry.settled) __panelTextCache.set(key, full)
238
+ return full
239
+ })
240
+ .catch(reason => {
241
+ // 只有超时是 AbortError;取消走哨兵,不落在这条分支。
242
+ if (reason && (reason.name === 'AbortError' || reason.code === 'ABORT_ERR')) return PANEL_TEXT_TIMEOUT
243
+ return null
244
+ })
245
+ .then(outcome => entry.settle(outcome))
246
+ }, PANEL_TEXT_DEBOUNCE_MS)
247
+ __panelTextPending = { timer, discard: () => entry.discard() }
248
+ return entry.promise
249
+ }
57
250
  const emitChanged = () => {
58
251
  // 数据变了:连同本地缓存一起作废(否则 8s TTL 会让 openSession 后的
59
252
  // scan 拿旧 payload 重算隐藏 = 「回滚了但界面没变」)。
253
+ clearPanelTextCache()
60
254
  invalidateMessagesMemo()
61
255
  if (__peekRowsCache) {
62
256
  const c = __peekRowsCache()
@@ -75,7 +269,8 @@ window.__ModuleLoader__.load({
75
269
  * - 并发调用共享同一个 promise;
76
270
  * - 已结算的响应在 MSG_COALESCE_MS 内复用(一次写操作的 5~6 路重拉 → 1~2 次网络);
77
271
  * - 只在 `ok:true` 时才留窗口:失败/非 2xx 立刻作废,免得把后续重试也吃掉;
78
- * - 1600ms 那档兜底刷新由调用方先 `invalidateMessagesMemo()` 再拉,保证是真网络。
272
+ * - 尾随兜底刷新(`__refreshSurface` 的 300ms 防抖)自己先 `invalidateMessagesMemo()`
273
+ * 再拉,保证是真网络。
79
274
  */
80
275
  var fetchMessagesJson = rawUrl => {
81
276
  // 归一 sessionId 写法:本文件有的调用方传 `session-xxx`(dock / 对话框),
@@ -85,18 +280,13 @@ window.__ModuleLoader__.load({
85
280
  const m = __messagesMemo
86
281
  if (m.url === url && m.p && (!m.settled || Date.now() - m.at < MSG_COALESCE_MS)) return m.p
87
282
  const entry = { url, at: Date.now(), p: null, settled: false }
88
- entry.p = fetch(url)
89
- .then(r =>
90
- r
91
- .json()
92
- .catch(() => null)
93
- .then(d => ({ r, d })),
94
- )
95
- .then(({ r, d }) => {
96
- if (!r.ok || !d || d.ok !== true) throw new Error((d && d.error) || 'HTTP ' + r.status)
283
+ entry.p = fetchWithTimeout(url, undefined, __readTimeoutMs)
284
+ .then(readOpsJson)
285
+ .then(r => {
286
+ if (!r.ok) throw opsError(r.status, r.data)
97
287
  entry.settled = true
98
288
  entry.at = Date.now()
99
- return d
289
+ return r.data
100
290
  })
101
291
  .catch(e => {
102
292
  if (__messagesMemo === entry) invalidateMessagesMemo()
@@ -106,6 +296,8 @@ window.__ModuleLoader__.load({
106
296
  return entry.p
107
297
  }
108
298
 
299
+ // ══ 10-i18n · zh / en 字典 ══
300
+
109
301
  // 0.9.7(P0-4):zh/en 两本字典 key 集合**必须一致且顺序一致**——宿主 locale
110
302
  // 的 translate() 按「活跃语言 → en」回退链查表(zh 回退 en,en 无回退),
111
303
  // 所以缺 key 不一定看得见:zh 缺 → 落到 en(0.9.x 这批 en 值是中文,
@@ -115,59 +307,50 @@ window.__ModuleLoader__.load({
115
307
  'button.title': '消息操作(回滚/删除/分支)',
116
308
  'dialog.title': '消息操作',
117
309
  'dialog.cancel': '关闭',
118
- 'dialog.runningWarn': '⚠ 会话正在运行:请先停止该会话再执行回滚/删除/分支。',
119
310
  'slot.revert': '回滚到此条',
120
311
  'slot.revertPrivacyHint': '回滚到此条(不是删除:AI 看不到,但原文仍在本地会话文件)',
121
312
  'slot.revertUnmatched': '在日志里定位不到这条消息的 seq(通常是模型写的摘要与渲染文本偏差过大)——请改用「消息操作」对话框。',
122
- 'slot.fork': '从此条分叉',
123
- 'slot.forkHint': '复制此条之前的对话到新会话,并把此条原文放回新会话输入框',
124
- 'slot.forkDone': '已分叉:新会话 {id}',
125
313
  'slot.forkUnavailable': '分叉不可用:会话正在运行,或宿主未提供 session/fork',
126
314
  // 0.24.0(P3 入口收敛):改名消除与外部插件 message-edit 的「同名不同义」。
127
315
  // 外部插件在 turnTail 也叫「编辑并重发」,但它 fork 出新分支、源会话不动;
128
316
  // 我们(铅笔)是**回撤源会话**再重发。同名让用户无法预判后果,故显式写出「回撤」。
129
317
  'slot.edit': '编辑并回撤重发',
130
- 'slot.editHint': '打开编辑框;点「发送并回撤」会回撤此条及之后的全部可见消息,再把改后文本当新消息发出',
131
- 'slot.editNoText': '这条消息没有可编辑的文本',
318
+ 'slot.editHint': '打开编辑框;点「撤销并发送」会回撤此条及之后的全部可见消息,再把改后文本当新消息发出',
132
319
  'slot.editUnmatched': '在日志里定位不到这条消息的 seq,暂时无法编辑',
133
320
  'edit.title': '编辑并回撤重发',
134
- 'edit.subtitle': '这条消息 · seq #{seq}',
135
- 'edit.loading': '正在读取原文…',
136
- 'edit.loadFail': '原文读取失败:',
137
- 'edit.retry': '重试',
138
321
  'edit.placeholder': '编辑这条消息…',
139
322
  'edit.cancel': '取消',
140
- 'edit.send': '发送并回撤',
141
- 'edit.sending': '回撤并发送中…',
323
+ 'edit.send': '撤销并发送',
324
+ 'edit.sending': '撤销并发送中…',
325
+ 'edit.sendFailed': '回撤已生效,但发送被拒:',
142
326
  'edit.empty': '内容为空,无法发送',
143
327
  'edit.failed': '回撤失败:',
144
- 'edit.done': '已回撤',
145
328
  'edit.doneSubmitted': '已回撤,改后的消息已提交',
146
329
  'edit.manual': '已回撤,改后的文本已放进输入框——请按回车发送',
147
- 'edit.running': '会话正在运行:需先停止会话再编辑重发',
330
+ 'edit.running': '会话正在运行:可以先改文字,但要等它停下来才能撤销并发送',
148
331
  'edit.replaceHint':
149
332
  '发送会先回撤此条及其之后的全部可见消息,再把改后的文本作为新消息发出。注意:这不是删除——AI 看不到被回撤的内容,但原文仍保留在本地会话文件、可被恢复,直接翻看会话文件仍能读到。',
150
- 'toast.openNew': '打开新会话',
151
- 'fork.official': '分支完成:新会话 {id}',
152
- 'fork.unavailable': '官方分支不可用:通常是因为会话正在运行,请先停止会话后重试。分支功能由 dsh 内置的 session/fork 提供。',
333
+ 'edit.shortcut': 'Enter 发送 · Shift+Enter 换行 · Esc 取消',
153
334
  'done.restore': '恢复完成:重放 {n} 条,跳过不可重放 {s} 条',
154
335
  'done.revert': '已回滚,原文可从恢复区放回',
155
336
  'done.revertNoRefill': '已回滚,但原文未能放回输入框(会话可能尚未挂载);可重试或从消息操作面板手动复制',
156
- 'done.delete': '已遮蔽,刷新页面后生效',
157
- 'action.reload': '刷新页面',
158
337
  errorPrefix: '操作失败:',
159
338
  'dock.title': '已回撤 {n} 条消息',
339
+ 'dock.titlePending': '{n} 轮待恢复(共 {m} 条仍被回撤)',
340
+ 'dock.titleTurns': '已回撤 {n} 条记录',
341
+ 'dock.stale': '这条回撤已被后续回撤取代,已从列表移除。',
160
342
  'dock.expand': '展开回撤列表',
161
343
  'dock.collapse': '折叠回撤列表',
162
- 'dock.shadowedN': '{n} 条已遮蔽',
163
344
  'dock.restore': '恢复',
164
345
  'dock.restoreHint': '恢复为重放:消息将出现在会话末尾,不会回到原位',
165
346
  'dock.restoring': '恢复中…',
166
- 'slot.quote': '引用到输入框',
167
- 'quote.done': '已引用到输入框',
168
- 'quote.unavailable': '引用不可用(输入框不可写或无全文)',
169
- 'quote.sourcePrefix': '引用自 seq {seq}',
170
- 'quote.doneWithSource': '已引用(来自 seq {seq})',
347
+ 'dock.discardLink': '不再恢复,直接丢弃',
348
+ 'dock.discardHint': '丢弃后这段对话永久不再出现在界面,也不会回到输入框;不可撤销',
349
+ 'dock.discardConfirm': '确认永久丢弃这段被回撤的对话(共 {n} 条)?',
350
+ 'dock.discardYes': '确认丢弃',
351
+ 'dock.discardCancel': '取消',
352
+ 'dock.discardDone': '已丢弃:不再恢复这段对话',
353
+ 'dock.discarding': '丢弃中…',
171
354
  'undo.label': '回滚上一条消息',
172
355
  'undo.desc': '移除最后一条用户消息,原文回填输入框',
173
356
  'undo.done.undo': '已回滚上一条消息',
@@ -201,7 +384,8 @@ window.__ModuleLoader__.load({
201
384
  // 告知内容一条没少:AI 看不到 / 原文仍在本地文件 / 可恢复。只是不再分两层说。
202
385
  'panel.revertConfirmBody':
203
386
  '将遮蔽 #{start}–#{end} 共 {n} 条消息(可见 {v} 条)。AI 将看不到它们,但原文仍保留在本地会话文件、可恢复。',
204
- 'panel.deleteConfirmTitle': '仅删除 #{seq}?',
387
+ 'panel.deleteConfirmTitle': '仅遮蔽 #{seq}?',
388
+ 'panel.timeout': '请求超时(结果未知,请刷新确认后再操作)。',
205
389
  'panel.deleteConfirmBody': '将遮蔽这 1 条消息,其他内容不动;日志仍保留,可恢复。',
206
390
  'panel.confirmRevert': '确认回滚',
207
391
  'panel.confirmDeleteOne': '确认遮蔽',
@@ -214,6 +398,9 @@ window.__ModuleLoader__.load({
214
398
  'panel.branch': '从此条分叉',
215
399
  'panel.branchHint': '复制此条之前的对话到新会话,并把此条原文放回新会话输入框',
216
400
  'panel.branchDone': '已分叉:新会话 {id}',
401
+ 'panel.textFail': '读取原文失败,无法分叉(不会用摘要代替)。',
402
+ 'panel.snippetOnly': '原文读取失败,这里只是前 160 字摘要,不是完整消息。',
403
+ 'panel.detailTimeout': '读取全文超时,这里只是前 160 字摘要,不是完整消息。',
217
404
  'panel.branchUserOnly': '分叉只对用户消息可用(AI 消息没有可回填的原文)',
218
405
  // 0.17.0(冲突 R2):行为是「复制原文到输入框」,不修改原消息。
219
406
  // 旧文案「编辑并重发」暗示会改原消息,实测会误导(发出后是新增一条,
@@ -232,6 +419,10 @@ window.__ModuleLoader__.load({
232
419
  'panel.untitled': '未命名会话',
233
420
  'panel.restore': '恢复',
234
421
  'panel.purge': '永久删除',
422
+ // 0.42.0(srv-audit D9/D10):回收站条目异常态(moving=删除中断留孤本;corrupt=清单损坏)
423
+ 'panel.trashMoving': '删除中断,仅存副本留作人工恢复',
424
+ 'panel.trashCorrupt': '清单损坏,只能永久删除',
425
+ 'panel.trashManual': '需人工处理',
235
426
  'panel.purgeConfirm': '再点一次永久删除',
236
427
  'panel.restored': '会话已恢复',
237
428
  'panel.purged': '回收站条目已永久删除',
@@ -244,14 +435,10 @@ window.__ModuleLoader__.load({
244
435
  'button.title': 'Message ops (revert / delete / branch)',
245
436
  'dialog.title': 'Message ops',
246
437
  'dialog.cancel': 'Close',
247
- 'dialog.runningWarn': '⚠ Session is running: stop it before revert / delete / branch.',
248
438
  'slot.revert': 'Revert to here',
249
439
  'slot.revertPrivacyHint': 'Revert to here (not deletion: hidden from the AI, but the original text stays in the local session file)',
250
440
  'slot.revertUnmatched':
251
441
  'Cannot locate this message seq in the log (usually the model-written summary drifted too far from the rendered text) — use the Message ops dialog instead.',
252
- 'slot.fork': 'Branch from here',
253
- 'slot.forkHint': 'Copies the conversation above this message into a new session and puts this message back in the new composer',
254
- 'slot.forkDone': 'Branched: new session {id}',
255
442
  'slot.forkUnavailable': 'Branch unavailable: the session is running, or the host provides no session/fork',
256
443
  // 0.24.0 (P3): renamed to disambiguate from the third-party message-edit plugin,
257
444
  // which also says "Edit and resend" but forks a NEW branch and leaves the source
@@ -259,49 +446,43 @@ window.__ModuleLoader__.load({
259
446
  // consequences — so the revert is now spelled out in the label itself.
260
447
  'slot.edit': 'Edit & revert-resend',
261
448
  'slot.editHint':
262
- 'Opens the editor. Pressing "Send and revert" reverts this message and every visible message after it, then sends the edited text as a new message.',
263
- 'slot.editNoText': 'This message has no text to edit',
449
+ 'Opens the editor. Pressing "Undo and send" reverts this message and every visible message after it, then sends the edited text as a new message.',
264
450
  'slot.editUnmatched': 'Cannot locate this message seq in the log, so it cannot be edited yet',
265
451
  'edit.title': 'Edit & revert-resend',
266
- 'edit.subtitle': 'This message · seq #{seq}',
267
- 'edit.loading': 'Loading the original text…',
268
- 'edit.loadFail': 'Could not load the original text: ',
269
- 'edit.retry': 'Retry',
270
452
  'edit.placeholder': 'Edit this message…',
271
453
  'edit.cancel': 'Cancel',
272
- 'edit.send': 'Send and revert',
273
- 'edit.sending': 'Reverting and sending…',
454
+ 'edit.send': 'Undo and send',
455
+ 'edit.sending': 'Undoing and sending…',
456
+ 'edit.sendFailed': 'The revert went through, but sending was rejected: ',
274
457
  'edit.empty': 'Nothing to send — the text is empty',
275
458
  'edit.failed': 'Revert failed: ',
276
- 'edit.done': 'Reverted',
277
459
  'edit.doneSubmitted': 'Reverted; the edited message has been submitted',
278
460
  'edit.manual': 'Reverted; the edited text is in the composer — press Enter to send',
279
- 'edit.running': 'The session is running: stop it before editing and resending',
461
+ 'edit.running': 'The session is running: edit freely, but Undo and send waits until it stops',
280
462
  'edit.replaceHint':
281
463
  'Sending reverts this message and every visible message after it, then sends the edited text as a new message. Note: this is not deletion — the AI will not see the reverted content, but the original text stays in the local session file, can be restored, and is still readable by opening that file directly.',
282
- 'toast.openNew': 'Open new session',
283
- 'fork.official': 'Branched (official fork): new session {id}',
284
- 'fork.unavailable':
285
- 'Built-in branch unavailable — usually because the session is running. Stop it and retry. Branching is provided by the dsh built-in session/fork.',
464
+ 'edit.shortcut': 'Enter to send · Shift+Enter for a new line · Esc to cancel',
286
465
  'done.restore': 'Restored: replayed {n}, skipped non-replayable {s}',
287
466
  'done.revert': 'Reverted — restore the original from the restore area',
288
467
  'done.revertNoRefill':
289
468
  'Reverted, but the original text could not be put back in the composer (the view may not be mounted yet); retry or copy it manually from Message Ops',
290
- 'done.delete': 'Hidden; reload to apply',
291
- 'action.reload': 'Reload page',
292
469
  errorPrefix: 'Operation failed: ',
293
470
  'dock.title': '{n} rolled back messages',
471
+ 'dock.titlePending': '{n} pending to restore ({m} still rolled back)',
472
+ 'dock.titleTurns': '{n} revert records',
473
+ 'dock.stale': 'This revert was superseded by a later one; removed from the list.',
294
474
  'dock.expand': 'Expand revert list',
295
475
  'dock.collapse': 'Collapse revert list',
296
- 'dock.shadowedN': '{n} shadowed',
297
476
  'dock.restore': 'Restore',
298
477
  'dock.restoreHint': 'Restores by replay: messages appear at the end of the session, not in their original place',
299
478
  'dock.restoring': 'Restoring…',
300
- 'slot.quote': 'Quote to composer',
301
- 'quote.done': 'Quoted into composer',
302
- 'quote.unavailable': 'Quote unavailable (composer locked or no full text)',
303
- 'quote.sourcePrefix': 'Quoted from seq {seq}',
304
- 'quote.doneWithSource': 'Quoted (from seq {seq})',
479
+ 'dock.discardLink': 'Do not restore, discard instead',
480
+ 'dock.discardHint': 'Discarded messages never return to the transcript or the composer; this cannot be undone',
481
+ 'dock.discardConfirm': 'Permanently discard this rolled-back conversation ({n} messages)?',
482
+ 'dock.discardYes': 'Discard',
483
+ 'dock.discardCancel': 'Cancel',
484
+ 'dock.discardDone': 'Discarded: this conversation will not be restored',
485
+ 'dock.discarding': 'Discarding…',
305
486
  'undo.label': 'Undo last message',
306
487
  'undo.desc': 'Remove the last user message and put its original text back into the composer',
307
488
  'undo.done.undo': 'Undid the last message',
@@ -333,7 +514,8 @@ window.__ModuleLoader__.load({
333
514
  'panel.revertConfirmTitle': 'Revert to #{seq}?',
334
515
  'panel.revertConfirmBody':
335
516
  'Shadows {n} messages (#{start}–#{end}, {v} visible). The AI will no longer see them, but the original text stays in the local session file and can be restored.',
336
- 'panel.deleteConfirmTitle': 'Delete only #{seq}?',
517
+ 'panel.deleteConfirmTitle': 'Hide only #{seq}?',
518
+ 'panel.timeout': 'Request timed out (result unknown — refresh before retrying).',
337
519
  'panel.deleteConfirmBody': 'This shadows this one message; everything else stays. The log stays append-only and can be restored.',
338
520
  'panel.confirmRevert': 'Confirm revert',
339
521
  'panel.confirmDeleteOne': 'Confirm hide',
@@ -346,6 +528,9 @@ window.__ModuleLoader__.load({
346
528
  'panel.branch': 'Fork from here',
347
529
  'panel.branchHint': 'Copy the conversation above this message into a new session and put this message back in the new composer',
348
530
  'panel.branchDone': 'Forked: {id}',
531
+ 'panel.textFail': 'Could not read the original text; branch cancelled (a snippet is never used).',
532
+ 'panel.snippetOnly': 'The full text could not be loaded; this is only the first 160 characters.',
533
+ 'panel.detailTimeout': 'Timed out loading the full text; this is only the first 160 characters.',
349
534
  'panel.branchUserOnly': 'Fork works on user messages only (assistant messages have no text to hand back)',
350
535
  'panel.openNew': 'Open new session',
351
536
  'panel.revertDone': 'Revert applied',
@@ -361,6 +546,9 @@ window.__ModuleLoader__.load({
361
546
  'panel.untitled': 'Untitled session',
362
547
  'panel.restore': 'Restore',
363
548
  'panel.purge': 'Delete forever',
549
+ 'panel.trashMoving': 'Delete was interrupted; the only copy is kept for manual recovery',
550
+ 'panel.trashCorrupt': 'Manifest is corrupt; only deleting forever is possible',
551
+ 'panel.trashManual': 'Needs manual handling',
364
552
  'panel.purgeConfirm': 'Click again to delete forever',
365
553
  'panel.restored': 'Session restored',
366
554
  'panel.purged': 'Trash entry permanently deleted',
@@ -369,6 +557,7 @@ window.__ModuleLoader__.load({
369
557
  'menu.ops': 'Message ops',
370
558
  }
371
559
 
560
+ // ══ 20-host-state · 宿主状态:locale / sessions / inputActions / __t / 面板样式 ══
372
561
  var __locale = null
373
562
  var __sessionsSvc = null
374
563
  /**
@@ -388,12 +577,10 @@ window.__ModuleLoader__.load({
388
577
  *
389
578
  * 现在:`sessionId -> InputActions`。读写一律按会话取,
390
579
  * 取不到就走**明确失败路径**,绝不静默退到别的会话。
580
+ * (0.25.0 清理:无 sessionId 的全局兜底变量 `__inputActions` 已删除——
581
+ * 它 0 个读取方,留着只会让后来者以为还有一条「最后一次已知」的退路。)
391
582
  */
392
583
  var __inputActionsBySession = new Map()
393
- // 兜底:仅用于**确实拿不到 sessionId** 的全局路径(如无 session 上下文的
394
- // 工具调用)。任何能拿到 sessionId 的地方都必须用上面的 Map,
395
- // 不允许读这个变量 —— 它是「最后一次已知」,可能属于另一个会话。
396
- var __inputActions = null
397
584
 
398
585
  /** 会话键归一:`session-x` 与 `x` 视为同一会话(宿主两种拼写都会传)。 */
399
586
  function sessionKeyOf(sessionId) {
@@ -415,7 +602,6 @@ window.__ModuleLoader__.load({
415
602
  function rememberInputActions(sessionId, inputActions) {
416
603
  if (!inputActions || typeof inputActions.setDraft !== 'function') return
417
604
  const key = sessionKeyOf(sessionId)
418
- __inputActions = inputActions // 仅供无 sessionId 的全局兜底
419
605
  if (key == null) return
420
606
  __inputActionsBySession.set(key, inputActions)
421
607
  }
@@ -437,10 +623,10 @@ window.__ModuleLoader__.load({
437
623
  // rowsCache 声明在 installUserRevertInjector() 内(闭包私有),而 /undo 的
438
624
  // onPick 在模块级作用域 —— 直接引用会 ReferenceError,表现为点菜单毫无反应。
439
625
  var __peekRowsCache = null // 0.6.0:会话视图会话 id(RevertDock/MsgSlotActions 刷新)
440
- // messageId→seq 索引缓存(每会话一次拉取;0.3.0 assistant-actions 槽用)
441
- var __seqIndexCache = new Map()
442
- // messageId→全文缓存(0.5.0 消息引用用)
443
- var __fullTextCache = new Map()
626
+ // 0.25.0 清理:messageId→seq / messageId→全文 两份缓存已删。
627
+ // 它们唯一的读者是 MsgSlotActions 的引用解析(0.23.0 起该插槽 return null),
628
+ // 写入方 syncSeqIndex 也随之删除;dataSig 驱动的失效广播一并退场。
629
+ // 现在 seq 的唯一权威来源是 rowsCache(DOM 注入器自己按会话维护)。
444
630
 
445
631
  function localeFallbackLang() {
446
632
  if (typeof navigator === 'undefined') return 'zh'
@@ -534,35 +720,9 @@ window.__ModuleLoader__.load({
534
720
  * 几何取自宿主 icon sprite 的 `dsw-icon-list-pen-outline-regular`
535
721
  * (16 viewBox,描边 1.2,与宿主动作行图标同一套视觉)。
536
722
  */
537
- /**
538
- * 分叉图标组件。0.18.0 起**不再用于面板唤起按钮**(那曾造成语义错位:
539
- * "消息操作"面板长着"分叉"的脸),但保留它是因为 `branchIconMarkup`
540
- * 与它共用 `BRANCH_PATH` 常量 —— `test/icon-render.test.js` 锁定了这条同源约束,
541
- * 防止两处各画一套分叉几何而慢慢漂移。
542
- */
543
- function BranchIcon() {
544
- return React.createElement(
545
- 'svg',
546
- {
547
- width: 16,
548
- height: 16,
549
- viewBox: '0 0 16 16',
550
- fill: 'none',
551
- xmlns: 'http://www.w3.org/2000/svg',
552
- 'aria-hidden': 'true',
553
- focusable: 'false',
554
- },
555
- React.createElement('path', {
556
- d: BRANCH_PATH,
557
- stroke: 'currentColor',
558
- strokeWidth: BRANCH_STROKE,
559
- strokeLinecap: 'round',
560
- strokeLinejoin: 'round',
561
- fill: 'none',
562
- }),
563
- )
564
- }
565
-
723
+ // 0.25.0 清理:React 版 `BranchIcon` 组件已删(0 处渲染)。
724
+ // 分叉几何现在只有一个入口 —— 侧栏菜单用的 `branchIconMarkup()`(innerHTML 场景),
725
+ // 两者原本共用 `BRANCH_PATH` / `BRANCH_STROKE`,删掉组件后常量仍是唯一数据源。
566
726
  function OpsPanelIcon() {
567
727
  return React.createElement(
568
728
  'svg',
@@ -625,7 +785,7 @@ window.__ModuleLoader__.load({
625
785
  const tag = document.createElement('style')
626
786
  tag.id = 'dsh-message-ops-panel-style'
627
787
  tag.textContent = [
628
- '.mopsPanelScrim{position:fixed;inset:0;z-index:1200;background:rgba(15,17,21,.28);display:flex;align-items:center;justify-content:center;padding:24px;animation:mopsFade .12s ease-out}',
788
+ '.mopsPanelScrim{position:fixed;inset:0;z-index:1200;background:var(--dsw-alias-bg-mask-1,rgba(15,17,21,.28));display:flex;align-items:center;justify-content:center;padding:24px;animation:mopsFade .12s ease-out}',
629
789
  '@keyframes mopsFade{from{opacity:0}to{opacity:1}}',
630
790
  '@keyframes mopsRise{from{opacity:0;transform:translateY(8px) scale(.985)}to{opacity:1;transform:none}}',
631
791
  '.mopsPanel{width:560px;max-width:min(560px,100%);height:min(760px,100%);max-height:100%;display:flex;flex-direction:column;background:var(--dsw-alias-bg-layer-1,#fff);color:var(--dsw-alias-label-primary,#0f1115);border:1px solid var(--dsw-alias-border-l2,#e6e6e6);box-shadow:0 24px 64px rgba(15,17,21,.24);font-family:inherit;font-size:13px;line-height:1.45;animation:mopsRise .16s cubic-bezier(.2,.8,.3,1)}',
@@ -634,13 +794,15 @@ window.__ModuleLoader__.load({
634
794
  '.mopsPanel button{font:inherit;color:inherit;border-radius:0}',
635
795
  '.mopsPanelHead{display:flex;align-items:flex-start;justify-content:space-between;gap:12px;padding:16px 18px 12px;border-bottom:1px solid var(--dsw-alias-border-l2,#e6e6e6)}',
636
796
  '.mopsPanelKicker{font-size:10px;letter-spacing:.14em;text-transform:uppercase;color:var(--dsw-alias-label-tertiary,#8a8a8e)}',
637
- '.mopsPanelTitle{font-size:15px;font-weight:600;margin-top:2px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;max-width:420px}',
797
+ '.mopsPanelTitle{font-size:15px;font-weight:500;margin-top:2px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;max-width:420px}',
638
798
  '.mopsPanelSub{font-size:11px;color:var(--dsw-alias-label-tertiary,#8a8a8e);margin-top:2px}',
639
799
  '.mopsPanelClose{width:30px;height:30px;border:1px solid var(--dsw-alias-border-l2,#e6e6e6);background:transparent;cursor:pointer;font-size:16px;line-height:1;flex:none}',
640
800
  '.mopsPanelClose:hover{background:var(--dsw-alias-interactive-bg-hover,rgba(15,17,21,.06))}',
641
801
  '.mopsTabs{display:flex;border-bottom:1px solid var(--dsw-alias-border-l2,#e6e6e6)}',
802
+ // 0.33.3:tabpanel 包装层与 .mopsPanel 的纵向 flex 布局等价(不改变视觉)。
803
+ '.mopsTabPanel{flex:1;min-height:0;display:flex;flex-direction:column}',
642
804
  '.mopsTab{flex:1;padding:9px 12px;border:0;border-bottom:2px solid transparent;background:transparent;cursor:pointer;font-size:12px;color:var(--dsw-alias-label-secondary,#6b6b70)}',
643
- '.mopsTab.on{border-bottom-color:var(--dsw-alias-brand-primary,#4d6bfe);color:var(--dsw-alias-label-primary,#0f1115);font-weight:600}',
805
+ '.mopsTab.on{border-bottom-color:var(--dsw-alias-brand-primary,#4d6bfe);color:var(--dsw-alias-label-primary,#0f1115);font-weight:500}',
644
806
  '.mopsSearchRow{display:flex;gap:8px;padding:12px 18px 8px}',
645
807
  '.mopsSearch{flex:1;min-width:0;height:32px;border:1px solid var(--dsw-alias-border-l2,#d8d8d8);background:transparent;color:inherit;padding:0 9px;font:inherit;font-size:12px;outline:none}',
646
808
  '.mopsSearch:focus{border-color:var(--dsw-alias-brand-primary,#4d6bfe)}',
@@ -653,25 +815,25 @@ window.__ModuleLoader__.load({
653
815
  '.mopsList:focus-visible{outline:2px solid var(--dsw-alias-brand-primary,#4d6bfe);outline-offset:-2px}',
654
816
  '.mopsRow{position:absolute;left:0;right:0;display:grid;grid-template-columns:44px 26px minmax(0,1fr) 48px;align-items:center;gap:8px;width:100%;border:0;border-bottom:1px solid var(--dsw-alias-border-l1,#f0f0f0);background:transparent;text-align:left;cursor:pointer;padding:0 12px 0 18px;color:inherit;font:inherit}',
655
817
  '.mopsRow:hover{background:var(--dsw-alias-interactive-bg-hover,rgba(15,17,21,.045))}',
656
- '.mopsRow.on{background:rgba(77,107,254,.08);box-shadow:inset 2px 0 0 var(--dsw-alias-brand-primary,#4d6bfe)}',
818
+ '.mopsRow.on{background:color-mix(in srgb,var(--dsw-alias-brand-primary,#4d6bfe) 10%,transparent);box-shadow:inset 2px 0 0 var(--dsw-alias-brand-primary,#4d6bfe)}',
657
819
  '.mopsRow.shadowed{opacity:.42}',
658
820
  '.mopsSeq{font-variant-numeric:tabular-nums;font-size:10px;color:var(--dsw-alias-label-tertiary,#9a9aa0)}',
659
- '.mopsRole{width:20px;height:20px;display:inline-flex;align-items:center;justify-content:center;border:1px solid var(--dsw-alias-border-l2,#d8d8d8);font-size:9px;font-weight:600;color:var(--dsw-alias-label-secondary,#6b6b70)}',
821
+ '.mopsRole{width:20px;height:20px;display:inline-flex;align-items:center;justify-content:center;border:1px solid var(--dsw-alias-border-l2,#d8d8d8);font-size:9px;font-weight:500;color:var(--dsw-alias-label-secondary,#6b6b70)}',
660
822
  '.mopsSnippet{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:12px}',
661
823
  '.mopsClock{font-size:10px;color:var(--dsw-alias-label-tertiary,#9a9aa0);text-align:right;font-variant-numeric:tabular-nums}',
662
824
  '.mopsEmpty{padding:28px 18px;color:var(--dsw-alias-label-tertiary,#8a8a8e);font-size:12px}',
663
825
  '.mopsErrorState{display:flex;align-items:flex-start;gap:10px;flex-wrap:wrap;color:var(--dsw-alias-state-error-primary,#c63b32)}',
664
826
  '.mopsErrorState .mopsAction{flex:none}',
665
- '.mopsDetail{flex:none;max-height:37%;overflow-y:auto;border-top:1px solid var(--dsw-alias-border-l2,#e6e6e6);padding:12px 18px 10px;background:var(--dsw-alias-bg-secondary,#fafafa)}',
827
+ '.mopsDetail{flex:none;max-height:37%;overflow-y:auto;border-top:1px solid var(--dsw-alias-border-l2,#e6e6e6);padding:12px 18px 10px;background:var(--dsw-alias-bg-layer-2,#f5f5f5)}',
666
828
  '.mopsDetailMeta{display:flex;gap:8px;align-items:center;font-size:10px;color:var(--dsw-alias-label-tertiary,#8a8a8e);margin-bottom:6px}',
667
- '.mopsDetailText{margin:0;white-space:pre-wrap;word-break:break-word;max-height:108px;overflow:auto;font-family:inherit;font-size:12px;line-height:1.55;color:var(--dsw-alias-label-primary,#0f1115)}',
829
+ '.mopsDetailText{margin:0;white-space:pre-wrap;word-break:break-word;max-height:none;overflow:visible;font-family:inherit;font-size:12px;line-height:1.55;color:var(--dsw-alias-label-primary,#0f1115)}',
668
830
  '.mopsDetailHint{padding:10px 0 14px;color:var(--dsw-alias-label-tertiary,#8a8a8e);font-size:12px}',
831
+ '.mopsDetailNote{margin-top:6px;font-size:11px;line-height:1.5;color:var(--dsw-alias-state-warning-primary,#c99a06)}',
669
832
  '.mopsActions{display:flex;gap:6px;flex-wrap:wrap;margin-top:10px}',
670
833
  '.mopsActionConfirm{display:flex;flex-direction:column;gap:7px;margin-top:10px;padding:10px;border:1px solid var(--dsw-alias-border-l2,#e6e6e6);background:var(--dsw-alias-bg-layer-1,#fff)}',
671
- '.mopsImpactTitle{font-size:12px;font-weight:600}',
834
+ '.mopsImpactTitle{font-size:12px;font-weight:500}',
672
835
  '.mopsImpact{font-size:11px;line-height:1.5;color:var(--dsw-alias-label-secondary,#6b6b70)}',
673
836
  // 常显隐私告知条:左竖线 + 灰底,与红色错误条区分;不可关闭,避免"勾了就真删"的误解
674
- '.mopsPrivacyNote{margin-top:2px;padding:6px 9px;border-left:2px solid var(--dsw-alias-label-tertiary,#9a9aa0);background:var(--dsw-alias-bg-layer-2,#efefef);border-radius:0 4px 4px 0;font-size:11px;line-height:1.5;color:var(--dsw-alias-label-secondary,#6b6b70)}',
675
837
  '.mopsAction{height:30px;padding:0 10px;border:1px solid var(--dsw-alias-border-l2,#cfcfcf);background:transparent;cursor:pointer;font-size:11px}',
676
838
  '.mopsAction:hover:not(:disabled){border-color:var(--dsw-alias-label-primary,#0f1115)}',
677
839
  '.mopsAction.primary{border-color:var(--dsw-alias-label-primary,#0f1115);background:var(--dsw-alias-label-primary,#0f1115);color:var(--dsw-alias-bg-layer-1,#fff)}',
@@ -695,8 +857,10 @@ window.__ModuleLoader__.load({
695
857
  '.mopsConfirmRow{display:flex;gap:8px;margin-top:4px}',
696
858
  '.mopsTrashItem{display:flex;align-items:center;gap:10px;padding:11px 18px;border-bottom:1px solid var(--dsw-alias-border-l1,#f0f0f0)}',
697
859
  '.mopsTrashMain{flex:1;min-width:0}',
698
- '.mopsTrashTitle{font-size:12px;font-weight:600;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}',
860
+ '.mopsTrashTitle{font-size:12px;font-weight:500;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}',
699
861
  '.mopsTrashMeta{font-size:10px;color:var(--dsw-alias-label-tertiary,#8a8a8e);margin-top:2px}',
862
+ // 0.42.0:异常态条目(moving / corrupt)不提供 Restore,改显一行说明
863
+ '.mopsTrashNote{flex:none;max-width:150px;font-size:10px;line-height:1.4;text-align:right;color:var(--dsw-alias-label-tertiary,#8a8a8e)}',
700
864
  '@media(max-width:760px){.mopsPanelScrim{padding:0}.mopsPanel{width:100%;height:100%;max-width:100%;max-height:100%;border:0}.mopsDetail{max-height:42%}}',
701
865
  ].join('')
702
866
  document.head.appendChild(tag)
@@ -705,6 +869,22 @@ window.__ModuleLoader__.load({
705
869
  }
706
870
  }
707
871
 
872
+ // ══ 30-panel · 操作面板(列表 / 全文预览 / 回撤 / 删除 / 分叉 / 会话删除) ══
873
+ /**
874
+ * 面板 Esc 的分层决策:busy 期间忽略 → 先退确认层 → 再清搜索 → 最后才关面板。
875
+ * 抽成纯函数是为了能真执行断言(原先埋在 onKey 闭包里,零测试)。
876
+ * @param {{busy: boolean, confirmDelete: boolean, confirmAction: string|null, query: string}} state
877
+ * @returns {'ignore'|'closeConfirm'|'cancelAction'|'clearQuery'|'close'}
878
+ */
879
+ function panelEscapeAction(state) {
880
+ const s = state || {}
881
+ if (s.busy) return 'ignore'
882
+ if (s.confirmDelete) return 'closeConfirm'
883
+ if (s.confirmAction) return 'cancelAction'
884
+ if (s.query && String(s.query).trim()) return 'clearQuery'
885
+ return 'close'
886
+ }
887
+
708
888
  function OpsPanel(props) {
709
889
  const t = (props && props.t) || __t
710
890
  useLocaleRevision()
@@ -734,10 +914,14 @@ window.__ModuleLoader__.load({
734
914
  const [childId, setChildId] = useState(null)
735
915
  const [busy, setBusy] = useState('')
736
916
  const [error, setError] = useState(null)
917
+ // 0.33.3(ui-live P2-2):动作错误与加载错误分开。旧实现共用一个 error,
918
+ // 1s 后的静默重查成功会 setError(null),把刚显示的 409 横幅清掉。
919
+ const [actionError, setActionError] = useState(null)
737
920
  const [done, setDone] = useState('')
738
921
  const [scrollTop, setScrollTop] = useState(0)
739
922
  const [viewport, setViewport] = useState(480)
740
923
  const listRef = useRef(null)
924
+ const scrollRaf = useRef(null)
741
925
  const searchRef = useRef(null)
742
926
  const panelRef = useRef(null)
743
927
  const scrimRef = useRef(null)
@@ -788,6 +972,7 @@ window.__ModuleLoader__.load({
788
972
  setPurgeId(null)
789
973
  setChildId(null)
790
974
  setError(null)
975
+ setActionError(null)
791
976
  setDone('')
792
977
  setScrollTop(0)
793
978
  }
@@ -795,7 +980,33 @@ window.__ModuleLoader__.load({
795
980
  return () => window.removeEventListener(EVENT, handler)
796
981
  }, [])
797
982
 
983
+ // 0.33.3(ui-live P1-2):面板是独立 slot,拿不到 sessionId;会话切换由 dock
984
+ // 广播。继续开着等于「界面已是 B、面板还对 A 执行 revert/delete」——直接关闭。
985
+ useEffect(() => {
986
+ const onSession = e => {
987
+ const next = e && e.detail ? e.detail.sessionId : null
988
+ const cur = sessionRef.current
989
+ if (!next || !cur) return
990
+ if (bareSessionId(next) !== bareSessionId(cur)) {
991
+ setOpen(false)
992
+ setTarget(null)
993
+ }
994
+ }
995
+ window.addEventListener(SESSION_EVENT, onSession)
996
+ return () => window.removeEventListener(SESSION_EVENT, onSession)
997
+ }, [])
998
+
798
999
  const sid = target && target.sessionId
1000
+ // PA-1:409 会把 target.running 锁成 true;面板没有轮询 → 用户停掉会话后按钮仍全灰。
1001
+ // overlay 槽不保证有 useSessions,故用有限次重查:1s/3s/8s 各拉一次 /messages,
1002
+ // loadMessages 会把 running 同步回权威值(停下来了就自动解锁)。
1003
+ const runningRecheckRef = useRef([])
1004
+ useEffect(
1005
+ () => () => {
1006
+ for (const timer of runningRecheckRef.current) clearTimeout(timer)
1007
+ },
1008
+ [],
1009
+ )
799
1010
 
800
1011
  const loadMessages = useCallback(
801
1012
  async quiet => {
@@ -825,7 +1036,7 @@ window.__ModuleLoader__.load({
825
1036
  setState('ready')
826
1037
  } catch (reason) {
827
1038
  if (requestId !== loadSeqRef.current) return
828
- const message = t('panel.loadFail') + (reason && reason.message ? reason.message : String(reason))
1039
+ const message = timeoutText(reason, t('panel.loadFail'))
829
1040
  if (quiet) setError(message)
830
1041
  else {
831
1042
  setLoadError(message)
@@ -841,6 +1052,16 @@ window.__ModuleLoader__.load({
841
1052
  loadMessages(false)
842
1053
  }, [open, sid, loadMessages])
843
1054
 
1055
+ // 409 之后的有限重查(1s/3s/8s):loadMessages 会把 running 同步回权威值
1056
+ const scheduleRunningRecheck = useCallback(() => {
1057
+ for (const ms of [1000, 3000, 8000]) {
1058
+ const timer = setTimeout(() => {
1059
+ loadMessages(true).catch(() => {})
1060
+ }, ms)
1061
+ runningRecheckRef.current.push(timer)
1062
+ }
1063
+ }, [loadMessages])
1064
+
844
1065
  useEffect(() => {
845
1066
  if (!open || tab !== 'messages') return
846
1067
  const q = query.trim()
@@ -861,21 +1082,16 @@ window.__ModuleLoader__.load({
861
1082
  (role !== 'all' ? '&role=' + encodeURIComponent(role) : '') +
862
1083
  '&limit=' +
863
1084
  PANEL_SEARCH_LIMIT
864
- fetch(url)
865
- .then(res =>
866
- res
867
- .json()
868
- .catch(() => null)
869
- .then(data => ({ res, data })),
870
- )
871
- .then(({ res, data }) => {
1085
+ fetchWithTimeout(url, undefined, __readTimeoutMs)
1086
+ .then(readOpsJson)
1087
+ .then(r => {
872
1088
  if (cancelled) return
873
- if (!res.ok || !data || data.ok !== true) throw new Error((data && data.error) || 'HTTP ' + res.status)
874
- setHits(Array.isArray(data.results) ? data.results : [])
1089
+ if (!r.ok) throw opsError(r.status, r.data)
1090
+ setHits(Array.isArray(r.data.results) ? r.data.results : [])
875
1091
  setError(null)
876
1092
  })
877
1093
  .catch(reason => {
878
- if (!cancelled) setError(t('panel.searchFail') + (reason && reason.message ? reason.message : String(reason)))
1094
+ if (!cancelled) setError(errText(reason, t('panel.searchFail')))
879
1095
  })
880
1096
  .finally(() => {
881
1097
  if (!cancelled) setSearching(false)
@@ -892,22 +1108,26 @@ window.__ModuleLoader__.load({
892
1108
  setTrashState('loading')
893
1109
  setTrashError(null)
894
1110
  try {
895
- const res = await fetch('/api/message-ops/session/trash')
896
- const data = await res.json().catch(() => null)
1111
+ // 竞态门是组件语义(requestId 是 hook state),保留在调用点;
1112
+ // 只把「读响应体 + 校验 + 转文案」换成单点(审计 §2.4)。
1113
+ const r = await readOpsJson(await fetchWithTimeout('/api/message-ops/session/trash', undefined, __readTimeoutMs))
897
1114
  if (requestId !== trashSeqRef.current) return
898
- if (!res.ok || !data || data.ok !== true) throw new Error((data && data.error) || 'HTTP ' + res.status)
899
- setTrash(Array.isArray(data.entries) ? data.entries : [])
1115
+ if (!r.ok) throw opsError(r.status, r.data)
1116
+ setTrash(Array.isArray(r.data.entries) ? r.data.entries : [])
900
1117
  setTrashError(null)
901
1118
  setTrashState('ready')
902
1119
  } catch (reason) {
903
1120
  if (requestId !== trashSeqRef.current) return
904
- setTrashError(t('panel.loadFail') + (reason && reason.message ? reason.message : String(reason)))
1121
+ setTrashError(errText(reason, t('panel.loadFail')))
905
1122
  setTrashState('error')
906
1123
  }
907
1124
  }, [t])
908
1125
 
909
1126
  useEffect(() => {
910
- if (open && tab === 'trash') loadTrash()
1127
+ if (open && tab === 'trash') {
1128
+ setPurgeId(null) // 重新进入回收站 → 撤防(避免跨操作残留的二次确认态)
1129
+ loadTrash()
1130
+ }
911
1131
  }, [open, tab, loadTrash])
912
1132
 
913
1133
  const close = useCallback(() => {
@@ -952,10 +1172,16 @@ window.__ModuleLoader__.load({
952
1172
  if (!open) return undefined
953
1173
  const onKey = e => {
954
1174
  if (e.key === 'Escape') {
955
- if (busy) return
956
- if (confirmDelete) closeConfirm()
957
- else if (confirmAction) cancelAction()
958
- else close()
1175
+ const action = panelEscapeAction({ busy, confirmDelete, confirmAction, query })
1176
+ if (action === 'ignore') return
1177
+ if (action === 'closeConfirm') return closeConfirm()
1178
+ if (action === 'cancelAction') return cancelAction()
1179
+ if (action === 'clearQuery') {
1180
+ setQuery('')
1181
+ clearPick()
1182
+ return
1183
+ }
1184
+ close()
959
1185
  } else if (e.key === '/') {
960
1186
  if (confirmDelete || confirmAction) return
961
1187
  const el = e.target
@@ -967,7 +1193,7 @@ window.__ModuleLoader__.load({
967
1193
  }
968
1194
  window.addEventListener('keydown', onKey)
969
1195
  return () => window.removeEventListener('keydown', onKey)
970
- }, [open, busy, confirmDelete, confirmAction, close, closeConfirm, cancelAction])
1196
+ }, [open, busy, confirmDelete, confirmAction, query, close, closeConfirm, cancelAction])
971
1197
 
972
1198
  useEffect(() => {
973
1199
  if (!open) return undefined
@@ -1096,9 +1322,15 @@ window.__ModuleLoader__.load({
1096
1322
  }, [open, confirmDelete, confirmAction])
1097
1323
 
1098
1324
  const baseRows = query.trim() ? hits || [] : messages
1099
- const rows = baseRows
1100
- .filter(m => m && m.role !== 'system' && (role === 'all' || m.role === role) && (includeShadowed || !m.shadowed))
1101
- .sort((a, b) => b.seq - a.seq)
1325
+ // 0.33.4(perf-audit #2):派生值进 useMemo。旧实现每次滚动 setScrollTop
1326
+ // 都触发一次渲染 → 全量 filter+sort(实测 50k 行 10–19ms/帧,超 16.7ms 预算)。
1327
+ const rows = useMemo(
1328
+ () =>
1329
+ baseRows
1330
+ .filter(m => m && m.role !== 'system' && (role === 'all' || m.role === role) && (includeShadowed || !m.shadowed))
1331
+ .sort((a, b) => b.seq - a.seq),
1332
+ [baseRows, role, includeShadowed],
1333
+ )
1102
1334
  const activeIndex = picked ? rows.findIndex(m => m.seq === picked.seq) : -1
1103
1335
 
1104
1336
  const clearPick = () => {
@@ -1109,16 +1341,6 @@ window.__ModuleLoader__.load({
1109
1341
  setConfirmAction(null)
1110
1342
  }
1111
1343
 
1112
- const previewRow = m => {
1113
- if (!m) return
1114
- detailReq.current += 1
1115
- setPicked(m)
1116
- setDetail(m.snippet || '')
1117
- setDetailState('ready')
1118
- setConfirmAction(null)
1119
- setDone('')
1120
- }
1121
-
1122
1344
  const scrollRowIntoView = index => {
1123
1345
  const el = listRef.current
1124
1346
  if (!el) return
@@ -1157,7 +1379,9 @@ window.__ModuleLoader__.load({
1157
1379
  e.preventDefault()
1158
1380
  const row = rows[next]
1159
1381
  if (!row) return
1160
- previewRow(row)
1382
+ // 0.30.0 P0:键盘与鼠标必须走同一条取全文路径。旧实现只把 detail 塞成
1383
+ // 160 字摘要,接着点「从此条分叉」会把截断文本写进新会话输入框。
1384
+ pick(row)
1161
1385
  scrollRowIntoView(next)
1162
1386
  }
1163
1387
 
@@ -1189,29 +1413,41 @@ window.__ModuleLoader__.load({
1189
1413
  if (!m || busy) return
1190
1414
  setConfirmAction(null)
1191
1415
  setPicked(m)
1416
+ // 0.32.2:换选一条消息即作废上一次分叉的「打开新会话」入口,
1417
+ // 否则回撤/删除成功的横幅里会挂着上一轮 branch 的 childId。
1418
+ setChildId(null)
1419
+ setActionError(null)
1192
1420
  setDetail(m.snippet || '')
1193
1421
  setDetailState('loading')
1194
1422
  setDone('')
1195
1423
  const req = ++detailReq.current
1196
- fetch('/api/message-ops/text?sessionId=' + encodeURIComponent(sid) + '&seq=' + encodeURIComponent(m.seq))
1197
- .then(res =>
1198
- res
1199
- .json()
1200
- .catch(() => null)
1201
- .then(data => ({ res, data })),
1202
- )
1203
- .then(({ res, data }) => {
1424
+ // 0.25.0(手感):全文取数交给 loadPanelText —— 命中缓存零请求、
1425
+ // 快速划过列表只发停下来的那一条、同 seq 在途共享。竞态仍由
1426
+ // detailReq 把关(过期结果一律丢弃)。
1427
+ // 0.46.0(P3-1):结果有四态 —— 全文 / null(真失败)/ 已取消 / 超时。
1428
+ // 取消是写操作作废了缓存(不是网络失败):保持「正在读取」并重取一次
1429
+ //(缓存已清,重取拿到的就是写后原文);只有真失败才回退 snippet 并注明。
1430
+ const showDetail = attempt => {
1431
+ loadPanelText(sid, m.seq).then(full => {
1204
1432
  if (req !== detailReq.current) return
1205
- if (!res.ok || !data || data.ok !== true) throw new Error((data && data.error) || 'HTTP ' + res.status)
1206
- const full = typeof data.text === 'string' && data.text !== '' ? data.text : null
1433
+ if (full === PANEL_TEXT_CANCELLED) {
1434
+ // 再被作废也不报「读取失败」:宁可等下一次选中,也不拿摘要冒充原文。
1435
+ setDetailState('loading')
1436
+ if (attempt === 0) showDetail(1)
1437
+ return
1438
+ }
1439
+ if (full === PANEL_TEXT_TIMEOUT) {
1440
+ setDetail(m.snippet || '')
1441
+ setDetailState('timeout')
1442
+ return
1443
+ }
1444
+ // 失败(null)→ 只有截断的 snippet,不许冒充原文(MED-5)。
1445
+ // 0.32.2:失败必须显式标注,否则用户以为这 160 字就是全部。
1207
1446
  setDetail(full ?? (m.snippet || ''))
1208
- setDetailState('ready')
1209
- })
1210
- .catch(() => {
1211
- if (req !== detailReq.current) return
1212
- setDetail(m.snippet || '') // 拉全文失败 → 只有截断的 snippet,不许冒充原文
1213
- setDetailState('ready')
1447
+ setDetailState(full == null ? 'snippet' : 'ready')
1214
1448
  })
1449
+ }
1450
+ showDetail(0)
1215
1451
  },
1216
1452
  [busy, sid],
1217
1453
  )
@@ -1226,28 +1462,47 @@ window.__ModuleLoader__.load({
1226
1462
  setError(null)
1227
1463
  setDone('')
1228
1464
  try {
1465
+ setActionError(null)
1229
1466
  if (mode === 'branch') {
1230
1467
  // 0.12.0:分叉 = opencode 的 before 语义(新会话不含此条,原文回输入框)。
1231
1468
  // 非破坏操作,故不受 running 限制(官方 fork 会自己拒绝运行中源会话)。
1232
1469
  // 取文本用 `detail`(该条全文,pick 时已按 seq 拉好);非用户消息不带文本。
1233
1470
  const pickedRole = picked && picked.role
1234
- const created = await forkFromUserMessage(actionSid, picked.seq, pickedRole === 'user' ? detail : '', picked.turnStartSeq)
1471
+ // 0.30.0 P0:分叉写入新会话输入框的必须是**全文**。detail 可能是列表/键盘
1472
+ // 路径留下的 snippet(160 字),直接写进去会静默截断用户原文。
1473
+ let text = ''
1474
+ if (pickedRole === 'user') {
1475
+ let full = await loadPanelText(actionSid, picked.seq)
1476
+ // 0.46.0(P3-1):取消说明缓存刚被写操作清空,重取一次拿写后原文;
1477
+ // 仍取不到就明确失败 —— 宁可取消分叉,也绝不拿摘要当原文。
1478
+ if (full === PANEL_TEXT_CANCELLED) full = await loadPanelText(actionSid, picked.seq)
1479
+ if (full === PANEL_TEXT_TIMEOUT) throw new Error(t('panel.textFail') + t('panel.timeout'))
1480
+ if (full === PANEL_TEXT_CANCELLED || full == null || String(full).trim() === '') throw new Error(t('panel.textFail'))
1481
+ text = full
1482
+ }
1483
+ const created = await forkFromUserMessage(actionSid, picked.seq, text, picked.turnStartSeq)
1235
1484
  if (sessionRef.current !== actionSid) return
1236
1485
  setChildId(created || null)
1237
1486
  setDone(t('panel.branchDone', { id: String(created || '') }))
1238
1487
  notifyDone(t('panel.branchDone', { id: String(created || '') }))
1239
1488
  return
1240
1489
  }
1241
- const res = await fetch('/api/message-ops/' + mode, {
1490
+ const res = await fetchWithTimeout('/api/message-ops/' + mode, {
1242
1491
  method: 'POST',
1243
1492
  headers: { 'content-type': 'application/json' },
1244
1493
  body: JSON.stringify({ sessionId: target.sessionId, seq: picked.seq }),
1245
1494
  })
1246
- const data = await res.json().catch(() => null)
1495
+ const r = await readOpsJson(res)
1247
1496
  if (sessionRef.current !== actionSid) return
1248
- if (!res.ok || !data || data.ok !== true) {
1249
- if (res.status === 409) setTarget(prev => (prev ? { ...prev, running: true } : prev))
1250
- throw new Error((data && data.error) || 'HTTP ' + res.status)
1497
+ // 非 branch 动作不得复用上一轮 branch 留下的「打开新会话」按钮。
1498
+ setChildId(null)
1499
+ if (!r.ok) {
1500
+ // 409 → 面板立刻切「运行中」(组件语义,留在调用点)
1501
+ if (r.status === 409) {
1502
+ setTarget(prev => (prev ? { ...prev, running: true } : prev))
1503
+ scheduleRunningRecheck()
1504
+ }
1505
+ throw opsError(r.status, r.data)
1251
1506
  }
1252
1507
  if (mode === 'revert') {
1253
1508
  setMessages(prev => prev.map(m => (m.seq >= picked.seq ? { ...m, shadowed: true, visible: false } : m)))
@@ -1269,17 +1524,15 @@ window.__ModuleLoader__.load({
1269
1524
  }, 0)
1270
1525
  notifyDone(msg)
1271
1526
  emitChanged()
1272
- try {
1273
- if (__uiWorkspace && typeof __uiWorkspace.openSession === 'function') __uiWorkspace.openSession(target.sessionId)
1274
- } catch {
1275
- /* view rebuild is best effort */
1276
- }
1527
+ // 0.26.0:统一走 safeOpenSession(失败 warn,不静默吞 —— 审计 §2.3)
1528
+ safeOpenSession(target.sessionId, 'panel-action')
1277
1529
  setTimeout(() => {
1278
1530
  loadMessages(true).catch(() => {})
1279
1531
  }, 650)
1280
1532
  } catch (reason) {
1281
1533
  if (sessionRef.current !== actionSid) return
1282
- setError(t('errorPrefix') + (reason && reason.message ? reason.message : String(reason)))
1534
+ // 动作错误独立存放:后台 quiet 重查成功不得把它清掉。
1535
+ setActionError(timeoutText(reason, t('errorPrefix')))
1283
1536
  } finally {
1284
1537
  setBusy('')
1285
1538
  }
@@ -1296,63 +1549,60 @@ window.__ModuleLoader__.load({
1296
1549
  setDeleteError(null)
1297
1550
  setDone('')
1298
1551
  try {
1299
- const res = await fetch('/api/message-ops/session/delete', {
1552
+ const res = await fetchWithTimeout('/api/message-ops/session/delete', {
1300
1553
  method: 'POST',
1301
1554
  headers: { 'content-type': 'application/json' },
1302
1555
  body: JSON.stringify({ sessionId: target.sessionId, confirmTitle: confirmTitle }),
1303
1556
  })
1304
- const data = await res.json().catch(() => null)
1557
+ const r = await readOpsJson(res)
1305
1558
  if (sessionRef.current !== actionSid) return
1306
- if (!res.ok || !data || data.ok !== true) {
1307
- if (res.status === 409) setTarget(prev => (prev ? { ...prev, running: true } : prev))
1308
- throw new Error((data && data.error) || 'HTTP ' + res.status)
1559
+ if (!r.ok) {
1560
+ if (r.status === 409) {
1561
+ setTarget(prev => (prev ? { ...prev, running: true } : prev))
1562
+ scheduleRunningRecheck()
1563
+ }
1564
+ throw opsError(r.status, r.data)
1309
1565
  }
1310
1566
  setConfirmDelete(false)
1311
1567
  setDone(t('panel.deleted'))
1312
1568
  notifyDone(t('panel.deleted'))
1313
1569
  emitChanged()
1314
- setTimeout(() => {
1315
- try {
1316
- window.location.reload()
1317
- } catch {
1318
- /* non-browser guard */
1319
- }
1320
- }, 700)
1570
+ // 0.33.13:archive 会经 workspace feed 让侧栏隐藏并关闭当前视图,
1571
+ // 不再需要整页 reload(用户会看到「Loading plugins…」且丢掉 SPA 状态)。
1572
+ setOpen(false)
1573
+ setTarget(null)
1321
1574
  } catch (reason) {
1322
1575
  if (sessionRef.current !== actionSid) return
1323
- setDeleteError(t('errorPrefix') + (reason && reason.message ? reason.message : String(reason)))
1576
+ setDeleteError(timeoutText(reason, t('errorPrefix')))
1324
1577
  } finally {
1325
1578
  setBusy('')
1326
1579
  }
1327
1580
  }, [target, busy, confirmTitle, t])
1328
1581
 
1329
1582
  const restoreEntry = useCallback(
1583
+ // 任何一次恢复都先撤防永久删除:否则「删→恢复→再删」会一次点击就真删。
1584
+
1330
1585
  async trashId => {
1331
1586
  if (busy) return
1587
+ setPurgeId(null) // 撤防永久删除(见上)
1332
1588
  setBusy('restore:' + trashId)
1333
1589
  setError(null)
1334
1590
  setDone('')
1335
1591
  try {
1336
- const res = await fetch('/api/message-ops/session/restore', {
1592
+ const res = await fetchWithTimeout('/api/message-ops/session/restore', {
1337
1593
  method: 'POST',
1338
1594
  headers: { 'content-type': 'application/json' },
1339
1595
  body: JSON.stringify({ trashId }),
1340
1596
  })
1341
- const data = await res.json().catch(() => null)
1342
- if (!res.ok || !data || data.ok !== true) throw new Error((data && data.error) || 'HTTP ' + res.status)
1597
+ const r = await readOpsJson(res)
1598
+ if (!r.ok) throw opsError(r.status, r.data)
1343
1599
  setTrash(prev => prev.filter(x => x.trashId !== trashId))
1344
1600
  setDone(t('panel.restored'))
1345
1601
  notifyDone(t('panel.restored'))
1346
1602
  emitChanged()
1347
- setTimeout(() => {
1348
- try {
1349
- window.location.reload()
1350
- } catch {
1351
- /* non-browser guard */
1352
- }
1353
- }, 700)
1603
+ // 0.33.13:unarchive 后宿主 feed 会把行放回侧栏,无需整页 reload。
1354
1604
  } catch (reason) {
1355
- setError(t('errorPrefix') + (reason && reason.message ? reason.message : String(reason)))
1605
+ setError(timeoutText(reason, t('errorPrefix')))
1356
1606
  } finally {
1357
1607
  setBusy('')
1358
1608
  }
@@ -1371,19 +1621,19 @@ window.__ModuleLoader__.load({
1371
1621
  setError(null)
1372
1622
  setDone('')
1373
1623
  try {
1374
- const res = await fetch('/api/message-ops/session/purge', {
1624
+ const res = await fetchWithTimeout('/api/message-ops/session/purge', {
1375
1625
  method: 'POST',
1376
1626
  headers: { 'content-type': 'application/json' },
1377
1627
  body: JSON.stringify({ trashId }),
1378
1628
  })
1379
- const data = await res.json().catch(() => null)
1380
- if (!res.ok || !data || data.ok !== true) throw new Error((data && data.error) || 'HTTP ' + res.status)
1629
+ const r = await readOpsJson(res)
1630
+ if (!r.ok) throw opsError(r.status, r.data)
1381
1631
  setTrash(prev => prev.filter(x => x.trashId !== trashId))
1382
1632
  setPurgeId(null)
1383
1633
  setDone(t('panel.purged'))
1384
1634
  notifyDone(t('panel.purged'))
1385
1635
  } catch (reason) {
1386
- setError(t('errorPrefix') + (reason && reason.message ? reason.message : String(reason)))
1636
+ setError(timeoutText(reason, t('errorPrefix')))
1387
1637
  } finally {
1388
1638
  setBusy('')
1389
1639
  }
@@ -1391,6 +1641,21 @@ window.__ModuleLoader__.load({
1391
1641
  [busy, purgeId, t],
1392
1642
  )
1393
1643
 
1644
+ // 0.33.9(React #310):hook 必须在**任何条件 return 之前**。
1645
+ // 单趟计数(原先 3 次 filter + 每帧重算)。
1646
+ const [visibleCount, shadowedCount, totalCount] = useMemo(() => {
1647
+ let visible = 0
1648
+ let shadowed = 0
1649
+ let total = 0
1650
+ for (const m of messages) {
1651
+ if (!m || m.role === 'system') continue
1652
+ total += 1
1653
+ if (m.shadowed) shadowed += 1
1654
+ else if (m.visible) visible += 1
1655
+ }
1656
+ return [visible, shadowed, total]
1657
+ }, [messages])
1658
+
1394
1659
  if (!open) return null
1395
1660
 
1396
1661
  const pickedLive = picked ? messages.find(m => m.seq === picked.seq) || picked : null
@@ -1400,9 +1665,6 @@ window.__ModuleLoader__.load({
1400
1665
  // 「能回滚 AI 消息却静默不回填」的旁路,故回滚按钮同样限定为用户消息。
1401
1666
  // 删除按钮仍用 canAct —— 删单条 AI 消息是合理能力,不受此限。
1402
1667
  const canRevert = canAct && pickedLive && pickedLive.role === 'user'
1403
- const visibleCount = messages.filter(m => m.role !== 'system' && m.visible && !m.shadowed).length
1404
- const shadowedCount = messages.filter(m => m.role !== 'system' && m.shadowed).length
1405
- const totalCount = messages.filter(m => m.role !== 'system').length
1406
1668
  const revertImpact = pickedLive ? messages.filter(m => m.role !== 'system' && !m.shadowed && m.seq >= pickedLive.seq) : []
1407
1669
  const revertCount = revertImpact.length
1408
1670
  const revertVisibleCount = revertImpact.filter(m => m.visible).length
@@ -1439,7 +1701,9 @@ window.__ModuleLoader__.load({
1439
1701
  role: 'presentation',
1440
1702
  ref: scrimRef,
1441
1703
  onMouseDown: e => {
1442
- if (e.target === e.currentTarget) close()
1704
+ // 确认层开着时点遮罩不关整个面板(与 Esc 一致:先退一层)
1705
+ if (e.target !== e.currentTarget || confirmDelete || confirmAction) return
1706
+ close()
1443
1707
  },
1444
1708
  },
1445
1709
  React.createElement(
@@ -1484,38 +1748,69 @@ window.__ModuleLoader__.load({
1484
1748
  ),
1485
1749
  React.createElement(
1486
1750
  'div',
1487
- { className: 'mopsTabs' },
1488
- React.createElement(
1489
- 'button',
1490
- {
1491
- type: 'button',
1492
- className: 'mopsTab' + (tab === 'messages' ? ' on' : ''),
1493
- onClick: () => {
1494
- setTab('messages')
1495
- setConfirmDelete(false)
1496
- setConfirmAction(null)
1497
- setDeleteError(null)
1498
- },
1499
- },
1500
- t('panel.messages') + ' ' + totalCount,
1501
- ),
1502
- React.createElement(
1503
- 'button',
1504
- {
1505
- type: 'button',
1506
- className: 'mopsTab' + (tab === 'trash' ? ' on' : ''),
1507
- onClick: () => {
1508
- setTab('trash')
1509
- setConfirmDelete(false)
1510
- setConfirmAction(null)
1511
- setDeleteError(null)
1512
- },
1513
- },
1514
- t('panel.trash') + (trash.length ? ' ' + trash.length : ''),
1515
- ),
1751
+ { className: 'mopsTabs', role: 'tablist', 'aria-label': t('dialog.title') },
1752
+ (() => {
1753
+ // 0.33.3(ui-live P2-4):APG tabs 模式 —— id/aria-controls/tabpanel/
1754
+ // roving tabindex/方向键。旧实现只有 aria-selected。
1755
+ const switchTab = (key, focus) => {
1756
+ setTab(key)
1757
+ setConfirmDelete(false)
1758
+ setConfirmAction(null)
1759
+ setDeleteError(null)
1760
+ if (focus && typeof document !== 'undefined') {
1761
+ const el = document.getElementById('mops-tab-' + key)
1762
+ if (el && typeof el.focus === 'function') el.focus()
1763
+ }
1764
+ }
1765
+ const onTabKey = e => {
1766
+ if (e.key === 'ArrowRight' || e.key === 'ArrowLeft' || e.key === 'Home' || e.key === 'End') {
1767
+ e.preventDefault()
1768
+ const next = e.key === 'Home' ? 'messages' : e.key === 'End' ? 'trash' : tab === 'messages' ? 'trash' : 'messages'
1769
+ switchTab(next, true)
1770
+ }
1771
+ }
1772
+ return [
1773
+ React.createElement(
1774
+ 'button',
1775
+ {
1776
+ key: 'messages',
1777
+ type: 'button',
1778
+ id: 'mops-tab-messages',
1779
+ className: 'mopsTab' + (tab === 'messages' ? ' on' : ''),
1780
+ role: 'tab',
1781
+ 'aria-selected': tab === 'messages',
1782
+ 'aria-controls': 'mops-tabpanel-messages',
1783
+ tabIndex: tab === 'messages' ? 0 : -1,
1784
+ onKeyDown: onTabKey,
1785
+ onClick: () => switchTab('messages', false),
1786
+ },
1787
+ t('panel.messages') + ' ' + totalCount,
1788
+ ),
1789
+ React.createElement(
1790
+ 'button',
1791
+ {
1792
+ key: 'trash',
1793
+ type: 'button',
1794
+ id: 'mops-tab-trash',
1795
+ className: 'mopsTab' + (tab === 'trash' ? ' on' : ''),
1796
+ role: 'tab',
1797
+ 'aria-selected': tab === 'trash',
1798
+ 'aria-controls': 'mops-tabpanel-trash',
1799
+ tabIndex: tab === 'trash' ? 0 : -1,
1800
+ onKeyDown: onTabKey,
1801
+ onClick: () => switchTab('trash', false),
1802
+ },
1803
+ t('panel.trash') + (trash.length ? ' ' + trash.length : ''),
1804
+ ),
1805
+ ]
1806
+ })(),
1516
1807
  ),
1517
- target.running && tab === 'messages' ? React.createElement('div', { className: 'mopsBanner warn' }, t('panel.running')) : null,
1518
- error ? React.createElement('div', { className: 'mopsBanner err', role: 'alert' }, error) : null,
1808
+ target.running && tab === 'messages' && !confirmAction
1809
+ ? React.createElement('div', { className: 'mopsBanner warn' }, t('panel.running'))
1810
+ : null,
1811
+ (actionError || error) && !confirmAction
1812
+ ? React.createElement('div', { className: 'mopsBanner err', role: 'alert' }, actionError || error)
1813
+ : null,
1519
1814
  done
1520
1815
  ? React.createElement(
1521
1816
  'div',
@@ -1529,11 +1824,7 @@ window.__ModuleLoader__.load({
1529
1824
  className: 'mopsAction primary',
1530
1825
  style: { marginLeft: 10 },
1531
1826
  onClick: () => {
1532
- try {
1533
- if (__uiWorkspace && typeof __uiWorkspace.openSession === 'function') __uiWorkspace.openSession(childId)
1534
- } catch {
1535
- /* best effort */
1536
- }
1827
+ safeOpenSession(childId, 'panel-branch')
1537
1828
  },
1538
1829
  },
1539
1830
  t('panel.openNew'),
@@ -1543,8 +1834,13 @@ window.__ModuleLoader__.load({
1543
1834
  : null,
1544
1835
  tab === 'messages'
1545
1836
  ? React.createElement(
1546
- React.Fragment,
1547
- null,
1837
+ 'div',
1838
+ {
1839
+ className: 'mopsTabPanel',
1840
+ role: 'tabpanel',
1841
+ id: 'mops-tabpanel-messages',
1842
+ 'aria-labelledby': 'mops-tab-messages',
1843
+ },
1548
1844
  React.createElement(
1549
1845
  'div',
1550
1846
  { className: 'mopsSearchRow' },
@@ -1554,6 +1850,14 @@ window.__ModuleLoader__.load({
1554
1850
  value: query,
1555
1851
  placeholder: t('panel.searchHint'),
1556
1852
  'aria-label': t('panel.search'),
1853
+ // PA-3:Enter/↓ 直接进列表并选中第一条(不必 Tab 过全部 chips)
1854
+ onKeyDown: e => {
1855
+ if (e.key !== 'Enter' && e.key !== 'ArrowDown') return
1856
+ e.preventDefault()
1857
+ if (listRef.current) listRef.current.focus()
1858
+ const first = rows[0]
1859
+ if (first) pick(first)
1860
+ },
1557
1861
  onChange: e => {
1558
1862
  setQuery(e.target.value)
1559
1863
  clearPick()
@@ -1609,7 +1913,17 @@ window.__ModuleLoader__.load({
1609
1913
  'aria-busy': state === 'loading' || showSearchLoading ? 'true' : undefined,
1610
1914
  'aria-activedescendant': state === 'ready' && activeRendered ? 'mops-opt-' + picked.seq : undefined,
1611
1915
  onKeyDown: handleListKeyDown,
1612
- onScroll: e => setScrollTop(e.currentTarget.scrollTop),
1916
+ onScroll: e => {
1917
+ // 0.33.4:滚动按帧合批,避免每个 scroll 事件都重渲染。
1918
+ const top = e.currentTarget.scrollTop
1919
+ if (scrollRaf.current != null) return
1920
+ const raf =
1921
+ typeof requestAnimationFrame === 'function' ? requestAnimationFrame : cb => setTimeout(cb, 16)
1922
+ scrollRaf.current = raf(() => {
1923
+ scrollRaf.current = null
1924
+ setScrollTop(top)
1925
+ })
1926
+ },
1613
1927
  },
1614
1928
  state === 'loading' || state === 'idle'
1615
1929
  ? React.createElement('div', { className: 'mopsEmpty', role: 'status', 'aria-live': 'polite' }, t('panel.loading'))
@@ -1699,6 +2013,11 @@ window.__ModuleLoader__.load({
1699
2013
  { className: 'mopsDetailText' },
1700
2014
  detailState === 'loading' ? t('panel.detailLoading') : detail || pickedLive.snippet || '—',
1701
2015
  ),
2016
+ detailState === 'snippet'
2017
+ ? React.createElement('div', { className: 'mopsDetailNote' }, t('panel.snippetOnly'))
2018
+ : detailState === 'timeout'
2019
+ ? React.createElement('div', { className: 'mopsDetailNote' }, t('panel.detailTimeout'))
2020
+ : null,
1702
2021
  React.createElement(
1703
2022
  'div',
1704
2023
  { className: 'mopsActions' },
@@ -1757,6 +2076,9 @@ window.__ModuleLoader__.load({
1757
2076
  seq: String(pickedLive.seq),
1758
2077
  }),
1759
2078
  ),
2079
+ (actionError || error)
2080
+ ? React.createElement('div', { className: 'mopsBanner err', role: 'alert' }, actionError || error)
2081
+ : null,
1760
2082
  React.createElement(
1761
2083
  'div',
1762
2084
  { className: 'mopsImpact' },
@@ -1845,6 +2167,9 @@ window.__ModuleLoader__.load({
1845
2167
  { className: 'mopsImpact', id: 'mops-delete-impact' },
1846
2168
  t('panel.deleteSessionImpact', { n: String(totalCount) }),
1847
2169
  ),
2170
+ deleteBlockedReason
2171
+ ? React.createElement('div', { className: 'mopsBanner warn', role: 'status' }, deleteBlockedReason)
2172
+ : null,
1848
2173
  target.running
1849
2174
  ? React.createElement('div', { className: 'mopsBanner warn', role: 'status' }, t('panel.running'))
1850
2175
  : null,
@@ -1898,7 +2223,14 @@ window.__ModuleLoader__.load({
1898
2223
  )
1899
2224
  : React.createElement(
1900
2225
  'div',
1901
- { className: 'mopsList', style: { borderTop: 0 }, 'aria-busy': trashState === 'loading' ? 'true' : undefined },
2226
+ {
2227
+ className: 'mopsList',
2228
+ style: { borderTop: 0 },
2229
+ role: 'tabpanel',
2230
+ id: 'mops-tabpanel-trash',
2231
+ 'aria-labelledby': 'mops-tab-trash',
2232
+ 'aria-busy': trashState === 'loading' ? 'true' : undefined,
2233
+ },
1902
2234
  trashState === 'loading' || trashState === 'idle'
1903
2235
  ? React.createElement('div', { className: 'mopsEmpty', role: 'status', 'aria-live': 'polite' }, t('panel.loading'))
1904
2236
  : trashState === 'error'
@@ -1934,20 +2266,29 @@ window.__ModuleLoader__.load({
1934
2266
  React.createElement(
1935
2267
  'div',
1936
2268
  { className: 'mopsTrashMeta' },
1937
- item.sessionId +
2269
+ (item.sessionId || t('panel.trashManual')) +
1938
2270
  (item.expiresAt ? ' · ' + t('panel.expires') + ' ' + new Date(item.expiresAt).toLocaleDateString() : ''),
1939
2271
  ),
1940
2272
  ),
1941
- React.createElement(
1942
- 'button',
1943
- {
1944
- type: 'button',
1945
- className: 'mopsAction',
1946
- disabled: !!busy,
1947
- onClick: () => restoreEntry(item.trashId),
1948
- },
1949
- busy === 'restore:' + item.trashId ? t('panel.busy') : t('panel.restore'),
1950
- ),
2273
+ // 0.42.0(srv-audit D9/D10):异常态条目不提供 Restore ——
2274
+ // moving(删除中断、仅存副本留作人工恢复)与 corrupt(清单损坏)
2275
+ // 调用恢复只会拿到 409,摆一个必错按钮是坏交互。
2276
+ item.state === 'moving' || item.state === 'corrupt' || item.corrupt === true
2277
+ ? React.createElement(
2278
+ 'span',
2279
+ { className: 'mopsTrashNote' },
2280
+ item.state === 'corrupt' || item.corrupt === true ? t('panel.trashCorrupt') : t('panel.trashMoving'),
2281
+ )
2282
+ : React.createElement(
2283
+ 'button',
2284
+ {
2285
+ type: 'button',
2286
+ className: 'mopsAction',
2287
+ disabled: !!busy,
2288
+ onClick: () => restoreEntry(item.trashId),
2289
+ },
2290
+ busy === 'restore:' + item.trashId ? t('panel.busy') : t('panel.restore'),
2291
+ ),
1951
2292
  React.createElement(
1952
2293
  'button',
1953
2294
  {
@@ -1969,521 +2310,584 @@ window.__ModuleLoader__.load({
1969
2310
  )
1970
2311
  }
1971
2312
 
1972
- // --- 0.20.0 · 「编辑并重发」的编排层 ----------------------------------------
2313
+ // --- 0.26.0 / 0.28.0 · 「编辑并回撤重发」的编排层 -----------------------------
1973
2314
  //
1974
- // 语义(用户明确要求 + lead 决断;**不是** opencode 的立即回填,也**不是** fork):
2315
+ // 语义(用户原话:干净的定制编辑框,就在那条消息旁边展开,然后发送):
1975
2316
  //
1976
- // 点铅笔 → 只读:GET /text 取全文,在编辑框里改文字。零写操作。
1977
- // 点「取消」/ Esc / 点遮罩 → 只清本地 state。零 fetch、零写盘、零 openSession。
1978
- // 点「发送并回撤」这一刻才写,顺序严格如下:
2317
+ // 点铅笔 → 纯读:预填 `/messages` 的 row.fullText,在**这条消息自己的行内**
2318
+ // (气泡下、动作行上)展开编辑区。零写操作。
2319
+ // 取消 / Esc → 关闭编辑区并把焦点还给铅笔。零 fetch、零写盘、零 openSession。
2320
+ // (0.28.0 起没有贴边浮层、也没有 click-outside:编辑区是行内元素。)
2321
+ // 点「撤销并发送」这一刻才写,顺序严格如下:
1979
2322
  // ① POST /api/message-ops/revert { sessionId, seq }
1980
- // 失败(含 409 运行中)→ 保留编辑框与用户已输入的文本,报错,不再往下走
1981
- // ② markRowsShadowedFrom(seq) —— 与其它回滚入口共用同一个防 409 护栏
1982
- // ③ writeSessionDraft(rawSessionId) —— 合并写入,保住 view 偏好;这是权威值
1983
- // ④ setDraft + persistDraft —— 尽力同步「活着的」编辑器
1984
- // ⑤ emitChanged + openSessionById —— 视图重建;remount 时从 localStorage 读回同一份草稿
1985
- // ⑥ 有界等待重挂后 submit() 一次 —— 不可用则明确提示「请按回车发送」,绝不静默
2323
+ // 失败(含 409 运行中)→ 保留浮层与用户已改的文本,报错,**零副作用**
2324
+ // ② markRowsShadowedFrom(seq) —— 与其它回滚入口共用同一个防 409 护栏
2325
+ // ③ emitChanged + openSession —— 视图重建(遮蔽才立即可见)
2326
+ // ④ sessions.using(...).prompt([{ type: 'text', text }], 'queue')
2327
+ // —— 官方发送面。失败按 error.code/message 上抛,**不再**假成功
1986
2328
  //
1987
- // 为什么 ③ 必须在 ⑤ 之前:openSession 会卸载并重挂编辑器,新挂载走
1988
- // `readConversationDraft(sid)` 从 localStorage 初始化。先落盘才是无竞态路径
1989
- // (0.11.3 / 0.14.0 两次事故的同一个教训,见 refillComposer 注释)。
2329
+ // 为什么删掉 0.20~0.25 的「写草稿 + 轮询 inputActions.submit」:
2330
+ // 老路径要先写 localStorage 草稿 → 重建视图 → 等宿主重挂编辑器(8×120ms 有界
2331
+ // 轮询)→ 再 setDraft + submit()。它有两个副作用:①改后的文本**留在 composer**
2332
+ // (用户发完还看得见同一段字,正是「UI 上又复现一遍」);②轮询期间宿主任何重渲染
2333
+ // 都可能让 submit 打到已 dispose 的实例。官方 `sessions.using` + `session.prompt`
2334
+ // 是宿主自己的发送面:排队语义由宿主保证,失败有结构化 error code。
1990
2335
  //
1991
- // 为什么不用 fork:「分叉」按钮的语义是源会话一字不动。同一个「编辑」动作若在
1992
- // 铅笔里改写源会话、在分叉里保留源会话,就是两套相反语义 —— 用户无法预期。
1993
- const EDIT_EVENT = 'dsh-message-ops:edit'
1994
- const EDIT_ID = 'message-ops-edit-resend'
1995
- const EDIT_STYLE_ID = 'dsh-message-ops-edit-style'
1996
- /** 等待 composer 重挂的最大轮数 / 间隔:有界,不无限自旋。 */
1997
- const EDIT_SUBMIT_ATTEMPTS = 8
1998
- const EDIT_SUBMIT_INTERVAL_MS = 120
2336
+ // 老宿主降级(sessions 服务 / session.prompt 缺席):**唯一**兜底 = 把文本写进该
2337
+ // 会话草稿并回读校验,再提示按回车(edit.manual)。只有这一条,绝不复制第二套
2338
+ // composer 逻辑。降级路径返回 persisted,组件据此选择文案。
2339
+ //
2340
+ // 为什么不用 fork:「分叉」的语义是源会话一字不动;同一个「编辑」动作若在铅笔里
2341
+ // 改写源会话、在分叉里保留源会话,就是两套相反语义 —— 用户无法预期。
2342
+ /**
2343
+ * 官方 session 引用来源标签。
2344
+ *
2345
+ * `SessionReferenceSource` 是**声明合并可扩展**的开放表(宿主只内置
2346
+ * controllerOperation / gateway 两项),第三方插件自报一个标签是官方允许的用法
2347
+ * (第三方 message-edit 插件同样用 'messageEdit')。它只进 retainedBy 计数,
2348
+ * 运行时**不做白名单校验**(已读 dsh-api-session-controller 的 retainScope 源码)。
2349
+ */
2350
+
2351
+ // ══ 40-edit · 编辑并重发:官方发送面 + 唯一编排 ══
2352
+ const EDIT_SOURCE = 'messageEdit'
1999
2353
 
2000
2354
  /**
2001
- * 有界等待 composer 重挂后提交**一次**。
2355
+ * 官方发送面:`sessions.using(target, { source }, ref => ref.binding.session.prompt(...))`。
2356
+ *
2357
+ * 为什么手写 using 而不是 retain/release:官方 `using` 的实现就是
2358
+ * `retain()` → `await reference.ready` → `operation()` → **`finally release()`**
2359
+ * (已读 dsh-api-session-controller/lib/client.js)。自己 retain 就得多写一遍
2360
+ * release,失败路径更容易漏 —— 漏了就是 scope 永远不回收。
2002
2361
  *
2003
- * 判据:该会话的 InputActions 换成新对象 = 宿主重挂了编辑器(openSession 之后必然发生)。
2004
- * 到上限仍没换(例如视图没重建的内联路径)就用当前这个提交一次 —— 宁可多一条
2005
- * 兜底提示,也不要无限等。**只提交一次**:重复 submit 会发出两条消息,比失败更糟。
2362
+ * 为什么 `prompt(..., 'queue')`:queue = 追加一轮,steer = 打断当前轮。回撤之后
2363
+ * 会话本来就在等新输入,queue 是官方的「接着跑一轮」语义(与宿主 composer 回车
2364
+ * 同一条 API)。运行中会话的回撤会被服务端 409 拦住(见 ①),所以不需要 steer 抢跑。
2006
2365
  *
2007
- * @param text - 要提交的文本
2008
- * @param options - { attempts, intervalMs, sessionId },测试注入更小值
2009
- * @returns Promise<boolean> 是否成功调用了宿主 submit
2366
+ * @param text - 改后的文本
2367
+ * @param options - { rawSessionId, sessions }
2368
+ * @returns { ok, accepted?, unavailable?, reason? }
2010
2369
  */
2011
- function submitEditedText(text, options) {
2370
+ async function promptEditedText(text, options) {
2012
2371
  const opts = options || {}
2013
- const attempts = Number.isSafeInteger(opts.attempts) && opts.attempts > 0 ? opts.attempts : EDIT_SUBMIT_ATTEMPTS
2014
- const intervalMs = Number.isSafeInteger(opts.intervalMs) && opts.intervalMs >= 0 ? opts.intervalMs : EDIT_SUBMIT_INTERVAL_MS
2015
- // 0.24.0 P4:按会话读 InputActions。opts.getInputActions 保留给真执行测试注入。
2016
- //
2017
- // ⚠️ 判据语义变化:旧实现用「对象变了」= 宿主重挂编辑器。改成按会话隔离后,
2018
- // 对象变化只说明**这一会话**的 shell 换了实例(重挂),跨会话不会误触发,
2019
- // 比旧判据更准。读不到该会话的 InputActions 时**不提交** ——
2020
- // 宁可让调用方提示手动回车,也不能拿别的会话的 submit 发出去。
2021
- const targetSessionId = opts.sessionId
2022
- const readInputActions = typeof opts.getInputActions === 'function' ? opts.getInputActions : () => inputActionsFor(targetSessionId)
2023
- const before = readInputActions()
2024
- return new Promise(resolve => {
2025
- let n = 0
2026
- const tick = () => {
2027
- n += 1
2028
- const ia = readInputActions()
2029
- const usable = ia && typeof ia.submit === 'function' && typeof ia.setDraft === 'function'
2030
- const remounted = !!ia && ia !== before
2031
- if (usable && (remounted || n >= attempts)) {
2032
- try {
2033
- // 先确保编辑器里就是这段文字:重挂后 draft 已从 localStorage 读回,
2034
- // 但内联路径(视图没重建)里编辑器仍是旧内容,必须显式覆盖。
2035
- ia.setDraft(text)
2036
- if (typeof ia.persistDraft === 'function') ia.persistDraft()
2037
- ia.submit()
2038
- resolve(true)
2039
- } catch (e) {
2040
- console.warn('[message-ops] submit failed:', e)
2041
- resolve(false)
2042
- }
2043
- return
2372
+ const rawSessionId = String(opts.rawSessionId || '').trim()
2373
+ const sessions = opts.sessions || __sessionsSvc
2374
+ if (!sessions || typeof sessions.using !== 'function') {
2375
+ return { ok: false, unavailable: true, reason: 'sessions service unavailable' }
2376
+ }
2377
+ try {
2378
+ return await sessions.using(rawSessionId, { source: EDIT_SOURCE }, async reference => {
2379
+ if (reference && reference.ready) await reference.ready
2380
+ const face = reference && reference.binding ? reference.binding.session : null
2381
+ if (!face || typeof face.prompt !== 'function') {
2382
+ return { ok: false, unavailable: true, reason: 'session.prompt unavailable' }
2044
2383
  }
2045
- if (n >= attempts) {
2046
- resolve(false)
2047
- return
2384
+ let result = null
2385
+ try {
2386
+ result = await face.prompt([{ type: 'text', text: text }], 'queue')
2387
+ } catch (e) {
2388
+ return { ok: false, reason: e && e.message ? e.message : String(e) }
2048
2389
  }
2049
- setTimeout(tick, intervalMs)
2050
- }
2051
- setTimeout(tick, intervalMs)
2052
- })
2390
+ if (!result || result.ok !== true) {
2391
+ const err = result && result.error
2392
+ return { ok: false, reason: (err && (err.code || err.message)) || 'prompt rejected' }
2393
+ }
2394
+ return { ok: true, accepted: true }
2395
+ })
2396
+ } catch (e) {
2397
+ // `using` 的 acquisition 失败(未知会话 / generation 已 dispose)也走这里。
2398
+ return { ok: false, reason: e && e.message ? e.message : String(e) }
2399
+ }
2053
2400
  }
2054
2401
 
2055
2402
  /**
2056
- * 「发送并回撤」的唯一编排实现。
2403
+ * 「撤销并发送」的唯一编排实现。
2057
2404
  *
2058
2405
  * 抽成具名函数(而不是埋在组件里)有两个理由:
2059
2406
  * 1. 时序是本功能的核心契约,必须能被测试**真执行**断言
2060
- * (revert 失败 → 不写草稿、不 openSession、用户文本保留)。
2407
+ * (revert 失败 → 零 prompt、零草稿、零视图重建)。
2061
2408
  * 2. 组件只负责 UI 状态;失败时「保留文本」由调用方按返回值决定。
2062
2409
  *
2063
- * @param options - { sessionId, rawSessionId, seq, text, deps }
2410
+ * @param options - { sessionId, rawSessionId, seq, text, deps, reverted }
2064
2411
  * sessionId 裸 uuid(给 HTTP)
2065
- * rawSessionId `session-` 前缀(给 openSession 与草稿键);缺省从 sessionId 补
2412
+ * rawSessionId `session-` 前缀(给 sessions.using 与草稿键);缺省从 sessionId 补
2413
+ * reverted 已经成功回撤过一次(「重新发送」):跳过 ①~③,直接走 ④。
2414
+ * 同一个 seq 再回撤必然 409,所以重试只能重发。
2066
2415
  * deps 可注入的副作用集合(测试用);缺省取真实实现
2067
- * @returns Promise<{ok, stage, submitted?, persisted?, reason?, status?}>
2068
- * stage: 'validate' | 'revert' | 'done'
2416
+ * @returns Promise<{ok, stage, submitted?, mode?, manual?, persisted?, reason?, status?}>
2417
+ * stage: 'validate' | 'revert' | 'send' | 'done'
2069
2418
  */
2070
2419
  async function sendEditAndRevert(options) {
2071
2420
  const opts = options || {}
2072
2421
  const sessionId = String(opts.sessionId || '').trim()
2073
- // 草稿键与 openSession 都必须用带 `session-` 前缀的写法:
2074
- // 裸 uuid 会让宿主 `sessions.retain` 抛 `unknown session` 并被外层 catch 静默吞掉
2075
- // (0.9.6 事故,见 afterWrite 注释)。这里显式补齐,不假设调用方传对。
2422
+ // sessions.using 与草稿键都必须用带 `session-` 前缀的写法:裸 uuid 会让宿主
2423
+ // `sessions.retain` 抛 `unknown session`(0.9.6 事故,见 afterWrite 注释)。
2076
2424
  const rawSessionId = String(opts.rawSessionId || '').trim() || (sessionId ? 'session-' + sessionId : '')
2077
2425
  const seq = opts.seq
2078
2426
  const text = typeof opts.text === 'string' ? opts.text : ''
2079
2427
  const deps = opts.deps || {}
2080
- // ⚠️ 这里只先解析 fetch:revert 失败时**不得**触碰任何草稿/视图副作用,
2428
+ const reverted = opts.reverted === true
2429
+ // ⚠️ 先只解析 fetch:revert 失败时**不得**触碰任何草稿/视图副作用,
2081
2430
  // 连「解析实现」都不该发生在失败之前(解析顺序 = 语义顺序)。
2082
2431
  const doFetch = deps.fetch || fetch
2083
2432
 
2084
- if (!sessionId || !Number.isSafeInteger(seq) || seq < 0) return { ok: false, stage: 'validate', reason: 'invalid target' }
2433
+ if (!sessionId) return { ok: false, stage: 'validate', reason: 'invalid target' }
2434
+ if (!reverted && !(Number.isSafeInteger(seq) && seq >= 0)) return { ok: false, stage: 'validate', reason: 'invalid target' }
2085
2435
  if (text.trim() === '') return { ok: false, stage: 'validate', reason: 'empty' }
2086
2436
 
2087
- // ① 回撤:失败就**什么都不做**(不写草稿、不重建视图、不动编辑器)
2088
- let res = null
2089
- let data = null
2090
- try {
2091
- res = await doFetch('/api/message-ops/revert', {
2092
- method: 'POST',
2093
- headers: { 'content-type': 'application/json' },
2094
- body: JSON.stringify({ sessionId, seq }),
2095
- })
2096
- data = await res.json().catch(() => null)
2097
- } catch (e) {
2098
- return { ok: false, stage: 'revert', reason: e && e.message ? e.message : String(e) }
2099
- }
2100
- if (!res || !res.ok || !data || data.ok !== true) {
2101
- return {
2102
- ok: false,
2103
- stage: 'revert',
2104
- status: res ? res.status : 0,
2105
- reason: (data && data.error) || 'HTTP ' + (res ? res.status : '?'),
2437
+ if (!reverted) {
2438
+ // ① 回撤:失败就**什么都不做**(不写草稿、不重建视图、不动编辑器)
2439
+ let res = null
2440
+ let data = null
2441
+ try {
2442
+ res = await doFetch('/api/message-ops/revert', {
2443
+ method: 'POST',
2444
+ headers: { 'content-type': 'application/json' },
2445
+ body: JSON.stringify({ sessionId, seq }),
2446
+ })
2447
+ // ⚠️ 本函数是**可被单独抽取执行**的编排层(contract-hardening 用 new Function
2448
+ // 抽它来断言时序),因此不许依赖模块级 helper —— 这里保留内联读法;
2449
+ // 语义与 readOpsJson 一致:解析失败 = {},绝不当成「服务端说了什么」。
2450
+ data = await res.json().catch(() => null)
2451
+ } catch (e) {
2452
+ return { ok: false, stage: 'revert', reason: e && e.message ? e.message : String(e) }
2453
+ }
2454
+ if (!res || !res.ok || !data || data.ok !== true) {
2455
+ return {
2456
+ ok: false,
2457
+ stage: 'revert',
2458
+ status: res ? res.status : 0,
2459
+ reason: (data && data.error) || 'HTTP ' + (res ? res.status : '?'),
2460
+ }
2106
2461
  }
2107
- }
2108
2462
 
2109
- // ── 回撤已成功 ── 从这里开始才解析并使用其余副作用 ──────────────────────
2110
- const doWrite = deps.writeSessionDraft || writeSessionDraft
2111
- const doRead = deps.readSessionDraft || readSessionDraft
2112
- const markShadowed = deps.markRowsShadowedFrom || markRowsShadowedFrom
2113
- const doSetDraft =
2114
- deps.setDraft ||
2115
- (v => {
2116
- // 0.24.0 P4:必须按会话取,取不到就明确失败(返回 false),
2117
- // 绝不静默退到 __inputActions —— 那可能是别的会话的 composer。
2118
- const ia = inputActionsFor(rawSessionId)
2119
- if (!ia || typeof ia.setDraft !== 'function') return false
2120
- return ia.setDraft(v)
2121
- })
2122
- const doPersistDraft =
2123
- deps.persistDraft ||
2124
- (() => {
2125
- const ia = inputActionsFor(rawSessionId)
2126
- if (!ia || typeof ia.persistDraft !== 'function') return false
2127
- return ia.persistDraft()
2128
- })
2129
- const doEmitChanged = deps.emitChanged || emitChanged
2130
- const doOpenSession = deps.openSessionById || openSessionById
2131
- const doSubmit = deps.submitEdited || (t => submitEditedText(t, { sessionId: rawSessionId }))
2463
+ // ── 回撤已成功 ── 从这里开始才解析并使用其余副作用 ──────────────────────
2464
+ const markShadowed = deps.markRowsShadowedFrom || markRowsShadowedFrom
2465
+ const doEmitChanged = deps.emitChanged || emitChanged
2466
+ const doOpenSession = deps.openSessionById || openSessionById
2132
2467
 
2133
- // ② 防 409 护栏:本地缓存里 >= seq 的行立刻标成已遮蔽(与 runUserRevert/runUndo 同一函数)
2134
- try {
2135
- markShadowed(seq)
2136
- } catch (e) {
2137
- console.warn('[message-ops] markRowsShadowedFrom failed:', e)
2138
- }
2468
+ // ② 防 409 护栏:本地缓存里 >= seq 的行立刻标成已遮蔽(与 runUserRevert/runUndo 同一函数)
2469
+ try {
2470
+ markShadowed(seq)
2471
+ } catch (e) {
2472
+ console.warn('[message-ops] markRowsShadowedFrom failed:', e)
2473
+ }
2139
2474
 
2140
- // ③ 权威落盘(合并写,保住 view 偏好)
2141
- let persisted = false
2142
- try {
2143
- persisted = doWrite(rawSessionId, text) === true
2144
- } catch (e) {
2145
- console.warn('[message-ops] writeSessionDraft failed:', e)
2146
- }
2147
- // 回读校验:只有读到**不同的非空值**才算落盘失败(读不到时保持原判断,不误判)
2148
- if (persisted && typeof doRead === 'function') {
2475
+ // ③ 通知 + 重建视图(rawSessionId 带前缀;裸 uuid 会抛 unknown session)
2476
+ try {
2477
+ doEmitChanged()
2478
+ } catch (e) {
2479
+ /* 广播失败不阻断写结果 */
2480
+ }
2149
2481
  try {
2150
- const stored = doRead(rawSessionId)
2151
- if (stored != null && stored !== text) persisted = false
2482
+ doOpenSession(rawSessionId)
2152
2483
  } catch (e) {
2153
- /* 读回失败不推翻写入结果 */
2484
+ console.warn('[message-ops] openSession failed:', e)
2154
2485
  }
2155
2486
  }
2156
2487
 
2157
- // ④ 尽力同步活着的编辑器(重挂路径靠 ③;这里只覆盖「视图没重建」的内联路径)
2488
+ // ④ 官方 prompt —— **恰好一次**。注入位是 deps.prompt(text, 'queue'):
2489
+ // 真执行测试与 contract-hardening 都从这个面观测,不靠源码形状。
2490
+ const doPrompt = deps.prompt || (t => promptEditedText(t, { rawSessionId: rawSessionId, sessions: deps.sessions }))
2491
+ let sent = null
2158
2492
  try {
2159
- doSetDraft(text)
2493
+ sent = await doPrompt(text, 'queue')
2160
2494
  } catch (e) {
2161
- console.warn('[message-ops] setDraft failed:', e)
2495
+ sent = { ok: false, reason: e && e.message ? e.message : String(e) }
2162
2496
  }
2163
- try {
2164
- doPersistDraft()
2165
- } catch (e) {
2166
- /* persistDraft 缺席不阻断 —— ③ 已经落盘 */
2497
+ if (sent && sent.ok === true) {
2498
+ return { ok: true, stage: 'done', submitted: true, mode: 'official' }
2167
2499
  }
2168
2500
 
2169
- // ⑤ 通知 + 重建视图(rawSessionId 带前缀;裸 uuid 会抛 unknown session)
2170
- try {
2171
- doEmitChanged()
2172
- } catch (e) {
2173
- /* 广播失败不阻断写结果 */
2174
- }
2175
- try {
2176
- doOpenSession(rawSessionId)
2177
- } catch (e) {
2178
- console.warn('[message-ops] openSession failed:', e)
2501
+ // 老宿主(官方发送面缺席)→ **唯一**降级:写草稿 + 回读校验 + 提示按回车。
2502
+ // 这一条真落盘才算成功;回读到的值不同就如实报 persisted=false。
2503
+ if (sent && sent.unavailable === true) {
2504
+ const doWrite = deps.writeSessionDraft || writeSessionDraft
2505
+ const doRead = deps.readSessionDraft || readSessionDraft
2506
+ let persisted = false
2507
+ try {
2508
+ persisted = doWrite(rawSessionId, text) === true
2509
+ } catch (e) {
2510
+ console.warn('[message-ops] writeSessionDraft failed:', e)
2511
+ }
2512
+ // 回读校验:只有读到**不同的非空值**才算落盘失败(读不到时保持原判断,不误判)
2513
+ if (persisted && typeof doRead === 'function') {
2514
+ try {
2515
+ const stored = doRead(rawSessionId)
2516
+ if (stored != null && stored !== text) persisted = false
2517
+ } catch (e) {
2518
+ /* 读回失败不推翻写入结果 */
2519
+ }
2520
+ }
2521
+ return { ok: true, stage: 'done', submitted: false, mode: 'manual', manual: true, persisted: persisted }
2179
2522
  }
2180
2523
 
2181
- // ⑥ 有界等待重挂后提交一次;不可用 → 调用方提示手动回车
2182
- let submitted = false
2183
- try {
2184
- submitted = (await doSubmit(text)) === true
2185
- } catch (e) {
2186
- console.warn('[message-ops] submitEdited failed:', e)
2187
- }
2188
- return { ok: true, stage: 'done', submitted: submitted === true, persisted: persisted }
2524
+ // 官方面在、但拒收/抛错:**回撤已经成功**,绝不能返回 ok:false 让 UI 报「回撤失败」。
2525
+ // 单列 stage:'send',组件据此给「回撤成功但发送被拒」的文案。
2526
+ const reason = sent && sent.reason ? String(sent.reason) : 'prompt rejected'
2527
+ return { ok: false, stage: 'send', submitted: false, mode: 'official', reason: reason }
2189
2528
  }
2190
2529
 
2191
- /**
2192
- * 编辑框样式:颜色全走 `--dsw-alias-*`,圆角全走 `--dsw-radius-*`,无裸 hex。
2193
- *
2194
- * ⚠️ 只用**已确认存在**的 token:`--dsw-alias-label-error` 与 `--dsw-alias-bg-layer-1`
2195
- * 在宿主 theme 包里并不存在(别处有误用),错误色一律用 `--dsw-alias-state-error-primary`,
2196
- * 背景用 `--dsw-alias-bg-layer-1`。全部带 fallback,深色模式不吃亏。
2197
- */
2198
- function ensureEditStyle() {
2530
+ // --- 0.28.0 就地编辑(替代 0.26 的浮动编辑层)-------------------------------
2531
+ //
2532
+ // 为什么重写:官方 `useAnchoredPosition` 在当前宿主(0.2.2-rc.5 构建产物)里
2533
+ // **已不存在**(只剩 `useAnchoredMaxHeight`),旧实现的
2534
+ // `useAnchoredPosition = primitives.useAnchoredPosition || (() => null)` 静默降级
2535
+ // → 面板永远停在 `visibility:hidden` 的测量态、坐标 (0,0)(真机复现)。
2536
+ //
2537
+ // 就地编辑不依赖任何定位 API:编辑器直接挂进这条消息自己的行里(气泡下方、
2538
+ // 动作行上方),宿主滚动/重排都带着它走。保存 = 回撤 + 官方 prompt
2539
+ // (仍由 `sendEditAndRevert` 单一编排,时序契约不变)。
2540
+
2541
+ // ══ 50-inline-edit · 就地编辑(气泡下、动作行上) ══
2542
+ const IE_STYLE_ID = 'dsh-message-ops-inline-edit-style'
2543
+ const IE_CLASS = 'mopsIeWrap'
2544
+ /** 当前打开的编辑器。宿主重建块时会换掉 DOM,靠它按 seq 重挂(文本不丢)。 */
2545
+ let inlineEdit = null
2546
+
2547
+ /** 就地编辑样式:只用已确认存在的 token;不做 absolute/fixed 定位。 */
2548
+ function ensureIeStyle() {
2199
2549
  try {
2200
2550
  if (typeof document === 'undefined' || !document.head) return
2201
- if (document.getElementById(EDIT_STYLE_ID)) return
2551
+ if (document.getElementById(IE_STYLE_ID)) return
2202
2552
  const tag = document.createElement('style')
2203
- tag.id = EDIT_STYLE_ID
2553
+ tag.id = IE_STYLE_ID
2204
2554
  tag.textContent = [
2205
- '.mopsErScrim{position:fixed;inset:0;z-index:1200;display:flex;align-items:center;justify-content:center;padding:24px;background:var(--dsw-alias-bg-mask-1,rgba(15,17,21,.42));animation:mopsErFade .12s ease-out}',
2206
- '@keyframes mopsErFade{from{opacity:0}to{opacity:1}}',
2207
- '@keyframes mopsErRise{from{opacity:0;transform:translateY(8px) scale(.985)}to{opacity:1;transform:none}}',
2208
- '@media(prefers-reduced-motion:reduce){.mopsErScrim,.mopsErPanel{animation:none}}',
2209
- '.mopsErPanel{width:min(560px,100%);max-height:min(720px,100%);display:flex;flex-direction:column;gap:10px;padding:16px;background:var(--dsw-alias-bg-layer-1,#fff);color:var(--dsw-alias-label-primary,#0f1115);border:1px solid var(--dsw-alias-border-l2,#e6e6e6);border-radius:var(--dsw-radius-md,12px);box-shadow:0 24px 64px rgba(15,17,21,.24);font-family:inherit;font-size:13px;line-height:1.45;animation:mopsErRise .16s cubic-bezier(.2,.8,.3,1)}',
2210
- '.mopsErPanel *{box-sizing:border-box}',
2211
- '.mopsErHead{display:flex;align-items:flex-start;justify-content:space-between;gap:12px;flex:none}',
2212
- '.mopsErTitle{font-size:15px;font-weight:600;line-height:22px}',
2213
- '.mopsErSub{font-size:11px;line-height:16px;color:var(--dsw-alias-label-tertiary,#8a8a8e);margin-top:2px;font-variant-numeric:tabular-nums}',
2214
- '.mopsErClose{width:28px;height:28px;flex:none;display:inline-flex;align-items:center;justify-content:center;border:1px solid transparent;border-radius:var(--dsw-radius-xs,4px);background:transparent;color:var(--dsw-alias-label-tertiary,#8a8a8e);cursor:pointer;font-size:16px;line-height:1}',
2215
- '.mopsErClose:hover:not(:disabled){background:var(--dsw-alias-interactive-bg-hover,rgba(128,128,128,.12));color:var(--dsw-alias-label-primary,#0f1115)}',
2216
- '.mopsErClose:disabled{opacity:.4;cursor:default}',
2217
- '.mopsErBody{flex:1;min-height:0;display:flex;flex-direction:column;gap:8px}',
2218
- '.mopsErText{width:100%;min-height:120px;max-height:40vh;resize:vertical;padding:10px;border:1px solid var(--dsw-alias-border-l2,#e6e6e6);border-radius:var(--dsw-radius-sm,8px);background:var(--dsw-alias-bg-layer-2,#f7f7f8);color:var(--dsw-alias-label-primary,#0f1115);font:inherit;font-size:14px;line-height:1.6;outline:none}',
2219
- '.mopsErText::placeholder{color:var(--dsw-alias-label-tertiary,#8a8a8e)}',
2220
- '.mopsErText:focus-visible{box-shadow:0 0 0 2px var(--dsw-alias-bg-layer-1,#fff),0 0 0 4px var(--dsw-alias-brand-primary,#4d6bfe)}',
2221
- '.mopsErText:disabled{opacity:.6;cursor:progress}',
2222
- '.mopsErText[aria-invalid="true"]{border-color:var(--dsw-alias-state-error-primary,#c63b32)}',
2223
- '.mopsErHint{font-size:11px;line-height:17px;color:var(--dsw-alias-label-tertiary,#8a8a8e)}',
2224
- '.mopsErError{font-size:12px;line-height:18px;color:var(--dsw-alias-state-error-primary,#c63b32);overflow-wrap:anywhere}',
2225
- '.mopsErOk{font-size:12px;line-height:18px;color:var(--dsw-alias-state-success-primary,#2f7d4a)}',
2226
- '.mopsErActions{flex:none;display:flex;gap:8px;justify-content:flex-end;flex-wrap:wrap}',
2227
- '.mopsErBtn{min-height:30px;padding:4px 9px;border-radius:var(--dsw-radius-xs,4px);font:inherit;font-size:12px;line-height:20px;cursor:pointer;border:1px solid transparent}',
2228
- '.mopsErGhost{color:var(--dsw-alias-label-secondary,#6b6b70);background:transparent}',
2229
- '.mopsErGhost:hover:not(:disabled){background:var(--dsw-alias-interactive-bg-hover,rgba(128,128,128,.12));color:var(--dsw-alias-label-primary,#0f1115)}',
2230
- '.mopsErPrimary{background:var(--dsw-alias-button-primary-fill,#2b2b2e);color:var(--dsw-alias-label-primary-foreground,#fff)}',
2231
- '.mopsErPrimary:hover:not(:disabled){background:var(--dsw-alias-button-primary-hover,#3a3a3e)}',
2232
- '.mopsErBtn:disabled{opacity:.5;cursor:not-allowed}',
2233
- '.mopsErBtn:focus-visible,.mopsErClose:focus-visible{outline:2px solid var(--dsw-alias-brand-primary,#4d6bfe);outline-offset:1px}',
2234
- '@media(max-width:760px){.mopsErScrim{padding:0}.mopsErPanel{width:100%;height:100%;max-height:100%;border:0;border-radius:0}}',
2555
+ '.mopsIeWrap{display:flex;flex-direction:column;gap:8px;align-self:flex-end;width:min(calc(var(--dsh-chat-content-width,748px)*.702),82%);margin-top:2px;text-align:left}',
2556
+ '.mopsIeWrap *{box-sizing:border-box}',
2557
+ '.mopsIeText{width:100%;min-height:72px;max-height:32vh;resize:vertical;padding:8px 10px;border:1px solid var(--dsw-alias-border-l2,#e6e6e6);border-radius:var(--dsw-radius-sm,8px);background:var(--dsw-alias-bg-layer-1,#fff);color:var(--dsw-alias-label-primary,#0f1115);font:inherit;font-size:14px;line-height:1.6}',
2558
+ '.mopsIeText:focus{border-color:var(--dsw-alias-state-business-primary,#4d6bfe);box-shadow:0 0 0 2px color-mix(in srgb,var(--dsw-alias-state-business-primary,#4d6bfe) 24%,transparent)}',
2559
+ '.mopsIeText:disabled{opacity:.7}',
2560
+ '.mopsIeHint{font-size:12px;line-height:1.5;color:var(--dsw-alias-label-tertiary,#8a8a8e)}',
2561
+ '.mopsIeStatus{font-size:12px;line-height:1.5;color:var(--dsw-alias-state-error-primary,#d33)}',
2562
+ '.mopsIeActions{display:flex;align-items:center;justify-content:flex-end;gap:8px}',
2563
+ '.mopsIeBtn{height:28px;padding:0 12px;border-radius:var(--dsw-radius-sm,8px);border:1px solid var(--dsw-alias-border-l2,#e6e6e6);background:var(--dsw-alias-bg-layer-1,#fff);color:var(--dsw-alias-label-primary,#0f1115);font:inherit;font-size:13px;cursor:pointer}',
2564
+ '.mopsIeBtn:disabled{opacity:.55;cursor:default}',
2565
+ '.mopsIePrimary{background:var(--dsw-alias-label-primary,#0f1115);color:var(--dsw-alias-bg-layer-1,#fff);border-color:transparent}',
2566
+ '.mopsIeGhost{background:transparent}',
2235
2567
  ].join('')
2236
2568
  document.head.appendChild(tag)
2237
2569
  } catch (e) {
2238
- /* 样式注入失败不影响功能 */
2570
+ /* 样式注入失败不阻断编辑(宿主禁用 style 时会退化) */
2239
2571
  }
2240
2572
  }
2241
2573
 
2242
2574
  /**
2243
- * 「编辑并重发」浮层(`shell.overlay` 槽,与本插件 OpsPanel 同族)。
2575
+ * 关闭编辑区。
2576
+ *
2577
+ * `restoreFocus` 默认 true:Esc / 取消后把焦点还给铅笔按钮 —— 否则焦点掉到
2578
+ * body,键盘用户会丢失位置(真机实测:Esc 后 document.activeElement 是 BODY)。
2579
+ * 发送成功后不还原:那一行会被回撤重建,旧按钮已不在 DOM 里。
2244
2580
  *
2245
- * 常驻挂载、内部 state 控制显隐 —— 与 OpsPanel 完全同款(list 槽的条目没有
2246
- * 「开关」概念,只能靠组件自身状态)。未打开时返回 null。
2581
+ * @param {'close'|'sent'} reason 关闭原因(sent = 发送成功,行会被重建)
2247
2582
  */
2248
- function EditResendOverlay(props) {
2249
- const { sessionId, useSessions } = props
2250
- const t = (props && props.t) || __t
2251
- useLocaleRevision()
2252
- if (sessionId) __currentSessionId = sessionId
2253
- const sessions = useSessions ? useSessions(s => s) : undefined
2254
- const [target, setTarget] = useState(null) // { sessionId, rawSessionId, seq }
2255
- const [draft, setDraft] = useState('')
2256
- const [textState, setTextState] = useState('idle') // idle|loading|ready|error
2257
- const [loadError, setLoadError] = useState(null)
2258
- const [saving, setSaving] = useState(false)
2259
- const [error, setError] = useState(null)
2260
- const [done, setDone] = useState('')
2261
- const textRef = useRef(null)
2262
- const reqRef = useRef(0)
2263
-
2264
- useEffect(() => {
2265
- ensureEditStyle()
2266
- const handler = e => {
2267
- const d = e && e.detail ? e.detail : {}
2268
- if (!d.sessionId || !Number.isSafeInteger(d.seq)) return
2269
- reqRef.current += 1
2270
- setTarget({ sessionId: String(d.sessionId), rawSessionId: d.rawSessionId || d.sessionId, seq: d.seq })
2271
- setDraft('')
2272
- setTextState('loading')
2273
- setLoadError(null)
2274
- setError(null)
2275
- setDone('')
2583
+ function closeInlineEdit(reason) {
2584
+ const prev = inlineEdit
2585
+ if (prev && prev.el && prev.el.isConnected) {
2586
+ try {
2587
+ prev.el.remove()
2588
+ } catch (e) {
2589
+ console.warn('[message-ops] inline editor remove failed:', e)
2276
2590
  }
2277
- window.addEventListener(EDIT_EVENT, handler)
2278
- return () => window.removeEventListener(EDIT_EVENT, handler)
2279
- }, [])
2280
-
2281
- const loadText = useCallback(() => {
2282
- if (!target) return
2283
- const req = ++reqRef.current
2284
- const sid = target.sessionId
2285
- setTextState('loading')
2286
- setLoadError(null)
2287
- fetch('/api/message-ops/text?sessionId=' + encodeURIComponent(sid) + '&seq=' + encodeURIComponent(target.seq))
2288
- .then(res =>
2289
- res
2290
- .json()
2291
- .catch(() => null)
2292
- .then(data => ({ res, data })),
2293
- )
2294
- .then(({ res, data }) => {
2295
- if (req !== reqRef.current) return
2296
- if (!res.ok || !data || data.ok !== true) throw new Error((data && data.error) || 'HTTP ' + res.status)
2297
- if (typeof data.text !== 'string' || data.text === '') throw new Error(t('slot.editNoText'))
2298
- // ⚠️ 只认 /text 的全文:绝不拿 160 字 snippet 冒充原文
2299
- // (service 侧硬截断,见 session-file.js 的 snippet.slice(0,160))
2300
- setDraft(data.text)
2301
- setTextState('ready')
2302
- })
2303
- .catch(reason => {
2304
- if (req !== reqRef.current) return
2305
- setLoadError(t('edit.loadFail') + (reason && reason.message ? reason.message : String(reason)))
2306
- setTextState('error')
2307
- })
2308
- }, [target, t])
2591
+ }
2592
+ inlineEdit = null
2593
+ if (prev && prev.btn && prev.btn.isConnected) {
2594
+ try {
2595
+ prev.btn.setAttribute('aria-expanded', 'false')
2596
+ prev.btn.removeAttribute('aria-controls')
2597
+ } catch (e) {
2598
+ /* aria 复位失败不影响编辑 */
2599
+ }
2600
+ }
2601
+ if ((reason || 'close') === 'close' && prev && prev.btn && prev.btn.isConnected) {
2602
+ try {
2603
+ prev.btn.focus()
2604
+ } catch (e) {
2605
+ /* 焦点归还失败不影响编辑 */
2606
+ }
2607
+ }
2608
+ }
2309
2609
 
2310
- useEffect(() => {
2311
- if (!target) return undefined
2312
- loadText()
2313
- return undefined
2314
- }, [target, loadText])
2610
+ /** 周期刷新编辑区的运行态(scan 每帧调用;编辑器没开时是空操作)。 */
2611
+ function paintInlineEdit() {
2612
+ if (inlineEdit && typeof inlineEdit.paint === 'function') {
2613
+ try {
2614
+ inlineEdit.paint()
2615
+ } catch (e) {
2616
+ console.warn('[message-ops] inline editor paint failed:', e)
2617
+ }
2618
+ }
2619
+ }
2315
2620
 
2316
- // 光标置末尾:长消息从第一行开始编辑很难受,用户多半是改尾部
2317
- useEffect(() => {
2318
- if (textState !== 'ready' || !textRef.current) return
2319
- const el = textRef.current
2621
+ /** 回撤已成功但发送被拒:文本放回该会话草稿(并更新活着的编辑器)。 */
2622
+ function stageDraft(rawSid, text) {
2623
+ try {
2624
+ writeSessionDraft(rawSid, text)
2625
+ } catch (e) {
2626
+ console.warn('[message-ops] writeSessionDraft failed:', e)
2627
+ }
2628
+ const live = inputActionsFor(rawSid)
2629
+ if (live && typeof live.setDraft === 'function') {
2320
2630
  try {
2321
- el.focus()
2322
- const end = el.value.length
2323
- el.setSelectionRange(end, end)
2631
+ live.setDraft(text)
2324
2632
  } catch (e) {
2325
- /* 非浏览器 / 不支持的输入类型:忽略 */
2633
+ console.warn('[message-ops] setDraft failed:', e)
2326
2634
  }
2327
- }, [textState])
2635
+ }
2636
+ }
2328
2637
 
2329
- const cancel = useCallback(() => {
2330
- if (saving) return
2331
- // 零副作用:只清本地 state。不清宿主草稿、不碰会话、不发请求。
2332
- reqRef.current += 1
2333
- setTarget(null)
2334
- setDraft('')
2335
- setTextState('idle')
2336
- setLoadError(null)
2337
- setError(null)
2338
- setDone('')
2339
- }, [saving])
2638
+ /** 行内挂载点:气泡栈之后、宿主动作行之前(动作行始终在最下面)。 */
2639
+ function mountInlineEdit(block, el, rowHint) {
2640
+ const rowEl = rowHint || block.querySelector('[class*="userRow"]') || block
2641
+ const acts = rowEl.querySelector('[class*="' + HOST_CLS.actions + '"]')
2642
+ if (acts && acts.parentElement === rowEl) rowEl.insertBefore(el, acts)
2643
+ else rowEl.appendChild(el)
2644
+ return rowEl
2645
+ }
2340
2646
 
2341
- const running = (() => {
2342
- if (!target || !sessions || !sessions.byId) return false
2343
- const summary =
2344
- sessions.byId[target.rawSessionId] || sessions.byId['session-' + target.sessionId] || sessions.byId[target.sessionId]
2345
- return summary ? summary.running === true : false
2346
- })()
2647
+ /**
2648
+ * 就地编辑入口(铅笔点击后调用)。
2649
+ *
2650
+ * @param btn - 铅笔按钮(读失败时据此复位 disabled)
2651
+ * @param block - 该条用户消息的流块(`data-chat-node-key` / `data-mops-seq`)
2652
+ * @param row - `/messages` 里的该行(`fullText` 是全文,**不是** snippet)
2653
+ * @param rawSidArg - 带 `session-` 前缀的会话 id(缺省取 `__currentSessionId`)
2654
+ * @param deps - 可注入副作用(测试用:send / notify / running / stageDraft)
2655
+ */
2656
+ function openInlineEdit(btn, block, row, rawSidArg, deps) {
2657
+ const rawSid = rawSidArg || __currentSessionId
2658
+ if (!rawSid || !row) return
2659
+ const sid = bareSessionId(rawSid)
2660
+ const seq = row.seq
2661
+ if (!Number.isSafeInteger(seq)) return
2662
+ // 同一条再点铅笔 = 收起(幂等;不会叠出两个编辑区)
2663
+ if (inlineEdit && inlineEdit.seq === seq && inlineEdit.block === block) {
2664
+ closeInlineEdit()
2665
+ return
2666
+ }
2667
+ closeInlineEdit()
2668
+ ensureIeStyle()
2669
+ // 批量 steering 的一个 flow 块里可能有多个 userRow(pending/echo 各一条),
2670
+ // 从 block 里 querySelector 会挂到上一条消息下面 —— 用铅笔自己的祖先定位。
2671
+ const rowHint = btn && typeof btn.closest === 'function' ? btn.closest('[class*="userRow"]') : null
2672
+
2673
+ const wrap = document.createElement('div')
2674
+ wrap.className = IE_CLASS
2675
+ wrap.id = 'mops-ie-' + seq
2676
+ wrap.setAttribute('data-mops-ie', '1')
2677
+ if (btn && typeof btn.setAttribute === 'function') {
2678
+ btn.setAttribute('aria-expanded', 'true')
2679
+ btn.setAttribute('aria-controls', wrap.id)
2680
+ }
2347
2681
 
2348
- const canSubmit = textState === 'ready' && !saving && draft.trim() !== '' && !running
2682
+ const ta = document.createElement('textarea')
2683
+ ta.className = 'mopsIeText'
2684
+ ta.rows = 3
2685
+ ta.value = typeof row.fullText === 'string' ? row.fullText : ''
2686
+ ta.placeholder = __t('edit.placeholder')
2687
+ ta.setAttribute('aria-label', __t('edit.title'))
2688
+
2689
+ const hint = document.createElement('div')
2690
+ hint.className = 'mopsIeHint'
2691
+ // D-3:回撤不是删除,原文仍在本地会话文件里。这句不能删。
2692
+ hint.textContent = __t('edit.replaceHint')
2693
+
2694
+ const status = document.createElement('div')
2695
+ status.className = 'mopsIeStatus'
2696
+ status.setAttribute('role', 'alert')
2697
+ status.hidden = true
2698
+
2699
+ const actions = document.createElement('div')
2700
+ actions.className = 'mopsIeActions'
2701
+ const cancelBtn = document.createElement('button')
2702
+ cancelBtn.type = 'button'
2703
+ cancelBtn.className = 'mopsIeBtn mopsIeGhost'
2704
+ cancelBtn.textContent = __t('edit.cancel')
2705
+ const sendBtn = document.createElement('button')
2706
+ sendBtn.type = 'button'
2707
+ sendBtn.className = 'mopsIeBtn mopsIePrimary'
2708
+ sendBtn.textContent = __t('edit.send')
2709
+ actions.appendChild(cancelBtn)
2710
+ actions.appendChild(sendBtn)
2711
+
2712
+ wrap.appendChild(ta)
2713
+ wrap.appendChild(hint)
2714
+ // 错误贴着输入框与按钮,而不是被按钮行隔开(IE-12)
2715
+ wrap.appendChild(status)
2716
+ wrap.appendChild(actions)
2717
+ mountInlineEdit(block, wrap, rowHint)
2718
+
2719
+ let saving = false
2720
+ const send = (deps && deps.send) || sendEditAndRevert
2721
+ const notify = (deps && deps.notify) || notifyDone
2722
+ const stash = (deps && deps.stageDraft) || stageDraft
2723
+ const runningNow = () =>
2724
+ deps && typeof deps.running === 'function'
2725
+ ? deps.running() === true
2726
+ : (() => {
2727
+ const cache = __peekRowsCache ? __peekRowsCache() : null
2728
+ return !!(cache && cache.running === true)
2729
+ })()
2730
+ const paint = () => {
2731
+ const running = runningNow()
2732
+ ta.readOnly = saving
2733
+ // 保存中不要 disabled:Chrome 对 disabled 元素会立刻失焦,
2734
+ // 焦点掉到 BODY 后 Esc(挂在 wrap 上)也收不到。用 aria-disabled 表达。
2735
+ cancelBtn.disabled = false
2736
+ cancelBtn.setAttribute('aria-disabled', saving ? 'true' : 'false')
2737
+ sendBtn.disabled = false
2738
+ sendBtn.setAttribute('aria-disabled', saving || running || ta.value.trim() === '' ? 'true' : 'false')
2739
+ sendBtn.textContent = saving ? __t('edit.sending') : __t('edit.send')
2740
+ sendBtn.title = running ? __t('edit.running') : __t('edit.shortcut')
2741
+ // 运行中不能只靠 tooltip:把原因写进可见的说明行(D-3 文案保留)
2742
+ hint.textContent = running ? __t('edit.replaceHint') + ' · ' + __t('edit.running') : __t('edit.replaceHint')
2743
+ }
2744
+ const fail = msg => {
2745
+ status.textContent = msg
2746
+ status.hidden = false
2747
+ }
2748
+ const clearFail = () => {
2749
+ status.textContent = ''
2750
+ status.hidden = true
2751
+ }
2349
2752
 
2350
- const send = useCallback(async () => {
2351
- if (!target || !canSubmit) return
2352
- setSaving(true)
2353
- setError(null)
2354
- setDone('')
2355
- const result = await sendEditAndRevert({
2356
- sessionId: target.sessionId,
2357
- rawSessionId: target.rawSessionId,
2358
- seq: target.seq,
2359
- text: draft,
2753
+ const submit = async () => {
2754
+ if (saving) return
2755
+ const text = ta.value
2756
+ if (text.trim() === '') {
2757
+ fail(__t('edit.empty'))
2758
+ return
2759
+ }
2760
+ if (runningNow()) {
2761
+ fail(__t('edit.running'))
2762
+ paint()
2763
+ return
2764
+ }
2765
+ clearFail()
2766
+ saving = true
2767
+ paint()
2768
+ // 0.32.2:回撤步必须有超时。sendEditAndRevert 明令不许依赖模块级 helper
2769
+ // (它能被单独抽取执行),所以超时通过 deps.fetch 注入;saving 才不会
2770
+ // 因为后端挂起而永久为 true(按钮 aria-disabled + textarea readOnly)。
2771
+ const result = await send({
2772
+ sessionId: sid,
2773
+ rawSessionId: rawSid,
2774
+ seq: seq,
2775
+ text: text,
2776
+ deps: { fetch: (url, init) => fetchWithTimeout(url, init, 15000) },
2360
2777
  })
2361
- if (!result.ok) {
2362
- // ⚠️ 失败必须保留编辑框 + 用户已输入的文本(不清 draft、不 close)
2363
- setSaving(false)
2364
- setError(
2365
- result.stage === 'revert'
2366
- ? t('edit.failed') + (result.reason || 'HTTP ' + result.status)
2367
- : result.reason === 'empty'
2368
- ? t('edit.empty')
2369
- : String(result.reason || ''),
2370
- )
2778
+ saving = false
2779
+ if (result.ok) {
2780
+ notify(result.submitted ? __t('edit.doneSubmitted') : __t('edit.manual'))
2781
+ closeInlineEdit('sent')
2782
+ focusComposer()
2371
2783
  return
2372
2784
  }
2373
- setSaving(false)
2374
- if (result.submitted) {
2375
- notifyDone(t('edit.doneSubmitted'))
2376
- cancel()
2785
+ if (result.stage === 'send') {
2786
+ // 回撤已生效、视图已重建 —— 编辑区所在的节点很可能已经没了。
2787
+ // 不赌「浮层活过重建」:文本直接放回输入框,用户按回车即可重发。
2788
+ stash(rawSid, text)
2789
+ notify(__t('edit.sendFailed') + (result.reason || ''), 'warn')
2790
+ closeInlineEdit('sent')
2791
+ focusComposer()
2377
2792
  return
2378
2793
  }
2379
- // 提交不可用:明确告诉用户文本已经在输入框里,别让人以为没发生
2380
- notifyDone(t('edit.manual'), 'warn')
2381
- setDone(t('edit.manual'))
2382
- }, [target, canSubmit, draft, t, cancel])
2383
-
2384
- if (!target) return null
2794
+ // 回撤失败(或参数非法):编辑区与文本都必须保留。
2795
+ // 0.33.3(ui-live P2-3):15s 超时的 AbortError message 是英文原文,
2796
+ // 走本地化超时文案(与面板同一口径),不把 "The operation was aborted." 摊给用户。
2797
+ const reasonText = /abort/i.test(String(result.reason || '')) ? __t('panel.timeout') : result.reason || ''
2798
+ fail((result.stage === 'revert' ? __t('edit.failed') : '') + reasonText)
2799
+ paint()
2800
+ }
2385
2801
 
2386
- const onKeyDown = e => {
2802
+ cancelBtn.addEventListener('click', e => {
2803
+ e.preventDefault()
2804
+ if (!saving) closeInlineEdit()
2805
+ })
2806
+ sendBtn.addEventListener('click', e => {
2807
+ e.preventDefault()
2808
+ if (saving || sendBtn.getAttribute('aria-disabled') === 'true') return
2809
+ submit()
2810
+ })
2811
+ ta.addEventListener('input', () => {
2812
+ clearFail()
2813
+ paint()
2814
+ })
2815
+ // IE-2:Esc 挂在整块上 —— 焦点 Tab 到按钮后仍然有效;Enter 只在输入框里提交
2816
+ wrap.addEventListener('keydown', e => {
2387
2817
  if (e.key === 'Escape') {
2388
2818
  e.preventDefault()
2389
- if (!saving) cancel()
2819
+ if (!saving) closeInlineEdit()
2390
2820
  return
2391
2821
  }
2392
- if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) {
2393
- e.preventDefault()
2394
- if (canSubmit) send()
2822
+ if (e.target !== ta) return
2823
+ if (e.key !== 'Enter' || e.shiftKey) return
2824
+ // IME 组词中的 Enter 是选词,不是提交(keyCode 229 是旧引擎的组词信号)
2825
+ if (e.isComposing || e.keyCode === 229) return
2826
+ e.preventDefault()
2827
+ submit()
2828
+ })
2829
+
2830
+ inlineEdit = { seq: seq, rawSid: rawSid, el: wrap, block: block, ta: ta, btn: btn || null, focused: false, sel: null, paint: paint, original: ta.value }
2831
+ ta.addEventListener('focus', () => {
2832
+ if (inlineEdit && inlineEdit.ta === ta) inlineEdit.focused = true
2833
+ })
2834
+ ta.addEventListener('blur', () => {
2835
+ if (inlineEdit && inlineEdit.ta === ta) {
2836
+ inlineEdit.focused = false
2837
+ inlineEdit.sel = [ta.selectionStart, ta.selectionEnd]
2395
2838
  }
2839
+ })
2840
+ ta.addEventListener('input', () => {
2841
+ if (inlineEdit && inlineEdit.ta === ta) inlineEdit.sel = [ta.selectionStart, ta.selectionEnd]
2842
+ })
2843
+ paint()
2844
+ try {
2845
+ // 编辑区比气泡高约 150px:靠近底部时要保证按钮与说明也在视口内
2846
+ if (typeof wrap.scrollIntoView === 'function') wrap.scrollIntoView({ block: 'nearest' })
2847
+ ta.focus({ preventScroll: true })
2848
+ ta.setSelectionRange(ta.value.length, ta.value.length)
2849
+ } catch (e) {
2850
+ /* 聚焦失败不影响编辑 */
2396
2851
  }
2852
+ if (btn) btn.disabled = false
2853
+ }
2397
2854
 
2398
- return React.createElement(
2399
- 'div',
2400
- {
2401
- className: 'mopsErScrim',
2402
- role: 'presentation',
2403
- onMouseDown: e => {
2404
- if (e.target === e.currentTarget && !saving) cancel()
2405
- },
2406
- },
2407
- React.createElement(
2408
- 'section',
2409
- {
2410
- className: 'mopsErPanel',
2411
- role: 'dialog',
2412
- 'aria-modal': 'true',
2413
- 'aria-labelledby': 'mops-er-title',
2414
- onKeyDown,
2415
- },
2416
- React.createElement(
2417
- 'div',
2418
- { className: 'mopsErHead' },
2419
- React.createElement(
2420
- 'div',
2421
- null,
2422
- React.createElement('div', { className: 'mopsErTitle', id: 'mops-er-title' }, t('edit.title')),
2423
- React.createElement('div', { className: 'mopsErSub' }, t('edit.subtitle', { seq: String(target.seq) })),
2424
- ),
2425
- React.createElement(
2426
- 'button',
2427
- {
2428
- type: 'button',
2429
- className: 'mopsErClose',
2430
- onClick: cancel,
2431
- disabled: saving,
2432
- title: t('edit.cancel'),
2433
- 'aria-label': t('edit.cancel'),
2434
- },
2435
- '×',
2436
- ),
2437
- ),
2438
- React.createElement(
2439
- 'div',
2440
- { className: 'mopsErBody' },
2441
- React.createElement('textarea', {
2442
- className: 'mopsErText',
2443
- ref: textRef,
2444
- value: draft,
2445
- rows: 6,
2446
- readOnly: saving,
2447
- disabled: textState !== 'ready',
2448
- 'aria-invalid': error || textState === 'error' ? 'true' : undefined,
2449
- placeholder: textState === 'loading' ? t('edit.loading') : t('edit.placeholder'),
2450
- onChange: e => setDraft(e.target.value),
2451
- 'aria-label': t('edit.title'),
2452
- }),
2453
- textState === 'error'
2454
- ? React.createElement(
2455
- 'div',
2456
- { className: 'mopsErError', role: 'alert' },
2457
- loadError,
2458
- ' ',
2459
- React.createElement('button', { type: 'button', className: 'mopsErBtn mopsErGhost', onClick: loadText }, t('edit.retry')),
2460
- )
2461
- : null,
2462
- running ? React.createElement('div', { className: 'mopsErError', role: 'alert' }, t('edit.running')) : null,
2463
- error ? React.createElement('div', { className: 'mopsErError', role: 'alert' }, error) : null,
2464
- done ? React.createElement('div', { className: 'mopsErOk', role: 'status' }, done) : null,
2465
- React.createElement('div', { className: 'mopsErHint' }, t('edit.replaceHint')),
2466
- ),
2467
- React.createElement(
2468
- 'div',
2469
- { className: 'mopsErActions' },
2470
- React.createElement(
2471
- 'button',
2472
- { type: 'button', className: 'mopsErBtn mopsErGhost', onClick: cancel, disabled: saving },
2473
- t('edit.cancel'),
2474
- ),
2475
- React.createElement(
2476
- 'button',
2477
- { type: 'button', className: 'mopsErBtn mopsErPrimary', onClick: send, disabled: !canSubmit },
2478
- saving ? t('edit.sending') : t('edit.send'),
2479
- ),
2480
- ),
2481
- ),
2855
+ /**
2856
+ * 宿主重建消息块后把编辑区挂回去(同一 seq 的新块),文本随元素保留。
2857
+ * 会话切换或该行已不存在 → 关闭。
2858
+ */
2859
+ function rehydrateInlineEdit() {
2860
+ if (!inlineEdit) return
2861
+ // 只有「确实切到了另一个会话」才关;当前会话未知(测试/宿主尚未挂载)时不猜。
2862
+ if (__currentSessionId && inlineEdit.rawSid !== __currentSessionId) {
2863
+ // IE-13:切会话时编辑区会被摘掉。改过的文本必须落回**原会话**草稿,
2864
+ // 否则用户打了一半的字凭空消失(原先 detach 分支不保存)。
2865
+ const text = inlineEdit.ta ? inlineEdit.ta.value : ''
2866
+ if (text && text !== inlineEdit.original) stageDraft(inlineEdit.rawSid, text)
2867
+ closeInlineEdit('detach')
2868
+ return
2869
+ }
2870
+ if (inlineEdit.el.isConnected) return
2871
+ const target = Array.from(document.querySelectorAll('[data-chat-flow-kind="user"]')).find(
2872
+ b => b.getAttribute('data-mops-seq') === String(inlineEdit.seq),
2482
2873
  )
2874
+ if (!target) return
2875
+ mountInlineEdit(target, inlineEdit.el)
2876
+ inlineEdit.block = target
2877
+ // 宿主重建块会摘掉元素 → 焦点掉到 body。用户正在打字时必须把焦点与光标还回去。
2878
+ if (inlineEdit.focused && document.activeElement === document.body) {
2879
+ try {
2880
+ inlineEdit.ta.focus({ preventScroll: true })
2881
+ if (inlineEdit.sel) inlineEdit.ta.setSelectionRange(inlineEdit.sel[0], inlineEdit.sel[1])
2882
+ } catch (e) {
2883
+ /* 恢复焦点失败不影响编辑 */
2884
+ }
2885
+ }
2483
2886
  }
2484
2887
 
2485
2888
  // --- 头部按钮 ---------------------------------------------------------------
2486
2889
 
2890
+ // ══ 60-session · 会话工具:分叉 / 草稿 / safeOpenSession / 通知 / OpsButton ══
2487
2891
  // 0.3.0 分支双路径选择:0.2.0+ 官方 sessions.fork({atSeq}) 优先。
2488
2892
  function pickForkPath(sessionsSvc) {
2489
2893
  if (sessionsSvc && typeof sessionsSvc.fork === 'function') {
@@ -2572,19 +2976,45 @@ window.__ModuleLoader__.load({
2572
2976
  }
2573
2977
  }
2574
2978
 
2575
- /** 打开会话(宿主唯一通道)。childId 需要 `session-` 前缀才不会抛 unknown session。 */
2576
- function openSessionById(sessionId) {
2979
+ /**
2980
+ * 打开会话(宿主唯一通道),**失败必须留痕**(审计 §2.3 的 6 处吞错单点)。
2981
+ *
2982
+ * 为什么不能继续静默 `catch {}`:`openSession` 失败的用户可见后果正是本轮反复
2983
+ * 修的那一类 ——「回滚后界面没变灰 / 恢复后消息不回来 / 铅笔点不开」。而
2984
+ * `/undo`、`/redo` 的 `afterWrite` 注释已把 0.9.6 事故写死:传裸 uuid →
2985
+ * 宿主 `sessions.retain` 抛 `unknown session <bare>` → 外层 `catch {}` 静默吞掉
2986
+ * → **「视图重建」这条路径从来没生效过**,只剩 150/700/1600ms 的 DOM 打补丁。
2987
+ * 同一份事故档案写在文档里,代码里 6 个调用点却有 5 个还在吞 —— 这条单点就是
2988
+ * 把「文档说的」变成「代码做的」。
2989
+ *
2990
+ * ⚠️ 仍然必须 catch:不 swallow 会让 React 渲染抛(这是渲染期调用)。
2991
+ * ⚠️ `sessionId` 必须带 `session-` 前缀:宿主 `sessions.retain(bare)` 只认
2992
+ * `session-<uuid>`(manager.js resolveTarget),传裸 uuid 必抛。
2993
+ *
2994
+ * @param sessionId - 会话 id(`session-<uuid>` 形态)
2995
+ * @param where - 调用点标记,写进 warn 文本 —— 排障时一眼看出是哪条路径没重建
2996
+ * @returns `true` = 真的调了宿主 `openSession`;`false` = 服务缺席 / 未挂载 / 抛了
2997
+ */
2998
+ function safeOpenSession(sessionId, where) {
2577
2999
  try {
2578
3000
  if (__uiWorkspace && typeof __uiWorkspace.openSession === 'function') {
2579
3001
  __uiWorkspace.openSession(sessionId)
2580
3002
  return true
2581
3003
  }
2582
3004
  } catch (e) {
2583
- console.warn('[message-ops] openSession failed:', e)
3005
+ console.warn('[message-ops] openSession failed @' + String(where || 'unknown') + ':', e)
2584
3006
  }
2585
3007
  return false
2586
3008
  }
2587
3009
 
3010
+ /**
3011
+ * `sendEditAndRevert` 的可注入依赖面:测试用 `deps.openSessionById` 观测时序,
3012
+ * 生产路径就是 {@link safeOpenSession}(保留本名是为了不破坏既有注入契约)。
3013
+ */
3014
+ function openSessionById(sessionId) {
3015
+ return safeOpenSession(sessionId, 'send-edit-revert')
3016
+ }
3017
+
2588
3018
  /**
2589
3019
  * 从一条**用户消息**分叉:复制到该条之前,并把该条原文放回新会话输入框。
2590
3020
  *
@@ -2605,13 +3035,119 @@ window.__ModuleLoader__.load({
2605
3035
  }
2606
3036
 
2607
3037
  // 成功反馈统一出口:devkit 标准 toast 优先,无 devkit 时对话框内文案兜底。
3038
+ /**
3039
+ * 带超时的 JSON 请求(PA-2):后端挂起/断网未收敛时,面板不能永久锁在 busy。
3040
+ * @param {string} url 请求地址
3041
+ * @param {object} init fetch 选项
3042
+ * @param {number} [timeoutMs] 超时(默认 15s)
3043
+ * @returns {Promise<Response>} fetch 响应
3044
+ */
3045
+ function fetchWithTimeout(url, init, timeoutMs, fetchImpl) {
3046
+ const limit = Number.isSafeInteger(timeoutMs) ? timeoutMs : 15000
3047
+ const doFetch = typeof fetchImpl === 'function' ? fetchImpl : fetch
3048
+ if (typeof AbortController !== 'function') return doFetch(url, init)
3049
+ const controller = new AbortController()
3050
+ const timer = setTimeout(() => controller.abort(), limit)
3051
+ return doFetch(url, Object.assign({}, init, { signal: controller.signal })).finally(() => clearTimeout(timer))
3052
+ }
3053
+
3054
+ /** 把超时/中止错误转成可读文案(其它错误原样交给 errText)。 */
3055
+ function timeoutText(reason, prefix) {
3056
+ if (reason && (reason.name === 'AbortError' || reason.code === 'ABORT_ERR')) return prefix + __t('panel.timeout')
3057
+ return errText(reason, prefix)
3058
+ }
3059
+
3060
+ /** 把焦点送回输入框:回撤/发送后那一行会被重建,焦点本来会掉到 body。 */
3061
+ function focusComposer() {
3062
+ try {
3063
+ // 0.33.12:只在**当前会话**的容器里找编辑器。全文档第一个
3064
+ // [contenteditable=true] 可能是隐藏的旧会话/别的编辑器。
3065
+ const sid = typeof __currentSessionId === 'string' ? __currentSessionId : ''
3066
+ const scope =
3067
+ (sid && document.querySelector('[data-session-id="' + sid.replace(/"/g, '') + '"]')) ||
3068
+ document.querySelector('[data-chat-flow]') ||
3069
+ document
3070
+ const ed = scope.querySelector('[contenteditable="true"]')
3071
+ if (ed && typeof ed.focus === 'function') ed.focus()
3072
+ } catch (e) {
3073
+ /* 焦点失败不影响主流程 */
3074
+ }
3075
+ }
3076
+
3077
+ const TOAST_HOST_ID = 'dsh-message-ops-toasts'
3078
+
3079
+ /** 自绘 toast 的样式(宿主 devkit 缺席时唯一的反馈通道)。 */
3080
+ function ensureToastStyle() {
3081
+ if (typeof document === 'undefined' || !document.head) return
3082
+ if (document.getElementById('dsh-message-ops-toast-style')) return
3083
+ const tag = document.createElement('style')
3084
+ tag.id = 'dsh-message-ops-toast-style'
3085
+ tag.textContent = [
3086
+ // 顶部右侧:避开输入框(底部)与居中正文;窄屏仍留 16px 边距。
3087
+ '#' + TOAST_HOST_ID + '{position:fixed;right:16px;top:calc(64px + env(safe-area-inset-top, 0px));display:flex;flex-direction:column;align-items:flex-end;gap:8px;z-index:2147483000;pointer-events:none}',
3088
+ '.mopsToast{max-width:min(560px,80vw);padding:8px 12px;border-radius:8px;font-size:13px;line-height:1.5;background:var(--dsw-alias-bg-layer-2,#2c2c2e);color:var(--dsw-alias-label-primary,#0f1115);border:1px solid var(--dsw-alias-border-l1,rgba(128,128,128,.25));box-shadow:0 4px 16px rgba(0,0,0,.18)}',
3089
+ '.mopsToast.warn{border-color:var(--dsw-alias-state-warning-primary,#c99a06)}',
3090
+ '.mopsToast.err{border-color:var(--dsw-alias-state-error-primary,#c63b32)}',
3091
+ '@media(prefers-reduced-motion:no-preference){.mopsToast{animation:mopsToastIn .16s ease-out}}',
3092
+ '@keyframes mopsToastIn{from{opacity:0;transform:translateY(4px)}to{opacity:1;transform:none}}',
3093
+ ].join('')
3094
+ document.head.appendChild(tag)
3095
+ }
3096
+
3097
+ /**
3098
+ * 宿主 devkit 缺席时的自绘 toast。
3099
+ *
3100
+ * 背景:本机 0.2.2-rc.5 的 `window.__dshDevkit` **是 undefined**(实测),
3101
+ * 于是 `notifyDone` 一直是空操作 —— 回滚成功、恢复失败、409 全都没有任何反馈。
3102
+ * 这里补一个最小实现:顶部右侧、3.5s 自动消失、最多 3 条、error 用 alert 播报。
3103
+ */
3104
+ function showFallbackToast(msg, kind) {
3105
+ try {
3106
+ if (typeof document === 'undefined' || !document.body) return
3107
+ ensureToastStyle()
3108
+ let host = document.getElementById(TOAST_HOST_ID)
3109
+ if (!host) {
3110
+ host = document.createElement('div')
3111
+ host.id = TOAST_HOST_ID
3112
+ host.setAttribute('aria-live', 'polite')
3113
+ document.body.appendChild(host)
3114
+ }
3115
+ const el = document.createElement('div')
3116
+ el.className = 'mopsToast' + (kind === 'error' ? ' err' : kind === 'warn' ? ' warn' : '')
3117
+ el.setAttribute('role', kind === 'error' ? 'alert' : 'status')
3118
+ el.textContent = msg
3119
+ host.appendChild(el)
3120
+ // 用 children[0] 而不是 firstChild:真实 DOM 两者等价,但测试/旧引擎里
3121
+ // firstChild 可能缺失(undefined 会让 removeChild 抛错,被 catch 后静默失效)。
3122
+ while (host.children.length > 3) {
3123
+ const oldest = host.children[0]
3124
+ if (!oldest) break
3125
+ host.removeChild(oldest)
3126
+ }
3127
+ setTimeout(() => {
3128
+ try {
3129
+ el.remove()
3130
+ } catch {
3131
+ /* 已移除 */
3132
+ }
3133
+ }, 4000)
3134
+ } catch (e) {
3135
+ console.warn('[message-ops] toast fallback failed:', e)
3136
+ }
3137
+ }
3138
+
2608
3139
  function notifyDone(msg, kind) {
3140
+ if (!msg) return
2609
3141
  try {
2610
3142
  const dk = window.__dshDevkit
2611
- if (dk && typeof dk.toast === 'function') dk.toast(msg, { kind: kind || 'ok' })
3143
+ if (dk && typeof dk.toast === 'function') {
3144
+ dk.toast(msg, { kind: kind || 'ok' })
3145
+ return
3146
+ }
2612
3147
  } catch {
2613
- /* toast 缺席不阻断成功反馈 */
3148
+ /* 宿主 toast 抛错 → 走自绘 */
2614
3149
  }
3150
+ showFallbackToast(msg, kind)
2615
3151
  }
2616
3152
 
2617
3153
  function OpsButton(props) {
@@ -2643,307 +3179,23 @@ window.__ModuleLoader__.load({
2643
3179
  )
2644
3180
  }
2645
3181
 
2646
- var IconQuote = null
2647
- try {
2648
- const P2 = require('@deepseek-ai/dsh-client-ui-primitives')
2649
- // 0.19.0:不再回退到 IconCopyOutlineRegular —— 宿主在 AI 消息下方本来就
2650
- // 有一个 Copy 按钮,用复制图标做「引用」会变成两个一模一样的复制按钮。
2651
- // 优先官方 chat 类图标;拿不到就用下面的引号几何(明确的引用语义)。
2652
- IconQuote = P2 && P2.IconChatOutlineRegular
2653
- } catch {
2654
- /* fallback below */
2655
- }
2656
- if (!IconQuote)
2657
- IconQuote = function QuoteFallback() {
2658
- return React.createElement(
2659
- 'svg',
2660
- { width: 16, height: 16, viewBox: '0 0 16 16', fill: 'none', 'aria-hidden': true, stroke: 'currentColor', strokeWidth: 1 },
2661
- React.createElement('path', {
2662
- d: 'M3 6.5A3.5 3.5 0 0 1 6.5 3H7v1.5h-.5A2 2 0 0 0 4.5 6.5V7H7v3.5H3V6.5ZM9 6.5A3.5 3.5 0 0 1 12.5 3H13v1.5h-.5A2 2 0 0 0 10.5 6.5V7H13v3.5H9V6.5Z',
2663
- }),
2664
- )
2665
- }
2666
-
2667
- // --- 0.3.0 assistant-actions 官方槽:每条 AI 消息旁的原生回撤按钮 ------------
3182
+ // --- 0.3.0 assistant-actions 官方槽:AI 消息动作区 -------------------------
2668
3183
  // 契约(dsh-cordis-client-runner):scope session,条目组件收 { messageId } +
2669
3184
  // 标准props(useSessions/sessionId/useSession/useChat…)。0.1.x 无此 key,
2670
3185
  // slots.inject 自动 no-op。
3186
+ //
3187
+ // 0.23.0 起本槽**不渲染任何按钮**(引用让位宿主、回撤按钮让位行内注入)。
3188
+ // 它留下的唯一职责 = 按会话捕获 inputActions(上面 ⚠️ 注释),必须保留注册。
2671
3189
  const CHAT_ACTIONS_SLOT = 'conversation.chat.assistant-actions'
2672
3190
  const CHAT_ACTIONS_ID = 'message-ops-row'
2673
3191
 
2674
3192
  function MsgSlotActions(props) {
2675
- const { messageId, sessionId, useSessions, inputActions, useChat } = props
2676
- const t = (props && props.t) || __t
2677
- useLocaleRevision()
3193
+ const { sessionId, inputActions } = props
2678
3194
  // 0.24.0 P4:按会话登记(本组件每条 AI 消息一个实例,必须带 sessionId 隔离)。
2679
3195
  React.useEffect(() => {
2680
3196
  rememberInputActions(sessionId, inputActions)
2681
3197
  return () => forgetInputActions(sessionId, inputActions)
2682
3198
  }, [sessionId, inputActions])
2683
- const sessions = useSessions ? useSessions(s => s) : undefined
2684
- const summary = sessions && sessions.byId ? sessions.byId[sessionId] : undefined
2685
- const running = summary ? summary.running === true : false
2686
- const [seq, setSeq] = React.useState(null)
2687
- const [fullText, setFullText] = React.useState(null)
2688
- const [busy, setBusy] = React.useState(null) // 'revert' | null(S11 双提交防护)
2689
- // 0.9.7(P4):索引被 dataSig 重建后要重跑解析,否则「新 AI 消息旁
2690
- // 没有回撤/引用按钮」—— 已经挂载的槽位 effect 不会因缓存被换而重跑。
2691
- const [idxRev, setIdxRev] = React.useState(0)
2692
- React.useEffect(() => {
2693
- const onIdx = () => setIdxRev(v => v + 1)
2694
- window.addEventListener(SEQ_INDEX_EVENT, onIdx)
2695
- return () => window.removeEventListener(SEQ_INDEX_EVENT, onIdx)
2696
- }, [])
2697
- React.useEffect(() => {
2698
- if (!messageId || !sessionId) return
2699
- let alive = true
2700
- let retried = false
2701
- const load = () => {
2702
- const p = fetchMessagesJson('/api/message-ops/messages?sessionId=' + encodeURIComponent(sessionId)).then(data => {
2703
- const index = new Map()
2704
- const full = new Map()
2705
- for (const m of (data && data.messages) || []) {
2706
- // 0.5.2(P2):同 id 取**最早** seq——与服务端 buildSeqIndex 口径一致
2707
- // (重试链取最早可见节点;此前内联 set 覆盖=取最大,双实现分裂)
2708
- if (m && m.id != null && !index.has(String(m.id))) index.set(String(m.id), m.seq)
2709
- if (m && m.id != null && m.fullText) full.set(String(m.id), m.fullText)
2710
- }
2711
- __seqIndexCache.set(sessionId, index)
2712
- __fullTextCache.set(sessionId, full)
2713
- return index
2714
- })
2715
- __seqIndexCache.set(sessionId, p)
2716
- // 0.5.2(P2):失败必须清缓存——否则 rejected promise 被永久缓存,
2717
- // 该会话按钮/dock 到刷新页面为止全部失效
2718
- // 0.9.7:只在缓存里还是**我们这条** promise 时才删(syncSeqIndex 可能已换掉)
2719
- p.catch(() => {
2720
- if (__seqIndexCache.get(sessionId) === p) __seqIndexCache.delete(sessionId)
2721
- })
2722
- return p
2723
- }
2724
- const resolve = index => {
2725
- if (!alive) return
2726
- const hit = index && index.get(String(messageId))
2727
- if (typeof hit === 'number') {
2728
- setSeq(hit)
2729
- return
2730
- }
2731
- // 0.9.7(P4):索引里没有这个 messageId = 会话已增长(或索引过期)。
2732
- // 旧实现这里**什么都不做**,`seq` 永远是 null → 组件 return null →
2733
- // 按钮再也不渲染。现在失效并重拉一次(retried 保证不自旋);
2734
- // 复用 fetchMessagesJson 的 1s 合并窗口,连续上新不会打爆请求。
2735
- if (retried) return
2736
- retried = true
2737
- __seqIndexCache.delete(sessionId)
2738
- __fullTextCache.delete(sessionId)
2739
- load()
2740
- .then(resolve)
2741
- .catch(() => {})
2742
- }
2743
- const cached = __seqIndexCache.get(sessionId)
2744
- if (cached && typeof cached.then === 'function') cached.then(resolve).catch(() => {})
2745
- else if (cached) resolve(cached)
2746
- else
2747
- load()
2748
- .then(resolve)
2749
- .catch(() => {})
2750
- return () => {
2751
- alive = false
2752
- }
2753
- }, [messageId, sessionId, idxRev])
2754
-
2755
- // 原文(引用用):seq 解析后按需取全文
2756
- React.useEffect(() => {
2757
- if (seq == null || !sessionId) return
2758
- let alive = true
2759
- const cached = __fullTextCache.get(sessionId)
2760
- const resolve = full => {
2761
- if (!alive) return
2762
- const hit = full && full.get(String(messageId))
2763
- if (typeof hit === 'string') setFullText(hit)
2764
- }
2765
- if (cached && typeof cached.then === 'function') cached.then(resolve).catch(() => {})
2766
- else if (cached) resolve(cached)
2767
- return () => {
2768
- alive = false
2769
- }
2770
- }, [seq, messageId, sessionId])
2771
-
2772
- // 0.5.0 回撤后的视图刷新:openSession(reveal) 重建会话视图 → 遮蔽立即呈现。
2773
- // (宿主 live 投影只处理 compaction 类 replace,插件标记需要视图重建才可见。)
2774
- const revealSession = () => {
2775
- try {
2776
- if (__uiWorkspace && typeof __uiWorkspace.openSession === 'function') {
2777
- __uiWorkspace.openSession(sessionId)
2778
- return true
2779
- }
2780
- } catch {
2781
- /* fallthrough */
2782
- }
2783
- return false
2784
- }
2785
-
2786
- // ── 0.18.0:引用改用官方 insertQuote(结构化 QuoteNode)──────────────────
2787
- //
2788
- // 旧实现(0.5.0)用 `captureInsertion` + `insertText` 手工拼 `> ` markdown:
2789
- //
2790
- // text.split('\n').map(l => '> ' + l).join('\n') + '\n\n'
2791
- //
2792
- // 问题(用户实测反馈「这 UI 做的怎么这么诡异」):
2793
- // 1. **不是引用**,是一段普通 markdown 文本 —— 宿主不会渲染成引用块,
2794
- // 也不会给删除按钮、不进结构化编辑语义;
2795
- // 2. `captureInsertion` 返回的是**插入位置快照**,用户在菜单里点完到
2796
- // 文本到达之间若改过草稿,位置就失效,文本会插到奇怪的地方;
2797
- // 3. 手工拼的 `> ` 会和用户已有内容粘连(无空行分隔时)。
2798
- //
2799
- // 宿主其实提供了官方能力(dsh-client-ui-conversation:15369):
2800
- // insertQuote: (text) => this.insertQuote(text)
2801
- // 它内部走 `draftEditor.insertQuote(text, labels)` →
2802
- // `$replaceDetectSpanWithNodes([$createQuoteNode(text, labels), Go(" ")])`
2803
- // 即:在当前光标处插入一个**真正的 QuoteNode**(带 remove 标签、独立 undo),
2804
- // 并自动补一个空格分隔。这才是"规范"的引用。
2805
- /**
2806
- * 0.19.0 引用:只引用「选中的一小段」,不再把整条 AI 消息塞进 composer。
2807
- *
2808
- * 用户原话:「这个引用为什么是直接把这个消息直接给我填进输入框,这什么情况?」
2809
- * 根因:旧实现把 fullText / /text 接口返回的**整条全文**传给 insertQuote,
2810
- * 于是 composer 里冒出一个几千字的巨大引用块,看起来就像"把消息整个塞进去"。
2811
- *
2812
- * 宿主官方 insertQuote 的语义是「引用一段选中文字」(QuoteNode +
2813
- * QuotePreview 可视化 + 模型可见的 markdown blockquote),本就该用小段。
2814
- *
2815
- * 文本来源优先级:
2816
- * 1. 用户在该消息内选中的文字(window.getSelection,限定消息节点内)
2817
- * 2. 无选中 → 取整条但截断到 QUOTE_MAX_CHARS,并标注来源(seq / 角色)
2818
- */
2819
- const QUOTE_MAX_CHARS = 600
2820
- // 0.20.0(bug-hunt M-1):按 Unicode code point 截断,且尽量在换行/空格处收尾,
2821
- // 避免把 emoji(代理对)或 markdown 围栏 ``` 从中间切坏。
2822
- // 0.22.0(真执行实测):按 code point 切会拆散 grapheme cluster。
2823
- // 实测 'a'.repeat(598) + '👨‍👩‍👧‍👦' → 尾部 U+1f468 U+200d U+2026,
2824
- // 家庭 emoji 被切成单人 + 悬空 ZWJ。改用 Intl.Segmenter 按 grapheme 切。
2825
- let quoteSegmenter = null
2826
- const graphemes = raw => {
2827
- if (typeof Intl !== 'undefined' && Intl.Segmenter) {
2828
- quoteSegmenter ||= new Intl.Segmenter('zh', { granularity: 'grapheme' })
2829
- return Array.from(quoteSegmenter.segment(String(raw)), part => part.segment)
2830
- }
2831
- return Array.from(String(raw))
2832
- }
2833
- const clipQuote = raw => {
2834
- const chars = graphemes(raw)
2835
- if (chars.length <= QUOTE_MAX_CHARS) return chars.join('')
2836
- let end = QUOTE_MAX_CHARS
2837
- // 往前找最近的空白/换行边界(最多回退 40 个 grapheme),不破坏单词;
2838
- // 找不到就硬切(此时至少不会拆散单个 grapheme)
2839
- for (let i = end; i > Math.max(0, end - 40); i--) {
2840
- if (/[\s\n]/.test(chars[i - 1])) {
2841
- end = i
2842
- break
2843
- }
2844
- }
2845
- return chars.slice(0, end).join('') + '…'
2846
- }
2847
- // 0.20.0(bug-hunt H-2):把「选区归属」收紧,避免静默串味。
2848
- // 旧实现算出 root 却从未使用,且用宽松的 [data-chat-flow-kind] 兜底
2849
- // (会命中 turn-tail / tool / system 等通用块),只看 anchorNode,
2850
- // 导致「选中 A 消息的一段、去点 B 消息的引用」会把 A 的文字当成 B 引用。
2851
- // 现在要求 anchor 与 focus 落在**同一个** data-chat-node-key 容器内,
2852
- // 且该容器必须存在;不满足就返回 null,回退到「截断+标注来源」路径。
2853
- const ownerOf = node => {
2854
- const el = node && (node.nodeType === 1 ? node : node.parentElement)
2855
- return el && el.closest ? el.closest('[data-chat-node-key]') : null
2856
- }
2857
- const selectionInMessage = () => {
2858
- try {
2859
- const sel = window.getSelection && window.getSelection()
2860
- if (!sel || sel.isCollapsed || sel.rangeCount === 0) return null
2861
- const text = String(sel.toString() || '').replace(/\s+$/g, '')
2862
- if (!text || text.length > QUOTE_MAX_CHARS * 2) return null
2863
- const anchorOwner = ownerOf(sel.anchorNode)
2864
- const focusOwner = ownerOf(sel.focusNode)
2865
- // 两端必须属于同一个精确的 chat node;跨消息选区不引用(防串味)
2866
- if (!anchorOwner || !focusOwner || anchorOwner !== focusOwner) return null
2867
- return clipQuote(text)
2868
- } catch {
2869
- return null
2870
- }
2871
- }
2872
- const runQuote = () => {
2873
- // 0.20.0(bug-hunt M-2):来源标注放在 toast,不塞进 QuoteNode 正文。
2874
- // QuoteNode.getTextContent() 是「模型可见文本」,正文里混入
2875
- // '[引用自 seq N]' 会污染送进模型的引用内容。
2876
- const finish = (ok, source) =>
2877
- notifyDone(
2878
- ok ? (source ? t('quote.doneWithSource', { seq: String(source) }) : t('quote.done')) : t('quote.unavailable'),
2879
- ok ? 'ok' : 'warn',
2880
- )
2881
- try {
2882
- if (!inputActions || typeof inputActions.insertQuote !== 'function') {
2883
- finish(false)
2884
- return
2885
- }
2886
- const put = (text, source) => {
2887
- if (typeof text !== 'string' || text.trim() === '') {
2888
- finish(false)
2889
- return
2890
- }
2891
- let ok = false
2892
- try {
2893
- ok = inputActions.insertQuote(text.replace(/\r\n?/g, '\n')) !== false
2894
- } catch (e) {
2895
- console.warn('[message-ops] insertQuote failed:', e)
2896
- ok = false
2897
- }
2898
- finish(ok, ok ? source : null)
2899
- }
2900
- // ① 选中片段优先:正文就是选中的文字,无需来源标注
2901
- const selected = selectionInMessage()
2902
- if (selected != null) {
2903
- put(selected, null)
2904
- return
2905
- }
2906
- // ② 无选中:取整条但截断;来源只通过 toast 告知,不进引用正文
2907
- if (fullText != null && fullText !== '') {
2908
- put(clipQuote(fullText), seq)
2909
- return
2910
- }
2911
- fetch('/api/message-ops/text?sessionId=' + encodeURIComponent(sessionId) + '&seq=' + encodeURIComponent(seq))
2912
- .then(r => (r.ok ? r.json() : null))
2913
- .then(d => put(d && d.ok && typeof d.text === 'string' ? clipQuote(d.text) : null, seq))
2914
- .catch(() => put(null))
2915
- } catch (e) {
2916
- notifyDone(t('errorPrefix') + (e && e.message ? e.message : String(e)), 'error')
2917
- }
2918
- }
2919
-
2920
- if (seq == null) return null
2921
- const act = (icon, label, mode, onClick, disabled) =>
2922
- React.createElement(
2923
- 'button',
2924
- {
2925
- type: 'button',
2926
- title: running && mode === 'revert' ? t('dialog.runningWarn') : label,
2927
- 'aria-label': label,
2928
- disabled: !!disabled,
2929
- style: {
2930
- display: 'inline-flex',
2931
- alignItems: 'center',
2932
- justifyContent: 'center',
2933
- minWidth: 44,
2934
- minHeight: 44,
2935
- padding: 0,
2936
- border: 'none',
2937
- background: 'transparent',
2938
- color: 'inherit',
2939
- opacity: busy && busy !== mode ? 0.4 : running && mode === 'revert' ? 0.35 : 0.72,
2940
- cursor: disabled ? 'default' : 'pointer',
2941
- borderRadius: 6,
2942
- },
2943
- onClick,
2944
- },
2945
- icon,
2946
- )
2947
3199
  // 0.23.0:AI 消息动作区**不再注入任何按钮**。
2948
3200
  //
2949
3201
  // 用户反馈:「引用不要每次把一整个上下文重新全部塞给 AI」。核查结论:
@@ -2957,6 +3209,8 @@ window.__ModuleLoader__.load({
2957
3209
  // · 而 deriveMessages() 本就遍历 surface.nodes 给出完整历史,
2958
3210
  // 引用当前会话里未被遮蔽的消息 = 同一内容在 prompt 里出现两遍,纯冗余。
2959
3211
  // 所以正确做法是让位给宿主,不再重复造轮子。
3212
+ // 引用机械(IconQuote / clipQuote / runQuote / selectionInMessage / 选区归属判定)
3213
+ // 与配套的 fullText / seq 解析已随之删除;不得再在本槽重建(docs/DECISIONS.md D-4)。
2960
3214
  //
2961
3215
  // ⚠️ 本组件**必须保留**:它负责按会话捕获 inputActions 到
2962
3216
  // __inputActionsBySession(编辑框 / 面板 / 行内回填都依赖),
@@ -2966,6 +3220,126 @@ window.__ModuleLoader__.load({
2966
3220
 
2967
3221
  // 0.4.2 引入(恢复的标记自动离开活跃列表 = opencode clear 语义)。
2968
3222
  // 0.5.0 脚本化编辑曾误删本函数 → dock 100% 静默失效(P0,0.5.2 恢复)。
3223
+ /**
3224
+ * 该 marker 是否仍应出现在恢复列表里。
3225
+ *
3226
+ * 0.27.0:必须判 `shadowed` —— 被后续回撤遮蔽的 marker 已被取代,恢复它等于
3227
+ * 绕过后来那次回撤。真机复现:回撤到第二条 → 再回撤到第一条后,dock 仍列出
3228
+ * 第一条回撤的待恢复轮;点恢复把已经回撤掉的第二、三条重新放回会话末尾。
3229
+ */
3230
+ function isActiveMarker(m) {
3231
+ return (
3232
+ !!m &&
3233
+ m.marker === true &&
3234
+ m.sourceKind !== 'compact-checkpoint' &&
3235
+ m.restoreComplete !== true &&
3236
+ m.committed !== true &&
3237
+ // 服务端按「被后续回撤的遮蔽集覆盖」算出:只覆盖 marker 自己的自噬记录不算
3238
+ m.superseded !== true
3239
+ )
3240
+ }
3241
+
3242
+ /**
3243
+
3244
+ // ══ 70-revert · 回撤目标选择 + 恢复贴条(dock) ══
3245
+ * 一行是否可作为回撤目标:当前 surface 上、未被遮蔽的**真实用户输入**。
3246
+ *
3247
+ * 不能只判 visible:回撤落盘后最后一条可见节点是 marker 自己(system/message),
3248
+ * 注入行(runtime-context / tool-jobs …)也带 role:'user'。旧实现拿它们去 POST,
3249
+ * 前者 409「is a revert/delete marker」,后者会把注入行当对话回撤。
3250
+ */
3251
+ function isRevertTarget(row) {
3252
+ return (
3253
+ !!row &&
3254
+ row.seq != null &&
3255
+ row.visible === true &&
3256
+ row.shadowed !== true &&
3257
+ row.role === 'user' &&
3258
+ row.sourceKind === 'user' &&
3259
+ // 0.33.0:宿主自己做 user 消息 rewind 时会写 user/message + replace 且
3260
+ // content 为空;它不是可回撤的“我发的消息”(原先会被 /undo 选中并回撤)。
3261
+ row.marker !== true &&
3262
+ String(row.fullText ?? '').trim() !== ''
3263
+ )
3264
+ }
3265
+
3266
+ /**
3267
+ * `/messages` 响应 → 回撤目标 / 回填用的行表。
3268
+ *
3269
+ * 0.28.0:判据以服务端 `sourceKind` 为准(`kind !== 'user'` 一律不是"我发的消息")。
3270
+ * 旧实现只靠一条文本正则挡注入行,覆盖不到的形态会漏进来;更糟的是行表里
3271
+ * **根本没有 sourceKind 字段**,而 0.27 的 `pickRevertTarget` 要求它等于 'user'
3272
+ * —— 于是 /undo 在生产里永远选不到目标(单元测试用的是手造行,假绿)。
3273
+ *
3274
+ * @param {object} payload GET /api/message-ops/messages 的响应
3275
+ * @returns {Array<object>} 按 seq 升序的用户消息行(含 sourceKind / fullText)
3276
+ */
3277
+ function revertRowsOf(payload) {
3278
+ const norm = x => String(x || '').replace(/\s+/g, '')
3279
+ // 兜底正则只服务「没有 sourceKind 的旧载荷」;有字段就按字段判。
3280
+ const injected = raw =>
3281
+ /^<system-reminder|current\s+runtime\s+context|^<system-Reminder|^background job\s+[\w-]+|^Background subagent\s+[0-9a-f]{8}-|^Agent\s+[0-9a-f]{8}-|^\[model changed:/i.test(
3282
+ String(raw || ''),
3283
+ )
3284
+ return ((payload && payload.messages) || [])
3285
+ .filter(m => m && m.role === 'user')
3286
+ .map(m => ({
3287
+ seq: m.seq,
3288
+ role: 'user',
3289
+ sourceKind: m.sourceKind == null ? null : String(m.sourceKind),
3290
+ sn: norm(m.snippet),
3291
+ raw: String(m.snippet == null ? '' : m.snippet),
3292
+ fullText: m.fullText ?? null,
3293
+ visible: m.visible !== false,
3294
+ shadowed: m.shadowed === true,
3295
+ turnStartSeq: m.turnStartSeq ?? null,
3296
+ }))
3297
+ .filter(r => r.sn && (r.sourceKind === null ? !injected(r.raw) : r.sourceKind === 'user'))
3298
+ .sort((a, b) => a.seq - b.seq)
3299
+ }
3300
+
3301
+ /** 从尾往头找最后一条可回撤的用户消息;没有返回 null。 */
3302
+ function pickRevertTarget(rows) {
3303
+ if (!Array.isArray(rows)) return null
3304
+ for (let i = rows.length - 1; i >= 0; i--) if (isRevertTarget(rows[i])) return rows[i]
3305
+ return null
3306
+ }
3307
+
3308
+ /** dock 行标签:优先本轮 upTo("恢复到哪"),整段行(无 upTo)才退回 marker seq。 */
3309
+ function dockRowLabel(row) {
3310
+ // 区间行(无待恢复轮):前缀用被遮蔽区间,而不是 marker 自己的 seq ——
3311
+ // 后者会显示成「#3410 · seq 3400..3410」,用户会以为 #3410 是被回撤的消息。
3312
+ if (row && row.rangeStart != null) {
3313
+ return row.rangeEnd != null && row.rangeEnd !== row.rangeStart ? 'seq ' + row.rangeStart + '..' + row.rangeEnd : 'seq ' + row.rangeStart
3314
+ }
3315
+ const at = row && row.upTo != null ? row.upTo : row && row.seq
3316
+ return '#' + at
3317
+ }
3318
+
3319
+ /**
3320
+ * 折叠态预览:第一条待恢复轮的**纯内容**(不带行内的「(+n)」计数后缀)。
3321
+ * @param {Array<{preview?:string,snippet?:string}>} rows dockRows
3322
+ * @returns {string} 预览文本
3323
+ */
3324
+ function dockPreviewOf(rows) {
3325
+ if (!Array.isArray(rows) || rows.length === 0) return ''
3326
+ const first = rows[0]
3327
+ return (first && (first.preview || first.snippet)) || ''
3328
+ }
3329
+
3330
+ /**
3331
+ * dock 行文案:`#13 · 第二条…`。
3332
+ *
3333
+ * 无文本可预览时服务端给的是 `'#' + turnSeq` —— 旧实现再拼一次前缀,出现
3334
+ * 「#35 · #35」这种既重复又无信息的行(真机实测)。同值只显示一次。
3335
+ */
3336
+ function dockRowText(row) {
3337
+ const label = dockRowLabel(row)
3338
+ const snippet = row && row.snippet ? String(row.snippet) : ''
3339
+ if (snippet === '' || snippet === label) return label
3340
+ return label + ' · ' + snippet
3341
+ }
3342
+
2969
3343
  function activeMarkers(msgs) {
2970
3344
  // 0.8.0:活跃判定收敛到服务端权威字段 restoreComplete
2971
3345
  // (按 restoredSourceSeqs 进度算;旧 notice 无该字段 → 服务端视为整段已恢复)。
@@ -2976,9 +3350,11 @@ window.__ModuleLoader__.load({
2976
3350
  // SessionRevert.commit() → revert:null → affordance 消失)。
2977
3351
  // 我们是 append-only,marker 不会真消失,所以由服务端按
2978
3352
  // 「marker 之后有无 source.kind==='user' 的真实输入」算出 committed。
3353
+ // 0.27.0:再加 `shadowed` 闸(见 isActiveMarker 注释)—— 被后续回撤遮蔽的
3354
+ // marker 已失效,恢复它就是绕过那次回撤。
2979
3355
  return (
2980
3356
  (msgs || [])
2981
- .filter(m => m.marker && m.sourceKind !== 'compact-checkpoint' && m.restoreComplete !== true && m.committed !== true)
3357
+ .filter(isActiveMarker)
2982
3358
  // 0.14.0:排掉「自噬 marker」—— 它的 replace 区间恰好覆盖**另一条 marker**
2983
3359
  // (典型是 `startSeq === endSeq === 前一条 marker 的 seq`,content 为空)。
2984
3360
  // 这种记录不是用户做过的回滚,是旧版 dock 拿 marker 当目标留下的残迹;
@@ -3016,6 +3392,9 @@ window.__ModuleLoader__.load({
3016
3392
  return { reload: true, baseline: next }
3017
3393
  }
3018
3394
 
3395
+ // 贴条展开列表的 id:chevron 的 aria-controls 指向它。
3396
+ const LIST_ID = 'dsh-message-ops-revert-list'
3397
+
3019
3398
  function RevertDock(props) {
3020
3399
  const { sessionId, useSessions, inputActions } = props
3021
3400
  if (sessionId) __currentSessionId = sessionId
@@ -3038,14 +3417,33 @@ window.__ModuleLoader__.load({
3038
3417
  // setMarkers 会把已正确的 markers 覆盖回去 → dock 重新出现。
3039
3418
  // 0.10.4 的 350/1400ms 延迟事实上起到了串行化作用,删除后重叠概率上升。
3040
3419
  const reqSeqRef = useRef(0)
3420
+ const announcedSidRef = useRef(null)
3421
+ // 0.33.3(ui-live P2-5):会话已被删除时不要在坏 id 上反复重拉(实测 80s 9 次 404)。
3422
+ const goneRef = useRef(null)
3041
3423
  const sessRef = useRef(sessionId) // 真正的「切了会话」判据(R1 回归修复)
3042
3424
  const landedSeqRef = useRef(0) // 已成功落地的最大请求序号(R2:失败不回滚)
3043
3425
  const [open, setOpen] = useState(false)
3044
3426
  const [markers, setMarkers] = useState(null) // 活跃回撤标记(已恢复的自动消失)
3045
3427
  const [shadowCount, setShadowCount] = useState(0) // 标记 range 内被遮蔽消息数(标题口径)
3046
3428
  const [restoring, setRestoring] = useState(null)
3429
+ const [confirmDiscard, setConfirmDiscard] = useState(false)
3430
+ const [note, setNote] = useState('')
3047
3431
  const [styleInjected, setStyleInjected] = useState(false)
3048
3432
 
3433
+ // 0.33.3:把会话切换广播出去。面板是独立 slot(拿不到 sessionId),没有这个
3434
+ // 信号就会一直展示旧会话的列表并对其执行写操作。必须放在 ref 声明之后的
3435
+ // effect 里 —— 写在 render 顶部会在 `announcedSidRef` 初始化前访问它(TDZ)。
3436
+ useEffect(() => {
3437
+ if (!sessionId || typeof window === 'undefined') return
3438
+ if (announcedSidRef.current === sessionId) return
3439
+ announcedSidRef.current = sessionId
3440
+ try {
3441
+ window.dispatchEvent(new CustomEvent(SESSION_EVENT, { detail: { sessionId } }))
3442
+ } catch {
3443
+ /* CustomEvent 不可用(旧宿主/测试桩)时静默 */
3444
+ }
3445
+ }, [sessionId])
3446
+
3049
3447
  // opencode SessionRevertDock 视觉(v2 布局,DSH 令牌等价映射)
3050
3448
  useEffect(() => {
3051
3449
  if (styleInjected || typeof document === 'undefined') return
@@ -3060,31 +3458,51 @@ window.__ModuleLoader__.load({
3060
3458
  // 0.6.0 贴条(对齐 opencode):宽度锁到输入卡片同源变量(uV2eYG_card 同款
3061
3459
  // max-width),居中;margin-bottom:-5px 把 composerStack 的6px gap 压成
3062
3460
  // **1px 视觉贴合**(实测基线 gap14→目标1)。
3063
- '.mopsRd{width:100%;max-width:var(--dsh-composer-card-max-width);margin-inline:auto;margin-bottom:-5px;overflow:hidden;border-radius:var(--dsw-radius-md,12px);border:.5px solid var(--dsw-alias-border-l1,rgba(128,128,128,.25));background:var(--dsw-alias-bg-layer-1,#1e1e20)}',
3461
+ '.mopsRd{width:100%;max-width:var(--dsh-composer-card-max-width);margin-inline:auto;margin-bottom:calc(1px - var(--dsh-composer-stack-gap,6px));overflow:hidden;border-radius:var(--dsw-radius-md,12px);border:.5px solid var(--dsw-alias-border-l1,rgba(128,128,128,.25));background:var(--dsw-alias-bg-layer-1,#1e1e20)}',
3064
3462
  // 头部 42px:图标 + label + 折叠预览 + 旋转 chevron
3065
- '.mopsRdHead{display:flex;height:40px;align-items:center;gap:8px;padding-left:16px;padding-right:8px;cursor:pointer;user-select:none}',
3463
+ '.mopsRdHead{display:flex;width:100%;height:40px;align-items:center;gap:8px;padding:0 8px 0 16px;cursor:pointer;user-select:none;font:inherit;text-align:left;color:inherit;background:none;border:0;border-radius:0}',
3066
3464
  '.mopsRdIcon{display:inline-flex;color:var(--dsw-alias-label-tertiary,#9a9aa0);flex:none}',
3067
- '.mopsRdLabel{font-size:13px;font-weight:500;line-height:20px;letter-spacing:-.04px;flex:none;cursor:default;color:var(--dsw-alias-label-primary,inherit)}',
3465
+ '.mopsRdLabel{font-size:13px;font-weight:500;line-height:20px;letter-spacing:-.04px;flex:none;cursor:pointer;color:var(--dsw-alias-label-primary,inherit)}',
3068
3466
  '.mopsRdLabelCollapsed{color:var(--dsw-alias-label-secondary,#a8a8ae)}',
3069
- '.mopsRdPreview{min-width:0;flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:13px;font-weight:400;line-height:20px;letter-spacing:-.04px;cursor:default;color:var(--dsw-alias-label-tertiary,#9a9aa0)}',
3070
- '.mopsRdChevron{margin-left:auto;flex:none;display:inline-flex;align-items:center;justify-content:center;width:28px;height:28px;border:none;border-radius:999px;background:transparent;color:var(--dsw-alias-label-tertiary,#9a9aa0);cursor:pointer;transition:transform .15s ease}',
3467
+ '.mopsRdPreview{min-width:0;flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:13px;font-weight:400;line-height:20px;letter-spacing:-.04px;cursor:pointer;color:var(--dsw-alias-label-tertiary,#9a9aa0)}',
3468
+ '.mopsRdChevronWrap{margin-left:auto;flex:none;display:inline-flex;align-items:center}',
3469
+ '.mopsRdChevron{display:inline-flex;align-items:center;justify-content:center;width:28px;height:28px;color:var(--dsw-alias-label-tertiary,#9a9aa0)}',
3470
+ '.mopsRdNote{padding:2px 16px 8px;font-size:12px;line-height:1.5;color:var(--dsw-alias-label-secondary,#a8a8ae)}',
3071
3471
  // 列表:24px 行 + neutral 小按钮(非文字链)
3072
3472
  '.mopsRdList{display:flex;flex-direction:column;gap:8px;max-height:168px;overflow-y:auto;padding:1px 16px 12px}',
3073
3473
  '.mopsRdRow{display:flex;height:24px;min-width:0;align-items:center;gap:8px}',
3074
3474
  '.mopsRdRowText{min-width:0;flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:13px;font-weight:400;line-height:20px;letter-spacing:-.04px;color:var(--dsw-alias-label-secondary,#a8a8ae)}',
3075
3475
  '.mopsRdRestore{flex:none;font:inherit;font-size:12px;line-height:18px;padding:2px 10px;border-radius:6px;cursor:pointer;color:var(--dsw-alias-label-primary,inherit);background:var(--dsw-alias-interactive-bg-hover,rgba(128,128,128,.12));border:1px solid var(--dsw-alias-border-l1,rgba(128,128,128,.2));opacity:1}',
3076
3476
  '.mopsRdRestore:disabled{opacity:.45;cursor:default}',
3477
+ // 底部「放弃恢复(丢弃)」:quiet 文字链 + 二次确认条;危险动作用 error 色
3478
+ '.mopsRdFoot{padding:0 16px 10px;display:flex;flex-direction:column;gap:6px}',
3479
+ '.mopsRdDiscardLink{align-self:flex-start;font:inherit;font-size:12px;line-height:18px;padding:0;border:0;background:none;cursor:pointer;color:var(--dsw-alias-label-tertiary,#9a9aa0);text-decoration:underline;text-underline-offset:2px}',
3480
+ '.mopsRdDiscardLink:hover{color:var(--dsw-alias-label-secondary,#a8a8ae)}',
3481
+ '.mopsRdDiscardLink:disabled{opacity:.45;cursor:default;text-decoration:none}',
3482
+ '.mopsRdConfirm{display:flex;align-items:center;gap:8px;flex-wrap:wrap;padding:8px;border-radius:8px;background:var(--dsw-alias-bg-layer-2,rgba(128,128,128,.08))}',
3483
+ '.mopsRdConfirmText{flex:1;min-width:140px;font-size:12px;line-height:1.5;color:var(--dsw-alias-label-primary,inherit)}',
3484
+ '.mopsRdDanger{flex:none;font:inherit;font-size:12px;line-height:18px;padding:2px 10px;border-radius:6px;cursor:pointer;color:#fff;background:var(--dsw-alias-state-error-primary,#c63b32);border:1px solid transparent}',
3485
+ '.mopsRdDanger:disabled{opacity:.5;cursor:default}',
3486
+ '.mopsRdCancel{flex:none;font:inherit;font-size:12px;line-height:18px;padding:2px 10px;border-radius:6px;cursor:pointer;color:var(--dsw-alias-label-secondary,#a8a8ae);background:none;border:1px solid var(--dsw-alias-border-l1,rgba(128,128,128,.2))}',
3077
3487
  ].join('')
3078
3488
  document.head.appendChild(tag)
3079
3489
  setStyleInjected(true)
3080
3490
  }, [styleInjected])
3081
3491
 
3082
3492
  useEffect(() => {
3083
- syncSyntheticTurnStyle([])
3084
3493
  let alive = true
3494
+ // F3:切会话先清空上一个会话的贴条状态 —— 否则新会话在首拉返回前
3495
+ // 会显示旧会话的回撤行,点了会用「新会话 id + 旧 seq」真的落盘。
3496
+ goneRef.current = null
3497
+ setMarkers(null)
3498
+ setShadowCount(0)
3499
+ setRestoring(null)
3500
+ setNote('')
3501
+ setOpen(false)
3085
3502
  const onChange = () => load()
3086
3503
  window.addEventListener(CHANGED_EVENT, onChange)
3087
3504
  const load = () => {
3505
+ if (goneRef.current === sessionId) return Promise.resolve()
3088
3506
  const reqSeq = ++reqSeqRef.current // 发起序号(防慢响应覆盖快响应)
3089
3507
  // R1(复审实测):fetchMessagesJson 有 MSG_COALESCE_MS=1000 共用窗——
3090
3508
  // 既有 scan 观察器在 T+200ms 已取到**落盘批窗(200ms)之前**的旧响应,
@@ -3099,10 +3517,10 @@ window.__ModuleLoader__.load({
3099
3517
  // 对非 2xx / ok!==true 会 throw,被下面 catch 吞掉),它的序号已被占用,
3100
3518
  // 先发那次**成功的**好响应就会被这里丢弃 → markers 停在旧值且无重试。
3101
3519
  // 故另记一个「已落地序号」,失败不回滚它。
3102
- if (reqSeq !== reqSeqRef.current || reqSeq <= landedSeqRef.current) return
3520
+ if (reqSeq <= landedSeqRef.current) return
3103
3521
  landedSeqRef.current = reqSeq
3104
3522
  const msgs = data.messages || []
3105
- syncSyntheticTurnStyle(msgs)
3523
+ syncSyntheticTurnStyle(msgs, sessionId)
3106
3524
  const act = activeMarkers(msgs)
3107
3525
  setMarkers(act)
3108
3526
  // 0.5.2(P2):标题口径 = 标记 range 内 visible=false 的去重 seq 数
@@ -3120,7 +3538,16 @@ window.__ModuleLoader__.load({
3120
3538
  }
3121
3539
  setShadowCount(seen.size)
3122
3540
  })
3123
- .catch(() => {})
3541
+ .catch(reason => {
3542
+ // 0.39.1:判据可以用 `reason.status` 了(0.38.0 起 opsError 会挂 status)。
3543
+ // 真实服务端 404 的文案是 `session log not found`(不含「404」),只按文案
3544
+ // 匹配会让闸门恒 false → 会话被删/移走后每次 CHANGED/activity 都重打一次
3545
+ // 404(0.33.3 注释里「80s 9 次 404」要堵的就是这个口子)。
3546
+ const status = reason && reason.status
3547
+ if (status === 404 || /404/.test(String((reason && reason.message) || reason))) {
3548
+ goneRef.current = sessionId
3549
+ }
3550
+ })
3124
3551
  }
3125
3552
 
3126
3553
  // F1(复审后重做):宿主在 user/message(source.kind==='user') 时会
@@ -3140,8 +3567,7 @@ window.__ModuleLoader__.load({
3140
3567
  return () => {
3141
3568
  alive = false
3142
3569
  loadRef.current = () => {}
3143
- syncSyntheticTurnStyle([])
3144
- window.removeEventListener(CHANGED_EVENT, onChange)
3570
+ window.removeEventListener(CHANGED_EVENT, onChange)
3145
3571
  }
3146
3572
  }, [sessionId])
3147
3573
 
@@ -3186,6 +3612,13 @@ window.__ModuleLoader__.load({
3186
3612
  if (step.reload) loadRef.current()
3187
3613
  }, [sessionId, activityAt])
3188
3614
 
3615
+ // 行内反馈 4s 后淡出(toast 只是增强,宿主没提供 devkit 时这里是唯一反馈)
3616
+ useEffect(() => {
3617
+ if (!note) return undefined
3618
+ const timer = setTimeout(() => setNote(''), 4000)
3619
+ return () => clearTimeout(timer)
3620
+ }, [note])
3621
+
3189
3622
  // 0.19.0(spec §3.4):去掉「markers 变化就自动折叠」。
3190
3623
  // 用户反馈:点开 dock 后一操作就被收回去,很烦。折叠状态只由用户
3191
3624
  // 点击 header / chevron 改变;恢复=重放的语义与文案保持不变。
@@ -3193,12 +3626,63 @@ window.__ModuleLoader__.load({
3193
3626
  // 不再写 setOpen(false),Hooks 顺序不受影响(下方无其它 Hook 依赖它)。
3194
3627
  if (!markers || !markers.length) return null
3195
3628
 
3629
+ // 0.39.0:丢弃(discard)——服务端早已支持「只停用标记、不重放」,但 UI 只有
3630
+ // 「恢复」。用户在「这段对话我不想要了、也不想它回到会话末尾」时无处可去
3631
+ // (只能留着贴条)。语义对应 opencode 的 revert.commit:放弃回撤内容。
3632
+ const discardAll = () => {
3633
+ if (restoring != null || running) return
3634
+ const targets = [...new Set((markers || []).map(m => m.seq))]
3635
+ if (!targets.length) return
3636
+ setConfirmDiscard(false)
3637
+ setRestoring('discard')
3638
+ setNote('')
3639
+ const doneText = t('dock.discardDone')
3640
+ Promise.resolve()
3641
+ .then(async () => {
3642
+ for (const seq of targets) {
3643
+ const res = await fetchWithTimeout('/api/message-ops/restore', {
3644
+ method: 'POST',
3645
+ headers: { 'content-type': 'application/json' },
3646
+ body: JSON.stringify({ sessionId, seq, discard: true }),
3647
+ })
3648
+ const r = await readOpsJson(res)
3649
+ if (!r.ok) throw opsError(r.status, r.data)
3650
+ }
3651
+ return targets.length
3652
+ })
3653
+ .then(() => {
3654
+ notifyDone(doneText)
3655
+ setNote(doneText)
3656
+ setMarkers([])
3657
+ setShadowCount(0)
3658
+ setOpen(false)
3659
+ emitChanged()
3660
+ if (__refreshSurface) __refreshSurface(sessionId)
3661
+ })
3662
+ .catch(reason => {
3663
+ const status = reason && reason.status
3664
+ const isGone = status === 404
3665
+ const text = status === 409 ? t('dock.stale') : errText(reason, t('errorPrefix'))
3666
+ notifyDone(text, 'error')
3667
+ setNote(text)
3668
+ if (isGone) {
3669
+ setMarkers([])
3670
+ setShadowCount(0)
3671
+ setOpen(false)
3672
+ }
3673
+ if (isGone || status === 409) emitChanged()
3674
+ })
3675
+ .finally(() => setRestoring(null))
3676
+ }
3677
+
3196
3678
  const restoreRow = row => {
3197
3679
  if (restoring != null || running) return
3198
3680
  setRestoring(rowKey(row))
3199
3681
  Promise.resolve()
3200
3682
  .then(() =>
3201
- fetch('/api/message-ops/restore', {
3683
+ // 0.32.2:裸 fetch 无超时 → 后端挂起时 restoring 永不复位,整条
3684
+ // dock 的按钮永久禁用(只能刷新)。与面板同一 15s 口径。
3685
+ fetchWithTimeout('/api/message-ops/restore', {
3202
3686
  method: 'POST',
3203
3687
  headers: { 'content-type': 'application/json' },
3204
3688
  // 0.8.0:upToSeq 存在 → 按轮步进恢复(只重放到该 seq)
@@ -3206,52 +3690,74 @@ window.__ModuleLoader__.load({
3206
3690
  }),
3207
3691
  )
3208
3692
  .then(async res => {
3209
- let data = {}
3210
- try {
3211
- data = await res.json()
3212
- } catch {
3213
- /* keep {} */
3214
- }
3215
- if (!res.ok || !data.ok) throw new Error(data.error || 'HTTP ' + res.status)
3216
- notifyDone(
3217
- t('done.restore', {
3218
- n: String(data.restoredCount != null ? data.restoredCount : '?'),
3219
- s: String(data.skipped != null ? data.skipped : 0),
3220
- }),
3221
- )
3222
- setRestoring(null)
3693
+ const r = await readOpsJson(res)
3694
+ if (!r.ok) throw opsError(r.status, r.data)
3695
+ const data = r.data
3696
+ const doneText = t('done.restore', {
3697
+ n: String(data.restoredCount != null ? data.restoredCount : '?'),
3698
+ s: String(data.skipped != null ? data.skipped : 0),
3699
+ })
3700
+ notifyDone(doneText)
3701
+ setNote(doneText)
3702
+ // 0.30.0:复位只留在 finally —— 重拉(约 30–150ms)窗口内按钮不能再次可点,
3703
+ // 否则连点会重复重放同一批消息。
3223
3704
  // 0.5.0:恢复后重建会话视图(重放消息立即可见)
3224
- try {
3225
- if (__uiWorkspace && typeof __uiWorkspace.openSession === 'function') __uiWorkspace.openSession(sessionId)
3226
- } catch {
3227
- /* fallthrough */
3705
+ // 0.26.0:统一走 safeOpenSession(失败 warn —— 审计 §2.3 指出的 6 处吞错之一)
3706
+ // F2:POST 期间用户可能已切到别的会话(组件不取消在途 promise)。
3707
+ // 切走了就别 openSession 把人拽回 A —— 反馈照常给,视图不动。
3708
+ if (bareSessionId(__currentSessionId) !== bareSessionId(sessionId)) {
3709
+ setNote(doneText)
3710
+ return
3228
3711
  }
3712
+ safeOpenSession(sessionId, 'dock-restore')
3229
3713
  // 0.9.1:重放的消息带**新 seq**,被恢复的行必须解除 hidden;dock 的
3230
3714
  // marker 列表要按权威数据重算(restoreComplete 会变 true)后重拉。
3231
3715
  emitChanged()
3232
- for (const delay of [150, 700, 1600])
3233
- setTimeout(() => {
3234
- if (__refreshSurface) __refreshSurface(sessionId)
3235
- }, delay)
3716
+ // 0.25.0(手感):三连 [150,700,1600] 改成「立即一次」(__refreshSurface
3717
+ // 自带 300ms 尾随防抖)。恢复是**重放**语义:重放出来的消息带新 seq,
3718
+ // 被恢复的行必须解除 hidden —— 这条兜底路径必须留,只是不再让用户白等。
3719
+ if (__refreshSurface) __refreshSurface(sessionId)
3720
+ // F8:本地先摘掉这一行(给即时反馈,且重拉失败时不留下可点的死行)。
3721
+ setMarkers(prev => (prev ? prev.filter(m => m.seq !== row.seq) : prev))
3236
3722
  const fresh = await fetchMessagesJson('/api/message-ops/messages?sessionId=' + encodeURIComponent(sessionId)).catch(() => null)
3237
3723
  if (fresh && fresh.ok) setMarkers(activeMarkers(fresh.messages || []))
3724
+ else loadRef.current()
3238
3725
  })
3239
3726
  .catch(reason => {
3240
- notifyDone(t('errorPrefix') + (reason && reason.message ? reason.message : String(reason)), 'error')
3727
+ const status = reason && reason.status
3728
+ const isStale = status === 409 || /409/.test(String(reason.message || ''))
3729
+ const isGone = status === 404
3730
+ const text = isStale ? t('dock.stale') : errText(reason, t('errorPrefix'))
3731
+ notifyDone(text, 'error')
3732
+ setNote(text)
3733
+ // 409(标记已被后续回撤取代 / 已恢复)时这一行已经失效:重拉列表把它摘掉,
3734
+ // 否则用户会对着一个点了就报错的死按钮继续点。
3735
+ // 0.36.2(ui-errors P3-1):404 = 会话日志已不存在(被外部删除/移走)。
3736
+ // 与 409 同分支摘行,并直接隐藏 dock —— 否则留下一个点了就报错的死行。
3737
+ if (isStale || isGone) emitChanged()
3738
+ if (isGone) {
3739
+ setMarkers([])
3740
+ setShadowCount(0)
3741
+ setOpen(false)
3742
+ }
3241
3743
  })
3242
3744
  .finally(() => setRestoring(null))
3243
3745
  }
3244
3746
 
3245
- const headerKbd = e => {
3246
- if (e.key === 'Enter' || e.key === ' ') {
3247
- e.preventDefault()
3248
- setOpen(v => !v)
3249
- }
3250
- }
3251
- // 0.5.2(P2):标题报「被遮蔽消息数」而非标记数——一个 revert 可遮蔽数百条,
3252
- // 用标记数会严重低报(0.4.2 文案引入的错口径);无 range 数据时回退标记数
3253
- const label = t('dock.title', { n: String(shadowCount || markers.length) })
3254
- const preview = markers[0] && markers[0].snippet ? markers[0].snippet : ''
3747
+ // 0.5.2(P2):标题报「被遮蔽消息数」而非标记数——一个 revert 可遮蔽数百条。
3748
+ // 0.33.3(ui-live P2-1):恢复是重放,遮蔽数**不会**随恢复减少,而展开行是按
3749
+ // 「待恢复轮」列的 —— 只看 26 却只有 3 行会被读成 23 条丢了。有 pending 时
3750
+ // 标题同时报「待恢复轮 + 仍遮蔽条数」,把两个口径分开。
3751
+ const pendingTurns = (markers || []).reduce(
3752
+ (n, mk) => n + (Array.isArray(mk.pendingTurns) ? mk.pendingTurns.length : 0),
3753
+ 0,
3754
+ )
3755
+ const label =
3756
+ pendingTurns > 0
3757
+ ? t('dock.titlePending', { n: String(pendingTurns), m: String(shadowCount) })
3758
+ : shadowCount > 0
3759
+ ? t('dock.title', { n: String(shadowCount) })
3760
+ : t('dock.titleTurns', { n: String(markers.length) })
3255
3761
 
3256
3762
  // 0.8.0:行 = 待恢复"轮"(对齐 opencode 按轮步进);无可重放轮的标记
3257
3763
  // 保留旧式整段行(空区间 → 停用 notice 路径)。restoring 键区分同标记多轮。
@@ -3260,18 +3766,19 @@ window.__ModuleLoader__.load({
3260
3766
  React.createElement(
3261
3767
  'div',
3262
3768
  { key: rowKey(row), className: 'mopsRdRow' },
3263
- React.createElement('span', { className: 'mopsRdRowText' }, '#' + row.seq + ' · ' + (row.snippet || '')),
3769
+ React.createElement('span', { className: 'mopsRdRowText', title: dockRowText(row) }, dockRowText(row)),
3264
3770
  React.createElement(
3265
3771
  'button',
3266
3772
  {
3267
3773
  type: 'button',
3268
3774
  className: 'mopsRdRestore',
3269
3775
  disabled: restoring != null || running,
3776
+ // 运行中禁用时 title 必须说「为什么不能点」,而不是继续讲恢复语义(RD-1)。
3270
3777
  // 0.10.2 专家组评估结论:唯一「严重度=高」的真实缺口是 restore 为**重放**语义 ——
3271
3778
  // 消息带新 seq 落到会话末尾,**不会回到原位**(引擎 SurfaceOp 只有 append/replace,
3272
3779
  // 不存在解除遮蔽的原语)。用户点下去看到消息"搬家到底部"会以为出 bug,
3273
3780
  // 所以把语义写在按钮上,别让人靠猜。
3274
- title: t('dock.restoreHint'),
3781
+ title: running ? t('panel.running') : t('dock.restoreHint'),
3275
3782
  onClick: () => restoreRow(row),
3276
3783
  },
3277
3784
  restoring === rowKey(row) ? t('dock.restoring') : t('dock.restore'),
@@ -3290,32 +3797,31 @@ window.__ModuleLoader__.load({
3290
3797
  // 区间退化成单点且恰好是另一条 marker 时,这条 marker 是**冗余生成**的,
3291
3798
  // 直接标出来,别让用户以为它是一轮真实对话。
3292
3799
  const span = rng ? (rng.endSeq > rng.startSeq ? 'seq ' + rng.startSeq + '..' + rng.endSeq : '#' + rng.startSeq) : ''
3293
- const rangeSnippet = mk.previewFirst || span
3800
+ const rangeSnippet = span
3294
3801
  if (Array.isArray(mk.pendingTurns) && mk.pendingTurns.length > 0) {
3295
3802
  for (const t of mk.pendingTurns) {
3296
3803
  dockRows.push({
3297
3804
  seq: mk.seq,
3298
3805
  upTo: t.upTo,
3806
+ preview: t.preview,
3299
3807
  snippet: t.preview + (t.count > 1 ? ' (+' + (t.count - 1) + ')' : ''),
3300
3808
  })
3301
3809
  }
3302
3810
  } else if (rng) {
3303
- dockRows.push({ seq: mk.seq, snippet: rangeSnippet, markerRange: rng })
3811
+ dockRows.push({ seq: mk.seq, preview: rangeSnippet, snippet: rangeSnippet, rangeStart: rng.startSeq, rangeEnd: rng.endSeq })
3304
3812
  }
3305
3813
  }
3306
3814
 
3815
+ // 没有任何可恢复行(老版本/外部写入的、没有 range 的 marker)→ 整个贴条不渲染,
3816
+ // 否则用户点开的是一个空盒子。
3817
+ if (dockRows.length === 0) return null
3818
+ // 折叠态预览 = 第一条待恢复轮的内容(不是 marker 自己的「[消息回滚] …seq N」notice)。
3819
+ const preview = dockPreviewOf(dockRows)
3820
+
3821
+ // 装饰性 chevron:展开/收起由头部 button 负责(避免嵌套交互元素)
3307
3822
  const chevron = React.createElement(
3308
- 'button',
3309
- {
3310
- type: 'button',
3311
- 'aria-label': open ? t('dock.collapse') : t('dock.expand'),
3312
- 'aria-expanded': open,
3313
- className: 'mopsRdChevron',
3314
- onClick: e => {
3315
- e.stopPropagation()
3316
- setOpen(v => !v)
3317
- },
3318
- },
3823
+ 'span',
3824
+ { className: 'mopsRdChevron' },
3319
3825
  React.createElement(
3320
3826
  'svg',
3321
3827
  {
@@ -3323,7 +3829,8 @@ window.__ModuleLoader__.load({
3323
3829
  height: 14,
3324
3830
  viewBox: '0 0 16 16',
3325
3831
  fill: 'none',
3326
- style: { transform: open ? 'rotate(0deg)' : 'rotate(180deg)', transition: 'transform .15s ease' },
3832
+ // 折叠态朝下(点它展开)、展开态朝上(点它收起)—— 旧实现是反的。
3833
+ style: { transform: open ? 'rotate(180deg)' : 'rotate(0deg)', transition: 'transform .15s ease' },
3327
3834
  },
3328
3835
  React.createElement('path', {
3329
3836
  d: 'M4 6l4 4 4-4',
@@ -3339,13 +3846,15 @@ window.__ModuleLoader__.load({
3339
3846
  'div',
3340
3847
  { className: 'mopsRd', role: 'region', 'aria-label': label },
3341
3848
  React.createElement(
3342
- 'div',
3849
+ 'button',
3343
3850
  {
3851
+ type: 'button',
3344
3852
  className: 'mopsRdHead',
3345
- role: 'button',
3346
- tabIndex: 0,
3853
+ // 头部自己就是展开/收起控件:键盘可达、有 aria-expanded/aria-controls;
3854
+ // chevron 只是装饰(aria-hidden),避免嵌套交互元素。
3855
+ 'aria-expanded': open,
3856
+ 'aria-controls': LIST_ID,
3347
3857
  onClick: () => setOpen(v => !v),
3348
- onKeyDown: headerKbd,
3349
3858
  },
3350
3859
  React.createElement(
3351
3860
  'span',
@@ -3368,14 +3877,52 @@ window.__ModuleLoader__.load({
3368
3877
  }),
3369
3878
  ),
3370
3879
  ),
3371
- React.createElement('span', { className: 'mopsRdLabel' + (open ? '' : ' mopsRdLabelCollapsed') }, label),
3372
- open ? null : React.createElement('span', { className: 'mopsRdPreview' }, preview),
3373
- React.createElement('span', { style: { marginLeft: 'auto', flex: 'none' } }, chevron),
3880
+ React.createElement('span', { className: 'mopsRdLabel' + (open ? ' mopsRdLabelCollapsed' : '') }, label),
3881
+ open ? null : React.createElement('span', { className: 'mopsRdPreview', title: preview }, preview),
3882
+ React.createElement('span', { className: 'mopsRdChevronWrap', 'aria-hidden': 'true' }, chevron),
3374
3883
  ),
3375
- open ? React.createElement('div', { className: 'mopsRdList' }, dockRows.map(rowEl)) : null,
3884
+ note
3885
+ ? React.createElement('div', { className: 'mopsRdNote', role: 'status' }, note)
3886
+ : null,
3887
+ open ? React.createElement('div', { id: LIST_ID, className: 'mopsRdList' }, dockRows.map(rowEl)) : null,
3888
+ open
3889
+ ? React.createElement(
3890
+ 'div',
3891
+ { className: 'mopsRdFoot' },
3892
+ confirmDiscard
3893
+ ? React.createElement(
3894
+ 'div',
3895
+ { className: 'mopsRdConfirm', role: 'alertdialog', 'aria-label': t('dock.discardYes') },
3896
+ React.createElement('span', { className: 'mopsRdConfirmText' }, t('dock.discardConfirm', { n: String(shadowCount) })),
3897
+ React.createElement(
3898
+ 'button',
3899
+ { type: 'button', className: 'mopsRdDanger', disabled: restoring != null || running, onClick: discardAll },
3900
+ restoring === 'discard' ? t('dock.discarding') : t('dock.discardYes'),
3901
+ ),
3902
+ React.createElement(
3903
+ 'button',
3904
+ { type: 'button', className: 'mopsRdCancel', onClick: () => setConfirmDiscard(false) },
3905
+ t('dock.discardCancel'),
3906
+ ),
3907
+ )
3908
+ : React.createElement(
3909
+ 'button',
3910
+ {
3911
+ type: 'button',
3912
+ className: 'mopsRdDiscardLink',
3913
+ disabled: restoring != null || running,
3914
+ title: t('dock.discardHint'),
3915
+ onClick: () => setConfirmDiscard(true),
3916
+ },
3917
+ t('dock.discardLink'),
3918
+ ),
3919
+ )
3920
+ : null,
3376
3921
  )
3377
3922
  }
3378
3923
 
3924
+ // ══ 80-inject · DOM 注入:用户消息动作行 / 可见性 / 扫描 ══
3925
+
3379
3926
  // --- 侧栏行菜单注入(DOM 级,同 session-delete 模式) ------------------------
3380
3927
 
3381
3928
  function findOpenSessionRow() {
@@ -3393,40 +3940,8 @@ window.__ModuleLoader__.load({
3393
3940
  function installUserRevertInjector() {
3394
3941
  if (window.__MOPS_USER_REVERT_INSTALLED) return
3395
3942
  window.__MOPS_USER_REVERT_INSTALLED = true
3396
- var rowsCache = { sid: null, rows: null, at: 0 }
3943
+ var rowsCache = { sid: null, rows: null, at: 0, running: false }
3397
3944
  __peekRowsCache = () => rowsCache
3398
- var norm = x => String(x || '').replace(/\s+/g, '')
3399
-
3400
- // 0.9.7(P4):messageId→seq / 全文索引挂在**同一个 dataSig** 上。
3401
- // 旧实现每会话只写一次、仅失败时 delete —— 会话增长后新 assistant 消息的
3402
- // messageId 不在索引里,`seq == null` → MsgSlotActions 直接 return null,
3403
- // 那条消息旁的回撤/引用按钮**再也不渲染**。dataSig 变了就用手里这份全量
3404
- // 载荷就地重建(零额外请求),并广播 SEQ_INDEX_EVENT 让已挂载的槽位重跑解析。
3405
- var __seqDataSig = null
3406
- var syncSeqIndex = (sid, messages, idx) => {
3407
- const sig = sid + '/' + idx.total + '/' + idx.shadowed.size + '/' + idx.visibleTurns.size
3408
- if (sig === __seqDataSig) return
3409
- __seqDataSig = sig
3410
- const index = new Map()
3411
- const full = new Map()
3412
- for (const m of messages || []) {
3413
- if (!m || m.id == null) continue
3414
- const k = String(m.id)
3415
- // 同 id 取**最早** seq —— 与槽位自己的 buildSeqIndex 口径一致
3416
- // (隐藏判据 buildIndex 取最新,两套语义不能混)。
3417
- if (!index.has(k)) index.set(k, m.seq)
3418
- if (m.fullText) full.set(k, m.fullText)
3419
- }
3420
- for (const key of [sid, 'session-' + sid]) {
3421
- __seqIndexCache.set(key, index)
3422
- __fullTextCache.set(key, full)
3423
- }
3424
- try {
3425
- window.dispatchEvent(new CustomEvent(SEQ_INDEX_EVENT))
3426
- } catch {
3427
- /* non-browser */
3428
- }
3429
- }
3430
3945
 
3431
3946
  var fetchRows = sidIn => {
3432
3947
  // 0.9.7:统一按**裸 uuid** 作缓存键。调用方有的传 `session-xxx`(scan /
@@ -3436,35 +3951,17 @@ window.__ModuleLoader__.load({
3436
3951
  if (rowsCache.sid === sid && rowsCache.rows && Date.now() - rowsCache.at < 8000) return Promise.resolve(rowsCache)
3437
3952
  return fetchMessagesJson('/api/message-ops/messages?sessionId=' + encodeURIComponent(sid))
3438
3953
  .then(d => {
3439
- // 宿主会把 <system-reminder> / runtime context 等也记为 role=user 的行,
3440
- // DOM 里并不渲染成"我的消息"块 —— 必须滤掉,否则按序配对会错位(0.7.0 根因)。
3441
- // 注意:对话框的「可回滚目标」列表仍应过滤 visible(那是另一套语义)。
3442
- // 稳妥做法本该在服务端打 injected 标志,先在客户端补齐正则。
3443
- // 判据一律用**原始 snippet**(norm() 删掉全部空白,正则必然失配)。
3444
- // 0.9.0 / 0.9.6 两轮事故复盘 + 120 份日志普查样本见 README「历史事故记录」#3。
3445
- // 关键约束:id 后必须跟得上具体形态([\w-]+ / [0-9a-f]{8}-),
3446
- // 否则 `Background job 是我自己的问题` 这种真人输入会被误杀
3447
- // (曾用 ^background job\b,测试当场抓到这个误杀)。
3448
- // 样本里没出现过的模式(已停止 / User feedback:)一律**不加** —— 没证据就不猜。
3449
- const injected = raw =>
3450
- /^<system-reminder|current\s+runtime\s+context|^<system-Reminder|^background job\s+[\w-]+|^Background subagent\s+[0-9a-f]{8}-|^Agent\s+[0-9a-f]{8}-|^\[model changed:/i.test(
3451
- String(raw || ''),
3452
- )
3453
- const rows = ((d && d.messages) || [])
3454
- .filter(m => m && m.role === 'user')
3455
- .map(m => ({
3456
- seq: m.seq,
3457
- sn: norm(m.snippet),
3458
- raw: String(m.snippet == null ? '' : m.snippet),
3459
- fullText: m.fullText ?? null,
3460
- visible: m.visible !== false,
3461
- turnStartSeq: m.turnStartSeq ?? null,
3462
- }))
3463
- .filter(r => r.sn && !injected(r.raw))
3954
+ // 行表判据单点在 revertRowsOf(0.28.0 起以 sourceKind 为准,正则只兜旧载荷)。
3955
+ const rows = revertRowsOf(d)
3464
3956
  // 0.9.1:同时产出 node-key 查表索引(隐藏 transcript 用)
3465
3957
  const idx = buildIndex(d)
3466
- rowsCache = { sid: sid, rows: rows, idx: idx, at: Date.now() }
3467
- syncSeqIndex(sid, d && d.messages, idx)
3958
+ // 0.25.0:把服务端 isRunning 一起缓存 —— 注入器是纯 DOM 闭包,拿不到
3959
+ // useSessions,只能靠这里带出来的 running 给按钮做状态提示。
3960
+ // 合成 turn 的宿主过程行(「Completed in 1s」)必须隐藏。0.28.x:这条
3961
+ // 规则原先只挂在 dock 组件里 —— dock 卸载后旧合成 turn 又露出,且没有
3962
+ // marker 时根本不隐藏。移到取数路径 = 每个会话首次取数就生效。
3963
+ syncSyntheticTurnStyle((d && d.messages) || [], sid)
3964
+ rowsCache = { sid: sid, rows: rows, idx: idx, at: Date.now(), running: d && d.running === true }
3468
3965
  return rowsCache
3469
3966
  })
3470
3967
  .catch(() => (rowsCache.sid === sid ? rowsCache : null))
@@ -3499,24 +3996,20 @@ window.__ModuleLoader__.load({
3499
3996
  var byTurn = new Map()
3500
3997
  var shadowed = new Set() // 落在 replace 区间内 = 已被回滚(transcript 藏行判据)
3501
3998
  var visibleTurns = new Set() // 含至少一条**未被遮蔽**消息的 turn 号(回合 chrome)
3502
- var dupByMessageId = new Map()
3503
3999
  for (var i = 0; i < list.length; i++) {
3504
4000
  var m = list[i]
3505
4001
  if (!m || typeof m.seq !== 'number') continue
3506
4002
  if (m.id != null) {
3507
4003
  var k = String(m.id)
3508
4004
  // restore 是「重放」语义 → 原件与副本可能同 id 并存。
3509
- // 0.9.1:不再「保留最早」,而是收集**全部** seq,隐藏判据取「任一 seq 越过
3510
- // fence」。回放副本才是当前 surface 上的那条,用最早的 seq 判会让
3511
- // 「恢复后再回滚」漏藏(实测 fence=70、副本 seq=70、原件 seq=54)。
3512
- if (byMessageId.has(k)) {
3513
- const arr = dupByMessageId.get(k) || [byMessageId.get(k)]
3514
- arr.push(m.seq)
3515
- dupByMessageId.set(k, arr)
3516
- byMessageId.set(k, m.seq) // 指向最新的
3517
- } else {
3518
- byMessageId.set(k, m.seq)
3519
- }
4005
+ // ⚠️ 0.26.0(审计 §4.1):这里**只保留最新 seq 一个值**。
4006
+ // 0.9.1 曾额外维护 `dupByMessageId`(收集同 id 的全部 seq)+ `seqOfNodeKey`
4007
+ // 返回 `hit.all`,声称供「隐藏判据取任一 seq 越过 fence」用 —— 但 0.9.1 的
4008
+ // `fences` 判据早已换成 `idx.shadowed`(见 applySurfaceVisibility),
4009
+ // 生产里**没有任何读取方会读 `hit.all`**(grep `hit.all` = 0)。
4010
+ // 测试(test/surface-visibility.test.js)当时测的是它自己手抄的副本,
4011
+ // 于是「生产 0 读者 / 测试绿」= 假绿灯。0.26.0 删掉:索引只留被消费的字段。
4012
+ byMessageId.set(k, m.seq) // 最新(当前 surface 上的那条)
3520
4013
  }
3521
4014
  if (m.type === 'assistant/message' && m.turn != null && m.step != null) {
3522
4015
  byTurnStep.set(m.turn + ':' + m.step, m.seq)
@@ -3531,10 +4024,15 @@ window.__ModuleLoader__.load({
3531
4024
  }
3532
4025
  // turnEnd 优先:它对「该 turn 内一条消息都没有」的情况仍然有效
3533
4026
  if (turnEnd) for (const k in turnEnd) if (Object.prototype.hasOwnProperty.call(turnEnd, k)) byTurn.set(k, turnEnd[k])
3534
- return { byMessageId, dupByMessageId, byTurnStep, byCallId, byTurn, shadowed, visibleTurns, total: list.length }
4027
+ // ⚠️ 返回形状 = **被消费的字段全集**(多一个字段 = 多一份要维护却没人读的状态):
4028
+ // byMessageId / byTurnStep / byCallId / byTurn → seqOfNodeKey 查表
4029
+ // shadowed → applySurfaceVisibility 藏行判据
4030
+ // visibleTurns → 回合 chrome 的藏行判据
4031
+ // total → ensureAssign 的 dataSig(变化重算)
4032
+ return { byMessageId, byTurnStep, byCallId, byTurn, shadowed, visibleTurns, total: list.length }
3535
4033
  }
3536
4034
 
3537
- /** node-key → { seq, all }(all = 同 id 的全部 seq,处理 restore 重放副本)。 */
4035
+ /** node-key → `{ kind, seq[, turn] }`(**只返回查到的 seq**;同 id 只留最新,见 buildIndex)。 */
3538
4036
  var seqOfNodeKey = (key, idx) => {
3539
4037
  var parsed = parseNodeKey(key)
3540
4038
  if (!parsed || !idx) return null
@@ -3544,16 +4042,15 @@ window.__ModuleLoader__.load({
3544
4042
  case 'developer-message':
3545
4043
  case 'trajectory-note': {
3546
4044
  const hit = idx.byMessageId.get(id)
3547
- if (hit === undefined) return null
3548
- return { kind: parsed.kind, seq: hit, all: idx.dupByMessageId.get(id) || [hit] }
4045
+ return hit === undefined ? null : { kind: parsed.kind, seq: hit }
3549
4046
  }
3550
4047
  case 'assistant-step': {
3551
4048
  const hit = idx.byTurnStep.get(id)
3552
- return hit === undefined ? null : { kind: parsed.kind, seq: hit, all: [hit] }
4049
+ return hit === undefined ? null : { kind: parsed.kind, seq: hit }
3553
4050
  }
3554
4051
  case 'tool-call': {
3555
4052
  const hit = idx.byCallId.get(id)
3556
- return hit === undefined ? null : { kind: parsed.kind, seq: hit, all: [hit] }
4053
+ return hit === undefined ? null : { kind: parsed.kind, seq: hit }
3557
4054
  }
3558
4055
  case 'turn-tail':
3559
4056
  case 'turn-process':
@@ -3563,7 +4060,7 @@ window.__ModuleLoader__.load({
3563
4060
  const hit = idx.byTurn.get(id)
3564
4061
  // 这类是**回合 chrome**,id 就是 turn 号 —— 判据要按「这个 turn 还有
3565
4062
  // 没有可见消息」而不是按 seq,因为 turn/end 本身多半不在 surface 上。
3566
- return hit === undefined ? null : { kind: parsed.kind, seq: hit, all: [hit], turn: id }
4063
+ return hit === undefined ? null : { kind: parsed.kind, seq: hit, turn: id }
3567
4064
  }
3568
4065
  default:
3569
4066
  return null // compaction / command / workflow-run 等不参与
@@ -3624,9 +4121,10 @@ window.__ModuleLoader__.load({
3624
4121
  return { hidden, unresolved, shown }
3625
4122
  }
3626
4123
 
3627
- // 用户消息锚点:优先官方 Sixlwa_userRow(含 .xzv4MW_actions),回退 flow-kind 属性
4124
+ // 用户消息锚点:优先官方 `HOST_CLS.userRow`(含 `HOST_CLS.actions` 动作行),
4125
+ // 回退稳定属性 `data-chat-flow-kind="user"`(二者都在顶部 HOST_CLS 单点定义)。
3628
4126
  // 锚点 = 每条用户消息自己的容器(一个块只算一次):
3629
- // 从官方动作行 .xzv4MW_actions 反查最近的消息容器,最贴近"一条消息"的粒度。
4127
+ // 从官方动作行反查最近的消息容器,最贴近"一条消息"的粒度。
3630
4128
  var userAnchors = () => {
3631
4129
  const out = []
3632
4130
  const seen = new Set()
@@ -3636,7 +4134,7 @@ window.__ModuleLoader__.load({
3636
4134
  out.push(el)
3637
4135
  }
3638
4136
  }
3639
- const rows = Array.from(document.querySelectorAll('[class*="xzv4MW_actions"]'))
4137
+ const rows = Array.from(document.querySelectorAll('[class*="' + HOST_CLS.actions + '"]'))
3640
4138
  for (const r of rows) {
3641
4139
  const block =
3642
4140
  r.closest('[data-chat-flow-kind="user"]') ||
@@ -3663,18 +4161,55 @@ window.__ModuleLoader__.load({
3663
4161
  // 配不上(data-mops-unmatched)→ 禁用 + 说明原因,绝不留装饰按钮。
3664
4162
  var syncEnabled = (block, btn) => {
3665
4163
  if (!btn) return
3666
- // 0.18.0/0.20.0:三种按钮各有自己的提示文案(编辑按钮不能写 revert 的 hint)
4164
+ // 0.18.0/0.20.0:两种按钮各有自己的提示文案(编辑按钮不能写 revert 的 hint)
3667
4165
  // 0.21.0:回滚按钮统一用「带隐私提示」的 title —— syncEnabled 会在
3668
4166
  // 注入后重设 title,若这里仍用 slot.revert 会覆盖掉 ensureBtn 里的隐私提示。
3669
- const hintKey = btn.classList.contains('mopsUserEdit') ? 'slot.editHint' : 'slot.revertPrivacyHint'
4167
+ const isEdit = btn.classList.contains('mopsUserEdit')
4168
+ const hintKey = isEdit ? 'slot.editHint' : 'slot.revertPrivacyHint'
3670
4169
  const ok = block.getAttribute('data-mops-seq')
3671
4170
  if (ok) {
4171
+ // 🔴 0.26.0 红线:**铅笔任何时候都可点**。
4172
+ //
4173
+ // 打开浮层是纯读(GET /text),不需要 idle;真正会被服务端 409 拦住的是
4174
+ // 「撤销并发送」,那一层已经由浮层里的发送按钮 disabled + edit.running 拦住。
4175
+ // 所以这里绝不允许出于「会话运行中」把入口 disabled —— 那正是用户投诉
4176
+ // 「运行时铅笔根本无法点击」的形态。
4177
+ //
4178
+ // 0.24~0.25 里这条路径本来就只改 title/attr、没动 disabled(已用真实浏览器
4179
+ // 138 点采样 + 原生鼠标点击验证过:运行中 disabled=false、可点开)。
4180
+ // 保留 running 字样是**告知**,不是禁用;视觉上只做轻微淡化,不再用
4181
+ // 0.5 那样容易被读成「禁用」的透明度。
4182
+ // F6:点击后到写请求收敛前,按钮处于 busy —— scan 每帧都会跑,
4183
+ // 这里若无条件 disabled=false,同一次意图会被重复点出第二次 POST。
4184
+ if (btn.getAttribute('data-mops-busy') === '1') {
4185
+ btn.disabled = true
4186
+ return
4187
+ }
3672
4188
  btn.disabled = false
3673
- btn.title = __t(hintKey)
4189
+ // F11:running 只在缓存属于当前会话时可信(切会话的 200ms 窗口内
4190
+ // 旧会话的 running 会把新会话的按钮/编辑器说成「运行中」)。
4191
+ const cacheSid = rowsCache.sid
4192
+ const sameSession = !cacheSid || !__currentSessionId || bareSessionId(cacheSid) === bareSessionId(__currentSessionId)
4193
+ const running = sameSession && rowsCache.running === true
4194
+ if (isEdit) {
4195
+ btn.title = running ? __t('edit.running') : __t(hintKey)
4196
+ // running 是「可点但发送要等」的信号:写进 aria 与 data-*,样式只做
4197
+ // 非常轻的提示(0.82 仍清晰可辨,不像 disabled 的 0.4/0.5)
4198
+ if (running) {
4199
+ btn.setAttribute('data-mops-running', '1')
4200
+ btn.setAttribute('aria-label', __t('edit.running'))
4201
+ } else {
4202
+ btn.removeAttribute('data-mops-running')
4203
+ btn.setAttribute('aria-label', __t('slot.edit'))
4204
+ }
4205
+ } else {
4206
+ btn.title = __t(hintKey)
4207
+ btn.removeAttribute('data-mops-running')
4208
+ }
3674
4209
  btn.removeAttribute('data-mops-unmatched')
3675
4210
  } else {
3676
4211
  btn.disabled = true
3677
- btn.title = __t('slot.revertUnmatched')
4212
+ btn.title = __t(isEdit ? 'slot.editUnmatched' : 'slot.revertUnmatched')
3678
4213
  btn.setAttribute('data-mops-unmatched', '1')
3679
4214
  }
3680
4215
  }
@@ -3747,12 +4282,26 @@ window.__ModuleLoader__.load({
3747
4282
  // 0.7.0:点击时先**同步完成**配对(打标是异步 fetch 的结果,
3748
4283
  // 早先点在未打标的按钮上会静默失败 = 用户反馈的"点了没用")。
3749
4284
  var runUserRevert = (btn, block) => {
3750
- const sid = __currentSessionId
3751
- if (!sid) return
4285
+ const rawSid = __currentSessionId
4286
+ if (!rawSid) return
3752
4287
  btn.disabled = true
4288
+ if (btn && btn.setAttribute) btn.setAttribute('data-mops-busy', '1')
4289
+ // 0.32.2(回归修复):busy 必须由**整条写链**的 finally 摘除。
4290
+ // 旧实现内层链没有 return,外层 then 立刻完成,内层 finally 只复位
4291
+ // disabled、永不删 data-mops-busy;而 scan 每帧按 busy 把按钮设回
4292
+ // disabled → 一次失败(409/500/断网)就让该行回撤按钮永久禁用。
4293
+ const release = () => {
4294
+ if (btn && btn.removeAttribute) btn.removeAttribute('data-mops-busy')
4295
+ syncEnabled(block, btn)
4296
+ }
4297
+ // 0.25.0(手感):ensureAssign 内部第一件事就是 fetchRows,并把同一个
4298
+ // cache 返回出来 —— 旧实现在它后面再 fetchRows(rawSid) 一次是纯重复
4299
+ // (命中 8s 缓存只是空转,未命中时平白多打一次 GET /messages)。
4300
+ // 复用返回值即可;只有 ensureAssign 彻底拿不到数据(网络失败 → null)
4301
+ // 时才补一次,避免「一次抖动就让这次点击变成点了没用」。
3753
4302
  Promise.resolve()
3754
- .then(() => ensureAssign(sid))
3755
- .then(() => fetchRows(sid))
4303
+ .then(() => ensureAssign(rawSid))
4304
+ .then(cache => cache || fetchRows(rawSid))
3756
4305
  .then(cache => {
3757
4306
  const rows = cache && cache.rows
3758
4307
  // 0.9.1:seq 来自 node-key 精确查表,**不再**做文本前缀匹配验证
@@ -3760,63 +4309,42 @@ window.__ModuleLoader__.load({
3760
4309
  const seq = Number(block.getAttribute('data-mops-seq'))
3761
4310
  const row = rows && rows.find(r => r.seq === seq)
3762
4311
  if (!row) {
3763
- ensureAssign(sid)
4312
+ ensureAssign(rawSid)
3764
4313
  notifyDone(__t('errorPrefix') + __t('slot.revertUnmatched'), 'error')
3765
- return
4314
+ return undefined
3766
4315
  }
3767
4316
  btn.disabled = true
3768
- Promise.resolve()
3769
- .then(() =>
3770
- fetch('/api/message-ops/revert', {
3771
- method: 'POST',
3772
- headers: { 'content-type': 'application/json' },
3773
- body: JSON.stringify({ sessionId: sid, seq: row.seq }),
3774
- }),
3775
- )
3776
- .then(async res => {
3777
- let data = {}
3778
- try {
3779
- data = await res.json()
3780
- } catch {
3781
- /* keep {} */
3782
- }
3783
- if (!res.ok || !data.ok) throw new Error(data.error || 'HTTP ' + res.status)
3784
- // 0.23.0(深挖):先回填再报成功,回填失败要让用户知道。
3785
- // 旧实现先 notifyDone(done.revert) 再 refillComposer 且丢弃返回值 →
3786
- // 用户看到「已回滚」却拿到空输入框(0.14.0 踩过的同一类静默失败)。
3787
- // 0.17.0(冲突 C2):按钮路径原先漏了「立刻标遮蔽」,
3788
- // 导致刷新窗口内重复点击会拿已遮蔽的 seq 去 POST → 409。
3789
- markRowsShadowedFrom(row.seq)
3790
- const filled = refillComposer(sid, row.seq)
3791
- if (filled) notifyDone(__t('done.revert'))
3792
- else notifyDone(__t('done.revertNoRefill'), 'warn')
3793
- emitChanged()
3794
- try {
3795
- if (__uiWorkspace && typeof __uiWorkspace.openSession === 'function') __uiWorkspace.openSession(sid)
3796
- } catch {
3797
- /* 视图重建失败不阻断 */
3798
- }
3799
- // 0.9.1:视图重建后重新拉权威可见性并隐藏被遮蔽的行。
3800
- // openSession 会重挂 DOM,旧节点上的 hidden 属性随之失效,必须重刷。
3801
- if (rowsCache) rowsCache.at = 0
3802
- for (const delay of [150, 700, 1600])
3803
- setTimeout(() => {
3804
- if (__refreshSurface) __refreshSurface(sid)
3805
- }, delay)
3806
- })
3807
- .catch(reason => {
3808
- notifyDone(__t('errorPrefix') + (reason && reason.message ? reason.message : String(reason)), 'error')
3809
- })
3810
- .finally(() => {
3811
- btn.disabled = false
3812
- })
4317
+ return fetchWithTimeout('/api/message-ops/revert', {
4318
+ method: 'POST',
4319
+ headers: { 'content-type': 'application/json' },
4320
+ body: JSON.stringify({ sessionId: rawSid, seq: row.seq }),
4321
+ }).then(async res => {
4322
+ const r = await readOpsJson(res)
4323
+ if (!r.ok) throw opsError(r.status, r.data)
4324
+ // 0.23.0(深挖):先回填再报成功,回填失败要让用户知道。
4325
+ // 旧实现先 notifyDone(done.revert) 再 refillComposer 且丢弃返回值 →
4326
+ // 用户看到「已回滚」却拿到空输入框(0.14.0 踩过的同一类静默失败)。
4327
+ // 0.17.0(冲突 C2):按钮路径原先漏了「立刻标遮蔽」,
4328
+ // 导致刷新窗口内重复点击会拿已遮蔽的 seq 去 POST → 409。
4329
+ markRowsShadowedFrom(row.seq)
4330
+ // 收尾单点在 afterWrite(emitChanged / safeOpenSession / 重算隐藏)。
4331
+ // 0.23.0:回填失败要让用户知道(旧实现报「已回滚」却给出空输入框)。
4332
+ const filled = refillComposer(rawSid, row.seq)
4333
+ afterWrite(rawSid, filled ? __t('done.revert') : __t('done.revertNoRefill'), filled ? undefined : 'warn')
4334
+ })
3813
4335
  })
4336
+ // 0.32.2:外层补 catch —— ensureAssign/fetchRows 的拒绝此前会逸出成
4337
+ // unhandled rejection,且按钮停在 disabled。
4338
+ .catch(reason => {
4339
+ notifyDone(timeoutText(reason, __t('errorPrefix')), 'error')
4340
+ })
4341
+ .finally(release)
3814
4342
  }
3815
4343
  /**
3816
4344
  * 0.20.0 铅笔编辑按钮:与回滚**同一动作行**,插在回滚与分叉之间。
3817
4345
  *
3818
- * 语义 = 打开「编辑并重发」浮层(`EditResendOverlay`),编辑框里改文字;
3819
- * **点「发送并回撤」那一刻**才回撤并重发。点按钮本身零写操作。
4346
+ * 语义 = 在这条消息行里就地展开编辑区(0.28.0 起,不再是浮动层);
4347
+ * **点「撤销并发送」那一刻**才回撤并重发。点按钮本身零写操作。
3820
4348
  *
3821
4349
  * 与 0.19.0 删掉的行内编辑的区别:那版只是把原文**回填 composer**
3822
4350
  * (`refillComposer`),跟回滚回填是同一件事,所以被判为重复入口而删除。
@@ -3824,13 +4352,35 @@ window.__ModuleLoader__.load({
3824
4352
  *
3825
4353
  * 图标取官方 `edit-outline` 几何(16 viewBox,填充几何 —— 与分叉图标同族写法)。
3826
4354
  */
4355
+ /**
4356
+ * 取得(必要时创建)本条消息的**插件动作行**,返回 `{ host, created }`。
4357
+ *
4358
+ * 审计 §3.2:`ensureBtn` / `ensureEditBtn` 原先是两段**逐字相同**的
4359
+ * 「查宿主动作行 → 查不到就建一个 `mopsUserActionsRow`」。
4360
+ * 合并成一个函数不是为了省 4 行,而是为了消灭一个真实风险:
4361
+ * 若宿主将来只提供 `TS9iAW_actions`、不再有 `xzv4MW_actions`,两个工厂会
4362
+ * **各自**建一行 → 同一条消息下出现**两个**插件动作行(回滚/铅笔分两排),
4363
+ * 这正是 0.16.0「撑裂行高」事故的同一类形态。
4364
+ *
4365
+ * 现在只有这一处会建行:先到先得,后来的复用同一个 host。
4366
+ */
4367
+ var ensureActionsHost = block => {
4368
+ // ① 宿主动作行(可见性跟随 hover 显隐,首选)
4369
+ let host = block.querySelector('[class*="' + HOST_CLS.actions + '"]')
4370
+ if (host) return { host: host, created: false }
4371
+ // ② **我们上一轮建的兜底行**:必须一起查,否则第二个工厂查不到就再建一行
4372
+ // (原实现正是这样:`ensureBtn` 建了一行、`ensureEditBtn` 又建一行 →
4373
+ // 同一条消息两排插件按钮,0.16.0「撑裂行高」事故的同一形态)。
4374
+ host = block.querySelector('[class*="mopsUserActionsRow"]')
4375
+ if (host) return { host: host, created: false }
4376
+ host = document.createElement('div')
4377
+ host.className = 'mopsUserActionsRow'
4378
+ block.appendChild(host)
4379
+ return { host: host, created: true }
4380
+ }
4381
+
3827
4382
  var ensureEditBtn = block => {
3828
- let host = block.querySelector('[class*="xzv4MW_actions"]')
3829
- if (!host) {
3830
- host = document.createElement('div')
3831
- host.className = 'mopsUserActionsRow'
3832
- block.appendChild(host)
3833
- }
4383
+ const { host } = ensureActionsHost(block)
3834
4384
  const existing = host.querySelector('.mopsUserEdit')
3835
4385
  if (existing) return existing
3836
4386
  const btn = document.createElement('button')
@@ -3855,7 +4405,7 @@ window.__ModuleLoader__.load({
3855
4405
  }
3856
4406
 
3857
4407
  /**
3858
- * 0.20.0 行内编辑入口:解析 seq → 派发 `EDIT_EVENT` 打开编辑浮层。
4408
+ * 0.20.0 行内编辑入口:解析 seq → 在消息行里就地展开编辑区(0.28.0 起不再用浮层)。
3859
4409
  *
3860
4410
  * 这一步**纯读**:`ensureAssign` / `fetchRows` 只读 `/api/message-ops/messages`,
3861
4411
  * 不发任何写请求、不改草稿。真正的写操作全在 `sendEditAndRevert` 里,
@@ -3864,6 +4414,12 @@ window.__ModuleLoader__.load({
3864
4414
  var runUserEdit = (btn, block) => {
3865
4415
  const sid = __currentSessionId
3866
4416
  if (!sid) return
4417
+ // 同一条再点铅笔 = 立即收起(0.28.1:同步判断,不等 /messages 往返;
4418
+ // 等待期也不再把按钮 disabled —— disabled 会丢键盘焦点)。
4419
+ if (inlineEdit && inlineEdit.block === block) {
4420
+ closeInlineEdit()
4421
+ return
4422
+ }
3867
4423
  btn.disabled = true
3868
4424
  Promise.resolve()
3869
4425
  .then(() => ensureAssign(sid))
@@ -3880,30 +4436,26 @@ window.__ModuleLoader__.load({
3880
4436
  notifyDone(__t('slot.editUnmatched'), 'warn')
3881
4437
  return
3882
4438
  }
3883
- // 裸 uuid 给 HTTP,带前缀的给 openSession 与草稿键
3884
- window.dispatchEvent(
3885
- new CustomEvent(EDIT_EVENT, {
3886
- detail: { sessionId: bareSessionId(sid), rawSessionId: sid, seq: seq },
3887
- }),
3888
- )
4439
+ // 0.28.0:就地编辑 —— 不再派发事件/浮层,直接在这条消息行里挂编辑器。
4440
+ // row.fullText 是 /messages 给出的全文(user 行本就是 messageTextFull),
4441
+ // 不用 snippet、也不用再打一次 /text。
4442
+ openInlineEdit(btn, block, row, sid)
3889
4443
  })
3890
4444
  .catch(reason => {
3891
- notifyDone(__t('errorPrefix') + (reason && reason.message ? reason.message : String(reason)), 'error')
4445
+ notifyDone(errText(reason, __t('errorPrefix')), 'error')
3892
4446
  })
3893
4447
  .finally(() => {
3894
- btn.disabled = false
4448
+ // 0.26.0:收尾交给 syncEnabled 而不是无条件 disabled=false ——
4449
+ // 配对失败的块必须保持 disabled(抛 true 会让装饰按钮可点且点了报错)。
4450
+ if (btn && btn.removeAttribute) btn.removeAttribute('data-mops-busy')
4451
+ syncEnabled(block, btn)
3895
4452
  })
3896
4453
  }
3897
4454
 
3898
4455
  // 三个按钮的顺序由 DOM 顺序决定:回滚在前(破坏性更高),编辑居中,分叉最后(非破坏)。
3899
4456
  var ensureBtn = block => {
3900
4457
  // 官方动作行(含 Copy):把按钮放到这一行里,与 Copy 同级
3901
- let host = block.querySelector('[class*="xzv4MW_actions"]')
3902
- if (!host) {
3903
- host = document.createElement('div')
3904
- host.className = 'mopsUserActionsRow'
3905
- block.appendChild(host)
3906
- }
4458
+ const { host } = ensureActionsHost(block)
3907
4459
  let btn = host.querySelector('.mopsUserRevert')
3908
4460
  if (btn) return btn
3909
4461
  btn = document.createElement('button')
@@ -3921,6 +4473,9 @@ window.__ModuleLoader__.load({
3921
4473
  runUserRevert(btn, block)
3922
4474
  })
3923
4475
  host.appendChild(btn)
4476
+ // 0.30.1:这组插件按钮的第一颗打标记 —— CSS 用 [data-mops-first] 画分隔线,
4477
+ // 旧选择器 :first-of-type 永远命中宿主的「时间文本」而不是我们的按钮(实测 0 命中)。
4478
+ if (!host.querySelector('[data-mops-first="1"]')) btn.setAttribute('data-mops-first', '1')
3924
4479
  // 0.9.7(P2-1):新按钮按块的**当前**打标状态立刻同步一次。
3925
4480
  // 门控之后 assignSeqs 可能被跳过(签名未变),靠这里保证「宿主重建了
3926
4481
  // 动作行 → 按钮重新挂上」这种情况仍然是 disabled/title 正确的。
@@ -3934,13 +4489,25 @@ window.__ModuleLoader__.load({
3934
4489
  // 0.23.0:行内 fork 按钮已删 —— dsh 官方在 AI 回合尾部已有
3935
4490
  // sessions.fork(conversation.chat.assistant-actions / TurnTailNodeView)。
3936
4491
  // 分叉能力统一由官方按钮 + 面板 branch(同样走官方 sessions.fork)承担。
3937
- ensureBtn(block)
4492
+ const first = ensureBtn(block)
3938
4493
  ensureEditBtn(block)
4494
+ // 宿主重建动作行后旧按钮可能被替换:保证标记只落在第一颗上
4495
+ if (first && !first.hasAttribute('data-mops-first')) {
4496
+ const marked = block.querySelector('[class*="' + HOST_CLS.actions + '"] [data-mops-first="1"]')
4497
+ if (!marked) first.setAttribute('data-mops-first', '1')
4498
+ }
3939
4499
  }
3940
- // 0.9.7(P0-2 读合并):把 150/700/1600ms 三档并成**一次**真网络请求,
3941
- // 落点 = 本 burst 第一档 + 1500ms ≈ 原来的 1600ms 那一档。
3942
- // 🔴 红线:这一档是「视图重建后重算隐藏」的兜底,绝不能砍成 0。
3943
- // 调用当下立刻 rowsCache.at = 0 —— openSession 触发的那次 scan 因此能用
4500
+ // 0.9.7(P0-2 读合并)/ 0.25.0(手感):写操作后的兜底刷新 = **一次**真网络请求。
4501
+ //
4502
+ // 历史:写操作后曾排 150/700/1600ms 三连调用,指望「DOM 重建在不同时刻完成,
4503
+ // 多打几档总能补上」。而本函数自身有防抖(窗口内重复调用只留最后一次),
4504
+ // 三连实际只跑一发 —— 但落点固定在 1500ms 后,用户点完回撤要**白等 1.6 秒**
4505
+ // 才看到灰。0.25.0 改成:调用方写后**立即**调一次(本函数立刻按防抖排程),
4506
+ // 防抖窗口 1500ms → **300ms**(尾随),既够宿主完成 openSession 的 DOM 重挂,
4507
+ // 又不让用户干等。
4508
+ // 🔴 红线:这一档是「视图重建后重算隐藏」的兜底,绝不能砍成 0 —— 300ms 是
4509
+ // 「一帧/两帧 + 一次重挂预算」,宁可多 300ms 也不许没有。
4510
+ // 调用当下立刻 rowsCache.at = 0 —— 紧随其后的 scan 因此能用
3944
4511
  // 共享窗口里的新鲜载荷先把隐藏刷对,不必等兜底那一发。
3945
4512
  var refreshTimer = null
3946
4513
  var refreshDeadline = 0
@@ -3949,7 +4516,7 @@ window.__ModuleLoader__.load({
3949
4516
  if (!id) return
3950
4517
  if (rowsCache) rowsCache.at = 0 // 强制重取权威数据
3951
4518
  const now = Date.now()
3952
- if (!refreshTimer) refreshDeadline = now + 1500
4519
+ if (!refreshTimer) refreshDeadline = now + 300
3953
4520
  clearTimeout(refreshTimer)
3954
4521
  refreshTimer = setTimeout(
3955
4522
  () => {
@@ -3976,7 +4543,16 @@ window.__ModuleLoader__.load({
3976
4543
  const sid = __currentSessionId
3977
4544
  if (!sid) return
3978
4545
  const blocks = userAnchors()
3979
- for (const b of blocks) ensureUserActions(b)
4546
+ for (const b of blocks) {
4547
+ ensureUserActions(b)
4548
+ // 0.25.0:running 变了要立刻同步按钮 title(否则要等 8s 缓存过期)。
4549
+ // 用缓存值,零额外请求。
4550
+ syncBlockButtons(b)
4551
+ }
4552
+ // 0.28.0:宿主重建消息块后把就地编辑区挂回去(文本随元素保留)。
4553
+ rehydrateInlineEdit()
4554
+ // 运行态随宿主刷新(编辑器开着时会话开始/停止运行)
4555
+ paintInlineEdit()
3980
4556
  // 0.9.1:**始终**刷新(原先只在按钮未打标时刷)——
3981
4557
  // 打标后 transcript 再变化(openSession 重建 / 分页 / restore 重放)
3982
4558
  // 就再也不会重算隐藏,导致「界面停在旧状态,必须重载页面才对」。
@@ -3992,7 +4568,9 @@ window.__ModuleLoader__.load({
3992
4568
  try {
3993
4569
  if (!e || !e.target || !e.target.closest) return
3994
4570
  if (!__currentSessionId) return
3995
- const block = e.target.closest('[class*="Sixlwa_userRow"], [data-chat-flow-kind="user"]')
4571
+ // hash 单点:HOST_CLS.userRow 不硬编码在选择器里(见顶部常量块)。
4572
+ // 稳定属性 `data-chat-flow-kind="user"` 在前 —— 宿主换 hash 也不会失配。
4573
+ const block = e.target.closest('[class*="' + HOST_CLS.userRow + '"], [data-chat-flow-kind="user"]')
3996
4574
  if (!block) return
3997
4575
  ensureUserActions(block)
3998
4576
  if (!block.hasAttribute('data-mops-seq')) ensureAssign(__currentSessionId)
@@ -4002,7 +4580,32 @@ window.__ModuleLoader__.load({
4002
4580
  },
4003
4581
  { passive: true },
4004
4582
  )
4005
- window.addEventListener('scroll', scan, { passive: true })
4583
+ // 0.25.0(手感):滚动走 rAF 合并。
4584
+ //
4585
+ // 改前:`scroll` 上一次事件跑一次 `scan()`,而 scan 每次要做 **3 次全文档
4586
+ // querySelectorAll**(userAnchors / data-chat-node-key / 块内动作行)。
4587
+ // 滚动是每帧多次派发的高频事件 —— 长会话里肉眼可见地发涩。
4588
+ // 改后:一帧内不管派发多少次,只跑一次 scan(rAF 合并,天然对齐宿主渲染节奏)。
4589
+ // 不改成 MO 的 scheduleScan()(200ms 尾随):那是为「宿主重建块」服务的防抖,
4590
+ // 拿它接滚动会让藏行/打标慢半拍,手感更差。
4591
+ var rafPending = false
4592
+ var onScroll = () => {
4593
+ if (rafPending) return
4594
+ rafPending = true
4595
+ var run = () => {
4596
+ rafPending = false
4597
+ scan()
4598
+ }
4599
+ // 老宿主/测试环境没有 rAF 时退回宏任务,语义仍是「合并到下一拍」
4600
+ try {
4601
+ if (typeof window.requestAnimationFrame === 'function') window.requestAnimationFrame(run)
4602
+ else setTimeout(run, 16)
4603
+ } catch {
4604
+ rafPending = false
4605
+ scan()
4606
+ }
4607
+ }
4608
+ window.addEventListener('scroll', onScroll, { passive: true })
4006
4609
  try {
4007
4610
  // 0.9.7(P1-2)回调过滤 + maxWait。
4008
4611
  // ① 过滤:整个 document.body 的 childList 海量 mutation(流式文本、
@@ -4015,7 +4618,10 @@ window.__ModuleLoader__.load({
4015
4618
  // 这是正确性问题,不只是性能。
4016
4619
  // ③ attributeFilter 只盯 data-chat-node-key:本插件不写该属性(写的是
4017
4620
  // data-mops-seq / hidden),所以不会被自己触发成环。
4018
- var MO_SEL = '[data-chat-node-key],[data-chat-flow-kind="user"],[class*="xzv4MW_actions"],[class*="_userRow"],[data-turn-tail]'
4621
+ // ④ `data-chat-flow-kind` / `class*` 只认 **added/removed 节点**(attributeFilter
4622
+ // 不含 className 与 flow-kind,见下方 observe 选项);hash 单点见 HOST_CLS。
4623
+ var MO_SEL =
4624
+ '[data-chat-node-key],[data-chat-flow-kind="user"],[class*="' + HOST_CLS.actions + '"],[class*="_userRow"],[data-turn-tail]'
4019
4625
  var scanPendingSince = 0
4020
4626
  var scheduleScan = () => {
4021
4627
  var now = Date.now()
@@ -4100,6 +4706,8 @@ window.__ModuleLoader__.load({
4100
4706
  '.mopsUserRevert svg,.mopsUserEdit svg{width:14px;height:14px;display:block}',
4101
4707
  '.mopsUserRevert:hover,.mopsUserEdit:hover{background:var(--dsw-alias-interactive-bg-hover,rgba(128,128,128,.12));color:var(--dsw-alias-label-secondary,#6b6b70)}',
4102
4708
  '.mopsUserRevert:disabled,.mopsUserEdit:disabled{opacity:.4;cursor:default;background:transparent}',
4709
+ '.mopsUserEdit[data-mops-running="1"]{opacity:.82}',
4710
+ '.mopsUserEdit[data-mops-running="1"]:hover{opacity:1}',
4103
4711
  '.mopsUserRevert:focus-visible,.mopsUserEdit:focus-visible{outline:2px solid var(--dsw-alias-border-l2,#b8b8b8);outline-offset:1px}',
4104
4712
  // 0.18.0:用户反馈「点时间图标也会回撤」——根因不是绑定错误,而是
4105
4713
  // 我们的按钮被 appendChild 到宿主 .actions 行末尾,而该行在
@@ -4108,8 +4716,8 @@ window.__ModuleLoader__.load({
4108
4716
  // 触屏上 28px 按钮的命中区紧贴时间文本,点时间很容易滑到回滚上。
4109
4717
  // 修:给插件按钮组加一道**视觉与命中分隔**(左侧细线 + 额外间距),
4110
4718
  // 让"消息元信息(时间/复制)"和"破坏性操作"在视觉上分成两组。
4111
- '.mopsUserRevert:first-of-type{margin-left:10px;position:relative}',
4112
- '.mopsUserRevert:first-of-type::before{content:"";position:absolute;left:-9px;top:50%;transform:translateY(-50%);width:1px;height:14px;background:var(--dsw-alias-border-l1,rgba(128,128,128,.28));pointer-events:none}',
4719
+ '.mopsUserRevert[data-mops-first="1"]{margin-left:10px;position:relative}',
4720
+ '.mopsUserRevert[data-mops-first="1"]::before{content:"";position:absolute;left:-9px;top:50%;transform:translateY(-50%);width:1px;height:14px;background:var(--dsw-alias-border-l1,rgba(128,128,128,.28));pointer-events:none}',
4113
4721
  '.mopsUserActionsRow{height:28px;display:flex;align-items:center;gap:8px;margin-left:-6px}',
4114
4722
  '@media (hover:none){.mopsUserActionsRow{opacity:1}}',
4115
4723
  ].join('')
@@ -4178,6 +4786,7 @@ window.__ModuleLoader__.load({
4178
4786
  }
4179
4787
  }
4180
4788
 
4789
+ // ══ 85-sidebar · 侧栏菜单注入 ══
4181
4790
  function installSidebarOps() {
4182
4791
  if (window.__dshMessageOpsSidebarInstalled) return
4183
4792
  window.__dshMessageOpsSidebarInstalled = true
@@ -4267,17 +4876,23 @@ window.__ModuleLoader__.load({
4267
4876
  * 服务端会以 `surface replace: start seq N not found in surface` 拒绝(实测)。
4268
4877
  * 回滚的前提就是「目标在 surface 上」,所以先筛 visible。
4269
4878
  */
4270
- var lastRevertable = () => {
4271
- const cache = __peekRowsCache ? __peekRowsCache() : null
4879
+ var lastRevertable = (cacheArg, currentSidArg) => {
4880
+ // 参数可选:生产调用零参(读全局),测试可注入以便真执行会话守卫。
4881
+ const cache = cacheArg || (__peekRowsCache ? __peekRowsCache() : null)
4272
4882
  if (!cache || !Array.isArray(cache.rows)) return null
4273
- for (var i = cache.rows.length - 1; i >= 0; i--) {
4274
- var r = cache.rows[i]
4275
- // 0.11.3:必须同时排除 shadowed。只用 visible 会在「回滚刚落盘、索引还没刷新」
4276
- // 的窗口里再次选中已被遮蔽的 seq → 服务端 409
4277
- // `surface replace: start seq N not found in surface`(实测 2026-10-25)。
4278
- if (r && r.seq != null && r.visible && r.shadowed !== true) return r
4279
- }
4280
- return null
4883
+ // 0.32.2:缓存必须属于当前会话。切会话后首次取数失败时 rowsCache 仍是
4884
+ // 上一个会话(fetchRows 的 catch 不改写缓存),旧实现会把 A 的 seq 写到
4885
+ // B 的 /revert 请求上 —— B 中同号若恰是真实用户消息就会被误回撤。
4886
+ // refillComposer 早就有这条闸;/undo 是唯一漏网的读缓存入口。
4887
+ const now = bareSessionId(currentSidArg !== undefined ? currentSidArg : __currentSessionId)
4888
+ if (!now || bareSessionId(cache.sid) !== now) return null
4889
+ // 0.11.3:必须同时排除 shadowed。只用 visible 会在「回滚刚落盘、索引还没刷新」
4890
+ // 的窗口里再次选中已被遮蔽的 seq → 服务端 409
4891
+ // `surface replace: start seq N not found in surface`(实测 2026-10-25)。
4892
+ // 0.27.0:目标必须是**真实用户输入**。回撤落盘后最后一条可见节点是 marker
4893
+ // 自己(system/message),旧实现会把它当目标 → /undo 必 409;注入行
4894
+ // (role:'user' + source.kind!=='user')与助手消息同样不该成为回撤目标。
4895
+ return pickRevertTarget(cache.rows)
4281
4896
  }
4282
4897
 
4283
4898
  /** 执行 undo/redo。返回 true 表示确实动过盘。 */
@@ -4294,21 +4909,19 @@ window.__ModuleLoader__.load({
4294
4909
  * 本文件其它调用点(对话框 :403、:684、:858、:1229)传的都是带前缀的,
4295
4910
  * 只有 /undo /redo 因为先 `bareSessionId` 而传错。
4296
4911
  */
4297
- var afterWrite = (rawSid, okMsg) => {
4298
- notifyDone(okMsg)
4912
+ var afterWrite = (rawSid, okMsg, level) => {
4913
+ notifyDone(okMsg, level)
4299
4914
  // emitChanged = 作废消息读缓存 + 清 rowsCache TTL + 广播 CHANGED
4300
4915
  // (dock 重拉 / 已打标 seq 摘牌),一次写只做一次。
4301
4916
  emitChanged()
4302
- try {
4303
- if (__uiWorkspace && typeof __uiWorkspace.openSession === 'function') __uiWorkspace.openSession(rawSid)
4304
- } catch (e) {
4305
- if (window.__MOPS_DEBUG) console.warn('[message-ops] openSession failed:', e)
4306
- }
4917
+ // 0.26.0:统一走 safeOpenSession。原实现只在 __MOPS_DEBUG 下才 warn,
4918
+ // 而这段注释本身就把「静默吞掉 → 视图重建从未生效」写成了事故档案 ——
4919
+ // 现在无条件 warn(排障时不必先知道要开哪个开关)。
4920
+ safeOpenSession(rawSid, 'after-write')
4307
4921
  const bare = bareSessionId(rawSid)
4308
- for (const delay of [150, 700, 1600])
4309
- setTimeout(() => {
4310
- if (__refreshSurface) __refreshSurface(bare)
4311
- }, delay)
4922
+ // 0.25.0(手感):三连 [150,700,1600] → 立即一次(__refreshSurface 自带
4923
+ // 300ms 尾随防抖)。视图重建后的「重算隐藏」兜底必须留,只是不再白等 1.6s。
4924
+ if (__refreshSurface) __refreshSurface(bare)
4312
4925
  }
4313
4926
 
4314
4927
  /**
@@ -4413,21 +5026,22 @@ window.__ModuleLoader__.load({
4413
5026
  notifyDone(__t('undo.none') || '没有可回滚的消息', 'error')
4414
5027
  return false
4415
5028
  }
4416
- fetch('/api/message-ops/revert', {
5029
+ fetchWithTimeout('/api/message-ops/revert', {
4417
5030
  method: 'POST',
4418
5031
  headers: { 'content-type': 'application/json' },
4419
5032
  body: JSON.stringify({ sessionId: sid, seq: target.seq }),
4420
5033
  })
4421
5034
  .then(async res => {
4422
- const data = await res.json().catch(() => ({}))
4423
- if (!res.ok || !data.ok) throw new Error(data.error || 'HTTP ' + res.status)
5035
+ const r = await readOpsJson(res)
5036
+ if (!r.ok) throw opsError(r.status, r.data)
4424
5037
  // 0.11.3:立刻把本行标成已遮蔽,否则 afterWrite 的异步刷新窗里
4425
5038
  // 再点一次 /undo 仍会选中同一个 seq → 409。
4426
5039
  markRowsShadowedFrom(target.seq)
4427
- refillComposer(rawSid, target.seq) // 先回填,再重建视图(与对话框一致)
4428
- afterWrite(rawSid, __t('undo.done.undo'))
5040
+ // 与按钮路径同一收尾:先回填再重建视图;回填失败必须说出来(旧实现静默)。
5041
+ const filled = refillComposer(rawSid, target.seq)
5042
+ afterWrite(rawSid, filled ? __t('undo.done.undo') : __t('done.revertNoRefill'), filled ? undefined : 'warn')
4429
5043
  })
4430
- .catch(reason => notifyDone(__t('errorPrefix') + (reason && reason.message ? reason.message : String(reason)), 'error'))
5044
+ .catch(reason => notifyDone(errText(reason, __t('errorPrefix')), 'error'))
4431
5045
  return true
4432
5046
  }
4433
5047
 
@@ -4451,19 +5065,19 @@ window.__ModuleLoader__.load({
4451
5065
  return null
4452
5066
  }
4453
5067
  const mk = markers[markers.length - 1] // 最新一条未恢复标记
4454
- return fetch('/api/message-ops/restore', {
5068
+ return fetchWithTimeout('/api/message-ops/restore', {
4455
5069
  method: 'POST',
4456
5070
  headers: { 'content-type': 'application/json' },
4457
5071
  body: JSON.stringify({ sessionId: sid, seq: mk.seq }),
4458
5072
  }).then(async res => {
4459
- const data = await res.json().catch(() => ({}))
4460
- if (!res.ok || !data.ok) throw new Error(data.error || 'HTTP ' + res.status)
5073
+ const r = await readOpsJson(res)
5074
+ if (!r.ok) throw opsError(r.status, r.data)
4461
5075
  // afterWrite 契约:rawSid 必须带 session- 前缀(传裸 uuid 会抛
4462
5076
  // `sessions.retain: unknown session` 并被外层 catch 静默吞掉)
4463
5077
  afterWrite(rawSid, __t('undo.done.redo'))
4464
5078
  })
4465
5079
  })
4466
- .catch(reason => notifyDone(__t('errorPrefix') + (reason && reason.message ? reason.message : String(reason)), 'error'))
5080
+ .catch(reason => notifyDone(errText(reason, __t('errorPrefix')), 'error'))
4467
5081
  return true
4468
5082
  }
4469
5083
 
@@ -4541,6 +5155,7 @@ window.__ModuleLoader__.load({
4541
5155
  } catch (e) {}
4542
5156
  }
4543
5157
 
5158
+ // ══ 90-apply · 插件装配(apply / 槽注册 / __test) ══
4544
5159
  function apply(ctx) {
4545
5160
  __sessionsSvc = ctx.get('sessions')
4546
5161
  __uiWorkspace = typeof ctx.get === 'function' ? ctx.get('uiWorkspace') : null
@@ -4616,18 +5231,6 @@ window.__ModuleLoader__.load({
4616
5231
  OpsPanel,
4617
5232
  ),
4618
5233
  )
4619
- // 0.20.0:编辑并重发浮层(同族模态,order 102 排在 OpsPanel 之后 —— 两者互斥打开)
4620
- ctx.slots.inject(OVERLAY_SLOT, () =>
4621
- ctx.slots.register(
4622
- {
4623
- name: OVERLAY_SLOT,
4624
- id: EDIT_ID,
4625
- order: 102,
4626
- ...(__locale ? { locale: NS } : {}),
4627
- },
4628
- EditResendOverlay,
4629
- ),
4630
- )
4631
5234
  installSidebarOps()
4632
5235
  installUserRevertInjector()
4633
5236
  }
@@ -4639,17 +5242,43 @@ window.__ModuleLoader__.load({
4639
5242
  activityTransition,
4640
5243
  forkBoundaryBefore,
4641
5244
  writeSessionDraft,
4642
- // 0.20.0:编辑并重发的编排层(可注入 deps 真执行断言时序)
5245
+ // 0.26.0:编辑并重发的编排层 + 官方发送面(可注入 deps 真执行断言时序)
4643
5246
  sendEditAndRevert,
4644
- submitEditedText,
5247
+ promptEditedText,
5248
+ EDIT_SOURCE,
5249
+ // 0.28.0 就地编辑(替代浮层):真执行测试面
5250
+ IE_CLASS,
5251
+ openInlineEdit,
5252
+ closeInlineEdit,
5253
+ rehydrateInlineEdit,
5254
+ // 0.31.0:宿主 devkit 缺席时的自绘反馈(真执行测试用)
5255
+ notifyDone,
5256
+ // 0.32.0:Esc 分层决策 / 超时请求(真执行测试用)
5257
+ panelEscapeAction,
5258
+ fetchWithTimeout,
5259
+ setReadTimeoutForTests,
5260
+ getReadTimeoutForTests,
4645
5261
  // 0.24.0 P4:按会话隔离的 InputActions 访问面(真执行测试用)
4646
5262
  rememberInputActions,
4647
5263
  forgetInputActions,
4648
5264
  inputActionsFor,
4649
5265
  sessionKeyOf,
4650
5266
  __inputActionsBySession,
4651
- EDIT_EVENT,
4652
- EDIT_ID,
5267
+ // 0.25.0(手感):面板全文取数层(缓存 + 尾随防抖 + 单飞)的真执行测试面
5268
+ loadPanelText,
5269
+ clearPanelTextCache,
5270
+ PANEL_TEXT_DEBOUNCE_MS,
5271
+ // 0.27.0 回撤语义回归面(真机复现后抽出,见 test/revert-semantics.test.js)
5272
+ isActiveMarker,
5273
+ isRevertTarget,
5274
+ pickRevertTarget,
5275
+ revertRowsOf,
5276
+ dockRowLabel,
5277
+ dockRowText,
5278
+ dockPreviewOf,
5279
+ activeMarkers,
5280
+ // 0.32.2:/undo 的会话守卫(缓存必须属于当前会话)
5281
+ lastRevertable,
4653
5282
  },
4654
5283
  }
4655
5284
  },