offscreen-android 0.0.0-stage → 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/src/lease.js ADDED
@@ -0,0 +1,314 @@
1
+ /**
2
+ * lease.js — App 占用的凭证。多屏 / 多 AI 场景下防止互相抢。
3
+ *
4
+ * ## 为什么需要
5
+ *
6
+ * 有了多屏池和占用检测之后,还缺一环:**检测到了冲突,但没人拦。**
7
+ * 两个 AI 都可能看到「这个 App 在别人屏上」,然后各自决定「我抢一下」,
8
+ * 结果互相拆台。
9
+ *
10
+ * 租约就是那张凭证:想用某个 App 就先 claim,别人 claim 时会失败并知道是谁拿着。
11
+ *
12
+ * ## 设计取舍(都是被实测逼出来的)
13
+ *
14
+ * **① 默认不抢占。** `onConflict` 默认 `'fail'`。设计文档的原话:
15
+ * 「默认抢占会变成 AI 互抢常态,默认失败才逼出『先查再决定』」。
16
+ *
17
+ * **② 宽限期只有 5 秒,因为 AI 一轮往返 6-9 秒。**
18
+ * 所以「体面退场」在物理上不可能 —— victim 收到撤销通知时,它这一轮已经在跑了。
19
+ * 能保证的只有「它下次调用会收到 E_LEASE_REVOKED,不会继续误操作」。
20
+ * 任何要求 AI 在宽限期内收尾的实现都是错的。
21
+ *
22
+ * **③ 抢占 = 转移租约,不是杀进程。**
23
+ * App 任务留在原屏,新持有者接手那块屏。UI 状态、滚动位置都还在。
24
+ * force-stop 只在租约到期且没人接的时候才考虑。
25
+ *
26
+ * **④ 不持久化。** 租约绑在屏的 socket 和进程上,daemon 一死全作废。
27
+ * 写盘只会造出「账本说有人持有、实际没人」的假象。
28
+ */
29
+
30
+ import { LEVEL, checkApp, canTouch } from './occupancy.js';
31
+ import * as pool from './pool.js';
32
+
33
+ /** leaseId → lease */
34
+ const leases = new Map();
35
+ let nextId = 1;
36
+
37
+ /** 抢占宽限期(毫秒)。见文件头注释②,不能设得太长。 */
38
+ export const GRACE_MS = 5000;
39
+
40
+ /** 默认租约时长(毫秒)。10 分钟,够一轮长任务。 */
41
+ export const DEFAULT_TTL_MS = 10 * 60 * 1000;
42
+
43
+ /**
44
+ * @typedef {object} Lease
45
+ * @property {string} leaseId
46
+ * @property {string} pkg
47
+ * @property {string} screenId
48
+ * @property {string} owner 会话标识
49
+ * @property {'exclusive'|'readonly'} mode
50
+ * @property {'user'|'agent'|'subagent'} priority
51
+ * @property {number} expiresAt
52
+ * @property {boolean} preemptible
53
+ * @property {string|null} nonPreemptibleReason
54
+ * @property {number} createdAt
55
+ */
56
+
57
+ function now() { return Date.now(); }
58
+
59
+ /** 清掉过期的租约 */
60
+ function reap() {
61
+ const t = now();
62
+ for (const [id, l] of leases) {
63
+ if (l.expiresAt <= t) leases.delete(id);
64
+ }
65
+ }
66
+
67
+ /** 找某个 pkg 现在有效的 exclusive 租约 */
68
+ function findExclusive(pkg) {
69
+ reap();
70
+ for (const l of leases.values()) {
71
+ if (l.pkg === pkg && l.mode === 'exclusive') return l;
72
+ }
73
+ return null;
74
+ }
75
+
76
+ /**
77
+ * 申请占用一个 App。
78
+ *
79
+ * @param {object} o
80
+ * @param {string} o.pkg
81
+ * @param {string} o.screenId 想在哪块屏上用它
82
+ * @param {string} [o.owner] 会话标识(拿不到就写 'unknown')
83
+ * @param {'exclusive'|'readonly'} [o.mode='exclusive']
84
+ * @param {'user'|'agent'|'subagent'} [o.priority='agent']
85
+ * @param {boolean} [o.preemptible=true]
86
+ * @param {string} [o.nonPreemptibleReason] 登录/支付/发送中由 AI 自报
87
+ * @param {'fail'|'wait'|'preempt'} [o.onConflict='fail']
88
+ * @param {number} [o.ttlMs]
89
+ * @returns {Promise<object>}
90
+ */
91
+ export async function claim(o = {}) {
92
+ const pkg = String(o.pkg || '').trim();
93
+ const screenId = String(o.screenId || '').trim();
94
+ if (!pkg) return { ok: false, code: 'E_BAD_ARG', hint: '需要 pkg' };
95
+
96
+ // 屏必须在池里
97
+ const info = pool.info();
98
+ const screen = info.screens.find((s) => s.screenId === screenId);
99
+ if (!screen) {
100
+ return {
101
+ ok: false,
102
+ code: 'E_NO_SCREEN',
103
+ hint: `没有这块屏「${screenId}」。现有:${info.screens.map((s) => s.screenId).join(', ') || '(空)'}`,
104
+ next: { action: 'create_screen' },
105
+ };
106
+ }
107
+
108
+ // 系统层先查一遍:用户正在看的东西绝不动
109
+ const ourScreens = new Map(info.screens.map((s) => [Number(s.displayId), s.screenId]));
110
+ const occ = await checkApp(pkg, { ourScreens });
111
+ if (!occ.ok) return { ok: false, code: 'E_PROBE_FAILED', hint: occ.hint };
112
+
113
+ const touch = canTouch(occ.level);
114
+ if (!touch.ok) {
115
+ return {
116
+ ok: false,
117
+ code: 'E_PROTECTED',
118
+ hint: `不能占用「${pkg}」:${touch.reason}`,
119
+ occupancy: { level: occ.level, levelName: occ.levelName },
120
+ next: { action: 'handoff_to_user' },
121
+ };
122
+ }
123
+
124
+ // 已有租约?
125
+ const held = findExclusive(pkg);
126
+ // **同屏不同 owner 也算冲突。** 第一版只拦了「屏不同」的情况,
127
+ // 于是同一块屏上 B 会话申请同一个 App 会直接建一个新租约 —— 结果三个租约都指向
128
+ // 同一个 pkg+screen,谁也没被拦住,租约形同虚设。
129
+ const sameOwner = held && held.owner === (o.owner || 'unknown');
130
+ if (held && !sameOwner) {
131
+ // 别人拿着
132
+ if (o.onConflict === 'preempt') {
133
+ const p = canPreempt(held, o);
134
+ if (!p.ok) {
135
+ return {
136
+ ok: false,
137
+ code: 'E_NOT_PREEMPTIBLE',
138
+ hint: p.reason,
139
+ holder: publicLease(held),
140
+ next: { action: 'wait' },
141
+ };
142
+ }
143
+ // 撤销旧的,给新的
144
+ const revoked = revoke(held.leaseId, `被 ${o.owner || 'unknown'} 抢占`);
145
+ const l = grant({ ...o, pkg, screenId });
146
+ return {
147
+ ok: true,
148
+ lease: publicLease(l),
149
+ preempted: publicLease(held),
150
+ revokedOk: revoked.ok,
151
+ note: `已接管。原持有者 ${held.owner} 会在下次调用时收到撤销通知 —— `
152
+ + `宽限期只有 ${GRACE_MS / 1000} 秒,比一轮往返短,所以它这一轮可能已经跑完了。`,
153
+ };
154
+ }
155
+ if (o.onConflict === 'wait') {
156
+ const waitMs = Math.max(0, held.expiresAt - now());
157
+ return {
158
+ ok: false,
159
+ code: 'E_APP_BUSY',
160
+ hint: `「${pkg}」正被 ${held.owner} 占着,最多还要 ${Math.ceil(waitMs / 1000)} 秒。`,
161
+ holder: publicLease(held),
162
+ retryAfterMs: waitMs,
163
+ next: { action: 'wait' },
164
+ };
165
+ }
166
+ // 默认 fail
167
+ return {
168
+ ok: false,
169
+ code: 'E_APP_BUSY',
170
+ hint: `「${pkg}」正被 ${held.owner} 占着(${held.screenId})。`
171
+ + `想抢就把 onConflict 设成 'preempt',想等就设成 'wait'。`,
172
+ holder: publicLease(held),
173
+ next: { action: 'preempt', alternatives: ['wait', 'use_other_app'] },
174
+ };
175
+ }
176
+
177
+ // 同一个 owner 重复申请 → 幂等返回,不新建
178
+ if (sameOwner) {
179
+ return { ok: true, lease: publicLease(held), reused: true };
180
+ }
181
+
182
+ const l = grant({ ...o, pkg, screenId });
183
+ return { ok: true, lease: publicLease(l) };
184
+ }
185
+
186
+ /** 给租约。内部用,不做校验。 */
187
+ function grant(o) {
188
+ const l = {
189
+ leaseId: `ls-${nextId++}`,
190
+ pkg: String(o.pkg),
191
+ screenId: String(o.screenId),
192
+ owner: String(o.owner || 'unknown'),
193
+ mode: o.mode === 'readonly' ? 'readonly' : 'exclusive',
194
+ priority: ['user', 'agent', 'subagent'].includes(o.priority) ? o.priority : 'agent',
195
+ expiresAt: now() + (Number(o.ttlMs) || DEFAULT_TTL_MS),
196
+ preemptible: o.preemptible !== false,
197
+ nonPreemptibleReason: o.nonPreemptibleReason ? String(o.nonPreemptibleReason).slice(0, 200) : null,
198
+ createdAt: now(),
199
+ };
200
+ leases.set(l.leaseId, l);
201
+ return l;
202
+ }
203
+
204
+ /**
205
+ * 能不能抢这个租约。
206
+ *
207
+ * 规则:user 级能抢 agent/subagent;agent 只能抢 subagent;
208
+ * 声明了 nonPreemptible 的一律不抢(登录、支付、发送中)。
209
+ */
210
+ function canPreempt(held, req) {
211
+ if (!held.preemptible) {
212
+ return {
213
+ ok: false,
214
+ reason: `原持有者声明了不可抢${held.nonPreemptibleReason ? `(${held.nonPreemptibleReason})` : ''}`,
215
+ };
216
+ }
217
+ const rank = { user: 3, agent: 2, subagent: 1 };
218
+ const mine = rank[req.priority] || 2;
219
+ const theirs = rank[held.priority] || 2;
220
+ if (mine < theirs) {
221
+ return { ok: false, reason: `优先级不够(你是 ${req.priority},对方是 ${held.priority})` };
222
+ }
223
+ return { ok: true };
224
+ }
225
+
226
+ /** 撤销一个租约。返回原租约信息,让调用方能通知 victim。 */
227
+ export function revoke(leaseId, reason = '') {
228
+ const l = leases.get(String(leaseId));
229
+ if (!l) return { ok: false, code: 'E_NO_LEASE', hint: `没有租约 ${leaseId}` };
230
+ leases.delete(String(leaseId));
231
+ return { ok: true, revoked: publicLease(l), reason };
232
+ }
233
+
234
+ /** 主动释放(AI 干完了自己放) */
235
+ export function release(leaseId) {
236
+ return revoke(leaseId, '主动释放');
237
+ }
238
+
239
+ /** 释放某个会话持有的全部租约(会话结束时用) */
240
+ export function releaseAll(owner, hint = '会话结束') {
241
+ const n = [];
242
+ for (const [id, l] of leases) {
243
+ if (l.owner === owner) { leases.delete(id); n.push(id); }
244
+ }
245
+ return { ok: true, released: n, hint };
246
+ }
247
+
248
+ /**
249
+ * 校验:这次操作有没有权限。
250
+ *
251
+ * 调用方(比如 vdisplay_input)在做有副作用的事之前调它。
252
+ *
253
+ * @param {string} pkg
254
+ * @param {string} screenId
255
+ * @param {string} owner
256
+ * @returns {{ok:boolean, code?:string, hint?:string}}
257
+ */
258
+ export function check(pkg, screenId, owner) {
259
+ reap();
260
+ const held = findExclusive(pkg);
261
+ if (!held) return { ok: true, hint: '没有租约,随便用' }; // 没人占就允许
262
+ if (held.screenId !== screenId) {
263
+ return {
264
+ ok: false,
265
+ code: 'E_WRONG_SCREEN',
266
+ hint: `「${pkg}」的租约绑在 ${held.screenId} 上,你现在在 ${screenId}。`
267
+ + `要么切到那块屏,要么先 claim。`,
268
+ };
269
+ }
270
+ if (held.owner !== owner) {
271
+ return {
272
+ ok: false,
273
+ code: 'E_NOT_OWNER',
274
+ hint: `「${pkg}」在 ${held.screenId} 上被 ${held.owner} 占着(你自称 ${owner})。`,
275
+ };
276
+ }
277
+ return { ok: true };
278
+ }
279
+
280
+ /** 对外可见的租约(不暴露内部字段) */
281
+ function publicLease(l) {
282
+ return {
283
+ leaseId: l.leaseId,
284
+ pkg: l.pkg,
285
+ screenId: l.screenId,
286
+ owner: l.owner,
287
+ mode: l.mode,
288
+ priority: l.priority,
289
+ preemptible: l.preemptible,
290
+ nonPreemptibleReason: l.nonPreemptibleReason,
291
+ remainingSec: Math.max(0, Math.round((l.expiresAt - now()) / 1000)),
292
+ };
293
+ }
294
+
295
+ /** 列出所有有效租约 */
296
+ export function list() {
297
+ reap();
298
+ return { ok: true, count: leases.size, leases: [...leases.values()].map(publicLease) };
299
+ }
300
+
301
+ /** 给 AI 看的可读说明 */
302
+ export function describeList() {
303
+ const r = list();
304
+ if (!r.count) return '当前没有任何租约。想占某个 App 用 screen_claim_app。';
305
+ const lines = [`共 ${r.count} 个租约:`];
306
+ for (const l of r.leases) {
307
+ lines.push(` ${l.leaseId} ${l.pkg} → ${l.screenId} 由 ${l.owner} 占用,`
308
+ + `还剩 ${l.remainingSec} 秒${l.preemptible ? '' : '(不可抢)'}`);
309
+ }
310
+ return lines.join('\n');
311
+ }
312
+
313
+ /** 测试用:清空 */
314
+ export function _reset() { leases.clear(); nextId = 1; }
@@ -0,0 +1,214 @@
1
+ /**
2
+ * occupancy.js — 查「某个 App 现在被谁占着」。
3
+ *
4
+ * ## 核心认知
5
+ *
6
+ * **Android 不记录「谁在用 App」,只记录「task 在哪块屏」。**
7
+ * 所以占用检测分两层:
8
+ *
9
+ * 事实层(系统可查):某包在哪些 display 上有 task、哪个有焦点、pid 多少
10
+ * 归属层(自己记账):这块屏是哪个会话的
11
+ *
12
+ * 只查系统 → 不知是谁;只记账 → 会撒谎(App 崩了、用户按返回了)。
13
+ * **两层必须每次对账。**
14
+ *
15
+ * ## 查询方式(U1 实测可行,32ms)
16
+ *
17
+ * dumpsys activity activities | grep 'Display #'
18
+ *
19
+ * 能读到 display 编号、taskId、包名、可见性、焦点。
20
+ *
21
+ * ## 一个有用的推论
22
+ *
23
+ * 私有虚拟屏用户看不见,**所以出现在 scrcpy 屏上的 task 100% 是 AI 的**。
24
+ * 这让「自家屏 vs 用户屏」的区分变得很简单:主屏(display 0)上的才是用户的。
25
+ */
26
+
27
+ import { adb } from './vd.js';
28
+
29
+ /**
30
+ * 解析 dumpsys activity activities 的 Display 分组。
31
+ *
32
+ * 输出格式(实测):
33
+ * Display #0 (activities from top to bottom):
34
+ * * Task{4626b03 #24685 type=standard I=io.github... U=0 visible=true ...}
35
+ * Display #210 (activities from top to bottom):
36
+ * * Task{ad74e9e #24742 type=standard A=1000:com.android.settings.root ...}
37
+ *
38
+ * @param {string} out dumpsys 输出
39
+ * @returns {Map<number, Array<{taskId:number, pkg:string, visible:boolean}>>}
40
+ */
41
+ export function parseDisplays(out) {
42
+ const result = new Map();
43
+ let currentDisplay = null;
44
+
45
+ for (const raw of String(out || '').split('\n')) {
46
+ const line = raw.trim();
47
+
48
+ const dm = line.match(/^Display #(-?\d+) \(/);
49
+ if (dm) {
50
+ currentDisplay = Number(dm[1]);
51
+ if (!result.has(currentDisplay)) result.set(currentDisplay, []);
52
+ continue;
53
+ }
54
+ if (currentDisplay === null) continue;
55
+
56
+ // Task 行里拿 taskId 和包名。包名有两种写法:
57
+ // A=1000:com.android.settings.root (带 uid 前缀)
58
+ // I=io.github.ccch1mneyyy.dsh_app/.LauncherInk
59
+ if (!/^\* Task\{/.test(line)) continue;
60
+ const tid = line.match(/#(\d+)/);
61
+ const pkgA = line.match(/\bA=\d+:([a-zA-Z0-9_.]+)/);
62
+ const pkgI = line.match(/\bI=([a-zA-Z0-9_.]+)\//);
63
+ const pkg = pkgA ? pkgA[1] : (pkgI ? pkgI[1] : null);
64
+ if (!tid || !pkg) continue;
65
+ const visible = /visible=true/.test(line);
66
+ result.get(currentDisplay).push({ taskId: Number(tid[1]), pkg, visible });
67
+ }
68
+ return result;
69
+ }
70
+
71
+ /**
72
+ * 包名匹配。
73
+ *
74
+ * **不能精确比对。** 实测系统报的是 `com.android.settings.root`(带进程后缀),
75
+ * 而调用方查的是 `com.android.settings` —— 精确匹配结果永远是 FREE,等于整个
76
+ * 占用检测失效。同理还有 `com.tencent.mm:push` 这类带 `:` 的进程名。
77
+ *
78
+ * 规则:完全相等,或者是「pkg + .」/「pkg + :」开头的子包/进程。
79
+ */
80
+ export function pkgMatches(query, actual) {
81
+ if (!query || !actual) return false;
82
+ if (query === actual) return true;
83
+ return actual.startsWith(query + '.') || actual.startsWith(query + ':');
84
+ }
85
+
86
+ /** 占用等级。数值越大越「不能碰」。 */
87
+ export const LEVEL = {
88
+ FREE: 0, // 哪都没有
89
+ SOFT: 1, // 只有进程,没 task
90
+ USER_BG: 2, // 主屏有 task 但不在前台
91
+ USER_ACTIVE: 3, // 主屏前台就是它
92
+ AI_HELD: 4, // 在我们自己的屏上
93
+ ORPHAN: 5, // 在我们自己的屏上但池里没记账
94
+ FOREIGN: 6, // 外来屏(不是我们建的)
95
+ };
96
+
97
+ const LEVEL_NAME = Object.fromEntries(Object.entries(LEVEL).map(([k, v]) => [v, k]));
98
+
99
+ /**
100
+ * 查一个包现在的占用情况。
101
+ *
102
+ * @param {string} pkg
103
+ * @param {object} [o]
104
+ * @param {Map<number,string>} [o.ourScreens] 我们认得的所有屏:displayId → screenId
105
+ * @returns {Promise<{ok:boolean, pkg:string, level:number, levelName:string,
106
+ * onMain:boolean, mainVisible:boolean,
107
+ * onOurScreens:Array<{displayId:number, screenId:string, visible:boolean}>,
108
+ * foreignDisplays:number[], hint?:string}>}
109
+ */
110
+ export async function checkApp(pkg, o = {}) {
111
+ const r = await adb(['shell', 'dumpsys activity activities 2>/dev/null']);
112
+ if (!r.ok) {
113
+ return { ok: false, hint: `查占用失败:${r.err || 'adb 不可用'}`, pkg };
114
+ }
115
+ const byDisplay = parseDisplays(r.out);
116
+
117
+ /*
118
+ * **解析不出来必须报错,不能当成"没人用"。**
119
+ *
120
+ * 原来这里没有检查:dumpsys 输出格式变了、或者 adb 返回空,parseDisplays 返回
121
+ * 空 Map,后面的循环一次都不执行,于是所有标志保持 false → level=FREE → canTouch 放行。
122
+ * 也就是说**探测失败会被当成"这 App 没人占,随便用"**,这是最危险的失败方向。
123
+ *
124
+ * 加断言:一个 display 都没解析出来 = 探测失败,闭着嘴拒绝。
125
+ */
126
+ if (byDisplay.size === 0) {
127
+ return {
128
+ ok: false,
129
+ pkg,
130
+ code: 'E_PROBE_FAILED',
131
+ hint: '占用探测失败:dumpsys activity activities 一个 display 都没解析出来。'
132
+ + '可能是 adb 断了,或者这台机器的 dumpsys 格式和预期不同。'
133
+ + '为了安全这里**不放行** —— 拿不到占用状态时不能假设没人用。',
134
+ };
135
+ }
136
+
137
+ const ourScreens = o.ourScreens || new Map();
138
+ const onOurScreens = [];
139
+ const foreignDisplays = [];
140
+ let onMain = false;
141
+ let mainVisible = false;
142
+
143
+ for (const [displayId, tasks] of byDisplay) {
144
+ const hit = tasks.filter((t) => pkgMatches(pkg, t.pkg));
145
+ if (!hit.length) continue;
146
+
147
+ if (displayId === 0) {
148
+ onMain = true;
149
+ mainVisible = hit.some((t) => t.visible);
150
+ } else if (ourScreens.has(displayId)) {
151
+ onOurScreens.push({
152
+ displayId,
153
+ screenId: ourScreens.get(displayId),
154
+ visible: hit.some((t) => t.visible),
155
+ });
156
+ } else {
157
+ foreignDisplays.push(displayId);
158
+ }
159
+ }
160
+
161
+ // 判定等级:取最严重的那个
162
+ let level = LEVEL.FREE;
163
+ if (foreignDisplays.length) level = Math.max(level, LEVEL.FOREIGN);
164
+ if (onOurScreens.length) level = Math.max(level, LEVEL.AI_HELD);
165
+ if (onMain) level = Math.max(level, mainVisible ? LEVEL.USER_ACTIVE : LEVEL.USER_BG);
166
+
167
+ return {
168
+ ok: true,
169
+ pkg,
170
+ level,
171
+ levelName: LEVEL_NAME[level],
172
+ onMain,
173
+ mainVisible,
174
+ onOurScreens,
175
+ foreignDisplays,
176
+ };
177
+ }
178
+
179
+ /**
180
+ * 这个占用等级能不能动。
181
+ *
182
+ * 规则很简单:**用户正在看的(USER_ACTIVE)和不是我们的屏(FOREIGN)绝对不碰。**
183
+ */
184
+ export function canTouch(level) {
185
+ if (level >= LEVEL.FOREIGN) return { ok: false, reason: '这块屏不是我们建的,不碰' };
186
+ if (level === LEVEL.USER_ACTIVE) return { ok: false, reason: '用户正在主屏上看这个 App,不碰' };
187
+ return { ok: true };
188
+ }
189
+
190
+ /**
191
+ * 给 AI 看的可读说明。
192
+ */
193
+ export function describe(res) {
194
+ if (!res.ok) return res.hint || '查不到';
195
+ const lines = [`「${res.pkg}」占用等级:${res.levelName}(${res.level})`];
196
+
197
+ if (res.onMain) {
198
+ lines.push(` · 用户主屏上有它的任务${res.mainVisible ? '(**正在前台**)' : '(在后台)'}`);
199
+ }
200
+ if (res.onOurScreens.length) {
201
+ for (const s of res.onOurScreens) {
202
+ lines.push(` · 在我们建的 ${s.screenId}(display ${s.displayId})上${s.visible ? ',可见' : ''}`);
203
+ }
204
+ }
205
+ if (res.foreignDisplays.length) {
206
+ lines.push(` · 出现在外来屏 display ${res.foreignDisplays.join(', ')} 上 —— 不是我们建的,不碰`);
207
+ }
208
+ if (res.level === LEVEL.FREE) lines.push(' · 哪儿都没找到它');
209
+
210
+ const t = canTouch(res.level);
211
+ lines.push('');
212
+ lines.push(t.ok ? '✅ 可以操作' : `❌ 不建议操作:${t.reason}`);
213
+ return lines.join('\n');
214
+ }