@capyclaw/rsp-suite 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,66 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * 工作台 CLI 驱动(真实设备联调/演示用):经宿主 workbench 的 MCP 面调用 rsp_* 工具,
4
+ * 与 AI 原生工具面同一条路径。令牌从环境变量 RSP_TOKEN 读取,不出现在命令行参数里。
5
+ *
6
+ * 用法:
7
+ * RSP_TOKEN=xxx node scripts/drive.mjs connect http://host:8765
8
+ * node scripts/drive.mjs tool rsp_screen '{"save":true}'
9
+ * node scripts/drive.mjs tool rsp_mouse '{"action":"click","x":480,"y":270,"space":"frame"}'
10
+ * node scripts/drive.mjs api status
11
+ * 环境变量 RSP_WB 覆盖工作台基址(默认 http://127.0.0.1:8046/capyclaw/rsp)
12
+ */
13
+ import { mkdirSync, writeFileSync } from 'node:fs'
14
+ import path from 'node:path'
15
+
16
+ const WB = process.env.RSP_WB || 'http://127.0.0.1:8046/capyclaw/rsp'
17
+ const TOKEN = process.env.RSP_TOKEN || ''
18
+ const cmd = process.argv[2]
19
+
20
+ async function api(pathname, body) {
21
+ const opt = body === undefined ? {} : { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) }
22
+ const r = await fetch(WB + pathname, opt)
23
+ const j = await r.json().catch(() => null)
24
+ return { status: r.status, body: j }
25
+ }
26
+
27
+ let mcpId = 0
28
+ async function tool(name, args) {
29
+ const r = await fetch(WB + '/mcp', {
30
+ method: 'POST', headers: { 'content-type': 'application/json' },
31
+ body: JSON.stringify({ jsonrpc: '2.0', id: ++mcpId, method: 'tools/call', params: { name, arguments: args } }),
32
+ })
33
+ const j = await r.json().catch(() => null)
34
+ const result = j?.result ?? j
35
+ // 图片内容落盘,只回路径与文本,避免把 base64 喷到终端
36
+ for (const c of result?.content || []) {
37
+ if (c.type === 'image' && c.data) {
38
+ const dir = path.join(process.cwd(), '.frames')
39
+ mkdirSync(dir, { recursive: true })
40
+ const f = path.join(dir, `frame-${Date.now()}.jpg`)
41
+ writeFileSync(f, Buffer.from(c.data, 'base64'))
42
+ c.file = f
43
+ delete c.data
44
+ }
45
+ }
46
+ return result
47
+ }
48
+
49
+ if (cmd === 'connect') {
50
+ const url = process.argv[3]
51
+ const { status, body } = await api('/api/connect', { url, token: TOKEN, name: process.argv[4] || 'real', persist: true })
52
+ console.log(JSON.stringify({ status, info: body?.info, error: body?.error }))
53
+ } else if (cmd === 'api') {
54
+ const { status, body } = await api('/api/' + (process.argv[3] || 'status'))
55
+ console.log(JSON.stringify({ status, body }))
56
+ } else if (cmd === 'tool') {
57
+ const name = process.argv[3]
58
+ // 参数优先取 argv;PowerShell 会吞引号,故支持 RSP_ARGS 环境变量传 JSON
59
+ const raw = process.argv[4] || process.env.RSP_ARGS || '{}'
60
+ const args = JSON.parse(raw)
61
+ const res = await tool(name, args)
62
+ console.log(JSON.stringify(res))
63
+ } else {
64
+ console.log('usage: drive.mjs connect <url> | tool <name> <json> | api <endpoint>')
65
+ process.exit(1)
66
+ }
@@ -0,0 +1,218 @@
1
+ /**
2
+ * RSP/1 客户端测试:纯函数单元 + 对 mock 被控端的协议集成。
3
+ * 覆盖:hello/帧、seq/ack、bad_event 保持连接、401/4001 鉴权、403 禁用、
4
+ * POST 降级、§5.5 断线补 up、screen 退避重连、move 限速、releaseAll。
5
+ */
6
+ import { test } from 'node:test'
7
+ import assert from 'node:assert/strict'
8
+ import { RspClient, jpegSize, splitText, maskToken, normalizeBase, PROTOCOL } from '../lib/client.mjs'
9
+ import { createMockRspServer, makeJpeg } from './mock-server.mjs'
10
+
11
+ async function waitFor(fn, timeout = 4000, step = 20) {
12
+ const end = Date.now() + timeout
13
+ while (Date.now() < end) {
14
+ const v = await fn()
15
+ if (v) return v
16
+ await new Promise((r) => setTimeout(r, step))
17
+ }
18
+ throw new Error('waitFor 超时')
19
+ }
20
+
21
+ // ---------- 纯函数 ----------
22
+
23
+ test('jpegSize 解析 SOF0 尺寸', () => {
24
+ assert.deepEqual(jpegSize(makeJpeg(960, 540)), { width: 960, height: 540 })
25
+ assert.deepEqual(jpegSize(makeJpeg(1920, 1080)), { width: 1920, height: 1080 })
26
+ assert.equal(jpegSize(null), null)
27
+ assert.equal(jpegSize(Buffer.from([1, 2, 3])), null)
28
+ assert.equal(jpegSize(Buffer.from([0xff, 0xd8, 0xff, 0xd9])), null) // 无 SOF
29
+ })
30
+
31
+ test('splitText 按 4096 UTF-16 码元分片且不切代理对', () => {
32
+ assert.deepEqual(splitText('你好'), ['你好'])
33
+ const long = 'a'.repeat(9000)
34
+ const chunks = splitText(long)
35
+ assert.deepEqual(chunks.map((c) => c.length), [4096, 4096, 808])
36
+ assert.equal(chunks.join(''), long)
37
+ // 高位代理恰好落在切口:回退一格,emoji 完整保留到下一片
38
+ const s = 'a'.repeat(4095) + '😀' + 'b'.repeat(100)
39
+ const cs = splitText(s)
40
+ assert.equal(cs[0].length, 4095)
41
+ assert.ok(cs[1].startsWith('😀'))
42
+ assert.equal(cs.join(''), s)
43
+ for (const c of cs) assert.ok(c.length <= 4096)
44
+ })
45
+
46
+ test('normalizeBase 归一化基址', () => {
47
+ assert.equal(normalizeBase({ url: 'http://192.168.1.5:8765/' }), 'http://192.168.1.5:8765')
48
+ assert.equal(normalizeBase({ url: 'https://example.com/rsp/' }), 'https://example.com/rsp')
49
+ assert.equal(normalizeBase({ host: '10.0.0.2' }), 'http://10.0.0.2:8765')
50
+ assert.equal(normalizeBase({ host: '10.0.0.2', port: 9000 }), 'http://10.0.0.2:9000')
51
+ assert.equal(normalizeBase({ host: '::1' }), 'http://[::1]:8765')
52
+ assert.throws(() => normalizeBase({ url: 'ftp://x' }), (e) => e.code === 'bad_event')
53
+ assert.throws(() => normalizeBase({}), (e) => e.code === 'bad_event')
54
+ })
55
+
56
+ test('maskToken 掩码', () => {
57
+ assert.equal(maskToken(''), null)
58
+ assert.equal(maskToken('short'), '****')
59
+ assert.equal(maskToken('abcdefghijklmnop'), 'abcd…mnop')
60
+ })
61
+
62
+ // ---------- 协议集成 ----------
63
+
64
+ async function setup(t, opts = {}) {
65
+ const mock = await createMockRspServer(opts)
66
+ const client = new RspClient({ baseUrl: mock.url, token: mock.token })
67
+ t.after(async () => { try { await client.disconnect() } catch { /* ignore */ } await mock.close() })
68
+ return { mock, client }
69
+ }
70
+
71
+ test('connect:校验 rsp/1、收 hello 与 JPEG 帧、status 尺寸', async (t) => {
72
+ const { mock, client } = await setup(t)
73
+ const info = await client.connect()
74
+ assert.equal(info.protocol, PROTOCOL)
75
+ assert.equal(info.screen.format, 'jpeg')
76
+ await waitFor(() => client.hello && client.lastFrame)
77
+ const st = client.status()
78
+ assert.equal(st.connected, true)
79
+ assert.deepEqual(st.logical, { width: 1920, height: 1080 })
80
+ assert.equal(st.lastFrame.width, 960)
81
+ assert.equal(st.lastFrame.height, 540)
82
+ assert.ok(st.frameCount > 0)
83
+ assert.equal(st.token, maskToken(mock.token))
84
+ assert.ok(client.lastFrame.bytes.length > 4)
85
+ })
86
+
87
+ test('sendEvent:mouse click 走 control.ws 并收 ack', async (t) => {
88
+ const { mock, client } = await setup(t)
89
+ await client.connect()
90
+ const r = await client.sendEvent({ cmd: 'mouse', action: 'click', x: 960, y: 540, clicks: 2 })
91
+ assert.equal(r.ok, true)
92
+ assert.equal(r.via, 'ws')
93
+ assert.equal(r.seq, 1)
94
+ const ev = mock.events.find((e) => e.cmd === 'mouse')
95
+ assert.equal(ev.action, 'click')
96
+ assert.equal(ev.x, 960); assert.equal(ev.y, 540); assert.equal(ev.clicks, 2)
97
+ assert.equal(ev.seq, 1)
98
+ })
99
+
100
+ test('bad_event:非法键位报错但连接保持', async (t) => {
101
+ const { mock, client } = await setup(t)
102
+ await client.connect()
103
+ await assert.rejects(
104
+ () => client.sendEvent({ cmd: 'key', action: 'down', code: 'Foo' }),
105
+ (e) => e.code === 'bad_event' && /Foo/.test(e.message),
106
+ )
107
+ assert.equal(client.controlState, 'open')
108
+ const r = await client.sendEvent({ cmd: 'key', action: 'down', code: 'KeyA' })
109
+ assert.equal(r.ok, true)
110
+ await client.sendEvent({ cmd: 'key', action: 'up', code: 'KeyA' })
111
+ assert.deepEqual(client.status().pressedKeys, [])
112
+ })
113
+
114
+ test('错误令牌:/info 401 → unauthorized', async (t) => {
115
+ const mock = await createMockRspServer()
116
+ t.after(() => mock.close())
117
+ const client = new RspClient({ baseUrl: mock.url, token: 'wrong-token' })
118
+ await assert.rejects(() => client.connect(), (e) => e.code === 'unauthorized')
119
+ })
120
+
121
+ test('操控禁用:画面可连,注入 → forbidden', async (t) => {
122
+ const { client } = await setup(t, { controlEnabled: false })
123
+ const info = await client.connect()
124
+ assert.equal(info.control.enabled, false)
125
+ await waitFor(() => client.lastFrame)
126
+ await assert.rejects(
127
+ () => client.sendEvent({ cmd: 'mouse', action: 'click', x: 1, y: 1 }),
128
+ (e) => e.code === 'forbidden',
129
+ )
130
+ })
131
+
132
+ test('control.ws 不可用:降级 POST /control', async (t) => {
133
+ const { mock, client } = await setup(t, { controlWs: false })
134
+ await client.connect()
135
+ assert.equal(client.controlMode, 'post')
136
+ const r = await client.sendEvent({ cmd: 'mouse', action: 'click', x: 100, y: 200 })
137
+ assert.equal(r.ok, true)
138
+ assert.equal(r.via, 'post')
139
+ const ev = mock.events.find((e) => e.cmd === 'mouse')
140
+ assert.equal(ev.x, 100); assert.equal(ev.y, 200)
141
+ assert.equal(ev.seq, undefined) // POST 不带 seq
142
+ })
143
+
144
+ test('§5.5 防卡键:control.ws 异常断开,被控端自动补 up', async (t) => {
145
+ const { mock, client } = await setup(t)
146
+ await client.connect()
147
+ await client.sendEvent({ cmd: 'key', action: 'down', code: 'KeyA' })
148
+ await client.sendEvent({ cmd: 'mouse', action: 'down', x: 10, y: 10, button: 'left' })
149
+ assert.deepEqual(client.status().pressedKeys, ['KeyA'])
150
+ assert.deepEqual(client.status().pressedButtons, ['left'])
151
+ client.controlWs.terminate() // 模拟控制端掉线(不走 releaseAll)
152
+ await waitFor(() => mock.releasedOnClose.length >= 2)
153
+ const ups = mock.releasedOnClose
154
+ assert.ok(ups.some((e) => e.cmd === 'key' && e.action === 'up' && e.code === 'KeyA'))
155
+ assert.ok(ups.some((e) => e.cmd === 'mouse' && e.action === 'up' && e.button === 'left'))
156
+ })
157
+
158
+ test('disconnect 主动补发按下态的 up(releaseAll)', async (t) => {
159
+ const { mock, client } = await setup(t)
160
+ await client.connect()
161
+ await client.sendEvent({ cmd: 'key', action: 'down', code: 'ShiftLeft' })
162
+ await client.disconnect()
163
+ await waitFor(() => mock.events.some((e) => e.cmd === 'key' && e.action === 'up' && e.code === 'ShiftLeft'))
164
+ })
165
+
166
+ test('screen.ws 断开后退避重连', async (t) => {
167
+ const { client } = await setup(t)
168
+ await client.connect()
169
+ await waitFor(() => client.lastFrame)
170
+ const before = client.frameCount
171
+ client.screenWs.terminate()
172
+ await waitFor(() => client.screenState === 'reconnecting' || client.screenState === 'connecting')
173
+ await waitFor(() => client.screenState === 'open', 5000)
174
+ await waitFor(() => client.frameCount > before, 3000)
175
+ })
176
+
177
+ test('WS 关闭码 4001 → auth-error,注入拒绝', async (t) => {
178
+ const mock = await createMockRspServer()
179
+ t.after(() => mock.close())
180
+ const info = { protocol: 'rsp/1', screen: { width: 1920, height: 1080, format: 'jpeg' }, control: { enabled: true }, engine: { ready: true } }
181
+ const client = new RspClient({
182
+ baseUrl: mock.url, token: 'wrong-token',
183
+ fetchImpl: async () => ({ ok: true, status: 200, json: async () => info }), // /info 假装通过,WS 真鉴权
184
+ })
185
+ t.after(async () => { try { await client.disconnect() } catch { /* ignore */ } })
186
+ let authErr = null
187
+ client.on('auth-error', (d) => { authErr = d })
188
+ await client.connect()
189
+ await waitFor(() => authErr)
190
+ assert.equal(client.screenState, 'auth-error')
191
+ await assert.rejects(() => client.sendEvent({ cmd: 'mouse', action: 'click', x: 1, y: 1 }), (e) => e.code === 'unauthorized')
192
+ })
193
+
194
+ test('move 限速 ≤60/s(间隔 ≥16ms)', async (t) => {
195
+ const { client } = await setup(t)
196
+ await client.connect()
197
+ const t0 = Date.now()
198
+ for (let i = 0; i < 3; i++) await client.sendEvent({ cmd: 'mouse', action: 'move', x: i, y: i })
199
+ assert.ok(Date.now() - t0 >= 25, '3 次 move 应至少间隔 2×16ms')
200
+ })
201
+
202
+ test('waitFrame 等到新帧', async (t) => {
203
+ const { client } = await setup(t)
204
+ await client.connect()
205
+ await waitFor(() => client.lastFrame)
206
+ const since = Date.now()
207
+ const f = await client.waitFrame(since, 2000)
208
+ assert.ok(f.at >= since)
209
+ })
210
+
211
+ test('超大事件 → too_large(客户端侧拦截)', async (t) => {
212
+ const { client } = await setup(t)
213
+ await client.connect()
214
+ await assert.rejects(
215
+ () => client.sendEvent({ cmd: 'text', text: 'x'.repeat(70000) }),
216
+ (e) => e.code === 'too_large',
217
+ )
218
+ })
@@ -0,0 +1,49 @@
1
+ // 回归:rsp_screen 抓帧落盘必须有界(磁盘版 session-keeper 事故模式),
2
+ // 且查看器 innerHTML 插值必须转义(目标名/基址来自调用者可控的 rsp_connect 参数)。
3
+ import test from 'node:test'
4
+ import assert from 'node:assert/strict'
5
+ import { mkdtempSync, writeFileSync, readdirSync, readFileSync } from 'node:fs'
6
+ import { tmpdir } from 'node:os'
7
+ import path from 'node:path'
8
+ import { fileURLToPath } from 'node:url'
9
+ import { pruneFrames } from '../lib/tools.mjs'
10
+
11
+ const here = path.dirname(fileURLToPath(import.meta.url))
12
+
13
+ test('pruneFrames 只保留最近 40 张抓帧', () => {
14
+ const dir = mkdtempSync(path.join(tmpdir(), 'rsp-frames-'))
15
+ // 60 张帧:名字里的时间戳单调递增,sort() 即时间序
16
+ for (let i = 0; i < 60; i++) writeFileSync(path.join(dir, `frame-${1700000000000 + i}.jpg`), 'x')
17
+ // 混入非帧文件:不应被误删
18
+ writeFileSync(path.join(dir, 'viewer-live.png'), 'keep')
19
+ writeFileSync(path.join(dir, 'notes.txt'), 'keep')
20
+ pruneFrames(dir)
21
+ const left = readdirSync(dir).filter((n) => /^frame-\d+\.jpg$/.test(n)).sort()
22
+ assert.equal(left.length, 40)
23
+ assert.equal(left[0], 'frame-1700000000020.jpg') // 最旧 20 张被删
24
+ assert.equal(left[39], 'frame-1700000000059.jpg')
25
+ assert.ok(readdirSync(dir).includes('viewer-live.png'))
26
+ assert.ok(readdirSync(dir).includes('notes.txt'))
27
+ })
28
+
29
+ test('pruneFrames 不足上限时一张不删', () => {
30
+ const dir = mkdtempSync(path.join(tmpdir(), 'rsp-frames-'))
31
+ for (let i = 0; i < 5; i++) writeFileSync(path.join(dir, `frame-${1700000000000 + i}.jpg`), 'x')
32
+ pruneFrames(dir)
33
+ assert.equal(readdirSync(dir).filter((n) => n.startsWith('frame-')).length, 5)
34
+ })
35
+
36
+ test('pruneFrames 目录不存在时静默返回', () => {
37
+ assert.doesNotThrow(() => pruneFrames(path.join(tmpdir(), 'rsp-frames-definitely-missing-xyz')))
38
+ })
39
+
40
+ test('查看器 innerHTML 插值全部经 esc 转义', () => {
41
+ const html = readFileSync(path.join(here, '..', 'ui', 'index.html'), 'utf8')
42
+ assert.match(html, /function esc\(s\)/)
43
+ // fillSelect 的 label 与 renderStatus 的 k/v 都必须包 esc(...)
44
+ assert.match(html, /sel\.innerHTML = options\.map\(\(\[v, label\]\) => .*esc\(label\)/)
45
+ assert.match(html, /\$\('status'\)\.innerHTML = rows\.map\(\(\[k, v\]\) => .*esc\(k\).*esc\(v\)/)
46
+ // 不允许再出现未转义的裸 label / 裸 v 插值
47
+ assert.ok(!/'>' \+ label \+ '<\/option>'/.test(html))
48
+ assert.ok(!/'<span class="v">' \+ v \+ '<\/span>'/.test(html))
49
+ })
@@ -0,0 +1,101 @@
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
+ })
@@ -0,0 +1,29 @@
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)
@@ -0,0 +1,109 @@
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)