@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,103 @@
1
+ // proof-race.cjs — T-01 验收①:paused 快速连续切换 10 轮,验证不再 500 ENOENT,且无 temp 残留。
2
+ // 用真实 index.js + 临时 DSH_HOME,直接打 /setting 路由(含并发交错,专打原来那个竞态)。
3
+ module.exports = async function (args) {
4
+ const fs = require('node:fs');
5
+ const os = require('node:os');
6
+ const path = require('node:path');
7
+ const { pathToFileURL } = require('node:url');
8
+
9
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), 'wp-race-'));
10
+ process.env.DSH_HOME = home;
11
+ const routes = [];
12
+ const ctx = {
13
+ effect(fn) { fn(); return () => {}; },
14
+ on() { return () => {}; },
15
+ get() { return undefined; },
16
+ webServer: { register(route) { routes.push(route); return () => {}; } },
17
+ workspaceRegistry: { list: () => [{ id: 'ws-a', path: 'D:\\a', title: 'A' }], async insertBefore() { return ['ws-a']; } },
18
+ };
19
+ const plugin = await import(pathToFileURL(path.resolve(args[0])).href);
20
+ plugin.apply(ctx);
21
+ const route = routes.find(r => r.path === '/workspace-pin/setting');
22
+
23
+ function makeRes() {
24
+ const res = { statusCode: 0, body: '' };
25
+ res.writeHead = (code) => { res.statusCode = code; return res; };
26
+ res.end = (chunk) => { if (chunk !== undefined) res.body += chunk; return res; };
27
+ return res;
28
+ }
29
+ function makeReq(body) {
30
+ const payload = [Buffer.from(JSON.stringify(body), 'utf8')];
31
+ return {
32
+ method: 'POST',
33
+ headers: { host: '127.0.0.1:1' },
34
+ url: '/',
35
+ async *[Symbol.asyncIterator]() { for (const chunk of payload) yield chunk; },
36
+ };
37
+ }
38
+ async function post(body) {
39
+ const res = makeRes();
40
+ await route.handler(makeReq(body), res);
41
+ let json = null;
42
+ try { json = JSON.parse(res.body); } catch { /* ignore */ }
43
+ return { code: res.statusCode, json };
44
+ }
45
+
46
+ const statePath = path.join(home, 'workspace-pin.json');
47
+ const tempLeftovers = () => fs.readdirSync(home).filter((n) => n.includes('.tmp'));
48
+
49
+ // 10 轮:每轮 true → false,且中途故意并发交错(模拟原来踩到的那条路径)
50
+ const codes = [];
51
+ for (let round = 1; round <= 10; round += 1) {
52
+ const on = await post({ key: 'paused', value: true });
53
+ codes.push(on.code);
54
+ // 立刻紧接 false(并且不等待任何异步收尾),这是原来 500 的触发序列
55
+ const off = await post({ key: 'paused', value: false });
56
+ codes.push(off.code);
57
+ if (on.code !== 200 || off.code !== 200) {
58
+ console.log(` 第 ${round} 轮异常:true=${on.code} ${JSON.stringify(on.json)} / false=${off.code} ${JSON.stringify(off.json)}`);
59
+ }
60
+ }
61
+
62
+ // 再来一轮"真并发":真/假同时打出去
63
+ const burst = await Promise.all([
64
+ post({ key: 'paused', value: true }),
65
+ post({ key: 'paused', value: false }),
66
+ post({ key: 'paused', value: true }),
67
+ post({ key: 'paused', value: false }),
68
+ post({ key: 'dailyLimit', value: 5 }),
69
+ post({ key: 'dailyLimit', value: 0 }),
70
+ ]);
71
+ burst.forEach((r) => codes.push(r.code));
72
+
73
+ const leftovers = tempLeftovers();
74
+ const ok = codes.every((c) => c === 200) && leftovers.length === 0;
75
+ const state = JSON.parse(fs.readFileSync(statePath, 'utf8'));
76
+
77
+ console.log('状态码序列:' + codes.join(' '));
78
+ console.log('非 200 个数:' + codes.filter((c) => c !== 200).length);
79
+ console.log('temp 残留:' + (leftovers.length === 0 ? '0 个' : leftovers.join(', ')));
80
+ console.log('落盘可读:paused=' + state.settings.paused + ' dailyLimit=' + state.settings.dailyLimit);
81
+ console.log(ok ? 'RACE PROOF PASS' : 'RACE PROOF FAIL');
82
+
83
+ fs.rmSync(home, { recursive: true, force: true });
84
+ return ok ? 0 : 1;
85
+ };
86
+ // 直接 `node tools/<file> …` 时自动执行:以前只导出函数,直接跑会静默 exit 0(T-20261125-05)
87
+ if (require.main === module) {
88
+ process.on('uncaughtException', (error) => {
89
+ console.error(' ERROR uncaughtException: ' + ((error && error.stack) || error));
90
+ process.exit(1);
91
+ });
92
+ process.on('unhandledRejection', (error) => {
93
+ console.error(' ERROR unhandledRejection: ' + ((error && error.stack) || error));
94
+ process.exit(1);
95
+ });
96
+ Promise.resolve()
97
+ .then(() => module.exports(process.argv.slice(2)))
98
+ .then((code) => { process.exitCode = typeof code === 'number' ? code : 1; },
99
+ (error) => {
100
+ console.error(' ERROR ' + ((error && error.stack) || error));
101
+ process.exitCode = 1;
102
+ });
103
+ }
@@ -0,0 +1,53 @@
1
+ # run-asar.ps1 - run a script with Electron in Node mode (ELECTRON_RUN_AS_NODE=1).
2
+ # Also performs a syntax pre-check (node --check) for .js/.cjs/.mjs targets first.
3
+ param(
4
+ [Parameter(Mandatory = $true)][string]$Script,
5
+ [Parameter(ValueFromRemainingArguments = $true)][string[]]$ScriptArgs
6
+ )
7
+
8
+ $exe = $env:DSH_NODE_EXECUTABLE
9
+ if (-not $exe) { $exe = 'D:\Program Files\DeepSeekHarness\DeepSeek Harness.exe' }
10
+
11
+ # v0.22.118: syntax pre-check via the bundled node.exe (Electron binary does not accept --check)
12
+ $nodeCheck = 'D:\Program Files\DeepSeekHarness\resources\runtime\primary-runtime\dependencies\node\bin\node.exe'
13
+ if ((Test-Path $nodeCheck) -and ($Script -match '\.(c|m)?js$')) {
14
+ $checkOut = & $nodeCheck --check $Script 2>&1
15
+ if ($LASTEXITCODE -ne 0) {
16
+ [Console]::Error.Write("SYNTAX ERROR in $Script`n" + ($checkOut -join "`n") + "`n")
17
+ exit 1
18
+ }
19
+ }
20
+
21
+ function Quote-Arg([string]$a) {
22
+ if ($a -eq '') { return '""' }
23
+ if ($a -notmatch '[\s"]') { return $a }
24
+ return '"' + ($a -replace '(\\*)"', '$1$1\"') + '"'
25
+ }
26
+
27
+ # v0.22.163: isolate test data dir (never let tests write into ~/.dsh/workspace-pin)
28
+ if (-not $env:WP_DATA_DIR) {
29
+ $testData = Join-Path $env:TEMP 'wp-test-data'
30
+ New-Item -ItemType Directory -Force -Path $testData | Out-Null
31
+ $env:WP_DATA_DIR = $testData
32
+ }
33
+
34
+ $psi = New-Object System.Diagnostics.ProcessStartInfo
35
+ $psi.FileName = $exe
36
+ $psi.UseShellExecute = $false
37
+ $psi.RedirectStandardOutput = $true
38
+ $psi.RedirectStandardError = $true
39
+ $psi.StandardOutputEncoding = [System.Text.Encoding]::UTF8
40
+ $psi.StandardErrorEncoding = [System.Text.Encoding]::UTF8
41
+ $psi.EnvironmentVariables['ELECTRON_RUN_AS_NODE'] = '1'
42
+
43
+ $argList = @('-e', 'Promise.resolve(require(process.argv[1])(process.argv.slice(2))).then(code => process.exit(typeof code === "number" ? code : 0), error => { console.error(error && error.stack || error); process.exit(1) })', '--', $Script)
44
+ if ($ScriptArgs) { $argList += $ScriptArgs }
45
+ $psi.Arguments = ($argList | ForEach-Object { Quote-Arg $_ }) -join ' '
46
+
47
+ $p = [System.Diagnostics.Process]::Start($psi)
48
+ $outTask = $p.StandardOutput.ReadToEndAsync()
49
+ $errTask = $p.StandardError.ReadToEndAsync()
50
+ $p.WaitForExit()
51
+ [Console]::Out.Write($outTask.Result)
52
+ if ($errTask.Result) { [Console]::Error.Write($errTask.Result) }
53
+ exit $p.ExitCode
package/tools/run.cmd ADDED
@@ -0,0 +1,8 @@
1
+ @echo off
2
+ rem run.cmd - run a .cjs/.mjs with the DSH bundled Electron as node.
3
+ rem usage: run.cmd <script> [args...]
4
+ setlocal
5
+ if "%DSH_NODE_EXECUTABLE%"=="" set "DSH_NODE_EXECUTABLE=D:\Program Files\DeepSeekHarness\DeepSeek Harness.exe"
6
+ set ELECTRON_RUN_AS_NODE=1
7
+ "%DSH_NODE_EXECUTABLE%" -e "require('./tools/boot.cjs')()" -- %*
8
+ exit /b %ERRORLEVEL%
package/tools/scan.cjs ADDED
@@ -0,0 +1,24 @@
1
+ // scan.cjs — 在 asar 内按正则扫描一个目录下的源码行
2
+ // 用法:run-asar.ps1 scan.cjs <dir> <regex> [extFilter]
3
+ module.exports = function (args) {
4
+ const fs = require('node:fs');
5
+ const path = require('node:path');
6
+ const dir = args[0];
7
+ const re = new RegExp(args[1]);
8
+ const ext = new RegExp(args[2] || '\\.(tsx?|js)$');
9
+ const walk = (p) => {
10
+ let st;
11
+ try { st = fs.statSync(p); } catch { return; }
12
+ if (st.isDirectory()) {
13
+ for (const c of fs.readdirSync(p)) walk(path.join(p, c));
14
+ return;
15
+ }
16
+ if (!ext.test(p)) return;
17
+ const lines = fs.readFileSync(p, 'utf8').split('\n');
18
+ lines.forEach((l, i) => {
19
+ if (re.test(l)) console.log(path.relative(dir, p) + ':' + (i + 1) + ': ' + l.trim().slice(0, 180));
20
+ });
21
+ };
22
+ for (const name of fs.readdirSync(dir)) walk(path.join(dir, name));
23
+ return 0;
24
+ };
@@ -0,0 +1,179 @@
1
+ // smoke.cjs — 改完 Host 代码、**装上去之前**必跑的最小写盘冒烟。
2
+ //
3
+ // 为什么要有它:2026-11-25 11:22 我把 `const temporary = …` 整行误吞进注释,
4
+ // 结果运行中的 Host **所有写盘都 500**,直到重启后才被发现。这个脚本 5 秒就能挡住。
5
+ //
6
+ // 用法:
7
+ // tools\run.cmd tools\smoke.cjs index.js # 本地起真实 index.js(临时 DSH_HOME)
8
+ // tools\run.cmd tools\smoke.cjs live 54292 # 直接打运行中的 Host(重启后验证)
9
+ // node tools\smoke.cjs live 54292 # 直接 node 跑也支持(自动执行 + 正确退出码)
10
+ //
11
+ // 退出码:0=全过,1=有失败/异常,2=参数错误。
12
+ //
13
+ // 设计说明:**不新增生产键**。用真实存在的 `dailyLimit` 做「写入-读回-还原」,
14
+ // 效果与用 `__smoke` 等价,但不会往用户的 settings 里塞垃圾字段。
15
+
16
+ const fs = require('node:fs');
17
+ const os = require('node:os');
18
+ const path = require('node:path');
19
+ const http = require('node:http');
20
+
21
+ const failures = [];
22
+ function check(ok, message) {
23
+ console.log((ok ? ' PASS ' : ' FAIL ') + message);
24
+ if (!ok) failures.push(message);
25
+ }
26
+ function die(code, message) {
27
+ console.error(' ERROR ' + message);
28
+ return code;
29
+ }
30
+
31
+ /* ---------------- 模式 A:本地真实 index.js ---------------- */
32
+ async function localMode(indexPath) {
33
+ const { pathToFileURL } = require('node:url');
34
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), 'wp-smoke-'));
35
+ process.env.DSH_HOME = home;
36
+ const routes = [];
37
+ const ctx = {
38
+ effect(fn) { fn(); return () => {}; },
39
+ on() { return () => {}; },
40
+ get() { return undefined; },
41
+ webServer: { register(route) { routes.push(route); return () => {}; } },
42
+ workspaceRegistry: { list: () => [{ id: 'ws-a', path: 'D:\\a', title: 'A' }], async insertBefore() { return ['ws-a']; } },
43
+ };
44
+ const plugin = await import(pathToFileURL(path.resolve(indexPath)).href);
45
+ plugin.apply(ctx);
46
+ const route = (n) => routes.find((r) => r.path === '/workspace-pin/' + n);
47
+ check(!!route('setting') && !!route('state'), '路由已注册(setting / state)');
48
+
49
+ function makeRes() {
50
+ const res = { statusCode: 0, body: '' };
51
+ res.writeHead = (code) => { res.statusCode = code; return res; };
52
+ res.end = (chunk) => { if (chunk !== undefined) res.body += chunk; return res; };
53
+ return res;
54
+ }
55
+ function makeReq(method, body) {
56
+ const payload = body === undefined ? [] : [Buffer.from(JSON.stringify(body), 'utf8')];
57
+ return {
58
+ method,
59
+ headers: { host: '127.0.0.1:1' },
60
+ url: '/',
61
+ async *[Symbol.asyncIterator]() { for (const chunk of payload) yield chunk; },
62
+ };
63
+ }
64
+ async function call(name, method, body) {
65
+ const res = makeRes();
66
+ await route(name).handler(makeReq(method, body), res);
67
+ let json = null;
68
+ try { json = JSON.parse(res.body); } catch { /* ignore */ }
69
+ return { code: res.statusCode, json };
70
+ }
71
+
72
+ const before = await call('state', 'GET');
73
+ check(before.code === 200, 'GET /state -> 200(实际 ' + before.code + ')');
74
+ const original = before.json && before.json.settings ? before.json.settings.dailyLimit : 0;
75
+
76
+ const wrote = await call('setting', 'POST', { key: 'dailyLimit', value: 7 });
77
+ check(wrote.code === 200, 'POST /setting {dailyLimit:7} -> 200(实际 ' + wrote.code + (wrote.json && wrote.json.error ? ' / ' + wrote.json.error : '') + ')');
78
+
79
+ const after = await call('state', 'GET');
80
+ check(after.code === 200 && after.json.settings.dailyLimit === 7, 'GET /state 读回 dailyLimit=7(实际 ' + (after.json && after.json.settings.dailyLimit) + ')');
81
+
82
+ const restored = await call('setting', 'POST', { key: 'dailyLimit', value: Number(original) || 0 });
83
+ check(restored.code === 200, 'POST /setting 还原 dailyLimit=' + original + ' -> 200(实际 ' + restored.code + ')');
84
+
85
+ const leftovers = fs.readdirSync(home).filter((n) => n.includes('.tmp'));
86
+ check(leftovers.length === 0, '临时文件残留 0 个(实际 ' + leftovers.length + ')');
87
+
88
+ fs.rmSync(home, { recursive: true, force: true });
89
+ }
90
+
91
+ /* ---------------- 模式 B:打运行中的 Host ---------------- */
92
+ function request(base, method, urlPath, body) {
93
+ return new Promise((resolve) => {
94
+ const payload = body === undefined ? null : Buffer.from(JSON.stringify(body), 'utf8');
95
+ const req = http.request(base + urlPath, {
96
+ method,
97
+ headers: payload ? { 'content-type': 'application/json', 'content-length': payload.length } : {},
98
+ timeout: 8000,
99
+ }, (res) => {
100
+ let text = '';
101
+ res.setEncoding('utf8');
102
+ res.on('data', (chunk) => { text += chunk; });
103
+ res.on('end', () => {
104
+ let json = null;
105
+ try { json = JSON.parse(text); } catch { /* ignore */ }
106
+ resolve({ code: res.statusCode, json, text });
107
+ });
108
+ });
109
+ req.on('error', (error) => resolve({ code: 0, json: null, text: String((error && error.message) || error) }));
110
+ req.on('timeout', () => { req.destroy(); resolve({ code: 0, json: null, text: 'timeout' }); });
111
+ if (payload) req.write(payload);
112
+ req.end();
113
+ });
114
+ }
115
+
116
+ async function liveMode(port) {
117
+ const base = 'http://127.0.0.1:' + port;
118
+ console.log(' live 打 http://127.0.0.1:' + port + '(8s 超时)');
119
+ const before = await request(base, 'GET', '/workspace-pin/state');
120
+ check(before.code === 200, 'GET /state -> 200(实际 ' + before.code + (before.code === 0 ? ' / ' + before.text : '') + ')');
121
+ const original = before.json && before.json.settings ? before.json.settings.dailyLimit : 0;
122
+
123
+ const wrote = await request(base, 'POST', '/workspace-pin/setting', { key: 'dailyLimit', value: 7 });
124
+ check(wrote.code === 200, 'POST /setting {dailyLimit:7} -> 200(实际 ' + wrote.code + (wrote.json && wrote.json.error ? ' / ' + wrote.json.error : (wrote.code === 0 ? ' / ' + wrote.text : '')) + ')');
125
+
126
+ const after = await request(base, 'GET', '/workspace-pin/state');
127
+ check(after.code === 200 && after.json.settings.dailyLimit === 7, 'GET /state 读回 dailyLimit=7(实际 ' + (after.json && after.json.settings.dailyLimit) + ')');
128
+
129
+ // 还原要放在最后,且即使前面失败也尽量执行;它自己的结果同样计入 check
130
+ const restored = await request(base, 'POST', '/workspace-pin/setting', { key: 'dailyLimit', value: Number(original) || 0 });
131
+ check(restored.code === 200, 'POST /setting 还原 dailyLimit=' + original + ' -> 200(实际 ' + restored.code + ')');
132
+ }
133
+
134
+ /* ---------------- 主流程 ---------------- */
135
+ async function main(args) {
136
+ const mode = args[0] || '';
137
+ if (mode === 'live') {
138
+ const rawPort = args[1];
139
+ const port = Number(rawPort);
140
+ if (!rawPort || !Number.isInteger(port) || port <= 0 || port > 65535) {
141
+ return die(2, 'live 模式需要端口号:tools\\run.cmd tools\\smoke.cjs live <port>(收到:' + JSON.stringify(rawPort) + ')');
142
+ }
143
+ await liveMode(port);
144
+ } else if (args.length === 0) {
145
+ return die(2, '缺少参数:tools\\run.cmd tools\\smoke.cjs index.js 或 ... smoke.cjs live <port>');
146
+ } else {
147
+ await localMode(args[0]);
148
+ }
149
+
150
+ const ok = failures.length === 0;
151
+ console.log(ok ? 'SMOKE PASS' : 'SMOKE FAIL(' + failures.length + ' 项)');
152
+ return ok ? 0 : 1;
153
+ }
154
+
155
+ /* ---------------- 入口:boot.cjs 调用,或直接 node 运行 ---------------- */
156
+ function guardAndRun(run) {
157
+ process.on('uncaughtException', (error) => {
158
+ console.error(' ERROR uncaughtException: ' + ((error && error.stack) || error));
159
+ process.exit(1);
160
+ });
161
+ process.on('unhandledRejection', (error) => {
162
+ console.error(' ERROR unhandledRejection: ' + ((error && error.stack) || error));
163
+ process.exit(1);
164
+ });
165
+ Promise.resolve()
166
+ .then(() => run(process.argv.slice(2)))
167
+ .then((code) => { process.exitCode = typeof code === 'number' ? code : 1; },
168
+ (error) => {
169
+ console.error(' ERROR ' + ((error && error.stack) || error));
170
+ process.exitCode = 1;
171
+ });
172
+ }
173
+
174
+ module.exports = async function (args) {
175
+ return main(args || []);
176
+ };
177
+
178
+ // 直接 `node tools/smoke.cjs …` 时自动执行(以前只导出函数,直接跑会静默 exit 0)
179
+ if (require.main === module) guardAndRun(main);
@@ -0,0 +1,165 @@
1
+ // source-health.cjs — 通用「源健康检查 + 跨进程熔断记忆」
2
+ //
3
+ // 用法(工具侧/脚本里都行):
4
+ // tools\run.cmd tools\source-health.cjs --url <URL> [--timeout 1500] [--threshold 2]
5
+ // [--cooldown 1800] [--state <json>] [--force] [--json]
6
+ // node tools\source-health.cjs --url <URL> ... # 直接 node 也可以
7
+ //
8
+ // 退出码:0=可用(已探活成功)|1=本次失败|3=熔断中已跳过(没发请求)|2=参数错
9
+ //
10
+ // 设计:
11
+ // - 熔断期内**直接跳过**,不发请求(省超时);
12
+ // - 连续 threshold 次失败 → 写 openUntil = now + cooldown*1000;
13
+ // - 探测成功 → 立即清 fail 计数与 openUntil;
14
+ // - 状态写 JSON(UTF-8 无 BOM,原子写 temp→rename,Windows 上带重试)。
15
+
16
+ const fs = require('node:fs');
17
+ const path = require('node:path');
18
+
19
+ const RETRYABLE = new Set(['EPERM', 'EACCES', 'EBUSY']);
20
+
21
+ function parseArgs(argv) {
22
+ const out = { timeout: 1500, threshold: 2, cooldown: 1800, json: false, force: false };
23
+ for (let i = 0; i < argv.length; i += 1) {
24
+ const a = argv[i];
25
+ const next = () => argv[i + 1];
26
+ if (a === '--url') { out.url = next(); i += 1; }
27
+ else if (a === '--timeout') { out.timeout = Number(next()); i += 1; }
28
+ else if (a === '--threshold') { out.threshold = Number(next()); i += 1; }
29
+ else if (a === '--cooldown') { out.cooldown = Number(next()); i += 1; } // 秒
30
+ else if (a === '--state') { out.state = next(); i += 1; }
31
+ else if (a === '--json') { out.json = true; }
32
+ else if (a === '--force') { out.force = true; }
33
+ else if (a === '--help' || a === '-h') { out.help = true; }
34
+ else if (a.startsWith('--')) { out.error = '未知参数:' + a; return out; }
35
+ }
36
+ return out;
37
+ }
38
+
39
+ function statePathOf(args) {
40
+ if (args.state) return path.resolve(args.state);
41
+ return path.join(process.cwd(), 'queue', 'source-health.json');
42
+ }
43
+
44
+ function readState(file) {
45
+ try {
46
+ const text = fs.readFileSync(file, 'utf8');
47
+ const json = JSON.parse(text);
48
+ if (json && typeof json === 'object' && json.sources && typeof json.sources === 'object') return json;
49
+ } catch (error) { /* 不存在/损坏都从空开始 */ }
50
+ return { version: 1, sources: {} };
51
+ }
52
+
53
+ async function writeState(file, state) {
54
+ const dir = path.dirname(file);
55
+ await fs.promises.mkdir(dir, { recursive: true });
56
+ const tmp = file + '.tmp-' + process.pid + '-' + Date.now().toString(36);
57
+ const body = JSON.stringify(state, null, 2) + '\n';
58
+ for (let attempt = 0; attempt < 5; attempt += 1) {
59
+ try {
60
+ await fs.promises.writeFile(tmp, body, 'utf8');
61
+ try { await fs.promises.rename(tmp, file); } catch (error) {
62
+ if (!error || !RETRYABLE.has(error.code)) throw error;
63
+ await new Promise(r => setTimeout(r, 30 * (attempt + 1)));
64
+ continue;
65
+ }
66
+ return;
67
+ } catch (error) {
68
+ if (attempt === 4) { try { await fs.promises.unlink(tmp); } catch (e) { /* ignore */ } throw error; }
69
+ await new Promise(r => setTimeout(r, 30 * (attempt + 1)));
70
+ }
71
+ }
72
+ }
73
+
74
+ async function probe(url, timeoutMs) {
75
+ const started = Date.now();
76
+ const controller = new AbortController();
77
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
78
+ try {
79
+ const res = await fetch(url, { signal: controller.signal, headers: { 'user-agent': 'source-health/1' } });
80
+ // 读一小段就够,确认不是空响应
81
+ await res.text();
82
+ return { ok: res.ok, status: res.status, latency: Date.now() - started };
83
+ } catch (error) {
84
+ const aborted = error && (error.name === 'AbortError' || /abort/i.test(String(error.message)));
85
+ return { ok: false, status: 0, latency: Date.now() - started, error: aborted ? 'timeout' : String((error && error.cause && error.cause.code) || (error && error.message) || error) };
86
+ } finally {
87
+ clearTimeout(timer);
88
+ }
89
+ }
90
+
91
+ async function main(argv) {
92
+ const args = parseArgs(argv);
93
+ if (args.help) {
94
+ console.log('用法: source-health.cjs --url <URL> [--timeout 1500] [--threshold 2] [--cooldown 1800] [--state <json>] [--force] [--json]');
95
+ return 0;
96
+ }
97
+ if (args.error) { console.error(' ERROR ' + args.error); return 2; }
98
+ if (!args.url || !/^https?:\/\//i.test(args.url)) { console.error(' ERROR 需要 --url http(s)://…'); return 2; }
99
+ if (!Number.isFinite(args.timeout) || args.timeout <= 0) { console.error(' ERROR --timeout 必须是正数(毫秒)'); return 2; }
100
+ if (!Number.isInteger(args.threshold) || args.threshold < 1) { console.error(' ERROR --threshold 必须是 ≥1 的整数'); return 2; }
101
+ if (!Number.isFinite(args.cooldown) || args.cooldown <= 0) { console.error(' ERROR --cooldown 必须是正数(秒)'); return 2; }
102
+
103
+ const file = statePathOf(args);
104
+ const state = readState(file);
105
+ const now = Date.now();
106
+ const entry = state.sources[args.url] || { fails: 0, openUntil: 0, lastStatus: null, lastAt: 0 };
107
+ const skipped = !args.force && entry.openUntil > now;
108
+
109
+ if (skipped) {
110
+ const left = Math.ceil((entry.openUntil - now) / 1000);
111
+ const out = { url: args.url, action: 'skip', openUntil: new Date(entry.openUntil).toISOString(), leftSeconds: left, fails: entry.fails };
112
+ if (args.json) console.log(JSON.stringify(out));
113
+ else console.log(' SKIP 熔断中,剩 ' + left + 's,未发请求:' + args.url);
114
+ return 3;
115
+ }
116
+
117
+ const result = await probe(args.url, args.timeout);
118
+ entry.lastStatus = result.status || result.error || 0;
119
+ entry.lastAt = new Date().toISOString();
120
+ if (result.ok) {
121
+ entry.fails = 0;
122
+ entry.openUntil = 0;
123
+ state.sources[args.url] = entry;
124
+ await writeState(file, state);
125
+ const out = { url: args.url, action: 'ok', status: result.status, latency: result.latency };
126
+ if (args.json) console.log(JSON.stringify(out));
127
+ else console.log(' PASS ' + result.status + ' ' + result.latency + 'ms ' + args.url);
128
+ return 0;
129
+ }
130
+
131
+ entry.fails = (Number(entry.fails) || 0) + 1;
132
+ let opened = false;
133
+ if (entry.fails >= args.threshold) {
134
+ entry.openUntil = now + Math.round(args.cooldown * 1000);
135
+ opened = true;
136
+ }
137
+ state.sources[args.url] = entry;
138
+ await writeState(file, state);
139
+ const out = {
140
+ url: args.url, action: 'fail', status: result.status, latency: result.latency, error: result.error,
141
+ fails: entry.fails, openUntil: entry.openUntil ? new Date(entry.openUntil).toISOString() : null,
142
+ };
143
+ if (args.json) console.log(JSON.stringify(out));
144
+ else console.log(' FAIL ' + (result.status || result.error) + ' ' + result.latency + 'ms 连续失败 ' + entry.fails + '/' + args.threshold + (opened ? ' → 熔断' : '') + ' ' + args.url);
145
+ return 1;
146
+ }
147
+
148
+ /* 直接 node 运行 / run.cmd 都支持;失败要有非零退出码 */
149
+ function guardAndRun(run) {
150
+ process.on('uncaughtException', (error) => {
151
+ console.error(' ERROR uncaughtException: ' + ((error && error.stack) || error));
152
+ process.exit(1);
153
+ });
154
+ process.on('unhandledRejection', (error) => {
155
+ console.error(' ERROR unhandledRejection: ' + ((error && error.stack) || error));
156
+ process.exit(1);
157
+ });
158
+ Promise.resolve()
159
+ .then(() => run(process.argv.slice(2)))
160
+ .then((code) => { process.exitCode = typeof code === 'number' ? code : 1; },
161
+ (error) => { console.error(' ERROR ' + ((error && error.stack) || error)); process.exitCode = 1; });
162
+ }
163
+
164
+ module.exports = main;
165
+ if (require.main === module) guardAndRun(main);
@@ -0,0 +1,20 @@
1
+ // splice.cjs — 把 client.js 的第 <start>..<end> 行(1-based,含)替换成 <replacement> 文件内容。
2
+ // 用法:run.cmd splice.cjs <target> <start> <end> <replacementFile>
3
+ module.exports = function (args) {
4
+ const fs = require('node:fs');
5
+ const target = args[0];
6
+ const start = Number(args[1]);
7
+ const end = Number(args[2]);
8
+ const replacementFile = args[3];
9
+ const lines = fs.readFileSync(target, 'utf8').split('\n');
10
+ if (!(start >= 1 && end >= start && end <= lines.length)) {
11
+ console.error('splice: 行号越界 ' + start + '..' + end + ' of ' + lines.length);
12
+ return 1;
13
+ }
14
+ const replacement = fs.readFileSync(replacementFile, 'utf8').replace(/\r\n/g, '\n').replace(/\n$/, '').split('\n');
15
+ const before = lines.slice(0, start - 1);
16
+ const after = lines.slice(end);
17
+ fs.writeFileSync(target, before.concat(replacement, after).join('\n'), 'utf8');
18
+ console.log('SPLICED ' + start + '..' + end + ' → ' + replacement.length + ' 行;总行数 ' + lines.length + ' → ' + (before.length + replacement.length + after.length));
19
+ return 0;
20
+ };
@@ -0,0 +1,74 @@
1
+ // test-account.cjs — 余额/日支的独立验收(不依赖其它插件、不碰用户数据)
2
+ // 覆盖:① 冷启动自己采样 ② 单条采样=0.00 ③ 两条记录差值 ④ 无账本+账号异常不报错
3
+ // 用法:tools\run-asar.ps1 tools\test-account.cjs index.js (必须在插件目录下运行)
4
+ const fs = require('node:fs')
5
+ const os = require('node:os')
6
+ const path = require('node:path')
7
+ const { pathToFileURL } = require('node:url')
8
+
9
+ module.exports = async function (args) {
10
+ const indexPath = path.resolve(args[0] || 'index.js')
11
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), 'wp-account-'))
12
+ process.env.DSH_HOME = home
13
+ delete process.env.WP_DATA_DIR
14
+ delete process.env.WP_BALANCE_LOG
15
+ const dataDir = path.join(home, 'workspace-pin')
16
+ const logFile = path.join(dataDir, 'balance-log.jsonl')
17
+
18
+ let balance = 100
19
+ let fail = false
20
+ const routes = []
21
+ const cleanups = []
22
+ const ctx = {
23
+ effect(fn) { const c = fn(); if (typeof c === 'function') cleanups.push(c); return () => {}; },
24
+ on() { return () => {}; },
25
+ get() { return undefined; },
26
+ webServer: { register(route) { routes.push(route); return () => {}; } },
27
+ workspaceRegistry: { list: () => [{ id: 'ws-a', path: 'D:\\a', title: 'A' }], async insertBefore() { return ['ws-a']; } },
28
+ deepseekAccount: {
29
+ async getBalance() {
30
+ if (fail) throw new Error('boom')
31
+ return { ok: true, value: { value: [{ balance, currency: 'CNY' }], bonusWallets: [] } }
32
+ },
33
+ },
34
+ }
35
+ const plugin = await import(pathToFileURL(indexPath).href)
36
+ plugin.apply(ctx)
37
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
38
+ const route = (n) => routes.find((r) => r.path === '/workspace-pin/' + n)
39
+ const makeRes = () => { const res = { statusCode: 0, body: '' }; res.writeHead = (c) => { res.statusCode = c; return res; }; res.end = (c) => { if (c !== undefined) res.body += c; return res; }; return res; }
40
+ const makeReq = (method, body) => ({ method, headers: { host: 'x' }, url: '/', async *[Symbol.asyncIterator]() { if (body !== undefined) yield Buffer.from(JSON.stringify(body)); } })
41
+ const call = async (name, method, body) => { const res = makeRes(); await route(name).handler(makeReq(method, body), res); let json = null; try { json = JSON.parse(res.body); } catch { /* ignore */ } return { code: res.statusCode, json }; }
42
+
43
+ const fails = []
44
+ const check = (ok, msg) => { console.log((ok ? ' PASS ' : ' FAIL ') + msg); if (!ok) fails.push(msg) }
45
+
46
+ await sleep(700)
47
+ check(fs.existsSync(logFile), '① 冷启动后生成本地账本')
48
+ const rows = fs.existsSync(logFile) ? fs.readFileSync(logFile, 'utf8').trim().split('\n').filter(Boolean).map((l) => JSON.parse(l)) : []
49
+ check(rows.length === 1 && rows[0].source === 'workspace-pin', '① 首条 source=workspace-pin(实际 ' + (rows[0] && rows[0].source) + ')')
50
+ check(String(rows[0] && rows[0].balance) === '100.00', '① 首条余额=100.00(实际 ' + (rows[0] && rows[0].balance) + ')')
51
+
52
+ let acct = await call('account', 'GET')
53
+ check(acct.code === 200 && acct.json.cost.reason === 'single-sample', '② 单条采样 reason=single-sample(实际 ' + (acct.json && acct.json.cost && acct.json.cost.reason) + ')')
54
+ check(acct.json.cost.spent === 0, '② 单条采样日支=0.00(实际 ' + acct.json.cost.spent + ')')
55
+
56
+ balance = 96.5
57
+ fs.appendFileSync(logFile, JSON.stringify({ at: new Date(Date.now() + 1000).toISOString(), balance: '96.50', currency: 'CNY', bonus: '', source: 'workspace-pin' }) + '\n', 'utf8')
58
+ await sleep(200)
59
+ acct = await call('account', 'GET')
60
+ check(acct.json.cost.reason === 'ok' && acct.json.cost.spent === 3.5, '③ 两条记录日支=3.50(实际 ' + acct.json.cost.spent + ' / ' + acct.json.cost.reason + ')')
61
+ check(acct.json.balanceSource === 'account' && acct.json.balance && acct.json.balance.amount === '96.50', '③ 余额走账号服务(实际 source=' + acct.json.balanceSource + ' amount=' + (acct.json.balance && acct.json.balance.amount) + ')')
62
+
63
+ fs.rmSync(dataDir, { recursive: true, force: true })
64
+ fail = true
65
+ await sleep(300)
66
+ acct = await call('account', 'GET')
67
+ check(acct.code === 200 && acct.json.balance === null, '④ 无账本+账号异常仍 200、balance=null(实际 ' + acct.code + ')')
68
+ check(acct.json.logConfigured === false, '④ logConfigured=false(实际 ' + acct.json.logConfigured + ')')
69
+
70
+ for (const fn of cleanups) { try { fn() } catch { /* ignore */ } }
71
+ fs.rmSync(home, { recursive: true, force: true })
72
+ console.log(fails.length === 0 ? 'ACCOUNT PASS' : 'ACCOUNT FAIL(' + fails.length + ' 项)')
73
+ return fails.length === 0 ? 0 : 1
74
+ }