dsh-copilot-vision 0.0.0-stage → 1.0.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.
- package/LICENSE +21 -0
- package/README.md +90 -2
- package/THIRD_PARTY_LICENSES/dsh-dolphin-security-MIT.txt +21 -0
- package/THIRD_PARTY_LICENSES/dsh-web-Apache-2.0.txt +202 -0
- package/THIRD_PARTY_NOTICES.md +149 -0
- package/cordis.patch.yml +5 -0
- package/package.json +52 -4
- package/src/actions.js +181 -0
- package/src/audit.js +40 -0
- package/src/auth.js +200 -0
- package/src/coords.js +43 -0
- package/src/diff.js +199 -0
- package/src/hotkey.js +61 -0
- package/src/index.js +64 -0
- package/src/paths.js +41 -0
- package/src/plugin.js +648 -0
- package/src/render.js +132 -0
- package/src/robot-ts.js +20 -0
- package/src/shot-index.js +149 -0
- package/src/vp-ssh-core.js +1328 -0
- package/src/wait.js +156 -0
package/src/actions.js
ADDED
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
// Vision-Pilot 工具的业务逻辑(宿主无关)。
|
|
2
|
+
// 本文件只依赖 robot-ts 与 node 内置模块,不 import @deepseek-ai/dsh-tools / cordis,
|
|
3
|
+
// 因此 test-mvp.mjs 可以直接调用来做回归,不需要 DSH 宿主。
|
|
4
|
+
|
|
5
|
+
import { mkdir } from 'node:fs/promises'
|
|
6
|
+
import { join } from 'node:path'
|
|
7
|
+
import { physicalToLogical, relativeToPhysical } from './coords.js'
|
|
8
|
+
import { loadRobotTs } from './robot-ts.js'
|
|
9
|
+
import { checkCanClick, consumeOnce, getStatus } from './auth.js'
|
|
10
|
+
import { logState } from './audit.js'
|
|
11
|
+
import { resolveShotsDir } from './paths.js'
|
|
12
|
+
import { get, nextShotId, record } from './shot-index.js'
|
|
13
|
+
|
|
14
|
+
// 目录解析集中在 src/paths.js(截图与审计日志共用同一个目录)。
|
|
15
|
+
// 之前用相对 src/ 的 .vp-shots,tarball 安装后会落进
|
|
16
|
+
// node_modules/vision-pilot/.vp-shots —— 用户找不到,重装即丢。
|
|
17
|
+
|
|
18
|
+
/** 主屏全屏截图,落盘为 PNG。每次调用新建会话,用完即 dispose(MVP 不做会话复用)。 */
|
|
19
|
+
export async function screenshotAction() {
|
|
20
|
+
const { Session } = loadRobotTs()
|
|
21
|
+
const session = await Session.create()
|
|
22
|
+
try {
|
|
23
|
+
if (!session.capabilities.canCaptureScreen) {
|
|
24
|
+
throw new Error('当前宿主环境不支持屏幕捕获(canCaptureScreen=false)')
|
|
25
|
+
}
|
|
26
|
+
const primary = await session.screen.primaryMonitor()
|
|
27
|
+
const img = await session.screen.captureMonitor(primary.id)
|
|
28
|
+
|
|
29
|
+
const dir = resolveShotsDir()
|
|
30
|
+
await mkdir(dir, { recursive: true })
|
|
31
|
+
const stamp = new Date().toISOString().replace(/[:.]/g, '-')
|
|
32
|
+
const path = join(dir, `vp-shot-${stamp}.png`)
|
|
33
|
+
await img.savePng(path)
|
|
34
|
+
|
|
35
|
+
const { width, height } = primary.physicalBounds.size
|
|
36
|
+
const shotId = nextShotId()
|
|
37
|
+
record(shotId, {
|
|
38
|
+
path,
|
|
39
|
+
width: img.width,
|
|
40
|
+
height: img.height,
|
|
41
|
+
scaleFactor: primary.scaleFactor,
|
|
42
|
+
physicalBounds: { width, height },
|
|
43
|
+
})
|
|
44
|
+
return {
|
|
45
|
+
shotId,
|
|
46
|
+
path,
|
|
47
|
+
width: img.width,
|
|
48
|
+
height: img.height,
|
|
49
|
+
scaleFactor: primary.scaleFactor,
|
|
50
|
+
physicalBounds: { width, height },
|
|
51
|
+
}
|
|
52
|
+
} finally {
|
|
53
|
+
await session.dispose()
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** 按物理像素坐标点击一次。x/y 来自 vp_screenshot 的图像坐标系;授权闸门先于坐标校验。 */
|
|
58
|
+
export async function clickAction(args = {}) {
|
|
59
|
+
const { x, y } = args
|
|
60
|
+
const gate = checkCanClick()
|
|
61
|
+
if (!gate.allowed) {
|
|
62
|
+
// 闸门在坐标校验之前,所以这里的 x/y 还没验过;只在确认是数值时才写进审计,
|
|
63
|
+
// 避免把任意入参当成坐标记录。logical 此刻拿不到 scaleFactor(不为此新建会话),故省略。
|
|
64
|
+
const state = getStatus().state
|
|
65
|
+
logState('clickDenied', 'tool', state, state, {
|
|
66
|
+
reason: gate.reason,
|
|
67
|
+
...(Number.isFinite(x) && Number.isFinite(y) ? { physical: { x, y } } : {}),
|
|
68
|
+
})
|
|
69
|
+
throw new Error(`vp_click 未获授权:${gate.reason}。可调用 vp_request_auth 请求,或按 Shift+Space 进入持续授权。`)
|
|
70
|
+
}
|
|
71
|
+
const { Session, MouseButton } = loadRobotTs()
|
|
72
|
+
const buttons = {
|
|
73
|
+
left: MouseButton.Left,
|
|
74
|
+
right: MouseButton.Right,
|
|
75
|
+
middle: MouseButton.Middle,
|
|
76
|
+
}
|
|
77
|
+
const { button = 'left' } = args
|
|
78
|
+
|
|
79
|
+
if (!Number.isFinite(x) || !Number.isFinite(y)) {
|
|
80
|
+
throw new Error(`vp_click: x/y 必须是有限数字,收到 x=${x}, y=${y}`)
|
|
81
|
+
}
|
|
82
|
+
if (x < 0 || y < 0) {
|
|
83
|
+
throw new Error(`vp_click: 坐标不能为负数,收到 x=${x}, y=${y}`)
|
|
84
|
+
}
|
|
85
|
+
if (!Object.hasOwn(buttons, button)) {
|
|
86
|
+
throw new Error(`vp_click: button 必须是 left|right|middle,收到 ${button}`)
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
const session = await Session.create()
|
|
90
|
+
try {
|
|
91
|
+
if (!session.capabilities.canInjectMouse) {
|
|
92
|
+
throw new Error('当前宿主环境不支持鼠标注入(canInjectMouse=false)')
|
|
93
|
+
}
|
|
94
|
+
const primary = await session.screen.primaryMonitor()
|
|
95
|
+
const { width, height } = primary.physicalBounds.size
|
|
96
|
+
|
|
97
|
+
if (x >= width || y >= height) {
|
|
98
|
+
throw new Error(
|
|
99
|
+
`vp_click: 物理坐标 (${x}, ${y}) 超出主屏范围 ` +
|
|
100
|
+
`0 <= x < ${width}, 0 <= y < ${height}(越界不会被静默夹到边界)`,
|
|
101
|
+
)
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
const logical = physicalToLogical({ x, y }, primary.scaleFactor)
|
|
105
|
+
// 参数与越界都通过后才消费放行,避免一次失败的调用浪费单次授权。
|
|
106
|
+
const consumed = consumeOnce()
|
|
107
|
+
if (!consumed.allowed) {
|
|
108
|
+
throw new Error(`vp_click 未获授权:${consumed.reason}。可调用 vp_request_auth 请求,或按 Shift+Space 进入持续授权。`)
|
|
109
|
+
}
|
|
110
|
+
await session.mouse.move(logical)
|
|
111
|
+
await session.mouse.click(buttons[button])
|
|
112
|
+
|
|
113
|
+
return {
|
|
114
|
+
clicked: true,
|
|
115
|
+
physical: { x, y },
|
|
116
|
+
logical,
|
|
117
|
+
button,
|
|
118
|
+
}
|
|
119
|
+
} finally {
|
|
120
|
+
await session.dispose()
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* 把「shotId + 1-based region 序号 + 相对百分比」解析成全局物理坐标。
|
|
126
|
+
* 只查索引与做算数,不碰屏幕、不碰授权,所以可以被测试直接调用。
|
|
127
|
+
*/
|
|
128
|
+
export function resolveRelativeTarget({ shotId, index, xPercent, yPercent }) {
|
|
129
|
+
if (!Number.isInteger(shotId)) {
|
|
130
|
+
throw new Error(`vp_click_relative: shotId 必须是整数,收到 ${shotId}`)
|
|
131
|
+
}
|
|
132
|
+
if (!Number.isInteger(index) || index < 1) {
|
|
133
|
+
throw new Error(`vp_click_relative: index 必须是 >=1 的整数(1-based),收到 ${index}`)
|
|
134
|
+
}
|
|
135
|
+
const meta = get(shotId)
|
|
136
|
+
if (meta === undefined) {
|
|
137
|
+
throw new Error(`vp_click_relative: shotId ${shotId} 不存在,可先用 vp_screenshot 或 vp_screenshot_diff 生成`)
|
|
138
|
+
}
|
|
139
|
+
if (!Array.isArray(meta.regions) || meta.regions.length === 0) {
|
|
140
|
+
throw new Error(
|
|
141
|
+
`vp_click_relative: shotId ${shotId} 没有差分区域;只有 vp_screenshot_diff / vp_wait_change ` +
|
|
142
|
+
'产出的 currentShotId 才能相对点击(普通 vp_screenshot 没有 region)',
|
|
143
|
+
)
|
|
144
|
+
}
|
|
145
|
+
if (index > meta.regions.length) {
|
|
146
|
+
throw new Error(
|
|
147
|
+
`vp_click_relative: index ${index} 超出范围,shotId ${shotId} 只有 ${meta.regions.length} 个区域(1..${meta.regions.length})`,
|
|
148
|
+
)
|
|
149
|
+
}
|
|
150
|
+
const bbox = meta.regions[index - 1].bbox
|
|
151
|
+
return { bbox, physical: relativeToPhysical(bbox, xPercent, yPercent) }
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* 在差分区域内部按相对位置点击。授权闸门与 vp_click 保持同一顺序:
|
|
156
|
+
* 授权 → 参数合法性 → 越界 → 消费,所以未授权时不会读索引、不会新建 robot-ts 会话。
|
|
157
|
+
*/
|
|
158
|
+
export async function clickRelativeAction(args = {}) {
|
|
159
|
+
const gate = checkCanClick()
|
|
160
|
+
if (!gate.allowed) {
|
|
161
|
+
const state = getStatus().state
|
|
162
|
+
logState('clickDenied', 'tool', state, state, { reason: gate.reason, tool: 'vp_click_relative' })
|
|
163
|
+
throw new Error(
|
|
164
|
+
`vp_click_relative 未获授权:${gate.reason}。可调用 vp_request_auth 请求,或按 Shift+Space 进入持续授权。`,
|
|
165
|
+
)
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
const { shotId, index, xPercent, yPercent, button = 'left' } = args
|
|
169
|
+
const { bbox, physical } = resolveRelativeTarget({ shotId, index, xPercent, yPercent })
|
|
170
|
+
const clicked = await clickAction({ x: physical.x, y: physical.y, button })
|
|
171
|
+
return {
|
|
172
|
+
clicked: true,
|
|
173
|
+
shotId,
|
|
174
|
+
index,
|
|
175
|
+
bbox,
|
|
176
|
+
relative: { xPercent, yPercent },
|
|
177
|
+
physical: clicked.physical,
|
|
178
|
+
logical: clicked.logical,
|
|
179
|
+
button: clicked.button,
|
|
180
|
+
}
|
|
181
|
+
}
|
package/src/audit.js
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
// 授权审计日志:JSON Lines 追加写到 audit.log(与截图同目录,VP_SHOT_DIR 可覆盖)。
|
|
2
|
+
// 只记录状态机动作、动作来源与前后状态;不记录任何按键内容,也不记录坐标以外的用户输入。
|
|
3
|
+
//
|
|
4
|
+
// 同步写盘是有意的:状态机的迁移函数都是同步的,异步排队会打乱事件顺序,
|
|
5
|
+
// 而审计日志的价值恰恰在于顺序可信。单行几百字节,耗时可忽略。
|
|
6
|
+
import { appendFileSync, mkdirSync } from 'node:fs'
|
|
7
|
+
import { join } from 'node:path'
|
|
8
|
+
import { resolveShotsDir } from './paths.js'
|
|
9
|
+
|
|
10
|
+
// 状态机会记录的动作集合(回归测试据此校验,不要在这里放实现分支)。
|
|
11
|
+
export const AUDIT_ACTIONS = [
|
|
12
|
+
'requestAuth',
|
|
13
|
+
'confirmPending',
|
|
14
|
+
'cancelPending',
|
|
15
|
+
'togglePersistent',
|
|
16
|
+
'consumeOnce',
|
|
17
|
+
'clickDenied',
|
|
18
|
+
]
|
|
19
|
+
|
|
20
|
+
export function auditLogPath() {
|
|
21
|
+
return join(resolveShotsDir(), 'audit.log')
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** 追加一条动作记录。字段固定为 timestamp/action/source/previousState/newState/extra?。 */
|
|
25
|
+
export function logState(action, source, previousState, newState, extra) {
|
|
26
|
+
const entry = {
|
|
27
|
+
timestamp: new Date().toISOString(),
|
|
28
|
+
action,
|
|
29
|
+
source,
|
|
30
|
+
previousState,
|
|
31
|
+
newState,
|
|
32
|
+
...(extra !== undefined ? { extra } : {}),
|
|
33
|
+
}
|
|
34
|
+
try {
|
|
35
|
+
mkdirSync(resolveShotsDir(), { recursive: true })
|
|
36
|
+
appendFileSync(auditLogPath(), `${JSON.stringify(entry)}\n`, 'utf8')
|
|
37
|
+
} catch {
|
|
38
|
+
/* 尽力而为:审计缺失是事后追溯能力的损失,不是放权的理由。 */
|
|
39
|
+
}
|
|
40
|
+
}
|
package/src/auth.js
ADDED
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
// Vision-Pilot 授权状态机(宿主无关,纯内存单例)。
|
|
2
|
+
//
|
|
3
|
+
// 原则:授权状态只由人的明确动作改变,不由时钟改变。
|
|
4
|
+
// 因此本文件没有任何到期判断,也不返回 remainingMs —— persistent 一经进入就一直有效,
|
|
5
|
+
// 直到用户再次按 Shift+Space 撤销。
|
|
6
|
+
//
|
|
7
|
+
// 五种 state:
|
|
8
|
+
// unauthorized 未授权
|
|
9
|
+
// pending-once 已请求单次授权、等待人类确认(带 pendingRequest)
|
|
10
|
+
// authorized-once 已确认、等待下一次点击消费(无 pendingRequest)
|
|
11
|
+
// pending-persistent 已请求持续授权、等待人类确认
|
|
12
|
+
// persistent 持续授权中,无到期
|
|
13
|
+
//
|
|
14
|
+
// 分工:checkCanClick() 只看是否放行、不改变状态;consumeOnce() 才真正消费
|
|
15
|
+
// authorized-once。因此坐标越界等失败路径不会浪费一次单次授权。
|
|
16
|
+
//
|
|
17
|
+
// 每次动作(含被拒绝的点击)都会追加一条审计记录,见 src/audit.js。
|
|
18
|
+
//
|
|
19
|
+
// 竞态约定(P0 修复):pendingRequest 的生命周期绑一个 AbortController。任何清空 pending 的
|
|
20
|
+
// 动作(热键接管/撤销、cancelPending)都必须 abort 它,让调用方那侧「还在等人点卡片」的
|
|
21
|
+
// promise 立刻收到 AUTH_CANCELLED 并正常返回,而不是等那个答案迟到后撞进 confirmPending()。
|
|
22
|
+
// confirmPending 只认自己那一次的 requestId:对不上就是迟到的答案,安全丢弃。
|
|
23
|
+
|
|
24
|
+
import { logState } from './audit.js'
|
|
25
|
+
|
|
26
|
+
const state = {
|
|
27
|
+
persistent: false,
|
|
28
|
+
onceGranted: false,
|
|
29
|
+
/** @type {{requestId: string, mode: 'once'|'persistent', requestedAt: number, controller: AbortController} | null} */
|
|
30
|
+
pendingRequest: null,
|
|
31
|
+
requestSeq: 0,
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** 当前授权状态(只读快照,不含内部的 AbortController)。 */
|
|
35
|
+
export function getStatus() {
|
|
36
|
+
if (state.persistent) {
|
|
37
|
+
return { state: 'persistent' }
|
|
38
|
+
}
|
|
39
|
+
if (state.pendingRequest !== null) {
|
|
40
|
+
const { requestId, mode, requestedAt } = state.pendingRequest
|
|
41
|
+
return {
|
|
42
|
+
state: mode === 'once' ? 'pending-once' : 'pending-persistent',
|
|
43
|
+
pendingRequest: { requestId, mode, requestedAt },
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
if (state.onceGranted) {
|
|
47
|
+
return { state: 'authorized-once' }
|
|
48
|
+
}
|
|
49
|
+
return { state: 'unauthorized' }
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function audit(action, source, previousState, extra) {
|
|
53
|
+
logState(action, source, previousState, getStatus().state, extra)
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* 清空待确认请求并通知调用方「这次请求已经不存在了」。
|
|
58
|
+
* 必须先置空再 abort:abort 是同步派发事件的,置空后监听方读到的状态才是终态。
|
|
59
|
+
*/
|
|
60
|
+
function clearPending(reason) {
|
|
61
|
+
const pending = state.pendingRequest
|
|
62
|
+
if (pending === null) return
|
|
63
|
+
state.pendingRequest = null
|
|
64
|
+
pending.controller.abort(reason)
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* 模型侧发起授权请求。只登记 pendingRequest,不改变放行状态。
|
|
69
|
+
* 返回的 signal 会在该请求被热键接管或被取消时 abort,调用方用它把「等人回答」的
|
|
70
|
+
* promise 换成一个可取消的等待。
|
|
71
|
+
*/
|
|
72
|
+
export function requestAuth(mode) {
|
|
73
|
+
if (mode !== 'once' && mode !== 'persistent') {
|
|
74
|
+
throw new Error(`requestAuth: mode 必须是 once 或 persistent,收到 ${mode}`)
|
|
75
|
+
}
|
|
76
|
+
const previousState = getStatus().state
|
|
77
|
+
// 连着发两次请求时,前一张卡片不能变成悬空的:它一被答就撞上「已丢弃」,
|
|
78
|
+
// 所以这里同样要 abort 掉,让前一次等待立刻正常返回。
|
|
79
|
+
clearPending({ code: 'AUTH_CANCELLED', reason: '被新的授权请求顶替' })
|
|
80
|
+
state.requestSeq += 1
|
|
81
|
+
const requestId = `auth-${state.requestSeq}`
|
|
82
|
+
const controller = new AbortController()
|
|
83
|
+
state.pendingRequest = { requestId, mode, requestedAt: Date.now(), controller }
|
|
84
|
+
audit('requestAuth', 'tool', previousState, { requestId, mode })
|
|
85
|
+
return { requestId, signal: controller.signal, status: getStatus() }
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* 人侧确认:pending-once → authorized-once;pending-persistent → persistent。
|
|
90
|
+
* 只认 requestId 对应的那一次请求。对不上(已被热键接管或已取消)时不改状态、
|
|
91
|
+
* 不写审计、不抛错,返回 confirmed:false —— 迟到的答案本来就该被丢弃。
|
|
92
|
+
*/
|
|
93
|
+
export function confirmPending(requestId) {
|
|
94
|
+
const request = state.pendingRequest
|
|
95
|
+
if (request === null || request.requestId !== requestId) {
|
|
96
|
+
return { ...getStatus(), confirmed: false }
|
|
97
|
+
}
|
|
98
|
+
const previousState = getStatus().state
|
|
99
|
+
state.pendingRequest = null
|
|
100
|
+
if (request.mode === 'once') {
|
|
101
|
+
state.onceGranted = true
|
|
102
|
+
} else {
|
|
103
|
+
state.persistent = true
|
|
104
|
+
state.onceGranted = false
|
|
105
|
+
}
|
|
106
|
+
request.controller.abort({ code: 'AUTH_CANCELLED', reason: '已由人确认' })
|
|
107
|
+
audit('confirmPending', 'user-question', previousState, { mode: request.mode, requestId })
|
|
108
|
+
return { ...getStatus(), confirmed: true }
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** 取消待确认请求与单次授权。persistent 不受影响(它只能由热键撤销)。 */
|
|
112
|
+
export function cancelPending() {
|
|
113
|
+
const previousState = getStatus().state
|
|
114
|
+
state.onceGranted = false
|
|
115
|
+
clearPending({ code: 'AUTH_CANCELLED', reason: '已取消' })
|
|
116
|
+
audit('cancelPending', 'tool', previousState)
|
|
117
|
+
return getStatus()
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* 热键调用。热键优先级最高,且是 persistent 唯一的入口与出口:
|
|
122
|
+
* persistent 中 → 撤销回 unauthorized;其余状态 → 进入 persistent(清 pending/authorized-once)。
|
|
123
|
+
*
|
|
124
|
+
* 撤销分支必须全清:persistent 期间人确认的「允许一次」会置 onceGranted,而 persistent 下的点击
|
|
125
|
+
* 走 persistent 放行分支、不消费它。若撤销时不清 onceGranted,撤销后状态就成了 authorized-once,
|
|
126
|
+
* 下一次点击仍会静默放行 —— 人以为已经收干净了。
|
|
127
|
+
*/
|
|
128
|
+
export function togglePersistent(source = 'hotkey') {
|
|
129
|
+
const previousState = getStatus().state
|
|
130
|
+
if (state.persistent) {
|
|
131
|
+
state.persistent = false
|
|
132
|
+
state.onceGranted = false
|
|
133
|
+
clearPending({ code: 'AUTH_CANCELLED', reason: '热键撤销' })
|
|
134
|
+
} else {
|
|
135
|
+
state.persistent = true
|
|
136
|
+
state.onceGranted = false
|
|
137
|
+
clearPending({ code: 'AUTH_CANCELLED', reason: '热键接管' })
|
|
138
|
+
}
|
|
139
|
+
audit('togglePersistent', source, previousState)
|
|
140
|
+
return getStatus()
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* 消费一次放行。持续授权下放行且不改变状态;单次授权放行即清空。
|
|
145
|
+
* 返回 { allowed, mode?, reason? }。
|
|
146
|
+
*/
|
|
147
|
+
export function consumeOnce() {
|
|
148
|
+
const previousState = getStatus().state
|
|
149
|
+
if (state.persistent) {
|
|
150
|
+
audit('consumeOnce', 'tool', previousState, { allowed: true, mode: 'persistent' })
|
|
151
|
+
return { allowed: true, mode: 'persistent' }
|
|
152
|
+
}
|
|
153
|
+
if (state.onceGranted) {
|
|
154
|
+
state.onceGranted = false
|
|
155
|
+
audit('consumeOnce', 'tool', previousState, { allowed: true, mode: 'once' })
|
|
156
|
+
return { allowed: true, mode: 'once' }
|
|
157
|
+
}
|
|
158
|
+
audit('consumeOnce', 'tool', previousState, {
|
|
159
|
+
allowed: false,
|
|
160
|
+
reason: state.pendingRequest !== null ? '授权请求待确认' : '未授权',
|
|
161
|
+
})
|
|
162
|
+
return {
|
|
163
|
+
allowed: false,
|
|
164
|
+
reason: state.pendingRequest !== null ? '授权请求待确认' : '未授权',
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** vp_click 的放行判断(不消费)。 */
|
|
169
|
+
export function checkCanClick() {
|
|
170
|
+
if (state.persistent) {
|
|
171
|
+
return { allowed: true, reason: '持续授权有效' }
|
|
172
|
+
}
|
|
173
|
+
if (state.onceGranted) {
|
|
174
|
+
return { allowed: true, reason: '单次授权待使用' }
|
|
175
|
+
}
|
|
176
|
+
if (state.pendingRequest !== null) {
|
|
177
|
+
return { allowed: false, reason: '授权请求待确认' }
|
|
178
|
+
}
|
|
179
|
+
return { allowed: false, reason: '未授权' }
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/** 测试专用:重置为未授权。 */
|
|
183
|
+
export function _resetForTests() {
|
|
184
|
+
state.persistent = false
|
|
185
|
+
state.onceGranted = false
|
|
186
|
+
clearPending({ code: 'AUTH_CANCELLED', reason: '测试重置' })
|
|
187
|
+
state.requestSeq = 0
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/**
|
|
191
|
+
* 测试专用:读内部标志位。persistent 期间 onceGranted 是否还挂着,
|
|
192
|
+
* getStatus() 看不出来(persistent 优先返回 'persistent'),只能从这里取证。
|
|
193
|
+
*/
|
|
194
|
+
export function _peekForTests() {
|
|
195
|
+
return {
|
|
196
|
+
persistent: state.persistent,
|
|
197
|
+
onceGranted: state.onceGranted,
|
|
198
|
+
hasPending: state.pendingRequest !== null,
|
|
199
|
+
}
|
|
200
|
+
}
|
package/src/coords.js
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
// 坐标契约的唯一真相源。
|
|
2
|
+
//
|
|
3
|
+
// robot-ts 的两套坐标系是不对称的:
|
|
4
|
+
// - screen.capture* / screen.pixel 吃 physical(物理像素,含 DPI 缩放)
|
|
5
|
+
// - mouse.move / mouse.position 吃 logical(逻辑像素 = physical / scaleFactor)
|
|
6
|
+
//
|
|
7
|
+
// vp_screenshot 产出的图像尺寸是物理像素,模型看图给出的坐标因此也是物理像素;
|
|
8
|
+
// vp_click 在注入前必须经 physicalToLogical() 换算,否则 125% 缩放下会偏 25%。
|
|
9
|
+
// 回归依据:test-click.mjs 实测 scaleFactor = 1.25,physical = 1920x1200,logical = 1536x960。
|
|
10
|
+
|
|
11
|
+
/** 物理像素 → 逻辑像素。p 为 {x, y},scaleFactor 来自 primaryMonitor().scaleFactor。 */
|
|
12
|
+
export function physicalToLogical(point, scaleFactor) {
|
|
13
|
+
return { x: point.x / scaleFactor, y: point.y / scaleFactor }
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* 局部区域内的相对位置 → 全局物理坐标。
|
|
18
|
+
* xPercent/yPercent ∈ [0, 1]:0 = bbox 左/上边缘,1 = bbox 右/下边缘(含)。
|
|
19
|
+
* 用 width-1 / height-1 是为了「1.0 落在最后一个像素上」,而不是落到 bbox 外面一像素。
|
|
20
|
+
* 这是 vp_click_relative 的唯一换算公式,测试直接对它断言。
|
|
21
|
+
*/
|
|
22
|
+
export function relativeToPhysical(bbox, xPercent, yPercent) {
|
|
23
|
+
for (const [label, value] of [['xPercent', xPercent], ['yPercent', yPercent]]) {
|
|
24
|
+
if (!Number.isFinite(value)) {
|
|
25
|
+
throw new Error(`${label} 必须是有限数字,收到 ${value}`)
|
|
26
|
+
}
|
|
27
|
+
if (value < 0 || value > 1) {
|
|
28
|
+
throw new Error(`${label} 必须在 0 到 1 之间(含端点),收到 ${value}`)
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
if (
|
|
32
|
+
bbox === null || typeof bbox !== 'object' ||
|
|
33
|
+
!Number.isInteger(bbox.x) || !Number.isInteger(bbox.y) ||
|
|
34
|
+
!Number.isInteger(bbox.width) || !Number.isInteger(bbox.height) ||
|
|
35
|
+
bbox.width < 1 || bbox.height < 1
|
|
36
|
+
) {
|
|
37
|
+
throw new Error(`bbox 必须是整数且宽高 >=1,收到 ${JSON.stringify(bbox)}`)
|
|
38
|
+
}
|
|
39
|
+
return {
|
|
40
|
+
x: bbox.x + Math.round(xPercent * (bbox.width - 1)),
|
|
41
|
+
y: bbox.y + Math.round(yPercent * (bbox.height - 1)),
|
|
42
|
+
}
|
|
43
|
+
}
|
package/src/diff.js
ADDED
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
// 截图差分:把「当前屏幕」与索引里某张历史截图逐像素比对,
|
|
2
|
+
// 输出若干连通差异区域及其局部裁剪图,供模型只看变化部分而不是整屏。
|
|
3
|
+
//
|
|
4
|
+
// 边界(有意为之,不是欠债):
|
|
5
|
+
// - localPath 仍是原尺寸裁剪:局部坐标 + bbox 左上角 = 全局物理坐标,模型可以直接换算。
|
|
6
|
+
// - 额外产出的 gridPath 是 4x 最近邻放大的「网格放大镜」(见 render.js),
|
|
7
|
+
// 它只用于目测/相对点击,不改变 localPath 的 1:1 语义。
|
|
8
|
+
// - 不做高频抽帧,只在调用时截一张当前图。
|
|
9
|
+
// - 尺寸/缩放不一致时直接抛错,不做任何重采样或硬算 —— 显示器或缩放变了,
|
|
10
|
+
// 旧截图的坐标系已经不可信,勉强对齐只会给出错误坐标。
|
|
11
|
+
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
|
|
12
|
+
import { join } from 'node:path'
|
|
13
|
+
import { PNG } from 'pngjs'
|
|
14
|
+
import pixelmatch from 'pixelmatch'
|
|
15
|
+
import { screenshotAction } from './actions.js'
|
|
16
|
+
import { get, recordRegions } from './shot-index.js'
|
|
17
|
+
import { resolveShotsDir } from './paths.js'
|
|
18
|
+
import { generateGridImage, MAX_GRID_SOURCE_AREA } from './render.js'
|
|
19
|
+
|
|
20
|
+
// 小于这个像素数的连通区域按噪声丢弃(光标闪烁、 blinking caret、亚像素抖动)。
|
|
21
|
+
export const DEFAULT_MIN_REGION_AREA = 100
|
|
22
|
+
|
|
23
|
+
// 网格图的成本是「每个区域一次 4x 放大 + PNG 编码」,差异块很多时(实测出现过单次 105 块)
|
|
24
|
+
// 全量生成只会拖慢工具并堆满临时目录,所以只给前 N 个(按面积降序)配网格图。
|
|
25
|
+
export const MAX_GRID_REGIONS = 12
|
|
26
|
+
|
|
27
|
+
function readPng(path) {
|
|
28
|
+
return PNG.sync.read(readFileSync(path))
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** 找出 mask 里的 4 邻域连通块,返回像素数与包围盒(图像坐标系,左上角原点)。 */
|
|
32
|
+
export function connectedComponents(mask, width, height) {
|
|
33
|
+
const total = width * height
|
|
34
|
+
const visited = new Uint8Array(total)
|
|
35
|
+
const components = []
|
|
36
|
+
|
|
37
|
+
for (let seed = 0; seed < total; seed++) {
|
|
38
|
+
if (mask[seed] === 0 || visited[seed] === 1) continue
|
|
39
|
+
visited[seed] = 1
|
|
40
|
+
const queue = [seed]
|
|
41
|
+
let pixels = 0
|
|
42
|
+
let minX = width
|
|
43
|
+
let maxX = -1
|
|
44
|
+
let minY = height
|
|
45
|
+
let maxY = -1
|
|
46
|
+
|
|
47
|
+
for (let head = 0; head < queue.length; head++) {
|
|
48
|
+
const cur = queue[head]
|
|
49
|
+
pixels += 1
|
|
50
|
+
const x = cur % width
|
|
51
|
+
const y = (cur / width) | 0
|
|
52
|
+
if (x < minX) minX = x
|
|
53
|
+
if (x > maxX) maxX = x
|
|
54
|
+
if (y < minY) minY = y
|
|
55
|
+
if (y > maxY) maxY = y
|
|
56
|
+
|
|
57
|
+
const push = (n) => {
|
|
58
|
+
if (mask[n] === 1 && visited[n] === 0) {
|
|
59
|
+
visited[n] = 1
|
|
60
|
+
queue.push(n)
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
if (x > 0) push(cur - 1)
|
|
64
|
+
if (x < width - 1) push(cur + 1)
|
|
65
|
+
if (y > 0) push(cur - width)
|
|
66
|
+
if (y < height - 1) push(cur + width)
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
components.push({
|
|
70
|
+
pixels,
|
|
71
|
+
bbox: { x: minX, y: minY, width: maxX - minX + 1, height: maxY - minY + 1 },
|
|
72
|
+
})
|
|
73
|
+
}
|
|
74
|
+
return components
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** 从当前图裁出 bbox 大小的 PNG(原尺寸,不缩放)。 */
|
|
78
|
+
function crop(source, bbox) {
|
|
79
|
+
const out = new PNG({ width: bbox.width, height: bbox.height })
|
|
80
|
+
for (let row = 0; row < bbox.height; row++) {
|
|
81
|
+
const from = ((bbox.y + row) * source.width + bbox.x) * 4
|
|
82
|
+
source.data.copy(
|
|
83
|
+
out.data,
|
|
84
|
+
row * bbox.width * 4,
|
|
85
|
+
from,
|
|
86
|
+
from + bbox.width * 4,
|
|
87
|
+
)
|
|
88
|
+
}
|
|
89
|
+
return out
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
const formatDims = (meta) => `${meta.width}x${meta.height}@${meta.scaleFactor}`
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* 对两张已落盘的截图做差分。不碰屏幕,可被单元测试直接调用。
|
|
96
|
+
* 两个 meta 都来自 shot-index(path/width/height/scaleFactor)。
|
|
97
|
+
*/
|
|
98
|
+
export function diffPair({
|
|
99
|
+
baselineMeta,
|
|
100
|
+
currentMeta,
|
|
101
|
+
baselineShotId,
|
|
102
|
+
currentShotId,
|
|
103
|
+
threshold = 0.1,
|
|
104
|
+
minArea = DEFAULT_MIN_REGION_AREA,
|
|
105
|
+
}) {
|
|
106
|
+
if (
|
|
107
|
+
baselineMeta.width !== currentMeta.width ||
|
|
108
|
+
baselineMeta.height !== currentMeta.height ||
|
|
109
|
+
baselineMeta.scaleFactor !== currentMeta.scaleFactor
|
|
110
|
+
) {
|
|
111
|
+
throw new Error(
|
|
112
|
+
`baseline 与当前截图尺寸/缩放不一致(baseline: ${formatDims(baselineMeta)},` +
|
|
113
|
+
`current: ${formatDims(currentMeta)}),可能显示器或缩放变了,请重新截图`,
|
|
114
|
+
)
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
const baseline = readPng(baselineMeta.path)
|
|
118
|
+
const current = readPng(currentMeta.path)
|
|
119
|
+
const width = baseline.width
|
|
120
|
+
const height = baseline.height
|
|
121
|
+
|
|
122
|
+
// diffMask=true:输出缓冲里只有真正的差异像素非零(被判定为抗锯齿的像素不进 mask),
|
|
123
|
+
// alpha 通道即差异掩码。
|
|
124
|
+
const output = new Uint8Array(width * height * 4)
|
|
125
|
+
pixelmatch(baseline.data, current.data, output, width, height, { threshold, diffMask: true })
|
|
126
|
+
|
|
127
|
+
const mask = new Uint8Array(width * height)
|
|
128
|
+
for (let i = 0; i < mask.length; i++) {
|
|
129
|
+
mask[i] = output[i * 4 + 3] !== 0 ? 1 : 0
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
const kept = connectedComponents(mask, width, height)
|
|
133
|
+
.filter((component) => component.pixels >= minArea)
|
|
134
|
+
.sort((a, b) => b.pixels - a.pixels)
|
|
135
|
+
|
|
136
|
+
const dir = resolveShotsDir()
|
|
137
|
+
mkdirSync(dir, { recursive: true })
|
|
138
|
+
|
|
139
|
+
const regions = kept.map((component, i) => {
|
|
140
|
+
const bbox = component.bbox
|
|
141
|
+
const localPath = join(dir, `vp-diff-${currentShotId}-${i + 1}.png`)
|
|
142
|
+
writeFileSync(localPath, PNG.sync.write(crop(current, bbox)))
|
|
143
|
+
const region = {
|
|
144
|
+
// offset 就是 bbox 左上角:局部图未放大,(0,0) 对应全局 offset。
|
|
145
|
+
bbox,
|
|
146
|
+
localPath,
|
|
147
|
+
offset: { x: bbox.x, y: bbox.y },
|
|
148
|
+
}
|
|
149
|
+
if (i >= MAX_GRID_REGIONS) {
|
|
150
|
+
region.gridSkipped = `只给前 ${MAX_GRID_REGIONS} 个区域生成网格图(本区域排第 ${i + 1})`
|
|
151
|
+
} else if (bbox.width * bbox.height > MAX_GRID_SOURCE_AREA) {
|
|
152
|
+
region.gridSkipped =
|
|
153
|
+
`区域 ${bbox.width}x${bbox.height} 超过网格图上限 ${MAX_GRID_SOURCE_AREA} 物理像素,直接看全屏更合适`
|
|
154
|
+
} else {
|
|
155
|
+
region.gridPath = generateGridImage(currentMeta.path, bbox, currentMeta.scaleFactor, {
|
|
156
|
+
shotId: currentShotId,
|
|
157
|
+
index: i + 1,
|
|
158
|
+
})
|
|
159
|
+
}
|
|
160
|
+
return region
|
|
161
|
+
})
|
|
162
|
+
|
|
163
|
+
// 索引里没有 currentShotId 时(直接调 diffPair 的测试场景)跳过,不影响差分结果本身。
|
|
164
|
+
recordRegions(currentShotId, regions)
|
|
165
|
+
|
|
166
|
+
const changedPixels = kept.reduce((sum, component) => sum + component.pixels, 0)
|
|
167
|
+
|
|
168
|
+
return {
|
|
169
|
+
changed: regions.length > 0,
|
|
170
|
+
regions,
|
|
171
|
+
coverage: regions.length === 0 ? 0 : changedPixels / (width * height),
|
|
172
|
+
baselineShotId,
|
|
173
|
+
currentShotId,
|
|
174
|
+
coordinateContract: 'physical',
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/** 截一张当前图,与 baselineShotId 指向的历史截图做差分。 */
|
|
179
|
+
export async function diffAction({
|
|
180
|
+
baseline,
|
|
181
|
+
threshold = 0.1,
|
|
182
|
+
minArea = DEFAULT_MIN_REGION_AREA,
|
|
183
|
+
}) {
|
|
184
|
+
const baselineMeta = get(baseline)
|
|
185
|
+
if (baselineMeta === undefined) {
|
|
186
|
+
throw new Error(
|
|
187
|
+
`vp_screenshot_diff: baseline shotId ${baseline} 不存在,可先用 vp_screenshot 截一张`,
|
|
188
|
+
)
|
|
189
|
+
}
|
|
190
|
+
const current = await screenshotAction()
|
|
191
|
+
return diffPair({
|
|
192
|
+
baselineMeta,
|
|
193
|
+
currentMeta: get(current.shotId),
|
|
194
|
+
baselineShotId: baseline,
|
|
195
|
+
currentShotId: current.shotId,
|
|
196
|
+
threshold,
|
|
197
|
+
minArea,
|
|
198
|
+
})
|
|
199
|
+
}
|