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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@240xu/dsh-message-ops",
3
- "version": "0.24.0",
3
+ "version": "0.47.0",
4
4
  "description": "DSH web 插件:消息级回滚 / 删除 / 恢复 / 分叉 / 编辑重发(补 dsh 官方没有的部分)。",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -24,7 +24,8 @@
24
24
  "./client": "./src/client.js",
25
25
  "./session-file": "./src/session-file.js",
26
26
  "./package.json": "./package.json",
27
- "./ops-core": "./src/ops-core.js"
27
+ "./ops-core": "./src/ops-core.js",
28
+ "./ops-write": "./src/ops-write.js"
28
29
  },
29
30
  "engines": {
30
31
  "node": ">=23.5"
@@ -41,9 +42,12 @@
41
42
  }
42
43
  },
43
44
  "scripts": {
44
- "test": "node --check src/client.js && node --test \"test/*.test.js\""
45
+ "build:client": "node scripts/build-client.mjs",
46
+ "test": "node --check src/client.js && node --test \"test/*.test.js\"",
47
+ "prepack": "npm run build:client"
45
48
  },
46
49
  "peerDependencies": {
47
- "@deepseek-ai/dsh-tools": "^0.1.0-rc.6 || ^0.2.0-rc.1"
50
+ "@deepseek-ai/dsh-tools": "^0.1.0-rc.6 || ^0.2.0-rc.1 || ^0.2.2-rc.5 || ^0.2.3-alpha.3",
51
+ "@deepseek-ai/dsh": "^0.1.0-rc.6 || ^0.2.0-rc.1 || ^0.2.2-rc.5 || ^0.2.3-alpha.3"
48
52
  }
49
53
  }
package/src/auth.js ADDED
@@ -0,0 +1,274 @@
1
+ /**
2
+ * HTTP 信任围栏与浏览器 cookie 鉴权(0.28.0 从 ops-core.js 拆出)。
3
+ *
4
+ * 为什么单独成文件:ops-core 是「纯逻辑规划层」,而这里是**安全边界**——
5
+ * 混在一起会让读代码的人以为回撤规划与鉴权是一回事,也让安全评审必须翻过
6
+ * 上千行规划代码。职责边界:本文件只回答「这个请求能不能进来」。
7
+ *
8
+ * 既有导入面不变:ops-core.js 仍转出这些名字。
9
+ */
10
+ import { createHash, createHmac, timingSafeEqual } from 'node:crypto'
11
+
12
+ // ---------------------------------------------------------------------------
13
+ // HTTP 信任围栏(评审 P0):插件经 webServer.register 挂载的路由不经过宿主
14
+ // connection RPC 面的 isTrustedApiRequest 围栏(dsh-src
15
+ // packages/client/connection/src/api-request-trust.ts),必须自建。三层:
16
+ // 1. Host 必须是回环地址 → 挡 DNS rebinding(伪造 Host 的攻击页直接 403);
17
+ // 2. sec-fetch-site: cross-site 拒绝 → 挡跨站浏览器请求;
18
+ // 3. Origin 存在时必须与 Host 同源 → 挡其余跨站 POST/GET。
19
+ // 非浏览器客户端(curl / Agent 工具 / 宿主自身)不带 sec-fetch-site 与
20
+ // Origin,且 Host 均为回环 → 天然放行,无需 token。
21
+ // ---------------------------------------------------------------------------
22
+
23
+ function headerOf(headers, name) {
24
+ const value = headers && headers[name]
25
+ return typeof value === 'string' ? value : undefined
26
+ }
27
+
28
+ function parseAuthority(authority) {
29
+ try {
30
+ return new URL(`http://${authority}`)
31
+ } catch {
32
+ return undefined
33
+ }
34
+ }
35
+
36
+ function isLoopbackHostname(hostname) {
37
+ if (hostname === 'localhost' || hostname === '[::1]') return true
38
+ const parts = hostname.split('.')
39
+ return parts.length === 4 && parts[0] === '127' && parts.every(p => /^\d{1,3}$/.test(p) && Number(p) <= 255)
40
+ }
41
+
42
+ /** 与 slv-check 同款的信任判定(回环 Host + 非 cross-site + Origin 同源)。 */
43
+ export function isTrustedApiRequest(req) {
44
+ const host = headerOf(req && req.headers, 'host')
45
+ if (host === undefined) return false
46
+ const hostUrl = parseAuthority(host)
47
+ if (hostUrl === undefined) return false
48
+ if (!isLoopbackHostname(hostUrl.hostname)) return false
49
+ if (headerOf(req.headers, 'sec-fetch-site') === 'cross-site') return false
50
+ const origin = headerOf(req.headers, 'origin')
51
+ if (origin === undefined) return true
52
+ try {
53
+ return new URL(origin).host === hostUrl.host
54
+ } catch {
55
+ return false
56
+ }
57
+ }
58
+
59
+ /**
60
+ * 写操作 CSRF 防护:Content-Type 必须 application/json(允许 ;charset=… 后缀)。
61
+ * 为何不需要一次性 token:浏览器对**所有** POST(含 text/plain 绕预检的
62
+ * 那条路)都会附带 Origin 头,第 3 层 Origin 同源校验已覆盖跨站 POST;
63
+ * Content-Type 约束是纵深防御(阻止非 JSON 客户端误写),而自定义头
64
+ * (如 X-Requested-With)天然触发 CORS 预检,与 Origin 校验等价,故
65
+ * 引入 token 只增加握手复杂度而不增加安全性——围栏已足够(论证记录于此)。
66
+ */
67
+ export function isJsonContentType(req) {
68
+ const ct = headerOf(req && req.headers, 'content-type') || ''
69
+ return ct.split(';')[0].trim().toLowerCase() === 'application/json'
70
+ }
71
+
72
+ // ---------------------------------------------------------------------------
73
+ // 0.10.8 · web 前端鉴权对齐(GET 也要过宿主的浏览器认证门)
74
+ // ---------------------------------------------------------------------------
75
+ // 宿主侧实况(全局 dsh 0.2.0-rc.2 的 dsh-client-connection/lib/index.js):
76
+ // admit(request)(:742-749)对每一条 /api 前缀请求(含 GET)都要求
77
+ // browserAuth 认证——根 token 只在 authorizeIndex 换 cookie:GET /<token>
78
+ // → 铸 HttpOnly+SameSite=Strict 的签名 cookie(名 = dsh-auth-<b64url(
79
+ // sha256(authority))>,载荷 v{1|2}.<b64url(json)>.<b64url(hmac-sha256)>
80
+ // secret 32 字节,存 credentials 记录 client-connection/browser-session)
81
+ // → 重定向 ./;此后每条 /api 都凭 cookie 过 admit,无 cookie → 401。
82
+ // 前端取数是同源 fetch(默认凭证)——cookie 自动随行,**全程没有
83
+ // Authorization 头,也没有 ?token= 打到 /api**。
84
+ // 插件路由此前只跑 isTrustedApiRequest(该围栏自述 "is not an auth layer"),
85
+ // 同机无凭证进程 GET 即可整卷消息/全文(宿主同条件 401——审计缺口)。
86
+ // 对齐修法(选型理由见报告):前端本来就带 cookie → 围栏里**校验同款
87
+ // cookie**;secret 经 credentials 服务的合法读法取(no-op modifyRecord,
88
+ // 勿写勿落盘)。无 credentials 服务 = 老宿主 → 保留旧围栏;有服务但记录
89
+ // 缺失/格式升级 → **fail-closed** 并告警,避免永久 allow-all。
90
+ // 非浏览器 GET(curl 等)从 200 变 401 = 与宿主对齐的有意行为变化。
91
+
92
+ const AUTH_RECORD_KEY = 'client-connection/browser-session'
93
+ const AUTH_COOKIE_PREFIX = 'dsh-auth-'
94
+ const AUTH_STORED_SECRET_VERSION = 1
95
+ const AUTH_SECRET_BYTES = 32
96
+
97
+ const BASE64URL_PATTERN = /^[A-Za-z0-9_-]+$/u
98
+
99
+ function encodeBase64Url(value) {
100
+ return Buffer.from(value).toString('base64').replaceAll('+', '-').replaceAll('/', '_').replace(/=+$/u, '')
101
+ }
102
+
103
+ function decodeBase64Url(value) {
104
+ if (!BASE64URL_PATTERN.test(value) || value.length % 4 === 1) return undefined
105
+ const padding = '='.repeat((4 - (value.length % 4)) % 4)
106
+ const decoded = Buffer.from(value.replaceAll('-', '+').replaceAll('_', '/') + padding, 'base64')
107
+ return encodeBase64Url(decoded) === value ? decoded : undefined
108
+ }
109
+
110
+ /** 宿主 requestAudience 的口径:HTTP 用 url.host;TLS 用 url.origin。插件
111
+ * 读不到监听面协议,两种拼写都试(名字与载荷 authority 用**同一个**拼写
112
+ * 配对校验,跨拼写伪造照样被拒)。 */
113
+ function cookieAuthorityCandidates(hostHeader) {
114
+ try {
115
+ const url = new URL(`http://${hostHeader}`)
116
+ return [url.host, `https://${url.host}`]
117
+ } catch {
118
+ return []
119
+ }
120
+ }
121
+
122
+ /** 宿主 cookieValue:按分号切段取**第一个**同名区的值(无解码语义)。 */
123
+ function cookieValue(rawCookie, name) {
124
+ if (typeof rawCookie !== 'string') return undefined
125
+ for (const segment of rawCookie.split(';')) {
126
+ const at = segment.indexOf('=')
127
+ if (at === -1 || segment.slice(0, at).trim() !== name) continue
128
+ return segment.slice(at + 1).trim()
129
+ }
130
+ return undefined
131
+ }
132
+
133
+ /** 宿主 decodeCookie 的镜像:三段结构 + HMAC + 载荷形状(v1 浏览器 peer / v2 带操作者 id)。 */
134
+ function decodeBrowserAuthCookie(value, secret) {
135
+ const parts = value.split('.')
136
+ const [version, body, encodedSignature] = parts
137
+ if (parts.length !== 3 || (version !== 'v1' && version !== 'v2') || body === undefined || encodedSignature === undefined) return undefined
138
+ const actualSignature = decodeBase64Url(encodedSignature)
139
+ if (actualSignature === undefined) return undefined
140
+ const expectedSignature = createHmac('sha256', secret).update(body).digest()
141
+ if (actualSignature.length !== expectedSignature.length || !timingSafeEqual(actualSignature, expectedSignature)) return undefined
142
+ const bodyBytes = decodeBase64Url(body)
143
+ if (bodyBytes === undefined) return undefined
144
+ let decoded
145
+ try {
146
+ decoded = JSON.parse(bodyBytes.toString('utf8'))
147
+ } catch {
148
+ return undefined
149
+ }
150
+ if (!decoded || typeof decoded !== 'object' || Array.isArray(decoded)) return undefined
151
+ if (decoded.version !== 1 && decoded.version !== 2) return undefined
152
+ if (version !== `v${decoded.version}`) return undefined
153
+ if (typeof decoded.authority !== 'string' || decoded.authority === '') return undefined
154
+ if (typeof decoded.issuedAt !== 'number' || !Number.isSafeInteger(decoded.issuedAt)) return undefined
155
+ if (typeof decoded.expiresAt !== 'number' || !Number.isSafeInteger(decoded.expiresAt)) return undefined
156
+ const payload = { version: decoded.version, authority: decoded.authority, issuedAt: decoded.issuedAt, expiresAt: decoded.expiresAt }
157
+ if (decoded.version === 1) return payload
158
+ if (typeof decoded.id !== 'string' || decoded.id.length === 0) return undefined
159
+ return { ...payload, id: decoded.id }
160
+ }
161
+
162
+ /**
163
+ * 校验请求是否携带**有效**的宿主浏览器认证 cookie。
164
+ * @returns 载荷(通过)或 undefined(未认证)。返回值只当布尔用。
165
+ */
166
+ export function browserAuthPayload(req, secret) {
167
+ if (secret == null) return undefined
168
+ const host = headerOf(req && req.headers, 'host')
169
+ if (host === undefined) return undefined
170
+ const rawCookie = headerOf(req.headers, 'cookie')
171
+ if (rawCookie === undefined) return undefined
172
+ const now = Date.now()
173
+ for (const authority of cookieAuthorityCandidates(host)) {
174
+ const value = cookieValue(rawCookie, AUTH_COOKIE_PREFIX + encodeBase64Url(createHash('sha256').update(authority).digest()))
175
+ if (value === undefined) continue
176
+ const payload = decodeBrowserAuthCookie(value, secret)
177
+ // payload.authority 与产生名字的同一个拼写配对(宿主同样的绑定语义)。
178
+ if (payload === undefined || payload.authority !== authority) continue
179
+ // 宿主 authenticate(:555 附近) 的时效三条;expiresAt-issuedAt 的 maxAge
180
+ // 窗口不复制(host 可配 cookieMaxAgeDays,插件复制会误杀合法长龄 cookie)。
181
+ if (payload.issuedAt > now || payload.expiresAt <= now || payload.expiresAt <= payload.issuedAt) continue
182
+ return payload
183
+ }
184
+ return undefined
185
+ }
186
+
187
+ /**
188
+ * 经 credentials 服务读宿主 BrowserAuth 签名 secret。**唯一读法**:
189
+ * no-op modifyRecord(mutate 返回 undefined = 记录未动、返回 current),
190
+ * 不落盘不经 argv。宿主无该成分 / 记录缺失 / 格式或长度不符 → null。
191
+ * 调用方据此决定老宿主降级还是 fail-closed(有 credentials 服务即后者)。
192
+ * @param {object|undefined} credentials ctx.get("credentials")
193
+ * @returns {Promise<Buffer|null>}
194
+ */
195
+ export async function loadBrowserAuthSecret(credentials) {
196
+ if (!credentials || typeof credentials.modifyRecord !== 'function') return null
197
+ let record
198
+ try {
199
+ record = await credentials.modifyRecord(AUTH_RECORD_KEY, async () => undefined)
200
+ } catch {
201
+ return null
202
+ }
203
+ if (record === undefined || record === null || typeof record !== 'object' || record.kind !== 'grant') return null
204
+ const payload = record.payload
205
+ if (!payload || typeof payload !== 'object' || payload.version !== AUTH_STORED_SECRET_VERSION) return null
206
+ if (typeof payload.secret !== 'string') return null
207
+ const secret = decodeBase64Url(payload.secret)
208
+ if (!secret || secret.length !== AUTH_SECRET_BYTES) return null
209
+ return secret
210
+ }
211
+
212
+ // 进程级 memo:secret 一次命中就终身持有(宿主 create 只在缺失时铸新记录,
213
+ // 正常进程内不会换代);探测失败 10s 内不重试,401 风暴不会打爆 credential 锁。
214
+ const WEB_AUTH_RETRY_MS = 10_000
215
+ let __webAuthSecret = null
216
+ let __webAuthProbeAt = 0
217
+ let __webAuthProbe = null
218
+ let __webAuthWarned = false
219
+
220
+ /** 测试钩子:直接注入/清除 secret,绕开 credentials 服务。 */
221
+ export function _setWebAuthSecret(secret) {
222
+ __webAuthSecret = secret
223
+ }
224
+ export function _resetWebAuth() {
225
+ __webAuthSecret = null
226
+ __webAuthProbeAt = 0
227
+ __webAuthProbe = null
228
+ __webAuthWarned = false
229
+ }
230
+
231
+ /**
232
+ * 围栏的鉴权半段:取活跃 secret(含单飞探测与 10s 失败 memo)。
233
+ * secret 存在但请求未携有效 cookie → false(路由层回 401);
234
+ * 无 credentials 服务(老宿主)→ true = 旧围栏;有服务但记录不可读 → false(fail-closed)。
235
+ * @param {object|undefined} ctx 插件 ctx(get("credentials"))
236
+ * @param {object} req http 请求
237
+ */
238
+ export async function webAuthGate(ctx, req) {
239
+ if (__webAuthSecret !== null) {
240
+ return browserAuthPayload(req, __webAuthSecret) !== undefined
241
+ }
242
+
243
+ let credentials = null
244
+ try {
245
+ credentials = ctx && typeof ctx.get === 'function' ? ctx.get('credentials') : null
246
+ } catch {
247
+ /* legacy ctx */
248
+ }
249
+ if (!credentials || typeof credentials.modifyRecord !== 'function') return true
250
+
251
+ const now = Date.now()
252
+ if (__webAuthProbe === null && now - __webAuthProbeAt >= WEB_AUTH_RETRY_MS) {
253
+ __webAuthProbeAt = now
254
+ __webAuthProbe = loadBrowserAuthSecret(credentials)
255
+ .then(secret => {
256
+ __webAuthSecret = secret
257
+ if (secret === null && !__webAuthWarned) {
258
+ __webAuthWarned = true
259
+ console.warn(
260
+ '[message-ops] BrowserAuth cookie 鉴权已启用但 `client-connection/browser-session` 记录不可读' +
261
+ '——GET 鉴权 fail-closed;请检查该记录是否存在',
262
+ )
263
+ }
264
+ return secret
265
+ })
266
+ .finally(() => {
267
+ __webAuthProbe = null
268
+ })
269
+ }
270
+
271
+ if (__webAuthProbe === null) return false
272
+ const secret = await __webAuthProbe
273
+ return secret !== null && browserAuthPayload(req, secret) !== undefined
274
+ }
@@ -0,0 +1,284 @@
1
+ // ══ 00-core · 常量 / 小工具 / 消息读缓存 ══
2
+ const React = require('react')
3
+ const { useCallback, useEffect, useMemo, useRef, useState } = React
4
+ const SLOT = 'conversation.session.header.actions'
5
+ const ROW_ID = 'message-ops'
6
+ const OVERLAY_SLOT = 'shell.overlay'
7
+ const INPUT_DOCK_SLOT = 'conversation.input.dock'
8
+ const INPUT_DOCK_ID = 'message-ops-revert-dock'
9
+ const DIALOG_ID = 'message-ops-dialog'
10
+ const EVENT = 'dsh-message-ops:open'
11
+ /**
12
+ * 宿主 CSS-module hash(**单点**,审计 §3.1)。
13
+ *
14
+ * ⚠️ 这是本插件跨版本最脆的一处依赖:这些类名是宿主 CSS module 编译产物,
15
+ * **每个版本都可能变**(README 事故:0.9.0 写死 `Sixlwa_*` 前缀 → 宿主换成
16
+ * `EvIC1a_*` → 锚点集为空 → 按钮拿不到 seq → 点击必失败;`_flowItem` 当兜底
17
+ * → 把官方 turn-tail 当用户消息挂回滚按钮)。现在写法已修正为
18
+ * 「**稳定属性 `data-chat-flow-kind` 优先 + hash-immune 后缀 `_userRow` 兜底**」,
19
+ * 全 hash 只在宿主确实提供、且无法用稳定属性表达的地方用。
20
+ *
21
+ * 新增候选**只加这里**,不许在各调用点各写一份 —— 否则宿主一升级,
22
+ * 4 处漏 1 处 = 「一半按钮挂得上、一半挂不上」。
23
+ * 只收录**真有消费点**的 hash:`Sixlwa_userStack`/`EvIC1a_flowItem`/`TS9iAW_*`
24
+ * 在本文件没有任何全 hash 消费(前两者靠 `_userStack`/`_flowItem` 后缀与稳定属性,
25
+ * 后者宿主换过一轮、我们根本没碰 TurnTailNodeView),收进来就是新的死配置。
26
+ */
27
+ const HOST_CLS = {
28
+ actions: 'xzv4MW_actions', // MessageIconActions.module.css(官方用户消息动作行)
29
+ userRow: 'Sixlwa_userRow', // MessageItem.module.css(用户消息容器)
30
+ }
31
+ // 0.5.2(P2):回滚/恢复成功后广播 → RevertDock 重拉标记(否则 dock 只在切会话时刷新)
32
+ const CHANGED_EVENT = 'dsh-message-ops:changed'
33
+ // 0.33.3:会话切换广播(dock 渲染时发现 sessionId 变化 → 面板据此关闭,
34
+ // 避免界面上已是新会话、面板还在对旧会话执行 revert/delete)。
35
+ const SESSION_EVENT = 'dsh-message-ops:session-changed'
36
+ // 0.9.7(P0-2 读合并):一次写操作会同时触发「写后立即一次刷新」+
37
+ // RevertDock 的 CHANGED 重拉 + openSession 后 MO 调度的 scan(5~6 次 GET)。
38
+ // 同一会话在此窗口内的请求共享同一个 promise。
39
+ // 0.25.0(手感):尾随兜底刷新由 __refreshSurface 的 300ms 防抖承担,且它拉取前
40
+ // 会先 invalidateMessagesMemo() 强制走真网络 —— 所以本窗口值不再与刷新时机挂钩。
41
+ const MSG_COALESCE_MS = 1000
42
+ // 0.39.3:读路径统一超时口径(原来只有写路径走 fetchWithTimeout,后端挂起时
43
+ // 列表/搜索/详情/回收站会永久 loading)。测试可调小(client-cov 审计 P3-3)。
44
+ var __readTimeoutMs = 15000
45
+ var setReadTimeoutForTests = ms => {
46
+ __readTimeoutMs = Number.isSafeInteger(ms) && ms > 0 ? ms : 15000
47
+ }
48
+ var getReadTimeoutForTests = () => __readTimeoutMs
49
+ var __messagesMemo = { url: null, at: 0, p: null, settled: false }
50
+ var invalidateMessagesMemo = () => {
51
+ __messagesMemo = { url: null, at: 0, p: null, settled: false }
52
+ }
53
+
54
+ /**
55
+ * 统一读 `/api/message-ops/*` 响应体(审计 §2.4 单点)。
56
+ *
57
+ * 改前有**三套**写法:`res.json().catch(() => null)`(6 处)、
58
+ * `.catch(() => ({}))`(2 处)、`try { ... } catch {}`(2 处)。其中
59
+ * `catch(() => null)` 把「服务端返回非 JSON 的 500 页面」与「返回了 JSON 但
60
+ * `ok:false`」压成同一个 `null` → 真正的 `data.error` 丢了 → 写操作
61
+ * (revert / restore)的用户可见文案坍缩成 `HTTP 500`,看不到「会话正在运行」
62
+ * 这类真原因。
63
+ *
64
+ * 本函数**只负责读**:恒返回对象(解析失败 / 空 body = `{}`),**绝不抛、绝不
65
+ * null** —— 调用方才能统一按 `data.error || 'HTTP ' + status` 拼文案。
66
+ * 成功判定统一走 `ok`(HTTP 2xx **且** 业务 `data.ok === true`,服务端所有
67
+ * 路由成功都回 `{ ok: true, ... }`)。
68
+ *
69
+ * ⚠️ 它**不**替代 fetch、不判 409、不碰 AbortController —— `setTarget(running:true)`
70
+ * 这类组件语义分支仍留在各调用点(审计 §6.1:万能 `fetchOpsJson` 不值得抽)。
71
+ *
72
+ * @returns {Promise<{ok: boolean, status: number, data: object}>}
73
+ */
74
+ var readOpsJson = async res => {
75
+ let data = null
76
+ try {
77
+ data = await res.json()
78
+ } catch {
79
+ /* 非 JSON 响应(网关 HTML 500 页 / 空 body):按空对象处理,别丢 round-trip */
80
+ }
81
+ if (!data || typeof data !== 'object') data = {}
82
+ return { ok: res.ok === true && data.ok === true, status: Number(res.status) || 0, data }
83
+ }
84
+
85
+ /**
86
+ * 把任意 catch 值转成用户可读文案(审计 §3.4 单点:原先同一表达式写 13 遍)。
87
+ *
88
+ * @param reason - catch 到的任意值(Error / string / undefined)
89
+ * @param prefix - 前置文案(通常是 `t('errorPrefix')` / `t('panel.loadFail')`)
90
+ */
91
+ var errText = (reason, prefix) => String(prefix || '') + (reason && reason.message ? reason.message : String(reason))
92
+
93
+ /** 统一失败出口:服务端文案优先,退 `HTTP <status>`(`status` 为 0 时退 `?`)。 */
94
+ // 0.38.0:必须把 HTTP 状态挂在错误对象上 —— 调用方(dock 的 409/404 分支)
95
+ // 靠 `reason.status` 判别「标记已失效 / 会话已不存在」。旧实现只留 message,
96
+ // 于是 0.36.2 的「404 摘行并隐藏」永远走不到(实测:dock 留着一个点了就报错的死行)。
97
+ var opsError = (status, data) => {
98
+ const err = new Error((data && data.error) || 'HTTP ' + (status || '?'))
99
+ if (Number.isFinite(status)) err.status = status
100
+ if (data && typeof data === 'object') err.data = data
101
+ return err
102
+ }
103
+ const SYNTHETIC_TURN_STYLE_ID = 'dsh-message-ops-synthetic-turn-hide'
104
+ // 0.32.2:turn 号每个会话都从 1 起,旧的全局规则没有会话维度 —— 切会话后
105
+ // 在新会话首次取数前,旧规则会把 B 的同号 turn-process 行误藏。sid 变化即
106
+ // 丢弃旧规则,再由调用方按新会话数据重算。
107
+ let syntheticStyleSid = null
108
+ const syncSyntheticTurnStyle = (messages, sid) => {
109
+ if (typeof document === 'undefined' || !document.head) return
110
+ const key = String(sid || '')
111
+ if (key !== syntheticStyleSid) {
112
+ syntheticStyleSid = key
113
+ const stale = document.getElementById(SYNTHETIC_TURN_STYLE_ID)
114
+ if (stale) stale.remove()
115
+ }
116
+ const turns = new Set()
117
+ for (const m of messages || []) {
118
+ if (m && m.syntheticTurn === true && Number.isSafeInteger(m.turn)) turns.add(m.turn)
119
+ }
120
+ let tag = document.getElementById(SYNTHETIC_TURN_STYLE_ID)
121
+ if (turns.size === 0) {
122
+ if (tag) tag.remove()
123
+ return
124
+ }
125
+ if (!tag) {
126
+ tag = document.createElement('style')
127
+ tag.id = SYNTHETIC_TURN_STYLE_ID
128
+ document.head.appendChild(tag)
129
+ }
130
+ tag.textContent = Array.from(turns)
131
+ .map(turn => '[data-chat-flow-kind="turn-process"][data-chat-turn="' + turn + '"]{display:none!important}')
132
+ .join('\n')
133
+ }
134
+ /**
135
+ * 0.25.0(手感)面板全文取数层:缓存 + 尾随防抖 + 单飞。
136
+ *
137
+ * 改前:面板 `pick` 每选中一条就直连一次 `GET /api/message-ops/text`,
138
+ * 无缓存、无防抖 —— 用 ↑/↓ 连续划过列表时按条发请求(服务端每条都要
139
+ * 解析一次会话日志),而用户真正停下来看的只有最后那一条;回看同一
140
+ * seq 也照样重打一遍。
141
+ * 改后:① 命中过的 `sid|seq` 零请求;② 150ms 尾随防抖,快速划过时只发
142
+ * 停下来的那一条;③ 同 key 在途请求共享同一个 promise(不重复发)。
143
+ *
144
+ * 失效:`emitChanged()`(任何写操作后全文都可能变)清空整张表;缓存键
145
+ * 带 sessionId,切会话天然隔离。**只缓存成功拿到的非空全文** —— 失败
146
+ * 不缓存,否则一次网络抖动会把详情永久钉在 snippet 上(MED-5 红线:
147
+ * snippet 不许冒充原文,失败时由调用方回退并保持「这不是全文」的语义)。
148
+ *
149
+ * 0.46.0(client-cov P3-1):返回值除「全文 / null(真失败)」外,多了两个
150
+ * **非失败终态哨兵**:被 `clearPanelTextCache()` 作废(写操作后原文可能已变)
151
+ * 与读请求超时。旧实现把作废也收成 `null`,于是「一次请求都没发」的详情区
152
+ * 会误报「原文读取失败」。用哨兵而不是 `AbortError` 的原因:超时本身就是
153
+ * `AbortError`,取消若也用同一个错误名就无法再区分(超时文案必须保留)。
154
+ */
155
+ const PANEL_TEXT_DEBOUNCE_MS = 150
156
+ const PANEL_TEXT_CANCELLED = Object.freeze({ cancelled: true })
157
+ const PANEL_TEXT_TIMEOUT = Object.freeze({ timeout: true })
158
+ var __panelTextCache = new Map()
159
+ /** key → 单飞项(含 promise 与结算函数);防抖窗口内也登记,取消时按此结算。 */
160
+ var __panelTextInflight = new Map()
161
+ /** 最近一次尚未发出请求的防抖项;被更新的一次选择取代时以 null 收尾。 */
162
+ var __panelTextPending = null
163
+ /** 从单飞表摘掉自己(可能已被 clear 清空,或被同 key 的新请求取代)。 */
164
+ const dropPanelTextEntry = (key, entry) => {
165
+ if (__panelTextInflight.get(key) === entry) __panelTextInflight.delete(key)
166
+ }
167
+ const clearPanelTextCache = () => {
168
+ __panelTextCache.clear()
169
+ const dropped = Array.from(__panelTextInflight.values())
170
+ __panelTextInflight.clear()
171
+ if (__panelTextPending) {
172
+ clearTimeout(__panelTextPending.timer)
173
+ __panelTextPending = null
174
+ }
175
+ // 写操作作废在途请求:结算为「已取消」而不是 null(null 在调用点代表真失败)。
176
+ for (const entry of dropped) entry.cancel()
177
+ }
178
+ var loadPanelText = (sessionId, seq) => {
179
+ const sid = String(sessionId == null ? '' : sessionId)
180
+ if (!sid || seq == null) return Promise.resolve(null)
181
+ const key = sid + '|' + String(seq)
182
+ const hit = __panelTextCache.get(key)
183
+ if (hit != null) return Promise.resolve(hit)
184
+ const inflight = __panelTextInflight.get(key)
185
+ if (inflight) return inflight.promise
186
+ // 尾随防抖:被更新的一次选择取代时,上一次的 promise 以 null 收尾
187
+ // (调用方本来就按 detailReq 竞态序号丢弃过期结果;这不算「取消」,否则
188
+ // 每次划动都会触发一次重取)。同时撤回单飞登记,失败态不许占坑。
189
+ if (__panelTextPending) {
190
+ const prev = __panelTextPending
191
+ __panelTextPending = null
192
+ clearTimeout(prev.timer)
193
+ prev.discard()
194
+ }
195
+ let settle = null
196
+ const entry = {
197
+ settled: false,
198
+ promise: new Promise(resolve => {
199
+ settle = resolve
200
+ }),
201
+ settle(outcome) {
202
+ if (this.settled) return
203
+ this.settled = true
204
+ dropPanelTextEntry(key, this)
205
+ settle(outcome)
206
+ },
207
+ discard() {
208
+ this.settle(null)
209
+ },
210
+ cancel() {
211
+ this.settle(PANEL_TEXT_CANCELLED)
212
+ },
213
+ }
214
+ __panelTextInflight.set(key, entry)
215
+ const timer = setTimeout(() => {
216
+ __panelTextPending = null
217
+ const url = '/api/message-ops/text?sessionId=' + encodeURIComponent(sid) + '&seq=' + encodeURIComponent(seq)
218
+ fetchWithTimeout(url, undefined, __readTimeoutMs)
219
+ .then(readOpsJson)
220
+ .then(r => {
221
+ if (!r.ok) throw opsError(r.status, r.data)
222
+ const full = typeof r.data.text === 'string' && r.data.text !== '' ? r.data.text : null
223
+ // 已被作废的请求晚到也不许回填缓存:那份全文可能是写操作前的旧数据。
224
+ if (full != null && !entry.settled) __panelTextCache.set(key, full)
225
+ return full
226
+ })
227
+ .catch(reason => {
228
+ // 只有超时是 AbortError;取消走哨兵,不落在这条分支。
229
+ if (reason && (reason.name === 'AbortError' || reason.code === 'ABORT_ERR')) return PANEL_TEXT_TIMEOUT
230
+ return null
231
+ })
232
+ .then(outcome => entry.settle(outcome))
233
+ }, PANEL_TEXT_DEBOUNCE_MS)
234
+ __panelTextPending = { timer, discard: () => entry.discard() }
235
+ return entry.promise
236
+ }
237
+ const emitChanged = () => {
238
+ // 数据变了:连同本地缓存一起作废(否则 8s TTL 会让 openSession 后的
239
+ // scan 拿旧 payload 重算隐藏 = 「回滚了但界面没变」)。
240
+ clearPanelTextCache()
241
+ invalidateMessagesMemo()
242
+ if (__peekRowsCache) {
243
+ const c = __peekRowsCache()
244
+ if (c) c.at = 0
245
+ }
246
+ try {
247
+ window.dispatchEvent(new CustomEvent(CHANGED_EVENT))
248
+ } catch {
249
+ /* noop */
250
+ }
251
+ }
252
+ const NS = 'dsh-message-ops'
253
+
254
+ /**
255
+ * GET /api/message-ops/messages 的唯一出口(0.9.7 读合并)。
256
+ * - 并发调用共享同一个 promise;
257
+ * - 已结算的响应在 MSG_COALESCE_MS 内复用(一次写操作的 5~6 路重拉 → 1~2 次网络);
258
+ * - 只在 `ok:true` 时才留窗口:失败/非 2xx 立刻作废,免得把后续重试也吃掉;
259
+ * - 尾随兜底刷新(`__refreshSurface` 的 300ms 防抖)自己先 `invalidateMessagesMemo()`
260
+ * 再拉,保证是真网络。
261
+ */
262
+ var fetchMessagesJson = rawUrl => {
263
+ // 归一 sessionId 写法:本文件有的调用方传 `session-xxx`(dock / 对话框),
264
+ // 有的传裸 uuid(fetchRows / /redo)。不归一就是两个缓存槽,合并直接失效。
265
+ // 服务端两种写法都认(index.js "uuid or session-<uuid> form")。
266
+ const url = String(rawUrl).replace(/([?&]sessionId=)session-/, '$1')
267
+ const m = __messagesMemo
268
+ if (m.url === url && m.p && (!m.settled || Date.now() - m.at < MSG_COALESCE_MS)) return m.p
269
+ const entry = { url, at: Date.now(), p: null, settled: false }
270
+ entry.p = fetchWithTimeout(url, undefined, __readTimeoutMs)
271
+ .then(readOpsJson)
272
+ .then(r => {
273
+ if (!r.ok) throw opsError(r.status, r.data)
274
+ entry.settled = true
275
+ entry.at = Date.now()
276
+ return r.data
277
+ })
278
+ .catch(e => {
279
+ if (__messagesMemo === entry) invalidateMessagesMemo()
280
+ throw e
281
+ })
282
+ __messagesMemo = entry
283
+ return entry.p
284
+ }