dsh-fishpal 0.9.12 → 0.9.14

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,49 @@
1
+ // 回归:没选好友 = 全局面板(2026-11-30 晚岸:「有好友之后就只看得到那个好友的界面,
2
+ // 能不能不点好友看全局?」原行为:selectedFp 默认落 sorted[0],永远没有「没选」这个状态。)
3
+ import fs from 'node:fs';
4
+ import assert from 'node:assert/strict';
5
+
6
+ const SRC = fs.readFileSync(new URL('./lib/ui.js', import.meta.url), 'utf8');
7
+ // ★ 注释里会原样引用旧代码(我写注释习惯写「原来这里是 …」),
8
+ // 所以**每一段**静态断言前都要先剥注释,不只是整文件。
9
+ // 2026-11-30 同一个坑踩了第三次 —— 所以做成函数,切出来的块也过一遍。
10
+ const strip = (s) =>
11
+ s
12
+ .split('\n')
13
+ .filter((l) => !/^\s*\/\//.test(l))
14
+ .join('\n');
15
+ const CODE = strip(SRC);
16
+ let pass = 0;
17
+ const ok = (name, cond) => {
18
+ assert.ok(cond, name);
19
+ pass++;
20
+ console.log(' ✓ ' + name);
21
+ };
22
+
23
+ // 1. 不再默认选第一个好友
24
+ ok('selectedFp 不再回落到 sorted[0]', !/:\s*sorted\[0\]\?\.fp/.test(CODE));
25
+ ok('selectedFp 选不到人时为 null', /: null;\s*$/m.test(SRC.split('\n').find((l) => l.includes('const selectedFp')) || ''));
26
+
27
+ // 2. 没选人时右栏是全局,而不是一句「先点左边一个好友」
28
+ const drawerStart = SRC.indexOf('const drawerRows = (() => {');
29
+ const drawerEnd = SRC.indexOf('// ── 左栏', drawerStart);
30
+ assert.ok(drawerStart > 0 && drawerEnd > drawerStart, '找不到 drawerRows 块');
31
+ const drawer = strip(SRC.slice(drawerStart, drawerEnd));
32
+ ok('没选人时走全局分支(不再提示先点好友)', !/先点左边一个好友/.test(drawer));
33
+ ok('全局分支有「全局 · 所有好友共用」', /全局 · 所有好友共用/.test(drawer));
34
+ ok('全局分支就地算拉黑/软删(不引用 TDZ 变量)', /sorted\.filter\(\(f\) => f\.blocked\)/.test(drawer));
35
+
36
+ // 3. 左栏有回到全局的入口
37
+ ok('左栏有「全局」这一行', /href="\?" data-global="1"/.test(SRC));
38
+ ok('全局行在选中好友时不带 active', /'<a class="peer global' \+ \(selectedFp \? '' : ' active'\)/.test(SRC));
39
+
40
+ // 4. 逻辑等价表:sel 指不到人 / 为空 → cur 为 null
41
+ const pick = (sorted, sel) =>
42
+ sel && sorted.some((f) => f.fp === sel) ? sorted.find((f) => f.fp === sel) : null;
43
+ const friends = [{ fp: 'A' }, { fp: 'B' }];
44
+ ok('点好友 A → 显示 A 的设置', pick(friends, 'A')?.fp === 'A');
45
+ ok('sel 为空 → 全局(cur 为 null)', pick(friends, '') === null);
46
+ ok('sel 指向已删好友 → 回全局', pick(friends, 'GONE') === null);
47
+ ok('一个好友都没有 → 全局', pick([], '') === null);
48
+
49
+ console.log(`\n结果:${pass} 通过,0 失败`);
@@ -0,0 +1,121 @@
1
+ // 端到端:真的起一个本机服务,真发 POST 到 /api/bottlehistory,
2
+ // 然后**回磁盘看文件**(不是看接口返回的 ok —— 那只能证明它说了 ok)。
3
+ import fs from 'node:fs';
4
+ import os from 'node:os';
5
+ import path from 'node:path';
6
+ import { startSettingsServer } from './lib/localserver.js';
7
+ import * as H from './lib/bottle-history.js';
8
+
9
+ let pass = 0, fail = 0;
10
+ function ck(name, cond, extra) {
11
+ if (cond) { pass++; console.log('PASS ' + name); }
12
+ else { fail++; console.log('FAIL ' + name + (extra ? ' :: ' + extra : '')); }
13
+ }
14
+
15
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'fishpal-hist-'));
16
+ const file = path.join(dir, 'bottle-history.json');
17
+
18
+ // 起手四条:b1 有回信 + 收藏,b2 没回信,b3 没回信;s1 是我自己丢出去的
19
+ H.recordBottle(dir, { bottleId: 'b1', text: '第一只瓶子' });
20
+ H.recordBottle(dir, { bottleId: 'b2', text: '第二只瓶子' });
21
+ H.recordBottle(dir, { bottleId: 'b3', text: '第三只瓶子' });
22
+ H.recordSent(dir, { bottleId: 's1', text: '我丢出去的那只' });
23
+ H.attachReply(dir, { bottleId: 'b1', text: '这是我回它的信' });
24
+ H.setFavorite(dir, 'b1', true);
25
+
26
+ const srv = await startSettingsServer({
27
+ // 只有这个是强制的;别的一律不传 = 那些接口明确 503,跟本次验证无关
28
+ onFriendPatch: () => ({ ok: true }),
29
+ getUiHtml: () => '<html><body>stub</body></html>',
30
+ port: 0,
31
+ // ⚠️ 这个桩必须跟 lib/index.js 里的 onBottleHistory **同签名**,
32
+ // 否则「方向有没有透传」这件事在这里永远测不到(桩吃什么都不影响结果)。
33
+ onBottleHistory: ({ action, id, on, keepFavorites, direction }) => {
34
+ if (action === 'favorite') return H.setFavorite(dir, id, on === true);
35
+ if (action === 'delete') return H.deleteItem(dir, id);
36
+ const r = H.clearHistory(dir, {
37
+ keepFavorites: keepFavorites !== false,
38
+ direction: direction === 'in' || direction === 'out' ? direction : '',
39
+ });
40
+ return { ...r, stats: H.stats(dir) };
41
+ },
42
+ });
43
+
44
+ const base = 'http://127.0.0.1:' + srv.port + '/api/bottlehistory';
45
+ async function post(body) {
46
+ const r = await fetch(base, {
47
+ method: 'POST',
48
+ headers: { 'Content-Type': 'application/json' },
49
+ body: JSON.stringify({ token: srv.token, ...body }),
50
+ });
51
+ return { status: r.status, json: await r.json() };
52
+ }
53
+ function disk() {
54
+ return JSON.parse(fs.readFileSync(file, 'utf8'));
55
+ }
56
+
57
+ try {
58
+ // 0. 令牌不对必须被挡
59
+ const bad = await fetch(base, {
60
+ method: 'POST',
61
+ headers: { 'Content-Type': 'application/json' },
62
+ body: JSON.stringify({ token: 'wrong', action: 'clear' }),
63
+ });
64
+ ck('令牌不对被挡(403)', bad.status === 403);
65
+ ck('令牌不对时文件没动', disk().items.length === 4);
66
+
67
+ // 1. 不认识的动作被挡
68
+ const badAct = await post({ action: 'drop_everything' });
69
+ ck('不认识的动作被挡(400)', badAct.status === 400 && badAct.json.ok === false);
70
+
71
+ // 2. 收藏
72
+ const fav = await post({ action: 'favorite', id: 'b2', on: true });
73
+ ck('收藏 b2 返回 ok', fav.json.ok === true && fav.json.favorited === true);
74
+ ck('磁盘上 b2 真的 favorited=true', disk().items.find((x) => x.id === 'b2').favorited === true);
75
+
76
+ // 3. 取消收藏
77
+ const unfav = await post({ action: 'favorite', id: 'b2', on: false });
78
+ ck('取消收藏 b2', unfav.json.ok === true && unfav.json.favorited === false);
79
+ ck('磁盘上 b2 真的变回 false', disk().items.find((x) => x.id === 'b2').favorited === false);
80
+
81
+ // 4. 删一条
82
+ const del = await post({ action: 'delete', id: 'b3' });
83
+ ck('删 b3 返回 ok', del.json.ok === true);
84
+ const afterDel = disk().items;
85
+ ck('磁盘上 b3 真的没了', !afterDel.some((x) => x.id === 'b3'));
86
+ ck('删完还剩 b1 / b2', afterDel.filter((x) => ['b1', 'b2'].includes(x.id)).length === 2, 'n=' + afterDel.length);
87
+
88
+ // 4b. ★ 只清「丢出去的」——「收到的」必须**一条都不少**
89
+ // (岸:「当然这个也是可以删的」+「两个展览馆」= 各清各的)
90
+ const inBefore = disk().items.filter((x) => (x.direction || 'in') === 'in').length;
91
+ const clrOut = await post({ action: 'clear', keepFavorites: true, direction: 'out' });
92
+ ck('只清 out 返回 ok', clrOut.json.ok === true);
93
+ ck('磁盘上 s1(丢出去的)真的没了', !disk().items.some((x) => x.id === 's1'));
94
+ const inAfter = disk().items.filter((x) => (x.direction || 'in') === 'in').length;
95
+ ck('清 out 之后「收的」一条没少', inAfter === inBefore, inBefore + ' → ' + inAfter);
96
+
97
+ // 5. 删不存在的 → 400,不能假装成功
98
+ const del2 = await post({ action: 'delete', id: 'nope' });
99
+ ck('删不存在的返回 400(不假成功)', del2.status === 400 && del2.json.ok === false);
100
+
101
+ // 6. 全删,收藏的留下
102
+ const clr = await post({ action: 'clear', keepFavorites: true });
103
+ ck('全删返回 ok', clr.json.ok === true);
104
+ const afterClear = disk().items;
105
+ ck('全删之后只剩收藏的 b1', afterClear.length === 1 && afterClear[0].id === 'b1', JSON.stringify(afterClear.map((x) => x.id)));
106
+ ck('留着的 b1 回信还在', afterClear[0].reply && afterClear[0].reply.text === '这是我回它的信');
107
+
108
+ // 7. 全删(不保留收藏)—— 脚本才用,但也要能跑
109
+ const clr2 = await post({ action: 'clear', keepFavorites: false });
110
+ ck('keepFavorites=false 时全清空', clr2.json.ok === true && disk().items.length === 0);
111
+
112
+ // 8. 没有 id 的 favorite / delete 要挡
113
+ const noId = await post({ action: 'favorite' });
114
+ ck('favorite 不给 id 被挡(400)', noId.status === 400);
115
+ } finally {
116
+ srv.close();
117
+ fs.rmSync(dir, { recursive: true, force: true });
118
+ }
119
+
120
+ console.log('\n结果:' + pass + ' 通过,' + fail + ' 失败');
121
+ process.exit(fail ? 1 : 0);
@@ -0,0 +1,88 @@
1
+ // 回归:把这轮探针抓到的 5 个问题钉死。
2
+ // ★ 每条都用一个「改回旧写法就会红」的断言 —— 不是复述实现,是钉住行为。
3
+ import fs from 'node:fs';
4
+ import os from 'node:os';
5
+ import path from 'node:path';
6
+ import * as H from './lib/bottle-history.js';
7
+ import { renderUi } from './lib/ui.js';
8
+
9
+ let pass = 0, fail = 0;
10
+ function ck(name, cond, extra) {
11
+ if (cond) { pass++; console.log('PASS ' + name); }
12
+ else { fail++; console.log('FAIL ' + name + (extra ? ' :: ' + extra : '')); }
13
+ }
14
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'fp-hist-safety-'));
15
+ const file = path.join(dir, 'bottle-history.json');
16
+ const reset = () => fs.writeFileSync(file, JSON.stringify({ schemaVersion: 2, items: [] }), 'utf8');
17
+
18
+ // ── 1. 文件坏了:老数据必须留一份档,不能静默吞掉 ──
19
+ reset();
20
+ H.recordBottle(dir, { bottleId: 'old1', text: '老瓶子一号' });
21
+ H.recordBottle(dir, { bottleId: 'old2', text: '老瓶子二号' });
22
+ fs.writeFileSync(file, '{"schemaVersion":2,"items":[{"id":"old1","tex', 'utf8');
23
+ const gotEmpty = H.loadHistory(dir);
24
+ const corrupts = fs.readdirSync(dir).filter((n) => n.startsWith('bottle-history.json.corrupt-'));
25
+ ck('坏文件读出来是空账本(不崩)', gotEmpty.items.length === 0);
26
+ ck('坏文件被改名留档,不静默覆盖', corrupts.length === 1, JSON.stringify(corrupts));
27
+ if (corrupts.length === 1) {
28
+ // 留档里还有老数据的影子 —— 这就是「还有机会捞回来」
29
+ const kept = fs.readFileSync(path.join(dir, corrupts[0]), 'utf8');
30
+ ck('留档里还看得到老瓶子的内容', kept.includes('old1') || kept.includes('老瓶子'));
31
+ }
32
+ H.recordBottle(dir, { bottleId: 'new1', text: '坏掉之后写进来的' });
33
+ ck('覆盖之后新数据正常写进去', H.loadHistory(dir).items.some((x) => x.id === 'new1'));
34
+
35
+ // ── 2. 超长正文必须截断(收端不能信对面给自己限了长度) ──
36
+ reset();
37
+ H.recordBottle(dir, { bottleId: 'huge', text: 'A'.repeat(200_000) });
38
+ const stored = H.loadHistory(dir).items[0];
39
+ ck('20 万字的正文被截到 2000 以内', stored.text.length <= 2000, 'len=' + stored.text.length);
40
+ ck('文件不会因为一条大正文爆到 100KB 以上', fs.statSync(file).size < 100_000, 'size=' + fs.statSync(file).size);
41
+
42
+ // ── 3. 收藏塞满:新瓶子记不上时必须如实报失败,不能骗 ok ──
43
+ reset();
44
+ const full = { schemaVersion: 2, items: [] };
45
+ for (let i = 0; i < 2000; i++) {
46
+ full.items.push({ id: 'f' + i, bottleId: 'f' + i, text: 'x', nick: '', peerFp: '', reply: null, favorited: true, firstAt: 1, lastAt: 1 + i, count: 1 });
47
+ }
48
+ fs.writeFileSync(file, JSON.stringify(full), 'utf8');
49
+ const r = H.recordBottle(dir, { bottleId: 'brand-new', text: '新来的' });
50
+ ck('收藏塞满时 recordBottle 不报 ok', r.ok === false, JSON.stringify(r));
51
+ ck('报失败时给的原因说得清', typeof r.error === 'string' && r.error.includes('满'), r.error);
52
+ ck('磁盘上确实没有这条(没骗人)', !H.loadHistory(dir).items.some((x) => x.id === 'brand-new'));
53
+ ck('收藏的 2000 条一条没丢', H.stats(dir).total === 2000);
54
+
55
+ // 非收藏塞满时,老的未收藏该被顶掉、新的能进来
56
+ fs.writeFileSync(file, JSON.stringify({ schemaVersion: 2, items: Array.from({ length: 2000 }, (_, i) => ({ id: 'n' + i, bottleId: 'n' + i, text: 'x', nick: '', peerFp: '', reply: null, favorited: false, firstAt: 1, lastAt: 1 + i, count: 1 })) }), 'utf8');
57
+ const r2 = H.recordBottle(dir, { bottleId: 'newest-one', text: '新的' });
58
+ ck('非收藏塞满时新条目能进(顶掉最老的)', r2.ok === true && H.loadHistory(dir).items.some((x) => x.id === 'newest-one'));
59
+ ck('非收藏塞满时总量仍是 2000', H.stats(dir).total === 2000);
60
+
61
+ // ── 4. 超过 200 条:界面上要说清楚只列了一部分 ──
62
+ reset();
63
+ for (let i = 0; i < 260; i++) H.recordBottle(dir, { bottleId: 'u' + i, text: '瓶子' + i, at: 1700000000000 + i });
64
+ const list = H.listHistory(dir);
65
+ const html = renderUi({
66
+ me: { nickname: 't' }, meFp: 'fp_t',
67
+ bottles: { history: { ...H.stats(dir), items: list }, recv: [], replies: [], drafts: [], recent: [] },
68
+ rev: 'r', connected: true, friends: [], recallable: [], selected: '', quarantine: [],
69
+ budget: null, loop: null, panel: {}, outboxCount: 0,
70
+ generatedAt: new Date().toISOString(), globalLevel: 'chat-only',
71
+ });
72
+ ck('260 条时界面写明「只列最近 200 条」', html.includes('只列最近 200 条'));
73
+ ck('260 条时告诉人还有多少条没列', html.includes('更早的 60 条'));
74
+ ck('260 条时仍然渲染出 200 条', (html.match(/class="bqitem"/g) || []).length === 200, String((html.match(/class="bqitem"/g) || []).length));
75
+
76
+ // ── 5. at=0 不能被当成「现在是 0 所以用现在」 ──
77
+ reset();
78
+ H.recordBottle(dir, { bottleId: 'z', text: 'x', at: 0 });
79
+ ck('at=0 时回退到当前时间(不是存成 0 也不是丢)',
80
+ typeof H.loadHistory(dir).items[0].firstAt === 'number' && H.loadHistory(dir).items[0].firstAt > 0);
81
+
82
+ // ── 6. 前端刷新计数的函数真的在页面里(删一条之后标题要跟着变) ──
83
+ ck('页面里有 bottleHistoryRefreshCount', html.includes('function bottleHistoryRefreshCount'));
84
+ ck('删一条的路径会调它', /function bottleHistoryDel[\s\S]{0,600}bottleHistoryRefreshCount/.test(html));
85
+
86
+ fs.rmSync(dir, { recursive: true, force: true });
87
+ console.log('\n结果:' + pass + ' 通过,' + fail + ' 失败');
88
+ process.exit(fail ? 1 : 0);
@@ -0,0 +1,84 @@
1
+ // 两个展览馆(2026-12-01 岸:「一个是收的瓶子,一个是丢的瓶子」+「收到了回信,也是
2
+ // 附在那个瓶子那边」)的语义钉子。
3
+ //
4
+ // ★ 这个文件存在的理由:这里钉的三条全都**曾经是 bug**,不是想象出来的场景。
5
+ // ① 我丢出去的瓶子,被人回了 —— 回信的 bottle_id 跟我那只**是同一个 id**
6
+ // (bottle.js:1005,`bottle_id` 和 `reply_to_bottle_id` 填的是同一个 key)。
7
+ // 以前走普通更新分支,**我写的正文被对方的回信覆盖**,署名还被改成了对方。
8
+ // 实测过一次:发「我丢出去的那只瓶子」→ 收回信 → 变成「别人回我的话」。
9
+ // ② 收的 / 丢的必须分开列表,不能串。
10
+ // ③ 清一个馆不能带走另一个馆。
11
+ import fs from 'node:fs';
12
+ import os from 'node:os';
13
+ import path from 'node:path';
14
+ import * as H from './lib/bottle-history.js';
15
+
16
+ let pass = 0, fail = 0;
17
+ function ck(name, cond, extra) {
18
+ if (cond) { pass++; console.log('PASS ' + name); }
19
+ else { fail++; console.log('FAIL ' + name + (extra ? ' :: ' + extra : '')); }
20
+ }
21
+
22
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'fishpal-halls-'));
23
+ const file = path.join(dir, 'bottle-history.json');
24
+ const disk = () => JSON.parse(fs.readFileSync(file, 'utf8'));
25
+
26
+ try {
27
+ // ── ① 发出去的那只,收到回信之后**一个字都不能变** ──
28
+ H.recordSent(dir, { bottleId: 's1', text: '我丢出去的那只瓶子' });
29
+ const before = H.listHistory(dir).find((x) => x.id === 's1');
30
+ ck('发出去记成 out', before && before.direction === 'out');
31
+ ck('发出去的正文是我写的', before.text === '我丢出去的那只瓶子');
32
+
33
+ // 别人的回信:bottle_id 跟我丢的相同(协议里就是这样)
34
+ H.recordBottle(dir, { bottleId: 's1', text: '别人回我的话', nick: '陌生人' });
35
+ const after = H.listHistory(dir).find((x) => x.id === 's1');
36
+ ck('★ 我写的正文没被回信覆盖', after.text === '我丢出去的那只瓶子', '实际:' + after.text);
37
+ ck('★ 署名没被改成对方', after.nick === '', '实际:' + after.nick);
38
+ ck('★ 方向还是 out', after.direction === 'out');
39
+ ck('★ 发了几遍没被回信涨上去', Number(after.count) === 1, 'count=' + after.count);
40
+ ck('回信挂在 gotReply 上', !!(after.gotReply && after.gotReply.text === '别人回我的话'));
41
+ ck('gotReply 记下了是谁回的', after.gotReply && after.gotReply.nick === '陌生人');
42
+ ck('没有因为回信多出一条', disk().items.length === 1, 'n=' + disk().items.length);
43
+
44
+ // ── ② 收的 / 丢的,各在各的列表 ──
45
+ H.recordBottle(dir, { bottleId: 'i1', text: '我捡到的一只' });
46
+ H.attachReply(dir, { bottleId: 'i1', text: '我回它的信' });
47
+ const ins = H.listHistory(dir, { direction: 'in' });
48
+ const outs = H.listHistory(dir, { direction: 'out' });
49
+ ck('收的馆里有 i1', ins.some((x) => x.id === 'i1'));
50
+ ck('收的馆里没有 s1', !ins.some((x) => x.id === 's1'));
51
+ ck('丢的馆里有 s1', outs.some((x) => x.id === 's1'));
52
+ ck('丢的馆里没有 i1', !outs.some((x) => x.id === 'i1'));
53
+ const st = H.stats(dir);
54
+ ck('分方向统计:in=1', st.in.total === 1);
55
+ ck('分方向统计:out=1', st.out.total === 1);
56
+ ck('分方向统计:合计=2', st.total === 2);
57
+
58
+ // ── ③ 清一个馆,另一个馆一条不动 ──
59
+ // 再加两只,保证两边都有内容,别用「本来就空」骗过测试
60
+ H.recordBottle(dir, { bottleId: 'i2', text: '另一只捡到的' });
61
+ H.recordSent(dir, { bottleId: 's2', text: '另一只丢出去的' });
62
+ const beforeIns = H.listHistory(dir, { direction: 'in' }).length;
63
+ const beforeOuts = H.listHistory(dir, { direction: 'out' }).length;
64
+ ck('清之前两边都有货', beforeIns === 2 && beforeOuts === 2, beforeIns + '/' + beforeOuts);
65
+
66
+ const clr = H.clearHistory(dir, { keepFavorites: true, direction: 'out' });
67
+ ck('只清 out 报 ok', clr.ok === true);
68
+ ck('out 清空了', H.listHistory(dir, { direction: 'out' }).length === 0);
69
+ ck('★ in 一条都没少', H.listHistory(dir, { direction: 'in' }).length === beforeIns,
70
+ '剩 ' + H.listHistory(dir, { direction: 'in' }).length);
71
+ ck('in 的内容还在', H.listHistory(dir, { direction: 'in' }).some((x) => x.id === 'i1'));
72
+
73
+ // ── ④ 收藏的不会被「清空」带走(两个馆各自守这条)──
74
+ H.setFavorite(dir, 'i1', true);
75
+ const clr2 = H.clearHistory(dir, { keepFavorites: true, direction: 'in' });
76
+ ck('清 in 之后收藏的 i1 还在', H.listHistory(dir, { direction: 'in' }).some((x) => x.id === 'i1'));
77
+ ck('清 in 之后没收藏的 i2 没了', !H.listHistory(dir, { direction: 'in' }).some((x) => x.id === 'i2'));
78
+ ck('清 in 报了留下的条数', Number(clr2.kept) === 1, 'kept=' + clr2.kept);
79
+ } finally {
80
+ fs.rmSync(dir, { recursive: true, force: true });
81
+ }
82
+
83
+ console.log('\n结果:' + pass + ' 通过,' + fail + ' 失败');
84
+ process.exit(fail ? 1 : 0);
@@ -0,0 +1,151 @@
1
+ // 验证:漂流瓶收藏馆的 UI 接线
2
+ // ① renderUi 能渲染出来(不崩)
3
+ // ② 新块出现在 HTML 里(空状态 / 有数据两种)
4
+ // ③ 抽出的 inline <script> 能被 new Function 解析(页面上所有函数都靠它)
5
+ import { renderUi } from './lib/ui.js';
6
+
7
+ let pass = 0, fail = 0;
8
+ function ck(name, cond, extra) {
9
+ if (cond) { pass++; console.log('PASS ' + name); }
10
+ else { fail++; console.log('FAIL ' + name + (extra ? ' :: ' + extra : '')); }
11
+ }
12
+
13
+ function mkView(history) {
14
+ return {
15
+ me: { nickname: '测试鱼' },
16
+ meFp: 'fp_test',
17
+ // ★ bottles 才是漂流瓶数据(bottle 是收瓶开关那份 config,两个字段名很像,别搞混)
18
+ bottles: { history, recv: [], replies: [], drafts: [], recent: [] },
19
+ rev: 'r1',
20
+ connected: true,
21
+ friends: [],
22
+ recallable: [],
23
+ selected: '',
24
+ quarantine: [],
25
+ budget: null,
26
+ loop: null,
27
+ panel: {},
28
+ outboxCount: 0,
29
+ generatedAt: new Date().toISOString(),
30
+ globalLevel: 'chat-only',
31
+ };
32
+ }
33
+
34
+ function extractScripts(html) {
35
+ const out = [];
36
+ const re = /<script\b[^>]*>([\s\S]*?)<\/script>/gi;
37
+ let m;
38
+ while ((m = re.exec(html))) if (m[1] && m[1].trim()) out.push(m[1]);
39
+ return out;
40
+ }
41
+
42
+ // ── 空账本 ──
43
+ let htmlEmpty = '';
44
+ try {
45
+ htmlEmpty = renderUi(mkView({ total: 0, replied: 0, unreplied: 0, favorited: 0, items: [], inItems: [], outItems: [] }));
46
+ ck('空账本能渲染(不崩)', typeof htmlEmpty === 'string' && htmlEmpty.length > 1000, 'len=' + htmlEmpty.length);
47
+ } catch (e) {
48
+ ck('空账本能渲染(不崩)', false, e.message);
49
+ }
50
+ // ★ 2026-12-01 岸:「就是有两个展览馆,一个是收的瓶子,一个是丢的瓶子。」
51
+ // 所以空账本里也得两块都在 —— 少一个就是「功能没做」。
52
+ ck('空账本里「收到的瓶子」在', htmlEmpty.includes('id="bottleHistoryIn"'));
53
+ ck('空账本里「丢出去的瓶子」在', htmlEmpty.includes('id="bottleHistoryOut"'));
54
+ ck('空账本写明「收的」还空着', htmlEmpty.includes('还没捡到过瓶子'));
55
+ ck('空账本写明「丢的」还空着', htmlEmpty.includes('还没扔过瓶子'));
56
+
57
+ // ── 有数据:**收的**和**丢的**各归各的馆 ──
58
+ const inItems = [
59
+ { id: 'b1', bottleId: 'b1', direction: 'in', text: '第一只瓶子:你好呀', nick: '', reply: { text: '我回你一句', at: Date.now(), status: 'approved' }, favorited: true, firstAt: Date.now(), lastAt: Date.now(), count: 1 },
60
+ { id: 'b2', bottleId: 'b2', direction: 'in', text: '第二只瓶子:今天下雨', nick: '匿名者', reply: null, favorited: false, firstAt: Date.now(), lastAt: Date.now(), count: 3 },
61
+ ];
62
+ const outItems = [
63
+ { id: 's1', bottleId: 's1', direction: 'out', text: '我扔出去的那只', nick: '', reply: null, gotReply: { text: '捡到的人回了我一句', at: Date.now(), nick: '捡到的人' }, favorited: false, firstAt: Date.now(), lastAt: Date.now(), count: 4 },
64
+ { id: 's2', bottleId: 's2', direction: 'out', text: '还没人理的那只', nick: '', reply: null, gotReply: null, favorited: false, firstAt: Date.now(), lastAt: Date.now(), count: 1 },
65
+ ];
66
+ let htmlData = '';
67
+ try {
68
+ htmlData = renderUi(
69
+ mkView({
70
+ total: 3, replied: 1, unreplied: 2, favorited: 1,
71
+ in: { total: 2, replied: 1, unreplied: 1, favorited: 1 },
72
+ out: { total: 2, replied: 1, unreplied: 1, favorited: 0 },
73
+ items: [...inItems, ...outItems],
74
+ inItems,
75
+ outItems,
76
+ })
77
+ );
78
+ ck('有数据能渲染', typeof htmlData === 'string' && htmlData.includes('第一只瓶子'));
79
+ } catch (e) {
80
+ ck('有数据能渲染', false, e.message);
81
+ }
82
+ // 两头都出现在页面里
83
+ ck('收的瓶子出现', htmlData.includes('第一只瓶子') && htmlData.includes('第二只瓶子'));
84
+ ck('丢出去的瓶子也出现', htmlData.includes('我扔出去的那只'));
85
+ // ★ 关键:**不许串馆**。丢出去的正文如果出现在「收的」那个 details 里,就是最坏的那种错。
86
+ function sliceHall(html, id) {
87
+ const i = html.indexOf('id="' + id + '"');
88
+ if (i < 0) return '';
89
+ const j = html.indexOf('</details>', i);
90
+ return j > i ? html.slice(i, j) : html.slice(i, i + 20000);
91
+ }
92
+ const inHall = sliceHall(htmlData, 'bottleHistoryIn');
93
+ const outHall = sliceHall(htmlData, 'bottleHistoryOut');
94
+ ck('「收的」馆里只有收的', inHall.includes('第一只瓶子') && !inHall.includes('我扔出去的那只'));
95
+ ck('「丢出去的」馆里只有丢的', outHall.includes('我扔出去的那只') && !outHall.includes('第一只瓶子'));
96
+ ck('回了的那条显示回信', inHall.includes('我回的那封信') && inHall.includes('我回你一句'));
97
+ ck('没回的那条写「这只我没回」', inHall.includes('这只我没回'));
98
+ ck('收藏标记出现', htmlData.includes('【收藏】') && htmlData.includes('已收藏'));
99
+ // 丢出去的那只讲的是「发了几遍」,不是「收到过几次」
100
+ ck('发了好几遍要标出来(不是「收到过」)', outHall.includes('发了 4 遍') && !outHall.includes('收到过 4 次'));
101
+ // ★ 2026-12-01:别人回了我丢的瓶子,回信要挂在**丢的**那条旁边(岸原话「也是附在那个瓶子那边」)
102
+ ck('丢出去的被回了 → 显示「有人回了你一句」', outHall.includes('有人回了你一句'));
103
+ ck('回信正文出现在丢的馆里', outHall.includes('捡到的人回了我一句'));
104
+ ck('没被回的那只写「还没人回这只」', outHall.includes('还没人回这只'));
105
+ // 反向:丢的馆里不该出现「我回的那封信」(那是我回别人,属收到的馆)
106
+ ck('丢的馆里不混「我回的那封信」', !outHall.includes('我回的那封信'));
107
+ // 两个馆各有一个清空按钮,而且名字分开
108
+ ck('「收的」有清空按钮', inHall.includes('清空收到的瓶子'));
109
+ ck('「丢出去的」有清空按钮', outHall.includes('清空丢出去的瓶子'));
110
+ ck('带「清空(保留收藏的 1 条)」', inHall.includes('保留收藏的 1 条'));
111
+ ck('三个前端函数都在页面里',
112
+ htmlData.includes('function bottleHistoryFav') &&
113
+ htmlData.includes('function bottleHistoryDel') &&
114
+ htmlData.includes('function bottleHistoryClear'));
115
+ // ★ 清空必须带方向,否则清一个馆会连另一个一起清 —— 这是最容易误伤的一步
116
+ ck('清空请求带方向', htmlData.includes("direction: dir") || htmlData.includes('direction: dir'));
117
+
118
+ // ── inline script 能不能解析(这是页面上所有按钮的命)──
119
+ const scripts = extractScripts(htmlData);
120
+ ck('抽到 inline script', scripts.length > 0, 'n=' + scripts.length);
121
+ let parseOk = true, parseErr = '';
122
+ for (const s of scripts) {
123
+ try { new Function(s); } catch (e) { parseOk = false; parseErr = e.message; break; }
124
+ }
125
+ ck('inline script 能被 new Function 解析', parseOk, parseErr);
126
+
127
+ // ── 没有 history 字段时也不能崩(老 view / 降级路径)──
128
+ let htmlNoHist = '';
129
+ try {
130
+ const v = mkView(null);
131
+ delete v.bottles.history;
132
+ htmlNoHist = renderUi(v);
133
+ ck('没有 history 字段也不崩', typeof htmlNoHist === 'string');
134
+ } catch (e) {
135
+ ck('没有 history 字段也不崩', false, e.message);
136
+ }
137
+
138
+ // ── 没有本机小服务(bottles 整个是 null)时,两块都不该出现 ──
139
+ let htmlNoSrv = '';
140
+ try {
141
+ const v = mkView(null);
142
+ v.bottles = null;
143
+ htmlNoSrv = renderUi(v);
144
+ ck('没有本机服务时不渲染两个馆',
145
+ !htmlNoSrv.includes('id="bottleHistoryIn"') && !htmlNoSrv.includes('id="bottleHistoryOut"'));
146
+ } catch (e) {
147
+ ck('没有本机服务时不渲染两个馆', false, e.message);
148
+ }
149
+
150
+ console.log('\n结果:' + pass + ' 通过,' + fail + ' 失败');
151
+ process.exit(fail ? 1 : 0);
@@ -0,0 +1,142 @@
1
+ // presence:在线状态判据(第①层:对面 DSH 在不在)
2
+ // 2026-11-30 晚岸提的判据坑:「万一对方收到了没回,显示却是不在线」——
3
+ // 这套测试就是钉住「不回 ≠ 不在线」。
4
+ import assert from 'node:assert/strict';
5
+ import {
6
+ STATE,
7
+ STALE_MS,
8
+ PROBE,
9
+ presenceTopic,
10
+ fpFromTopic,
11
+ buildPacket,
12
+ parsePacket,
13
+ createPresence,
14
+ } from './lib/presence.js';
15
+
16
+ let pass = 0;
17
+ const ok = (name, cond) => {
18
+ assert.ok(cond, name);
19
+ pass++;
20
+ console.log(' ✓ ' + name);
21
+ };
22
+
23
+ // ── topic ────────────────────────────────────────────────────────────────
24
+ const fp = 'fp_00000000000000000000000000000000';
25
+ const topic = presenceTopic(fp);
26
+ ok('topic 形状对', topic === 'fishpal/presence/' + fp);
27
+ ok('topic 能反解回 fp', fpFromTopic(topic) === fp);
28
+ ok('别的 topic 反解成 null', fpFromTopic('fishpal/peer/abc') === null);
29
+ ok('presence topic 非法字符被剥掉', presenceTopic('a/b c') === 'fishpal/presence/abc');
30
+
31
+ // ── 报文 ─────────────────────────────────────────────────────────────────
32
+ const raw = buildPacket(fp, true, 1000);
33
+ const parsed = parsePacket(raw);
34
+ ok('报文往返:fp', parsed.fp === fp);
35
+ ok('报文往返:online', parsed.online === true);
36
+ ok('报文往返:ts', parsed.ts === 1000);
37
+
38
+ ok('不是 JSON → null(不能当离线)', parsePacket('hello') === null);
39
+ ok('缺 fp → null', parsePacket('{"online":true}') === null);
40
+ ok('online 不是布尔 → null', parsePacket('{"fp":"x","online":"yes"}') === null);
41
+ ok('null 输入 → null', parsePacket(null) === null);
42
+
43
+ // ── 四态 ─────────────────────────────────────────────────────────────────
44
+ const T0 = 1_000_000;
45
+ let pres = createPresence({ now: () => T0 });
46
+
47
+ ok('从没收到过 → unknown(不猜成离线)', pres.stateOf('ghost') === STATE.UNKNOWN);
48
+
49
+ pres.ingest(buildPacket('A', true, T0), T0);
50
+ ok('收到 online:true → online', pres.stateOf('A', T0) === STATE.ONLINE);
51
+
52
+ pres.ingest(buildPacket('B', false, T0), T0);
53
+ ok('收到 online:false → offline', pres.stateOf('B', T0) === STATE.OFFLINE);
54
+
55
+ // 在线过,但很久没更新 → away(可能断了,遗嘱还没来)
56
+ ok('在线但超过 STALE → away', pres.stateOf('A', T0 + STALE_MS + 1) === STATE.AWAY);
57
+ ok('在线且刚好在 STALE 内 → online', pres.stateOf('A', T0 + STALE_MS) === STATE.ONLINE);
58
+
59
+ // ── ★ 核心判据:不回话不等于不在线 ──────────────────────────────────────
60
+ // 这条是岸自己指出的坑。presence 只认连接层,压根不看 messages / lastAt / 回没回。
61
+ pres = createPresence({ now: () => T0 });
62
+ pres.ingest(buildPacket('silent', true, T0), T0);
63
+ ok(
64
+ '★ 对方一直没回话,但 presence 是在线 → 仍然 online',
65
+ pres.stateOf('silent', T0 + 60_000) === STATE.ONLINE
66
+ );
67
+ // 没有 ingest 过任何「消息」类东西,也不影响判定 —— 状态只由 presence 决定
68
+ ok('★ 没收到过任何消息,不影响在线判定', pres.stateOf('silent', T0 + 5 * 60_000) === STATE.ONLINE);
69
+
70
+ // ── 旧报文不能盖新报文(retain 重放会先给你一条很旧的)──────────────────
71
+ pres = createPresence({ now: () => T0 });
72
+ pres.note('C', false, T0 + 5000); // 新:离线
73
+ pres.ingest(buildPacket('C', true, T0), T0 + 1); // 旧:在线(重放)
74
+ ok('旧报文不覆盖新报文', pres.stateOf('C', T0 + 5000) === STATE.OFFLINE);
75
+
76
+ // ── 非 presence 报文不会污染状态 ─────────────────────────────────────────
77
+ pres = createPresence({ now: () => T0 });
78
+ ok('普通消息 ingest 返回 null', pres.ingest('{"type":"chat","text":"hi"}', T0) === null);
79
+ ok('普通消息不会把状态变成 offline', pres.stateOf('D', T0) === STATE.UNKNOWN);
80
+
81
+ // ── snapshot / clear ─────────────────────────────────────────────────────
82
+ pres = createPresence({ now: () => T0 });
83
+ pres.ingest(buildPacket('E', true, T0), T0);
84
+ ok('snapshot 里有 E', pres.snapshot().E && pres.snapshot().E.online === true);
85
+ pres.clear();
86
+ ok('clear 之后回到 unknown', pres.stateOf('E', T0) === STATE.UNKNOWN);
87
+
88
+ // ── freshOf ──────────────────────────────────────────────────────────────
89
+ pres = createPresence({ now: () => T0 });
90
+ ok('没记录时 freshOf 是 false', pres.freshOf('F', T0) === false);
91
+ pres.ingest(buildPacket('F', true, T0), T0);
92
+ ok('刚收到时 freshOf 是 true', pres.freshOf('F', T0 + 1000) === true);
93
+ ok('超过 FRESH 后 freshOf 是 false', pres.freshOf('F', T0 + 5 * 60_000) === false);
94
+
95
+ // ── 惰性探测(岸 2026-11-30 晚的方案)────────────────────────────────────
96
+ pres = createPresence({ now: () => T0 });
97
+ ok('从没收到过 → 不该探', pres.due('ghost', T0).due === false);
98
+
99
+ pres.ingest(buildPacket('P', true, T0), T0);
100
+ ok('刚收到状态 → 不该探(省着点)', pres.due('P', T0 + 1000).due === false);
101
+ ok('超过 AFTER_MS → 该探', pres.due('P', T0 + PROBE.AFTER_MS + 1).due === true);
102
+
103
+ pres.markProbe('P', 'n1', T0 + PROBE.AFTER_MS + 1);
104
+ ok('正在探的时候不叠着探', pres.due('P', T0 + PROBE.AFTER_MS + 2000).due === false);
105
+
106
+ // ★ 最关键的一条:从没回过 pong(可能旧版本不认 ping)—— 超时也**不许**判离线
107
+ pres = createPresence({ now: () => T0 });
108
+ pres.ingest(buildPacket('old', true, T0), T0);
109
+ ok('旧的对方:没回过 pong', pres.probeCapable('old') === false);
110
+ pres.markProbe('old', 'n1', T0);
111
+ const settledOld = pres.tick(T0 + PROBE.TIMEOUT_MS + 1);
112
+ ok('旧版本探测超时 → 不能判离线', pres.stateOf('old', T0 + PROBE.TIMEOUT_MS + 1) !== STATE.OFFLINE);
113
+ ok('旧版本探测超时 → 结论是「不确定」(away)', settledOld[0]?.verdict === STATE.AWAY);
114
+
115
+ // ★ 认 ping 的对方:回过一次 pong 之后,超时才能判离线
116
+ pres = createPresence({ now: () => T0 });
117
+ pres.ingest(buildPacket('new', true, T0), T0);
118
+ pres.markPong('new', T0 + 1000);
119
+ ok('回过 pong → 认得它认 ping', pres.probeCapable('new') === true);
120
+ pres.markProbe('new', 'n2', T0 + 2000);
121
+ pres.tick(T0 + 2000 + PROBE.TIMEOUT_MS + 1);
122
+ ok('★ 认 ping 的对方超时没回 → 判离线', pres.stateOf('new', T0 + 2000 + PROBE.TIMEOUT_MS + 1) === STATE.OFFLINE);
123
+ ok('判离线后不再探', pres.due('new', T0 + 9000).due === false);
124
+
125
+ // markPong 本身也算一次「确认在线」
126
+ pres = createPresence({ now: () => T0 });
127
+ pres.markPong('X', T0);
128
+ ok('markPong 直接把状态刷成在线', pres.stateOf('X', T0) === STATE.ONLINE);
129
+
130
+ // 日上限:一天探满 MAX_PER_DAY 次之后就不探了
131
+ pres = createPresence({ now: () => T0 });
132
+ pres.ingest(buildPacket('cap', true, T0), T0);
133
+ for (let i = 0; i < PROBE.MAX_PER_DAY; i++) {
134
+ pres.markProbe('cap', 'n' + i, T0 + PROBE.AFTER_MS + 1);
135
+ pres.tick(T0 + PROBE.AFTER_MS + 1 + PROBE.TIMEOUT_MS + 1);
136
+ }
137
+ ok(
138
+ '探满一天上限后不再探',
139
+ pres.due('cap', T0 + PROBE.AFTER_MS + 10 * 60_000) .due === false
140
+ );
141
+
142
+ console.log(`\n结果:${pass} 通过,0 失败`);