dsh-knit 0.5.1 → 0.11.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.
@@ -20,19 +20,28 @@ const PROJECT_ROOT = makeWorkspace()
20
20
 
21
21
  /**
22
22
  * 起一个挂着 Knit 路由的回环 server(伪造 cordis 的 webServer / sessions / effect)。
23
+ *
24
+ * ⚠️ `inject` 必须**照抄 cordis 的真实语义**:只有它真的能提供所请求的依赖时才回调。
25
+ * v0.7 给 `apply` 加了第二个 `ctx.inject(['tools'], …)`,如果这里对所有 deps 都无脑回调,
26
+ * 那个回调会拿到一个没有 `tools` 的假 ctx —— 那是**替身的谎**,不是代码的 bug
27
+ * (AGENTS.md §6.1 的教训)。真实的 cordis 在回调前保证依赖可用。
28
+ *
23
29
  * @returns {Promise<{base:string, close:Function}>} 地址根与关闭函数
24
30
  */
25
31
  async function startKnitServer() {
26
32
  let handler = null
33
+ const provided = {
34
+ webServer: {
35
+ register({ handler: h }) { handler = h; return () => {} },
36
+ },
37
+ sessions: { get: () => ({ header: { cwd: PROJECT_ROOT } }) },
38
+ effect(fn) { fn() },
39
+ }
27
40
  apply({
28
- inject(_deps, cb) {
29
- cb({
30
- webServer: {
31
- register({ handler: h }) { handler = h; return () => {} },
32
- },
33
- sessions: { get: () => ({ header: { cwd: PROJECT_ROOT } }) },
34
- effect(fn) { fn() },
35
- })
41
+ inject(deps, cb) {
42
+ // 只提供 webServer / sessions;tools 不存在 → 那条回调不该被调用
43
+ if (!deps.every((dep) => dep in provided)) return
44
+ cb(provided)
36
45
  },
37
46
  })
38
47
  assert.ok(handler, 'apply 应注册路由 handler')
@@ -77,7 +86,11 @@ test('HTTP 端到端:媒体列表、/raw 整文件、Range 206、安全拒绝'
77
86
  assert.match(r.headers.get('content-type'), /image\/png/)
78
87
  assert.equal(r.headers.get('accept-ranges'), 'bytes')
79
88
  assert.equal(r.headers.get('x-content-type-options'), 'nosniff')
89
+ // v0.11 ③:`sandbox` 这一半原来只写在源码里、没有断言 —— 而它是 SVG 脚本失效的
90
+ // 关键(`default-src 'none'` 管外链,`sandbox` 管内联脚本上下文)。
91
+ // 「安全说明里声称的都指向真实检查」这条要求把它抓出来了。
80
92
  assert.match(r.headers.get('content-security-policy') || '', /default-src 'none'/)
93
+ assert.match(r.headers.get('content-security-policy') || '', /sandbox/)
81
94
  assert.equal(Number(r.headers.get('content-length')), realSize)
82
95
  assert.equal((await r.arrayBuffer()).byteLength, realSize)
83
96
 
@@ -156,13 +156,42 @@ test('extractKeywords: 中文取到有意义的词,滤掉虚词', () => {
156
156
  })
157
157
 
158
158
  test('extractKeywords: 最新消息只出现一次的词也保留,旧消息的要重复才要', () => {
159
- const kws = extractKeywords(['最新话题甲甲甲', '很久以前的话题乙乙乙'], 5)
159
+ // 旧消息刻意用**不重复**的音节:n-gram 是滑窗,重复音节会把自己的 2-gram
160
+ // 数成两次,那样测的就不是「门槛」而是「重叠计数」了(见下一条用例)。
161
+ const kws = extractKeywords(['最新话题甲甲甲', '很久以前的话题乙丙丁'], 5)
160
162
  assert.ok(kws.length > 0, '应取到词')
161
163
  // 旧消息里的词只出现一次、且不在最新消息里 → 整段滤掉
162
- assert.ok(kws.every((k) => !k.term.includes('乙')), `不该出现旧消息的词:${kws.map((k) => k.term).join('/')}`)
164
+ assert.ok(
165
+ kws.every((k) => !/[乙丙丁]/.test(k.term)),
166
+ `不该出现只在旧消息里露过一次的词:${kws.map((k) => k.term).join('/')}`,
167
+ )
163
168
  assert.ok(kws.some((k) => k.term.includes('甲')), `应含最新消息的词:${kws.map((k) => k.term).join('/')}`)
164
169
  })
165
170
 
171
+ test('extractKeywords: 重叠的 n-gram 会把「只出现一次」数成两次(已知行为)', () => {
172
+ // 「乙乙乙」里 2-gram「乙乙」占两个重叠窗口 → seen = 2,于是过得了中文那道门槛。
173
+ // 这是滑窗式 n-gram 的固有性质(不是 v0.6 引入的),记在这里免得以后被当成回归。
174
+ // 真实语料里重复音节的概率远低于这里,所以影响有限;
175
+ // 而即便漏进来,语料里不存在的词也会被 IDF 归零,不影响排序。
176
+ const kws = extractKeywords(['别的话题', '很久以前的话题乙乙乙'], 30)
177
+ assert.ok(kws.some((k) => k.term === '乙乙'), '重叠窗口应当计入两次')
178
+ })
179
+
180
+ test('extractKeywords: 丢掉首尾是虚词的跨词碎片,但保住真词的构词成分', () => {
181
+ // 碎片:n-gram 把相邻两个词的字粘起来,首/尾落在纯虚词上
182
+ const fragments = extractKeywords(['把图片和视频都放进来'], 30).map((k) => k.term)
183
+ assert.ok(!fragments.includes('图片和'), `尾字是虚词的 3-gram 应被丢掉:${fragments.join('/')}`)
184
+ assert.ok(!fragments.includes('和视频'), `首字是虚词的 3-gram 应被丢掉:${fragments.join('/')}`)
185
+
186
+ // 真词:以「上/下/中」这类**构词成分**开头(它们在 CN_STOP_CHARS 里,但不在窄集里)。
187
+ // 各自单独作为**最新**那条消息 —— 中文 n-gram 要「出现 2 次」或「在最新消息里」
188
+ // 才过门槛,塞进旧消息里会被门槛拦掉,那测的就不是首尾判定了。
189
+ const up = extractKeywords(['上传这张截图'], 30).map((k) => k.term)
190
+ assert.ok(up.includes('上传'), `「上传」是真词,应保留:${up.join('/')}`)
191
+ const ctx = extractKeywords(['注意上下文里的路径'], 30).map((k) => k.term)
192
+ assert.ok(ctx.includes('上下文'), `「上下文」是真词,应保留:${ctx.join('/')}`)
193
+ })
194
+
166
195
  test('extractKeywords: 最新消息的中文片段会进入候选(当下话题的最强信号)', () => {
167
196
  const kws = extractKeywords(['独一无二词汇出现了'], 20)
168
197
  assert.ok(kws.length > 0, '最新消息里的词应当保留')
@@ -191,9 +220,94 @@ test('rankByRelevance: 没有关键词时全部 0 分且不打乱顺序', () =>
191
220
  { rel: 'a.md', mtimeMs: 2, haystack: { title: '', summary: '', body: '' } },
192
221
  { rel: 'b.md', mtimeMs: 1, haystack: { title: '', summary: '', body: '' } },
193
222
  ]
194
- const { docs: ranked } = rankByRelevance(docs, [], Date.now())
223
+ const { docs: ranked, matched } = rankByRelevance(docs, [], Date.now())
195
224
  assert.deepEqual(ranked.map((d) => d.rel), ['a.md', 'b.md'])
196
225
  assert.ok(ranked.every((d) => d.score === 0))
226
+ assert.deepEqual(matched, [], '没有关键词就没有 matched')
227
+ })
228
+
229
+ /* ── v0.6:BM25 的三条新行为 ─────────────────────────── */
230
+
231
+ /** 造一条文档:haystack 口径与宿主一致(先截 2500 再小写)。 */
232
+ function bm25Doc(rel, { title = '', summary = '', body = '' }, mtimeMs) {
233
+ return {
234
+ rel,
235
+ mtimeMs,
236
+ haystack: {
237
+ title: title.toLowerCase(),
238
+ summary: summary.toLowerCase(),
239
+ body: body.slice(0, 2500).toLowerCase(),
240
+ },
241
+ }
242
+ }
243
+
244
+ test('rankByRelevance: IDF 让高频词不再霸榜(v0.6 核心行为)', () => {
245
+ const now = Date.now()
246
+ // 「knit」出现在**每一篇**(df = N)→ idf 接近 0;「排序」只出现在一篇 → idf 高。
247
+ // 旧引擎按命中次数算,满篇 knit 的那篇必赢 —— 这正是评测集里两个陷阱用例失败的原因。
248
+ // ⚠️ 项目名必须真的铺开在多数文档里,否则 df=1,测的就不是 IDF 了。
249
+ const docs = [
250
+ bm25Doc('noise.md', { title: 'knit', body: 'knit '.repeat(40) }, now),
251
+ bm25Doc('topic.md', { title: '排序', body: 'knit 排序 相关性排序 关键词 排序 命中' }, now),
252
+ bm25Doc('other.md', { title: '媒体', body: 'knit 的图片与视频浏览' }, now),
253
+ ]
254
+ const kws = extractKeywords(['knit 的排序是不是不准', 'knit 的相关性排序到底怎么算'])
255
+ const { docs: ranked } = rankByRelevance(docs, kws, now)
256
+ assert.equal(ranked[0].rel, 'topic.md', `高频词霸榜了:${ranked.map((d) => `${d.rel}=${d.score}`).join('/')}`)
257
+ })
258
+
259
+ test('rankByRelevance: 长度归一化压住「长文档堆词」(v0.6 核心行为)', () => {
260
+ const now = Date.now()
261
+ // 两篇都命中 3 次,但一篇是长文 —— 旧引擎只看命中次数,两者同分。
262
+ const docs = [
263
+ bm25Doc('short.md', { title: '排序', body: '排序 排序 排序' }, now),
264
+ bm25Doc('long.md', { title: '归档', body: `排序 排序 排序${'填充'.repeat(700)}` }, now),
265
+ ]
266
+ const kws = [{ term: '排序', weight: 100 }]
267
+ const { docs: ranked } = rankByRelevance(docs, kws, now)
268
+ assert.equal(ranked[0].rel, 'short.md', '短而聚焦的文档应当赢过长而堆词的')
269
+ assert.ok(ranked[1].score < 100, '长文档应当被长度归一化压低')
270
+ })
271
+
272
+ test('rankByRelevance: 语料里没有的词不贡献分数(df = 0 → idf = 0)', () => {
273
+ const now = Date.now()
274
+ const docs = [
275
+ bm25Doc('a.md', { title: '排序', body: '相关性排序' }, now),
276
+ bm25Doc('b.md', { title: '媒体', body: '图片与视频' }, now),
277
+ ]
278
+ // 一个语料里根本不存在、但权重极高的词,不该把任何一篇抬起来
279
+ const { docs: ranked, maxRaw, matched } = rankByRelevance(
280
+ docs, [{ term: 'zqxwv', weight: 9999 }], now,
281
+ )
282
+ assert.equal(maxRaw, 0, '没有词命中时 maxRaw 必须是 0')
283
+ assert.ok(ranked.every((d) => d.score === 0))
284
+ assert.deepEqual(matched, [], 'df = 0 的词不算 matched')
285
+ })
286
+
287
+ test('rankByRelevance: 字段全空(media 的 summary/body)不产生 NaN', () => {
288
+ const now = Date.now()
289
+ // kind=media 时每篇的 summary 与 body 都是空串 → avgdl 为 0。
290
+ // 不做短路的话这里会除零,NaN 会顺着 maxRaw 污染全部文档的分数。
291
+ const docs = [
292
+ bm25Doc('shot.png', { title: 'knit-screenshot.png' }, now),
293
+ bm25Doc('clip.mp4', { title: 'knit-clip.mp4' }, now),
294
+ ]
295
+ const { docs: ranked, maxRaw } = rankByRelevance(docs, [{ term: 'knit', weight: 10 }], now)
296
+ assert.ok(Number.isFinite(maxRaw), `maxRaw 不是有限数:${maxRaw}`)
297
+ assert.ok(ranked.every((d) => Number.isFinite(d.raw)), 'raw 里出现了 NaN/Infinity')
298
+ assert.ok(ranked.every((d) => Number.isInteger(d.score) && d.score >= 0 && d.score <= 100))
299
+ })
300
+
301
+ test('rankByRelevance: matched 只回语料里真实存在的词,且按权重降序', () => {
302
+ const now = Date.now()
303
+ const docs = [bm25Doc('a.md', { title: '排序', body: '相关性排序' }, now)]
304
+ // 三个词:两个语料里有,一个没有
305
+ const { matched } = rankByRelevance(docs, [
306
+ { term: '排序', weight: 10 },
307
+ { term: 'zzzz', weight: 900 },
308
+ { term: '相关性', weight: 50 },
309
+ ], now)
310
+ assert.deepEqual(matched, ['相关性', '排序'], '只留命中语料的词,且按权重降序')
197
311
  })
198
312
 
199
313
  test('topicLabel: 用、连接前几个词', () => {
@@ -276,8 +276,7 @@ test('错误码:完全没有 code 时退回通用文案', async () => {
276
276
  assert.match(textOf(byClass(en.nodes, 'knit-msg')[0]), /The host returned a failure/)
277
277
 
278
278
  const zh = await renderPanel('zh', () => ({ ok: false }))
279
- assert.match(textOf(byClass(zh.nodes, 'knit-msg')[0]), /宿主返回失败/)
280
- })
279
+ assert.match(textOf(byClass(zh.nodes, 'knit-msg')[0]), /宿主返回失败/)})
281
280
 
282
281
  /* ── 注册层面的文案 ─────────────────────────────────── */
283
282
 
@@ -342,3 +341,23 @@ test('冒烟:中英环境下渲染同一份数据都不抛错,且文案确
342
341
  assert.ok(!/Refresh|Sorted by/.test(zhText), `中文环境混进了英文:${zhText}`)
343
342
  assert.ok(!/刷新|按/.test(enText), `英文环境混进了中文:${enText}`)
344
343
  })
344
+
345
+ /* ── 文案洁癖:词典里不出现表情装饰 ───────────────────── */
346
+
347
+ test('词典:不出现 🤖 之类的表情字符(用户明确要求删掉)', async () => {
348
+ const { readFileSync } = await import('node:fs')
349
+ const source = readFileSync(new URL('../src/client/client.js', import.meta.url), 'utf8')
350
+
351
+ // 用户原话:「🤖 这个图标删除」—— 排序依据那行原本顶着这个表情。
352
+ // 只扫词典(ZH / EN 两段),因为组件的 🆕 是**有意的**新文档标记,不在词典里。
353
+ for (const name of ['ZH', 'EN']) {
354
+ const body = source.match(new RegExp(`const ${name} = \\{([\\s\\S]*?)\\n \\}`))
355
+ assert.ok(body, `没找到 ${name} 词典`)
356
+ // 只拦表情符号区(U+1F300–U+1FAFF),放行 → 这类排版符号
357
+ const found = [...body[1]].filter((ch) => {
358
+ const cp = ch.codePointAt(0)
359
+ return cp >= 0x1f300 && cp <= 0x1faff
360
+ })
361
+ assert.deepEqual(found, [], `${name} 词典里出现了表情字符:${found.join(' ')}`)
362
+ }
363
+ })
@@ -0,0 +1,149 @@
1
+ /**
2
+ * Knit v0.8 · 「当前话题」标签的可读性回归。
3
+ *
4
+ * 为什么单独一个文件:v0.6 的评测只量了**排序**(top-1 / MRR),
5
+ * 从来没量过标签 —— 于是「按「目文档、项目文」排序」这种碎片一路漏到了真机上,
6
+ * 是**验收时用 getUserMedia 之外的手段**(读会话日志)才发现的。
7
+ * 这个文件的唯一职责就是守住标签。
8
+ *
9
+ * 断言是**双向**的:
10
+ * - `expect`:真词必须出现(防止「什么都不显示」也算过关)
11
+ * - `deny`:**旧碎片必须不出现**(这是真正的回归钉)
12
+ * 另外所有标签词都必须是**输入里真实存在的子串** —— 标签只能来自用户自己打的字。
13
+ */
14
+ import test from 'node:test'
15
+ import assert from 'node:assert/strict'
16
+
17
+ import { readableTopics, extractKeywords, rankByRelevance } from '../src/host/relevance.js'
18
+ import { CORPUS, NOW } from './eval/fixture.mjs'
19
+
20
+ /**
21
+ * 跑一遍「抽词 → 按语料过滤 → 合并标签」的完整链路。
22
+ * @param {string} query - 一句话
23
+ * @returns {{label: string[], matched: string[]}} 标签与真实命中的词
24
+ */
25
+ function labelFor(query) {
26
+ const keywords = extractKeywords([query], 30)
27
+ const { matched, label } = rankByRelevance(CORPUS, keywords, NOW)
28
+ return { label, matched }
29
+ }
30
+
31
+ /**
32
+ * 用例。`deny` 里的都是 v0.8 之前真机上出现过的碎片。
33
+ * @type {Array<{q: string, expect: string[], deny: string[]}>}
34
+ */
35
+ const CASES = [
36
+ {
37
+ // 真机验收里 agent 自己拼的 query —— 旧标签就是「目文档、项目文、索引」
38
+ q: '项目文档 索引',
39
+ expect: ['项目文档'],
40
+ deny: ['目文档', '项目文'],
41
+ },
42
+ {
43
+ q: '这个项目有什么文档',
44
+ expect: ['项目', '文档'],
45
+ deny: ['目有什', '什么文'],
46
+ },
47
+ {
48
+ // 旧标签:「bm25、排序、关性排」
49
+ q: '排序算法 相关性排序 BM25',
50
+ expect: ['bm25', '排序算法', '相关性排序'],
51
+ deny: ['关性排', '序算法', '性排序'],
52
+ },
53
+ {
54
+ // 旧标签:「名白名、展名白、扩展名」
55
+ q: '扩展名白名单都放行什么',
56
+ expect: ['扩展名白名单'],
57
+ deny: ['名白名', '展名白'],
58
+ },
59
+ {
60
+ // 旧标签:「停浮层、悬停浮」
61
+ q: '悬停浮层是怎么做的',
62
+ expect: ['悬停浮层'],
63
+ deny: ['停浮层', '悬停浮'],
64
+ },
65
+ {
66
+ // 旧标签:「灰色太、色太深」;「对比度」被 CN_EDGE_STOP 的「对」误杀成「比度」
67
+ q: '这个灰色太深了,读文档对比度不够',
68
+ expect: ['对比度'],
69
+ deny: ['比度', '灰色太', '色太深'],
70
+ },
71
+ ]
72
+
73
+ test('话题标签: 真词必须出现,旧碎片必须不出现', () => {
74
+ // 大小写不敏感:标签是**切原文**得来的,所以保留用户自己打的大小写
75
+ // (打 BM25 就显示 BM25,不会被小写成 bm25)。这是有意的 —— 标签就该是用户的原话。
76
+ const has = (list, term) => list.some((x) => x === term || x.toLowerCase() === term.toLowerCase())
77
+ for (const testCase of CASES) {
78
+ const { label } = labelFor(testCase.q)
79
+ const text = label.join('、')
80
+ assert.ok(label.length > 0, `「${testCase.q}」不该没有标签`)
81
+ for (const want of testCase.expect) {
82
+ assert.ok(has(label, want), `「${testCase.q}」的标签应含「${want}」,实际是「${text}」`)
83
+ }
84
+ for (const bad of testCase.deny) {
85
+ assert.ok(!has(label, bad), `「${testCase.q}」的标签不该含碎片「${bad}」,实际是「${text}」`)
86
+ }
87
+ }
88
+ })
89
+
90
+ test('话题标签: 每个词都必须是输入里真实存在的子串', () => {
91
+ // 标签只能来自用户自己打的字 —— 合并区间时切错位置会切出输入里没有的串
92
+ for (const testCase of CASES) {
93
+ const { label } = labelFor(testCase.q)
94
+ for (const term of label) {
95
+ assert.ok(testCase.q.includes(term), `「${term}」不是「${testCase.q}」的子串`)
96
+ }
97
+ }
98
+ })
99
+
100
+ test('话题标签: 合并的是原文区间,不是把词拼起来', () => {
101
+ // 两个**重叠**的碎片 → 合并成原文那一段
102
+ const keywords = [
103
+ { term: '项目文', weight: 27, spans: [{ text: '项目文档 索引', start: 0, end: 3 }] },
104
+ { term: '目文档', weight: 27, spans: [{ text: '项目文档 索引', start: 1, end: 4 }] },
105
+ ]
106
+ assert.deepEqual(readableTopics(keywords, 3), ['项目文档'])
107
+ })
108
+
109
+ test('话题标签: 相邻但不重叠的两段不合并', () => {
110
+ // 合并相邻段会把「相关」+「性排」粘成更难看的「相关性排」—— 所以只认严格重叠。
111
+ // 两者权重相同,顺带不依赖 tie-break 的具体次序。
112
+ const keywords = [
113
+ { term: '相关', weight: 12, spans: [{ text: '相关性排序', start: 0, end: 2 }] },
114
+ { term: '性排', weight: 12, spans: [{ text: '相关性排序', start: 2, end: 4 }] },
115
+ ]
116
+ const out = readableTopics(keywords, 3)
117
+ assert.equal(out.length, 2, `相邻的两段应当各自成为一个标签,实际:${out.join('、')}`)
118
+ assert.ok(out.includes('相关') && out.includes('性排'), `实际:${out.join('、')}`)
119
+ })
120
+
121
+ test('话题标签: 合并后过长的丢掉,不吐一长串', () => {
122
+ const long = '一二三四五六七八九十甲乙丙丁'
123
+ const keywords = [
124
+ { term: '一二三', weight: 10, spans: [{ text: long, start: 0, end: 3 }] },
125
+ { term: '二三四', weight: 10, spans: [{ text: long, start: 1, end: 4 }] },
126
+ { term: '三四五', weight: 10, spans: [{ text: long, start: 2, end: 5 }] },
127
+ { term: '四五六', weight: 10, spans: [{ text: long, start: 3, end: 6 }] },
128
+ { term: '五六七', weight: 10, spans: [{ text: long, start: 4, end: 7 }] },
129
+ { term: '六七八', weight: 10, spans: [{ text: long, start: 5, end: 8 }] },
130
+ ]
131
+ const out = readableTopics(keywords, 3)
132
+ for (const term of out) {
133
+ assert.ok(term.length <= 12, `标签「${term}」太长了`)
134
+ }
135
+ })
136
+
137
+ test('话题标签: 没有 spans 时返回空数组(由调用方回落)', () => {
138
+ assert.deepEqual(readableTopics([{ term: '排序', weight: 10 }], 3), [])
139
+ assert.deepEqual(readableTopics([], 3), [])
140
+ })
141
+
142
+ test('话题标签: 按权重降序,且去重', () => {
143
+ const keywords = [
144
+ { term: '甲甲', weight: 5, spans: [{ text: '甲甲 乙乙', start: 0, end: 2 }] },
145
+ { term: '乙乙', weight: 20, spans: [{ text: '甲甲 乙乙', start: 3, end: 5 }] },
146
+ { term: '乙乙', weight: 20, spans: [{ text: '甲甲 乙乙', start: 3, end: 5 }] },
147
+ ]
148
+ assert.deepEqual(readableTopics(keywords, 3), ['乙乙', '甲甲'])
149
+ })
@@ -9,7 +9,7 @@
9
9
  import test from 'node:test'
10
10
  import assert from 'node:assert/strict'
11
11
 
12
- import { loadClientModule, createHarness, byClass, textOf, makeLocale } from './harness.mjs'
12
+ import { loadClientModule, createHarness, byClass, byExactClass, textOf, makeLocale } from './harness.mjs'
13
13
 
14
14
  const harness = createHarness()
15
15
  const React = globalThis.__knitReact
@@ -206,3 +206,152 @@ test('路径:成功时不残留上一次的错误提示', async () => {
206
206
  nodes = harness.render(h(KnitBody, { sessionId: 's1' }))
207
207
  assert.equal(byClass(nodes, 'knit-notice').length, 0, '再成功,提示应清掉')
208
208
  })
209
+
210
+ /* ── 预览头那行路径:点它打开的是这篇文档本身 ────────── */
211
+
212
+ test('路径:点预览头的路径,打开的是这篇文档的绝对路径', async () => {
213
+ const calls = []
214
+ globalThis.fetch = async (url) => ({
215
+ json: async () => (String(url).includes('/api/doc')
216
+ ? { ok: true, rel: 'a.md', title: 'A', text: '正文', truncated: false }
217
+ : listPayload()),
218
+ })
219
+ const { KnitBody } = boot({
220
+ openWorkspacePath: async (request) => { calls.push(request); return { ok: true, value: { opened: true } } },
221
+ }).exports.__test
222
+
223
+ harness.reset()
224
+ let nodes = harness.render(h(KnitBody, { sessionId: 's1' }))
225
+ await harness.flush()
226
+ nodes = harness.render(h(KnitBody, { sessionId: 's1' }))
227
+ byClass(nodes, 'knit-doc')[0].props.onClick()
228
+ nodes = harness.render(h(KnitBody, { sessionId: 's1' }))
229
+
230
+ byExactClass(nodes, 'knit-preview-path')[0].props.onClick()
231
+ await harness.flush()
232
+
233
+ assert.equal(calls.length, 1, '应调用一次')
234
+ assert.deepEqual(calls[0], { path: '/Users/me/proj/a.md' }, '用宿主给的绝对 path')
235
+ })
236
+
237
+ test('路径:宿主没给 path 时用 root + rel 兜底', async () => {
238
+ const calls = []
239
+ const payload = listPayload({
240
+ docs: [{ rel: 'sub/b.md', name: 'b.md', title: 'B', summary: 's', mtimeMs: Date.now(), score: null }],
241
+ })
242
+ globalThis.fetch = async (url) => ({
243
+ json: async () => (String(url).includes('/api/doc')
244
+ ? { ok: true, rel: 'sub/b.md', title: 'B', text: '正文', truncated: false }
245
+ : payload),
246
+ })
247
+ const { KnitBody } = boot({
248
+ openWorkspacePath: async (request) => { calls.push(request); return { ok: true, value: { opened: true } } },
249
+ }).exports.__test
250
+
251
+ harness.reset()
252
+ let nodes = harness.render(h(KnitBody, { sessionId: 's1' }))
253
+ await harness.flush()
254
+ nodes = harness.render(h(KnitBody, { sessionId: 's1' }))
255
+ byClass(nodes, 'knit-doc')[0].props.onClick()
256
+ nodes = harness.render(h(KnitBody, { sessionId: 's1' }))
257
+
258
+ byExactClass(nodes, 'knit-preview-path')[0].props.onClick()
259
+ await harness.flush()
260
+
261
+ assert.deepEqual(calls[0], { path: '/Users/me/proj/sub/b.md' }, 'root + rel 拼出来')
262
+ })
263
+
264
+ test('路径:拼不出绝对路径时按钮 disabled,点了也不发请求', async () => {
265
+ const calls = []
266
+ globalThis.fetch = async (url) => ({
267
+ json: async () => (String(url).includes('/api/doc')
268
+ ? { ok: true, rel: 'sub/b.md', title: 'B', text: '正文', truncated: false }
269
+ : listPayload({
270
+ root: '',
271
+ docs: [{ rel: 'sub/b.md', name: 'b.md', title: 'B', summary: 's', mtimeMs: Date.now(), score: null }],
272
+ })),
273
+ })
274
+ const { KnitBody } = boot({
275
+ openWorkspacePath: async (request) => { calls.push(request); return { ok: true, value: { opened: true } } },
276
+ }).exports.__test
277
+
278
+ harness.reset()
279
+ let nodes = harness.render(h(KnitBody, { sessionId: 's1' }))
280
+ await harness.flush()
281
+ nodes = harness.render(h(KnitBody, { sessionId: 's1' }))
282
+ byClass(nodes, 'knit-doc')[0].props.onClick()
283
+ nodes = harness.render(h(KnitBody, { sessionId: 's1' }))
284
+
285
+ const pathBtn = byExactClass(nodes, 'knit-preview-path')[0]
286
+ assert.equal(pathBtn.props.disabled, true, 'root 与 path 都拿不到 → 不给点')
287
+ pathBtn.props.onClick() // 回调里也有守卫,不该抛也不该发请求
288
+ await harness.flush()
289
+ assert.equal(calls.length, 0)
290
+ })
291
+
292
+ /**
293
+ * v0.10:预览头右上角那个位置从「新标签页」换成了「在本地打开」。
294
+ *
295
+ * 动机:「新标签页」开的是官方文档预览,但面板里已经有就地预览(重复度高、
296
+ * 用得少);而「用默认应用打开这篇文档」原本只藏在路径面包屑的悬停提示里。
297
+ * 把值钱的那个放到显眼处。双击列表行仍能开新标签页 —— 所以这条要同时断言
298
+ * **头部不再有「新标签页」**。
299
+ */
300
+ test('预览头:右上角是「在本地打开」,点击打开这篇文档', async () => {
301
+ const calls = []
302
+ globalThis.fetch = async (url) => ({
303
+ json: async () => (String(url).includes('/api/doc')
304
+ ? { ok: true, rel: 'a.md', title: 'A', text: '正文', truncated: false }
305
+ : listPayload()),
306
+ })
307
+ const { KnitBody } = boot({
308
+ openWorkspacePath: async (request) => { calls.push(request); return { ok: true, value: { opened: true } } },
309
+ }).exports.__test
310
+
311
+ harness.reset()
312
+ let nodes = harness.render(h(KnitBody, { sessionId: 's1' }))
313
+ await harness.flush()
314
+ nodes = harness.render(h(KnitBody, { sessionId: 's1' }))
315
+ byClass(nodes, 'knit-doc')[0].props.onClick()
316
+ nodes = harness.render(h(KnitBody, { sessionId: 's1' }))
317
+
318
+ const headBtns = byClass(nodes, 'knit-btn')
319
+ const labels = headBtns.map(textOf)
320
+ assert.ok(labels.includes('在本地打开'), '头部有「在本地打开」按钮,实际:' + labels.join(' / '))
321
+ assert.ok(!labels.includes('新标签页'), '「新标签页」已从头部移除,实际:' + labels.join(' / '))
322
+
323
+ const localBtn = headBtns.find((n) => textOf(n) === '在本地打开')
324
+ assert.notEqual(localBtn.props.disabled, true, '有服务时不禁用')
325
+ // tooltip 里带完整相对路径 —— 与路径面包屑同一套提示
326
+ assert.match(String(localBtn.props.title), /a\.md/, 'tooltip 里带相对路径')
327
+ localBtn.props.onClick()
328
+ await harness.flush()
329
+ assert.deepEqual(calls[0], { path: '/Users/me/proj/a.md' }, '打开的是这篇文档的绝对路径')
330
+ })
331
+
332
+ test('预览头:没有 remote.session 时「在本地打开」给出提示,不是白点一下', async () => {
333
+ globalThis.fetch = async (url) => ({
334
+ json: async () => (String(url).includes('/api/doc')
335
+ ? { ok: true, rel: 'a.md', title: 'A', text: '正文', truncated: false }
336
+ : listPayload()),
337
+ })
338
+ const { KnitBody } = boot({}).exports.__test // 不给 openWorkspacePath
339
+
340
+ harness.reset()
341
+ let nodes = harness.render(h(KnitBody, { sessionId: 's1' }))
342
+ await harness.flush()
343
+ nodes = harness.render(h(KnitBody, { sessionId: 's1' }))
344
+ byClass(nodes, 'knit-doc')[0].props.onClick()
345
+ nodes = harness.render(h(KnitBody, { sessionId: 's1' }))
346
+
347
+ const localBtn = byClass(nodes, 'knit-btn').find((n) => textOf(n) === '在本地打开')
348
+ assert.ok(localBtn, '按钮仍然渲染(位置稳定)')
349
+ // 「禁用」只在**拿不到绝对路径**时用;拿得到路径但没有服务,走「点了给可见提示」——
350
+ // 与路径面包屑同一条规矩(见「路径:没有 remote.session 服务时给出提示」)
351
+ assert.notEqual(localBtn.props.disabled, true, '路径拿得到 → 不禁用')
352
+
353
+ localBtn.props.onClick()
354
+ await harness.flush()
355
+ nodes = harness.render(h(KnitBody, { sessionId: 's1' }))
356
+ assert.ok(byClass(nodes, 'knit-notice').length >= 1, '应给出可见提示而不是白点一下')
357
+ })
@@ -309,7 +309,9 @@ test('即时响应:面板已挂着时,点浮层某篇立刻展开预览,
309
309
 
310
310
  await harness.flush() // 只等文档接口
311
311
  panel = harness.render(h(KnitBody, { sessionId: 's-1' }))
312
- assert.match(textOf(byExactClass(panel, 'knit-preview')[0]), /目标/, '正文应已渲染')
312
+ // 预览头现在显示路径面包屑(文件名)而不是标题 —— 见「预览头显示路径面包屑」那条用例
313
+ assert.match(textOf(byExactClass(panel, 'knit-preview')[0]), /target\.md/, '预览头应指向被点的那一篇')
314
+ assert.equal(byExactClass(panel, 'knit-preview-note').length, 0, '正文应已到 ready,不该还停在 loading')
313
315
  })
314
316
 
315
317
  test('即时响应:面板还没挂时,信号留成挂起值,挂载第一帧就取走', async () => {