@weitc/dfy-awesome-sidebar 0.0.0-stage → 1.0.2

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.
Files changed (120) hide show
  1. package/CHANGELOG.md +4540 -0
  2. package/FEASIBILITY.md +250 -0
  3. package/INSTALL.md +93 -0
  4. package/LICENSE +43 -0
  5. package/README.md +170 -2
  6. package/assets/backgrounds/sidebar-default.jpg +0 -0
  7. package/assets/eggs/325/avatar.png +0 -0
  8. package/assets/eggs/325/baka-65-105-40s.webm +0 -0
  9. package/assets/eggs/325/stage.jpg +0 -0
  10. package/assets/eggs/347/avatar.png +0 -0
  11. package/assets/eggs/347/stage.jpg +0 -0
  12. package/assets/eggs/347/track-10-50-40s.webm +0 -0
  13. package/assets/themes/glass/actions-frame.css +90 -0
  14. package/assets/themes/glass/brand-frame.css +64 -0
  15. package/assets/themes/glass/footer-frame.css +111 -0
  16. package/assets/themes/glass/header-frame.css +285 -0
  17. package/assets/themes/glass/options-frame.css +129 -0
  18. package/assets/themes/glass/sidebar-outer.css +66 -0
  19. package/assets/themes/glass/topbar-frame.css +91 -0
  20. package/assets/themes/metal/actions-frame.css +90 -0
  21. package/assets/themes/metal/brand-frame.css +64 -0
  22. package/assets/themes/metal/footer-frame.css +111 -0
  23. package/assets/themes/metal/header-frame.css +300 -0
  24. package/assets/themes/metal/options-frame.css +129 -0
  25. package/assets/themes/metal/sidebar-outer.css +66 -0
  26. package/assets/themes/metal/topbar-frame.css +91 -0
  27. package/assets/themes/minimal/actions-frame.css +90 -0
  28. package/assets/themes/minimal/brand-frame.css +64 -0
  29. package/assets/themes/minimal/footer-frame.css +115 -0
  30. package/assets/themes/minimal/header-frame.css +271 -0
  31. package/assets/themes/minimal/options-frame.css +129 -0
  32. package/assets/themes/minimal/sidebar-outer.css +66 -0
  33. package/assets/themes/minimal/topbar-frame.css +91 -0
  34. package/assets/themes/neon/actions-frame.css +90 -0
  35. package/assets/themes/neon/brand-frame.css +64 -0
  36. package/assets/themes/neon/footer-frame.css +111 -0
  37. package/assets/themes/neon/header-frame.css +286 -0
  38. package/assets/themes/neon/options-frame.css +129 -0
  39. package/assets/themes/neon/sidebar-outer.css +66 -0
  40. package/assets/themes/neon/topbar-frame.css +91 -0
  41. package/assets/themes/ocean/actions-frame.css +90 -0
  42. package/assets/themes/ocean/brand-frame.css +64 -0
  43. package/assets/themes/ocean/footer-frame.css +111 -0
  44. package/assets/themes/ocean/header-frame.css +287 -0
  45. package/assets/themes/ocean/options-frame.css +129 -0
  46. package/assets/themes/ocean/sidebar-outer.css +66 -0
  47. package/assets/themes/ocean/topbar-frame.css +91 -0
  48. package/assets/themes/oldday/actions-frame.css +90 -0
  49. package/assets/themes/oldday/brand-frame.css +43 -0
  50. package/assets/themes/oldday/footer-frame.css +116 -0
  51. package/assets/themes/oldday/header-frame.css +142 -0
  52. package/assets/themes/oldday/options-frame.css +129 -0
  53. package/assets/themes/oldday/sidebar-outer.css +69 -0
  54. package/assets/themes/oldday/topbar-frame.css +91 -0
  55. package/assets/themes/pop/actions-frame.css +3 -0
  56. package/assets/themes/pop/brand-frame.css +3 -0
  57. package/assets/themes/pop/footer-frame.css +3 -0
  58. package/assets/themes/pop/header-frame.css +289 -0
  59. package/assets/themes/pop/options-frame.css +3 -0
  60. package/assets/themes/pop/pop-dust.css +37 -0
  61. package/assets/themes/pop/sidebar-outer.css +3 -0
  62. package/assets/themes/pop/topbar-frame.css +3 -0
  63. package/assets/themes/vaporwave/actions-frame.css +3 -0
  64. package/assets/themes/vaporwave/brand-frame.css +3 -0
  65. package/assets/themes/vaporwave/footer-frame.css +3 -0
  66. package/assets/themes/vaporwave/header-frame.css +436 -0
  67. package/assets/themes/vaporwave/options-frame.css +3 -0
  68. package/assets/themes/vaporwave/sidebar-outer.css +3 -0
  69. package/assets/themes/vaporwave/topbar-frame.css +3 -0
  70. package/assets/themes/vaporwave/vapor-dust.css +40 -0
  71. package/client.js +8116 -0
  72. package/cordis.patch.yml +6 -0
  73. package/docs/ACCEPTANCE-/345/244/264/345/203/217/351/242/204/350/247/210-20261201.md +42 -0
  74. package/docs/DETAIL.md +1 -0
  75. package/docs/DETAIL.zh.md +1 -0
  76. package/docs/pin-compare.png +0 -0
  77. package/docs/pin-modes.png +0 -0
  78. package/docs/preview.svg +84 -0
  79. package/docs/shot-fix7.png +0 -0
  80. package/docs/shot-frame-ocean.png +0 -0
  81. package/docs/shot-metal.png +0 -0
  82. package/docs/shot-stars.png +0 -0
  83. package/docs/shot-zones.png +0 -0
  84. package/icon.svg +5 -0
  85. package/index.js +2050 -0
  86. package/locale/en.json +7 -0
  87. package/locale/zh.json +7 -0
  88. package/package.json +58 -3
  89. package/pin.ps1 +172 -0
  90. package/rollback.ps1 +196 -0
  91. package/tools/__pycache__/pack-release.cpython-312.pyc +0 -0
  92. package/tools/_slice.txt +9 -0
  93. package/tools/boot.cjs +16 -0
  94. package/tools/build-frame-css.cjs +33 -0
  95. package/tools/check-docs.ps1 +41 -0
  96. package/tools/check-names.ps1 +35 -0
  97. package/tools/extract.cjs +28 -0
  98. package/tools/find-in-asar.cjs +43 -0
  99. package/tools/list-dir.cjs +21 -0
  100. package/tools/list-pkgs.cjs +10 -0
  101. package/tools/probe-delay.cjs +109 -0
  102. package/tools/probe-star-icon.cjs +164 -0
  103. package/tools/proof-glow-persist.cjs +102 -0
  104. package/tools/proof-migration.cjs +88 -0
  105. package/tools/proof-opacity.cjs +153 -0
  106. package/tools/proof-race.cjs +103 -0
  107. package/tools/run-asar.ps1 +53 -0
  108. package/tools/run.cmd +8 -0
  109. package/tools/scan.cjs +24 -0
  110. package/tools/smoke.cjs +179 -0
  111. package/tools/source-health.cjs +165 -0
  112. package/tools/splice.cjs +20 -0
  113. package/tools/test-account.cjs +74 -0
  114. package/tools/test-client.cjs +265 -0
  115. package/tools/test-dom.cjs +258 -0
  116. package/tools/test-host.cjs +500 -0
  117. package/tools/test-menu.cjs +591 -0
  118. package/tools/test-recharge.cjs +111 -0
  119. package/tools/test-v20.cjs +1793 -0
  120. package/workspace-pin.cmd +8 -0
@@ -0,0 +1,500 @@
1
+ // test-host.cjs — 用假 ctx + 临时 DSH_HOME 跑一遍 index.js 的路由与排序逻辑(v2 规格)
2
+ // 覆盖:唯一置顶、星标顺序、取消后回位、置顶+星标、拖拽回弹、迁移、各类守卫。
3
+ // 用法:run-asar.ps1 test-host.cjs <index.js 绝对路径>
4
+ module.exports = async function (args) {
5
+ const fs = require('node:fs');
6
+ const os = require('node:os');
7
+ const path = require('node:path');
8
+ const { pathToFileURL } = require('node:url');
9
+
10
+ const pluginPath = args[0];
11
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), 'workspace-pin-v2-'));
12
+ process.env.DSH_HOME = home;
13
+ const stateFile = path.join(home, 'workspace-pin.json');
14
+
15
+ const problems = [];
16
+ const expect = (condition, message) => { if (!condition) problems.push(message); return condition; };
17
+
18
+ /* ---------- 假注册表:与 dsh-workspace insertBefore 语义一致 ---------- */
19
+ let order = ['w-a', 'w-b', 'w-c', 'w-d'];
20
+ const writes = [];
21
+ const registry = {
22
+ list() { return order.map(id => ({ id, path: 'D:\\' + id, title: id })); },
23
+ async insertBefore(id, beforeId) {
24
+ if (!order.includes(id)) throw new Error('unknown workspace ' + id);
25
+ if (beforeId !== undefined && !order.includes(beforeId)) throw new Error('unknown anchor ' + beforeId);
26
+ if (beforeId === id) return order.slice();
27
+ const without = order.filter(x => x !== id);
28
+ const at = beforeId === undefined ? without.length : without.indexOf(beforeId);
29
+ order = [...without.slice(0, at), id, ...without.slice(at)];
30
+ writes.push({ id, beforeId, result: order.slice() });
31
+ return order.slice();
32
+ },
33
+ };
34
+
35
+ /* ---------- 假 webServer + 事件 ---------- */
36
+ const routes = [];
37
+ const handlers = new Map();
38
+ const ctx = {
39
+ effect(fn) { fn(); return () => {}; },
40
+ on(event, handler) { handlers.set(event, handler); return () => {}; },
41
+ get() { return undefined; },
42
+ webServer: { register(route) { routes.push(route); return () => {}; } },
43
+ workspaceRegistry: registry,
44
+ };
45
+
46
+ const plugin = await import(pathToFileURL(pluginPath).href);
47
+ expect(typeof plugin.apply === 'function', 'index.js 应导出 apply');
48
+ expect(Array.isArray(plugin.inject) && plugin.inject.includes('webServer') && plugin.inject.includes('workspaceRegistry'),
49
+ 'index.js 的 inject 应包含 webServer 与 workspaceRegistry');
50
+ plugin.apply(ctx);
51
+
52
+ const route = (p) => routes.find(r => r.path === '/workspace-pin/' + p);
53
+ for (const name of ['state', 'pin', 'star', 'order']) {
54
+ expect(route(name) && route(name).kind === 'exact', `应注册 exact 路由 /workspace-pin/${name}`);
55
+ }
56
+ expect(handlers.has('domain/changed'), '应监听 domain/changed(拖拽回弹)');
57
+
58
+ /* ---------- 假 req/res ---------- */
59
+ function fakeReq(method, body, headers) {
60
+ const chunks = body === undefined ? [] : [Buffer.from(body, 'utf8')];
61
+ return {
62
+ method,
63
+ headers: Object.assign({ host: '127.0.0.1:49696' }, headers),
64
+ async *[Symbol.asyncIterator]() { for (const c of chunks) yield c; },
65
+ };
66
+ }
67
+ function fakeRes() {
68
+ const res = { statusCode: 0, headers: null, body: '', ended: false };
69
+ res.writeHead = (code, headers) => { res.statusCode = code; res.headers = headers; return res; };
70
+ res.end = (chunk) => { if (chunk !== undefined) res.body += chunk; res.ended = true; return res; };
71
+ return res;
72
+ }
73
+ async function call(name, method, body, headers) {
74
+ const res = fakeRes();
75
+ await route(name).handler(fakeReq(method, body === undefined ? undefined : JSON.stringify(body), headers), res);
76
+ let json = null;
77
+ try { json = JSON.parse(res.body); } catch { /* 非 JSON */ }
78
+ return { status: res.statusCode, json, text: res.body };
79
+ }
80
+ const getState = async () => (await call('state', 'GET')).json;
81
+ const pin = async (workspaceId) => call('pin', 'POST', { workspaceId });
82
+ const star = async (kind, id, starred) => call('star', 'POST', { kind, id, starred });
83
+ const setOrder = (ids) => { order = ids.slice(); };
84
+ const emitChange = async () => {
85
+ handlers.get('domain/changed')({ domain: 'workspace', table: '', key: '', operation: 'put', value: {} });
86
+ await new Promise(resolve => setTimeout(resolve, 200));
87
+ };
88
+
89
+ /* ---------- 1. 初始 ---------- */
90
+ let r = await call('state', 'GET');
91
+ expect(r.status === 200, `GET state 应 200,实际 ${r.status}`);
92
+ expect(r.json.pinnedWorkspaceId === null, '初始无置顶');
93
+ expect(r.json.starredWorkspaces.length === 0 && r.json.starredSessions.length === 0, '初始无星标');
94
+ expect(r.json.workspaceIds.join(',') === order.join(','), 'state 应返回当前顺序');
95
+
96
+ /* ---------- 2. 唯一置顶:置顶 A 再置顶 B ---------- */
97
+ r = await pin('w-b');
98
+ expect(r.json.pinnedWorkspaceId === 'w-b', `置顶 w-b,实际 ${r.json.pinnedWorkspaceId}`);
99
+ expect(order.join(',') === 'w-b,w-a,w-c,w-d', `w-b 应在最上,实际 ${order.join(',')}`);
100
+
101
+ r = await pin('w-c');
102
+ expect(r.json.pinnedWorkspaceId === 'w-c', `置顶 w-c 后唯一置顶应为 w-c,实际 ${r.json.pinnedWorkspaceId}`);
103
+ expect(order.join(',') === 'w-c,w-a,w-b,w-d', `顺序应为 w-c,w-a,w-b,w-d,实际 ${order.join(',')}`);
104
+ expect(r.json.pinnedWorkspaceId !== 'w-b', 'w-b 应被自动取消置顶(唯一性)');
105
+
106
+ /* ---------- 3. 取消置顶回原位 ---------- */
107
+ r = await pin(null);
108
+ expect(r.json.pinnedWorkspaceId === null, '取消置顶后无置顶');
109
+ expect(order.join(',') === 'w-a,w-c,w-b,w-d', `取消后顺序应为 w-a,w-c,w-b,w-d,实际 ${order.join(',')}`);
110
+
111
+ /* ---------- 4. 星标:三个按星标先后 ---------- */
112
+ setOrder(['w-a', 'w-b', 'w-c', 'w-d']);
113
+ await call('order', 'POST', { workspaceIds: order });
114
+ r = await star('workspace', 'w-c', true);
115
+ expect(r.json.starredWorkspaces.join(',') === 'w-c', `星标集合应为 w-c,实际 ${r.json.starredWorkspaces.join(',')}`);
116
+ expect(order.join(',') === 'w-c,w-a,w-b,w-d', `星标区应在最前,实际 ${order.join(',')}`);
117
+ r = await star('workspace', 'w-a', true);
118
+ r = await star('workspace', 'w-d', true);
119
+ expect(r.json.starredWorkspaces.join(',') === 'w-c,w-a,w-d', `星标顺序应为 w-c,w-a,w-d,实际 ${r.json.starredWorkspaces.join(',')}`);
120
+ expect(order.join(',') === 'w-c,w-a,w-d,w-b', `顺序应为 w-c,w-a,w-d,w-b,实际 ${order.join(',')}`);
121
+
122
+ /* ---------- 5. 取消星标退出星标区 ---------- */
123
+ r = await star('workspace', 'w-a', false);
124
+ expect(r.json.starredWorkspaces.join(',') === 'w-c,w-d', `取消后星标应为 w-c,w-d,实际 ${r.json.starredWorkspaces.join(',')}`);
125
+ expect(order.join(',') === 'w-c,w-d,w-a,w-b', `w-a 应退出星标区,实际 ${order.join(',')}`);
126
+
127
+ /* ---------- 6. 置顶 + 星标:置顶优先,取消置顶后回星标区 ---------- */
128
+ await pin('w-c');
129
+ expect(order.join(',') === 'w-c,w-d,w-a,w-b', `置顶 w-c(已星标)应仍在最上,实际 ${order.join(',')}`);
130
+ await pin(null);
131
+ expect(order.join(',') === 'w-c,w-d,w-a,w-b', `取消置顶后应回星标区,实际 ${order.join(',')}`);
132
+
133
+ /* ---------- 7. 拖拽回弹:任何来源把顺序挪坏,都会被纠正 ---------- */
134
+ setOrder(['w-a', 'w-b', 'w-c', 'w-d']); // 模拟用户把 w-c 拖到了普通区下面
135
+ await emitChange();
136
+ expect(order.join(',') === 'w-c,w-d,w-a,w-b', `回弹后应为 w-c,w-d,w-a,w-b,实际 ${order.join(',')}`);
137
+
138
+ setOrder(['w-d', 'w-a', 'w-b', 'w-c']); // 模拟把星标项打散
139
+ await emitChange();
140
+ // 分区被修正,但星标块内部保留拖动后的相对顺序(d 在 c 前)
141
+ expect(order.join(',') === 'w-d,w-c,w-a,w-b', `回弹后应为 w-d,w-c,w-a,w-b,实际 ${order.join(',')}`);
142
+
143
+ /* ---------- 8. 星标会话:只记状态,不动工作区顺序 ---------- */
144
+ const before = order.join(',');
145
+ r = await star('session', 'session-1', true);
146
+ expect(r.json.starredSessions.join(',') === 'session-1', '会话星标应记录');
147
+ await star('session', 'session-2', true);
148
+ r = await star('session', 'session-1', false);
149
+ expect(r.json.starredSessions.join(',') === 'session-2', `取消后应只剩 session-2,实际 ${r.json.starredSessions.join(',')}`);
150
+ expect(order.join(',') === before, '星标会话不应改变工作区顺序');
151
+
152
+ /* ---------- 9. 状态文件形状(v3、无 BOM) ---------- */
153
+ const raw = fs.readFileSync(stateFile);
154
+ expect(raw[0] === 0x7b, '状态文件不应带 BOM');
155
+ const saved = JSON.parse(raw.toString('utf8'));
156
+ expect(saved.version === 4, `状态文件版本应为 4,实际 ${saved.version}`);
157
+ expect(saved.settings && saved.settings.nativeSessionPin === 'plugin', '落盘应含 settings.nativeSessionPin=plugin');
158
+ expect(saved.settings.workspaceStarColor === '#E5484D' && saved.settings.sessionStarColor === '#E8B93B', '落盘应含默认星标颜色');
159
+ expect(saved.starredWorkspaces.join(',') === 'w-d,w-c', `落盘星标应为 w-d,w-c(块内顺序回写),实际 ${saved.starredWorkspaces.join(',')}`);
160
+ expect(saved.starredSessions.join(',') === 'session-2', '落盘会话星标应保留');
161
+ expect('pinnedWorkspaceId' in saved && 'pinnedPrev' in saved, '落盘应含 pinnedWorkspaceId / pinnedPrev');
162
+
163
+ /* ---------- 9.5 星标区内部拖动排序:顺序保留,并回写状态 ---------- */
164
+ expect(order.join(',') === 'w-d,w-c,w-a,w-b', `前置顺序应为 w-d,w-c,w-a,w-b,实际 ${order.join(',')}`);
165
+ setOrder(['w-c', 'w-d', 'w-a', 'w-b']); // 模拟用户在星标区内部把 w-c 拖回 w-d 前面
166
+ await emitChange();
167
+ expect(order.join(',') === 'w-c,w-d,w-a,w-b', `星标区内部排序应被保留,实际 ${order.join(',')}`);
168
+ const reordered = JSON.parse(fs.readFileSync(stateFile, 'utf8'));
169
+ expect(reordered.starredWorkspaces.join(',') === 'w-c,w-d',
170
+ `星标顺序应回写为 w-c,w-d,实际 ${reordered.starredWorkspaces.join(',')}`);
171
+ /* ---------- 10. 迁移:v2 records → v3 单值 ---------- */
172
+ fs.writeFileSync(stateFile, JSON.stringify({
173
+ version: 2,
174
+ records: [{ id: 'w-b', prev: 'w-a', pinned: true }, { id: 'w-c', pinned: true }],
175
+ }), 'utf8');
176
+ r = await call('state', 'GET');
177
+ expect(r.json.pinnedWorkspaceId === 'w-b', `v2 迁移应取第一条置顶 w-b,实际 ${r.json.pinnedWorkspaceId}`);
178
+ expect(r.json.starredWorkspaces.length === 0, 'v2 迁移后星标应为空');
179
+
180
+ /* ---------- 11. 迁移:v1 pinned 数组 ---------- */
181
+ fs.writeFileSync(stateFile, JSON.stringify({ version: 1, pinned: ['w-d'] }), 'utf8');
182
+ r = await call('state', 'GET');
183
+ expect(r.json.pinnedWorkspaceId === 'w-d', `v1 迁移应取第一个 w-d,实际 ${r.json.pinnedWorkspaceId}`);
184
+
185
+ /* ---------- 12. 守卫 ---------- */
186
+ expect((await pin('nope')).status === 404, '置顶未知工作区应 404');
187
+ expect((await star('workspace', 'nope', true)).status === 404, '星标未知工作区应 404');
188
+ expect((await call('star', 'POST', { kind: 'bogus', id: 'w-a', starred: true })).status === 400, '非法 kind 应 400');
189
+ expect((await call('star', 'POST', { kind: 'session', id: 'w-a' })).status === 400, '缺 starred 应 400');
190
+ expect((await call('pin', 'POST', { workspaceId: 42 })).status === 400, 'workspaceId 类型错误应 400');
191
+ expect((await call('state', 'POST', {})).status === 405, 'POST state 应 405');
192
+ expect((await call('pin', 'GET')).status === 405, 'GET pin 应 405');
193
+ expect((await call('pin', 'POST', { workspaceId: 'w-b' }, { origin: 'https://evil.example' })).status === 403, '跨站 Origin 应 403');
194
+ expect((await call('pin', 'POST', { workspaceId: 'w-b' }, { origin: 'http://127.0.0.1:49696' })).status === 200, '同源 Origin 应 200');
195
+
196
+ /* ---------- 13. 坏状态文件 → 退化为空,不抛错 ---------- */
197
+ fs.writeFileSync(stateFile, '{ not json', 'utf8');
198
+ r = await call('state', 'GET');
199
+ expect(r.status === 200 && r.json.pinnedWorkspaceId === null, '坏状态文件应退化为空状态');
200
+
201
+ /* ---------- 14. v0.20:新设置项默认值 ---------- */
202
+ fs.writeFileSync(stateFile, JSON.stringify({ version: 4, settings: {} }), 'utf8');
203
+ r = await call('state', 'GET');
204
+ const s = r.json.settings;
205
+ expect(s.settingsTab === 1, 'settingsTab 默认应为 1,实际 ' + s.settingsTab);
206
+ expect(s.areaOpacity === 50, 'areaOpacity 默认应为 50,实际 ' + s.areaOpacity);
207
+ expect(s.sidebarBackground === '', 'sidebarBackground 默认应为空串,实际 ' + JSON.stringify(s.sidebarBackground));
208
+ expect(s.showTokenBalance === false, 'showTokenBalance 默认应为 false,实际 ' + s.showTokenBalance);
209
+ expect(s.avatar && s.avatar.enabled === false, 'avatar.enabled 默认应为 false');
210
+ expect(s.avatar && typeof s.avatar.workspace === 'object' && typeof s.avatar.session === 'object', 'avatar 应有 workspace/session 两份映射');
211
+
212
+ /* ---------- 14.5 v0.20.7:旧 workspaceOpacity → 新 areaOpacity 迁移 ---------- */
213
+ fs.writeFileSync(stateFile, JSON.stringify({ version: 4, settings: { workspaceOpacity: 37 } }), 'utf8');
214
+ r = await call('state', 'GET');
215
+ expect(r.json.settings.areaOpacity === 37, '旧 workspaceOpacity=37 应迁移成 areaOpacity=37,实际 ' + r.json.settings.areaOpacity);
216
+ expect(!('workspaceOpacity' in r.json.settings), '返回的 settings 里不应再有旧键 workspaceOpacity');
217
+ // 迁移后写一次盘,旧键必须从文件里消失
218
+ await call('setting', 'POST', { key: 'areaOpacity', value: 41 });
219
+ {
220
+ const raw = JSON.parse(fs.readFileSync(stateFile, 'utf8'));
221
+ expect(raw.settings.areaOpacity === 41, '新键应落盘为 41,实际 ' + raw.settings.areaOpacity);
222
+ expect(!('workspaceOpacity' in raw.settings), '落盘后旧键 workspaceOpacity 必须被删掉');
223
+ }
224
+ // 旧键当别名写入也应落到新键
225
+ {
226
+ const alias = await call('setting', 'POST', { key: 'workspaceOpacity', value: 12 });
227
+ expect(alias.status === 200, '旧键别名写入应 200(老前端窗口期不报错),实际 ' + alias.status);
228
+ expect(alias.json.settings.areaOpacity === 12, '旧键别名应写进 areaOpacity');
229
+ }
230
+
231
+ /* ---------- 15. v0.20:设置项校验 ---------- */
232
+ expect((await call('setting', 'POST', { key: 'settingsTab', value: 2 })).json.settings.settingsTab === 2, 'settingsTab=2 应写入');
233
+ expect((await call('setting', 'POST', { key: 'settingsTab', value: '3' })).json.settings.settingsTab === 3, 'settingsTab="3"(字符串)应归一成 3');
234
+ expect((await call('setting', 'POST', { key: 'settingsTab', value: 4 })).status === 400, 'settingsTab=4 应 400');
235
+ expect((await call('setting', 'POST', { key: 'settingsTab', value: 0 })).status === 400, 'settingsTab=0 应 400');
236
+ expect((await call('setting', 'POST', { key: 'areaOpacity', value: 0 })).json.settings.areaOpacity === 0, '透明度 0 应写入');
237
+ expect((await call('setting', 'POST', { key: 'areaOpacity', value: 100 })).json.settings.areaOpacity === 100, '透明度 100 应写入');
238
+ expect((await call('setting', 'POST', { key: 'areaOpacity', value: 101 })).status === 400, '透明度 101 应 400');
239
+ expect((await call('setting', 'POST', { key: 'areaOpacity', value: 4.5 })).status === 400, '透明度小数应 400');
240
+ expect((await call('setting', 'POST', { key: 'showTokenBalance', value: true })).json.settings.showTokenBalance === true, 'showTokenBalance=true 应写入');
241
+ expect((await call('setting', 'POST', { key: 'showTokenBalance', value: 'true' })).status === 400, 'showTokenBalance 非布尔应 400');
242
+
243
+ /* ---------- 16. v0.20:素材落盘 + 读取 + 路径守卫 ---------- */
244
+ const assetsDir = path.join(home, 'workspace-pin-assets');
245
+ const PIXEL = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==';
246
+ expect(route('asset') && route('asset').kind === 'exact', '应注册 exact 路由 /workspace-pin/asset');
247
+ expect(route('account') && route('account').kind === 'exact', '应注册 exact 路由 /workspace-pin/account');
248
+
249
+ const savedWs = await call('asset', 'POST', { kind: 'ws', id: 'w-a', dataUrl: PIXEL });
250
+ expect(savedWs.status === 200, 'POST asset(ws) 应 200,实际 ' + savedWs.status);
251
+ // v0.20.5:文件名必须每次带新 token(否则 immutable 缓存会让换头像看不到新图)
252
+ expect(savedWs.json && /^ws-w-a-[a-z0-9]+\.png$/.test(savedWs.json.name),
253
+ '工作区头像应命名为 ws-<id>-<token>.png,实际 ' + JSON.stringify(savedWs.json && savedWs.json.name));
254
+ expect(savedWs.json && fs.existsSync(savedWs.json.path), '工作区头像应真正落到磁盘');
255
+ expect(savedWs.json.path === path.join(assetsDir, savedWs.json.name), '素材必须落在 <DSH_HOME>/workspace-pin-assets 下');
256
+ const savedSe = await call('asset', 'POST', { kind: 'se', id: 'session-1', dataUrl: PIXEL });
257
+ expect(savedSe.json && /^se-session-1-[a-z0-9]+\.png$/.test(savedSe.json.name), '会话头像应命名为 se-<id>-<token>.png,实际 ' + JSON.stringify(savedSe.json && savedSe.json.name));
258
+ const savedSidebar = await call('asset', 'POST', { kind: 'sidebar', id: null, dataUrl: PIXEL });
259
+ expect(savedSidebar.status === 200 && /^sidebar-[a-z0-9]+\.png$/.test(savedSidebar.json.name), '背景图应命名为 sidebar-<token>.png,实际 ' + JSON.stringify(savedSidebar.json && savedSidebar.json.name));
260
+
261
+ expect((await call('asset', 'POST', { kind: 'zzz', dataUrl: PIXEL })).status === 400, '非法 kind 应 400');
262
+ expect((await call('asset', 'POST', { kind: 'ws', id: '../../etc', dataUrl: PIXEL })).status === 400, 'id 里的路径穿越应 400');
263
+ expect((await call('asset', 'POST', { kind: 'ws', id: 'w-a', dataUrl: 'data:text/html;base64,AAA' })).status === 400, '非图片 data URL 应 400');
264
+
265
+ // GET:能取回同一张图,且 content-type 正确
266
+ const assetReq = (query) => {
267
+ const req = fakeReq('GET');
268
+ req.url = '/workspace-pin/asset' + (query || '');
269
+ return req;
270
+ };
271
+ {
272
+ const res = fakeRes();
273
+ await route('asset').handler(assetReq('?name=' + encodeURIComponent(savedWs.json.name)), res);
274
+ expect(res.statusCode === 200, 'GET ?name=<ws 头像> 应 200,实际 ' + res.statusCode);
275
+ expect(res.headers && res.headers['content-type'] === 'image/png', 'PNG 素材 content-type 应为 image/png');
276
+ expect(res.body && res.body.length > 0, 'GET asset 应回图片字节');
277
+ expect(res.headers['content-length'] > 0, 'GET asset 应带 content-length');
278
+ }
279
+ {
280
+ const res = fakeRes();
281
+ await route('asset').handler(assetReq('?name=' + encodeURIComponent('..\\workspace-pin.json')), res);
282
+ expect(res.statusCode === 400, '穿越文件名应 400,实际 ' + res.statusCode);
283
+ }
284
+ {
285
+ const res = fakeRes();
286
+ await route('asset').handler(assetReq('?name=ws-nothere.png'), res);
287
+ expect(res.statusCode === 404, '不存在的素材应 404,实际 ' + res.statusCode);
288
+ }
289
+
290
+ /* ---------- 17. v0.20:背景图 / 头像设置只认素材目录内的路径 ---------- */
291
+ expect((await call('setting', 'POST', { key: 'sidebarBackground', value: '' })).json.settings.sidebarBackground === '', '清空背景图应写入空串');
292
+ expect((await call('setting', 'POST', { key: 'sidebarBackground', value: 'C:\\Windows\\win.ini' })).status === 400, '素材目录外的路径应 400');
293
+ const withBg = await call('setting', 'POST', { key: 'sidebarBackground', value: savedSidebar.json.path });
294
+ expect(withBg.status === 200 && withBg.json.settings.sidebarBackground === savedSidebar.json.path, '合法背景图路径应写入');
295
+ const withAvatar = await call('setting', 'POST', {
296
+ key: 'avatar',
297
+ value: {
298
+ enabled: true,
299
+ workspace: { 'w-a': savedWs.json.path, 'w-b': 'C:\\Windows\\win.ini' },
300
+ session: { 'session-1': savedSe.json.path },
301
+ },
302
+ });
303
+ expect(withAvatar.status === 200, 'avatar 写入应 200');
304
+ expect(withAvatar.json.settings.avatar.enabled === true, 'avatar.enabled 应写入 true');
305
+ expect(withAvatar.json.settings.avatar.workspace['w-a'] === savedWs.json.path, '工作区头像路径应保留');
306
+ expect(!('w-b' in withAvatar.json.settings.avatar.workspace), '素材目录外的头像路径应被丢弃');
307
+ // v0.20.5:素材目录内但文件不存在的路径也要丢弃(否则渲染成空白圆)
308
+ {
309
+ const ghost = path.join(assetsDir, 'ws-ghost.png');
310
+ const res2 = await call('setting', 'POST', {
311
+ key: 'avatar',
312
+ value: { enabled: true, workspace: { 'w-a': savedWs.json.path, 'w-ghost': ghost }, session: {} },
313
+ });
314
+ expect(res2.status === 200, '写 avatar 应 200');
315
+ expect(('w-ghost' in (res2.json.settings.avatar.workspace || {})), 'T-20261127 新策略:文件暂时不存在的头像条目应保留(不再静默丢弃配置)');
316
+ }
317
+ expect(withAvatar.json.settings.avatar.session['session-1'] === savedSe.json.path, '会话头像路径应保留');
318
+
319
+ /* ---------- 18. v0.20:新设置刷新后保留(重新读盘) ---------- */
320
+ const reloaded = await call('state', 'GET');
321
+ expect(reloaded.json.settings.settingsTab === 3, 'settingsTab 应落盘保留,实际 ' + reloaded.json.settings.settingsTab);
322
+ expect(reloaded.json.settings.areaOpacity === 100, '透明度应落盘保留,实际 ' + reloaded.json.settings.areaOpacity);
323
+ expect(reloaded.json.settings.showTokenBalance === true, 'showTokenBalance 应落盘保留');
324
+ expect(reloaded.json.settings.sidebarBackground === savedSidebar.json.path, '背景图路径应落盘保留');
325
+ expect(reloaded.json.settings.avatar.enabled === true && reloaded.json.settings.avatar.workspace['w-a'] === savedWs.json.path,
326
+ '头像设置应落盘保留');
327
+ {
328
+ const raw = fs.readFileSync(stateFile, 'utf8');
329
+ expect(raw.charCodeAt(0) !== 0xFEFF, '状态文件不得带 BOM');
330
+ expect(raw.indexOf('base64') === -1, 'JSON 里不得出现 base64(图片只存路径)');
331
+ expect(raw.indexOf(assetsDir.replace(/\\/g, '\\\\')) !== -1, 'JSON 里应只有素材路径');
332
+ }
333
+
334
+ /* ---------- 19. v0.20:账户数据(余额读不到就 null,绝不编数字) ---------- */
335
+ {
336
+ const missingLog = path.join(os.tmpdir(), 'workspace-pin-no-such-cost-' + Date.now() + '.jsonl');
337
+ process.env.WP_BALANCE_LOG = missingLog;
338
+ const res = fakeRes();
339
+ await route('account').handler(fakeReq('GET'), res);
340
+ const json = JSON.parse(res.body);
341
+ expect(res.statusCode === 200, 'GET account 应 200');
342
+ expect(json.balance === null, '没有余额流水时应返回 null,实际 ' + JSON.stringify(json.balance));
343
+ expect(json.tokensToday && json.tokensToday.tokens === null, '今日 token 无来源时应为 null,绝不编数字');
344
+ }
345
+ {
346
+ // 放一份余额流水,验证真的能读到最后一条
347
+ const logDir = fs.mkdtempSync(path.join(os.tmpdir(), 'workspace-pin-cost-'));
348
+ const logFile = path.join(logDir, 'balance-log.jsonl');
349
+ fs.writeFileSync(logFile, [
350
+ JSON.stringify({ at: '2026-11-24T08:00:00.000Z', balance: '400.1000000000', currency: 'CNY' }),
351
+ '{ broken json',
352
+ JSON.stringify({ at: '2026-11-24T08:30:03.081Z', balance: '336.8014640000000000', currency: 'CNY' }),
353
+ '',
354
+ ].join('\n'), 'utf8');
355
+ process.env.WP_BALANCE_LOG = logFile;
356
+ // 余额有 60s 缓存,换文件后要重新加载插件实例才能生效——这里直接重放 apply
357
+ routes.length = 0;
358
+ plugin.apply(ctx);
359
+ const res = fakeRes();
360
+ await route('account').handler(fakeReq('GET'), res);
361
+ const json = JSON.parse(res.body);
362
+ expect(json.balance && json.balance.amount === '336.80', '应读到流水最后一条且收敛到两位,实际 ' + JSON.stringify(json.balance && json.balance.amount));
363
+ expect(json.balance && json.balance.currency === 'CNY', '币种应取自流水');
364
+ expect(json.tokensToday && json.tokensToday.tokens === null, '今日 token 仍应为 null');
365
+ delete process.env.WP_BALANCE_LOG;
366
+ fs.rmSync(logDir, { recursive: true, force: true });
367
+ }
368
+
369
+ /* ---------- 20. v0.20.5:同一工作区换两次头像 → 文件名必须变、旧文件清理 ---------- */
370
+ {
371
+ // a) 换上传必须换新文件名(否则 immutable 缓存会一直显示旧图)
372
+ const again = await call('asset', 'POST', { kind: 'ws', id: 'w-a', dataUrl: PIXEL });
373
+ expect(again.status === 200, '第二次上传应 200');
374
+ expect(again.json.name !== savedWs.json.name,
375
+ '换头像必须换新文件名:' + savedWs.json.name + ' vs ' + again.json.name);
376
+ expect(fs.existsSync(again.json.path), '新文件应存在');
377
+ expect(again.json.bytes > 0, '新文件应有内容');
378
+ // b) 旧文件此时**仍被 settings 引用**,绝不能删(删了界面就空白)
379
+ expect(fs.existsSync(savedWs.json.path), '仍被 settings 引用的旧文件不得被清理');
380
+
381
+ // c) 把 settings 指到新文件后,下一轮上传才会清掉「上一张」(旧的一直被引用着就不删)
382
+ await call('setting', 'POST', {
383
+ key: 'avatar',
384
+ value: { enabled: true, workspace: { 'w-a': again.json.path }, session: {} },
385
+ });
386
+ const third = await call('asset', 'POST', { kind: 'ws', id: 'w-a', dataUrl: PIXEL });
387
+ expect(third.status === 200, '第三次上传应 200');
388
+ // 此刻 settings 指的还是 again → savedWs 无人引用被清,again 仍受保护
389
+ expect(!fs.existsSync(savedWs.json.path), '无人引用的最老那张应被清理');
390
+ expect(fs.existsSync(again.json.path), '当前引用的那张必须还在');
391
+ await call('setting', 'POST', {
392
+ key: 'avatar',
393
+ value: { enabled: true, workspace: { 'w-a': third.json.path }, session: {} },
394
+ });
395
+ // d) 再传一次 → 上一张(again)变无人引用,被清掉
396
+ const fourth = await call('asset', 'POST', { kind: 'ws', id: 'w-a', dataUrl: PIXEL });
397
+ expect(fourth.status === 200, '第四次上传应 200');
398
+ await call('setting', 'POST', {
399
+ key: 'avatar',
400
+ value: { enabled: true, workspace: { 'w-a': fourth.json.path }, session: {} },
401
+ });
402
+ const listing = fs.readdirSync(assetsDir).filter(n => n.indexOf('ws-w-a') === 0);
403
+ expect(listing.length === 2, '任一时刻最多只多留「上一张」待清,实际 ' + JSON.stringify(listing));
404
+ expect(listing.indexOf(fourth.json.name) !== -1, '当前引用的那张必须在');
405
+ expect(listing.indexOf(third.json.name) !== -1, '上一张(此刻仍被引用)也应还在');
406
+ expect(!fs.existsSync(savedWs.json.path) && !fs.existsSync(again.json.path), '更早的两张应已清理');
407
+ }
408
+
409
+ /* ---------- 21. T-01:今日消费 = |当日基线 − 当前|,基线按自然日、日志优先 ---------- */
410
+ {
411
+ const logDir = fs.mkdtempSync(path.join(os.tmpdir(), 'wp-cost-'));
412
+ const logFile = path.join(logDir, 'balance-log.jsonl');
413
+ const todayIso = new Date().toISOString();
414
+ const yesterdayIso = new Date(Date.now() - 26 * 3600 * 1000).toISOString();
415
+ fs.writeFileSync(logFile, [
416
+ JSON.stringify({ at: yesterdayIso, balance: '500.00', currency: 'CNY' }), // 昨天的,不该被当基线
417
+ JSON.stringify({ at: todayIso, balance: '305.32910976', currency: 'CNY' }), // 今天首条
418
+ JSON.stringify({ at: new Date().toISOString(), balance: '296.78887144', currency: 'CNY' }),
419
+ '',
420
+ ].join('\n'), 'utf8');
421
+ process.env.WP_BALANCE_LOG = logFile;
422
+ routes.length = 0;
423
+ plugin.apply(ctx);
424
+ const r1 = await call('account', 'GET');
425
+ expect(r1.status === 200, 'GET /account 应 200');
426
+ expect(r1.json.cost && r1.json.cost.baselineSource === 'log-first', '基线应取当天首条日志,实际 ' + (r1.json.cost && r1.json.cost.baselineSource));
427
+ expect(Math.abs((r1.json.cost.baseline.balance) - 305.32910976) < 1e-9, '基线余额应是当天首条 305.32910976');
428
+ expect(r1.json.cost.spent === 8.54, '今日消费应为 8.54,实际 ' + (r1.json.cost && r1.json.cost.spent));
429
+ expect(r1.json.cost.recharge === false, '正常消费不应标充值');
430
+ expect(r1.json.cost.tokensToday === null, '今日 token 无官方口径 → 必须是 null(显示 --)');
431
+ {
432
+ const st = JSON.parse(fs.readFileSync(stateFile, 'utf8'));
433
+ expect(st.settings.costBaseline && st.settings.costBaseline.day, 'costBaseline 必须落盘且带 day');
434
+ expect(Math.abs(st.settings.costBaseline.balance - 305.32910976) < 1e-9, '落盘基线应等于当天首条');
435
+ expect(typeof st.settings.costBaseline.at === 'string', 'costBaseline 必须带 at 时间点');
436
+ }
437
+
438
+ // 充值场景:当前余额 > 基线 → 不许出负数,标 recharge
439
+ fs.writeFileSync(logFile, [
440
+ JSON.stringify({ at: todayIso, balance: '300.00', currency: 'CNY' }),
441
+ JSON.stringify({ at: new Date().toISOString(), balance: '420.00', currency: 'CNY' }),
442
+ '',
443
+ ].join('\n'), 'utf8');
444
+ routes.length = 0;
445
+ plugin.apply(ctx);
446
+ const r2 = await call('account', 'GET');
447
+ expect(r2.json.cost.recharge === true, '余额变大应标 recharge');
448
+ expect(r2.json.cost.spent === null, '充值场景 spent 必须为 null(前端显示 --),实际 ' + r2.json.cost.spent);
449
+ expect(r2.json.cost.reason === 'recharge', 'reason 应为 recharge');
450
+
451
+ // 跨天:日志里只有昨天的 → 不应把昨天的当今日基线
452
+ fs.writeFileSync(logFile, [
453
+ JSON.stringify({ at: yesterdayIso, balance: '500.00', currency: 'CNY' }),
454
+ '',
455
+ ].join('\n'), 'utf8');
456
+ routes.length = 0;
457
+ plugin.apply(ctx);
458
+ const r3 = await call('account', 'GET');
459
+ expect(r3.json.cost.logFirst === null, '当天没有采样时 logFirst 应为 null');
460
+ expect(r3.json.cost.baseline === null || r3.json.cost.baseline.day !== '', '不应把昨天读数当今日基线');
461
+
462
+ delete process.env.WP_BALANCE_LOG;
463
+ fs.rmSync(logDir, { recursive: true, force: true });
464
+ }
465
+
466
+ /* ---------- 22. 版本一致性(今天踩过三次「报告写 A、实际装 B」) ---------- */
467
+ {
468
+ const root = process.cwd();
469
+ const pkg = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8'));
470
+ const clientSrc = fs.readFileSync(path.join(root, 'client.js'), 'utf8');
471
+ const clientVersion = (clientSrc.match(/const CLIENT_VERSION = '([^']+)'/) || [])[1] || null;
472
+ const changelog = fs.readFileSync(path.join(root, 'CHANGELOG.md'), 'utf8');
473
+ const changelogVersions = Array.from(changelog.matchAll(/^#\s*v?([0-9]+\.[0-9]+\.[0-9]+)/gm)).map((m) => m[1]);
474
+
475
+ expect(!!pkg.version, 'package.json 必须有 version');
476
+ expect(clientVersion !== null, 'client.js 必须有 CLIENT_VERSION');
477
+ expect(clientVersion === pkg.version,
478
+ 'client.js CLIENT_VERSION(' + clientVersion + ') 必须等于 package.json(' + pkg.version + ')');
479
+ // 不取「最后一条」——CHANGELOG 是多鱼共写、会被别人追加;只要该版本有登记即可
480
+ expect(changelogVersions.indexOf(pkg.version) !== -1,
481
+ 'CHANGELOG.md 里必须存在 v' + pkg.version + ' 的顶层条目(现有:' + changelogVersions.slice(-3).join(', ') + ' …)');
482
+ console.log(' [22] 版本一致性:package.json = client.js CLIENT_VERSION = v' + pkg.version + ',CHANGELOG 有登记');
483
+ }
484
+
485
+ fs.rmSync(home, { recursive: true, force: true });
486
+
487
+ if (problems.length > 0) {
488
+ console.log('FAIL');
489
+ for (const p of problems) console.log(' - ' + p);
490
+ return 1;
491
+ }
492
+ console.log('PASS index.js(v2 规格)');
493
+ console.log(' routes : state(GET) pin(POST) star(POST) order(POST) + 兼容 toggle');
494
+ console.log(' 唯一置顶 : pin w-b → pin w-c ⇒ 只剩 w-c(w-b 自动取消并回位)');
495
+ console.log(' 星标顺序 : w-c → w-a → w-d ⇒ order ' + 'w-c,w-a,w-d,w-b');
496
+ console.log(' 拖拽回弹 : 任意打乱 → 自动纠正回 置顶/星标 结构');
497
+ console.log(' 迁移 : v1 pinned[] / v2 records[] → v3 单值');
498
+ console.log(' 写次数 : ' + writes.length + ' 次 insertBefore');
499
+ return 0;
500
+ };