@web-auto/camo 0.2.0 → 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.
- package/LICENSE +21 -21
- package/README.md +586 -586
- package/bin/browser-service.mjs +11 -11
- package/bin/camo.mjs +22 -22
- package/package.json +48 -48
- package/scripts/build.mjs +19 -19
- package/scripts/bump-version.mjs +34 -34
- package/scripts/check-file-size.mjs +80 -80
- package/scripts/file-size-policy.json +12 -2
- package/scripts/install.mjs +76 -76
- package/scripts/release.sh +54 -54
- package/src/autoscript/action-providers/index.mjs +6 -6
- package/src/autoscript/impact-engine.mjs +78 -78
- package/src/autoscript/runtime.mjs +1017 -1017
- package/src/autoscript/schema.mjs +376 -376
- package/src/cli.mjs +405 -405
- package/src/commands/attach.mjs +141 -141
- package/src/commands/autoscript.mjs +1011 -1011
- package/src/commands/browser.mjs +1255 -1255
- package/src/commands/container.mjs +401 -401
- package/src/commands/cookies.mjs +69 -69
- package/src/commands/create.mjs +98 -98
- package/src/commands/devtools.mjs +349 -349
- package/src/commands/events.mjs +152 -152
- package/src/commands/highlight-mode.mjs +24 -24
- package/src/commands/init.mjs +68 -68
- package/src/commands/lifecycle.mjs +275 -275
- package/src/commands/mouse.mjs +45 -45
- package/src/commands/profile.mjs +46 -46
- package/src/commands/record.mjs +115 -115
- package/src/commands/system.mjs +14 -14
- package/src/commands/window.mjs +123 -123
- package/src/container/change-notifier.mjs +362 -362
- package/src/container/element-filter.mjs +143 -143
- package/src/container/index.mjs +3 -3
- package/src/container/runtime-core/checkpoint.mjs +209 -209
- package/src/container/runtime-core/index.mjs +21 -21
- package/src/container/runtime-core/operations/index.mjs +774 -774
- package/src/container/runtime-core/operations/selector-scripts.mjs +277 -277
- package/src/container/runtime-core/operations/tab-pool.mjs +746 -746
- package/src/container/runtime-core/operations/viewport.mjs +189 -189
- package/src/container/runtime-core/search.mjs +190 -190
- package/src/container/runtime-core/subscription.mjs +224 -224
- package/src/container/runtime-core/utils.mjs +94 -94
- package/src/container/runtime-core/validation.mjs +127 -127
- package/src/container/runtime-core.mjs +1 -1
- package/src/container/subscription-registry.mjs +459 -459
- package/src/core/actions.mjs +561 -561
- package/src/core/browser.mjs +266 -266
- package/src/core/index.mjs +52 -52
- package/src/core/utils.mjs +91 -91
- package/src/events/daemon-entry.mjs +33 -33
- package/src/events/daemon.mjs +80 -80
- package/src/events/progress-log.mjs +109 -109
- package/src/events/ws-server.mjs +239 -239
- package/src/lib/client.mjs +200 -200
- package/src/lifecycle/cleanup.mjs +83 -83
- package/src/lifecycle/lock.mjs +126 -126
- package/src/lifecycle/session-registry.mjs +279 -279
- package/src/lifecycle/session-view.mjs +76 -76
- package/src/lifecycle/session-watchdog.mjs +281 -281
- package/src/services/browser-service/index.js +671 -671
- package/src/services/browser-service/internal/BrowserSession.input.test.js +389 -389
- package/src/services/browser-service/internal/BrowserSession.js +325 -304
- package/src/services/browser-service/internal/ElementRegistry.js +60 -60
- package/src/services/browser-service/internal/ProfileLock.js +84 -84
- package/src/services/browser-service/internal/SessionManager.js +184 -184
- package/src/services/browser-service/internal/SessionManager.test.js +39 -39
- package/src/services/browser-service/internal/browser-session/cookies.js +144 -144
- package/src/services/browser-service/internal/browser-session/input-ops.js +222 -222
- package/src/services/browser-service/internal/browser-session/input-pipeline.js +144 -144
- package/src/services/browser-service/internal/browser-session/logging.js +46 -46
- package/src/services/browser-service/internal/browser-session/navigation.js +38 -38
- package/src/services/browser-service/internal/browser-session/page-hooks.js +442 -442
- package/src/services/browser-service/internal/browser-session/page-management.js +302 -302
- package/src/services/browser-service/internal/browser-session/page-management.test.js +148 -148
- package/src/services/browser-service/internal/browser-session/recording.js +198 -198
- package/src/services/browser-service/internal/browser-session/runtime-events.js +61 -61
- package/src/services/browser-service/internal/browser-session/session-core.js +84 -84
- package/src/services/browser-service/internal/browser-session/session-state.js +38 -38
- package/src/services/browser-service/internal/browser-session/types.js +14 -14
- package/src/services/browser-service/internal/browser-session/utils.js +95 -95
- package/src/services/browser-service/internal/browser-session/viewport-manager.js +46 -46
- package/src/services/browser-service/internal/browser-session/viewport.js +215 -215
- package/src/services/browser-service/internal/container-matcher.js +851 -851
- package/src/services/browser-service/internal/container-registry.js +182 -182
- package/src/services/browser-service/internal/engine-manager.js +259 -259
- package/src/services/browser-service/internal/fingerprint.js +203 -203
- package/src/services/browser-service/internal/heartbeat.js +137 -137
- package/src/services/browser-service/internal/logging.js +46 -46
- package/src/services/browser-service/internal/page-runtime/runtime.js +1317 -1317
- package/src/services/browser-service/internal/pageRuntime.js +28 -28
- package/src/services/browser-service/internal/runtimeInjector.js +31 -31
- package/src/services/browser-service/internal/service-process-logger.js +140 -140
- package/src/services/browser-service/internal/state-bus.js +45 -45
- package/src/services/browser-service/internal/storage-paths.js +42 -42
- package/src/services/browser-service/internal/ws-server.js +1194 -1194
- package/src/services/browser-service/internal/ws-server.test.js +58 -58
- package/src/services/browser-service/server.mjs +6 -6
- package/src/services/controller/cli-bridge.js +93 -93
- package/src/services/controller/container-index.js +50 -50
- package/src/services/controller/container-storage.js +36 -36
- package/src/services/controller/controller-actions.js +207 -207
- package/src/services/controller/controller.js +1138 -1138
- package/src/services/controller/selectors.js +54 -54
- package/src/services/controller/transport.js +125 -125
- package/src/utils/args.mjs +26 -26
- package/src/utils/browser-service.mjs +544 -544
- package/src/utils/command-log.mjs +64 -64
- package/src/utils/config.mjs +214 -214
- package/src/utils/fingerprint.mjs +181 -181
- package/src/utils/help.mjs +216 -216
- package/src/utils/js-policy.mjs +13 -13
- package/src/utils/ws-client.mjs +30 -30
|
@@ -1,746 +1,746 @@
|
|
|
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;
|
|
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
|
-
function resolveTimeoutMs(raw, fallback) {
|
|
31
|
-
const parsed = Number(raw);
|
|
32
|
-
if (!Number.isFinite(parsed) || parsed <= 0) return fallback;
|
|
33
|
-
return Math.max(500, Math.floor(parsed));
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
function resolveViewportSyncConfig({ params = {}, inherited = null }) {
|
|
37
|
-
const enabled = params.syncViewport !== undefined
|
|
38
|
-
? params.syncViewport !== false
|
|
39
|
-
: inherited?.enabled !== false;
|
|
40
|
-
return {
|
|
41
|
-
enabled,
|
|
42
|
-
apiTimeoutMs: resolveTimeoutMs(
|
|
43
|
-
params.viewportApiTimeoutMs ?? inherited?.apiTimeoutMs,
|
|
44
|
-
DEFAULT_VIEWPORT_API_TIMEOUT_MS,
|
|
45
|
-
),
|
|
46
|
-
settleMs: Math.max(
|
|
47
|
-
0,
|
|
48
|
-
Number(params.viewportSettleMs ?? inherited?.settleMs ?? DEFAULT_VIEWPORT_SETTLE_MS) || DEFAULT_VIEWPORT_SETTLE_MS,
|
|
49
|
-
),
|
|
50
|
-
attempts: Math.max(
|
|
51
|
-
1,
|
|
52
|
-
Number(params.viewportAttempts ?? inherited?.attempts ?? DEFAULT_VIEWPORT_ATTEMPTS) || DEFAULT_VIEWPORT_ATTEMPTS,
|
|
53
|
-
),
|
|
54
|
-
tolerancePx: Math.max(
|
|
55
|
-
0,
|
|
56
|
-
Number(params.viewportTolerancePx ?? inherited?.tolerancePx ?? DEFAULT_VIEWPORT_TOLERANCE_PX) || DEFAULT_VIEWPORT_TOLERANCE_PX,
|
|
57
|
-
),
|
|
58
|
-
};
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
/**
|
|
64
|
-
* 双重超时保护:在 runtime 层强制超时,即使 fetch 超时失效
|
|
65
|
-
*/
|
|
66
|
-
async function withRuntimeLayerTimeout(promise, timeoutMs, timeoutMessage) {
|
|
67
|
-
let runtimeTimer = null;
|
|
68
|
-
|
|
69
|
-
return Promise.race([
|
|
70
|
-
promise,
|
|
71
|
-
new Promise((_, reject) => {
|
|
72
|
-
runtimeTimer = setTimeout(() => {
|
|
73
|
-
console.error(`[RuntimeLayerTimeout] ${timeoutMessage}`);
|
|
74
|
-
reject(new Error(`Runtime layer timeout after ${timeoutMs}ms: ${timeoutMessage}`));
|
|
75
|
-
}, timeoutMs);
|
|
76
|
-
}),
|
|
77
|
-
]).finally(() => {
|
|
78
|
-
if (runtimeTimer) clearTimeout(runtimeTimer);
|
|
79
|
-
});
|
|
80
|
-
}
|
|
81
|
-
|
|
82
|
-
/**
|
|
83
|
-
* 带强制 runtime 层超时的 API 调用
|
|
84
|
-
*/
|
|
85
|
-
async function callApiWithRuntimeTimeout(action, payload, timeoutMs, runtimeTimeoutMs) {
|
|
86
|
-
const effectiveTimeoutMs = resolveTimeoutMs(timeoutMs, DEFAULT_API_TIMEOUT_MS);
|
|
87
|
-
const effectiveRuntimeTimeoutMs = Math.min(effectiveTimeoutMs + 5000, RUNTIME_LAYER_TIMEOUT_MS);
|
|
88
|
-
|
|
89
|
-
console.log(`[callApiWithRuntimeTimeout] ${action} timeout: ${effectiveTimeoutMs}ms, runtime: ${effectiveRuntimeTimeoutMs}ms`);
|
|
90
|
-
|
|
91
|
-
return withRuntimeLayerTimeout(
|
|
92
|
-
callAPI(action, payload),
|
|
93
|
-
effectiveRuntimeTimeoutMs,
|
|
94
|
-
`${action} runtime timeout after ${effectiveRuntimeTimeoutMs}ms`,
|
|
95
|
-
);
|
|
96
|
-
}
|
|
97
|
-
|
|
98
|
-
async function callApiWithTimeout(action, payload, timeoutMs) {
|
|
99
|
-
const effectiveTimeoutMs = resolveTimeoutMs(timeoutMs, DEFAULT_API_TIMEOUT_MS);
|
|
100
|
-
return withTimeout(
|
|
101
|
-
callAPI(action, payload),
|
|
102
|
-
effectiveTimeoutMs,
|
|
103
|
-
`${action} timeout after ${effectiveTimeoutMs}ms`,
|
|
104
|
-
);
|
|
105
|
-
}
|
|
106
|
-
|
|
107
|
-
async function syncTabViewportIfNeeded({ profileId, syncConfig }) {
|
|
108
|
-
if (!syncConfig?.enabled) {
|
|
109
|
-
return { ok: true, code: 'OPERATION_SKIPPED', message: 'sync viewport disabled' };
|
|
110
|
-
}
|
|
111
|
-
return executeViewportOperation({
|
|
112
|
-
profileId,
|
|
113
|
-
action: 'sync_window_viewport',
|
|
114
|
-
params: {
|
|
115
|
-
followWindow: true,
|
|
116
|
-
settleMs: syncConfig.settleMs,
|
|
117
|
-
attempts: syncConfig.attempts,
|
|
118
|
-
tolerancePx: syncConfig.tolerancePx,
|
|
119
|
-
apiTimeoutMs: syncConfig.apiTimeoutMs,
|
|
120
|
-
},
|
|
121
|
-
});
|
|
122
|
-
}
|
|
123
|
-
|
|
124
|
-
function parseUrl(raw) {
|
|
125
|
-
try {
|
|
126
|
-
return new URL(String(raw || ''));
|
|
127
|
-
} catch {
|
|
128
|
-
return null;
|
|
129
|
-
}
|
|
130
|
-
}
|
|
131
|
-
|
|
132
|
-
function normalizeSeedUrl(rawSeedUrl) {
|
|
133
|
-
const parsed = parseUrl(rawSeedUrl);
|
|
134
|
-
if (!parsed) return String(rawSeedUrl || '').trim();
|
|
135
|
-
const host = String(parsed.hostname || '').toLowerCase();
|
|
136
|
-
const pathname = String(parsed.pathname || '');
|
|
137
|
-
const isXhsHost = host.includes('xiaohongshu.com');
|
|
138
|
-
const isXhsDetailPath = /^\/explore\/[^/]+$/.test(pathname);
|
|
139
|
-
if (isXhsHost && isXhsDetailPath) {
|
|
140
|
-
parsed.pathname = '/explore';
|
|
141
|
-
parsed.search = '';
|
|
142
|
-
parsed.hash = '';
|
|
143
|
-
return parsed.toString();
|
|
144
|
-
}
|
|
145
|
-
return parsed.toString();
|
|
146
|
-
}
|
|
147
|
-
|
|
148
|
-
function isXhsDetailUrl(rawUrl) {
|
|
149
|
-
const parsed = parseUrl(rawUrl);
|
|
150
|
-
if (!parsed) return false;
|
|
151
|
-
const host = String(parsed.hostname || '').toLowerCase();
|
|
152
|
-
const pathname = String(parsed.pathname || '');
|
|
153
|
-
return host.includes('xiaohongshu.com') && /^\/explore\/[^/]+$/.test(pathname);
|
|
154
|
-
}
|
|
155
|
-
|
|
156
|
-
async function resolveXhsListUrlFromState(profileId, timeoutMs) {
|
|
157
|
-
try {
|
|
158
|
-
const payload = await callApiWithTimeout('evaluate', {
|
|
159
|
-
profileId,
|
|
160
|
-
script: `(() => {
|
|
161
|
-
const STATE_KEY = '__camoXhsState';
|
|
162
|
-
const safeString = (value) => typeof value === 'string' ? value.trim() : '';
|
|
163
|
-
let state = window.__camoXhsState && typeof window.__camoXhsState === 'object'
|
|
164
|
-
? window.__camoXhsState
|
|
165
|
-
: null;
|
|
166
|
-
if (!state) {
|
|
167
|
-
try {
|
|
168
|
-
const stored = localStorage.getItem(STATE_KEY);
|
|
169
|
-
if (stored) state = JSON.parse(stored);
|
|
170
|
-
} catch {}
|
|
171
|
-
}
|
|
172
|
-
const lastListUrl = safeString(state?.lastListUrl);
|
|
173
|
-
return { lastListUrl };
|
|
174
|
-
})()`,
|
|
175
|
-
}, timeoutMs);
|
|
176
|
-
const result = payload?.result || payload || {};
|
|
177
|
-
const candidate = String(result?.lastListUrl || '').trim();
|
|
178
|
-
return candidate || null;
|
|
179
|
-
} catch {
|
|
180
|
-
return null;
|
|
181
|
-
}
|
|
182
|
-
}
|
|
183
|
-
|
|
184
|
-
function shouldNavigateToSeed(currentUrl, seedUrl) {
|
|
185
|
-
const current = parseUrl(currentUrl);
|
|
186
|
-
const seed = parseUrl(seedUrl);
|
|
187
|
-
if (!seed) return false;
|
|
188
|
-
if (!current) return true;
|
|
189
|
-
const currentPath = String(current.pathname || '');
|
|
190
|
-
const seedPath = String(seed.pathname || '');
|
|
191
|
-
const currentIsXhsDetail = /^\/explore\/[^/]+$/.test(currentPath);
|
|
192
|
-
if (current.protocol === 'about:') return true;
|
|
193
|
-
if (current.origin !== seed.origin) return true;
|
|
194
|
-
if (seedPath.includes('/search_result') && !currentPath.includes('/search_result')) return true;
|
|
195
|
-
if (seedPath === '/explore' && currentIsXhsDetail) return true;
|
|
196
|
-
if (seedPath.includes('/explore') && !currentPath.includes('/explore') && !currentPath.includes('/search_result')) return true;
|
|
197
|
-
return false;
|
|
198
|
-
}
|
|
199
|
-
|
|
200
|
-
async function seedNewestTabIfNeeded({
|
|
201
|
-
profileId,
|
|
202
|
-
seedUrl,
|
|
203
|
-
openDelayMs,
|
|
204
|
-
apiTimeoutMs,
|
|
205
|
-
navigationTimeoutMs,
|
|
206
|
-
syncConfig,
|
|
207
|
-
}) {
|
|
208
|
-
if (!seedUrl) return;
|
|
209
|
-
const listed = await callApiWithTimeout('page:list', { profileId }, apiTimeoutMs);
|
|
210
|
-
const { pages, activeIndex } = extractPageList(listed);
|
|
211
|
-
const newest = [...pages]
|
|
212
|
-
.filter((page) => Number.isFinite(Number(page?.index)))
|
|
213
|
-
.sort((a, b) => Number(b.index) - Number(a.index))[0];
|
|
214
|
-
if (!newest) return;
|
|
215
|
-
|
|
216
|
-
const targetIndex = Number(newest.index);
|
|
217
|
-
if (Number(activeIndex) !== targetIndex) {
|
|
218
|
-
await callApiWithTimeout('page:switch', { profileId, index: targetIndex }, apiTimeoutMs);
|
|
219
|
-
}
|
|
220
|
-
try {
|
|
221
|
-
if (shouldNavigateToSeed(newest.url, seedUrl)) {
|
|
222
|
-
await callApiWithTimeout('goto', { profileId, url: seedUrl }, navigationTimeoutMs);
|
|
223
|
-
if (openDelayMs > 0) await sleep(Math.min(openDelayMs, 1200));
|
|
224
|
-
}
|
|
225
|
-
const syncResult = await syncTabViewportIfNeeded({ profileId, syncConfig });
|
|
226
|
-
if (!syncResult?.ok) {
|
|
227
|
-
throw new Error(syncResult?.message || 'sync_window_viewport failed');
|
|
228
|
-
}
|
|
229
|
-
} catch {
|
|
230
|
-
// Best-effort seeding; failing to navigate/sync shouldn't block tab pool init.
|
|
231
|
-
}
|
|
232
|
-
}
|
|
233
|
-
|
|
234
|
-
async function waitForTabCountIncrease({
|
|
235
|
-
profileId,
|
|
236
|
-
beforeCount,
|
|
237
|
-
apiTimeoutMs,
|
|
238
|
-
maxWaitMs,
|
|
239
|
-
pollMs = 250,
|
|
240
|
-
}) {
|
|
241
|
-
const startedAt = Date.now();
|
|
242
|
-
const effectivePollMs = Math.max(80, Number(pollMs) || 250);
|
|
243
|
-
const waitMs = Math.max(400, Number(maxWaitMs) || 4000);
|
|
244
|
-
const listTimeoutMs = Math.max(1000, Math.min(resolveTimeoutMs(apiTimeoutMs, DEFAULT_API_TIMEOUT_MS), 8000));
|
|
245
|
-
let lastError = null;
|
|
246
|
-
|
|
247
|
-
while (Date.now() - startedAt <= waitMs) {
|
|
248
|
-
try {
|
|
249
|
-
const pollStartTime = Date.now();
|
|
250
|
-
const listed = await callApiWithRuntimeTimeout('page:list', { profileId }, listTimeoutMs, RUNTIME_LAYER_TIMEOUT_MS);
|
|
251
|
-
console.log(`[waitForTabCountIncrease] page:list took ${Date.now() - pollStartTime}ms`);
|
|
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
|
-
}
|
|
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;
|
|
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
|
+
function resolveTimeoutMs(raw, fallback) {
|
|
31
|
+
const parsed = Number(raw);
|
|
32
|
+
if (!Number.isFinite(parsed) || parsed <= 0) return fallback;
|
|
33
|
+
return Math.max(500, Math.floor(parsed));
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function resolveViewportSyncConfig({ params = {}, inherited = null }) {
|
|
37
|
+
const enabled = params.syncViewport !== undefined
|
|
38
|
+
? params.syncViewport !== false
|
|
39
|
+
: inherited?.enabled !== false;
|
|
40
|
+
return {
|
|
41
|
+
enabled,
|
|
42
|
+
apiTimeoutMs: resolveTimeoutMs(
|
|
43
|
+
params.viewportApiTimeoutMs ?? inherited?.apiTimeoutMs,
|
|
44
|
+
DEFAULT_VIEWPORT_API_TIMEOUT_MS,
|
|
45
|
+
),
|
|
46
|
+
settleMs: Math.max(
|
|
47
|
+
0,
|
|
48
|
+
Number(params.viewportSettleMs ?? inherited?.settleMs ?? DEFAULT_VIEWPORT_SETTLE_MS) || DEFAULT_VIEWPORT_SETTLE_MS,
|
|
49
|
+
),
|
|
50
|
+
attempts: Math.max(
|
|
51
|
+
1,
|
|
52
|
+
Number(params.viewportAttempts ?? inherited?.attempts ?? DEFAULT_VIEWPORT_ATTEMPTS) || DEFAULT_VIEWPORT_ATTEMPTS,
|
|
53
|
+
),
|
|
54
|
+
tolerancePx: Math.max(
|
|
55
|
+
0,
|
|
56
|
+
Number(params.viewportTolerancePx ?? inherited?.tolerancePx ?? DEFAULT_VIEWPORT_TOLERANCE_PX) || DEFAULT_VIEWPORT_TOLERANCE_PX,
|
|
57
|
+
),
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* 双重超时保护:在 runtime 层强制超时,即使 fetch 超时失效
|
|
65
|
+
*/
|
|
66
|
+
async function withRuntimeLayerTimeout(promise, timeoutMs, timeoutMessage) {
|
|
67
|
+
let runtimeTimer = null;
|
|
68
|
+
|
|
69
|
+
return Promise.race([
|
|
70
|
+
promise,
|
|
71
|
+
new Promise((_, reject) => {
|
|
72
|
+
runtimeTimer = setTimeout(() => {
|
|
73
|
+
console.error(`[RuntimeLayerTimeout] ${timeoutMessage}`);
|
|
74
|
+
reject(new Error(`Runtime layer timeout after ${timeoutMs}ms: ${timeoutMessage}`));
|
|
75
|
+
}, timeoutMs);
|
|
76
|
+
}),
|
|
77
|
+
]).finally(() => {
|
|
78
|
+
if (runtimeTimer) clearTimeout(runtimeTimer);
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* 带强制 runtime 层超时的 API 调用
|
|
84
|
+
*/
|
|
85
|
+
async function callApiWithRuntimeTimeout(action, payload, timeoutMs, runtimeTimeoutMs) {
|
|
86
|
+
const effectiveTimeoutMs = resolveTimeoutMs(timeoutMs, DEFAULT_API_TIMEOUT_MS);
|
|
87
|
+
const effectiveRuntimeTimeoutMs = Math.min(effectiveTimeoutMs + 5000, RUNTIME_LAYER_TIMEOUT_MS);
|
|
88
|
+
|
|
89
|
+
console.log(`[callApiWithRuntimeTimeout] ${action} timeout: ${effectiveTimeoutMs}ms, runtime: ${effectiveRuntimeTimeoutMs}ms`);
|
|
90
|
+
|
|
91
|
+
return withRuntimeLayerTimeout(
|
|
92
|
+
callAPI(action, payload),
|
|
93
|
+
effectiveRuntimeTimeoutMs,
|
|
94
|
+
`${action} runtime timeout after ${effectiveRuntimeTimeoutMs}ms`,
|
|
95
|
+
);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
async function callApiWithTimeout(action, payload, timeoutMs) {
|
|
99
|
+
const effectiveTimeoutMs = resolveTimeoutMs(timeoutMs, DEFAULT_API_TIMEOUT_MS);
|
|
100
|
+
return withTimeout(
|
|
101
|
+
callAPI(action, payload),
|
|
102
|
+
effectiveTimeoutMs,
|
|
103
|
+
`${action} timeout after ${effectiveTimeoutMs}ms`,
|
|
104
|
+
);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
async function syncTabViewportIfNeeded({ profileId, syncConfig }) {
|
|
108
|
+
if (!syncConfig?.enabled) {
|
|
109
|
+
return { ok: true, code: 'OPERATION_SKIPPED', message: 'sync viewport disabled' };
|
|
110
|
+
}
|
|
111
|
+
return executeViewportOperation({
|
|
112
|
+
profileId,
|
|
113
|
+
action: 'sync_window_viewport',
|
|
114
|
+
params: {
|
|
115
|
+
followWindow: true,
|
|
116
|
+
settleMs: syncConfig.settleMs,
|
|
117
|
+
attempts: syncConfig.attempts,
|
|
118
|
+
tolerancePx: syncConfig.tolerancePx,
|
|
119
|
+
apiTimeoutMs: syncConfig.apiTimeoutMs,
|
|
120
|
+
},
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function parseUrl(raw) {
|
|
125
|
+
try {
|
|
126
|
+
return new URL(String(raw || ''));
|
|
127
|
+
} catch {
|
|
128
|
+
return null;
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
function normalizeSeedUrl(rawSeedUrl) {
|
|
133
|
+
const parsed = parseUrl(rawSeedUrl);
|
|
134
|
+
if (!parsed) return String(rawSeedUrl || '').trim();
|
|
135
|
+
const host = String(parsed.hostname || '').toLowerCase();
|
|
136
|
+
const pathname = String(parsed.pathname || '');
|
|
137
|
+
const isXhsHost = host.includes('xiaohongshu.com');
|
|
138
|
+
const isXhsDetailPath = /^\/explore\/[^/]+$/.test(pathname);
|
|
139
|
+
if (isXhsHost && isXhsDetailPath) {
|
|
140
|
+
parsed.pathname = '/explore';
|
|
141
|
+
parsed.search = '';
|
|
142
|
+
parsed.hash = '';
|
|
143
|
+
return parsed.toString();
|
|
144
|
+
}
|
|
145
|
+
return parsed.toString();
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
function isXhsDetailUrl(rawUrl) {
|
|
149
|
+
const parsed = parseUrl(rawUrl);
|
|
150
|
+
if (!parsed) return false;
|
|
151
|
+
const host = String(parsed.hostname || '').toLowerCase();
|
|
152
|
+
const pathname = String(parsed.pathname || '');
|
|
153
|
+
return host.includes('xiaohongshu.com') && /^\/explore\/[^/]+$/.test(pathname);
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
async function resolveXhsListUrlFromState(profileId, timeoutMs) {
|
|
157
|
+
try {
|
|
158
|
+
const payload = await callApiWithTimeout('evaluate', {
|
|
159
|
+
profileId,
|
|
160
|
+
script: `(() => {
|
|
161
|
+
const STATE_KEY = '__camoXhsState';
|
|
162
|
+
const safeString = (value) => typeof value === 'string' ? value.trim() : '';
|
|
163
|
+
let state = window.__camoXhsState && typeof window.__camoXhsState === 'object'
|
|
164
|
+
? window.__camoXhsState
|
|
165
|
+
: null;
|
|
166
|
+
if (!state) {
|
|
167
|
+
try {
|
|
168
|
+
const stored = localStorage.getItem(STATE_KEY);
|
|
169
|
+
if (stored) state = JSON.parse(stored);
|
|
170
|
+
} catch {}
|
|
171
|
+
}
|
|
172
|
+
const lastListUrl = safeString(state?.lastListUrl);
|
|
173
|
+
return { lastListUrl };
|
|
174
|
+
})()`,
|
|
175
|
+
}, timeoutMs);
|
|
176
|
+
const result = payload?.result || payload || {};
|
|
177
|
+
const candidate = String(result?.lastListUrl || '').trim();
|
|
178
|
+
return candidate || null;
|
|
179
|
+
} catch {
|
|
180
|
+
return null;
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
function shouldNavigateToSeed(currentUrl, seedUrl) {
|
|
185
|
+
const current = parseUrl(currentUrl);
|
|
186
|
+
const seed = parseUrl(seedUrl);
|
|
187
|
+
if (!seed) return false;
|
|
188
|
+
if (!current) return true;
|
|
189
|
+
const currentPath = String(current.pathname || '');
|
|
190
|
+
const seedPath = String(seed.pathname || '');
|
|
191
|
+
const currentIsXhsDetail = /^\/explore\/[^/]+$/.test(currentPath);
|
|
192
|
+
if (current.protocol === 'about:') return true;
|
|
193
|
+
if (current.origin !== seed.origin) return true;
|
|
194
|
+
if (seedPath.includes('/search_result') && !currentPath.includes('/search_result')) return true;
|
|
195
|
+
if (seedPath === '/explore' && currentIsXhsDetail) return true;
|
|
196
|
+
if (seedPath.includes('/explore') && !currentPath.includes('/explore') && !currentPath.includes('/search_result')) return true;
|
|
197
|
+
return false;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
async function seedNewestTabIfNeeded({
|
|
201
|
+
profileId,
|
|
202
|
+
seedUrl,
|
|
203
|
+
openDelayMs,
|
|
204
|
+
apiTimeoutMs,
|
|
205
|
+
navigationTimeoutMs,
|
|
206
|
+
syncConfig,
|
|
207
|
+
}) {
|
|
208
|
+
if (!seedUrl) return;
|
|
209
|
+
const listed = await callApiWithTimeout('page:list', { profileId }, apiTimeoutMs);
|
|
210
|
+
const { pages, activeIndex } = extractPageList(listed);
|
|
211
|
+
const newest = [...pages]
|
|
212
|
+
.filter((page) => Number.isFinite(Number(page?.index)))
|
|
213
|
+
.sort((a, b) => Number(b.index) - Number(a.index))[0];
|
|
214
|
+
if (!newest) return;
|
|
215
|
+
|
|
216
|
+
const targetIndex = Number(newest.index);
|
|
217
|
+
if (Number(activeIndex) !== targetIndex) {
|
|
218
|
+
await callApiWithTimeout('page:switch', { profileId, index: targetIndex }, apiTimeoutMs);
|
|
219
|
+
}
|
|
220
|
+
try {
|
|
221
|
+
if (shouldNavigateToSeed(newest.url, seedUrl)) {
|
|
222
|
+
await callApiWithTimeout('goto', { profileId, url: seedUrl }, navigationTimeoutMs);
|
|
223
|
+
if (openDelayMs > 0) await sleep(Math.min(openDelayMs, 1200));
|
|
224
|
+
}
|
|
225
|
+
const syncResult = await syncTabViewportIfNeeded({ profileId, syncConfig });
|
|
226
|
+
if (!syncResult?.ok) {
|
|
227
|
+
throw new Error(syncResult?.message || 'sync_window_viewport failed');
|
|
228
|
+
}
|
|
229
|
+
} catch {
|
|
230
|
+
// Best-effort seeding; failing to navigate/sync shouldn't block tab pool init.
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
async function waitForTabCountIncrease({
|
|
235
|
+
profileId,
|
|
236
|
+
beforeCount,
|
|
237
|
+
apiTimeoutMs,
|
|
238
|
+
maxWaitMs,
|
|
239
|
+
pollMs = 250,
|
|
240
|
+
}) {
|
|
241
|
+
const startedAt = Date.now();
|
|
242
|
+
const effectivePollMs = Math.max(80, Number(pollMs) || 250);
|
|
243
|
+
const waitMs = Math.max(400, Number(maxWaitMs) || 4000);
|
|
244
|
+
const listTimeoutMs = Math.max(1000, Math.min(resolveTimeoutMs(apiTimeoutMs, DEFAULT_API_TIMEOUT_MS), 8000));
|
|
245
|
+
let lastError = null;
|
|
246
|
+
|
|
247
|
+
while (Date.now() - startedAt <= waitMs) {
|
|
248
|
+
try {
|
|
249
|
+
const pollStartTime = Date.now();
|
|
250
|
+
const listed = await callApiWithRuntimeTimeout('page:list', { profileId }, listTimeoutMs, RUNTIME_LAYER_TIMEOUT_MS);
|
|
251
|
+
console.log(`[waitForTabCountIncrease] page:list took ${Date.now() - pollStartTime}ms`);
|
|
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
|
+
}
|