@240xu/dsh-message-ops 0.9.6 → 0.10.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.
@@ -0,0 +1,259 @@
1
+ /**
2
+ * 0.9.7 客户端性能改动的**红线锁**。
3
+ *
4
+ * 这些断言来自只读性能审计,每一条都对应一个「改回去就会复发」的 bug。
5
+ * 与 client-p0-locks 一样:client.js 执行覆盖为 0,只能锁源码结构。
6
+ */
7
+ import test from 'node:test'
8
+ import assert from 'node:assert/strict'
9
+ import { readFileSync } from 'node:fs'
10
+ import { fileURLToPath } from 'node:url'
11
+ import { dirname, join } from 'node:path'
12
+
13
+ const src = readFileSync(join(dirname(fileURLToPath(import.meta.url)), '..', 'src', 'client.js'), 'utf8')
14
+
15
+ // ═══════════════════════════════════════════════════════════════════════════
16
+ // P2-1 · ensureAssign 三签名门控 + 藏行幂等跳写
17
+ // ═══════════════════════════════════════════════════════════════════════════
18
+ test('P2-1:assignSeqs 有三签名门控(dataSig / domSig / anchorSig)', () => {
19
+ const ea = src.match(/var ensureAssign = \(sid\) => fetchRows\(sid\)\.then\(\(cache\) => \{[\s\S]*?\n {6}\}\)/)
20
+ assert.ok(ea, '找不到 ensureAssign')
21
+ const body = ea[0]
22
+ // ① dataSig = idx.total / shadowed.size / visibleTurns.size
23
+ assert.ok(/idx\.total \+ '\/' \+ idx\.shadowed\.size \+ '\/' \+ idx\.visibleTurns\.size/.test(body), '缺 dataSig')
24
+ // ② domSig = transcript 行数
25
+ assert.ok(/rows\.length/.test(body), '缺 domSig')
26
+ // ③ anchorSig = 每个 user 块的 node-key + 打标状态
27
+ assert.ok(/sigOf\(sid, dataSig, rows\.length, anchors\)/.test(body), '缺签名组装')
28
+ assert.ok(/var anchorSigOf = \(anchors\) => \{/.test(src), '缺 anchorSig 生成器')
29
+ const as = src.indexOf('var anchorSigOf')
30
+ assert.ok(as >= 0 && /getAttribute\('data-mops-seq'\)/.test(src.slice(as, as + 600)),
31
+ 'anchorSig 必须包含打标状态(宿主重建块 / CHANGED 摘牌要能被发现)')
32
+ assert.ok(/if \(before !== assignSig\) \{/.test(body), '门控条件缺失 —— 会退回每次全量改写')
33
+ assert.ok(/assignSeqs\(sid, cache, anchors\)/.test(body), 'assignSeqs 必须在门控内')
34
+ // 会话 id 也必须进签名,否则切会话后签名可能撞车
35
+ assert.ok(/var sigOf = \(sid, dataSig, rowsLen, anchors\) =>\s*bareSessionId\(sid\) \+ '\|'/.test(src),
36
+ '签名里没带 sid')
37
+ })
38
+
39
+ test('P2-1 红线:applySurfaceVisibility 保持无条件执行(在门控 if 之外)', () => {
40
+ const ea = src.match(/var ensureAssign = \(sid\) => fetchRows\(sid\)\.then\(\(cache\) => \{[\s\S]*?\n {6}\}\)/)
41
+ assert.ok(ea, '找不到 ensureAssign')
42
+ const body = ea[0]
43
+ assert.ok(/\}\n {8}applySurfaceVisibility\(rows, idx\)/.test(body),
44
+ '藏行必须无条件跑 —— 这是 0.9.6 修的核心,砍成条件执行 = 隐藏不更新')
45
+ assert.ok(!/if\s*\([^\n]*\)\s*applySurfaceVisibility/.test(body), '不许包进任何 if')
46
+ })
47
+
48
+ test('P2-1:藏行改成幂等跳写(判据/时机不变,只省重复 DOM 写)', () => {
49
+ // 目标态 ≠ 当前态才写
50
+ assert.ok(/row\.getAttribute\('hidden'\) !== 'until-found'/.test(src), 'hidden 写入不是幂等的')
51
+ assert.ok(/if \(row\.hasAttribute\('hidden'\)\) row\.removeAttribute\('hidden'\)/.test(src),
52
+ 'hidden 移除不是幂等的')
53
+ // 判据本身不许动
54
+ assert.ok(/shouldHide = idx\.shadowed\.has\(hit\.seq\)/.test(src), '藏行判据被改(必须是 shadowed)')
55
+ assert.ok(/shouldHide = !idx\.visibleTurns\.has\(String\(hit\.turn\)\)/.test(src), '回合 chrome 判据被改')
56
+ assert.ok(/if \(hit === null\) \{/.test(src) && /unresolved\+\+/.test(src), '查不到必须保持可见')
57
+ // 判定后必须仍然逐行执行(不允许按签名整段跳过)
58
+ const fn = src.match(/var applySurfaceVisibility = [\s\S]*?\n {6}\};/)
59
+ assert.ok(fn && !/if \([^)]*Sig[^)]*\) return/.test(fn[0]), '不许按签名跳过整段藏行计算')
60
+ })
61
+
62
+ // ═══════════════════════════════════════════════════════════════════════════
63
+ // P1-2 · MutationObserver 回调过滤 + 防抖 maxWait
64
+ // ═══════════════════════════════════════════════════════════════════════════
65
+ test('P1-2:MO 回调先过滤,matches 与 querySelector 两者都试', () => {
66
+ assert.ok(/nodeType !== 1/.test(src), '非元素节点必须跳过')
67
+ assert.ok(/n\.matches\(MO_SEL\)/.test(src), '新增节点自身可能就是目标')
68
+ assert.ok(/n\.querySelector\(MO_SEL\)/.test(src), '新增子树可能是祖先容器')
69
+ assert.ok(/catch \{ scheduleScan\(\) \}/.test(src), '过滤自身出错必须放行(宁可多扫一次)')
70
+ assert.ok(/MO_SEL = '\[data-chat-node-key\]/.test(src), '选择器必须覆盖宿主 chat 行')
71
+ assert.ok(/\[class\*="xzv4MW_actions"\]/.test(src), '选择器必须覆盖官方用户动作行')
72
+ })
73
+
74
+ test('P1-2:防抖 trailing 200ms + maxWait(连续 mutation 不许无限推迟)', () => {
75
+ assert.ok(/scanPendingSince >= 1000/.test(src), '缺 maxWait —— 流式输出时遮蔽行会长时间保持可见')
76
+ assert.ok(/setTimeout\(\(\) => \{ scan\._t = null; scanPendingSince = 0; scan\(\) \}, 200\)/.test(src),
77
+ 'trailing 200ms 防抖被改')
78
+ })
79
+
80
+ test('P1-2:attributeFilter 只盯宿主写入的 data-chat-node-key(不自触发)', () => {
81
+ assert.ok(/attributeFilter: \['data-chat-node-key'\]/.test(src))
82
+ assert.ok(!/setAttribute\('data-chat-node-key'/.test(src), '本插件不许写这个属性(会成环)')
83
+ })
84
+
85
+ // ═══════════════════════════════════════════════════════════════════════════
86
+ // P0-2-client · 写操作后的读合并
87
+ // ═══════════════════════════════════════════════════════════════════════════
88
+ test('红线:150/700/1600 三连三处全保留(1600ms 兜底不能砍成 0)', () => {
89
+ assert.equal((src.match(/\[150, 700, 1600\]/g) || []).length, 3,
90
+ 'restoreRow / runUserRevert / afterWrite 各一处,缺一处就退回「隐藏不更新」')
91
+ })
92
+
93
+ test('读合并:合并窗口 <1600ms,且兜底档强制走真网络', () => {
94
+ const m = /const MSG_COALESCE_MS = (\d+)/.exec(src)
95
+ assert.ok(m, '缺合并窗口常量')
96
+ const w = Number(m[1])
97
+ assert.ok(w >= 300, `窗口 ${w}ms 太短,盖不住 dock + openSession 后的 scan`)
98
+ assert.ok(w < 1600, `窗口 ${w}ms ≥1600 会把兜底那一发吞掉`)
99
+ const rs = src.match(/__refreshSurface = \(sid\) => \{[\s\S]*?\n {6}\}/)
100
+ assert.ok(rs, '找不到 __refreshSurface')
101
+ assert.ok(/invalidateMessagesMemo\(\)/.test(rs[0]), '兜底档必须先作废窗口再拉,否则吃的是旧响应')
102
+ assert.ok(/refreshDeadline/.test(rs[0]), '三档必须并成一次(deadline 合并),不是各拉各的')
103
+ })
104
+
105
+ test('红线:refillComposer / setDraft 必须发生在首次刷新之前', () => {
106
+ // 悬停回滚按钮:refill → emitChanged → 三连
107
+ const s0 = src.indexOf("notifyDone(__t('done.revert'))")
108
+ assert.ok(s0 >= 0, '找不到 runUserRevert 成功分支')
109
+ const s1 = src.indexOf('.finally(() => { btn.disabled = false })', s0)
110
+ assert.ok(s1 > s0, '找不到 runUserRevert 收尾')
111
+ const block = src.slice(s0, s1)
112
+ const r = block.indexOf('refillComposer(')
113
+ const e = block.indexOf('emitChanged(')
114
+ const l = block.indexOf('for (const delay of [150, 700, 1600]')
115
+ assert.ok(r >= 0, 'runUserRevert 不回填 composer')
116
+ assert.ok(e > r, 'emitChanged(= 首次刷新)必须排在 refillComposer 之后')
117
+ assert.ok(l > e, '三连必须排在 emitChanged 之后')
118
+
119
+ // /undo:refill → afterWrite(afterWrite 内部才是 emitChanged + 三连)
120
+ const un = src.indexOf('refillComposer(rawSid, target.seq)')
121
+ assert.ok(un >= 0, '/undo 不回填')
122
+ const aw = src.indexOf('afterWrite(rawSid,', un)
123
+ assert.ok(aw > un, '/undo 必须先回填再走 afterWrite')
124
+
125
+ // /redo 是「加回内容」,不回填(既有 composer-refill R2 锁的互补)
126
+ const redo = src.match(/var runRedo = \(\) => \{[\s\S]*?\n {4}\}/)
127
+ assert.ok(redo && !/refillComposer\(/.test(redo[0]), '/redo 不应回填 composer')
128
+ })
129
+
130
+ test('读合并:所有 message 列表 GET 都走 fetchMessagesJson', () => {
131
+ const urls = src.split('\n').filter((l) => /api\/message-ops\/messages\?sessionId=/.test(l))
132
+ assert.ok(urls.length > 0)
133
+ const stray = urls.filter((l) => /(^|[^a-zA-Z])fetch\(/.test(l))
134
+ assert.deepEqual(stray, [], '还有绕过合并窗口的裸 fetch:\n' + stray.join('\n'))
135
+ // 两种 sessionId 写法必须归一,否则 session-xxx / xxx 各占一个缓存槽 = 合并失效
136
+ assert.ok(src.includes('[?&]sessionId=)session-'), 'fetchMessagesJson 没归一 session- 前缀')
137
+ const norm = (u) => String(u).replace(/([?&]sessionId=)session-/, '$1')
138
+ assert.equal(norm('/api/message-ops/messages?sessionId=session-abc'), '/api/message-ops/messages?sessionId=abc')
139
+ assert.equal(norm('/api/message-ops/messages?sessionId=abc'), '/api/message-ops/messages?sessionId=abc')
140
+ })
141
+
142
+ // ═══════════════════════════════════════════════════════════════════════════
143
+ // 真·执行测试:把 src/client.js 里的 applySurfaceVisibility 原样抠出来跑。
144
+ // client.js 正文此前执行覆盖 = 0,这条是唯一真执行它的用例。
145
+ // ═══════════════════════════════════════════════════════════════════════════
146
+ /** 与 src/client.js 的 seqOfNodeKey 同构的最小替身:key 形如 `<len><kind><id>` */
147
+ const fakeSeqOfNodeKey = (key) => {
148
+ const m = /^(\d+):(.+)$/.exec(String(key || ''))
149
+ if (!m) return null
150
+ const kindLen = Number(m[1])
151
+ const kind = m[2].slice(0, kindLen)
152
+ const id = m[2].slice(kindLen)
153
+ if (kind === 'turn-tail') return { kind, seq: 0, all: [0], turn: id }
154
+ if (kind === 'input-message') return { kind, seq: Number(id), all: [Number(id)] }
155
+ return null
156
+ }
157
+
158
+ const loadApplySurfaceVisibility = () => {
159
+ const m = src.match(/var applySurfaceVisibility = \(root, idx\) => \{[\s\S]*?\n {6}\};/)
160
+ assert.ok(m, '源码里抠不出 applySurfaceVisibility')
161
+ const factory = new Function('seqOfNodeKey', `${m[0]}\nreturn applySurfaceVisibility`)
162
+ return factory(fakeSeqOfNodeKey)
163
+ }
164
+
165
+ const makeRow = (key, hidden) => {
166
+ const attrs = {}
167
+ if (key != null) attrs['data-chat-node-key'] = key
168
+ if (hidden != null) attrs.hidden = hidden
169
+ return {
170
+ attrs,
171
+ writes: 0,
172
+ getAttribute(n) { return Object.prototype.hasOwnProperty.call(this.attrs, n) ? this.attrs[n] : null },
173
+ hasAttribute(n) { return Object.prototype.hasOwnProperty.call(this.attrs, n) },
174
+ setAttribute(n, v) { this.attrs[n] = v; this.writes++ },
175
+ removeAttribute(n) { delete this.attrs[n]; this.writes++ },
176
+ }
177
+ }
178
+ const idxOf = (shadowedSeqs, visibleTurns) => ({
179
+ shadowed: new Set(shadowedSeqs),
180
+ visibleTurns: new Set((visibleTurns ?? []).map(String)),
181
+ })
182
+
183
+ test('真执行:shadowed 行被藏、未遮蔽行保持可见(0.9.6 判据)', () => {
184
+ const apply = loadApplySurfaceVisibility()
185
+ const rows = [
186
+ makeRow('13:input-message8'), // seq 8,未遮蔽
187
+ makeRow('13:input-message54'), // seq 54,已遮蔽
188
+ makeRow('9:turn-tail3'), // turn 3,有可见消息
189
+ makeRow('9:turn-tail4'), // turn 4,全遮蔽
190
+ makeRow('garbage'), // 查不到 → 必须保持可见
191
+ ]
192
+ const out = apply(rows, idxOf([54], [3]))
193
+ assert.equal(out.hidden, 2, 'seq54 + turn4 应被藏')
194
+ assert.equal(out.unresolved, 1)
195
+ assert.equal(rows[0].getAttribute('hidden'), null, '未遮蔽行不许藏')
196
+ assert.equal(rows[1].getAttribute('hidden'), 'until-found')
197
+ assert.equal(rows[2].getAttribute('hidden'), null)
198
+ assert.equal(rows[3].getAttribute('hidden'), 'until-found')
199
+ assert.equal(rows[4].getAttribute('hidden'), null, '查不到时保持可见(唯一会误藏用户内容的路径)')
200
+ })
201
+
202
+ test('真执行:幂等跳写 —— 已在目标态时零 DOM 写', () => {
203
+ const apply = loadApplySurfaceVisibility()
204
+ const idx = idxOf([54], [3])
205
+ const rows = [
206
+ makeRow('13:input-message8'),
207
+ makeRow('13:input-message54', 'until-found'),
208
+ makeRow('9:turn-tail4', 'until-found'),
209
+ makeRow('garbage'),
210
+ ]
211
+ apply(rows, idx) // 第一次:把状态摆到位
212
+ const writesAfterFirst = rows.reduce((n, r) => n + r.writes, 0)
213
+ assert.equal(writesAfterFirst, 0, '已在目标态 → 一次写都不该发生')
214
+ apply(rows, idx) // 第二次:仍然零写
215
+ assert.equal(rows.reduce((n, r) => n + r.writes, 0), 0, '重复扫描不该再碰属性')
216
+ })
217
+
218
+ test('真执行:状态翻转时仍然会写(幂等不是「不写」)', () => {
219
+ const apply = loadApplySurfaceVisibility()
220
+ const clean = makeRow('13:input-message54')
221
+ apply([clean], idxOf([], []))
222
+ assert.equal(clean.writes, 0, '未遮蔽 → 保持无 hidden,零写')
223
+ apply([clean], idxOf([54], []))
224
+ assert.equal(clean.getAttribute('hidden'), 'until-found')
225
+ assert.equal(clean.writes, 1, '状态翻转必须写')
226
+ apply([clean], idxOf([54], []))
227
+ assert.equal(clean.writes, 1, '翻转后重复扫描不再写')
228
+ apply([clean], idxOf([], []))
229
+ assert.equal(clean.getAttribute('hidden'), null)
230
+ assert.equal(clean.writes, 2, '解除隐藏也要写')
231
+ })
232
+
233
+ test('真执行:接受已查好的行集合(省一次 querySelectorAll)', () => {
234
+ const apply = loadApplySurfaceVisibility()
235
+ const rows = [makeRow('13:input-message1')]
236
+ assert.deepEqual(apply(rows, idxOf([], [])), { hidden: 0, unresolved: 0, shown: 1 })
237
+ // root 为 null 时退回自查询 —— 没有 document 的环境下不抛
238
+ const fakeDoc = { querySelectorAll: () => rows }
239
+ assert.deepEqual(apply(fakeDoc, idxOf([], [])), { hidden: 0, unresolved: 0, shown: 1 })
240
+ assert.equal(apply(rows, null).hidden, 0, 'idx 为空直接短路')
241
+ })
242
+
243
+ // ═══════════════════════════════════════════════════════════════════════════
244
+ // P4 · __seqIndexCache 挂到 dataSig
245
+ // ═══════════════════════════════════════════════════════════════════════════
246
+ test('P4:seq 索引随 dataSig 失效并广播,已挂载槽位会重解析', () => {
247
+ assert.ok(/SEQ_INDEX_EVENT/.test(src), '缺失效广播')
248
+ assert.ok(/syncSeqIndex\(/.test(src), '缺 dataSig 驱动的索引重建')
249
+ const fn = src.match(/var syncSeqIndex = \(sid, messages, idx\) => \{[\s\S]*?\n {6}\}/)
250
+ assert.ok(fn, '找不到 syncSeqIndex')
251
+ assert.ok(/idx\.total/.test(fn[0]) && /idx\.shadowed\.size/.test(fn[0]), '签名必须含数据规模')
252
+ assert.ok(/if \(sig === __seqDataSig\) return/.test(fn[0]), '签名没变就别重建')
253
+ assert.ok(/__seqIndexCache\.set\(key, index\)/.test(fn[0]), '必须真的写回索引')
254
+ // 槽位侧订阅
255
+ assert.ok(/window\.addEventListener\(SEQ_INDEX_EVENT, onIdx\)/.test(src), '槽位没订阅失效事件')
256
+ assert.ok(/\[messageId, sessionId, idxRev\]/.test(src), '解析 effect 没把失效代号放进依赖')
257
+ // miss 必须重试一次(否则 seq 恒 null → 按钮永不渲染)
258
+ assert.ok(/if \(retried\) return/.test(src), '缺一次性重试')
259
+ })
@@ -0,0 +1,202 @@
1
+ /**
2
+ * 0.9.7 · 文件派生缓存(P0-1)的行为契约。
3
+ *
4
+ * 锁四件事:
5
+ * 1. **visible 绝不进缓存** —— 它依赖 live.surface.nodes;陈旧的 visible 会让
6
+ * /undo 的 lastRevertable() 挑到不在 surface 上的 seq(服务端 409 / 回填错目标)。
7
+ * 这是 0.9.6 修复的红线,本文件用「同文件两次 list、中间换 surface」直接钉死。
8
+ * 2. running / runningSource 不进缓存(agents 注册表随时变)。
9
+ * 3. 缓存条目**不含 raw events**(114MB/次的短命堆分配),只含派生结果;
10
+ * 且缓存对象不被每请求字段改写(每次返回的是新拷贝)。
11
+ * 4. 在途去重:3 个并发 list 只读 1 次盘;mtime+size 变化(追加一帧)必须失效。
12
+ *
13
+ * 藏行判据仍是 shadowed(不是 visible)——见 surface-visibility / transcript
14
+ * 那两组测试;这里额外断言 shadowed 在缓存前后逐位一致。
15
+ */
16
+ import test from "node:test"
17
+ import assert from "node:assert/strict"
18
+ import fs from "node:fs"
19
+ import os from "node:os"
20
+ import path from "node:path"
21
+ import url from "node:url"
22
+ import { zstdCompressSync, constants } from "node:zlib"
23
+
24
+ const ROOT = path.resolve(path.dirname(url.fileURLToPath(import.meta.url)), "..")
25
+ process.env.DSH_HOME = fs.mkdtempSync(path.join(os.tmpdir(), "dsh-msgops-cache-"))
26
+
27
+ const { encodeSessionFile, listMessages } = await import("../src/session-file.js")
28
+ const { _internals } = await import("../src/index.js")
29
+ const { opsList, loadDerived, derivedCache } = _internals
30
+
31
+ const SID = "session-00000000-4444-5555-6666-777777777777"
32
+ const BARE = SID.slice("session-".length)
33
+
34
+ function header() {
35
+ return { type: "session", version: 3, id: SID, createdAt: 1, cwd: "/tmp/x", delegationDepth: 0 }
36
+ }
37
+ function msg(type, seq, text) {
38
+ return {
39
+ type, seq, time: 1000 + seq, surfaceOp: "append",
40
+ data: { turn: 1, step: 1, message: { role: type === "user/message" ? "user" : "assistant", content: [{ type: "text", text }] } },
41
+ }
42
+ }
43
+ const EVENTS = [
44
+ msg("user/message", 0, "问题一"),
45
+ msg("assistant/message", 1, "回答一"),
46
+ msg("user/message", 2, "问题二"),
47
+ msg("assistant/message", 3, "回答二"),
48
+ {
49
+ type: "system/message", seq: 4, time: 1100,
50
+ surfaceOp: { op: "replace", startSeq: 1, endSeq: 2 },
51
+ sourceEventSeqs: [1, 2],
52
+ data: { turn: 1, step: 1, message: { role: "system", content: [{ type: "text", text: "[消息回滚] 到 seq 1" }] } },
53
+ },
54
+ msg("user/message", 5, "问题三"),
55
+ msg("assistant/message", 6, "回答三"),
56
+ ]
57
+
58
+ const logPath = path.join(process.env.DSH_HOME, "sessions", "proj-cache", SID, "session.v3.jsonl.zstd")
59
+ fs.mkdirSync(path.dirname(logPath), { recursive: true })
60
+ fs.writeFileSync(logPath, encodeSessionFile(header(), EVENTS))
61
+
62
+ /** 测试用 ctx:sessions/agents 两个注册表都可换,模拟 live surface / 运行状态变化。 */
63
+ function ctxFor({ nodes = null, status = "idle" } = {}) {
64
+ const session = nodes === null ? undefined : { id: SID, surface: { nodes } }
65
+ const agent = { status }
66
+ const sessions = { get: () => session, list: () => (session ? [session] : []) }
67
+ const agents = { get: () => agent }
68
+ return {
69
+ sessions, agents,
70
+ get(name) { return name === "sessions" ? sessions : name === "agents" ? agents : undefined },
71
+ }
72
+ }
73
+ const visibleMap = (r) => r.messages.filter((m) => m.visible).map((m) => m.seq)
74
+
75
+ test("缓存命中后 visible 仍随 live surface 重算(0.9.6 红线)", async () => {
76
+ // 第一次:会话不在对象层 → 走 !shadowed 兜底
77
+ const r1 = await opsList(ctxFor({ nodes: null }), SID)
78
+ assert.equal(r1.ok, true)
79
+ assert.deepEqual(visibleMap(r1), [0, 3, 4, 5, 6], "兜底判据 = !shadowed(seq 1,2 被 replace 遮蔽;marker seq 4 自己可见)")
80
+ assert.equal(r1.visibleCount, 5)
81
+
82
+ // 第二次:live surface 只挂 0 与 1 —— 文件没变,纯缓存命中
83
+ const r2 = await opsList(ctxFor({ nodes: [0, 1] }), SID)
84
+ assert.deepEqual(visibleMap(r2), [0, 1], "缓存命中也必须用新 surface,绝不能回放上一次的 visible")
85
+ assert.equal(r2.visibleCount, 2)
86
+
87
+ // 第三次:再换一个 surface
88
+ const r3 = await opsList(ctxFor({ nodes: [5] }), SID)
89
+ assert.deepEqual(visibleMap(r3), [5])
90
+ assert.equal(r3.visibleCount, 1)
91
+
92
+ // 三次返回的 messages 必须是**不同对象**(缓存对象不被改写)
93
+ assert.notStrictEqual(r1.messages, r2.messages)
94
+ assert.notStrictEqual(r1.messages[0], r2.messages[0])
95
+ // 但文件派生字段逐位一致
96
+ assert.deepEqual(r1.messages.map((m) => [m.seq, m.snippet, m.shadowed]), r3.messages.map((m) => [m.seq, m.snippet, m.shadowed]))
97
+ })
98
+
99
+ test("藏行判据是 shadowed 且跨请求稳定(0.9.6)", async () => {
100
+ const a = await opsList(ctxFor({ nodes: [1, 2] }), SID) // 即使 surface 上有 1,2
101
+ const b = await opsList(ctxFor({ nodes: [1, 2] }), SID)
102
+ for (const r of [a, b]) {
103
+ assert.equal(r.messages.find((m) => m.seq === 1).shadowed, true)
104
+ assert.equal(r.messages.find((m) => m.seq === 2).shadowed, true)
105
+ assert.equal(r.messages.find((m) => m.seq === 0).shadowed, false)
106
+ // shadowed 恒由 computeShadowed 得出,与 visible 是否为 true 无关
107
+ assert.equal(r.messages.find((m) => m.seq === 1).visible, true)
108
+ }
109
+ assert.deepEqual(a.messages.map((m) => m.shadowed), b.messages.map((m) => m.shadowed))
110
+ })
111
+
112
+ test("running / runningSource 每请求重算,不进缓存", async () => {
113
+ const idle = await opsList(ctxFor({ status: "idle" }), SID)
114
+ assert.equal(idle.running, false)
115
+ const run = await opsList(ctxFor({ status: "running" }), SID)
116
+ assert.equal(run.running, true)
117
+ assert.equal(run.runningSource, "agent-status-running")
118
+ assert.equal((await opsList(ctxFor({ status: "idle" }), SID)).running, false)
119
+ })
120
+
121
+ test("缓存条目不含 raw events,且 LRU 上限 16", async () => {
122
+ derivedCache.clear()
123
+ await opsList(ctxFor(), SID)
124
+ assert.equal(derivedCache.size, 1)
125
+ const entry = derivedCache.get(logPath)
126
+ assert.ok(entry, "应按 logPath 建条目")
127
+ assert.deepEqual(Object.keys(entry).sort(), ["mtimeMs", "promise", "size"])
128
+ const derived = await entry.promise
129
+ assert.ok(!("events" in derived), "derived 不得持有 raw events(114MB/次)")
130
+ assert.deepEqual(Object.keys(derived).sort(), ["header", "messages", "shadowed", "turnEndSeq"])
131
+ assert.equal(derived.messages.length, listMessages(EVENTS).length)
132
+
133
+ // 再灌 20 个真实会话日志 → 上限必须是 16,且最早插入的被淘汰
134
+ const extra = [];
135
+ for (let i = 0; i < 20; i++) {
136
+ const id = `session-00000000-0000-4000-8000-${String(i).padStart(12, "0")}`;
137
+ const dir = path.join(process.env.DSH_HOME, "sessions", "proj-lru", id);
138
+ fs.mkdirSync(dir, { recursive: true });
139
+ fs.writeFileSync(path.join(dir, "session.v3.jsonl.zstd"), encodeSessionFile({ ...header(), id }, [msg("user/message", 0, "x" + i)]));
140
+ extra.push(path.join(dir, "session.v3.jsonl.zstd"));
141
+ }
142
+ for (const p of extra) await loadDerived(p);
143
+ assert.equal(derivedCache.size, 16, `LRU 未生效:size=${derivedCache.size}`)
144
+ assert.equal(derivedCache.has(logPath), false, "最早插入的条目应被淘汰")
145
+ })
146
+
147
+ test("在途去重:3 个并发 list 只读 1 次盘", async () => {
148
+ derivedCache.clear()
149
+ const realReadFile = fs.promises.readFile
150
+ let reads = 0
151
+ fs.promises.readFile = async (...args) => { reads++; return realReadFile(...args) }
152
+ try {
153
+ const [a, b, c] = await Promise.all([opsList(ctxFor(), SID), opsList(ctxFor(), SID), opsList(ctxFor(), SID)])
154
+ assert.equal(reads, 1, `并发应共享一次读取,实际 ${reads} 次`)
155
+ assert.equal(a.total, b.total)
156
+ assert.deepEqual(visibleMap(a), visibleMap(c))
157
+ } finally {
158
+ fs.promises.readFile = realReadFile
159
+ }
160
+ assert.equal(derivedCache.size, 1)
161
+ // 串行再问一次:仍是缓存命中(不再读盘)
162
+ const before = fs.promises.readFile
163
+ let reads2 = 0
164
+ fs.promises.readFile = async (...args) => { reads2++; return before(...args) }
165
+ try { await opsList(ctxFor(), SID) } finally { fs.promises.readFile = before }
166
+ assert.equal(reads2, 0, "命中不应再读盘")
167
+ })
168
+
169
+ test("mtime+size 失效:追加一帧后立即看到新事件", async () => {
170
+ derivedCache.clear()
171
+ const first = await opsList(ctxFor(), SID)
172
+ assert.equal(first.total, EVENTS.length)
173
+
174
+ // append-only 追加一个 user 消息帧(裸 zstd,与 diskAppend 同构)
175
+ const extra = msg("user/message", 7, "问题四")
176
+ const frame = zstdCompressSync(Buffer.from(JSON.stringify(extra) + "\n", "utf8"), {
177
+ params: { [constants.ZSTD_c_checksumFlag]: 1 },
178
+ })
179
+ const stBefore = fs.statSync(logPath)
180
+ fs.appendFileSync(logPath, frame)
181
+ // 保证 mtime/size 至少有一个变化(size 必变)
182
+ assert.ok(fs.statSync(logPath).size > stBefore.size)
183
+
184
+ const second = await opsList(ctxFor(), SID)
185
+ assert.equal(second.total, EVENTS.length + 1, "读前 stat 必须让追加生效")
186
+ assert.equal(second.messages.at(-1).snippet, "问题四")
187
+
188
+ // 同步 loadDerived 也走重算路径
189
+ const st = fs.statSync(logPath)
190
+ const entry = derivedCache.get(logPath)
191
+ assert.equal(entry.size, st.size)
192
+ assert.equal(entry.mtimeMs, st.mtimeMs)
193
+ })
194
+
195
+ test("findSessionDirs 两种 id 拼写都能命中缓存(key 是 logPath 不是 sessionId)", async () => {
196
+ derivedCache.clear()
197
+ const byFull = await opsList(ctxFor(), SID)
198
+ const byBare = await opsList(ctxFor(), BARE)
199
+ assert.equal(byFull.session.id, SID)
200
+ assert.equal(byBare.session.id, SID)
201
+ assert.equal(derivedCache.size, 1, "同一文件的两种 id 拼写必须命中同一条缓存")
202
+ })
@@ -0,0 +1,98 @@
1
+ /**
2
+ * 0.10.1 revert 的 commit 生命周期(对齐 opencode)。
3
+ *
4
+ * 用户反馈:「我把消息改完发出去了,恢复弹窗仍然存在,我不知道它让我恢复到哪去」。
5
+ *
6
+ * opencode 源码(anomalyco/opencode @ dev)核对结论:
7
+ * core/src/session/session.ts:165
8
+ * // Commit a staged revert only after preparation succeeds, before admitting new work.
9
+ * if (session.revert) yield* SessionRevert.commit(bus, session)
10
+ * → 用户发出下一条消息时**自动 commit**
11
+ * core/src/session/projector.ts:759 → `DELETE WHERE seq >= boundary.seq` + `revert: null`
12
+ * app/.../use-session-commands.tsx:287
13
+ * disabled: !actions.session.data.revertMessageID()
14
+ * → opencode **没有常驻弹窗**,只有会灰掉的 undo/redo 命令;状态清零 = affordance 消失
15
+ *
16
+ * 我们是 append-only 日志,marker 不会真消失 → 由 markCommitted 自算。
17
+ */
18
+ import test from 'node:test'
19
+ import assert from 'node:assert/strict'
20
+ import { markCommitted } from '../src/session-file.js'
21
+
22
+ const marker = (seq, extra = {}) => ({ seq, type: 'system/message', marker: true, ...extra })
23
+ const realUser = (seq) => ({ seq, type: 'user/message', sourceKind: 'user' })
24
+ const kinded = (seq, sourceKind) => ({ seq, type: 'user/message', sourceKind })
25
+
26
+ test('未发新消息 → marker 未提交(dock 应该显示)', () => {
27
+ const msgs = [realUser(8), marker(63)]
28
+ markCommitted(msgs)
29
+ assert.equal(msgs[1].committed, false)
30
+ })
31
+
32
+ test('发出下一条真实消息 → marker 已提交(dock 应消失)', () => {
33
+ const msgs = [realUser(8), marker(63), realUser(70)]
34
+ markCommitted(msgs)
35
+ assert.equal(msgs[1].committed, true, '这是用户反馈的核心场景')
36
+ })
37
+
38
+ test('注入行不算提交(否则 background job 落地就会让弹窗自己消失)', () => {
39
+ const injectedKinds = ['tool-jobs', 'agent-instructions', 'runtime-context',
40
+ 'skill-catalog', 'subagent-settled', 'model-selection', 'team-message',
41
+ 'goal', 'agent-message', 'compact-checkpoint', 'user-approval']
42
+ for (const k of injectedKinds) {
43
+ const msgs = [realUser(8), marker(63), kinded(70, k)]
44
+ markCommitted(msgs)
45
+ assert.equal(msgs[1].committed, false, `${k} 不应触发提交`)
46
+ }
47
+ })
48
+
49
+ test('restore 重放副本不算提交(否则恢复一次弹窗就没了)', () => {
50
+ const msgs = [realUser(8), marker(63), kinded(70, 'plugin:@240xu/dsh-message-ops')]
51
+ markCommitted(msgs)
52
+ assert.equal(msgs[1].committed, false)
53
+ })
54
+
55
+ test('边界之前的真实消息不影响判定', () => {
56
+ const msgs = [realUser(8), realUser(30), marker(63)]
57
+ markCommitted(msgs)
58
+ assert.equal(msgs[2].committed, false, '边界之前的真实消息不该提交它')
59
+ })
60
+
61
+ test('多个 marker 各自独立判定', () => {
62
+ const msgs = [realUser(8), marker(63), realUser(70), marker(80)]
63
+ markCommitted(msgs)
64
+ assert.equal(msgs[1].committed, true, '63 之后有真实消息 → 已提交')
65
+ assert.equal(msgs[3].committed, false, '80 之后没有 → 仍可恢复')
66
+ })
67
+
68
+ test('非 marker 行不被打上 committed(避免污染普通消息)', () => {
69
+ const msgs = [realUser(8), marker(63), realUser(70)]
70
+ markCommitted(msgs)
71
+ assert.ok(!('committed' in msgs[0]))
72
+ assert.ok(!('committed' in msgs[2]))
73
+ })
74
+
75
+ test('activeMarkers 过滤条件(与 client.js 同构)', () => {
76
+ const active = (msgs) => (msgs || []).filter((m) =>
77
+ m.marker && m.sourceKind !== 'compact-checkpoint'
78
+ && m.restoreComplete !== true && m.committed !== true)
79
+ const msgs = [
80
+ { seq: 63, marker: true, committed: false, restoreComplete: false }, // 活跃
81
+ { seq: 70, marker: true, committed: true, restoreComplete: false }, // 已提交 → 排除
82
+ { seq: 80, marker: true, committed: false, restoreComplete: true }, // 已恢复 → 排除
83
+ { seq: 90, marker: true, sourceKind: 'compact-checkpoint', committed: false, restoreComplete: false },
84
+ ]
85
+ const out = active(msgs)
86
+ assert.equal(out.length, 1)
87
+ assert.equal(out[0].seq, 63)
88
+ })
89
+
90
+ test('源码锁:activeMarkers 必须排 committed', async () => {
91
+ const { readFileSync } = await import('node:fs')
92
+ const { fileURLToPath } = await import('node:url')
93
+ const { dirname, join } = await import('node:path')
94
+ const src = readFileSync(join(dirname(fileURLToPath(import.meta.url)), '..', 'src', 'client.js'), 'utf8')
95
+ const m = src.match(/function activeMarkers[\s\S]{0,2000}?\n {4}\}/)
96
+ assert.ok(m, '找不到 activeMarkers')
97
+ assert.ok(/committed !== true/.test(m[0]), 'activeMarkers 未排除已提交的 marker —— 弹窗会常驻(用户报告的 bug)')
98
+ })
@@ -1,19 +1,36 @@
1
1
  /**
2
2
  * 0.9.4 transcript 隐藏判据 —— 回归「正文几乎空白」事故。
3
3
  *
4
+ * 🔴🔴 本文件是「历史判据的回归样本」,**不是**当前实现的规格 🔴🔴
5
+ *
6
+ * 文件里的 `decide()` / `visible` 集合 / `fences` 全是 **0.9.4 时代的判据副本**,
7
+ * 与 `src/client.js` 当前(0.9.6+)的 `shadowed` 判据**不同源**:
8
+ * - 当前真判据:`shouldHide = idx.shadowed.has(hit.seq)`(replace 区间)+ 回合 chrome
9
+ * 的 `!idx.visibleTurns.has(turn)`;权威锁在 `test/client-perf-locks.test.js`。
10
+ * - 本文件保留的是「当年为什么会出事、当年怎么算的」的原始样本,全绿只因测的是自己的副本。
11
+ * ⛔ **禁止**把这里的 helper 与其它测试的 helper 合并去重 —— 合并等于把 0.9.4 的
12
+ * 过期契约焊死成「现行契约」。`test/undo-slash.test.js` 的
13
+ * `shouldHide(cands, fences, reverted)` 与本文件属同一批,同样不许合并。
14
+ * (唯一仍与现行实现同源的是 `pickLastVisible`:它对齐 client.js 的
15
+ * `lastRevertable`「可回滚目标」语义,那一套至今仍用 `visible`。)
16
+ *
4
17
  * 事故:会话有 19 个**离散** marker([9,9]、[10,4368]、[6830,8573] …),
5
18
  * 服务端把它们塌缩成 revertFences = range.start 的列表 [10, 6830, 9829, 11429],
6
19
  * 客户端判据 `seq >= min(fences)` 等价于 `seq >= 10`,
7
20
  * 于是 4792/4793 条全被 hidden —— 截图里正文几乎空白。
8
21
  *
9
- * 正确判据 = 模型 surface(`m.visible`)。实测它与宿主 visibleCount 精确吻合:
22
+ * 当时(0.9.4)认为的正确判据 = 模型 surface(`m.visible`)。实测它与宿主
23
+ * visibleCount 精确吻合:
10
24
  * 156b9ecf: total 4793, visibleCount 2083 → !visible 应为 2710
11
25
  * 4e10c1a2: total 5038, visibleCount 464 → !visible 应为 4574
26
+ * ⚠️ 0.9.6 又把它换成了 `shadowed`(live 路径下 tool/call 恒 visible=false,
27
+ * 拿 visible 当判据会整页误藏工具行)—— 见文件末尾的「当前判据对照」测试。
12
28
  */
13
29
  import test from 'node:test'
14
30
  import assert from 'node:assert/strict'
31
+ import fs from 'node:fs'
15
32
 
16
- /** 与 client.js 同构:隐藏判据 */
33
+ /** 0.9.4 判据(已废弃)的历史副本 —— 与 client.js 当前 shadowed 判据不同源,禁止合并。 */
17
34
  function decide(hit, idx) {
18
35
  if (hit === null) return null // 查不到 → 保持可见
19
36
  if (hit.turn !== undefined) return !idx.visibleTurns.has(String(hit.turn))
@@ -21,6 +38,7 @@ function decide(hit, idx) {
21
38
  }
22
39
 
23
40
  test('回归:fence 塌缩会把离散区间放大成「seq >= 最小值」', () => {
41
+ // [0.9.4 判据(已废弃)] fences 只存在于历史实现,client.js 早已不发 revertFences。
24
42
  const fences = [10, 6830, 9829, 11429] // 实测(19 个 marker 的 range.start)
25
43
  const total = 4793
26
44
  const hiddenByFence = Array.from({ length: total }, (_, i) => i + 7).filter(s => fences.some(f => s >= f))
@@ -30,6 +48,7 @@ test('回归:fence 塌缩会把离散区间放大成「seq >= 最小值」', (
30
48
  })
31
49
 
32
50
  test('正确判据与宿主 visibleCount 精确吻合(会话 156b9ecf)', () => {
51
+ // [0.9.4 判据(已废弃)] 当时的「正确判据」= m.visible;0.9.6 起真判据是 shadowed。
33
52
  const total = 4793, visibleCount = 2083
34
53
  // 构造:前 visibleCount 条可见,其余被遮蔽
35
54
  const visible = new Set()
@@ -40,6 +59,7 @@ test('正确判据与宿主 visibleCount 精确吻合(会话 156b9ecf)', ()
40
59
  })
41
60
 
42
61
  test('第二条会话同样吻合(4e10c1a2)', () => {
62
+ // [0.9.4 判据(已废弃)] 同上:visible 口径的量化样本。
43
63
  const total = 5038, visibleCount = 464
44
64
  const visible = new Set()
45
65
  for (let i = 0; i < visibleCount; i++) visible.add(i + 7)
@@ -59,6 +79,8 @@ test('回合 chrome 按「本 turn 有无可见消息」判,不按 seq', () =>
59
79
  })
60
80
 
61
81
  test('消息类:在 surface 上就露,不在就藏', () => {
82
+ // [0.9.4 判据(已废弃)] 消息类分支用的 idx.visible 已被 0.9.6 的 shadowed 取代;
83
+ // 回合 chrome 分支(visibleTurns)仍与现行实现同源。
62
84
  const idx = { visible: new Set([8, 18]), visibleTurns: new Set() }
63
85
  assert.equal(decide({ kind: 'input-message', seq: 8, all: [8] }, idx), false, '在 surface → 露')
64
86
  assert.equal(decide({ kind: 'input-message', seq: 54, all: [54] }, idx), true, '不在 → 藏')
@@ -70,3 +92,20 @@ test('查不到一律保持可见(绝不误藏)', () => {
70
92
  const idx = { visible: new Set([1]), visibleTurns: new Set() }
71
93
  assert.equal(decide(null, idx), null)
72
94
  })
95
+
96
+ // ── 对照:现行实现(0.9.6+)用的是 shadowed,不是本文件上面那些副本 ──────────
97
+ // 上面所有断言都是历史判据的回归样本;这一条负责把「真判据在 client.js 哪里」钉死,
98
+ // 免得后人误以为本文件的 decide() 就是现行规格。
99
+ test('[当前判据对照] client.js 藏行判据 = idx.shadowed,不是本文件的 visible/fences 副本', () => {
100
+ const src = fs.readFileSync(new URL('../src/client.js', import.meta.url), 'utf8')
101
+ assert.ok(/shouldHide = idx\.shadowed\.has\(hit\.seq\)/.test(src),
102
+ '消息/工具类判据必须是 idx.shadowed(0.9.6)')
103
+ assert.ok(/shouldHide = !idx\.visibleTurns\.has\(String\(hit\.turn\)\)/.test(src),
104
+ '回合 chrome 判据必须是 idx.visibleTurns')
105
+ assert.ok(!/idx\.visible\.has\(/.test(src),
106
+ 'client.js 不得回退到 idx.visible 判据(live 路径下 tool/call 恒 false → 整页误藏)')
107
+ // revertFences 允许出现在**注释**里(指向 README「历史事故记录」#4 的演进史指针),
108
+ // 但任何**代码行**出现 = 塌缩判据复活 —— 所以先剥掉整行注释再查。
109
+ const codeOnly = src.split('\n').filter((l) => !/^\s*(\/\/|\/\*|\*)/.test(l)).join('\n')
110
+ assert.ok(!/\brevertFences\b/.test(codeOnly), 'client.js 代码不得复活 revertFences 塌缩判据(注释指针除外)')
111
+ })