@capyclaw/rsp-suite 0.1.0 → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dsh-suite.json +13 -3
- package/node_modules/@capyclaw/foundation/README.md +51 -0
- package/node_modules/@capyclaw/foundation/abi/assets.mjs +26 -0
- package/node_modules/@capyclaw/foundation/abi/bridge.mjs +88 -0
- package/node_modules/@capyclaw/foundation/abi/errors.mjs +63 -0
- package/node_modules/@capyclaw/foundation/abi/index.mjs +50 -0
- package/node_modules/@capyclaw/foundation/abi/kinds.mjs +271 -0
- package/node_modules/@capyclaw/foundation/abi/loader.mjs +352 -0
- package/node_modules/@capyclaw/foundation/abi/schema.mjs +98 -0
- package/node_modules/@capyclaw/foundation/abi/spec.mjs +258 -0
- package/node_modules/@capyclaw/foundation/abi/validate.mjs +24 -0
- package/node_modules/@capyclaw/foundation/abi/version.mjs +140 -0
- package/node_modules/@capyclaw/foundation/abi/visibility.mjs +90 -0
- package/node_modules/@capyclaw/foundation/cordis.patch.yml +5 -0
- package/node_modules/@capyclaw/foundation/kit/index.mjs +6 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/client-panel.mjs +98 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/host-event.mjs +35 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/http-router.mjs +69 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/lifecycle-hook.mjs +72 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/own-server.mjs +113 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/raw.mjs +69 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/runtime-driver.mjs +120 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/service-provider.mjs +77 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/skill-provider.mjs +56 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/tool-provider.mjs +50 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/ui-panel.mjs +64 -0
- package/node_modules/@capyclaw/foundation/lib/ctx-service.mjs +42 -0
- package/node_modules/@capyclaw/foundation/lib/host/caps.mjs +38 -0
- package/node_modules/@capyclaw/foundation/lib/host/contract.mjs +88 -0
- package/node_modules/@capyclaw/foundation/lib/host/dsh.mjs +54 -0
- package/node_modules/@capyclaw/foundation/lib/host/memory.mjs +187 -0
- package/node_modules/@capyclaw/foundation/lib/host.mjs +23 -0
- package/node_modules/@capyclaw/foundation/lib/kernel.mjs +195 -0
- package/node_modules/@capyclaw/foundation/lib/skill/scan.mjs +115 -0
- package/node_modules/@capyclaw/foundation/lib/subsystems/events.mjs +60 -0
- package/node_modules/@capyclaw/foundation/lib/subsystems/log.mjs +51 -0
- package/node_modules/@capyclaw/foundation/lib/subsystems/net.mjs +198 -0
- package/node_modules/@capyclaw/foundation/package.json +53 -0
- package/node_modules/@capyclaw/foundation/runtime/index.mjs +20 -0
- package/node_modules/@capyclaw/plugin-kit/INTEGRATION.md +100 -0
- package/node_modules/@capyclaw/plugin-kit/README.md +70 -0
- package/node_modules/@capyclaw/plugin-kit/bin/sync.mjs +103 -0
- package/node_modules/@capyclaw/plugin-kit/package.json +72 -0
- package/node_modules/@capyclaw/plugin-kit/src/cli.mjs +56 -0
- package/node_modules/@capyclaw/plugin-kit/src/config.mjs +142 -0
- package/node_modules/@capyclaw/plugin-kit/src/editor/heartbeat-worker.js +132 -0
- package/node_modules/@capyclaw/plugin-kit/src/editor/heartbeat.mjs +26 -0
- package/node_modules/@capyclaw/plugin-kit/src/editor/lease.mjs +60 -0
- package/node_modules/@capyclaw/plugin-kit/src/editor/shadow.mjs +219 -0
- package/node_modules/@capyclaw/plugin-kit/src/editor/transport.js +13 -0
- package/node_modules/@capyclaw/plugin-kit/src/index.mjs +13 -0
- package/node_modules/@capyclaw/plugin-kit/src/ledger.mjs +151 -0
- package/node_modules/@capyclaw/plugin-kit/src/pack.mjs +230 -0
- package/node_modules/@capyclaw/plugin-kit/src/runtime/context.mjs +128 -0
- package/node_modules/@capyclaw/plugin-kit/src/self-contained.mjs +307 -0
- package/node_modules/@capyclaw/plugin-kit/src/service/api.mjs +45 -0
- package/node_modules/@capyclaw/plugin-kit/src/service/http.mjs +113 -0
- package/node_modules/@capyclaw/plugin-kit/src/service/mcp-http.mjs +150 -0
- package/node_modules/@capyclaw/plugin-kit/src/service/server.mjs +131 -0
- package/node_modules/@capyclaw/plugin-kit/src/service/static.mjs +79 -0
- package/node_modules/@capyclaw/plugin-kit/src/skills/provider.mjs +82 -0
- package/node_modules/@capyclaw/plugin-kit/src/store/blob-store.mjs +109 -0
- package/node_modules/@capyclaw/plugin-kit/src/store/content-store.mjs +17 -0
- package/node_modules/@capyclaw/plugin-kit/src/store/journal-store.mjs +89 -0
- package/node_modules/@capyclaw/plugin-kit/src/tools/result.mjs +57 -0
- package/node_modules/@capyclaw/plugin-kit/src/tools/validate.mjs +150 -0
- package/node_modules/@capyclaw/plugin-kit/src/tuning.mjs +82 -0
- package/node_modules/@capyclaw/plugin-kit/src/util/fs-lock.mjs +132 -0
- package/node_modules/@capyclaw/plugin-kit/src/util/http.mjs +130 -0
- package/node_modules/@capyclaw/plugin-kit/src/workspace/manager.mjs +664 -0
- package/node_modules/@capyclaw/plugin-kit/src/zip.mjs +181 -0
- package/{skill → node_modules/@capyclaw/rsp-skill-remote-screen}/contract/rsp-contract.json +102 -13
- package/{skill → node_modules/@capyclaw/rsp-skill-remote-screen}/skills/remote-screen/SKILL.md +13 -2
- package/{workbench → node_modules/@capyclaw/rsp-workbench}/contract/capabilities.json +32 -0
- package/{workbench → node_modules/@capyclaw/rsp-workbench}/lib/client.mjs +238 -11
- package/node_modules/@capyclaw/rsp-workbench/lib/host.mjs +51 -0
- package/{workbench → node_modules/@capyclaw/rsp-workbench}/lib/tools.mjs +116 -16
- package/{workbench → node_modules/@capyclaw/rsp-workbench}/lib/workbench.mjs +21 -2
- package/node_modules/@capyclaw/rsp-workbench/plugin.mjs +17 -0
- package/{workbench → node_modules/@capyclaw/rsp-workbench}/ui/index.html +113 -10
- package/node_modules/@capyclaw/service-host/README.md +86 -0
- package/node_modules/@capyclaw/service-host/cordis.patch.yml +4 -0
- package/node_modules/@capyclaw/service-host/dsh-suite.json +29 -0
- package/node_modules/@capyclaw/service-host/lib/host.mjs +22 -0
- package/node_modules/@capyclaw/service-host/package.json +60 -0
- package/node_modules/@capyclaw/service-host/src/index.mjs +597 -0
- package/node_modules/@capyclaw/service-host/src/tuning.mjs +63 -0
- package/node_modules/@capyclaw/suite-kit/README.md +289 -0
- package/node_modules/@capyclaw/suite-kit/bin/dsh-domain.mjs +98 -0
- package/node_modules/@capyclaw/suite-kit/bin/dsh-suite.mjs +174 -0
- package/node_modules/@capyclaw/suite-kit/client/embed.js +35 -0
- package/node_modules/@capyclaw/suite-kit/domain.schema.json +129 -0
- package/node_modules/@capyclaw/suite-kit/package.json +58 -0
- package/node_modules/@capyclaw/suite-kit/src/activation-registry.mjs +184 -0
- package/node_modules/@capyclaw/suite-kit/src/artifacts.mjs +131 -0
- package/node_modules/@capyclaw/suite-kit/src/capability.mjs +181 -0
- package/node_modules/@capyclaw/suite-kit/src/compose.mjs +201 -0
- package/node_modules/@capyclaw/suite-kit/src/domain.mjs +138 -0
- package/node_modules/@capyclaw/suite-kit/src/embed.mjs +81 -0
- package/node_modules/@capyclaw/suite-kit/src/host.mjs +251 -0
- package/node_modules/@capyclaw/suite-kit/src/index.mjs +24 -0
- package/node_modules/@capyclaw/suite-kit/src/manifest.mjs +263 -0
- package/node_modules/@capyclaw/suite-kit/src/orchestration.mjs +100 -0
- package/node_modules/@capyclaw/suite-kit/src/profile.mjs +584 -0
- package/node_modules/@capyclaw/suite-kit/src/surface.mjs +28 -0
- package/node_modules/@capyclaw/suite-kit/suite.schema.json +128 -0
- package/node_modules/@capyclaw/tool-host/README.md +56 -0
- package/node_modules/@capyclaw/tool-host/cordis.patch.yml +4 -0
- package/node_modules/@capyclaw/tool-host/dsh-suite.json +30 -0
- package/node_modules/@capyclaw/tool-host/lib/host.mjs +46 -0
- package/node_modules/@capyclaw/tool-host/package.json +59 -0
- package/node_modules/@capyclaw/tool-host/src/admit-images.mjs +80 -0
- package/node_modules/@capyclaw/tool-host/src/caller-session.mjs +25 -0
- package/node_modules/@capyclaw/tool-host/src/descriptors.mjs +166 -0
- package/node_modules/@capyclaw/tool-host/src/index.mjs +461 -0
- package/node_modules/@capyclaw/tool-host/src/mode-gate.mjs +272 -0
- package/node_modules/ws/LICENSE +20 -0
- package/node_modules/ws/README.md +539 -0
- package/node_modules/ws/browser.js +8 -0
- package/node_modules/ws/index.js +22 -0
- package/node_modules/ws/lib/buffer-util.js +142 -0
- package/node_modules/ws/lib/constants.js +19 -0
- package/node_modules/ws/lib/event-target.js +292 -0
- package/node_modules/ws/lib/extension.js +203 -0
- package/node_modules/ws/lib/limiter.js +55 -0
- package/node_modules/ws/lib/permessage-deflate.js +530 -0
- package/node_modules/ws/lib/receiver.js +751 -0
- package/node_modules/ws/lib/sender.js +610 -0
- package/node_modules/ws/lib/stream.js +161 -0
- package/node_modules/ws/lib/subprotocol.js +62 -0
- package/node_modules/ws/lib/validation.js +152 -0
- package/node_modules/ws/lib/websocket-server.js +562 -0
- package/node_modules/ws/lib/websocket.js +1440 -0
- package/node_modules/ws/package.json +74 -0
- package/node_modules/ws/wrapper.mjs +21 -0
- package/package.json +22 -9
- package/workbench/lib/host.mjs +0 -111
- package/workbench/plugin.mjs +0 -2
- package/workbench/scripts/build-contract.mjs +0 -41
- package/workbench/scripts/drive.mjs +0 -66
- package/workbench/test/client.test.mjs +0 -218
- package/workbench/test/frames-prune.test.mjs +0 -49
- package/workbench/test/h264.test.mjs +0 -101
- package/workbench/test/live-persistent-smoke.mjs +0 -29
- package/workbench/test/live-smoke.mjs +0 -109
- package/workbench/test/mock-server.mjs +0 -194
- package/workbench/test/persistence.test.mjs +0 -177
- package/workbench/test/persistent.test.mjs +0 -160
- package/workbench/test/session-mode.test.mjs +0 -118
- package/workbench/test/workbench.test.mjs +0 -385
- package/workbench/verify-e2e.mjs +0 -44
- /package/{skill → node_modules/@capyclaw/rsp-skill-remote-screen}/README.md +0 -0
- /package/{skill → node_modules/@capyclaw/rsp-skill-remote-screen}/cordis.patch.yml +0 -0
- /package/{skill → node_modules/@capyclaw/rsp-skill-remote-screen}/package.json +0 -0
- /package/{skill → node_modules/@capyclaw/rsp-skill-remote-screen}/plugin.mjs +0 -0
- /package/{workbench → node_modules/@capyclaw/rsp-workbench}/lib/descriptors.mjs +0 -0
- /package/{workbench → node_modules/@capyclaw/rsp-workbench}/lib/manager.mjs +0 -0
- /package/{workbench → node_modules/@capyclaw/rsp-workbench}/lib/session-mode.mjs +0 -0
- /package/{workbench → node_modules/@capyclaw/rsp-workbench}/package.json +0 -0
|
@@ -1,101 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* 实时 H.264 增量通道(RSP/1 §7.3/§7.6)确定性测试:
|
|
3
|
-
* - 被控端未提供 /screen.h264.ws 时代理回 503(回退 JPEG,不致命);
|
|
4
|
-
* - 代理 /api/screen.h264 先补 SPS/PPS/IDR head,再原样转发 live Annex-B chunk;
|
|
5
|
-
* - client._openH264 解析 hello 并缓存 SPS/PPS/IDR head。
|
|
6
|
-
* 真实帧率/延迟证明见 reference/bench-realtime.mjs(ffmpeg 持久采集 + 硬件 H.264)。
|
|
7
|
-
*/
|
|
8
|
-
import test from 'node:test'
|
|
9
|
-
import assert from 'node:assert/strict'
|
|
10
|
-
import { mkdtempSync } from 'node:fs'
|
|
11
|
-
import { tmpdir } from 'node:os'
|
|
12
|
-
import path from 'node:path'
|
|
13
|
-
import { WebSocketServer } from 'ws'
|
|
14
|
-
import { createToolHost } from '@capyclaw/tool-host/src'
|
|
15
|
-
import { createServiceHost } from '@capyclaw/service-host/src'
|
|
16
|
-
import { createRspWorkbench } from '../lib/workbench.mjs'
|
|
17
|
-
import { RspManager } from '../lib/manager.mjs'
|
|
18
|
-
import { RspClient } from '../lib/client.mjs'
|
|
19
|
-
import { createMockRspServer } from './mock-server.mjs'
|
|
20
|
-
|
|
21
|
-
const SPS = Buffer.from([0, 0, 0, 1, 0x67, 0x42, 0x00, 0x1f, 0x00])
|
|
22
|
-
const PPS = Buffer.from([0, 0, 0, 1, 0x68, 0xce, 0x3c, 0x80])
|
|
23
|
-
const IDR = Buffer.from([0, 0, 0, 1, 0x65, 0x88, 0x84, 0x00, 0x11])
|
|
24
|
-
const P = Buffer.from([0, 0, 0, 1, 0x41, 0x9a, 0x22, 0x33])
|
|
25
|
-
|
|
26
|
-
async function waitFor(fn, timeout = 4000, step = 20) {
|
|
27
|
-
const end = Date.now() + timeout
|
|
28
|
-
while (Date.now() < end) { const v = await fn(); if (v) return v; await new Promise((r) => setTimeout(r, step)) }
|
|
29
|
-
throw new Error('waitFor 超时')
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
async function setup(t) {
|
|
33
|
-
const mock = await createMockRspServer({})
|
|
34
|
-
const hostDir = mkdtempSync(path.join(tmpdir(), 'rsp-h264-test-'))
|
|
35
|
-
const manager = new RspManager({ hostDir })
|
|
36
|
-
const wb = createRspWorkbench({ toolHost: createToolHost({}), serviceHost: createServiceHost({}), manager, config: { hostDir } })
|
|
37
|
-
const l = await wb.app.listen({ port: 0, hostDir })
|
|
38
|
-
t.after(async () => { await wb.close(); await mock.close() })
|
|
39
|
-
const connect = async () => {
|
|
40
|
-
const r = await wb.registry.TOOL_IMPL.rsp_connect({ url: mock.url, token: mock.token, name: 'mock' })
|
|
41
|
-
assert.equal(r.isError, false)
|
|
42
|
-
await waitFor(() => manager.connected && manager.client.lastFrame)
|
|
43
|
-
}
|
|
44
|
-
return { mock, wb, manager, l, connect }
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
test('被控端无 h264 端点:代理 503,client 回退 unsupported', async (t) => {
|
|
48
|
-
const { manager, l, connect } = await setup(t)
|
|
49
|
-
await connect()
|
|
50
|
-
await waitFor(() => manager.client.h264State !== 'connecting' && manager.client.h264State !== 'idle')
|
|
51
|
-
assert.notEqual(manager.client.h264State, 'open')
|
|
52
|
-
const res = await fetch(l.url + '/api/screen.h264')
|
|
53
|
-
assert.equal(res.status, 503)
|
|
54
|
-
const body = await res.json()
|
|
55
|
-
assert.equal(body.code, 'engine_unavailable')
|
|
56
|
-
})
|
|
57
|
-
|
|
58
|
-
test('代理先补 head 再转发 live chunk(字节级一致)', async (t) => {
|
|
59
|
-
const { manager, l, connect } = await setup(t)
|
|
60
|
-
await connect()
|
|
61
|
-
const client = manager.client
|
|
62
|
-
client.h264State = 'open'
|
|
63
|
-
client.h264Head = [SPS, PPS, IDR]
|
|
64
|
-
const ac = new AbortController()
|
|
65
|
-
const res = await fetch(l.url + '/api/screen.h264', { signal: ac.signal })
|
|
66
|
-
assert.equal(res.status, 200)
|
|
67
|
-
assert.equal(res.headers.get('x-rsp-format'), 'h264')
|
|
68
|
-
const reader = res.body.getReader()
|
|
69
|
-
const chunks = []
|
|
70
|
-
const readSome = async () => { const { value } = await reader.read(); if (value) chunks.push(Buffer.from(value)) }
|
|
71
|
-
await readSome() // head
|
|
72
|
-
// 回归:req 的 'close' 在 GET 请求体读完即触发;代理若误监听它,
|
|
73
|
-
// 延迟到达的 live chunk 会丢。等 120ms 确保该事件已发生再注入。
|
|
74
|
-
await new Promise((r) => setTimeout(r, 120))
|
|
75
|
-
client.emit('h264', P)
|
|
76
|
-
await readSome() // live
|
|
77
|
-
ac.abort()
|
|
78
|
-
const got = Buffer.concat(chunks)
|
|
79
|
-
const want = Buffer.concat([SPS, PPS, IDR, P])
|
|
80
|
-
assert.ok(got.subarray(0, want.length).equals(want), 'head+live 字节应一致')
|
|
81
|
-
})
|
|
82
|
-
|
|
83
|
-
test('client._openH264 解析 hello 并缓存 SPS/PPS/IDR', async (t) => {
|
|
84
|
-
const wss = new WebSocketServer({ port: 0 })
|
|
85
|
-
await new Promise((r) => wss.on('listening', r))
|
|
86
|
-
const port = wss.address().port
|
|
87
|
-
wss.on('connection', (ws) => {
|
|
88
|
-
ws.send(JSON.stringify({ protocol: 'rsp/1', kind: 'hello', format: 'h264', width: 1920, height: 1080, fps: 30 }))
|
|
89
|
-
ws.send(SPS); ws.send(PPS); ws.send(IDR); ws.send(P)
|
|
90
|
-
})
|
|
91
|
-
t.after(() => new Promise((r) => wss.close(r)))
|
|
92
|
-
const client = new RspClient({ baseUrl: `http://127.0.0.1:${port}`, token: 'x' })
|
|
93
|
-
t.after(() => client.disconnect())
|
|
94
|
-
client._openH264()
|
|
95
|
-
await waitFor(() => client.h264State === 'open' && client.h264Hello && client.h264Head.length >= 3)
|
|
96
|
-
assert.equal(client.h264Hello.format, 'h264')
|
|
97
|
-
assert.equal(client.h264Hello.width, 1920)
|
|
98
|
-
const types = client.h264Head.map((b) => b[4] & 0x1f)
|
|
99
|
-
assert.deepEqual(types, [7, 8, 5])
|
|
100
|
-
await client.disconnect()
|
|
101
|
-
})
|
|
@@ -1,29 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* 手动冒烟:用真实保险库(~/.dsh-rsp)验证「激活即连」常驻连接。
|
|
3
|
-
* 运行:node test/live-persistent-smoke.mjs
|
|
4
|
-
* 只读验证:startPersistent 不写 vault;结束 close() 断开。不触碰运行中的宿主。
|
|
5
|
-
*/
|
|
6
|
-
import os from 'node:os'
|
|
7
|
-
import path from 'node:path'
|
|
8
|
-
import { RspManager } from '../lib/manager.mjs'
|
|
9
|
-
|
|
10
|
-
const hostDir = process.env.DSH_RSP_HOST_DIR || path.join(os.homedir(), '.dsh-rsp')
|
|
11
|
-
const m = new RspManager({ hostDir, logger: (...a) => console.log('[log]', ...a) })
|
|
12
|
-
const before = m.status()
|
|
13
|
-
console.log('激活前 connected=', before.connected, 'active=', before.remembered.active)
|
|
14
|
-
m.startPersistent()
|
|
15
|
-
const deadline = Date.now() + 15000
|
|
16
|
-
let ok = false
|
|
17
|
-
while (Date.now() < deadline) {
|
|
18
|
-
const st = m.status()
|
|
19
|
-
if (st.persistent.connected) { ok = true; break }
|
|
20
|
-
await new Promise((r) => setTimeout(r, 200))
|
|
21
|
-
}
|
|
22
|
-
const st = m.status('some-brand-new-session')
|
|
23
|
-
console.log('常驻 connected=', st.persistent.connected, 'wanted=', st.persistent.wanted)
|
|
24
|
-
console.log('新会话视图 connected=', st.connected, 'viaPersistent=', st.viaPersistent, 'target=', st.target && st.target.name)
|
|
25
|
-
const c = m.clientFor('some-brand-new-session')
|
|
26
|
-
console.log('查看器取帧源=', !!c, 'lastFrame=', c && c.lastFrame ? (c.lastFrame.width + 'x' + c.lastFrame.height) : null)
|
|
27
|
-
await m.close()
|
|
28
|
-
console.log(ok ? 'SMOKE PASS:激活即连真实目标成功' : 'SMOKE FAIL:15s 内未连上(目标可能离线/锁屏不影响连接)')
|
|
29
|
-
process.exit(ok ? 0 : 1)
|
|
@@ -1,109 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* 活体冒烟:把「真实安装在宿主里的 rsp-workbench」指向一个规范一致的 mock 被控端,
|
|
3
|
-
* 通过宿主的 HTTP/MCP 面驱动全部工具,验证部署本身端到端可用(区别于进程内单测)。
|
|
4
|
-
* 运行:node test/live-smoke.mjs [hostBase] (默认 http://127.0.0.1:8046)
|
|
5
|
-
* mock 与脚本同进程,可直接读 mock.events 断言被控端实际收到的事件。
|
|
6
|
-
*/
|
|
7
|
-
import { createMockRspServer } from './mock-server.mjs'
|
|
8
|
-
import { jpegSize } from '../lib/client.mjs'
|
|
9
|
-
|
|
10
|
-
const HOST = process.argv[2] || 'http://127.0.0.1:8046'
|
|
11
|
-
const WB = HOST + '/capyclaw/rsp'
|
|
12
|
-
const results = []
|
|
13
|
-
const check = (name, cond, extra = '') => { results.push({ name, ok: !!cond, extra }); console.log(`${cond ? '✓' : '✗'} ${name}${extra ? ' ' + extra : ''}`) }
|
|
14
|
-
const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
|
|
15
|
-
|
|
16
|
-
async function jget(path) { const r = await fetch(WB + path); return { status: r.status, body: await r.json().catch(() => null) } }
|
|
17
|
-
async function jpost(path, obj) {
|
|
18
|
-
const r = await fetch(WB + path, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(obj) })
|
|
19
|
-
return { status: r.status, body: await r.json().catch(() => null) }
|
|
20
|
-
}
|
|
21
|
-
let mcpId = 0
|
|
22
|
-
async function mcp(name, args) {
|
|
23
|
-
const r = await fetch(WB + '/mcp', {
|
|
24
|
-
method: 'POST', headers: { 'content-type': 'application/json' },
|
|
25
|
-
body: JSON.stringify({ jsonrpc: '2.0', id: ++mcpId, method: 'tools/call', params: { name, arguments: args } }),
|
|
26
|
-
})
|
|
27
|
-
const j = await r.json().catch(() => null)
|
|
28
|
-
return j?.result ?? j
|
|
29
|
-
}
|
|
30
|
-
const textOf = (res) => (res?.content || []).filter((c) => c.type === 'text').map((c) => c.text).join('\n')
|
|
31
|
-
const parseMeta = (res) => { try { return JSON.parse(textOf(res)) } catch { return null } }
|
|
32
|
-
|
|
33
|
-
const mock = await createMockRspServer({})
|
|
34
|
-
console.log(`mock 被控端: ${mock.url} logical=${mock.logical.width}x${mock.logical.height} frame=${mock.frame.width}x${mock.frame.height}`)
|
|
35
|
-
console.log(`宿主工作台: ${WB}\n`)
|
|
36
|
-
|
|
37
|
-
try {
|
|
38
|
-
// 1. 连接(persist:false 不落盘目标)
|
|
39
|
-
const conn = await jpost('/api/connect', { url: mock.url, token: mock.token, name: 'live-smoke', persist: false })
|
|
40
|
-
check('connect 200 + protocol rsp/1', conn.status === 200 && conn.body?.info?.protocol === 'rsp/1', `status=${conn.status}`)
|
|
41
|
-
await sleep(400) // 等首帧
|
|
42
|
-
const st = await jget('/api/status')
|
|
43
|
-
check('status connected', st.body?.connected === true, JSON.stringify(st.body?.client?.logical || {}))
|
|
44
|
-
|
|
45
|
-
// 2. 抓帧(MCP rsp_screen)
|
|
46
|
-
const screen = await mcp('rsp_screen', { save: false })
|
|
47
|
-
const hasImage = (screen?.content || []).some((c) => c.type === 'image' && c.mimeType === 'image/jpeg')
|
|
48
|
-
const meta = parseMeta(screen)
|
|
49
|
-
check('rsp_screen 内联 JPEG', hasImage)
|
|
50
|
-
check('rsp_screen 坐标换算 scale=2', meta?.frameToLogicalScale?.x === 2 && meta?.frameToLogicalScale?.y === 2, JSON.stringify(meta?.frameToLogicalScale || {}))
|
|
51
|
-
|
|
52
|
-
// 3. 鼠标点击:frame(480,270) → logical(960,540)
|
|
53
|
-
const click = await mcp('rsp_mouse', { action: 'click', x: 480, y: 270, space: 'frame' })
|
|
54
|
-
check('rsp_mouse click ok', !click?.isError, textOf(click).slice(0, 120))
|
|
55
|
-
// 4. 键盘快捷键 Cmd+A(成对 down/up)
|
|
56
|
-
await mcp('rsp_key', { action: 'down', code: 'KeyA', modifiers: ['cmd'] })
|
|
57
|
-
await mcp('rsp_key', { action: 'up', code: 'KeyA', modifiers: ['cmd'] })
|
|
58
|
-
// 5. 文本(Unicode 注入)
|
|
59
|
-
await mcp('rsp_text', { text: '你好,世界' })
|
|
60
|
-
// 6. 拖拽:frame(100,100)→(300,200) = logical(200,200)→(600,400)
|
|
61
|
-
await mcp('rsp_drag', { fromX: 100, fromY: 100, toX: 300, toY: 200, steps: 4, space: 'frame' })
|
|
62
|
-
// 7. 批处理滚轮
|
|
63
|
-
await mcp('rsp_batch', { events: [{ cmd: 'mouse', action: 'scroll', dx: 0, dy: 120 }] })
|
|
64
|
-
await sleep(200)
|
|
65
|
-
|
|
66
|
-
// 断言被控端实际收到的事件
|
|
67
|
-
const ev = mock.events
|
|
68
|
-
const clickEv = ev.find((e) => e.cmd === 'mouse' && e.action === 'click')
|
|
69
|
-
check('被控端收到 click@(960,540)', clickEv && clickEv.x === 960 && clickEv.y === 540, JSON.stringify(clickEv || null))
|
|
70
|
-
const kd = ev.find((e) => e.cmd === 'key' && e.action === 'down' && e.code === 'KeyA')
|
|
71
|
-
const ku = ev.find((e) => e.cmd === 'key' && e.action === 'up' && e.code === 'KeyA')
|
|
72
|
-
check('被控端收到 KeyA down+up(cmd)', kd && ku && JSON.stringify(kd.modifiers) === '["cmd"]', JSON.stringify(kd?.modifiers || []))
|
|
73
|
-
const txt = ev.find((e) => e.cmd === 'text')
|
|
74
|
-
check('被控端收到文本「你好,世界」', txt && txt.text === '你好,世界', JSON.stringify(txt?.text || ''))
|
|
75
|
-
const downs = ev.filter((e) => e.cmd === 'mouse' && e.action === 'down')
|
|
76
|
-
const ups = ev.filter((e) => e.cmd === 'mouse' && e.action === 'up')
|
|
77
|
-
const moves = ev.filter((e) => e.cmd === 'mouse' && e.action === 'move')
|
|
78
|
-
const dragDown = downs.find((e) => e.x === 200 && e.y === 200)
|
|
79
|
-
const dragUp = ups.find((e) => e.x === 600 && e.y === 400)
|
|
80
|
-
check('拖拽 down@(200,200) up@(600,400) + 中间 move', dragDown && dragUp && moves.length >= 3, `down=${!!dragDown} up=${!!dragUp} moves=${moves.length}`)
|
|
81
|
-
const scroll = ev.find((e) => e.cmd === 'mouse' && e.action === 'scroll')
|
|
82
|
-
check('被控端收到 scroll dy=120', scroll && scroll.dy === 120, JSON.stringify(scroll || null))
|
|
83
|
-
|
|
84
|
-
// 8. /api/frame 直出 JPEG
|
|
85
|
-
const fr = await fetch(WB + '/api/frame')
|
|
86
|
-
const buf = Buffer.from(await fr.arrayBuffer())
|
|
87
|
-
const size = jpegSize(buf)
|
|
88
|
-
check('/api/frame JPEG 960x540', fr.status === 200 && buf[0] === 0xff && buf[1] === 0xd8 && size?.width === 960 && size?.height === 540, `${fr.status} ${size?.width}x${size?.height}`)
|
|
89
|
-
|
|
90
|
-
// 9. /api/screen.mjpg 代理(令牌留服务端)
|
|
91
|
-
const mj = await fetch(WB + '/api/screen.mjpg')
|
|
92
|
-
const reader = mj.body.getReader()
|
|
93
|
-
const { value } = await reader.read()
|
|
94
|
-
await reader.cancel()
|
|
95
|
-
const head = Buffer.from(value || []).toString('latin1')
|
|
96
|
-
check('/api/screen.mjpg multipart 代理', mj.status === 200 && head.includes('--rspframe') && head.includes('image/jpeg'), `ct=${mj.headers.get('content-type')}`)
|
|
97
|
-
|
|
98
|
-
// 10. 断开
|
|
99
|
-
const disc = await jpost('/api/disconnect', { forget: true })
|
|
100
|
-
check('disconnect ok', disc.status === 200, JSON.stringify(disc.body || {}))
|
|
101
|
-
} catch (err) {
|
|
102
|
-
check('无异常', false, String(err?.stack || err))
|
|
103
|
-
} finally {
|
|
104
|
-
await mock.close()
|
|
105
|
-
}
|
|
106
|
-
|
|
107
|
-
const failed = results.filter((r) => !r.ok)
|
|
108
|
-
console.log(`\n${failed.length === 0 ? '✅ LIVE SMOKE PASS' : '❌ LIVE SMOKE FAIL'} ${results.length - failed.length}/${results.length}`)
|
|
109
|
-
process.exit(failed.length === 0 ? 0 : 1)
|
|
@@ -1,194 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* RSP/1 被控端 mock(测试夹具)。严格按规范实现服务端侧,用于验证控制端:
|
|
3
|
-
* - GET /info(鉴权)、GET /screen(MJPEG)、POST /control(鉴权/禁用/校验)
|
|
4
|
-
* - WS /screen.ws(TEXT hello + BINARY JPEG 帧)、WS /control.ws(seq/ack、error、§5.5 断线补 up)
|
|
5
|
-
* - 鉴权失败:HTTP 401;WS 握手后关闭码 4001。操控禁用:WS 4003 / POST 403。
|
|
6
|
-
* 记录所有注入事件到 events[],供断言。
|
|
7
|
-
*/
|
|
8
|
-
import http from 'node:http'
|
|
9
|
-
import { WebSocketServer } from 'ws'
|
|
10
|
-
|
|
11
|
-
/** 构造携带 SOF0 尺寸的最小 JPEG(jpegSize 可解析;非可解码图,测试只验字节/尺寸)。 */
|
|
12
|
-
export function makeJpeg(w, h) {
|
|
13
|
-
return Buffer.from([
|
|
14
|
-
0xff, 0xd8, // SOI
|
|
15
|
-
0xff, 0xc0, 0x00, 0x0b, 0x08, // SOF0, len=11, precision=8
|
|
16
|
-
(h >> 8) & 0xff, h & 0xff, (w >> 8) & 0xff, w & 0xff, // height, width
|
|
17
|
-
0x01, 0x01, 0x11, 0x00, // 1 component
|
|
18
|
-
0xff, 0xd9, // EOI
|
|
19
|
-
])
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
const KEY_CODES = new Set([
|
|
23
|
-
...Array.from({ length: 26 }, (_, i) => 'Key' + String.fromCharCode(65 + i)),
|
|
24
|
-
...Array.from({ length: 10 }, (_, i) => 'Digit' + i),
|
|
25
|
-
'Minus', 'Equal', 'BracketLeft', 'BracketRight', 'Backslash', 'Semicolon', 'Quote', 'Comma', 'Period', 'Slash', 'Backquote',
|
|
26
|
-
'Enter', 'Tab', 'Space', 'Backspace', 'Escape', 'CapsLock', 'Delete', 'Insert', 'Home', 'End', 'PageUp', 'PageDown',
|
|
27
|
-
'ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown',
|
|
28
|
-
'ShiftLeft', 'ShiftRight', 'ControlLeft', 'ControlRight', 'AltLeft', 'AltRight', 'MetaLeft', 'MetaRight',
|
|
29
|
-
...Array.from({ length: 20 }, (_, i) => 'F' + (i + 1)),
|
|
30
|
-
...Array.from({ length: 10 }, (_, i) => 'Numpad' + i),
|
|
31
|
-
'NumpadDivide', 'NumpadMultiply', 'NumpadSubtract', 'NumpadAdd', 'NumpadEnter', 'NumpadDecimal',
|
|
32
|
-
])
|
|
33
|
-
|
|
34
|
-
/** 轻量事件校验(镜像 §5)。返回 null=合法,否则 {code,message}。 */
|
|
35
|
-
export function validateEvent(ev) {
|
|
36
|
-
if (!ev || typeof ev !== 'object') return { code: 'bad_event', message: 'event must be object' }
|
|
37
|
-
if (ev.cmd === 'mouse') {
|
|
38
|
-
if (!['move', 'down', 'up', 'click', 'scroll'].includes(ev.action)) return { code: 'bad_event', message: 'bad mouse action: ' + ev.action }
|
|
39
|
-
if (ev.action !== 'scroll' && (typeof ev.x !== 'number' || typeof ev.y !== 'number')) return { code: 'bad_event', message: 'mouse x/y required' }
|
|
40
|
-
if (ev.button && !['left', 'right', 'middle'].includes(ev.button)) return { code: 'bad_event', message: 'bad button' }
|
|
41
|
-
return null
|
|
42
|
-
}
|
|
43
|
-
if (ev.cmd === 'key') {
|
|
44
|
-
if (!['down', 'up'].includes(ev.action)) return { code: 'bad_event', message: 'bad key action' }
|
|
45
|
-
if (!KEY_CODES.has(ev.code)) return { code: 'bad_event', message: 'unknown key code: ' + ev.code }
|
|
46
|
-
return null
|
|
47
|
-
}
|
|
48
|
-
if (ev.cmd === 'text') {
|
|
49
|
-
if (typeof ev.text !== 'string') return { code: 'bad_event', message: 'text must be string' }
|
|
50
|
-
if (ev.text.length > 4096) return { code: 'bad_event', message: 'text too long' }
|
|
51
|
-
return null
|
|
52
|
-
}
|
|
53
|
-
return { code: 'bad_event', message: 'unknown cmd: ' + ev.cmd }
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
function tokenOf(req) {
|
|
57
|
-
const u = new URL(req.url, 'http://localhost')
|
|
58
|
-
const q = u.searchParams.get('token')
|
|
59
|
-
if (q) return q
|
|
60
|
-
const h = req.headers.authorization || ''
|
|
61
|
-
const m = /^Bearer\s+(.+)$/i.exec(h)
|
|
62
|
-
return m ? m[1] : null
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
export async function createMockRspServer(opts = {}) {
|
|
66
|
-
const token = opts.token ?? 'mock-token-abcdefghijklmnop'
|
|
67
|
-
const logical = { width: opts.width ?? 1920, height: opts.height ?? 1080 }
|
|
68
|
-
const frame = { width: opts.frameWidth ?? 960, height: opts.frameHeight ?? 540 }
|
|
69
|
-
const fps = opts.fps ?? 30
|
|
70
|
-
let controlEnabled = opts.controlEnabled ?? true
|
|
71
|
-
let engineReady = opts.engineReady ?? true
|
|
72
|
-
const controlWsEnabled = opts.controlWs !== false // false=拒绝 /control.ws 升级(测 POST 降级)
|
|
73
|
-
const events = [] // 所有注入事件(ws + post)
|
|
74
|
-
const releasedOnClose = [] // §5.5 断线自动补发的 up
|
|
75
|
-
const screenClients = new Set()
|
|
76
|
-
const timers = new Set()
|
|
77
|
-
|
|
78
|
-
const info = () => ({
|
|
79
|
-
protocol: 'rsp/1', service: 'remote-screen', serviceVersion: '0.1.0-mock',
|
|
80
|
-
screen: { width: logical.width, height: logical.height, format: 'jpeg', fps, maxWidth: logical.width },
|
|
81
|
-
control: { enabled: controlEnabled },
|
|
82
|
-
viewers: screenClients.size,
|
|
83
|
-
engine: { ready: engineReady, axTrusted: true, screenCapture: true },
|
|
84
|
-
})
|
|
85
|
-
const json = (res, code, obj) => { res.writeHead(code, { 'content-type': 'application/json' }); res.end(JSON.stringify(obj)) }
|
|
86
|
-
const authOk = (req) => tokenOf(req) === token
|
|
87
|
-
|
|
88
|
-
const server = http.createServer((req, res) => {
|
|
89
|
-
const u = new URL(req.url, 'http://localhost')
|
|
90
|
-
const p = u.pathname
|
|
91
|
-
if (p === '/') { res.writeHead(200, { 'content-type': 'text/plain' }); res.end('mock rsp viewer'); return }
|
|
92
|
-
if (p === '/info') {
|
|
93
|
-
if (!authOk(req)) return json(res, 401, { error: { code: 'unauthorized', message: 'bad token' } })
|
|
94
|
-
return json(res, 200, info())
|
|
95
|
-
}
|
|
96
|
-
if (p === '/screen') {
|
|
97
|
-
if (!authOk(req)) return json(res, 401, { error: { code: 'unauthorized', message: 'bad token' } })
|
|
98
|
-
if (!engineReady) return json(res, 503, { error: { code: 'engine_unavailable', message: 'engine not ready' } })
|
|
99
|
-
res.writeHead(200, { 'content-type': 'multipart/x-mixed-replace; boundary=rspframe', 'cache-control': 'no-store' })
|
|
100
|
-
const t = setInterval(() => {
|
|
101
|
-
const jpg = makeJpeg(frame.width, frame.height)
|
|
102
|
-
res.write(`--rspframe\r\nContent-Type: image/jpeg\r\nContent-Length: ${jpg.length}\r\n\r\n`)
|
|
103
|
-
res.write(jpg); res.write('\r\n')
|
|
104
|
-
}, Math.max(20, 1000 / fps))
|
|
105
|
-
timers.add(t)
|
|
106
|
-
req.on('close', () => { clearInterval(t); timers.delete(t) })
|
|
107
|
-
return
|
|
108
|
-
}
|
|
109
|
-
if (p === '/control' && req.method === 'POST') {
|
|
110
|
-
if (!authOk(req)) return json(res, 401, { error: { code: 'unauthorized', message: 'bad token' } })
|
|
111
|
-
if (!controlEnabled) return json(res, 403, { error: { code: 'forbidden', message: 'control disabled' } })
|
|
112
|
-
if (!engineReady) return json(res, 503, { error: { code: 'engine_unavailable', message: 'engine not ready' } })
|
|
113
|
-
let body = ''
|
|
114
|
-
req.on('data', (c) => { body += c; if (body.length > 65536) { json(res, 413, { error: { code: 'too_large', message: 'body too large' } }); req.destroy() } })
|
|
115
|
-
req.on('end', () => {
|
|
116
|
-
let ev; try { ev = JSON.parse(body) } catch { return json(res, 400, { error: { code: 'bad_event', message: 'bad json' } }) }
|
|
117
|
-
const bad = validateEvent(ev)
|
|
118
|
-
if (bad) return json(res, 400, { error: bad })
|
|
119
|
-
events.push(ev)
|
|
120
|
-
json(res, 200, { ok: true })
|
|
121
|
-
})
|
|
122
|
-
return
|
|
123
|
-
}
|
|
124
|
-
json(res, 404, { error: { code: 'not_found', message: 'unknown path ' + p } })
|
|
125
|
-
})
|
|
126
|
-
|
|
127
|
-
const wssScreen = new WebSocketServer({ noServer: true })
|
|
128
|
-
const wssControl = new WebSocketServer({ noServer: true })
|
|
129
|
-
|
|
130
|
-
function setupScreen(ws) {
|
|
131
|
-
screenClients.add(ws)
|
|
132
|
-
ws.send(JSON.stringify({ protocol: 'rsp/1', kind: 'hello', width: logical.width, height: logical.height, fps, format: 'jpeg' }))
|
|
133
|
-
const t = setInterval(() => { if (ws.readyState === 1) ws.send(makeJpeg(frame.width, frame.height)) }, Math.max(20, 1000 / fps))
|
|
134
|
-
timers.add(t)
|
|
135
|
-
ws.on('message', () => { /* §4.1.7 忽略客户端消息 */ })
|
|
136
|
-
ws.on('close', () => { screenClients.delete(ws); clearInterval(t); timers.delete(t) })
|
|
137
|
-
}
|
|
138
|
-
|
|
139
|
-
function setupControl(ws) {
|
|
140
|
-
const pressedKeys = new Set(), pressedButtons = new Set()
|
|
141
|
-
ws.on('message', (data, isBinary) => {
|
|
142
|
-
if (isBinary) { ws.close(4004, 'binary not allowed'); return }
|
|
143
|
-
const text = data.toString()
|
|
144
|
-
if (Buffer.byteLength(text) > 65536) { ws.close(4004, 'too large'); return }
|
|
145
|
-
let ev; try { ev = JSON.parse(text) } catch { ws.send(JSON.stringify({ kind: 'error', code: 'bad_event', message: 'bad json' })); return }
|
|
146
|
-
const bad = validateEvent(ev)
|
|
147
|
-
if (bad) { ws.send(JSON.stringify({ kind: 'error', ...bad })); return }
|
|
148
|
-
events.push(ev)
|
|
149
|
-
if (ev.cmd === 'key') { ev.action === 'down' ? pressedKeys.add(ev.code) : pressedKeys.delete(ev.code) }
|
|
150
|
-
if (ev.cmd === 'mouse') { const b = ev.button || 'left'; ev.action === 'down' ? pressedButtons.add(b) : pressedButtons.delete(b) }
|
|
151
|
-
if (ev.seq != null) ws.send(JSON.stringify({ kind: 'ack', seq: ev.seq }))
|
|
152
|
-
})
|
|
153
|
-
ws.on('close', () => {
|
|
154
|
-
// §5.5 断线自动补 up
|
|
155
|
-
for (const code of pressedKeys) { const up = { cmd: 'key', action: 'up', code }; events.push(up); releasedOnClose.push(up) }
|
|
156
|
-
for (const button of pressedButtons) { const up = { cmd: 'mouse', action: 'up', x: 0, y: 0, button }; events.push(up); releasedOnClose.push(up) }
|
|
157
|
-
})
|
|
158
|
-
}
|
|
159
|
-
|
|
160
|
-
server.on('upgrade', (req, socket, head) => {
|
|
161
|
-
const u = new URL(req.url, 'http://localhost')
|
|
162
|
-
const ok = authOk(req)
|
|
163
|
-
if (u.pathname === '/screen.ws') {
|
|
164
|
-
wssScreen.handleUpgrade(req, socket, head, (ws) => { if (!ok) { ws.close(4001, 'unauthorized'); return } setupScreen(ws) })
|
|
165
|
-
} else if (u.pathname === '/control.ws') {
|
|
166
|
-
if (!controlWsEnabled) { socket.write('HTTP/1.1 503 Service Unavailable\r\nConnection: close\r\n\r\n'); socket.destroy(); return }
|
|
167
|
-
if (!controlEnabled) { wssControl.handleUpgrade(req, socket, head, (ws) => ws.close(4003, 'control disabled')); return }
|
|
168
|
-
wssControl.handleUpgrade(req, socket, head, (ws) => { if (!ok) { ws.close(4001, 'unauthorized'); return } setupControl(ws) })
|
|
169
|
-
} else {
|
|
170
|
-
socket.write('HTTP/1.1 404 Not Found\r\nConnection: close\r\n\r\n'); socket.destroy()
|
|
171
|
-
}
|
|
172
|
-
})
|
|
173
|
-
|
|
174
|
-
await new Promise((r) => server.listen(0, '127.0.0.1', r))
|
|
175
|
-
const port = server.address().port
|
|
176
|
-
const url = `http://127.0.0.1:${port}`
|
|
177
|
-
|
|
178
|
-
async function close() {
|
|
179
|
-
for (const t of timers) clearInterval(t)
|
|
180
|
-
timers.clear()
|
|
181
|
-
for (const ws of wssScreen.clients) ws.terminate()
|
|
182
|
-
for (const ws of wssControl.clients) ws.terminate()
|
|
183
|
-
await new Promise((r) => { wssScreen.close(() => wssControl.close(() => server.close(r))) })
|
|
184
|
-
}
|
|
185
|
-
|
|
186
|
-
return {
|
|
187
|
-
server, url, port, token, events, releasedOnClose, logical, frame,
|
|
188
|
-
get controlEnabled() { return controlEnabled },
|
|
189
|
-
setControlEnabled(v) { controlEnabled = v },
|
|
190
|
-
get engineReady() { return engineReady },
|
|
191
|
-
setEngineReady(v) { engineReady = v },
|
|
192
|
-
close,
|
|
193
|
-
}
|
|
194
|
-
}
|
|
@@ -1,177 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* 连接态持久化(目标保险库 + 每会话独立连接)专项测试。
|
|
3
|
-
* 对标 browser-suite login-vault 语义:共享记忆、不共享连接;懒自动重连;原子写;v1 迁移。
|
|
4
|
-
*/
|
|
5
|
-
import test from 'node:test'
|
|
6
|
-
import assert from 'node:assert/strict'
|
|
7
|
-
import { mkdtempSync, readFileSync, writeFileSync, existsSync } from 'node:fs'
|
|
8
|
-
import { tmpdir } from 'node:os'
|
|
9
|
-
import path from 'node:path'
|
|
10
|
-
import { RspManager, loadVault, saveVault, VAULT_VERSION, DEFAULT_BUCKET } from '../lib/manager.mjs'
|
|
11
|
-
import { createMockRspServer } from './mock-server.mjs'
|
|
12
|
-
|
|
13
|
-
async function waitFor(fn, timeout = 4000, step = 20) {
|
|
14
|
-
const end = Date.now() + timeout
|
|
15
|
-
while (Date.now() < end) {
|
|
16
|
-
const v = await fn()
|
|
17
|
-
if (v) return v
|
|
18
|
-
await new Promise((r) => setTimeout(r, step))
|
|
19
|
-
}
|
|
20
|
-
throw new Error('waitFor 超时')
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
function tmpHost() { return mkdtempSync(path.join(tmpdir(), 'rsp-vault-test-')) }
|
|
24
|
-
|
|
25
|
-
test('loadVault:缺失/损坏/未知版本收敛为空库;v1 自动迁移', () => {
|
|
26
|
-
const dir = tmpHost()
|
|
27
|
-
const file = path.join(dir, 'targets.json')
|
|
28
|
-
assert.deepEqual(loadVault(file).targets, {})
|
|
29
|
-
writeFileSync(file, '{ broken json')
|
|
30
|
-
assert.deepEqual(loadVault(file).targets, {})
|
|
31
|
-
writeFileSync(file, JSON.stringify({ version: 99, targets: { x: {} } }))
|
|
32
|
-
assert.deepEqual(loadVault(file).targets, {})
|
|
33
|
-
writeFileSync(file, JSON.stringify({ active: { name: 'mac', baseUrl: 'http://1.2.3.4:8765', token: 'tok' }, updatedAt: '2026-01-01T00:00:00.000Z' }))
|
|
34
|
-
const v = loadVault(file)
|
|
35
|
-
assert.equal(v.version, VAULT_VERSION)
|
|
36
|
-
assert.equal(v.active, 'mac')
|
|
37
|
-
assert.equal(v.targets.mac.token, 'tok')
|
|
38
|
-
assert.equal(v.targets.mac.baseUrl, 'http://1.2.3.4:8765')
|
|
39
|
-
})
|
|
40
|
-
|
|
41
|
-
test('saveVault:原子写 + 版本戳;DSH_RSP_TARGET_VAULT=false 关闭', () => {
|
|
42
|
-
const dir = tmpHost()
|
|
43
|
-
const file = path.join(dir, 'targets.json')
|
|
44
|
-
const v = { version: VAULT_VERSION, targets: {}, sessions: {}, active: null, updatedAt: null }
|
|
45
|
-
assert.equal(saveVault(file, v), true)
|
|
46
|
-
assert.equal(JSON.parse(readFileSync(file, 'utf8')).version, VAULT_VERSION)
|
|
47
|
-
assert.ok(!existsSync(file + '.tmp'), 'tmp 应被 rename 掉')
|
|
48
|
-
process.env.DSH_RSP_TARGET_VAULT = 'false'
|
|
49
|
-
try {
|
|
50
|
-
assert.equal(saveVault(file, { ...v, active: 'x' }), false)
|
|
51
|
-
assert.equal(JSON.parse(readFileSync(file, 'utf8')).active, null)
|
|
52
|
-
} finally { delete process.env.DSH_RSP_TARGET_VAULT }
|
|
53
|
-
})
|
|
54
|
-
|
|
55
|
-
test('多目标合并记忆:连 A 再连 B 不丢 A;同基址免 token;name 选用', async (t) => {
|
|
56
|
-
const a = await createMockRspServer()
|
|
57
|
-
const b = await createMockRspServer()
|
|
58
|
-
t.after(async () => { await a.close(); await b.close() })
|
|
59
|
-
const hostDir = tmpHost()
|
|
60
|
-
const m = new RspManager({ hostDir })
|
|
61
|
-
t.after(() => m.close())
|
|
62
|
-
await m.connect({ url: a.url, token: a.token, name: 'A' }, 's1')
|
|
63
|
-
await m.connect({ url: b.url, token: b.token, name: 'B' }, 's1')
|
|
64
|
-
const rem = m.remembered()
|
|
65
|
-
assert.deepEqual(rem.targets.map((x) => x.name).sort(), ['A', 'B'])
|
|
66
|
-
assert.equal(rem.active, 'B')
|
|
67
|
-
assert.ok(rem.targets.every((x) => !x.token.includes(a.token) && !x.token.includes(b.token)), 'remembered 令牌必须掩码')
|
|
68
|
-
// 同基址再连可省略 token(复用记忆令牌)
|
|
69
|
-
await m.connect({ url: a.url }, 's2')
|
|
70
|
-
assert.equal(m.bindings.get('s2').name, 'A')
|
|
71
|
-
// name 选用已记住目标
|
|
72
|
-
await m.connect({ name: 'B' }, 's3')
|
|
73
|
-
assert.equal(m.bindings.get('s3').baseUrl, b.url)
|
|
74
|
-
// 未知别名 → no_target
|
|
75
|
-
await assert.rejects(() => m.connect({ name: 'nope' }, 's4'), (e) => e.code === 'no_target')
|
|
76
|
-
// 新基址无 token → bad_event
|
|
77
|
-
await assert.rejects(() => m.connect({ url: 'http://127.0.0.1:1' }, 's4'), (e) => e.code === 'bad_event')
|
|
78
|
-
// 落盘 v2 且含会话绑定
|
|
79
|
-
const disk = JSON.parse(readFileSync(path.join(hostDir, 'targets.json'), 'utf8'))
|
|
80
|
-
assert.equal(disk.version, VAULT_VERSION)
|
|
81
|
-
assert.equal(disk.sessions.s1, 'B')
|
|
82
|
-
assert.equal(disk.sessions.s2, 'A')
|
|
83
|
-
assert.equal(disk.sessions.s3, 'B')
|
|
84
|
-
})
|
|
85
|
-
|
|
86
|
-
test('会话隔离:两个会话各自连同一被控端,互不抢画面;断一个不影响另一个', async (t) => {
|
|
87
|
-
const mock = await createMockRspServer()
|
|
88
|
-
t.after(() => mock.close())
|
|
89
|
-
const m = new RspManager({ hostDir: tmpHost() })
|
|
90
|
-
t.after(() => m.close())
|
|
91
|
-
await m.connect({ url: mock.url, token: mock.token, name: 'mac' }, 'sess-A')
|
|
92
|
-
await m.connect({ url: mock.url, token: mock.token, name: 'mac' }, 'sess-B')
|
|
93
|
-
const ca = m.clients.get('sess-A')
|
|
94
|
-
const cb = m.clients.get('sess-B')
|
|
95
|
-
assert.ok(ca && cb && ca !== cb, '每会话独立 client')
|
|
96
|
-
await waitFor(() => ca.lastFrame && cb.lastFrame)
|
|
97
|
-
await m.disconnect({}, 'sess-A')
|
|
98
|
-
assert.equal(m.clients.has('sess-A'), false)
|
|
99
|
-
assert.ok(m.clients.get('sess-B') && !m.clients.get('sess-B').closed, 'B 不受 A 断开影响')
|
|
100
|
-
assert.equal(m.status('sess-B').connected, true)
|
|
101
|
-
// A 显式断开后不懒自动重连(尊重断开意图)
|
|
102
|
-
await assert.rejects(() => m.requireClient('sess-A'), (e) => e.code === 'not_connected')
|
|
103
|
-
// B 仍可直接取用
|
|
104
|
-
assert.equal(await m.requireClient('sess-B'), cb)
|
|
105
|
-
})
|
|
106
|
-
|
|
107
|
-
test('跨进程恢复:新 manager 按会话绑定懒自动重连(登录态注入语义)', async (t) => {
|
|
108
|
-
const mock = await createMockRspServer()
|
|
109
|
-
t.after(() => mock.close())
|
|
110
|
-
const hostDir = tmpHost()
|
|
111
|
-
const m1 = new RspManager({ hostDir })
|
|
112
|
-
await m1.connect({ url: mock.url, token: mock.token, name: 'mac' }, 'sess-X')
|
|
113
|
-
await m1.close()
|
|
114
|
-
const m2 = new RspManager({ hostDir })
|
|
115
|
-
t.after(() => m2.close())
|
|
116
|
-
assert.equal(m2.clients.size, 0, '新进程无活连接')
|
|
117
|
-
assert.equal(m2.status('sess-X').configured, true)
|
|
118
|
-
const c = await m2.requireClient('sess-X') // 首次动作懒重连
|
|
119
|
-
assert.ok(c && !c.closed)
|
|
120
|
-
await waitFor(() => c.lastFrame)
|
|
121
|
-
assert.equal(m2.bindings.get('sess-X').name, 'mac')
|
|
122
|
-
// 无绑定会话回落 vault.active
|
|
123
|
-
const c2 = await m2.requireClient('sess-unknown')
|
|
124
|
-
assert.ok(c2 && !c2.closed)
|
|
125
|
-
})
|
|
126
|
-
|
|
127
|
-
test('forget:解除本会话绑定;目标无其它引用才删;有引用保留', async (t) => {
|
|
128
|
-
const mock = await createMockRspServer()
|
|
129
|
-
t.after(() => mock.close())
|
|
130
|
-
const hostDir = tmpHost()
|
|
131
|
-
const m = new RspManager({ hostDir })
|
|
132
|
-
t.after(() => m.close())
|
|
133
|
-
await m.connect({ url: mock.url, token: mock.token, name: 'mac' }, 's1')
|
|
134
|
-
await m.connect({ name: 'mac' }, 's2')
|
|
135
|
-
await m.disconnect({ forget: true }, 's1')
|
|
136
|
-
assert.ok(m.vault.targets.mac, 's2 仍引用 → 目标保留')
|
|
137
|
-
assert.equal(m.vault.sessions.s1, undefined)
|
|
138
|
-
await m.disconnect({ forget: true }, 's2')
|
|
139
|
-
assert.equal(m.vault.targets.mac, undefined, '无引用 → 删除')
|
|
140
|
-
const disk = JSON.parse(readFileSync(path.join(hostDir, 'targets.json'), 'utf8'))
|
|
141
|
-
assert.deepEqual(disk.targets, {})
|
|
142
|
-
})
|
|
143
|
-
|
|
144
|
-
test('persist:false 不写盘;DEFAULT_BUCKET 兜底无会话调用', async (t) => {
|
|
145
|
-
const mock = await createMockRspServer()
|
|
146
|
-
t.after(() => mock.close())
|
|
147
|
-
const hostDir = tmpHost()
|
|
148
|
-
const m = new RspManager({ hostDir })
|
|
149
|
-
t.after(() => m.close())
|
|
150
|
-
await m.connect({ url: mock.url, token: mock.token, name: 'tmp', persist: false })
|
|
151
|
-
assert.ok(!existsSync(path.join(hostDir, 'targets.json')))
|
|
152
|
-
assert.ok(m.clients.get(DEFAULT_BUCKET))
|
|
153
|
-
assert.equal(m.activeSession, DEFAULT_BUCKET)
|
|
154
|
-
assert.equal(m.client, m.clients.get(DEFAULT_BUCKET))
|
|
155
|
-
})
|
|
156
|
-
|
|
157
|
-
test('clientFor / sessions / status 的会话视图', async (t) => {
|
|
158
|
-
const mock = await createMockRspServer()
|
|
159
|
-
t.after(() => mock.close())
|
|
160
|
-
const m = new RspManager({ hostDir: tmpHost() })
|
|
161
|
-
t.after(() => m.close())
|
|
162
|
-
await m.connect({ url: mock.url, token: mock.token, name: 'mac' }, 's1')
|
|
163
|
-
await m.connect({ url: mock.url, token: mock.token, name: 'mac' }, 's2')
|
|
164
|
-
assert.equal(m.clientFor('s1'), m.clients.get('s1'))
|
|
165
|
-
assert.equal(m.clientFor(), m.clients.get(DEFAULT_BUCKET) || null, '缺省看无会话桶,与 connect/disconnect 的缺省桶一致')
|
|
166
|
-
const st0 = m.status()
|
|
167
|
-
assert.equal(st0.session, null)
|
|
168
|
-
assert.equal(st0.connected, false, '无会话桶未连接时不冒领其它会话的连接')
|
|
169
|
-
assert.equal(st0.target.name, 'mac', 'configured 回落记忆库 active')
|
|
170
|
-
const list = await waitFor(() => { const l = m.sessions(); return l.length === 2 && l.every((x) => x.connected) ? l : null })
|
|
171
|
-
assert.ok(list.every((x) => x.target === 'mac' && x.connected))
|
|
172
|
-
const st = m.status('s1')
|
|
173
|
-
assert.equal(st.session, 's1')
|
|
174
|
-
assert.equal(st.activeSession, 's2')
|
|
175
|
-
assert.equal(st.target.name, 'mac')
|
|
176
|
-
assert.ok(st.remembered.targets.length === 1)
|
|
177
|
-
})
|