@web-auto/camo 0.1.26 → 0.2.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.
Files changed (117) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +586 -586
  3. package/bin/browser-service.mjs +11 -11
  4. package/bin/camo.mjs +22 -22
  5. package/package.json +48 -48
  6. package/scripts/build.mjs +19 -19
  7. package/scripts/bump-version.mjs +34 -34
  8. package/scripts/check-file-size.mjs +80 -80
  9. package/scripts/file-size-policy.json +12 -2
  10. package/scripts/install.mjs +76 -76
  11. package/scripts/release.sh +54 -54
  12. package/src/autoscript/action-providers/index.mjs +6 -6
  13. package/src/autoscript/impact-engine.mjs +78 -78
  14. package/src/autoscript/runtime.mjs +1017 -1017
  15. package/src/autoscript/schema.mjs +376 -376
  16. package/src/cli.mjs +405 -405
  17. package/src/commands/attach.mjs +141 -141
  18. package/src/commands/autoscript.mjs +1011 -1011
  19. package/src/commands/browser.mjs +1255 -1257
  20. package/src/commands/container.mjs +401 -401
  21. package/src/commands/cookies.mjs +69 -69
  22. package/src/commands/create.mjs +98 -98
  23. package/src/commands/devtools.mjs +349 -349
  24. package/src/commands/events.mjs +152 -152
  25. package/src/commands/highlight-mode.mjs +24 -24
  26. package/src/commands/init.mjs +68 -68
  27. package/src/commands/lifecycle.mjs +275 -275
  28. package/src/commands/mouse.mjs +45 -45
  29. package/src/commands/profile.mjs +46 -46
  30. package/src/commands/record.mjs +115 -115
  31. package/src/commands/system.mjs +14 -14
  32. package/src/commands/window.mjs +123 -123
  33. package/src/container/change-notifier.mjs +362 -362
  34. package/src/container/element-filter.mjs +143 -143
  35. package/src/container/index.mjs +3 -3
  36. package/src/container/runtime-core/checkpoint.mjs +209 -209
  37. package/src/container/runtime-core/index.mjs +21 -21
  38. package/src/container/runtime-core/operations/index.mjs +774 -774
  39. package/src/container/runtime-core/operations/selector-scripts.mjs +277 -277
  40. package/src/container/runtime-core/operations/tab-pool.mjs +746 -746
  41. package/src/container/runtime-core/operations/viewport.mjs +189 -189
  42. package/src/container/runtime-core/search.mjs +190 -190
  43. package/src/container/runtime-core/subscription.mjs +224 -224
  44. package/src/container/runtime-core/utils.mjs +94 -94
  45. package/src/container/runtime-core/validation.mjs +127 -184
  46. package/src/container/runtime-core.mjs +1 -1
  47. package/src/container/subscription-registry.mjs +459 -459
  48. package/src/core/actions.mjs +561 -561
  49. package/src/core/browser.mjs +266 -266
  50. package/src/core/index.mjs +52 -52
  51. package/src/core/utils.mjs +91 -91
  52. package/src/events/daemon-entry.mjs +33 -33
  53. package/src/events/daemon.mjs +80 -80
  54. package/src/events/progress-log.mjs +109 -109
  55. package/src/events/ws-server.mjs +239 -239
  56. package/src/lib/client.mjs +200 -200
  57. package/src/lifecycle/cleanup.mjs +83 -83
  58. package/src/lifecycle/lock.mjs +126 -126
  59. package/src/lifecycle/session-registry.mjs +279 -279
  60. package/src/lifecycle/session-view.mjs +76 -76
  61. package/src/lifecycle/session-watchdog.mjs +281 -281
  62. package/src/services/browser-service/index.js +671 -674
  63. package/src/services/browser-service/internal/BrowserSession.input.test.js +389 -389
  64. package/src/services/browser-service/internal/BrowserSession.js +325 -336
  65. package/src/services/browser-service/internal/ElementRegistry.js +60 -60
  66. package/src/services/browser-service/internal/ProfileLock.js +84 -84
  67. package/src/services/browser-service/internal/SessionManager.js +184 -184
  68. package/src/services/browser-service/internal/SessionManager.test.js +39 -39
  69. package/src/services/browser-service/internal/browser-session/cookies.js +144 -144
  70. package/src/services/browser-service/internal/browser-session/input-ops.js +222 -219
  71. package/src/services/browser-service/internal/browser-session/input-pipeline.js +144 -144
  72. package/src/services/browser-service/internal/browser-session/logging.js +46 -46
  73. package/src/services/browser-service/internal/browser-session/navigation.js +38 -38
  74. package/src/services/browser-service/internal/browser-session/page-hooks.js +442 -442
  75. package/src/services/browser-service/internal/browser-session/page-management.js +302 -336
  76. package/src/services/browser-service/internal/browser-session/page-management.test.js +148 -148
  77. package/src/services/browser-service/internal/browser-session/recording.js +198 -198
  78. package/src/services/browser-service/internal/browser-session/runtime-events.js +61 -61
  79. package/src/services/browser-service/internal/browser-session/session-core.js +84 -84
  80. package/src/services/browser-service/internal/browser-session/session-state.js +38 -38
  81. package/src/services/browser-service/internal/browser-session/types.js +14 -14
  82. package/src/services/browser-service/internal/browser-session/utils.js +95 -95
  83. package/src/services/browser-service/internal/browser-session/viewport-manager.js +46 -46
  84. package/src/services/browser-service/internal/browser-session/viewport.js +215 -215
  85. package/src/services/browser-service/internal/container-matcher.js +851 -851
  86. package/src/services/browser-service/internal/container-registry.js +182 -182
  87. package/src/services/browser-service/internal/engine-manager.js +259 -259
  88. package/src/services/browser-service/internal/fingerprint.js +203 -203
  89. package/src/services/browser-service/internal/heartbeat.js +137 -137
  90. package/src/services/browser-service/internal/logging.js +46 -46
  91. package/src/services/browser-service/internal/page-runtime/runtime.js +1317 -1317
  92. package/src/services/browser-service/internal/pageRuntime.js +28 -28
  93. package/src/services/browser-service/internal/runtimeInjector.js +31 -31
  94. package/src/services/browser-service/internal/service-process-logger.js +140 -140
  95. package/src/services/browser-service/internal/state-bus.js +45 -45
  96. package/src/services/browser-service/internal/storage-paths.js +42 -42
  97. package/src/services/browser-service/internal/ws-server.js +1194 -1194
  98. package/src/services/browser-service/internal/ws-server.test.js +58 -58
  99. package/src/services/browser-service/server.mjs +6 -6
  100. package/src/services/controller/cli-bridge.js +93 -93
  101. package/src/services/controller/container-index.js +50 -50
  102. package/src/services/controller/container-storage.js +36 -36
  103. package/src/services/controller/controller-actions.js +207 -207
  104. package/src/services/controller/controller.js +1138 -1138
  105. package/src/services/controller/selectors.js +54 -54
  106. package/src/services/controller/transport.js +125 -125
  107. package/src/utils/args.mjs +26 -26
  108. package/src/utils/browser-service.mjs +544 -544
  109. package/src/utils/command-log.mjs +64 -64
  110. package/src/utils/config.mjs +214 -214
  111. package/src/utils/fingerprint.mjs +181 -181
  112. package/src/utils/help.mjs +216 -216
  113. package/src/utils/js-policy.mjs +13 -13
  114. package/src/utils/ws-client.mjs +30 -30
  115. package/src/container/runtime-core/operations/tab-pool.mjs.bak +0 -762
  116. package/src/container/runtime-core/operations/tab-pool.mjs.syntax-error +0 -762
  117. package/src/services/browser-service/index.js.bak +0 -671
@@ -1,762 +0,0 @@
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
- const RUNTIME_LAYER_TIMEOUT_MS = 10000; // 额外的 runtime 层超时保护
13
-
14
- function sleep(ms) {
15
- return new Promise((resolve) => setTimeout(resolve, ms));
16
- }
17
-
18
- function withTimeout(promise, timeoutMs, timeoutMessage) {
19
- let timer = null;
20
- return Promise.race([
21
- promise,
22
- new Promise((_, reject) => {
23
- timer = setTimeout(() => reject(new Error(timeoutMessage)), timeoutMs);
24
- }),
25
- ]).finally(() => {
26
- if (timer) clearTimeout(timer);
27
- });
28
- }
29
-
30
- /**
31
- * 双重超时保护:在 runtime 层强制超时,即使 fetch 超时失效
32
- * 使用 Promise.race + setTimeout 确保 Promise 一定会在指定时间内 reject
33
- */
34
- async function withRuntimeLayerTimeout(promise, timeoutMs, timeoutMessage) {
35
- let timer = null;
36
- let runtimeTimer = null;
37
-
38
- return Promise.race([
39
- promise,
40
- new Promise((_, reject) => {
41
- runtimeTimer = setTimeout(() => {
42
- console.error(`[RuntimeLayerTimeout] ${timeoutMessage}`);
43
- reject(new Error(`Runtime layer timeout after ${timeoutMs}ms: ${timeoutMessage}`));
44
- }, timeoutMs);
45
- }),
46
- ]).finally(() => {
47
- if (timer) clearTimeout(timer);
48
- if (runtimeTimer) clearTimeout(runtimeTimer);
49
- });
50
- }
51
-
52
- function resolveTimeoutMs(raw, fallback) {
53
- const parsed = Number(raw);
54
- if (!Number.isFinite(parsed) || parsed <= 0) return fallback;
55
- return Math.max(500, Math.floor(parsed));
56
- }
57
-
58
- function resolveViewportSyncConfig({ params = {}, inherited = null }) {
59
- const enabled = params.syncViewport !== undefined
60
- ? params.syncViewport !== false
61
- : inherited?.enabled !== false;
62
- return {
63
- enabled,
64
- apiTimeoutMs: resolveTimeoutMs(
65
- params.viewportApiTimeoutMs ?? inherited?.apiTimeoutMs,
66
- DEFAULT_VIEWPORT_API_TIMEOUT_MS,
67
- ),
68
- settleMs: Math.max(
69
- 0,
70
- Number(params.viewportSettleMs ?? inherited?.settleMs ?? DEFAULT_VIEWPORT_SETTLE_MS) || DEFAULT_VIEWPORT_SETTLE_MS,
71
- ),
72
- attempts: Math.max(
73
- 1,
74
- Number(params.viewportAttempts ?? inherited?.attempts ?? DEFAULT_VIEWPORT_ATTEMPTS) || DEFAULT_VIEWPORT_ATTEMPTS,
75
- ),
76
- tolerancePx: Math.max(
77
- 0,
78
- Number(params.viewportTolerancePx ?? inherited?.tolerancePx ?? DEFAULT_VIEWPORT_TOLERANCE_PX) || DEFAULT_VIEWPORT_TOLERANCE_PX,
79
- ),
80
- };
81
- }
82
-
83
- async function callApiWithTimeout(action, payload, timeoutMs) {
84
- const effectiveTimeoutMs = resolveTimeoutMs(timeoutMs, DEFAULT_API_TIMEOUT_MS);
85
- return withTimeout(
86
- callAPI(action, payload),
87
- effectiveTimeoutMs,
88
- `${action} timeout after ${effectiveTimeoutMs}ms (network layer)`,
89
- );
90
- }
91
-
92
- /**
93
- * 带强制 runtime 层超时的 API 调用
94
- * 用于关键操作,确保即使 fetch 超时失效也能在合理时间内返回
95
- */
96
- async function callApiWithRuntimeTimeout(action, payload, timeoutMs, runtimeTimeoutMs) {
97
- const effectiveTimeoutMs = resolveTimeoutMs(timeoutMs, DEFAULT_API_TIMEOUT_MS);
98
- const effectiveTimeoutMs = Math.min(effectiveTimeoutMs + 5000, RUNTIME_LAYER_TIMEOUT_MS);
99
-
100
- console.log(`[callApiWithRuntimeTimeout] ${action} timeout: ${effectiveTimeoutMs}ms, runtime: ${effectiveRuntimeTimeoutMs}ms`);
101
-
102
- return withRuntimeLayerTimeout(
103
- callAPI(action, payload),
104
- effectiveRuntimeTimeoutMs,
105
- `${action} runtime timeout after ${effectiveRuntimeTimeoutMs}ms`,
106
- );
107
- }
108
-
109
- async function syncTabViewportIfNeeded({ profileId, syncConfig }) {
110
- if (!syncConfig?.enabled) {
111
- return { ok: true, code: 'OPERATION_SKIPPED', message: 'sync viewport disabled' };
112
- }
113
- return executeViewportOperation({
114
- profileId,
115
- action: 'sync_window_viewport',
116
- params: {
117
- followWindow: true,
118
- settleMs: syncConfig.settleMs,
119
- attempts: syncConfig.attempts,
120
- tolerancePx: syncConfig.tolerancePx,
121
- apiTimeoutMs: syncConfig.apiTimeoutMs,
122
- },
123
- });
124
- }
125
-
126
- function parseUrl(raw) {
127
- try {
128
- return new URL(String(raw || ''));
129
- } catch {
130
- return null;
131
- }
132
- }
133
-
134
- function normalizeSeedUrl(rawSeedUrl) {
135
- const parsed = parseUrl(rawSeedUrl);
136
- if (!parsed) return String(rawSeedUrl || '').trim();
137
- const host = String(parsed.hostname || '').toLowerCase();
138
- const pathname = String(parsed.pathname || '');
139
- const isXhsHost = host.includes('xiaohongshu.com');
140
- const isXhsDetailPath = /^\/explore\/[^/]+$/.test(pathname);
141
- if (isXhsHost && isXhsDetailPath) {
142
- parsed.pathname = '/explore';
143
- parsed.search = '';
144
- parsed.hash = '';
145
- return parsed.toString();
146
- }
147
- return parsed.toString();
148
- }
149
-
150
- function isXhsDetailUrl(rawUrl) {
151
- const parsed = parseUrl(rawUrl);
152
- if (!parsed) return false;
153
- const host = String(parsed.hostname || '').toLowerCase();
154
- const pathname = String(parsed.pathname || '');
155
- return host.includes('xiaohongshu.com') && /^\/explore\/[^/]+$/.test(pathname);
156
- }
157
-
158
- async function resolveXhsListUrlFromState(profileId, timeoutMs) {
159
- try {
160
- const payload = await callApiWithTimeout('evaluate', {
161
- profileId,
162
- script: `(() => {
163
- const STATE_KEY = '__camoXhsState';
164
- const safeString = (value) => typeof value === 'string' ? value.trim() : '';
165
- let state = window.__camoXhsState && typeof window.__camoXhsState === 'object'
166
- ? window.__camoXhsState
167
- : null;
168
- if (!state) {
169
- try {
170
- const stored = localStorage.getItem(STATE_KEY);
171
- if (stored) state = JSON.parse(stored);
172
- } catch {}
173
- }
174
- const lastListUrl = safeString(state?.lastListUrl);
175
- return { lastListUrl };
176
- })()`,
177
- }, timeoutMs);
178
- const result = payload?.result || payload || {};
179
- const candidate = String(result?.lastListUrl || '').trim();
180
- return candidate || null;
181
- } catch {
182
- return null;
183
- }
184
- }
185
-
186
- function shouldNavigateToSeed(currentUrl, seedUrl) {
187
- const current = parseUrl(currentUrl);
188
- const seed = parseUrl(seedUrl);
189
- if (!seed) return false;
190
- if (!current) return true;
191
- const currentPath = String(current.pathname || '');
192
- const seedPath = String(seed.pathname || '');
193
- const currentIsXhsDetail = /^\/explore\/[^/]+$/.test(currentPath);
194
- if (current.protocol === 'about:') return true;
195
- if (current.origin !== seed.origin) return true;
196
- if (seedPath.includes('/search_result') && !currentPath.includes('/search_result')) return true;
197
- if (seedPath === '/explore' && currentIsXhsDetail) return true;
198
- if (seedPath.includes('/explore') && !currentPath.includes('/explore') && !currentPath.includes('/search_result')) return true;
199
- return false;
200
- }
201
-
202
- async function seedNewestTabIfNeeded({
203
- profileId,
204
- seedUrl,
205
- openDelayMs,
206
- apiTimeoutMs,
207
- navigationTimeoutMs,
208
- syncConfig,
209
- }) {
210
- if (!seedUrl) return;
211
- const listed = await callApiWithTimeout('page:list', { profileId }, apiTimeoutMs);
212
- const { pages, activeIndex } = extractPageList(listed);
213
- const newest = [...pages]
214
- .filter((page) => Number.isFinite(Number(page?.index)))
215
- .sort((a, b) => Number(b.index) - Number(a.index))[0];
216
- if (!newest) return;
217
-
218
- const targetIndex = Number(newest.index);
219
- if (Number(activeIndex) !== targetIndex) {
220
- await callApiWithTimeout('page:switch', { profileId, index: targetIndex }, apiTimeoutMs);
221
- }
222
- try {
223
- if (shouldNavigateToSeed(newest.url, seedUrl)) {
224
- await callApiWithTimeout('goto', { profileId, url: seedUrl }, navigationTimeoutMs);
225
- if (openDelayMs > 0) await sleep(Math.min(openDelayMs, 1200));
226
- }
227
- const syncResult = await syncTabViewportIfNeeded({ profileId, syncConfig });
228
- if (!syncResult?.ok) {
229
- throw new Error(syncResult?.message || 'sync_window_viewport failed');
230
- }
231
- } catch {
232
- // Best-effort seeding; failing to navigate/sync shouldn't block tab pool init.
233
- }
234
- }
235
-
236
- async function waitForTabCountIncrease({
237
- profileId,
238
- beforeCount,
239
- apiTimeoutMs,
240
- maxWaitMs,
241
- pollMs = 250,
242
- }) {
243
- const startedAt = Date.now();
244
- const effectivePollMs = Math.max(80, Number(pollMs) || 250);
245
- const waitMs = Math.max(400, Number(maxWaitMs) || 4000);
246
- const listTimeoutMs = Math.max(1000, Math.min(resolveTimeoutMs(apiTimeoutMs, DEFAULT_API_TIMEOUT_MS), 8000));
247
- let lastError = null;
248
-
249
- while (Date.now() - startedAt <= waitMs) {
250
- try {
251
- const listed = await callApiWithRuntimeTimeout('page:list', { profileId }, listTimeoutMs);
252
- const { pages } = extractPageList(listed);
253
- if (pages.length > beforeCount) {
254
- return {
255
- ok: true,
256
- elapsedMs: Date.now() - startedAt,
257
- afterCount: pages.length,
258
- };
259
- }
260
- } catch (err) {
261
- lastError = err;
262
- }
263
- await sleep(effectivePollMs);
264
- }
265
-
266
- return {
267
- ok: false,
268
- elapsedMs: Date.now() - startedAt,
269
- error: lastError,
270
- };
271
- }
272
-
273
- async function hydrateBlankNewestTab({
274
- profileId,
275
- beforeCount,
276
- seedUrl,
277
- openDelayMs,
278
- apiTimeoutMs,
279
- navigationTimeoutMs,
280
- tabAppearTimeoutMs,
281
- syncConfig,
282
- }) {
283
- if (!seedUrl) {
284
- return { ok: false, reason: 'missing_seed_url' };
285
- }
286
- const listed = await callApiWithTimeout('page:list', { profileId }, apiTimeoutMs);
287
- const { pages } = extractPageList(listed);
288
- const candidates = [...pages]
289
- .filter((page) => Number.isFinite(Number(page?.index)))
290
- .sort((a, b) => Number(b.index) - Number(a.index));
291
- const newest = candidates[0] || null;
292
- if (!newest) {
293
- return { ok: false, reason: 'no_pages' };
294
- }
295
- const currentCount = pages.length;
296
- if (currentCount <= beforeCount) {
297
- return { ok: false, reason: 'count_not_increased' };
298
- }
299
- const currentUrl = String(newest.url || '').trim().toLowerCase();
300
- const isBlank = !currentUrl || currentUrl === 'about:blank';
301
- if (!isBlank) {
302
- return { ok: true, reason: 'newest_already_navigated', afterCount: currentCount };
303
- }
304
- await callApiWithTimeout('page:switch', { profileId, index: Number(newest.index) }, apiTimeoutMs);
305
- await callApiWithTimeout('goto', { profileId, url: seedUrl }, navigationTimeoutMs);
306
- if (openDelayMs > 0) {
307
- await sleep(Math.min(openDelayMs, 1200));
308
- }
309
- const syncResult = await syncTabViewportIfNeeded({ profileId, syncConfig });
310
- if (!syncResult?.ok) {
311
- throw new Error(syncResult?.message || 'sync_window_viewport failed');
312
- }
313
- const after = await waitForTabCountIncrease({
314
- profileId,
315
- beforeCount,
316
- apiTimeoutMs,
317
- maxWaitMs: Math.max(1500, Math.min(tabAppearTimeoutMs, 6000)),
318
- });
319
- return {
320
- ok: true,
321
- reason: 'blank_tab_hydrated',
322
- afterCount: after?.afterCount || currentCount,
323
- };
324
- }
325
-
326
- async function openTabBestEffort({
327
- profileId,
328
- seedUrl,
329
- seedOnOpen = true,
330
- shortcutOnly = false,
331
- openDelayMs,
332
- beforeCount,
333
- apiTimeoutMs,
334
- navigationTimeoutMs,
335
- shortcutTimeoutMs,
336
- tabAppearTimeoutMs,
337
- syncConfig,
338
- }) {
339
- const waitForTab = async () => waitForTabCountIncrease({
340
- profileId,
341
- beforeCount,
342
- apiTimeoutMs,
343
- maxWaitMs: tabAppearTimeoutMs,
344
- });
345
- const settle = async () => {
346
- if (openDelayMs > 0) {
347
- await new Promise((resolve) => setTimeout(resolve, openDelayMs));
348
- }
349
- };
350
-
351
- let openError = null;
352
- const openCommandTimeoutMs = Math.max(
353
- 60000,
354
- resolveTimeoutMs(apiTimeoutMs, DEFAULT_API_TIMEOUT_MS),
355
- resolveTimeoutMs(tabAppearTimeoutMs, 0) + Math.max(30000, Math.min(openDelayMs || 0, 20000)),
356
- );
357
- const payload = seedOnOpen && seedUrl
358
- ? { profileId, url: seedUrl }
359
- : { profileId };
360
- try {
361
- await callApiWithTimeout('newPage', payload, openCommandTimeoutMs);
362
- await settle();
363
- const newPageOpened = await waitForTab();
364
- if (newPageOpened.ok) {
365
- if (seedOnOpen && seedUrl) {
366
- await seedNewestTabIfNeeded({
367
- profileId,
368
- seedUrl,
369
- openDelayMs,
370
- apiTimeoutMs,
371
- navigationTimeoutMs,
372
- syncConfig,
373
- });
374
- }
375
- return { ok: true, mode: 'newPage', error: null };
376
- }
377
- const hydrated = await hydrateBlankNewestTab({
378
- profileId,
379
- beforeCount,
380
- seedUrl,
381
- openDelayMs,
382
- apiTimeoutMs,
383
- navigationTimeoutMs,
384
- tabAppearTimeoutMs,
385
- syncConfig,
386
- }).catch((error) => ({ ok: false, error }));
387
- if (hydrated?.ok) {
388
- return { ok: true, mode: 'newPage_hydrated_blank', error: null };
389
- }
390
- if (hydrated?.error) {
391
- openError = hydrated.error;
392
- }
393
- } catch (err) {
394
- openError = err;
395
- }
396
-
397
- return { ok: false, mode: null, error: openError };
398
- }
399
-
400
- export async function executeTabPoolOperation({ profileId, action, params = {}, context = {} }) {
401
- const runtimeState = context?.runtime && typeof context.runtime === 'object' ? context.runtime : null;
402
-
403
- if (action === 'ensure_tab_pool') {
404
- const tabCount = Math.max(1, Number(params.tabCount ?? params.count ?? 1) || 1);
405
- const minOpenDelayMs = Math.max(0, Number(params.minDelayMs ?? params.minOpenDelayMs ?? 0) || 0);
406
- const openDelayMs = Math.max(
407
- minOpenDelayMs,
408
- Math.max(0, Number(params.openDelayMs ?? 350) || 350),
409
- );
410
- const normalizeTabs = params.normalizeTabs === true;
411
- const seedOnOpen = params.seedOnOpen !== false;
412
- const shortcutOnly = params.shortcutOnly === true;
413
- const reuseOnly = params.reuseOnly === true;
414
- const apiTimeoutMs = resolveTimeoutMs(params.apiTimeoutMs, DEFAULT_API_TIMEOUT_MS);
415
- const navigationTimeoutMs = resolveTimeoutMs(params.navigationTimeoutMs ?? params.gotoTimeoutMs, DEFAULT_NAV_TIMEOUT_MS);
416
- const shortcutTimeoutMs = resolveTimeoutMs(params.shortcutTimeoutMs, SHORTCUT_OPEN_TIMEOUT_MS);
417
- const tabAppearTimeoutMs = resolveTimeoutMs(
418
- params.tabAppearTimeoutMs,
419
- Math.max(20000, openDelayMs + 15000),
420
- );
421
- const syncConfig = resolveViewportSyncConfig({ params });
422
- const configuredSeedUrl = normalizeSeedUrl(String(params.url || '').trim());
423
-
424
- let listed = await callApiWithTimeout('page:list', { profileId }, apiTimeoutMs);
425
- let { pages, activeIndex } = extractPageList(listed);
426
- const defaultSeedUrl = String(
427
- configuredSeedUrl
428
- || pages.find((item) => item?.active)?.url
429
- || pages[0]?.url
430
- || '',
431
- ).trim();
432
- let fallbackSeedUrl = defaultSeedUrl;
433
- if (!configuredSeedUrl && isXhsDetailUrl(defaultSeedUrl)) {
434
- const recoveredListUrl = await resolveXhsListUrlFromState(profileId, apiTimeoutMs);
435
- if (recoveredListUrl) fallbackSeedUrl = recoveredListUrl;
436
- }
437
- fallbackSeedUrl = normalizeSeedUrl(fallbackSeedUrl);
438
- let openFailures = 0;
439
- const maxOpenFailures = Math.max(3, tabCount);
440
-
441
- while (pages.length < tabCount) {
442
- if (reuseOnly) {
443
- break;
444
- }
445
- const beforeCount = pages.length;
446
- const openResult = await openTabBestEffort({
447
- profileId,
448
- seedUrl: fallbackSeedUrl,
449
- seedOnOpen,
450
- shortcutOnly,
451
- openDelayMs,
452
- beforeCount,
453
- apiTimeoutMs,
454
- navigationTimeoutMs,
455
- shortcutTimeoutMs,
456
- tabAppearTimeoutMs,
457
- syncConfig,
458
- });
459
- listed = await callApiWithTimeout('page:list', { profileId }, apiTimeoutMs);
460
- ({ pages, activeIndex } = extractPageList(listed));
461
- if (!openResult.ok || pages.length <= beforeCount) {
462
- openFailures += 1;
463
- if (openFailures >= maxOpenFailures) {
464
- return asErrorPayload('OPERATION_FAILED', 'new_tab_failed', {
465
- tabCount,
466
- beforeCount,
467
- afterCount: pages.length,
468
- seedUrl: fallbackSeedUrl || null,
469
- mode: openResult.mode || null,
470
- reason: openResult.error?.message || 'cannot open new tab',
471
- attempts: openFailures,
472
- });
473
- }
474
- if (openDelayMs > 0) {
475
- await sleep(Math.min(openDelayMs, 1200));
476
- } else {
477
- await sleep(300);
478
- }
479
- continue;
480
- }
481
- }
482
-
483
- if (reuseOnly && pages.length === 0) {
484
- return asErrorPayload('TAB_POOL_EMPTY', 'reuse_only_tab_pool_requires_existing_tabs', {
485
- tabCount,
486
- });
487
- }
488
-
489
- const sortedPages = [...pages].sort((a, b) => Number(a.index) - Number(b.index));
490
- const activePage = sortedPages.find((item) => Number(item.index) === Number(activeIndex)) || null;
491
- const selected = [
492
- ...(activePage ? [activePage] : []),
493
- ...sortedPages.filter((item) => Number(item.index) !== Number(activeIndex)),
494
- ].slice(0, tabCount);
495
-
496
- const forceNormalizeFromDetail = Boolean(seedOnOpen && !configuredSeedUrl && isXhsDetailUrl(defaultSeedUrl));
497
- const shouldNormalizeSlots = seedOnOpen && Boolean(fallbackSeedUrl) && (normalizeTabs || forceNormalizeFromDetail);
498
-
499
- if (shouldNormalizeSlots) {
500
- for (const page of selected) {
501
- const pageIndex = Number(page.index);
502
- if (!Number.isFinite(pageIndex)) continue;
503
- try {
504
- await callApiWithTimeout('page:switch', { profileId, index: pageIndex }, apiTimeoutMs);
505
- if (shouldNavigateToSeed(page.url, fallbackSeedUrl)) {
506
- await callApiWithTimeout('goto', { profileId, url: fallbackSeedUrl }, navigationTimeoutMs);
507
- if (openDelayMs > 0) await sleep(Math.min(openDelayMs, 1200));
508
- }
509
- const syncResult = await syncTabViewportIfNeeded({ profileId, syncConfig });
510
- if (!syncResult?.ok) {
511
- throw new Error(syncResult?.message || 'tab viewport sync failed');
512
- }
513
- } catch (err) {
514
- const activePage = selected.find((item) => Number(item.index) === Number(activeIndex)) || selected[0] || null;
515
- const slots = activePage
516
- ? [{
517
- slotIndex: 1,
518
- tabRealIndex: Number(activePage.index),
519
- url: String(activePage.url || ''),
520
- }]
521
- : [];
522
- if (runtimeState) {
523
- runtimeState.tabPool = {
524
- slots,
525
- cursor: 0,
526
- count: slots.length,
527
- syncConfig,
528
- apiTimeoutMs,
529
- initializedAt: new Date().toISOString(),
530
- };
531
- }
532
- return {
533
- ok: true,
534
- code: 'OPERATION_DEGRADED',
535
- message: 'ensure_tab_pool degraded to active tab',
536
- data: {
537
- tabCount: slots.length,
538
- normalized: false,
539
- degraded: true,
540
- reason: err?.message || 'page switch failed',
541
- slots,
542
- pages: activePage ? [activePage] : [],
543
- },
544
- };
545
- }
546
- }
547
- listed = await callApiWithTimeout('page:list', { profileId }, apiTimeoutMs);
548
- ({ pages } = extractPageList(listed));
549
- }
550
-
551
- const refreshedByIndex = new Map(
552
- pages.map((page) => [Number(page.index), page]),
553
- );
554
- const slots = selected.map((page, idx) => ({
555
- slotIndex: idx + 1,
556
- tabRealIndex: Number(page.index),
557
- url: String(refreshedByIndex.get(Number(page.index))?.url || page.url || ''),
558
- }));
559
-
560
- if (slots.length > 0) {
561
- try {
562
- await callApiWithTimeout('page:switch', {
563
- profileId,
564
- index: Number(slots[0].tabRealIndex),
565
- }, apiTimeoutMs);
566
- const syncResult = await syncTabViewportIfNeeded({ profileId, syncConfig });
567
- if (!syncResult?.ok) {
568
- throw new Error(syncResult?.message || 'tab viewport sync failed');
569
- }
570
- } catch (err) {
571
- if (runtimeState) {
572
- runtimeState.tabPool = {
573
- slots,
574
- cursor: 0,
575
- count: slots.length,
576
- syncConfig,
577
- apiTimeoutMs,
578
- initializedAt: new Date().toISOString(),
579
- };
580
- }
581
- return {
582
- ok: true,
583
- code: 'OPERATION_DEGRADED',
584
- message: 'ensure_tab_pool degraded on final switch',
585
- data: {
586
- tabCount: slots.length,
587
- normalized: false,
588
- degraded: true,
589
- reason: err?.message || 'page switch failed',
590
- slots,
591
- pages: slots,
592
- },
593
- };
594
- }
595
- }
596
-
597
- if (runtimeState) {
598
- runtimeState.tabPool = {
599
- slots,
600
- cursor: 0,
601
- count: slots.length,
602
- syncConfig,
603
- apiTimeoutMs,
604
- initializedAt: new Date().toISOString(),
605
- };
606
- runtimeState.currentTab = slots[0]
607
- ? {
608
- slotIndex: Number(slots[0].slotIndex),
609
- tabRealIndex: Number(slots[0].tabRealIndex),
610
- url: String(slots[0].url || ''),
611
- }
612
- : null;
613
- }
614
-
615
- return {
616
- ok: true,
617
- code: 'OPERATION_DONE',
618
- message: 'ensure_tab_pool done',
619
- data: {
620
- tabCount: slots.length,
621
- normalized: shouldNormalizeSlots,
622
- slots,
623
- pages: selected,
624
- },
625
- };
626
- }
627
-
628
- if (action === 'tab_pool_switch_next') {
629
- const settleMs = Math.max(0, Number(params.settleMs ?? params.waitMs ?? 450) || 450);
630
- const pool = runtimeState?.tabPool;
631
- const slots = normalizeArray(pool?.slots);
632
- if (!runtimeState || slots.length === 0) {
633
- return asErrorPayload('TAB_POOL_NOT_INITIALIZED', 'tab_pool_switch_next requires ensure_tab_pool first');
634
- }
635
-
636
- const cursor = Math.max(0, Number(pool.cursor) || 0);
637
- const selected = slots[cursor % slots.length];
638
- runtimeState.tabPool.cursor = (cursor + 1) % slots.length;
639
- const targetIndex = Number(selected.tabRealIndex);
640
- const apiTimeoutMs = resolveTimeoutMs(params.apiTimeoutMs ?? pool?.apiTimeoutMs, DEFAULT_API_TIMEOUT_MS);
641
- const syncConfig = resolveViewportSyncConfig({ params, inherited: pool?.syncConfig });
642
-
643
- const beforeList = await callApiWithTimeout('page:list', { profileId }, apiTimeoutMs);
644
- const { activeIndex: beforeActiveIndex } = extractPageList(beforeList);
645
- if (Number(beforeActiveIndex) !== targetIndex) {
646
- await callApiWithTimeout('page:switch', {
647
- profileId,
648
- index: targetIndex,
649
- }, apiTimeoutMs);
650
- const syncResult = await syncTabViewportIfNeeded({ profileId, syncConfig });
651
- if (!syncResult?.ok) {
652
- return asErrorPayload('OPERATION_FAILED', 'tab viewport sync failed', {
653
- targetIndex,
654
- syncResult,
655
- });
656
- }
657
- }
658
-
659
- if (settleMs > 0) {
660
- await new Promise((resolve) => setTimeout(resolve, settleMs));
661
- }
662
-
663
- const listed = await callApiWithTimeout('page:list', { profileId }, apiTimeoutMs);
664
- const { activeIndex } = extractPageList(listed);
665
- if (Number(activeIndex) !== targetIndex) {
666
- return asErrorPayload('OPERATION_FAILED', 'tab_pool_switch_next did not activate target tab', {
667
- expectedIndex: targetIndex,
668
- activeIndex,
669
- selected,
670
- });
671
- }
672
- runtimeState.currentTab = {
673
- slotIndex: Number(selected.slotIndex),
674
- tabRealIndex: targetIndex,
675
- activeIndex,
676
- url: String(selected.url || ''),
677
- };
678
-
679
- return {
680
- ok: true,
681
- code: 'OPERATION_DONE',
682
- message: 'tab_pool_switch_next done',
683
- data: {
684
- currentTab: runtimeState.currentTab,
685
- cursor: runtimeState.tabPool.cursor,
686
- slots,
687
- },
688
- };
689
- }
690
-
691
- if (action === 'tab_pool_switch_slot') {
692
- const pool = runtimeState?.tabPool;
693
- const slots = normalizeArray(pool?.slots);
694
- if (!runtimeState || slots.length === 0) {
695
- return asErrorPayload('TAB_POOL_NOT_INITIALIZED', 'tab_pool_switch_slot requires ensure_tab_pool first');
696
- }
697
-
698
- const requestedSlotIndex = Number(params.slotIndex ?? params.slot ?? 1);
699
- if (!Number.isFinite(requestedSlotIndex) || requestedSlotIndex < 1) {
700
- return asErrorPayload('OPERATION_FAILED', 'tab_pool_switch_slot requires params.slotIndex >= 1');
701
- }
702
- const slot = slots.find((item) => Number(item.slotIndex) === Math.floor(requestedSlotIndex));
703
- if (!slot) {
704
- return asErrorPayload('OPERATION_FAILED', `tab_pool slot not found: ${requestedSlotIndex}`);
705
- }
706
- const targetIndex = Number(slot.tabRealIndex);
707
- const apiTimeoutMs = resolveTimeoutMs(params.apiTimeoutMs ?? pool?.apiTimeoutMs, DEFAULT_API_TIMEOUT_MS);
708
- const syncConfig = resolveViewportSyncConfig({ params, inherited: pool?.syncConfig });
709
-
710
- const beforeList = await callApiWithTimeout('page:list', { profileId }, apiTimeoutMs);
711
- const { activeIndex: beforeActiveIndex } = extractPageList(beforeList);
712
- if (Number(beforeActiveIndex) !== targetIndex) {
713
- await callApiWithTimeout('page:switch', { profileId, index: targetIndex }, apiTimeoutMs);
714
- const syncResult = await syncTabViewportIfNeeded({ profileId, syncConfig });
715
- if (!syncResult?.ok) {
716
- return asErrorPayload('OPERATION_FAILED', 'tab viewport sync failed', {
717
- targetIndex,
718
- syncResult,
719
- });
720
- }
721
- }
722
- const listed = await callApiWithTimeout('page:list', { profileId }, apiTimeoutMs);
723
- const { activeIndex } = extractPageList(listed);
724
- if (Number(activeIndex) !== targetIndex) {
725
- return asErrorPayload('OPERATION_FAILED', 'tab_pool_switch_slot did not activate target tab', {
726
- expectedIndex: targetIndex,
727
- activeIndex,
728
- slot,
729
- });
730
- }
731
- runtimeState.currentTab = {
732
- slotIndex: Number(slot.slotIndex),
733
- tabRealIndex: targetIndex,
734
- activeIndex,
735
- url: String(slot.url || ''),
736
- };
737
- return {
738
- ok: true,
739
- code: 'OPERATION_DONE',
740
- message: 'tab_pool_switch_slot done',
741
- data: { currentTab: runtimeState.currentTab, slots },
742
- };
743
- }
744
-
745
- return asErrorPayload('UNSUPPORTED_OPERATION', `Unsupported tab operation: ${action}`);
746
- }
747
- /**
748
- * 带强制 runtime 层超时的 API 调用
749
- * 用于关键操作,确保即使 fetch 超时失效也能在合理时间内返回
750
- */
751
- async function callApiWithRuntimeTimeout(action, payload, timeoutMs, runtimeTimeoutMs) {
752
- const effectiveTimeoutMs = resolveTimeoutMs(timeoutMs, DEFAULT_API_TIMEOUT_MS);
753
- const effectiveRuntimeTimeoutMs = Math.min(effectiveTimeoutMs + 5000, RUNTIME_LAYER_TIMEOUT_MS);
754
-
755
- console.log(`[callApiWithRuntimeTimeout] ${action} timeout: ${effectiveTimeoutMs}ms, runtime: ${effectiveRuntimeTimeoutMs}ms`);
756
-
757
- return withRuntimeLayerTimeout(
758
- callAPI(action, payload),
759
- effectiveRuntimeTimeoutMs,
760
- `${action} runtime timeout after ${effectiveRuntimeTimeoutMs}ms`,
761
- );
762
- }