@web-auto/camo 0.1.3 → 0.1.4
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/README.md +137 -0
- package/package.json +2 -1
- package/scripts/check-file-size.mjs +80 -0
- package/scripts/file-size-policy.json +8 -0
- package/src/autoscript/action-providers/index.mjs +9 -0
- package/src/autoscript/action-providers/xhs/comments.mjs +412 -0
- package/src/autoscript/action-providers/xhs/common.mjs +77 -0
- package/src/autoscript/action-providers/xhs/detail.mjs +181 -0
- package/src/autoscript/action-providers/xhs/interaction.mjs +466 -0
- package/src/autoscript/action-providers/xhs/like-rules.mjs +57 -0
- package/src/autoscript/action-providers/xhs/persistence.mjs +167 -0
- package/src/autoscript/action-providers/xhs/search.mjs +174 -0
- package/src/autoscript/action-providers/xhs.mjs +133 -0
- package/src/autoscript/impact-engine.mjs +78 -0
- package/src/autoscript/runtime.mjs +1015 -0
- package/src/autoscript/schema.mjs +370 -0
- package/src/autoscript/xhs-unified-template.mjs +931 -0
- package/src/cli.mjs +185 -79
- package/src/commands/autoscript.mjs +1100 -0
- package/src/commands/browser.mjs +20 -4
- package/src/commands/container.mjs +298 -75
- package/src/commands/events.mjs +152 -0
- package/src/commands/lifecycle.mjs +17 -3
- package/src/commands/window.mjs +32 -1
- package/src/container/change-notifier.mjs +165 -24
- package/src/container/element-filter.mjs +51 -5
- package/src/container/runtime-core/checkpoint.mjs +195 -0
- package/src/container/runtime-core/index.mjs +21 -0
- package/src/container/runtime-core/operations/index.mjs +351 -0
- package/src/container/runtime-core/operations/selector-scripts.mjs +68 -0
- package/src/container/runtime-core/operations/tab-pool.mjs +544 -0
- package/src/container/runtime-core/operations/viewport.mjs +143 -0
- package/src/container/runtime-core/subscription.mjs +87 -0
- package/src/container/runtime-core/utils.mjs +94 -0
- package/src/container/runtime-core/validation.mjs +127 -0
- package/src/container/runtime-core.mjs +1 -0
- package/src/container/subscription-registry.mjs +459 -0
- package/src/core/actions.mjs +573 -0
- package/src/core/browser.mjs +270 -0
- package/src/core/index.mjs +53 -0
- package/src/core/utils.mjs +87 -0
- package/src/events/daemon-entry.mjs +33 -0
- package/src/events/daemon.mjs +80 -0
- package/src/events/progress-log.mjs +109 -0
- package/src/events/ws-server.mjs +239 -0
- package/src/lib/client.mjs +8 -5
- package/src/lifecycle/session-registry.mjs +8 -4
- package/src/lifecycle/session-watchdog.mjs +220 -0
- package/src/utils/browser-service.mjs +232 -9
- package/src/utils/help.mjs +26 -3
|
@@ -0,0 +1,544 @@
|
|
|
1
|
+
import { callAPI } from '../../../utils/browser-service.mjs';
|
|
2
|
+
import { asErrorPayload, extractPageList, normalizeArray } from '../utils.mjs';
|
|
3
|
+
import { executeViewportOperation } from './viewport.mjs';
|
|
4
|
+
|
|
5
|
+
const SHORTCUT_OPEN_TIMEOUT_MS = 2500;
|
|
6
|
+
const DEFAULT_API_TIMEOUT_MS = 15000;
|
|
7
|
+
const DEFAULT_NAV_TIMEOUT_MS = 25000;
|
|
8
|
+
const DEFAULT_VIEWPORT_API_TIMEOUT_MS = 8000;
|
|
9
|
+
const DEFAULT_VIEWPORT_SETTLE_MS = 120;
|
|
10
|
+
const DEFAULT_VIEWPORT_ATTEMPTS = 1;
|
|
11
|
+
const DEFAULT_VIEWPORT_TOLERANCE_PX = 3;
|
|
12
|
+
|
|
13
|
+
function sleep(ms) {
|
|
14
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function withTimeout(promise, timeoutMs, timeoutMessage) {
|
|
18
|
+
let timer = null;
|
|
19
|
+
return Promise.race([
|
|
20
|
+
promise,
|
|
21
|
+
new Promise((_, reject) => {
|
|
22
|
+
timer = setTimeout(() => reject(new Error(timeoutMessage)), timeoutMs);
|
|
23
|
+
}),
|
|
24
|
+
]).finally(() => {
|
|
25
|
+
if (timer) clearTimeout(timer);
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function resolveTimeoutMs(raw, fallback) {
|
|
30
|
+
const parsed = Number(raw);
|
|
31
|
+
if (!Number.isFinite(parsed) || parsed <= 0) return fallback;
|
|
32
|
+
return Math.max(500, Math.floor(parsed));
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function resolveViewportSyncConfig({ params = {}, inherited = null }) {
|
|
36
|
+
const enabled = params.syncViewport !== undefined
|
|
37
|
+
? params.syncViewport !== false
|
|
38
|
+
: inherited?.enabled !== false;
|
|
39
|
+
return {
|
|
40
|
+
enabled,
|
|
41
|
+
apiTimeoutMs: resolveTimeoutMs(
|
|
42
|
+
params.viewportApiTimeoutMs ?? inherited?.apiTimeoutMs,
|
|
43
|
+
DEFAULT_VIEWPORT_API_TIMEOUT_MS,
|
|
44
|
+
),
|
|
45
|
+
settleMs: Math.max(
|
|
46
|
+
0,
|
|
47
|
+
Number(params.viewportSettleMs ?? inherited?.settleMs ?? DEFAULT_VIEWPORT_SETTLE_MS) || DEFAULT_VIEWPORT_SETTLE_MS,
|
|
48
|
+
),
|
|
49
|
+
attempts: Math.max(
|
|
50
|
+
1,
|
|
51
|
+
Number(params.viewportAttempts ?? inherited?.attempts ?? DEFAULT_VIEWPORT_ATTEMPTS) || DEFAULT_VIEWPORT_ATTEMPTS,
|
|
52
|
+
),
|
|
53
|
+
tolerancePx: Math.max(
|
|
54
|
+
0,
|
|
55
|
+
Number(params.viewportTolerancePx ?? inherited?.tolerancePx ?? DEFAULT_VIEWPORT_TOLERANCE_PX) || DEFAULT_VIEWPORT_TOLERANCE_PX,
|
|
56
|
+
),
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
async function callApiWithTimeout(action, payload, timeoutMs) {
|
|
61
|
+
const effectiveTimeoutMs = resolveTimeoutMs(timeoutMs, DEFAULT_API_TIMEOUT_MS);
|
|
62
|
+
return withTimeout(
|
|
63
|
+
callAPI(action, payload),
|
|
64
|
+
effectiveTimeoutMs,
|
|
65
|
+
`${action} timeout after ${effectiveTimeoutMs}ms`,
|
|
66
|
+
);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
async function syncTabViewportIfNeeded({ profileId, syncConfig }) {
|
|
70
|
+
if (!syncConfig?.enabled) {
|
|
71
|
+
return { ok: true, code: 'OPERATION_SKIPPED', message: 'sync viewport disabled' };
|
|
72
|
+
}
|
|
73
|
+
return executeViewportOperation({
|
|
74
|
+
profileId,
|
|
75
|
+
action: 'sync_window_viewport',
|
|
76
|
+
params: {
|
|
77
|
+
followWindow: true,
|
|
78
|
+
settleMs: syncConfig.settleMs,
|
|
79
|
+
attempts: syncConfig.attempts,
|
|
80
|
+
tolerancePx: syncConfig.tolerancePx,
|
|
81
|
+
apiTimeoutMs: syncConfig.apiTimeoutMs,
|
|
82
|
+
},
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function parseUrl(raw) {
|
|
87
|
+
try {
|
|
88
|
+
return new URL(String(raw || ''));
|
|
89
|
+
} catch {
|
|
90
|
+
return null;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function normalizeSeedUrl(rawSeedUrl) {
|
|
95
|
+
const parsed = parseUrl(rawSeedUrl);
|
|
96
|
+
if (!parsed) return String(rawSeedUrl || '').trim();
|
|
97
|
+
const host = String(parsed.hostname || '').toLowerCase();
|
|
98
|
+
const pathname = String(parsed.pathname || '');
|
|
99
|
+
const isXhsHost = host.includes('xiaohongshu.com');
|
|
100
|
+
const isXhsDetailPath = /^\/explore\/[^/]+$/.test(pathname);
|
|
101
|
+
if (isXhsHost && isXhsDetailPath) {
|
|
102
|
+
parsed.pathname = '/explore';
|
|
103
|
+
parsed.search = '';
|
|
104
|
+
parsed.hash = '';
|
|
105
|
+
return parsed.toString();
|
|
106
|
+
}
|
|
107
|
+
return parsed.toString();
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function isXhsDetailUrl(rawUrl) {
|
|
111
|
+
const parsed = parseUrl(rawUrl);
|
|
112
|
+
if (!parsed) return false;
|
|
113
|
+
const host = String(parsed.hostname || '').toLowerCase();
|
|
114
|
+
const pathname = String(parsed.pathname || '');
|
|
115
|
+
return host.includes('xiaohongshu.com') && /^\/explore\/[^/]+$/.test(pathname);
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
async function resolveXhsListUrlFromState(profileId, timeoutMs) {
|
|
119
|
+
try {
|
|
120
|
+
const payload = await callApiWithTimeout('evaluate', {
|
|
121
|
+
profileId,
|
|
122
|
+
script: `(() => {
|
|
123
|
+
const STATE_KEY = '__camoXhsState';
|
|
124
|
+
const safeString = (value) => typeof value === 'string' ? value.trim() : '';
|
|
125
|
+
let state = window.__camoXhsState && typeof window.__camoXhsState === 'object'
|
|
126
|
+
? window.__camoXhsState
|
|
127
|
+
: null;
|
|
128
|
+
if (!state) {
|
|
129
|
+
try {
|
|
130
|
+
const stored = localStorage.getItem(STATE_KEY);
|
|
131
|
+
if (stored) state = JSON.parse(stored);
|
|
132
|
+
} catch {}
|
|
133
|
+
}
|
|
134
|
+
const lastListUrl = safeString(state?.lastListUrl);
|
|
135
|
+
return { lastListUrl };
|
|
136
|
+
})()`,
|
|
137
|
+
}, timeoutMs);
|
|
138
|
+
const result = payload?.result || payload || {};
|
|
139
|
+
const candidate = String(result?.lastListUrl || '').trim();
|
|
140
|
+
return candidate || null;
|
|
141
|
+
} catch {
|
|
142
|
+
return null;
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
function shouldNavigateToSeed(currentUrl, seedUrl) {
|
|
147
|
+
const current = parseUrl(currentUrl);
|
|
148
|
+
const seed = parseUrl(seedUrl);
|
|
149
|
+
if (!seed) return false;
|
|
150
|
+
if (!current) return true;
|
|
151
|
+
const currentPath = String(current.pathname || '');
|
|
152
|
+
const seedPath = String(seed.pathname || '');
|
|
153
|
+
const currentIsXhsDetail = /^\/explore\/[^/]+$/.test(currentPath);
|
|
154
|
+
if (current.protocol === 'about:') return true;
|
|
155
|
+
if (current.origin !== seed.origin) return true;
|
|
156
|
+
if (seedPath.includes('/search_result') && !currentPath.includes('/search_result')) return true;
|
|
157
|
+
if (seedPath === '/explore' && currentIsXhsDetail) return true;
|
|
158
|
+
if (seedPath.includes('/explore') && !currentPath.includes('/explore') && !currentPath.includes('/search_result')) return true;
|
|
159
|
+
return false;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
async function seedNewestTabIfNeeded({
|
|
163
|
+
profileId,
|
|
164
|
+
seedUrl,
|
|
165
|
+
openDelayMs,
|
|
166
|
+
apiTimeoutMs,
|
|
167
|
+
navigationTimeoutMs,
|
|
168
|
+
syncConfig,
|
|
169
|
+
}) {
|
|
170
|
+
if (!seedUrl) return;
|
|
171
|
+
const listed = await callApiWithTimeout('page:list', { profileId }, apiTimeoutMs);
|
|
172
|
+
const { pages, activeIndex } = extractPageList(listed);
|
|
173
|
+
const newest = [...pages]
|
|
174
|
+
.filter((page) => Number.isFinite(Number(page?.index)))
|
|
175
|
+
.sort((a, b) => Number(b.index) - Number(a.index))[0];
|
|
176
|
+
if (!newest) return;
|
|
177
|
+
|
|
178
|
+
const targetIndex = Number(newest.index);
|
|
179
|
+
if (Number(activeIndex) !== targetIndex) {
|
|
180
|
+
await callApiWithTimeout('page:switch', { profileId, index: targetIndex }, apiTimeoutMs);
|
|
181
|
+
}
|
|
182
|
+
if (shouldNavigateToSeed(newest.url, seedUrl)) {
|
|
183
|
+
await callApiWithTimeout('goto', { profileId, url: seedUrl }, navigationTimeoutMs);
|
|
184
|
+
if (openDelayMs > 0) await sleep(Math.min(openDelayMs, 1200));
|
|
185
|
+
}
|
|
186
|
+
const syncResult = await syncTabViewportIfNeeded({ profileId, syncConfig });
|
|
187
|
+
if (!syncResult?.ok) {
|
|
188
|
+
throw new Error(syncResult?.message || 'sync_window_viewport failed');
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
async function tryOpenTabWithShortcut(profileId, timeoutMs) {
|
|
193
|
+
const candidates = process.platform === 'darwin'
|
|
194
|
+
? ['Meta+t', 'Control+t']
|
|
195
|
+
: ['Control+t', 'Meta+t'];
|
|
196
|
+
let lastError = null;
|
|
197
|
+
for (const key of candidates) {
|
|
198
|
+
try {
|
|
199
|
+
await callApiWithTimeout('keyboard:press', { profileId, key }, timeoutMs);
|
|
200
|
+
return { ok: true, key };
|
|
201
|
+
} catch (err) {
|
|
202
|
+
lastError = err;
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
return { ok: false, error: lastError };
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
async function openTabBestEffort({
|
|
209
|
+
profileId,
|
|
210
|
+
seedUrl,
|
|
211
|
+
openDelayMs,
|
|
212
|
+
beforeCount,
|
|
213
|
+
apiTimeoutMs,
|
|
214
|
+
navigationTimeoutMs,
|
|
215
|
+
shortcutTimeoutMs,
|
|
216
|
+
syncConfig,
|
|
217
|
+
}) {
|
|
218
|
+
const hasNewTab = async () => {
|
|
219
|
+
const listed = await callApiWithTimeout('page:list', { profileId }, apiTimeoutMs);
|
|
220
|
+
const { pages } = extractPageList(listed);
|
|
221
|
+
return pages.length > beforeCount;
|
|
222
|
+
};
|
|
223
|
+
const settle = async () => {
|
|
224
|
+
if (openDelayMs > 0) {
|
|
225
|
+
await new Promise((resolve) => setTimeout(resolve, openDelayMs));
|
|
226
|
+
}
|
|
227
|
+
};
|
|
228
|
+
|
|
229
|
+
let openError = null;
|
|
230
|
+
const shortcutResult = await tryOpenTabWithShortcut(profileId, shortcutTimeoutMs);
|
|
231
|
+
if (shortcutResult.ok) {
|
|
232
|
+
await settle();
|
|
233
|
+
if (await hasNewTab()) {
|
|
234
|
+
await seedNewestTabIfNeeded({
|
|
235
|
+
profileId,
|
|
236
|
+
seedUrl,
|
|
237
|
+
openDelayMs,
|
|
238
|
+
apiTimeoutMs,
|
|
239
|
+
navigationTimeoutMs,
|
|
240
|
+
syncConfig,
|
|
241
|
+
});
|
|
242
|
+
return { ok: true, mode: `shortcut:${shortcutResult.key}`, error: null };
|
|
243
|
+
}
|
|
244
|
+
} else {
|
|
245
|
+
openError = shortcutResult.error;
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
const payload = seedUrl
|
|
249
|
+
? { profileId, url: seedUrl }
|
|
250
|
+
: { profileId };
|
|
251
|
+
try {
|
|
252
|
+
await callApiWithTimeout('newPage', payload, apiTimeoutMs);
|
|
253
|
+
await settle();
|
|
254
|
+
if (await hasNewTab()) {
|
|
255
|
+
await seedNewestTabIfNeeded({
|
|
256
|
+
profileId,
|
|
257
|
+
seedUrl,
|
|
258
|
+
openDelayMs,
|
|
259
|
+
apiTimeoutMs,
|
|
260
|
+
navigationTimeoutMs,
|
|
261
|
+
syncConfig,
|
|
262
|
+
});
|
|
263
|
+
return { ok: true, mode: 'newPage', error: null };
|
|
264
|
+
}
|
|
265
|
+
} catch (err) {
|
|
266
|
+
openError = err;
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
try {
|
|
270
|
+
const popupResult = await callApiWithTimeout('evaluate', {
|
|
271
|
+
profileId,
|
|
272
|
+
script: `(() => {
|
|
273
|
+
const popup = window.open(${JSON.stringify(seedUrl || 'about:blank')}, '_blank');
|
|
274
|
+
return { opened: !!popup };
|
|
275
|
+
})()`,
|
|
276
|
+
}, apiTimeoutMs);
|
|
277
|
+
const popupData = popupResult?.result || popupResult || {};
|
|
278
|
+
if (Boolean(popupData?.opened || popupData?.ok)) {
|
|
279
|
+
await settle();
|
|
280
|
+
if (await hasNewTab()) {
|
|
281
|
+
await seedNewestTabIfNeeded({
|
|
282
|
+
profileId,
|
|
283
|
+
seedUrl,
|
|
284
|
+
openDelayMs,
|
|
285
|
+
apiTimeoutMs,
|
|
286
|
+
navigationTimeoutMs,
|
|
287
|
+
syncConfig,
|
|
288
|
+
});
|
|
289
|
+
return { ok: true, mode: 'window.open', error: null };
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
} catch (err) {
|
|
293
|
+
openError = err;
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
return { ok: false, mode: null, error: openError };
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
export async function executeTabPoolOperation({ profileId, action, params = {}, context = {} }) {
|
|
300
|
+
const runtimeState = context?.runtime && typeof context.runtime === 'object' ? context.runtime : null;
|
|
301
|
+
|
|
302
|
+
if (action === 'ensure_tab_pool') {
|
|
303
|
+
const tabCount = Math.max(1, Number(params.tabCount ?? params.count ?? 1) || 1);
|
|
304
|
+
const openDelayMs = Math.max(0, Number(params.openDelayMs ?? 350) || 350);
|
|
305
|
+
const normalizeTabs = params.normalizeTabs === true;
|
|
306
|
+
const apiTimeoutMs = resolveTimeoutMs(params.apiTimeoutMs, DEFAULT_API_TIMEOUT_MS);
|
|
307
|
+
const navigationTimeoutMs = resolveTimeoutMs(params.navigationTimeoutMs ?? params.gotoTimeoutMs, DEFAULT_NAV_TIMEOUT_MS);
|
|
308
|
+
const shortcutTimeoutMs = resolveTimeoutMs(params.shortcutTimeoutMs, SHORTCUT_OPEN_TIMEOUT_MS);
|
|
309
|
+
const syncConfig = resolveViewportSyncConfig({ params });
|
|
310
|
+
const configuredSeedUrl = normalizeSeedUrl(String(params.url || '').trim());
|
|
311
|
+
|
|
312
|
+
let listed = await callApiWithTimeout('page:list', { profileId }, apiTimeoutMs);
|
|
313
|
+
let { pages, activeIndex } = extractPageList(listed);
|
|
314
|
+
const defaultSeedUrl = String(
|
|
315
|
+
configuredSeedUrl
|
|
316
|
+
|| pages.find((item) => item?.active)?.url
|
|
317
|
+
|| pages[0]?.url
|
|
318
|
+
|| '',
|
|
319
|
+
).trim();
|
|
320
|
+
let fallbackSeedUrl = defaultSeedUrl;
|
|
321
|
+
if (!configuredSeedUrl && isXhsDetailUrl(defaultSeedUrl)) {
|
|
322
|
+
const recoveredListUrl = await resolveXhsListUrlFromState(profileId, apiTimeoutMs);
|
|
323
|
+
if (recoveredListUrl) fallbackSeedUrl = recoveredListUrl;
|
|
324
|
+
}
|
|
325
|
+
fallbackSeedUrl = normalizeSeedUrl(fallbackSeedUrl);
|
|
326
|
+
|
|
327
|
+
while (pages.length < tabCount) {
|
|
328
|
+
const beforeCount = pages.length;
|
|
329
|
+
const openResult = await openTabBestEffort({
|
|
330
|
+
profileId,
|
|
331
|
+
seedUrl: fallbackSeedUrl,
|
|
332
|
+
openDelayMs,
|
|
333
|
+
beforeCount,
|
|
334
|
+
apiTimeoutMs,
|
|
335
|
+
navigationTimeoutMs,
|
|
336
|
+
shortcutTimeoutMs,
|
|
337
|
+
syncConfig,
|
|
338
|
+
});
|
|
339
|
+
listed = await callApiWithTimeout('page:list', { profileId }, apiTimeoutMs);
|
|
340
|
+
({ pages, activeIndex } = extractPageList(listed));
|
|
341
|
+
if (!openResult.ok || pages.length <= beforeCount) {
|
|
342
|
+
return asErrorPayload('OPERATION_FAILED', 'new_tab_failed', {
|
|
343
|
+
tabCount,
|
|
344
|
+
beforeCount,
|
|
345
|
+
afterCount: pages.length,
|
|
346
|
+
seedUrl: fallbackSeedUrl || null,
|
|
347
|
+
mode: openResult.mode || null,
|
|
348
|
+
reason: openResult.error?.message || 'cannot open new tab',
|
|
349
|
+
});
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
const sortedPages = [...pages].sort((a, b) => Number(a.index) - Number(b.index));
|
|
354
|
+
const activePage = sortedPages.find((item) => Number(item.index) === Number(activeIndex)) || null;
|
|
355
|
+
const selected = [
|
|
356
|
+
...(activePage ? [activePage] : []),
|
|
357
|
+
...sortedPages.filter((item) => Number(item.index) !== Number(activeIndex)),
|
|
358
|
+
].slice(0, tabCount);
|
|
359
|
+
|
|
360
|
+
const forceNormalizeFromDetail = Boolean(!configuredSeedUrl && isXhsDetailUrl(defaultSeedUrl));
|
|
361
|
+
const shouldNormalizeSlots = Boolean(fallbackSeedUrl) && (normalizeTabs || forceNormalizeFromDetail);
|
|
362
|
+
|
|
363
|
+
if (shouldNormalizeSlots) {
|
|
364
|
+
for (const page of selected) {
|
|
365
|
+
const pageIndex = Number(page.index);
|
|
366
|
+
if (!Number.isFinite(pageIndex)) continue;
|
|
367
|
+
await callApiWithTimeout('page:switch', { profileId, index: pageIndex }, apiTimeoutMs);
|
|
368
|
+
if (shouldNavigateToSeed(page.url, fallbackSeedUrl)) {
|
|
369
|
+
await callApiWithTimeout('goto', { profileId, url: fallbackSeedUrl }, navigationTimeoutMs);
|
|
370
|
+
if (openDelayMs > 0) await sleep(Math.min(openDelayMs, 1200));
|
|
371
|
+
}
|
|
372
|
+
const syncResult = await syncTabViewportIfNeeded({ profileId, syncConfig });
|
|
373
|
+
if (!syncResult?.ok) {
|
|
374
|
+
return asErrorPayload('OPERATION_FAILED', 'tab viewport sync failed', {
|
|
375
|
+
pageIndex,
|
|
376
|
+
syncResult,
|
|
377
|
+
});
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
listed = await callApiWithTimeout('page:list', { profileId }, apiTimeoutMs);
|
|
381
|
+
({ pages } = extractPageList(listed));
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
const refreshedByIndex = new Map(
|
|
385
|
+
pages.map((page) => [Number(page.index), page]),
|
|
386
|
+
);
|
|
387
|
+
const slots = selected.map((page, idx) => ({
|
|
388
|
+
slotIndex: idx + 1,
|
|
389
|
+
tabRealIndex: Number(page.index),
|
|
390
|
+
url: String(refreshedByIndex.get(Number(page.index))?.url || page.url || ''),
|
|
391
|
+
}));
|
|
392
|
+
|
|
393
|
+
if (slots.length > 0) {
|
|
394
|
+
await callApiWithTimeout('page:switch', {
|
|
395
|
+
profileId,
|
|
396
|
+
index: Number(slots[0].tabRealIndex),
|
|
397
|
+
}, apiTimeoutMs);
|
|
398
|
+
const syncResult = await syncTabViewportIfNeeded({ profileId, syncConfig });
|
|
399
|
+
if (!syncResult?.ok) {
|
|
400
|
+
return asErrorPayload('OPERATION_FAILED', 'tab viewport sync failed', { slotIndex: 1, syncResult });
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
if (runtimeState) {
|
|
405
|
+
runtimeState.tabPool = {
|
|
406
|
+
slots,
|
|
407
|
+
cursor: 0,
|
|
408
|
+
count: slots.length,
|
|
409
|
+
syncConfig,
|
|
410
|
+
apiTimeoutMs,
|
|
411
|
+
initializedAt: new Date().toISOString(),
|
|
412
|
+
};
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
return {
|
|
416
|
+
ok: true,
|
|
417
|
+
code: 'OPERATION_DONE',
|
|
418
|
+
message: 'ensure_tab_pool done',
|
|
419
|
+
data: {
|
|
420
|
+
tabCount: slots.length,
|
|
421
|
+
normalized: shouldNormalizeSlots,
|
|
422
|
+
slots,
|
|
423
|
+
pages: selected,
|
|
424
|
+
},
|
|
425
|
+
};
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
if (action === 'tab_pool_switch_next') {
|
|
429
|
+
const settleMs = Math.max(0, Number(params.settleMs ?? params.waitMs ?? 450) || 450);
|
|
430
|
+
const pool = runtimeState?.tabPool;
|
|
431
|
+
const slots = normalizeArray(pool?.slots);
|
|
432
|
+
if (!runtimeState || slots.length === 0) {
|
|
433
|
+
return asErrorPayload('TAB_POOL_NOT_INITIALIZED', 'tab_pool_switch_next requires ensure_tab_pool first');
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
const cursor = Math.max(0, Number(pool.cursor) || 0);
|
|
437
|
+
const selected = slots[cursor % slots.length];
|
|
438
|
+
runtimeState.tabPool.cursor = (cursor + 1) % slots.length;
|
|
439
|
+
const targetIndex = Number(selected.tabRealIndex);
|
|
440
|
+
const apiTimeoutMs = resolveTimeoutMs(params.apiTimeoutMs ?? pool?.apiTimeoutMs, DEFAULT_API_TIMEOUT_MS);
|
|
441
|
+
const syncConfig = resolveViewportSyncConfig({ params, inherited: pool?.syncConfig });
|
|
442
|
+
|
|
443
|
+
const beforeList = await callApiWithTimeout('page:list', { profileId }, apiTimeoutMs);
|
|
444
|
+
const { activeIndex: beforeActiveIndex } = extractPageList(beforeList);
|
|
445
|
+
if (Number(beforeActiveIndex) !== targetIndex) {
|
|
446
|
+
await callApiWithTimeout('page:switch', {
|
|
447
|
+
profileId,
|
|
448
|
+
index: targetIndex,
|
|
449
|
+
}, apiTimeoutMs);
|
|
450
|
+
const syncResult = await syncTabViewportIfNeeded({ profileId, syncConfig });
|
|
451
|
+
if (!syncResult?.ok) {
|
|
452
|
+
return asErrorPayload('OPERATION_FAILED', 'tab viewport sync failed', {
|
|
453
|
+
targetIndex,
|
|
454
|
+
syncResult,
|
|
455
|
+
});
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
if (settleMs > 0) {
|
|
460
|
+
await new Promise((resolve) => setTimeout(resolve, settleMs));
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
const listed = await callApiWithTimeout('page:list', { profileId }, apiTimeoutMs);
|
|
464
|
+
const { activeIndex } = extractPageList(listed);
|
|
465
|
+
if (Number(activeIndex) !== targetIndex) {
|
|
466
|
+
return asErrorPayload('OPERATION_FAILED', 'tab_pool_switch_next did not activate target tab', {
|
|
467
|
+
expectedIndex: targetIndex,
|
|
468
|
+
activeIndex,
|
|
469
|
+
selected,
|
|
470
|
+
});
|
|
471
|
+
}
|
|
472
|
+
runtimeState.currentTab = {
|
|
473
|
+
slotIndex: selected.slotIndex,
|
|
474
|
+
tabRealIndex: targetIndex,
|
|
475
|
+
activeIndex,
|
|
476
|
+
};
|
|
477
|
+
|
|
478
|
+
return {
|
|
479
|
+
ok: true,
|
|
480
|
+
code: 'OPERATION_DONE',
|
|
481
|
+
message: 'tab_pool_switch_next done',
|
|
482
|
+
data: {
|
|
483
|
+
currentTab: runtimeState.currentTab,
|
|
484
|
+
cursor: runtimeState.tabPool.cursor,
|
|
485
|
+
slots,
|
|
486
|
+
},
|
|
487
|
+
};
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
if (action === 'tab_pool_switch_slot') {
|
|
491
|
+
const pool = runtimeState?.tabPool;
|
|
492
|
+
const slots = normalizeArray(pool?.slots);
|
|
493
|
+
if (!runtimeState || slots.length === 0) {
|
|
494
|
+
return asErrorPayload('TAB_POOL_NOT_INITIALIZED', 'tab_pool_switch_slot requires ensure_tab_pool first');
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
const requestedSlotIndex = Number(params.slotIndex ?? params.slot ?? 1);
|
|
498
|
+
if (!Number.isFinite(requestedSlotIndex) || requestedSlotIndex < 1) {
|
|
499
|
+
return asErrorPayload('OPERATION_FAILED', 'tab_pool_switch_slot requires params.slotIndex >= 1');
|
|
500
|
+
}
|
|
501
|
+
const slot = slots.find((item) => Number(item.slotIndex) === Math.floor(requestedSlotIndex));
|
|
502
|
+
if (!slot) {
|
|
503
|
+
return asErrorPayload('OPERATION_FAILED', `tab_pool slot not found: ${requestedSlotIndex}`);
|
|
504
|
+
}
|
|
505
|
+
const targetIndex = Number(slot.tabRealIndex);
|
|
506
|
+
const apiTimeoutMs = resolveTimeoutMs(params.apiTimeoutMs ?? pool?.apiTimeoutMs, DEFAULT_API_TIMEOUT_MS);
|
|
507
|
+
const syncConfig = resolveViewportSyncConfig({ params, inherited: pool?.syncConfig });
|
|
508
|
+
|
|
509
|
+
const beforeList = await callApiWithTimeout('page:list', { profileId }, apiTimeoutMs);
|
|
510
|
+
const { activeIndex: beforeActiveIndex } = extractPageList(beforeList);
|
|
511
|
+
if (Number(beforeActiveIndex) !== targetIndex) {
|
|
512
|
+
await callApiWithTimeout('page:switch', { profileId, index: targetIndex }, apiTimeoutMs);
|
|
513
|
+
const syncResult = await syncTabViewportIfNeeded({ profileId, syncConfig });
|
|
514
|
+
if (!syncResult?.ok) {
|
|
515
|
+
return asErrorPayload('OPERATION_FAILED', 'tab viewport sync failed', {
|
|
516
|
+
targetIndex,
|
|
517
|
+
syncResult,
|
|
518
|
+
});
|
|
519
|
+
}
|
|
520
|
+
}
|
|
521
|
+
const listed = await callApiWithTimeout('page:list', { profileId }, apiTimeoutMs);
|
|
522
|
+
const { activeIndex } = extractPageList(listed);
|
|
523
|
+
if (Number(activeIndex) !== targetIndex) {
|
|
524
|
+
return asErrorPayload('OPERATION_FAILED', 'tab_pool_switch_slot did not activate target tab', {
|
|
525
|
+
expectedIndex: targetIndex,
|
|
526
|
+
activeIndex,
|
|
527
|
+
slot,
|
|
528
|
+
});
|
|
529
|
+
}
|
|
530
|
+
runtimeState.currentTab = {
|
|
531
|
+
slotIndex: slot.slotIndex,
|
|
532
|
+
tabRealIndex: targetIndex,
|
|
533
|
+
activeIndex,
|
|
534
|
+
};
|
|
535
|
+
return {
|
|
536
|
+
ok: true,
|
|
537
|
+
code: 'OPERATION_DONE',
|
|
538
|
+
message: 'tab_pool_switch_slot done',
|
|
539
|
+
data: { currentTab: runtimeState.currentTab, slots },
|
|
540
|
+
};
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
return asErrorPayload('UNSUPPORTED_OPERATION', `Unsupported tab operation: ${action}`);
|
|
544
|
+
}
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
import { callAPI } from '../../../utils/browser-service.mjs';
|
|
2
|
+
import { asErrorPayload, getCurrentUrl, normalizeArray } from '../utils.mjs';
|
|
3
|
+
|
|
4
|
+
function callWithTimeout(action, payload, timeoutMs) {
|
|
5
|
+
let timer = null;
|
|
6
|
+
return Promise.race([
|
|
7
|
+
callAPI(action, payload),
|
|
8
|
+
new Promise((_, reject) => {
|
|
9
|
+
timer = setTimeout(() => {
|
|
10
|
+
reject(new Error(`${action} timeout after ${timeoutMs}ms`));
|
|
11
|
+
}, timeoutMs);
|
|
12
|
+
}),
|
|
13
|
+
]).finally(() => {
|
|
14
|
+
if (timer) clearTimeout(timer);
|
|
15
|
+
});
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export async function executeViewportOperation({ profileId, action, params = {} }) {
|
|
19
|
+
if (action === 'get_current_url') {
|
|
20
|
+
const url = await getCurrentUrl(profileId);
|
|
21
|
+
const includes = normalizeArray(params.includes || params.urlIncludes).map((item) => String(item));
|
|
22
|
+
const excludes = normalizeArray(params.excludes || params.urlExcludes).map((item) => String(item));
|
|
23
|
+
const missing = includes.filter((token) => !url.includes(token));
|
|
24
|
+
const forbidden = excludes.filter((token) => url.includes(token));
|
|
25
|
+
if (missing.length > 0 || forbidden.length > 0) {
|
|
26
|
+
return asErrorPayload('URL_MISMATCH', 'current url validation failed', {
|
|
27
|
+
url,
|
|
28
|
+
includes,
|
|
29
|
+
excludes,
|
|
30
|
+
missing,
|
|
31
|
+
forbidden,
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
return { ok: true, code: 'OPERATION_DONE', message: 'get_current_url done', data: { url } };
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
if (action === 'sync_window_viewport') {
|
|
38
|
+
const rawWidth = Number(params.width ?? params.viewportWidth);
|
|
39
|
+
const rawHeight = Number(params.height ?? params.viewportHeight);
|
|
40
|
+
const hasTargetViewport = Number.isFinite(rawWidth) && Number.isFinite(rawHeight);
|
|
41
|
+
const width = hasTargetViewport ? Math.max(320, rawWidth) : null;
|
|
42
|
+
const height = hasTargetViewport ? Math.max(240, rawHeight) : null;
|
|
43
|
+
const followWindow = params.followWindow !== false;
|
|
44
|
+
const settleMs = Math.max(0, Number(params.settleMs ?? 180) || 180);
|
|
45
|
+
const attempts = Math.max(1, Number(params.attempts ?? 3) || 3);
|
|
46
|
+
const tolerance = Math.max(0, Number(params.tolerancePx ?? 3) || 3);
|
|
47
|
+
const apiTimeoutMs = Math.max(1000, Number(params.apiTimeoutMs ?? 8000) || 8000);
|
|
48
|
+
|
|
49
|
+
const probeWindow = async () => {
|
|
50
|
+
const probe = await callWithTimeout('evaluate', {
|
|
51
|
+
profileId,
|
|
52
|
+
script: '({ innerWidth: window.innerWidth, innerHeight: window.innerHeight, outerWidth: window.outerWidth, outerHeight: window.outerHeight })',
|
|
53
|
+
}, apiTimeoutMs);
|
|
54
|
+
return probe?.result || {};
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
let measured = await probeWindow();
|
|
58
|
+
if (followWindow && !hasTargetViewport) {
|
|
59
|
+
const innerWidth = Math.max(320, Number(measured.innerWidth || 0) || 1280);
|
|
60
|
+
const innerHeight = Math.max(240, Number(measured.innerHeight || 0) || 720);
|
|
61
|
+
const outerWidth = Math.max(320, Number(measured.outerWidth || 0) || innerWidth);
|
|
62
|
+
const outerHeight = Math.max(240, Number(measured.outerHeight || 0) || innerHeight);
|
|
63
|
+
const rawDeltaW = Math.max(0, outerWidth - innerWidth);
|
|
64
|
+
const rawDeltaH = Math.max(0, outerHeight - innerHeight);
|
|
65
|
+
const frameW = rawDeltaW > 400 ? 16 : Math.min(rawDeltaW, 120);
|
|
66
|
+
const frameH = rawDeltaH > 400 ? 88 : Math.min(rawDeltaH, 180);
|
|
67
|
+
const followWidth = Math.max(320, outerWidth - frameW);
|
|
68
|
+
const followHeight = Math.max(240, outerHeight - frameH);
|
|
69
|
+
|
|
70
|
+
await callWithTimeout('page:setViewport', { profileId, width: followWidth, height: followHeight }, apiTimeoutMs);
|
|
71
|
+
const synced = await probeWindow();
|
|
72
|
+
return {
|
|
73
|
+
ok: true,
|
|
74
|
+
code: 'OPERATION_DONE',
|
|
75
|
+
message: 'sync_window_viewport follow window done',
|
|
76
|
+
data: {
|
|
77
|
+
followWindow: true,
|
|
78
|
+
viewport: { width: followWidth, height: followHeight },
|
|
79
|
+
frame: { width: frameW, height: frameH },
|
|
80
|
+
measured: synced,
|
|
81
|
+
},
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
if (!hasTargetViewport) {
|
|
86
|
+
return asErrorPayload('OPERATION_FAILED', 'sync_window_viewport requires width/height when followWindow=false');
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
await callWithTimeout('page:setViewport', { profileId, width, height }, apiTimeoutMs);
|
|
90
|
+
|
|
91
|
+
for (let i = 0; i < attempts; i += 1) {
|
|
92
|
+
measured = await probeWindow();
|
|
93
|
+
const innerWidth = Number(measured.innerWidth || 0);
|
|
94
|
+
const innerHeight = Number(measured.innerHeight || 0);
|
|
95
|
+
const widthOk = Math.abs(innerWidth - width) <= tolerance;
|
|
96
|
+
const heightOk = Math.abs(innerHeight - height) <= tolerance;
|
|
97
|
+
if (widthOk && heightOk) {
|
|
98
|
+
return {
|
|
99
|
+
ok: true,
|
|
100
|
+
code: 'OPERATION_DONE',
|
|
101
|
+
message: 'sync_window_viewport done',
|
|
102
|
+
data: {
|
|
103
|
+
width,
|
|
104
|
+
height,
|
|
105
|
+
followWindow,
|
|
106
|
+
attempts: i + 1,
|
|
107
|
+
measured,
|
|
108
|
+
matched: true,
|
|
109
|
+
},
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
const outerWidth = Number(measured.outerWidth || 0);
|
|
114
|
+
const outerHeight = Number(measured.outerHeight || 0);
|
|
115
|
+
const targetWindowWidth = Math.max(width + 16, outerWidth + (width - innerWidth));
|
|
116
|
+
const targetWindowHeight = Math.max(height + 80, outerHeight + (height - innerHeight));
|
|
117
|
+
await callWithTimeout('window:resize', {
|
|
118
|
+
profileId,
|
|
119
|
+
width: Math.round(targetWindowWidth),
|
|
120
|
+
height: Math.round(targetWindowHeight),
|
|
121
|
+
}, apiTimeoutMs);
|
|
122
|
+
if (settleMs > 0) await new Promise((resolve) => setTimeout(resolve, settleMs));
|
|
123
|
+
await callWithTimeout('page:setViewport', { profileId, width, height }, apiTimeoutMs);
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
return {
|
|
127
|
+
ok: true,
|
|
128
|
+
code: 'OPERATION_DONE',
|
|
129
|
+
message: 'sync_window_viewport best effort done',
|
|
130
|
+
data: {
|
|
131
|
+
width,
|
|
132
|
+
height,
|
|
133
|
+
followWindow,
|
|
134
|
+
attempts,
|
|
135
|
+
measured,
|
|
136
|
+
matched: Math.abs(Number(measured.innerWidth || 0) - width) <= tolerance
|
|
137
|
+
&& Math.abs(Number(measured.innerHeight || 0) - height) <= tolerance,
|
|
138
|
+
},
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
return asErrorPayload('UNSUPPORTED_OPERATION', `Unsupported viewport operation: ${action}`);
|
|
143
|
+
}
|