synabun 2026.3.31007 → 2026.4.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/CHANGELOG.md +51 -52
- package/hooks/claude-code/prompt-submit.mjs +6 -6
- package/mcp-server/dist/services/neural-interface.d.ts +20 -19
- package/mcp-server/dist/services/neural-interface.d.ts.map +1 -1
- package/mcp-server/dist/services/neural-interface.js +52 -45
- package/mcp-server/dist/services/neural-interface.js.map +1 -1
- package/mcp-server/dist/tools/browser-advanced.d.ts +4 -0
- package/mcp-server/dist/tools/browser-advanced.d.ts.map +1 -1
- package/mcp-server/dist/tools/browser-advanced.js +7 -4
- package/mcp-server/dist/tools/browser-advanced.js.map +1 -1
- package/mcp-server/dist/tools/browser-interact.d.ts +16 -0
- package/mcp-server/dist/tools/browser-interact.d.ts.map +1 -1
- package/mcp-server/dist/tools/browser-interact.js +25 -16
- package/mcp-server/dist/tools/browser-interact.js.map +1 -1
- package/mcp-server/dist/tools/browser-navigate.d.ts +8 -0
- package/mcp-server/dist/tools/browser-navigate.d.ts.map +1 -1
- package/mcp-server/dist/tools/browser-navigate.js +13 -8
- package/mcp-server/dist/tools/browser-navigate.js.map +1 -1
- package/mcp-server/dist/tools/browser-observe.d.ts +48 -0
- package/mcp-server/dist/tools/browser-observe.d.ts.map +1 -1
- package/mcp-server/dist/tools/browser-observe.js +74 -49
- package/mcp-server/dist/tools/browser-observe.js.map +1 -1
- package/mcp-server/dist/tools/leonardo-browser-tools.d.ts +20 -0
- package/mcp-server/dist/tools/leonardo-browser-tools.d.ts.map +1 -1
- package/mcp-server/dist/tools/leonardo-browser-tools.js +39 -34
- package/mcp-server/dist/tools/leonardo-browser-tools.js.map +1 -1
- package/mcp-server/src/services/neural-interface.ts +58 -46
- package/mcp-server/src/tools/browser-advanced.ts +10 -5
- package/mcp-server/src/tools/browser-interact.ts +34 -24
- package/mcp-server/src/tools/browser-navigate.ts +83 -77
- package/mcp-server/src/tools/browser-observe.ts +99 -73
- package/mcp-server/src/tools/leonardo-browser-tools.ts +47 -37
- package/neural-interface/public/shared/styles.css +49 -0
- package/neural-interface/public/shared/ui-automation-studio.js +71 -3
- package/neural-interface/public/shared/ui-claude-panel.js +29 -23
- package/neural-interface/public/shared/ui-settings.js +10 -10
- package/neural-interface/public/shared/ui-terminal.js +9 -7
- package/neural-interface/server.js +732 -386
- package/package.json +1 -1
|
@@ -4553,7 +4553,7 @@ app.get('/api/loop/active', (req, res) => {
|
|
|
4553
4553
|
// POST /api/loop/launch — create loop state + terminal session atomically
|
|
4554
4554
|
app.post('/api/loop/launch', async (req, res) => {
|
|
4555
4555
|
try {
|
|
4556
|
-
const { task, context, iterations, maxMinutes, usesBrowser, cwd, profile, model, browserSessionId: requestedBrowserSessionId } = req.body;
|
|
4556
|
+
const { task, context, iterations, maxMinutes, usesBrowser, cwd, profile, model, effort, browserSessionId: requestedBrowserSessionId } = req.body;
|
|
4557
4557
|
if (!task?.trim()) return res.status(400).json({ error: 'task is required' });
|
|
4558
4558
|
|
|
4559
4559
|
// Validate profile if provided
|
|
@@ -4587,22 +4587,33 @@ app.post('/api/loop/launch', async (req, res) => {
|
|
|
4587
4587
|
let browserSessionId = null;
|
|
4588
4588
|
let browserTabId = null;
|
|
4589
4589
|
if (usesBrowser) {
|
|
4590
|
-
// Strategy
|
|
4591
|
-
|
|
4592
|
-
|
|
4590
|
+
// Strategy 0: Best-effort pin to the caller-provided browser session.
|
|
4591
|
+
if (requestedBrowserSessionId) {
|
|
4592
|
+
const requested = browserSessions.get(requestedBrowserSessionId);
|
|
4593
|
+
if (requested) {
|
|
4593
4594
|
try {
|
|
4594
|
-
await
|
|
4595
|
-
browserSessionId =
|
|
4596
|
-
console.log(`[loop]
|
|
4597
|
-
|
|
4598
|
-
|
|
4599
|
-
|
|
4600
|
-
await destroyBrowserSession(id).catch(() => {});
|
|
4595
|
+
await requested.page.evaluate('1');
|
|
4596
|
+
browserSessionId = requestedBrowserSessionId;
|
|
4597
|
+
console.log(`[loop] Using requested browser session ${browserSessionId}`);
|
|
4598
|
+
} catch (err) {
|
|
4599
|
+
console.warn(`[loop] Requested browser session ${requestedBrowserSessionId} is unhealthy — destroying`);
|
|
4600
|
+
await destroyBrowserSession(requestedBrowserSessionId).catch(() => {});
|
|
4601
4601
|
}
|
|
4602
|
+
} else {
|
|
4603
|
+
console.warn(`[loop] Requested browser session ${requestedBrowserSessionId} not found — falling back to shared discovery`);
|
|
4604
|
+
}
|
|
4605
|
+
}
|
|
4606
|
+
|
|
4607
|
+
// Strategy 1: Reuse an existing healthy browser session
|
|
4608
|
+
if (!browserSessionId) {
|
|
4609
|
+
const reusable = await findReusableBrowserSession({ excludeAgentOwned: true });
|
|
4610
|
+
if (reusable) {
|
|
4611
|
+
browserSessionId = reusable.id;
|
|
4612
|
+
console.log(`[loop] Reusing existing browser session ${browserSessionId}`);
|
|
4602
4613
|
}
|
|
4603
4614
|
}
|
|
4604
4615
|
|
|
4605
|
-
// Strategy 2: No existing session —
|
|
4616
|
+
// Strategy 2: No existing session — create one using the selected browser profile
|
|
4606
4617
|
if (!browserSessionId) {
|
|
4607
4618
|
try {
|
|
4608
4619
|
const result = await createBrowserSession({ url: 'about:blank' });
|
|
@@ -4614,30 +4625,32 @@ app.post('/api/loop/launch', async (req, res) => {
|
|
|
4614
4625
|
profileMode: result.profileMode, profileSource: result.profileSource,
|
|
4615
4626
|
});
|
|
4616
4627
|
} catch (err) {
|
|
4617
|
-
console.warn(`[loop] Failed to create browser session: ${err.message}
|
|
4628
|
+
console.warn(`[loop] Failed to create browser session: ${err.message}`);
|
|
4618
4629
|
}
|
|
4619
4630
|
}
|
|
4620
4631
|
|
|
4632
|
+
if (!browserSessionId) {
|
|
4633
|
+
return res.status(500).json({ error: 'Could not start browser session for this loop. Open Browser Settings and verify the selected profile can launch.' });
|
|
4634
|
+
}
|
|
4635
|
+
|
|
4621
4636
|
// Open a new tab in the shared session for this loop
|
|
4622
|
-
|
|
4623
|
-
|
|
4624
|
-
|
|
4625
|
-
|
|
4626
|
-
|
|
4627
|
-
|
|
4628
|
-
|
|
4629
|
-
|
|
4630
|
-
|
|
4631
|
-
|
|
4632
|
-
|
|
4633
|
-
|
|
4634
|
-
|
|
4635
|
-
|
|
4636
|
-
browserTabId = claimedSession.activeTabId;
|
|
4637
|
-
}
|
|
4638
|
-
} else {
|
|
4639
|
-
browserTabId = claimedSession?.activeTabId || null;
|
|
4637
|
+
const claimedSession = browserSessions.get(browserSessionId);
|
|
4638
|
+
if (claimedSession?.graceTimer) {
|
|
4639
|
+
clearTimeout(claimedSession.graceTimer);
|
|
4640
|
+
claimedSession.graceTimer = null;
|
|
4641
|
+
}
|
|
4642
|
+
if (claimedSession?.tabs && claimedSession.tabs.size > 0) {
|
|
4643
|
+
try {
|
|
4644
|
+
const newTab = await createSessionTab(claimedSession, browserSessionId, 'about:blank');
|
|
4645
|
+
browserTabId = newTab.tabId;
|
|
4646
|
+
await _switchSessionTab(claimedSession, browserSessionId, browserTabId);
|
|
4647
|
+
console.log(`[loop] Created new tab ${browserTabId} in session ${browserSessionId}`);
|
|
4648
|
+
} catch (err) {
|
|
4649
|
+
console.warn(`[loop] Failed to create new tab, reusing active tab:`, err.message);
|
|
4650
|
+
browserTabId = claimedSession.activeTabId;
|
|
4640
4651
|
}
|
|
4652
|
+
} else {
|
|
4653
|
+
browserTabId = claimedSession?.activeTabId || null;
|
|
4641
4654
|
}
|
|
4642
4655
|
}
|
|
4643
4656
|
|
|
@@ -4652,7 +4665,8 @@ app.post('/api/loop/launch', async (req, res) => {
|
|
|
4652
4665
|
const terminalSessionId = randomBytes(16).toString('hex');
|
|
4653
4666
|
const loopExtraEnv = { SYNABUN_TERMINAL_SESSION: terminalSessionId };
|
|
4654
4667
|
if (browserSessionId) loopExtraEnv.SYNABUN_BROWSER_SESSION = browserSessionId;
|
|
4655
|
-
|
|
4668
|
+
if (browserTabId) loopExtraEnv.SYNABUN_BROWSER_TAB = browserTabId;
|
|
4669
|
+
createTerminalSession(cliProfile, 120, 30, loopCwd, { model, effort, extraEnv: loopExtraEnv, sessionId: terminalSessionId });
|
|
4656
4670
|
|
|
4657
4671
|
// 3. Create pending loop state file (placeholder — prompt-submit hook will rename)
|
|
4658
4672
|
const pendingId = 'pending-' + randomBytes(8).toString('hex');
|
|
@@ -4673,6 +4687,7 @@ app.post('/api/loop/launch', async (req, res) => {
|
|
|
4673
4687
|
browserTabId: browserTabId || null,
|
|
4674
4688
|
profile: cliProfile,
|
|
4675
4689
|
model: model || null,
|
|
4690
|
+
effort: effort || null,
|
|
4676
4691
|
};
|
|
4677
4692
|
writeFileSync(resolve(LOOP_DIR, `${pendingId}.json`), JSON.stringify(loopState, null, 2));
|
|
4678
4693
|
|
|
@@ -4946,18 +4961,17 @@ async function launchScheduledLoop(schedule) {
|
|
|
4946
4961
|
|
|
4947
4962
|
const cliProfile = schedule.profile || 'claude-code';
|
|
4948
4963
|
const cliModel = schedule.model || null;
|
|
4964
|
+
const cliEffort = schedule.effort || null;
|
|
4949
4965
|
const scheduledUsesBrowser = schedule.usesBrowser !== undefined ? !!schedule.usesBrowser : !!template.usesBrowser;
|
|
4950
4966
|
|
|
4951
|
-
// Reuse existing
|
|
4967
|
+
// Reuse an existing healthy browser session or create one
|
|
4952
4968
|
let scheduledBrowserSessionId = null;
|
|
4953
4969
|
let scheduledBrowserTabId = null;
|
|
4954
4970
|
const schedExtraEnv = {};
|
|
4955
4971
|
if (scheduledUsesBrowser) {
|
|
4956
|
-
|
|
4957
|
-
|
|
4958
|
-
|
|
4959
|
-
try { await session.page.evaluate('1'); scheduledBrowserSessionId = id; break; } catch {}
|
|
4960
|
-
}
|
|
4972
|
+
const reusable = await findReusableBrowserSession({ excludeAgentOwned: true });
|
|
4973
|
+
if (reusable) {
|
|
4974
|
+
scheduledBrowserSessionId = reusable.id;
|
|
4961
4975
|
}
|
|
4962
4976
|
// Create if none exists
|
|
4963
4977
|
if (!scheduledBrowserSessionId) {
|
|
@@ -4974,6 +4988,9 @@ async function launchScheduledLoop(schedule) {
|
|
|
4974
4988
|
console.warn(`[schedule] Failed to create browser session: ${err.message}`);
|
|
4975
4989
|
}
|
|
4976
4990
|
}
|
|
4991
|
+
if (!scheduledBrowserSessionId) {
|
|
4992
|
+
throw new Error('Could not start browser session for scheduled loop');
|
|
4993
|
+
}
|
|
4977
4994
|
// Open a new tab for this scheduled loop
|
|
4978
4995
|
if (scheduledBrowserSessionId) {
|
|
4979
4996
|
schedExtraEnv.SYNABUN_BROWSER_SESSION = scheduledBrowserSessionId;
|
|
@@ -4986,10 +5003,11 @@ async function launchScheduledLoop(schedule) {
|
|
|
4986
5003
|
await _switchSessionTab(bSession, scheduledBrowserSessionId, scheduledBrowserTabId);
|
|
4987
5004
|
} catch { scheduledBrowserTabId = bSession.activeTabId; }
|
|
4988
5005
|
}
|
|
5006
|
+
if (scheduledBrowserTabId) schedExtraEnv.SYNABUN_BROWSER_TAB = scheduledBrowserTabId;
|
|
4989
5007
|
}
|
|
4990
5008
|
}
|
|
4991
5009
|
|
|
4992
|
-
const terminalSessionId = createTerminalSession(cliProfile, 120, 30, PACKAGE_ROOT, { model: cliModel, extraEnv: schedExtraEnv });
|
|
5010
|
+
const terminalSessionId = createTerminalSession(cliProfile, 120, 30, PACKAGE_ROOT, { model: cliModel, effort: cliEffort, extraEnv: schedExtraEnv });
|
|
4993
5011
|
|
|
4994
5012
|
const pendingId = 'pending-' + randomBytes(8).toString('hex');
|
|
4995
5013
|
const loopState = {
|
|
@@ -5157,6 +5175,7 @@ function launchQuickTimer(timerId, templateId, context) {
|
|
|
5157
5175
|
dayThemes: {},
|
|
5158
5176
|
profile: timerData.profile || undefined,
|
|
5159
5177
|
model: timerData.model || undefined,
|
|
5178
|
+
effort: timerData.effort || undefined,
|
|
5160
5179
|
usesBrowser: timerData.usesBrowser,
|
|
5161
5180
|
};
|
|
5162
5181
|
console.log(`[quick-timer] Firing "${template.name}" (timer ${timerId}) profile=${fakeSchedule.profile || 'default'} model=${fakeSchedule.model || 'default'}`);
|
|
@@ -5168,7 +5187,7 @@ function launchQuickTimer(timerId, templateId, context) {
|
|
|
5168
5187
|
// POST /api/quick-timer — fire a template after N minutes (standalone, no schedule)
|
|
5169
5188
|
app.post('/api/quick-timer', (req, res) => {
|
|
5170
5189
|
try {
|
|
5171
|
-
const { templateId, minutes, context, profile, model, usesBrowser } = req.body;
|
|
5190
|
+
const { templateId, minutes, context, profile, model, effort, usesBrowser } = req.body;
|
|
5172
5191
|
const mins = Number(minutes);
|
|
5173
5192
|
if (!templateId?.trim()) return res.status(400).json({ error: 'templateId is required' });
|
|
5174
5193
|
if (!mins || mins < 1 || mins > 1440) return res.status(400).json({ error: 'minutes must be 1–1440' });
|
|
@@ -5181,6 +5200,7 @@ app.post('/api/quick-timer', (req, res) => {
|
|
|
5181
5200
|
const firesAt = new Date(Date.now() + mins * 60_000).toISOString();
|
|
5182
5201
|
const timerProfile = profile || 'claude-code';
|
|
5183
5202
|
const timerModel = model || null;
|
|
5203
|
+
const timerEffort = effort || null;
|
|
5184
5204
|
const timerUsesBrowser = usesBrowser !== undefined ? !!usesBrowser : !!template.usesBrowser;
|
|
5185
5205
|
|
|
5186
5206
|
const timeoutId = setTimeout(() => {
|
|
@@ -5188,10 +5208,10 @@ app.post('/api/quick-timer', (req, res) => {
|
|
|
5188
5208
|
_quickTimers.delete(timerId);
|
|
5189
5209
|
}, mins * 60_000);
|
|
5190
5210
|
|
|
5191
|
-
_quickTimers.set(timerId, { timeoutId, templateId, templateName: template.name, firesAt, minutes: mins, profile: timerProfile, model: timerModel, usesBrowser: timerUsesBrowser, createdAt: new Date().toISOString() });
|
|
5192
|
-
console.log(`[quick-timer] Set: "${template.name}" fires in ${mins}m at ${firesAt} (${timerProfile}/${timerModel || 'default'})`);
|
|
5193
|
-
broadcastSync({ type: 'quick-timer:set', timerId, templateName: template.name, firesAt, minutes: mins, profile: timerProfile, model: timerModel, usesBrowser: timerUsesBrowser });
|
|
5194
|
-
res.json({ ok: true, timerId, templateName: template.name, firesAt, minutes: mins, profile: timerProfile, model: timerModel, usesBrowser: timerUsesBrowser });
|
|
5211
|
+
_quickTimers.set(timerId, { timeoutId, templateId, templateName: template.name, firesAt, minutes: mins, profile: timerProfile, model: timerModel, effort: timerEffort, usesBrowser: timerUsesBrowser, createdAt: new Date().toISOString() });
|
|
5212
|
+
console.log(`[quick-timer] Set: "${template.name}" fires in ${mins}m at ${firesAt} (${timerProfile}/${timerModel || 'default'}${timerEffort ? '/' + timerEffort : ''})`);
|
|
5213
|
+
broadcastSync({ type: 'quick-timer:set', timerId, templateName: template.name, firesAt, minutes: mins, profile: timerProfile, model: timerModel, effort: timerEffort, usesBrowser: timerUsesBrowser });
|
|
5214
|
+
res.json({ ok: true, timerId, templateName: template.name, firesAt, minutes: mins, profile: timerProfile, model: timerModel, effort: timerEffort, usesBrowser: timerUsesBrowser });
|
|
5195
5215
|
} catch (err) {
|
|
5196
5216
|
res.status(500).json({ error: err.message });
|
|
5197
5217
|
}
|
|
@@ -5220,7 +5240,7 @@ app.delete('/api/quick-timers/:id', (req, res) => {
|
|
|
5220
5240
|
// POST /api/quick-timer/now — fire a template immediately (same pipeline as scheduled, for debugging)
|
|
5221
5241
|
app.post('/api/quick-timer/now', (req, res) => {
|
|
5222
5242
|
try {
|
|
5223
|
-
const { templateId, profile, model, usesBrowser } = req.body;
|
|
5243
|
+
const { templateId, profile, model, effort, usesBrowser } = req.body;
|
|
5224
5244
|
if (!templateId?.trim()) return res.status(400).json({ error: 'templateId is required' });
|
|
5225
5245
|
|
|
5226
5246
|
const templates = readLoopTemplates();
|
|
@@ -5229,6 +5249,7 @@ app.post('/api/quick-timer/now', (req, res) => {
|
|
|
5229
5249
|
|
|
5230
5250
|
const timerProfile = profile || 'claude-code';
|
|
5231
5251
|
const timerModel = model || null;
|
|
5252
|
+
const timerEffort = effort || null;
|
|
5232
5253
|
const timerUsesBrowser = usesBrowser !== undefined ? !!usesBrowser : !!template.usesBrowser;
|
|
5233
5254
|
|
|
5234
5255
|
const fakeSchedule = {
|
|
@@ -5239,15 +5260,16 @@ app.post('/api/quick-timer/now', (req, res) => {
|
|
|
5239
5260
|
dayThemes: {},
|
|
5240
5261
|
profile: timerProfile,
|
|
5241
5262
|
model: timerModel,
|
|
5263
|
+
effort: timerEffort,
|
|
5242
5264
|
usesBrowser: timerUsesBrowser,
|
|
5243
5265
|
};
|
|
5244
5266
|
|
|
5245
|
-
console.log(`[quick-timer] Firing NOW "${template.name}" profile=${timerProfile} model=${timerModel || 'default'}`);
|
|
5267
|
+
console.log(`[quick-timer] Firing NOW "${template.name}" profile=${timerProfile} model=${timerModel || 'default'}${timerEffort ? ' effort=' + timerEffort : ''}`);
|
|
5246
5268
|
_scheduleQueue.push(fakeSchedule);
|
|
5247
5269
|
processScheduleQueue();
|
|
5248
5270
|
|
|
5249
|
-
broadcastSync({ type: 'quick-timer:fired-now', templateName: template.name, profile: timerProfile, model: timerModel });
|
|
5250
|
-
res.json({ ok: true, templateName: template.name, profile: timerProfile, model: timerModel, usesBrowser: timerUsesBrowser });
|
|
5271
|
+
broadcastSync({ type: 'quick-timer:fired-now', templateName: template.name, profile: timerProfile, model: timerModel, effort: timerEffort });
|
|
5272
|
+
res.json({ ok: true, templateName: template.name, profile: timerProfile, model: timerModel, effort: timerEffort, usesBrowser: timerUsesBrowser });
|
|
5251
5273
|
} catch (err) {
|
|
5252
5274
|
res.status(500).json({ error: err.message });
|
|
5253
5275
|
}
|
|
@@ -5452,12 +5474,13 @@ const AGENT_IS_WIN = process.platform === 'win32';
|
|
|
5452
5474
|
* - withSynabun=false → empty config (fully isolated)
|
|
5453
5475
|
* - withSynabun=true → includes SynaBun MCP with optional browser session pinning
|
|
5454
5476
|
*/
|
|
5455
|
-
function buildAgentMcpConfig(withSynabun, browserSessionId) {
|
|
5477
|
+
function buildAgentMcpConfig(withSynabun, browserSessionId, browserTabId) {
|
|
5456
5478
|
if (!withSynabun) return '{"mcpServers":{}}';
|
|
5457
5479
|
const mcpPreload = resolve(PACKAGE_ROOT, 'mcp-server', 'dist', 'preload.js');
|
|
5458
5480
|
const dotenvPath = resolve(DATA_HOME, '.env');
|
|
5459
5481
|
const env = { DOTENV_PATH: dotenvPath, SYNABUN_DATA_HOME: DATA_HOME, MEMORY_DATA_DIR: resolve(DATA_HOME, 'mcp-data') };
|
|
5460
5482
|
if (browserSessionId) env.SYNABUN_BROWSER_SESSION = browserSessionId;
|
|
5483
|
+
if (browserTabId) env.SYNABUN_BROWSER_TAB = browserTabId;
|
|
5461
5484
|
return JSON.stringify({
|
|
5462
5485
|
mcpServers: {
|
|
5463
5486
|
SynaBun: { type: 'stdio', command: 'node', args: [mcpPreload], env },
|
|
@@ -5493,6 +5516,7 @@ function spawnAgentProcess(agent, prompt, extraEnv = {}) {
|
|
|
5493
5516
|
agent._resumableSessionId = sessionId; // Mark this session-id as resumable for next iteration
|
|
5494
5517
|
|
|
5495
5518
|
if (agent.model && agent.model !== 'default') args.push('--model', agent.model);
|
|
5519
|
+
if (agent.effort && ['low', 'medium', 'high', 'max'].includes(agent.effort)) args.push('--effort', agent.effort);
|
|
5496
5520
|
if (agent._maxTurns) args.push('--max-turns', String(agent._maxTurns));
|
|
5497
5521
|
if (agent._systemPrompt) args.push('--system-prompt', agent._systemPrompt);
|
|
5498
5522
|
if (agent._allowedTools?.length) args.push('--allowedTools', ...agent._allowedTools);
|
|
@@ -5598,13 +5622,13 @@ function spawnAgentProcess(agent, prompt, extraEnv = {}) {
|
|
|
5598
5622
|
*/
|
|
5599
5623
|
async function launchAgentController(opts) {
|
|
5600
5624
|
const {
|
|
5601
|
-
task, model, cwd, allowedTools, addDirs, systemPrompt, maxTurns,
|
|
5602
|
-
withSynabun = false, browserSessionId = null,
|
|
5625
|
+
task, model, effort, cwd, allowedTools, addDirs, systemPrompt, maxTurns,
|
|
5626
|
+
withSynabun = false, browserSessionId = null, browserTabId = null,
|
|
5603
5627
|
mode = 'single', iterations = 1, maxMinutes = 30, context = null,
|
|
5604
5628
|
} = opts;
|
|
5605
5629
|
|
|
5606
5630
|
const agentId = randomUUID();
|
|
5607
|
-
const mcpConfig = buildAgentMcpConfig(withSynabun, browserSessionId);
|
|
5631
|
+
const mcpConfig = buildAgentMcpConfig(withSynabun, browserSessionId, browserTabId);
|
|
5608
5632
|
const agentCwd = cwd || PACKAGE_ROOT;
|
|
5609
5633
|
|
|
5610
5634
|
// Build default system prompt for agents — overrides CLAUDE.md boot sequence
|
|
@@ -5649,6 +5673,7 @@ async function launchAgentController(opts) {
|
|
|
5649
5673
|
sessionId: randomUUID(),
|
|
5650
5674
|
task,
|
|
5651
5675
|
model: model || 'default',
|
|
5676
|
+
effort: effort || null,
|
|
5652
5677
|
cwd: agentCwd,
|
|
5653
5678
|
status: 'running',
|
|
5654
5679
|
mode,
|
|
@@ -5729,7 +5754,8 @@ async function launchAgentController(opts) {
|
|
|
5729
5754
|
agent.browserSessionId = nb.sessionId;
|
|
5730
5755
|
const bs = browserSessions.get(nb.sessionId);
|
|
5731
5756
|
if (bs) bs._agentOwned = agentId;
|
|
5732
|
-
agent.
|
|
5757
|
+
agent.browserTabId = bs?.activeTabId || null;
|
|
5758
|
+
agent._mcpConfig = buildAgentMcpConfig(agent.withSynabun, agent.browserSessionId, agent.browserTabId);
|
|
5733
5759
|
console.log(`[agent] ${agentId} fresh browser ${agent.browserSessionId} for iteration ${i}`);
|
|
5734
5760
|
break;
|
|
5735
5761
|
} catch (err) {
|
|
@@ -5738,7 +5764,7 @@ async function launchAgentController(opts) {
|
|
|
5738
5764
|
else {
|
|
5739
5765
|
console.error(`[agent] ${agentId} all browser create attempts failed for iteration ${i}`);
|
|
5740
5766
|
// Update MCP config without browser so agent doesn't reference a dead session
|
|
5741
|
-
agent._mcpConfig = buildAgentMcpConfig(agent.withSynabun, null);
|
|
5767
|
+
agent._mcpConfig = buildAgentMcpConfig(agent.withSynabun, null, null);
|
|
5742
5768
|
}
|
|
5743
5769
|
}
|
|
5744
5770
|
}
|
|
@@ -5886,7 +5912,7 @@ async function launchAgentController(opts) {
|
|
|
5886
5912
|
app.post('/api/agents/launch', async (req, res) => {
|
|
5887
5913
|
try {
|
|
5888
5914
|
const {
|
|
5889
|
-
task, model, cwd, allowedTools, addDirs, systemPrompt, maxTurns,
|
|
5915
|
+
task, model, effort, cwd, allowedTools, addDirs, systemPrompt, maxTurns,
|
|
5890
5916
|
withSynabun, browserProfile,
|
|
5891
5917
|
mode, iterations, maxMinutes, context,
|
|
5892
5918
|
} = req.body;
|
|
@@ -5906,7 +5932,8 @@ app.post('/api/agents/launch', async (req, res) => {
|
|
|
5906
5932
|
});
|
|
5907
5933
|
console.log(`[agent] Pre-created browser session ${browserSessionId} for agent`);
|
|
5908
5934
|
} catch (err) {
|
|
5909
|
-
console.warn(`[agent] Browser pre-create failed: ${err.message}
|
|
5935
|
+
console.warn(`[agent] Browser pre-create failed: ${err.message}`);
|
|
5936
|
+
return res.status(500).json({ error: `Could not start browser session for this automation: ${err.message}` });
|
|
5910
5937
|
}
|
|
5911
5938
|
}
|
|
5912
5939
|
|
|
@@ -5915,7 +5942,7 @@ app.post('/api/agents/launch', async (req, res) => {
|
|
|
5915
5942
|
const effectiveMaxTurns = maxTurns || (browserSessionId ? 200 : 100);
|
|
5916
5943
|
|
|
5917
5944
|
const agent = await launchAgentController({
|
|
5918
|
-
task: task.trim(), model, cwd, allowedTools, addDirs, systemPrompt,
|
|
5945
|
+
task: task.trim(), model, effort, cwd, allowedTools, addDirs, systemPrompt,
|
|
5919
5946
|
maxTurns: effectiveMaxTurns,
|
|
5920
5947
|
withSynabun: !!withSynabun,
|
|
5921
5948
|
browserSessionId,
|
|
@@ -10446,6 +10473,14 @@ function getTerminalProfile(profileId, opts = {}) {
|
|
|
10446
10473
|
if (builder) cmd = builder(cleanModel);
|
|
10447
10474
|
}
|
|
10448
10475
|
|
|
10476
|
+
// Append effort flag for Claude Code (extended thinking)
|
|
10477
|
+
if (opts.effort && profileId === 'claude-code') {
|
|
10478
|
+
const validEfforts = ['low', 'medium', 'high', 'max'];
|
|
10479
|
+
if (validEfforts.includes(opts.effort)) {
|
|
10480
|
+
cmd = `${cmd} --effort ${opts.effort}`;
|
|
10481
|
+
}
|
|
10482
|
+
}
|
|
10483
|
+
|
|
10449
10484
|
return {
|
|
10450
10485
|
shell: DEFAULT_SHELL,
|
|
10451
10486
|
args: IS_WIN ? ['/k', cmd] : ['-c', `${cmd}; exec $SHELL`],
|
|
@@ -12598,6 +12633,38 @@ function isSessionUsedByActiveLoop(sessionId) {
|
|
|
12598
12633
|
return false;
|
|
12599
12634
|
}
|
|
12600
12635
|
|
|
12636
|
+
async function findReusableBrowserSession(opts = {}) {
|
|
12637
|
+
const { excludeAgentOwned = true } = opts;
|
|
12638
|
+
const cfg = loadBrowserConfig();
|
|
12639
|
+
let selectedPath = cfg.userDataDir || '';
|
|
12640
|
+
if (selectedPath && !selectedPath.startsWith('/') && !(/^[A-Z]:/i.test(selectedPath))) {
|
|
12641
|
+
selectedPath = resolve(DATA_HOME, selectedPath);
|
|
12642
|
+
}
|
|
12643
|
+
const normalize = (p) => (p || '').replace(/[\\/]+$/, '').replace(/\\/g, '/').toLowerCase();
|
|
12644
|
+
const selectedNorm = normalize(selectedPath);
|
|
12645
|
+
for (const [id, session] of browserSessions) {
|
|
12646
|
+
if (excludeAgentOwned && session._agentOwned) continue;
|
|
12647
|
+
if (selectedNorm) {
|
|
12648
|
+
const sessionSelected = normalize(session._selectedProfilePath);
|
|
12649
|
+
const sessionRoot = normalize(session._launchUserDataDir);
|
|
12650
|
+
const sessionActiveProfile = normalize(resolve(session._launchUserDataDir || '', session._launchProfileDirectory || 'Default'));
|
|
12651
|
+
if (selectedNorm !== sessionSelected && selectedNorm !== sessionRoot && selectedNorm !== sessionActiveProfile) {
|
|
12652
|
+
continue;
|
|
12653
|
+
}
|
|
12654
|
+
} else if (session._profileMode !== 'clean') {
|
|
12655
|
+
continue;
|
|
12656
|
+
}
|
|
12657
|
+
try {
|
|
12658
|
+
await session.page.evaluate('1');
|
|
12659
|
+
return { id, session };
|
|
12660
|
+
} catch {
|
|
12661
|
+
console.warn(`[browser] Existing session ${id} is a zombie — destroying`);
|
|
12662
|
+
await destroyBrowserSession(id).catch(() => {});
|
|
12663
|
+
}
|
|
12664
|
+
}
|
|
12665
|
+
return null;
|
|
12666
|
+
}
|
|
12667
|
+
|
|
12601
12668
|
// ── Real-time sync WebSocket (multi-client state broadcast) ──
|
|
12602
12669
|
const syncClients = new Set(); // Set<WebSocket>
|
|
12603
12670
|
|
|
@@ -12927,44 +12994,173 @@ function detectChromeProfiles() {
|
|
|
12927
12994
|
return profiles;
|
|
12928
12995
|
}
|
|
12929
12996
|
|
|
12997
|
+
function lookupDetectedProfile(profilePath) {
|
|
12998
|
+
if (!profilePath) return null;
|
|
12999
|
+
const needle = profilePath.replace(/\\/g, '/').toLowerCase().replace(/\/+$/, '');
|
|
13000
|
+
return detectChromeProfiles().find(p => (
|
|
13001
|
+
p.path.replace(/\\/g, '/').toLowerCase().replace(/\/+$/, '') === needle
|
|
13002
|
+
)) || null;
|
|
13003
|
+
}
|
|
13004
|
+
|
|
13005
|
+
function isBrowserProcessRunning(browserType = 'chrome') {
|
|
13006
|
+
try {
|
|
13007
|
+
if (IS_WIN) {
|
|
13008
|
+
const image = browserType === 'msedge' ? 'msedge.exe' : 'chrome.exe';
|
|
13009
|
+
const tasklist = execSync(`tasklist /FI "IMAGENAME eq ${image}" /NH`, { encoding: 'utf8', timeout: 3000 });
|
|
13010
|
+
return tasklist.toLowerCase().includes(image.toLowerCase());
|
|
13011
|
+
}
|
|
13012
|
+
if (process.platform === 'darwin') {
|
|
13013
|
+
const proc = browserType === 'msedge' ? 'Microsoft Edge' : browserType === 'chromium' ? 'Chromium' : 'Google Chrome';
|
|
13014
|
+
const pgrep = execSync(`pgrep -x "${proc}"`, { encoding: 'utf8', timeout: 3000 });
|
|
13015
|
+
return pgrep.trim().length > 0;
|
|
13016
|
+
}
|
|
13017
|
+
const primary = browserType === 'msedge' ? 'microsoft-edge' : browserType === 'chromium' ? 'chromium' : 'chrome';
|
|
13018
|
+
const fallback = browserType === 'msedge' ? 'microsoft-edge-stable' : browserType === 'chromium' ? 'chromium-browser' : 'google-chrome';
|
|
13019
|
+
const pgrep = execSync(`pgrep -x "${primary}" || pgrep -x "${fallback}"`, { encoding: 'utf8', timeout: 3000 });
|
|
13020
|
+
return pgrep.trim().length > 0;
|
|
13021
|
+
} catch {
|
|
13022
|
+
return false;
|
|
13023
|
+
}
|
|
13024
|
+
}
|
|
13025
|
+
|
|
13026
|
+
function getManagedProfileRoot() {
|
|
13027
|
+
return resolve(DATA_HOME, 'data', 'chrome-profile');
|
|
13028
|
+
}
|
|
13029
|
+
|
|
13030
|
+
function prepareMirroredProfile(sourceRoot, profileDirectory, browserType = 'chrome') {
|
|
13031
|
+
const sourceProfileDir = resolve(sourceRoot, profileDirectory || 'Default');
|
|
13032
|
+
if (!existsSync(sourceProfileDir)) {
|
|
13033
|
+
throw new Error(`Selected profile directory not found: ${sourceProfileDir}`);
|
|
13034
|
+
}
|
|
13035
|
+
|
|
13036
|
+
const mirrorKey = createHash('md5')
|
|
13037
|
+
.update(`${browserType}:${sourceRoot}:${profileDirectory || 'Default'}`)
|
|
13038
|
+
.digest('hex')
|
|
13039
|
+
.slice(0, 12);
|
|
13040
|
+
const mirrorRoot = resolve(DATA_HOME, 'data', 'browser-profiles', mirrorKey);
|
|
13041
|
+
const mirrorProfileDir = resolve(mirrorRoot, profileDirectory || 'Default');
|
|
13042
|
+
|
|
13043
|
+
mkdirSync(mirrorRoot, { recursive: true });
|
|
13044
|
+
|
|
13045
|
+
// Seed the mirror once from the selected profile; after that the mirror owns its state.
|
|
13046
|
+
if (!existsSync(mirrorProfileDir)) {
|
|
13047
|
+
console.log(`[browser] Seeding mirrored profile from ${sourceProfileDir} -> ${mirrorProfileDir}`);
|
|
13048
|
+
cpSync(sourceProfileDir, mirrorProfileDir, { recursive: true });
|
|
13049
|
+
}
|
|
13050
|
+
|
|
13051
|
+
const localStateSrc = resolve(sourceRoot, 'Local State');
|
|
13052
|
+
const localStateDest = resolve(mirrorRoot, 'Local State');
|
|
13053
|
+
if (existsSync(localStateSrc)) {
|
|
13054
|
+
try { copyFileSync(localStateSrc, localStateDest); } catch {}
|
|
13055
|
+
}
|
|
13056
|
+
|
|
13057
|
+
for (const stale of ['SingletonLock', 'SingletonSocket', 'SingletonCookie', 'DevToolsActivePort']) {
|
|
13058
|
+
try {
|
|
13059
|
+
const rootPath = resolve(mirrorRoot, stale);
|
|
13060
|
+
if (existsSync(rootPath)) unlinkSync(rootPath);
|
|
13061
|
+
} catch {}
|
|
13062
|
+
try {
|
|
13063
|
+
const profilePath = resolve(mirrorProfileDir, stale);
|
|
13064
|
+
if (existsSync(profilePath)) unlinkSync(profilePath);
|
|
13065
|
+
} catch {}
|
|
13066
|
+
}
|
|
13067
|
+
|
|
13068
|
+
return { mirrorRoot, mirrorProfileDir };
|
|
13069
|
+
}
|
|
13070
|
+
|
|
12930
13071
|
// ── Shared system browser: one-time CDP setup ──
|
|
12931
|
-
//
|
|
12932
|
-
//
|
|
12933
|
-
// Self-heals if Chrome was quit externally (re-probes port 9222).
|
|
13072
|
+
// Prefers port 9222 for compatibility, but can self-heal to a dynamic DevTools
|
|
13073
|
+
// endpoint when 9222 isn't exposed in time.
|
|
12934
13074
|
const CDP_PORT = 9222;
|
|
13075
|
+
const CDP_LAUNCH_TIMEOUT_MS = 20000;
|
|
12935
13076
|
let _chromeDebuggableReady = false;
|
|
13077
|
+
let _chromeCdpEndpoint = null; // http://127.0.0.1:<port>
|
|
13078
|
+
let _chromeDebugCacheKey = null;
|
|
12936
13079
|
|
|
12937
|
-
|
|
13080
|
+
function _cdpCacheKey(executablePath, userDataDir, profileDirectory) {
|
|
13081
|
+
const ep = (executablePath || '').replace(/\\/g, '/').toLowerCase();
|
|
13082
|
+
const udd = (userDataDir || '').replace(/[\\/]+$/, '').replace(/\\/g, '/').toLowerCase();
|
|
13083
|
+
const pd = (profileDirectory || '').toLowerCase();
|
|
13084
|
+
return `${ep}|${udd}|${pd}`;
|
|
13085
|
+
}
|
|
13086
|
+
|
|
13087
|
+
function _toHttpEndpoint(endpointOrPort) {
|
|
13088
|
+
if (typeof endpointOrPort === 'number') return `http://127.0.0.1:${endpointOrPort}`;
|
|
13089
|
+
if (!endpointOrPort || typeof endpointOrPort !== 'string') return null;
|
|
13090
|
+
if (endpointOrPort.startsWith('http://') || endpointOrPort.startsWith('https://')) {
|
|
13091
|
+
return endpointOrPort.replace(/\/+$/, '');
|
|
13092
|
+
}
|
|
13093
|
+
if (endpointOrPort.startsWith('ws://') || endpointOrPort.startsWith('wss://')) {
|
|
13094
|
+
try {
|
|
13095
|
+
const u = new URL(endpointOrPort);
|
|
13096
|
+
return `http://${u.hostname}:${u.port}`;
|
|
13097
|
+
} catch {
|
|
13098
|
+
return null;
|
|
13099
|
+
}
|
|
13100
|
+
}
|
|
13101
|
+
return null;
|
|
13102
|
+
}
|
|
13103
|
+
|
|
13104
|
+
async function probeCdpEndpoint(endpointOrPort) {
|
|
12938
13105
|
const http = await import('node:http');
|
|
13106
|
+
const httpEndpoint = _toHttpEndpoint(endpointOrPort);
|
|
13107
|
+
if (!httpEndpoint) return { ok: false };
|
|
12939
13108
|
|
|
12940
|
-
|
|
12941
|
-
const req = http.get(
|
|
13109
|
+
return await new Promise((resolveP) => {
|
|
13110
|
+
const req = http.get(`${httpEndpoint}/json/version`, (res) => {
|
|
12942
13111
|
let data = '';
|
|
12943
13112
|
res.on('data', chunk => data += chunk);
|
|
12944
|
-
res.on('end', () =>
|
|
13113
|
+
res.on('end', () => {
|
|
13114
|
+
if (!res.statusCode || res.statusCode < 200 || res.statusCode >= 300) {
|
|
13115
|
+
return resolveP({ ok: false });
|
|
13116
|
+
}
|
|
13117
|
+
try {
|
|
13118
|
+
const parsed = JSON.parse(data || '{}');
|
|
13119
|
+
resolveP({
|
|
13120
|
+
ok: true,
|
|
13121
|
+
httpEndpoint,
|
|
13122
|
+
wsEndpoint: parsed.webSocketDebuggerUrl || null,
|
|
13123
|
+
});
|
|
13124
|
+
} catch {
|
|
13125
|
+
resolveP({ ok: true, httpEndpoint, wsEndpoint: null });
|
|
13126
|
+
}
|
|
13127
|
+
});
|
|
12945
13128
|
});
|
|
12946
|
-
req.on('error', () => resolveP(false));
|
|
12947
|
-
req.setTimeout(2000, () => { req.destroy(); resolveP(false); });
|
|
13129
|
+
req.on('error', () => resolveP({ ok: false }));
|
|
13130
|
+
req.setTimeout(2000, () => { req.destroy(); resolveP({ ok: false }); });
|
|
12948
13131
|
});
|
|
13132
|
+
}
|
|
12949
13133
|
|
|
12950
|
-
|
|
12951
|
-
if (
|
|
12952
|
-
|
|
12953
|
-
|
|
12954
|
-
|
|
12955
|
-
|
|
12956
|
-
|
|
12957
|
-
|
|
12958
|
-
|
|
12959
|
-
return
|
|
13134
|
+
function _readDevToolsActivePort(userDataDir) {
|
|
13135
|
+
if (!userDataDir) return null;
|
|
13136
|
+
try {
|
|
13137
|
+
const fp = resolve(userDataDir, 'DevToolsActivePort');
|
|
13138
|
+
if (!existsSync(fp)) return null;
|
|
13139
|
+
const lines = readFileSync(fp, 'utf-8')
|
|
13140
|
+
.split(/\r?\n/)
|
|
13141
|
+
.map(s => s.trim())
|
|
13142
|
+
.filter(Boolean);
|
|
13143
|
+
if (lines.length === 0) return null;
|
|
13144
|
+
const parsedPort = parseInt(lines[0], 10);
|
|
13145
|
+
if (!Number.isFinite(parsedPort) || parsedPort <= 0) return null;
|
|
13146
|
+
const httpEndpoint = `http://127.0.0.1:${parsedPort}`;
|
|
13147
|
+
let wsEndpoint = null;
|
|
13148
|
+
if (lines[1]) {
|
|
13149
|
+
wsEndpoint = lines[1].startsWith('ws://') || lines[1].startsWith('wss://')
|
|
13150
|
+
? lines[1]
|
|
13151
|
+
: `ws://127.0.0.1:${parsedPort}${lines[1].startsWith('/') ? '' : '/'}${lines[1]}`;
|
|
13152
|
+
}
|
|
13153
|
+
return { port: parsedPort, httpEndpoint, wsEndpoint };
|
|
13154
|
+
} catch {
|
|
13155
|
+
return null;
|
|
12960
13156
|
}
|
|
13157
|
+
}
|
|
12961
13158
|
|
|
12962
|
-
|
|
12963
|
-
|
|
12964
|
-
|
|
12965
|
-
|
|
12966
|
-
const { execSync: execSyncCmd } = await import('node:child_process');
|
|
13159
|
+
function _stderrTail(lines, max = 8) {
|
|
13160
|
+
return lines.slice(-max).join(' | ');
|
|
13161
|
+
}
|
|
12967
13162
|
|
|
13163
|
+
async function _shutdownChromeForDebugRestart(execSyncCmd) {
|
|
12968
13164
|
if (process.platform === 'darwin') {
|
|
12969
13165
|
try { execSyncCmd('osascript -e \'tell application "Google Chrome" to quit\'', { timeout: 3000 }); } catch {}
|
|
12970
13166
|
const quitStart = Date.now();
|
|
@@ -12978,80 +13174,196 @@ async function ensureChromeDebuggable() {
|
|
|
12978
13174
|
try { execSyncCmd(`killall -9 "${procName}"`, { timeout: 3000 }); } catch {}
|
|
12979
13175
|
}
|
|
12980
13176
|
} else {
|
|
12981
|
-
try { execSyncCmd('pkill -9 -f "google-chrome|chromium"', { timeout: 3000 }); } catch {}
|
|
13177
|
+
try { execSyncCmd('pkill -9 -f "google-chrome|chromium|msedge"', { timeout: 3000 }); } catch {}
|
|
13178
|
+
}
|
|
13179
|
+
}
|
|
13180
|
+
|
|
13181
|
+
async function _launchChromeAndWaitForCdp({
|
|
13182
|
+
chromeBin,
|
|
13183
|
+
chromeArgs,
|
|
13184
|
+
userDataDir,
|
|
13185
|
+
timeoutMs,
|
|
13186
|
+
allowPreferredPortProbe,
|
|
13187
|
+
}) {
|
|
13188
|
+
const { spawn: spawnChild } = await import('node:child_process');
|
|
13189
|
+
const stderrLines = [];
|
|
13190
|
+
let stderrWsEndpoint = null;
|
|
13191
|
+
let spawnError = null;
|
|
13192
|
+
|
|
13193
|
+
console.log(`[browser] Spawning: ${chromeBin} ${chromeArgs.join(' ')}`);
|
|
13194
|
+
const cp = spawnChild(chromeBin, chromeArgs, { stdio: ['ignore', 'ignore', 'pipe'], detached: true });
|
|
13195
|
+
cp.on('error', (err) => { spawnError = err; });
|
|
13196
|
+
cp.stderr?.on('data', (chunk) => {
|
|
13197
|
+
const text = String(chunk || '');
|
|
13198
|
+
for (const line of text.split(/\r?\n/).map(s => s.trim()).filter(Boolean)) {
|
|
13199
|
+
stderrLines.push(line);
|
|
13200
|
+
if (stderrLines.length > 80) stderrLines.shift();
|
|
13201
|
+
const m = line.match(/DevTools listening on (ws:\/\/\S+)/i);
|
|
13202
|
+
if (m && m[1]) stderrWsEndpoint = m[1];
|
|
13203
|
+
}
|
|
13204
|
+
});
|
|
13205
|
+
cp.unref();
|
|
13206
|
+
|
|
13207
|
+
const startedAt = Date.now();
|
|
13208
|
+
while (Date.now() - startedAt < timeoutMs) {
|
|
13209
|
+
if (spawnError) {
|
|
13210
|
+
throw new Error(`Chrome spawn failed: ${spawnError.message}`);
|
|
13211
|
+
}
|
|
13212
|
+
|
|
13213
|
+
if (stderrWsEndpoint) {
|
|
13214
|
+
const probed = await probeCdpEndpoint(stderrWsEndpoint);
|
|
13215
|
+
if (probed.ok) return { ...probed, source: 'stderr-devtools-endpoint' };
|
|
13216
|
+
}
|
|
13217
|
+
|
|
13218
|
+
const fromFile = _readDevToolsActivePort(userDataDir);
|
|
13219
|
+
if (fromFile?.httpEndpoint) {
|
|
13220
|
+
const probed = await probeCdpEndpoint(fromFile.httpEndpoint);
|
|
13221
|
+
if (probed.ok) return { ...probed, source: 'DevToolsActivePort' };
|
|
13222
|
+
}
|
|
13223
|
+
|
|
13224
|
+
if (allowPreferredPortProbe) {
|
|
13225
|
+
const preferred = await probeCdpEndpoint(CDP_PORT);
|
|
13226
|
+
if (preferred.ok) return { ...preferred, source: `port-${CDP_PORT}` };
|
|
13227
|
+
}
|
|
13228
|
+
|
|
13229
|
+
await new Promise(r => setTimeout(r, 250));
|
|
12982
13230
|
}
|
|
12983
13231
|
|
|
12984
|
-
|
|
13232
|
+
const diag = _stderrTail(stderrLines) || 'no stderr output';
|
|
13233
|
+
throw new Error(`Chrome did not expose DevTools within ${Math.round(timeoutMs / 1000)}s (stderr: ${diag})`);
|
|
13234
|
+
}
|
|
12985
13235
|
|
|
13236
|
+
async function ensureChromeDebuggable(opts = {}) {
|
|
12986
13237
|
const savedCfg = loadBrowserConfig();
|
|
12987
|
-
|
|
12988
|
-
|
|
12989
|
-
|
|
13238
|
+
const {
|
|
13239
|
+
userDataDir: rawUserDataDir = savedCfg.userDataDir || null,
|
|
13240
|
+
profileDirectory: requestedProfileDir = null,
|
|
13241
|
+
executablePath: requestedExecutablePath = null,
|
|
13242
|
+
channel: requestedChannel = savedCfg.channel || null,
|
|
13243
|
+
viewport = savedCfg.viewport || {},
|
|
13244
|
+
} = opts;
|
|
13245
|
+
|
|
13246
|
+
let userDataDir = rawUserDataDir || null;
|
|
13247
|
+
if (userDataDir && !userDataDir.startsWith('/') && !(/^[A-Z]:/i.test(userDataDir))) {
|
|
13248
|
+
userDataDir = resolve(DATA_HOME, userDataDir);
|
|
12990
13249
|
}
|
|
12991
13250
|
|
|
12992
|
-
let
|
|
12993
|
-
if (
|
|
12994
|
-
const
|
|
12995
|
-
const
|
|
12996
|
-
if (/^(default|profile \d+)$/i.test(
|
|
12997
|
-
|
|
12998
|
-
|
|
13251
|
+
let profileDirectory = requestedProfileDir || null;
|
|
13252
|
+
if (!profileDirectory && userDataDir) {
|
|
13253
|
+
const parts = userDataDir.replace(/[\\/]+$/, '').replace(/\\/g, '/').split('/');
|
|
13254
|
+
const last = parts[parts.length - 1];
|
|
13255
|
+
if (/^(default|profile \d+)$/i.test(last)) {
|
|
13256
|
+
profileDirectory = last;
|
|
13257
|
+
userDataDir = parts.slice(0, -1).join('/');
|
|
12999
13258
|
}
|
|
13000
13259
|
}
|
|
13260
|
+
if (!profileDirectory) profileDirectory = 'Default';
|
|
13261
|
+
|
|
13262
|
+
const chromeBin = [requestedExecutablePath, savedCfg.executablePath, findBrowserExecutable(requestedChannel)]
|
|
13263
|
+
.find(p => p && existsSync(p))
|
|
13264
|
+
|| (process.platform === 'darwin' ? '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome' : null);
|
|
13265
|
+
if (!chromeBin || !existsSync(chromeBin)) {
|
|
13266
|
+
throw new Error(`Cannot find Chrome executable. Attempted: ${requestedExecutablePath || savedCfg.executablePath || requestedChannel || 'auto-detect'}`);
|
|
13267
|
+
}
|
|
13001
13268
|
|
|
13002
|
-
|
|
13269
|
+
const cacheKey = _cdpCacheKey(chromeBin, userDataDir, profileDirectory);
|
|
13270
|
+
if (_chromeDebuggableReady && _chromeCdpEndpoint && _chromeDebugCacheKey === cacheKey) {
|
|
13271
|
+
const cached = await probeCdpEndpoint(_chromeCdpEndpoint);
|
|
13272
|
+
if (cached.ok) return { endpoint: cached.httpEndpoint, source: 'cache' };
|
|
13273
|
+
}
|
|
13274
|
+
|
|
13275
|
+
// Reuse preferred fixed-port endpoint only when profile+binary cache key matches.
|
|
13276
|
+
if (_chromeDebugCacheKey === cacheKey) {
|
|
13277
|
+
const preferred = await probeCdpEndpoint(CDP_PORT);
|
|
13278
|
+
if (preferred.ok) {
|
|
13279
|
+
_chromeDebuggableReady = true;
|
|
13280
|
+
_chromeCdpEndpoint = preferred.httpEndpoint;
|
|
13281
|
+
return { endpoint: preferred.httpEndpoint, source: `existing-port-${CDP_PORT}` };
|
|
13282
|
+
}
|
|
13283
|
+
}
|
|
13284
|
+
|
|
13285
|
+
console.log(`[browser] Chrome not debuggable for cacheKey=${cacheKey} — restarting with debugging`);
|
|
13286
|
+
broadcastSync({ type: 'notification', level: 'info', message: `Restarting Chrome with remote debugging...` });
|
|
13287
|
+
|
|
13288
|
+
const { execSync: execSyncCmd } = await import('node:child_process');
|
|
13289
|
+
await _shutdownChromeForDebugRestart(execSyncCmd);
|
|
13290
|
+
await new Promise(r => setTimeout(r, 1200));
|
|
13291
|
+
|
|
13292
|
+
if (userDataDir) {
|
|
13003
13293
|
for (const f of ['SingletonLock', 'DevToolsActivePort']) {
|
|
13004
|
-
try { const p = resolve(
|
|
13294
|
+
try { const p = resolve(userDataDir, f); if (existsSync(p)) unlinkSync(p); } catch {}
|
|
13005
13295
|
}
|
|
13006
|
-
const
|
|
13007
|
-
if (existsSync(
|
|
13296
|
+
const prefsFile = resolve(userDataDir, profileDirectory, 'Preferences');
|
|
13297
|
+
if (existsSync(prefsFile)) {
|
|
13008
13298
|
try {
|
|
13009
|
-
const
|
|
13010
|
-
if (
|
|
13299
|
+
const prefs = JSON.parse(readFileSync(prefsFile, 'utf-8'));
|
|
13300
|
+
if (prefs.profile) {
|
|
13301
|
+
prefs.profile.exit_type = 'Normal';
|
|
13302
|
+
prefs.profile.exited_cleanly = true;
|
|
13303
|
+
writeFileSync(prefsFile, JSON.stringify(prefs));
|
|
13304
|
+
}
|
|
13011
13305
|
} catch {}
|
|
13012
13306
|
}
|
|
13013
13307
|
}
|
|
13014
13308
|
|
|
13015
|
-
const
|
|
13016
|
-
|
|
13017
|
-
|
|
13018
|
-
|
|
13019
|
-
|
|
13020
|
-
|
|
13021
|
-
|
|
13022
|
-
|
|
13023
|
-
|
|
13024
|
-
|
|
13025
|
-
'--no-first-run', '--no-default-browser-check', '--disable-popup-blocking',
|
|
13026
|
-
`--window-size=${_vpW},${_vpH}`,
|
|
13027
|
-
'--disable-backgrounding-occluded-windows', '--disable-renderer-backgrounding', '--disable-background-timer-throttling',
|
|
13309
|
+
const vpW = viewport?.width || 1280;
|
|
13310
|
+
const vpH = viewport?.height || 800;
|
|
13311
|
+
const baseArgs = [
|
|
13312
|
+
'--no-first-run',
|
|
13313
|
+
'--no-default-browser-check',
|
|
13314
|
+
'--disable-popup-blocking',
|
|
13315
|
+
`--window-size=${vpW},${vpH}`,
|
|
13316
|
+
'--disable-backgrounding-occluded-windows',
|
|
13317
|
+
'--disable-renderer-backgrounding',
|
|
13318
|
+
'--disable-background-timer-throttling',
|
|
13028
13319
|
'--restore-last-session',
|
|
13029
13320
|
];
|
|
13030
|
-
if (
|
|
13031
|
-
if (
|
|
13321
|
+
if (userDataDir) baseArgs.push(`--user-data-dir=${userDataDir}`);
|
|
13322
|
+
if (profileDirectory) baseArgs.push(`--profile-directory=${profileDirectory}`);
|
|
13032
13323
|
|
|
13033
|
-
|
|
13034
|
-
|
|
13035
|
-
|
|
13036
|
-
|
|
13037
|
-
|
|
13324
|
+
let ready;
|
|
13325
|
+
try {
|
|
13326
|
+
ready = await _launchChromeAndWaitForCdp({
|
|
13327
|
+
chromeBin,
|
|
13328
|
+
chromeArgs: [...baseArgs, `--remote-debugging-port=${CDP_PORT}`],
|
|
13329
|
+
userDataDir,
|
|
13330
|
+
timeoutMs: CDP_LAUNCH_TIMEOUT_MS,
|
|
13331
|
+
allowPreferredPortProbe: true,
|
|
13332
|
+
});
|
|
13333
|
+
} catch (primaryErr) {
|
|
13334
|
+
console.warn(`[browser] Fixed port ${CDP_PORT} debug launch failed, retrying with dynamic port: ${primaryErr.message}`);
|
|
13335
|
+
await _shutdownChromeForDebugRestart(execSyncCmd);
|
|
13336
|
+
await new Promise(r => setTimeout(r, 1000));
|
|
13038
13337
|
|
|
13039
|
-
|
|
13040
|
-
|
|
13041
|
-
|
|
13042
|
-
|
|
13043
|
-
|
|
13044
|
-
|
|
13045
|
-
}
|
|
13338
|
+
if (userDataDir) {
|
|
13339
|
+
try {
|
|
13340
|
+
const devtoolsPortFile = resolve(userDataDir, 'DevToolsActivePort');
|
|
13341
|
+
if (existsSync(devtoolsPortFile)) unlinkSync(devtoolsPortFile);
|
|
13342
|
+
} catch {}
|
|
13343
|
+
}
|
|
13046
13344
|
|
|
13047
|
-
|
|
13048
|
-
|
|
13345
|
+
try {
|
|
13346
|
+
ready = await _launchChromeAndWaitForCdp({
|
|
13347
|
+
chromeBin,
|
|
13348
|
+
chromeArgs: [...baseArgs, '--remote-debugging-port=0'],
|
|
13349
|
+
userDataDir,
|
|
13350
|
+
timeoutMs: CDP_LAUNCH_TIMEOUT_MS,
|
|
13351
|
+
allowPreferredPortProbe: false,
|
|
13352
|
+
});
|
|
13353
|
+
} catch (fallbackErr) {
|
|
13354
|
+
throw new Error(`Primary debug launch failed (${primaryErr.message}); dynamic-port retry failed (${fallbackErr.message})`);
|
|
13355
|
+
}
|
|
13049
13356
|
}
|
|
13050
13357
|
|
|
13051
13358
|
_chromeDebuggableReady = true;
|
|
13052
|
-
|
|
13053
|
-
|
|
13054
|
-
|
|
13359
|
+
_chromeCdpEndpoint = ready.httpEndpoint;
|
|
13360
|
+
_chromeDebugCacheKey = cacheKey;
|
|
13361
|
+
const cdpPort = (() => {
|
|
13362
|
+
try { return new URL(ready.httpEndpoint).port || 'unknown'; } catch { return 'unknown'; }
|
|
13363
|
+
})();
|
|
13364
|
+
console.log(`[browser] Chrome debuggable at ${ready.httpEndpoint} (source=${ready.source})`);
|
|
13365
|
+
broadcastSync({ type: 'notification', level: 'info', message: `Chrome ready with debugging on port ${cdpPort}` });
|
|
13366
|
+
return { endpoint: ready.httpEndpoint, source: ready.source };
|
|
13055
13367
|
}
|
|
13056
13368
|
|
|
13057
13369
|
/**
|
|
@@ -13121,17 +13433,20 @@ async function createBrowserSession(options = {}) {
|
|
|
13121
13433
|
userDataDir = resolve(DATA_HOME, userDataDir);
|
|
13122
13434
|
}
|
|
13123
13435
|
let _profileDirectory = null; // Chrome --profile-directory flag
|
|
13124
|
-
let _sourceProfilePath = null; // Original
|
|
13125
|
-
let _isInsideChromeDir = false;
|
|
13436
|
+
let _sourceProfilePath = null; // Original selected profile dir (for labels + cookie bootstrap)
|
|
13126
13437
|
let _sourceBrowser = null; // 'chrome' | 'msedge' | 'chromium' — which browser owns this profile
|
|
13438
|
+
let _selectedProfileKind = userDataDir ? 'custom' : 'clean'; // clean | managed | system | custom
|
|
13127
13439
|
|
|
13128
13440
|
if (userDataDir) {
|
|
13129
13441
|
const normalized = userDataDir.replace(/[\\/]+$/, '').replace(/\\/g, '/').toLowerCase();
|
|
13442
|
+
const managedRoot = getManagedProfileRoot().replace(/\\/g, '/').toLowerCase();
|
|
13130
13443
|
|
|
13131
13444
|
// Known Chrome/Edge/Chromium User Data root directories per platform
|
|
13132
13445
|
const _home = process.env.HOME || process.env.USERPROFILE || '';
|
|
13133
13446
|
const chromeRootDefs = IS_WIN ? [
|
|
13134
13447
|
{ root: ((process.env.LOCALAPPDATA || '') + '/Google/Chrome/User Data').replace(/\\/g, '/').toLowerCase(), browser: 'chrome' },
|
|
13448
|
+
{ root: ((process.env.LOCALAPPDATA || '') + '/Microsoft/Edge/User Data').replace(/\\/g, '/').toLowerCase(), browser: 'msedge' },
|
|
13449
|
+
{ root: ((process.env.LOCALAPPDATA || '') + '/Chromium/User Data').replace(/\\/g, '/').toLowerCase(), browser: 'chromium' },
|
|
13135
13450
|
{ root: ((process.env['ProgramFiles'] || '') + '/Google/Chrome/User Data').replace(/\\/g, '/').toLowerCase(), browser: 'chrome' },
|
|
13136
13451
|
] : process.platform === 'darwin' ? [
|
|
13137
13452
|
{ root: (_home + '/Library/Application Support/Google/Chrome').toLowerCase(), browser: 'chrome' },
|
|
@@ -13143,28 +13458,45 @@ async function createBrowserSession(options = {}) {
|
|
|
13143
13458
|
{ root: (_home + '/.config/microsoft-edge').toLowerCase(), browser: 'msedge' },
|
|
13144
13459
|
];
|
|
13145
13460
|
|
|
13146
|
-
|
|
13461
|
+
if (normalized === managedRoot || normalized.startsWith(managedRoot + '/')) {
|
|
13462
|
+
_selectedProfileKind = 'managed';
|
|
13463
|
+
}
|
|
13464
|
+
|
|
13147
13465
|
for (const { root, browser: rootBrowser } of chromeRootDefs.filter(d => d.root)) {
|
|
13466
|
+
if (normalized === root) {
|
|
13467
|
+
_selectedProfileKind = 'system';
|
|
13468
|
+
_sourceBrowser = rootBrowser;
|
|
13469
|
+
break;
|
|
13470
|
+
}
|
|
13148
13471
|
if (normalized.startsWith(root + '/')) {
|
|
13149
13472
|
const remainder = normalized.slice(root.length + 1).replace(/\/+$/, '');
|
|
13150
|
-
if (/^(default|profile \d+)
|
|
13473
|
+
if (/^(default|profile \d+)$/i.test(remainder)) {
|
|
13151
13474
|
_sourceProfilePath = userDataDir;
|
|
13152
13475
|
const parts = userDataDir.replace(/\\/g, '/').replace(/\/+$/, '').split('/');
|
|
13153
13476
|
_profileDirectory = parts.pop(); // "Profile 1", "Default", etc.
|
|
13154
|
-
userDataDir = parts.join('/');
|
|
13155
|
-
|
|
13477
|
+
userDataDir = parts.join('/');
|
|
13478
|
+
_selectedProfileKind = root === managedRoot ? 'managed' : 'system';
|
|
13156
13479
|
_sourceBrowser = rootBrowser;
|
|
13157
13480
|
console.log(`[browser] Detected ${rootBrowser} profile: --profile-directory=${_profileDirectory}`);
|
|
13158
13481
|
console.log(`[browser] Using ${rootBrowser} User Data dir: ${userDataDir}`);
|
|
13159
13482
|
break;
|
|
13160
13483
|
}
|
|
13161
13484
|
}
|
|
13162
|
-
|
|
13163
|
-
|
|
13164
|
-
|
|
13165
|
-
|
|
13485
|
+
}
|
|
13486
|
+
|
|
13487
|
+
if (!_profileDirectory) {
|
|
13488
|
+
const parts = userDataDir.replace(/[\\/]+$/, '').replace(/\\/g, '/').split('/');
|
|
13489
|
+
const last = parts[parts.length - 1];
|
|
13490
|
+
if (/^(default|profile \d+)$/i.test(last)) {
|
|
13491
|
+
_profileDirectory = last;
|
|
13492
|
+
_sourceProfilePath = userDataDir;
|
|
13493
|
+
userDataDir = parts.slice(0, -1).join('/');
|
|
13166
13494
|
}
|
|
13167
13495
|
}
|
|
13496
|
+
|
|
13497
|
+
if (!_sourceProfilePath && userDataDir) {
|
|
13498
|
+
_sourceProfilePath = resolve(userDataDir, _profileDirectory || 'Default');
|
|
13499
|
+
}
|
|
13168
13500
|
}
|
|
13169
13501
|
|
|
13170
13502
|
// Only disable extensions when NOT using a user profile (they'd want their extensions)
|
|
@@ -13172,7 +13504,7 @@ async function createBrowserSession(options = {}) {
|
|
|
13172
13504
|
stealthArgs.push('--disable-extensions');
|
|
13173
13505
|
}
|
|
13174
13506
|
|
|
13175
|
-
// NOTE: --profile-directory is
|
|
13507
|
+
// NOTE: --profile-directory is appended per launch target so direct and mirror modes can differ.
|
|
13176
13508
|
|
|
13177
13509
|
// Append user's extra launch args from config
|
|
13178
13510
|
if (savedCfg.extraArgs) {
|
|
@@ -13286,8 +13618,13 @@ async function createBrowserSession(options = {}) {
|
|
|
13286
13618
|
let browser, context, page;
|
|
13287
13619
|
let _isPersistent = false;
|
|
13288
13620
|
let _chromeProcess = null; // CDP mode: ref to spawned Chrome process
|
|
13289
|
-
let _profileMode = userDataDir ? 'direct' : 'clean';
|
|
13290
|
-
|
|
13621
|
+
let _profileMode = userDataDir ? (_selectedProfileKind === 'managed' ? 'managed' : 'direct') : 'clean';
|
|
13622
|
+
const _detectedSource = lookupDetectedProfile(_sourceProfilePath);
|
|
13623
|
+
let _profileSourceName = _selectedProfileKind === 'managed'
|
|
13624
|
+
? 'SynaBun Profile'
|
|
13625
|
+
: (_detectedSource?.name || _profileDirectory || (userDataDir ? 'Default' : null));
|
|
13626
|
+
let _launchUserDataDir = userDataDir || null;
|
|
13627
|
+
let _launchProfileDirectory = _profileDirectory || (userDataDir ? 'Default' : null);
|
|
13291
13628
|
|
|
13292
13629
|
if (userDataDir) {
|
|
13293
13630
|
// ── Persistent context: uses a Chrome profile directory ──
|
|
@@ -13295,57 +13632,39 @@ async function createBrowserSession(options = {}) {
|
|
|
13295
13632
|
_isPersistent = true;
|
|
13296
13633
|
|
|
13297
13634
|
const _browserLabel = _sourceBrowser === 'msedge' ? 'Edge' : _sourceBrowser === 'chromium' ? 'Chromium' : 'Chrome';
|
|
13635
|
+
const launchPersistentProfile = async (launchRoot, launchProfileDir, launchMode) => {
|
|
13636
|
+
const launchArgs = [...stealthArgs];
|
|
13298
13637
|
|
|
13299
|
-
|
|
13300
|
-
|
|
13301
|
-
|
|
13302
|
-
|
|
13303
|
-
|
|
13304
|
-
|
|
13305
|
-
|
|
13306
|
-
|
|
13307
|
-
const cdpEndpoint = `http://127.0.0.1:${CDP_PORT}`;
|
|
13308
|
-
|
|
13309
|
-
// ── Connect via CDP ──
|
|
13310
|
-
console.log(`[browser] Connecting via CDP: ${cdpEndpoint}`);
|
|
13311
|
-
browser = await chromium.connectOverCDP(cdpEndpoint);
|
|
13312
|
-
const contexts = browser.contexts();
|
|
13313
|
-
context = contexts[0] || await browser.newContext(contextOpts);
|
|
13314
|
-
|
|
13315
|
-
// Open a fresh page for the automation (don't disturb existing tabs)
|
|
13316
|
-
page = await context.newPage();
|
|
13317
|
-
|
|
13318
|
-
broadcastSync({ type: 'notification', level: 'info', message: `Connected to ${_browserLabel} profile "${_profileSourceName || 'Default'}" via CDP on port ${CDP_PORT}.` });
|
|
13319
|
-
|
|
13320
|
-
} else {
|
|
13321
|
-
// ── Non-Chrome persistent profile: use Playwright's launchPersistentContext ──
|
|
13322
|
-
|
|
13323
|
-
// Clean singleton lock files
|
|
13324
|
-
for (const lockFile of ['SingletonLock', 'SingletonSocket', 'SingletonCookie']) {
|
|
13325
|
-
const lf = resolve(userDataDir, lockFile);
|
|
13326
|
-
try { if (existsSync(lf)) { unlinkSync(lf); console.log(`[browser] Removed stale ${lockFile}`); } } catch {}
|
|
13638
|
+
for (const lockFile of ['SingletonLock', 'SingletonSocket', 'SingletonCookie', 'DevToolsActivePort']) {
|
|
13639
|
+
const lf = resolve(launchRoot, lockFile);
|
|
13640
|
+
try {
|
|
13641
|
+
if (existsSync(lf)) {
|
|
13642
|
+
unlinkSync(lf);
|
|
13643
|
+
console.log(`[browser] Removed stale ${lockFile} from ${launchMode} root`);
|
|
13644
|
+
}
|
|
13645
|
+
} catch {}
|
|
13327
13646
|
}
|
|
13328
13647
|
|
|
13329
|
-
if (
|
|
13330
|
-
|
|
13331
|
-
console.log(`[browser] Using --profile-directory=${
|
|
13648
|
+
if (launchProfileDir) {
|
|
13649
|
+
launchArgs.push(`--profile-directory=${launchProfileDir}`);
|
|
13650
|
+
console.log(`[browser] Using --profile-directory=${launchProfileDir} (${launchMode})`);
|
|
13332
13651
|
}
|
|
13333
13652
|
|
|
13334
|
-
|
|
13335
|
-
|
|
13336
|
-
if (existsSync(_prefsFile)) {
|
|
13653
|
+
const prefsFile = resolve(launchRoot, launchProfileDir || 'Default', 'Preferences');
|
|
13654
|
+
if (existsSync(prefsFile)) {
|
|
13337
13655
|
try {
|
|
13338
|
-
const
|
|
13339
|
-
if (
|
|
13340
|
-
|
|
13341
|
-
|
|
13342
|
-
writeFileSync(
|
|
13656
|
+
const prefs = JSON.parse(readFileSync(prefsFile, 'utf-8'));
|
|
13657
|
+
if (prefs.profile) {
|
|
13658
|
+
prefs.profile.exit_type = 'Normal';
|
|
13659
|
+
prefs.profile.exited_cleanly = true;
|
|
13660
|
+
writeFileSync(prefsFile, JSON.stringify(prefs));
|
|
13343
13661
|
}
|
|
13344
13662
|
} catch {}
|
|
13345
13663
|
}
|
|
13346
13664
|
|
|
13347
|
-
const
|
|
13665
|
+
const persistentLaunchOpts = {
|
|
13348
13666
|
...launchOpts,
|
|
13667
|
+
args: launchArgs,
|
|
13349
13668
|
...contextOpts,
|
|
13350
13669
|
ignoreDefaultArgs: [
|
|
13351
13670
|
'--disable-extensions',
|
|
@@ -13356,35 +13675,85 @@ async function createBrowserSession(options = {}) {
|
|
|
13356
13675
|
],
|
|
13357
13676
|
};
|
|
13358
13677
|
|
|
13359
|
-
console.log(`[browser] Launching persistent context at: ${
|
|
13678
|
+
console.log(`[browser] Launching ${launchMode} persistent context at: ${launchRoot}${launchProfileDir ? ` (profile: ${launchProfileDir})` : ''}`);
|
|
13679
|
+
let launchContext;
|
|
13360
13680
|
try {
|
|
13361
|
-
|
|
13681
|
+
launchContext = await chromium.launchPersistentContext(launchRoot, persistentLaunchOpts);
|
|
13362
13682
|
} catch (err) {
|
|
13363
13683
|
const msg = err.message || '';
|
|
13364
13684
|
if (msg.includes('ProcessSingleton') || msg.includes('already in use') || msg.includes('lock') || msg.includes('SingletonLock')) {
|
|
13365
|
-
throw new Error(`Browser profile is locked
|
|
13685
|
+
throw new Error(`Browser profile is locked. Original error: ${msg}`);
|
|
13366
13686
|
}
|
|
13367
13687
|
throw err;
|
|
13368
13688
|
}
|
|
13369
13689
|
|
|
13370
|
-
// Verify alive
|
|
13371
13690
|
await new Promise(r => setTimeout(r, 500));
|
|
13372
13691
|
let contextAlive = true;
|
|
13373
13692
|
try {
|
|
13374
|
-
const testPages =
|
|
13693
|
+
const testPages = launchContext.pages();
|
|
13375
13694
|
if (testPages.length === 0) contextAlive = false;
|
|
13376
13695
|
} catch { contextAlive = false; }
|
|
13377
|
-
|
|
13378
13696
|
if (!contextAlive) {
|
|
13379
|
-
throw new Error(
|
|
13697
|
+
throw new Error('Browser closed immediately after launch.');
|
|
13698
|
+
}
|
|
13699
|
+
|
|
13700
|
+
const launchBrowser = launchContext;
|
|
13701
|
+
const existingPages = launchContext.pages();
|
|
13702
|
+
const launchPage = await launchContext.newPage();
|
|
13703
|
+
for (const existing of existingPages) {
|
|
13704
|
+
await existing.close().catch(() => {});
|
|
13380
13705
|
}
|
|
13381
|
-
browser = context;
|
|
13382
13706
|
|
|
13383
|
-
|
|
13384
|
-
|
|
13385
|
-
|
|
13386
|
-
|
|
13707
|
+
return { launchBrowser, launchContext, launchPage };
|
|
13708
|
+
};
|
|
13709
|
+
|
|
13710
|
+
if (_selectedProfileKind === 'system') {
|
|
13711
|
+
const requestedProfileDir = _profileDirectory || 'Default';
|
|
13712
|
+
|
|
13713
|
+
// CDP mode with mirrored profile: Chrome refuses remote debugging when
|
|
13714
|
+
// using its own default user-data-dir. Copy the profile to a mirror
|
|
13715
|
+
// directory (non-default) and spawn Chrome from there via CDP.
|
|
13716
|
+
const { mirrorRoot } = prepareMirroredProfile(userDataDir, requestedProfileDir, _sourceBrowser || 'chrome');
|
|
13717
|
+
|
|
13718
|
+
try {
|
|
13719
|
+
const cdpResult = await ensureChromeDebuggable({
|
|
13720
|
+
userDataDir: mirrorRoot,
|
|
13721
|
+
profileDirectory: requestedProfileDir,
|
|
13722
|
+
executablePath: launchOpts.executablePath || undefined,
|
|
13723
|
+
channel: launchOpts.channel || undefined,
|
|
13724
|
+
viewport: { width: vpW, height: vpH },
|
|
13725
|
+
});
|
|
13726
|
+
|
|
13727
|
+
browser = await chromium.connectOverCDP(cdpResult.endpoint);
|
|
13728
|
+
context = browser.contexts()[0];
|
|
13729
|
+
if (!context) throw new Error('CDP connected but no browser context available');
|
|
13730
|
+
|
|
13731
|
+
page = await context.newPage();
|
|
13732
|
+
_isPersistent = false;
|
|
13733
|
+
_profileMode = 'cdp';
|
|
13734
|
+
_launchUserDataDir = mirrorRoot;
|
|
13735
|
+
_launchProfileDirectory = requestedProfileDir;
|
|
13736
|
+
|
|
13737
|
+
console.log(`[browser] CDP connected to mirrored ${_profileSourceName || requestedProfileDir} via ${cdpResult.source}`);
|
|
13738
|
+
} catch (cdpErr) {
|
|
13739
|
+
throw new Error(
|
|
13740
|
+
`Could not connect to ${_browserLabel} via CDP: ${cdpErr.message}`
|
|
13741
|
+
);
|
|
13387
13742
|
}
|
|
13743
|
+
} else {
|
|
13744
|
+
const launchRoot = _selectedProfileKind === 'managed' ? getManagedProfileRoot() : userDataDir;
|
|
13745
|
+
const launchProfileDir = _profileDirectory || 'Default';
|
|
13746
|
+
if (_selectedProfileKind === 'managed') {
|
|
13747
|
+
try { if (!existsSync(launchRoot)) mkdirSync(launchRoot, { recursive: true }); } catch {}
|
|
13748
|
+
_profileSourceName = 'SynaBun Profile';
|
|
13749
|
+
}
|
|
13750
|
+
const launched = await launchPersistentProfile(launchRoot, launchProfileDir, _selectedProfileKind === 'managed' ? 'managed' : 'direct');
|
|
13751
|
+
browser = launched.launchBrowser;
|
|
13752
|
+
context = launched.launchContext;
|
|
13753
|
+
page = launched.launchPage;
|
|
13754
|
+
_profileMode = _selectedProfileKind === 'managed' ? 'managed' : 'direct';
|
|
13755
|
+
_launchUserDataDir = launchRoot;
|
|
13756
|
+
_launchProfileDirectory = launchProfileDir;
|
|
13388
13757
|
}
|
|
13389
13758
|
} else {
|
|
13390
13759
|
// ── Standard: clean sandboxed browser ──
|
|
@@ -13393,54 +13762,11 @@ async function createBrowserSession(options = {}) {
|
|
|
13393
13762
|
page = await context.newPage();
|
|
13394
13763
|
}
|
|
13395
13764
|
|
|
13396
|
-
// ── Restore saved cookies/localStorage from storageState ──
|
|
13397
|
-
// Skip for CDP mode — real Chrome already has all cookies natively.
|
|
13398
|
-
// For non-Chrome persistent contexts, inject cookies after launch.
|
|
13399
|
-
if (_isPersistent && _profileMode !== 'cdp' && savedCfg.persistStorage !== false && !savedCfg.clearStorageOnStart) {
|
|
13400
|
-
if (existsSync(STORAGE_STATE_PATH)) {
|
|
13401
|
-
try {
|
|
13402
|
-
const savedState = JSON.parse(readFileSync(STORAGE_STATE_PATH, 'utf-8'));
|
|
13403
|
-
if (savedState.cookies && savedState.cookies.length > 0) {
|
|
13404
|
-
await context.addCookies(savedState.cookies);
|
|
13405
|
-
console.log(`[browser] Restored ${savedState.cookies.length} cookies from ${STORAGE_STATE_PATH}`);
|
|
13406
|
-
}
|
|
13407
|
-
// Restore localStorage lazily via addInitScript — injects stored items
|
|
13408
|
-
// on first visit to each origin, before page scripts run. Avoids creating
|
|
13409
|
-
// extra pages/tabs and navigating to every saved origin on launch.
|
|
13410
|
-
if (savedState.origins && savedState.origins.length > 0) {
|
|
13411
|
-
const storageMap = {};
|
|
13412
|
-
for (const origin of savedState.origins) {
|
|
13413
|
-
if (origin.localStorage && origin.localStorage.length > 0) {
|
|
13414
|
-
storageMap[origin.origin] = origin.localStorage;
|
|
13415
|
-
}
|
|
13416
|
-
}
|
|
13417
|
-
if (Object.keys(storageMap).length > 0) {
|
|
13418
|
-
await context.addInitScript(`(function() {
|
|
13419
|
-
var m = ${JSON.stringify(storageMap)};
|
|
13420
|
-
var k = '__synabun_ls_restored_' + location.origin;
|
|
13421
|
-
var items = m[location.origin];
|
|
13422
|
-
if (items && !sessionStorage.getItem(k)) {
|
|
13423
|
-
for (var i = 0; i < items.length; i++) {
|
|
13424
|
-
try { localStorage.setItem(items[i].name, items[i].value); } catch(e) {}
|
|
13425
|
-
}
|
|
13426
|
-
try { sessionStorage.setItem(k, '1'); } catch(e) {}
|
|
13427
|
-
}
|
|
13428
|
-
})()`);
|
|
13429
|
-
console.log(`[browser] Registered lazy localStorage restore for ${Object.keys(storageMap).length} origins`);
|
|
13430
|
-
}
|
|
13431
|
-
}
|
|
13432
|
-
} catch (e) {
|
|
13433
|
-
console.warn(`[browser] Failed to restore storage state: ${e.message}`);
|
|
13434
|
-
}
|
|
13435
|
-
}
|
|
13436
|
-
}
|
|
13437
|
-
|
|
13438
13765
|
// ── Decrypt and inject cookies from Chrome profile (macOS) ──
|
|
13439
|
-
// Mirror mode
|
|
13440
|
-
//
|
|
13766
|
+
// Mirror mode may start from an isolated copy; bootstrap fresh auth from the
|
|
13767
|
+
// selected source profile's Cookies DB so the mirrored copy inherits logins.
|
|
13441
13768
|
if (_isPersistent && _profileMode === 'mirror' && !savedCfg.clearStorageOnStart) {
|
|
13442
|
-
const
|
|
13443
|
-
const decryptedCookies = decryptChromeCookies(mirrorProfileDir, _sourceBrowser || 'chrome');
|
|
13769
|
+
const decryptedCookies = decryptChromeCookies(_sourceProfilePath, _sourceBrowser || 'chrome');
|
|
13444
13770
|
if (decryptedCookies.length > 0) {
|
|
13445
13771
|
try {
|
|
13446
13772
|
await context.addCookies(decryptedCookies);
|
|
@@ -13451,10 +13777,8 @@ async function createBrowserSession(options = {}) {
|
|
|
13451
13777
|
}
|
|
13452
13778
|
}
|
|
13453
13779
|
|
|
13454
|
-
// ──
|
|
13455
|
-
|
|
13456
|
-
// window.chrome.runtime crashes Chrome's internal extension messaging (SIGSEGV).
|
|
13457
|
-
const doStealth = savedCfg.stealthFingerprint !== false && _profileMode !== 'cdp';
|
|
13780
|
+
// ── Stealth injections (if enabled) ──
|
|
13781
|
+
const doStealth = savedCfg.stealthFingerprint !== false;
|
|
13458
13782
|
if (doStealth) {
|
|
13459
13783
|
const cdpStealth = await page.context().newCDPSession(page);
|
|
13460
13784
|
try {
|
|
@@ -13522,6 +13846,9 @@ async function createBrowserSession(options = {}) {
|
|
|
13522
13846
|
_profileMode: _profileMode || 'clean',
|
|
13523
13847
|
_profileSourceName: _profileSourceName || null,
|
|
13524
13848
|
_storageStatePath: STORAGE_STATE_PATH,
|
|
13849
|
+
_launchUserDataDir: _launchUserDataDir || null,
|
|
13850
|
+
_launchProfileDirectory: _launchProfileDirectory || null,
|
|
13851
|
+
_selectedProfilePath: _sourceProfilePath || null,
|
|
13525
13852
|
_chromeProcess: _chromeProcess || null, // CDP mode: spawned Chrome process
|
|
13526
13853
|
clients: new Set(), // WebSocket connections for screencast
|
|
13527
13854
|
screencastActive: false,
|
|
@@ -13617,9 +13944,8 @@ async function createBrowserSession(options = {}) {
|
|
|
13617
13944
|
browserSessions.set(sessionId, session);
|
|
13618
13945
|
|
|
13619
13946
|
// ── Periodic cookie autosave (every 30s) ──
|
|
13620
|
-
// Protects against cookie loss when the user closes the
|
|
13621
|
-
|
|
13622
|
-
if (savedCfg.persistStorage !== false && _profileMode !== 'cdp') {
|
|
13947
|
+
// Protects against cookie loss when the user closes the window directly.
|
|
13948
|
+
if (savedCfg.persistStorage !== false && !_isPersistent && _profileMode !== 'cdp') {
|
|
13623
13949
|
session._autosaveInterval = setInterval(async () => {
|
|
13624
13950
|
if (!session.context) { clearInterval(session._autosaveInterval); return; }
|
|
13625
13951
|
try {
|
|
@@ -13800,9 +14126,8 @@ async function destroyBrowserSession(sessionId) {
|
|
|
13800
14126
|
// Remove from Map immediately to prevent races (new sessions seeing zombie entries)
|
|
13801
14127
|
browserSessions.delete(sessionId);
|
|
13802
14128
|
|
|
13803
|
-
// Save storage state (cookies, localStorage) — skip for CDP mode (Chrome persists its own).
|
|
13804
14129
|
const savedCfg = loadBrowserConfig();
|
|
13805
|
-
if (savedCfg.persistStorage !== false && session.context && !session._chromeProcess) {
|
|
14130
|
+
if (savedCfg.persistStorage !== false && session.context && !session._chromeProcess && !session._isPersistent && session._profileMode !== 'cdp') {
|
|
13806
14131
|
// Use per-profile storage path from session (set at creation), fall back to config default
|
|
13807
14132
|
const storagePath = session._storageStatePath || resolve(DATA_HOME, savedCfg.storageStatePath || 'data/browser-storage.json');
|
|
13808
14133
|
try {
|
|
@@ -13820,11 +14145,10 @@ async function destroyBrowserSession(sessionId) {
|
|
|
13820
14145
|
if (session.graceTimer) clearTimeout(session.graceTimer);
|
|
13821
14146
|
try { await stopScreencast(session); } catch {}
|
|
13822
14147
|
if (session._profileMode === 'cdp' && !session._chromeProcess) {
|
|
13823
|
-
//
|
|
13824
|
-
try { await session.browser.
|
|
13825
|
-
console.log(`[browser] Disconnected from running Chrome (session ${sessionId})`);
|
|
14148
|
+
// Connected to user's running Chrome via CDP — just disconnect, don't kill Chrome
|
|
14149
|
+
try { await session.browser.disconnect(); } catch {}
|
|
13826
14150
|
} else if (session._chromeProcess) {
|
|
13827
|
-
//
|
|
14151
|
+
// Spawned Chrome process: disconnect Playwright, then kill Chrome
|
|
13828
14152
|
try { await session.browser.close(); } catch {}
|
|
13829
14153
|
try {
|
|
13830
14154
|
if (!session._chromeProcess.killed) {
|
|
@@ -13834,50 +14158,51 @@ async function destroyBrowserSession(sessionId) {
|
|
|
13834
14158
|
}, 3000);
|
|
13835
14159
|
}
|
|
13836
14160
|
} catch {}
|
|
13837
|
-
// Mark profile as cleanly exited
|
|
13838
|
-
const _cfg = loadBrowserConfig();
|
|
13839
|
-
if (_cfg.userDataDir) {
|
|
13840
|
-
const normalized = _cfg.userDataDir.replace(/[\\/]+$/, '').replace(/\\/g, '/');
|
|
13841
|
-
const parts = normalized.split('/');
|
|
13842
|
-
const lastPart = parts[parts.length - 1];
|
|
13843
|
-
const isProfileSubdir = /^(default|profile \d+)$/i.test(lastPart);
|
|
13844
|
-
const userDataRoot = isProfileSubdir ? parts.slice(0, -1).join('/') : normalized;
|
|
13845
|
-
const profileDir = isProfileSubdir ? lastPart : 'Default';
|
|
13846
|
-
const pp = resolve(userDataRoot, profileDir, 'Preferences');
|
|
13847
|
-
if (existsSync(pp)) {
|
|
13848
|
-
try {
|
|
13849
|
-
const prefs = JSON.parse(readFileSync(pp, 'utf-8'));
|
|
13850
|
-
if (prefs.profile) {
|
|
13851
|
-
prefs.profile.exit_type = 'Normal';
|
|
13852
|
-
prefs.profile.exited_cleanly = true;
|
|
13853
|
-
}
|
|
13854
|
-
writeFileSync(pp, JSON.stringify(prefs));
|
|
13855
|
-
} catch {}
|
|
13856
|
-
}
|
|
13857
|
-
}
|
|
13858
14161
|
} else if (session._isPersistent) {
|
|
13859
|
-
// Persistent context
|
|
14162
|
+
// Persistent context: close context kills browser
|
|
13860
14163
|
try { await session.context.close(); } catch {}
|
|
13861
|
-
const _cfg = loadBrowserConfig();
|
|
13862
|
-
if (_cfg.userDataDir) {
|
|
13863
|
-
const pp = resolve(_cfg.userDataDir, 'Default', 'Preferences');
|
|
13864
|
-
if (existsSync(pp)) {
|
|
13865
|
-
try {
|
|
13866
|
-
const prefs = JSON.parse(readFileSync(pp, 'utf-8'));
|
|
13867
|
-
if (prefs.profile) {
|
|
13868
|
-
prefs.profile.exit_type = 'Normal';
|
|
13869
|
-
prefs.profile.exited_cleanly = true;
|
|
13870
|
-
}
|
|
13871
|
-
writeFileSync(pp, JSON.stringify(prefs));
|
|
13872
|
-
} catch {}
|
|
13873
|
-
}
|
|
13874
|
-
}
|
|
13875
14164
|
} else {
|
|
13876
14165
|
try { await session.browser.close(); } catch {}
|
|
13877
14166
|
}
|
|
14167
|
+
if (session._isPersistent && session._launchUserDataDir) {
|
|
14168
|
+
const pp = resolve(session._launchUserDataDir, session._launchProfileDirectory || 'Default', 'Preferences');
|
|
14169
|
+
if (existsSync(pp)) {
|
|
14170
|
+
try {
|
|
14171
|
+
const prefs = JSON.parse(readFileSync(pp, 'utf-8'));
|
|
14172
|
+
if (prefs.profile) {
|
|
14173
|
+
prefs.profile.exit_type = 'Normal';
|
|
14174
|
+
prefs.profile.exited_cleanly = true;
|
|
14175
|
+
}
|
|
14176
|
+
writeFileSync(pp, JSON.stringify(prefs));
|
|
14177
|
+
} catch {}
|
|
14178
|
+
}
|
|
14179
|
+
}
|
|
13878
14180
|
broadcastSync({ type: 'browser:session-deleted', sessionId });
|
|
13879
14181
|
}
|
|
13880
14182
|
|
|
14183
|
+
// ── Tab-level page routing (concurrent loop isolation) ──
|
|
14184
|
+
|
|
14185
|
+
/**
|
|
14186
|
+
* Resolve the Playwright page for an API request.
|
|
14187
|
+
* If tabId is provided (body or query), targets that specific tab's page directly.
|
|
14188
|
+
* Otherwise falls back to session.page (the active tab) for backward compat.
|
|
14189
|
+
*/
|
|
14190
|
+
function getTargetPage(session, req) {
|
|
14191
|
+
const tabId = req.body?.tabId || req.query?.tabId;
|
|
14192
|
+
if (!tabId) return { page: session.page, cdpSession: session.cdpSession, tabId: session.activeTabId };
|
|
14193
|
+
const tab = session.tabs?.get(tabId);
|
|
14194
|
+
if (!tab) return null;
|
|
14195
|
+
return { page: tab.page, cdpSession: tab.cdpSession, tabId };
|
|
14196
|
+
}
|
|
14197
|
+
|
|
14198
|
+
/** Update session-level URL/title only when operating on the active tab. */
|
|
14199
|
+
async function syncPageState(session, routed) {
|
|
14200
|
+
const url = routed.page.url();
|
|
14201
|
+
const title = await routed.page.title().catch(() => '');
|
|
14202
|
+
if (routed.tabId === session.activeTabId) { session.currentUrl = url; session.title = title; }
|
|
14203
|
+
return { url, title };
|
|
14204
|
+
}
|
|
14205
|
+
|
|
13881
14206
|
// ── Browser REST endpoints ──
|
|
13882
14207
|
|
|
13883
14208
|
app.get('/api/browser/sessions', (req, res) => {
|
|
@@ -13979,12 +14304,13 @@ app.delete('/api/browser/sessions/:id/tabs/:tabId', async (req, res) => {
|
|
|
13979
14304
|
app.post('/api/browser/sessions/:id/navigate', async (req, res) => {
|
|
13980
14305
|
const session = browserSessions.get(req.params.id);
|
|
13981
14306
|
if (!session) return res.status(404).json({ error: 'Session not found' });
|
|
14307
|
+
const routed = getTargetPage(session, req);
|
|
14308
|
+
if (!routed) return res.status(404).json({ error: `Tab ${req.body?.tabId} not found in session` });
|
|
13982
14309
|
const { url } = req.body;
|
|
13983
14310
|
try {
|
|
13984
|
-
await
|
|
13985
|
-
|
|
13986
|
-
|
|
13987
|
-
res.json({ ok: true, url: session.currentUrl, title: session.title });
|
|
14311
|
+
await routed.page.goto(url, { waitUntil: 'domcontentloaded', timeout: 15000 });
|
|
14312
|
+
const state = await syncPageState(session, routed);
|
|
14313
|
+
res.json({ ok: true, url: state.url, title: state.title });
|
|
13988
14314
|
} catch (err) {
|
|
13989
14315
|
res.status(500).json({ error: err.message });
|
|
13990
14316
|
}
|
|
@@ -13993,11 +14319,12 @@ app.post('/api/browser/sessions/:id/navigate', async (req, res) => {
|
|
|
13993
14319
|
app.post('/api/browser/sessions/:id/back', async (req, res) => {
|
|
13994
14320
|
const session = browserSessions.get(req.params.id);
|
|
13995
14321
|
if (!session) return res.status(404).json({ error: 'Session not found' });
|
|
14322
|
+
const routed = getTargetPage(session, req);
|
|
14323
|
+
if (!routed) return res.status(404).json({ error: `Tab ${req.body?.tabId} not found in session` });
|
|
13996
14324
|
try {
|
|
13997
|
-
await
|
|
13998
|
-
|
|
13999
|
-
|
|
14000
|
-
res.json({ ok: true, url: session.currentUrl, title: session.title });
|
|
14325
|
+
await routed.page.goBack({ timeout: 10000 });
|
|
14326
|
+
const state = await syncPageState(session, routed);
|
|
14327
|
+
res.json({ ok: true, url: state.url, title: state.title });
|
|
14001
14328
|
} catch (err) {
|
|
14002
14329
|
res.json({ ok: false, error: err.message });
|
|
14003
14330
|
}
|
|
@@ -14006,11 +14333,12 @@ app.post('/api/browser/sessions/:id/back', async (req, res) => {
|
|
|
14006
14333
|
app.post('/api/browser/sessions/:id/forward', async (req, res) => {
|
|
14007
14334
|
const session = browserSessions.get(req.params.id);
|
|
14008
14335
|
if (!session) return res.status(404).json({ error: 'Session not found' });
|
|
14336
|
+
const routed = getTargetPage(session, req);
|
|
14337
|
+
if (!routed) return res.status(404).json({ error: `Tab ${req.body?.tabId} not found in session` });
|
|
14009
14338
|
try {
|
|
14010
|
-
await
|
|
14011
|
-
|
|
14012
|
-
|
|
14013
|
-
res.json({ ok: true, url: session.currentUrl, title: session.title });
|
|
14339
|
+
await routed.page.goForward({ timeout: 10000 });
|
|
14340
|
+
const state = await syncPageState(session, routed);
|
|
14341
|
+
res.json({ ok: true, url: state.url, title: state.title });
|
|
14014
14342
|
} catch (err) {
|
|
14015
14343
|
res.json({ ok: false, error: err.message });
|
|
14016
14344
|
}
|
|
@@ -14019,11 +14347,12 @@ app.post('/api/browser/sessions/:id/forward', async (req, res) => {
|
|
|
14019
14347
|
app.post('/api/browser/sessions/:id/reload', async (req, res) => {
|
|
14020
14348
|
const session = browserSessions.get(req.params.id);
|
|
14021
14349
|
if (!session) return res.status(404).json({ error: 'Session not found' });
|
|
14350
|
+
const routed = getTargetPage(session, req);
|
|
14351
|
+
if (!routed) return res.status(404).json({ error: `Tab ${req.body?.tabId} not found in session` });
|
|
14022
14352
|
try {
|
|
14023
|
-
await
|
|
14024
|
-
|
|
14025
|
-
|
|
14026
|
-
res.json({ ok: true, url: session.currentUrl, title: session.title });
|
|
14353
|
+
await routed.page.reload({ timeout: 15000 });
|
|
14354
|
+
const state = await syncPageState(session, routed);
|
|
14355
|
+
res.json({ ok: true, url: state.url, title: state.title });
|
|
14027
14356
|
} catch (err) {
|
|
14028
14357
|
res.json({ ok: false, error: err.message });
|
|
14029
14358
|
}
|
|
@@ -14033,8 +14362,10 @@ app.post('/api/browser/sessions/:id/reload', async (req, res) => {
|
|
|
14033
14362
|
app.get('/api/browser/sessions/:id/screenshot', async (req, res) => {
|
|
14034
14363
|
const session = browserSessions.get(req.params.id);
|
|
14035
14364
|
if (!session) return res.status(404).json({ error: 'Session not found' });
|
|
14365
|
+
const routed = getTargetPage(session, req);
|
|
14366
|
+
if (!routed) return res.status(404).json({ error: `Tab ${req.query?.tabId} not found in session` });
|
|
14036
14367
|
try {
|
|
14037
|
-
const buf = await
|
|
14368
|
+
const buf = await routed.page.screenshot({ type: 'jpeg', quality: 80 });
|
|
14038
14369
|
res.set('Content-Type', 'image/jpeg');
|
|
14039
14370
|
res.send(buf);
|
|
14040
14371
|
} catch (err) {
|
|
@@ -14113,15 +14444,17 @@ async function getInteractiveHints(page) {
|
|
|
14113
14444
|
app.post('/api/browser/sessions/:id/click', async (req, res) => {
|
|
14114
14445
|
const session = browserSessions.get(req.params.id);
|
|
14115
14446
|
if (!session) return res.status(404).json({ error: 'Session not found' });
|
|
14447
|
+
const routed = getTargetPage(session, req);
|
|
14448
|
+
if (!routed) return res.status(404).json({ error: `Tab ${req.body?.tabId} not found in session` });
|
|
14116
14449
|
const { selector: rawSelector, timeout, nthMatch } = req.body;
|
|
14117
14450
|
if (!rawSelector) return res.status(400).json({ error: 'selector required' });
|
|
14118
14451
|
const selector = normalizeSelector(rawSelector);
|
|
14119
14452
|
try {
|
|
14120
|
-
const loc =
|
|
14453
|
+
const loc = routed.page.locator(selector);
|
|
14121
14454
|
// Pre-check element count for better error messages
|
|
14122
14455
|
const count = await loc.count().catch(() => -1);
|
|
14123
14456
|
if (count === 0) {
|
|
14124
|
-
const hints = await getInteractiveHints(
|
|
14457
|
+
const hints = await getInteractiveHints(routed.page);
|
|
14125
14458
|
return res.status(400).json({ error: `No elements match selector: ${selector}`, hints });
|
|
14126
14459
|
}
|
|
14127
14460
|
if (count > 1 && nthMatch === undefined) {
|
|
@@ -14129,9 +14462,8 @@ app.post('/api/browser/sessions/:id/click', async (req, res) => {
|
|
|
14129
14462
|
}
|
|
14130
14463
|
const target = (count > 1 && nthMatch !== undefined) ? loc.nth(nthMatch) : loc;
|
|
14131
14464
|
await target.click({ timeout: timeout || 5000 });
|
|
14132
|
-
|
|
14133
|
-
|
|
14134
|
-
res.json({ ok: true, url: session.currentUrl, title: session.title });
|
|
14465
|
+
const state = await syncPageState(session, routed);
|
|
14466
|
+
res.json({ ok: true, url: state.url, title: state.title });
|
|
14135
14467
|
} catch (err) {
|
|
14136
14468
|
res.status(500).json({ error: err.message });
|
|
14137
14469
|
}
|
|
@@ -14140,14 +14472,16 @@ app.post('/api/browser/sessions/:id/click', async (req, res) => {
|
|
|
14140
14472
|
app.post('/api/browser/sessions/:id/fill', async (req, res) => {
|
|
14141
14473
|
const session = browserSessions.get(req.params.id);
|
|
14142
14474
|
if (!session) return res.status(404).json({ error: 'Session not found' });
|
|
14475
|
+
const routed = getTargetPage(session, req);
|
|
14476
|
+
if (!routed) return res.status(404).json({ error: `Tab ${req.body?.tabId} not found in session` });
|
|
14143
14477
|
const { selector: rawFillSel, value, timeout, nthMatch } = req.body;
|
|
14144
14478
|
if (!rawFillSel) return res.status(400).json({ error: 'selector required' });
|
|
14145
14479
|
const selector = normalizeSelector(rawFillSel);
|
|
14146
14480
|
try {
|
|
14147
|
-
const loc =
|
|
14481
|
+
const loc = routed.page.locator(selector);
|
|
14148
14482
|
const count = await loc.count().catch(() => -1);
|
|
14149
14483
|
if (count === 0) {
|
|
14150
|
-
const hints = await getInteractiveHints(
|
|
14484
|
+
const hints = await getInteractiveHints(routed.page);
|
|
14151
14485
|
return res.status(400).json({ error: `No elements match selector: ${selector}`, hints });
|
|
14152
14486
|
}
|
|
14153
14487
|
if (count > 1 && nthMatch === undefined) {
|
|
@@ -14155,9 +14489,8 @@ app.post('/api/browser/sessions/:id/fill', async (req, res) => {
|
|
|
14155
14489
|
}
|
|
14156
14490
|
const target = (count > 1 && nthMatch !== undefined) ? loc.nth(nthMatch) : loc;
|
|
14157
14491
|
await target.fill(value ?? '', { timeout: timeout || 5000 });
|
|
14158
|
-
|
|
14159
|
-
|
|
14160
|
-
res.json({ ok: true, url: session.currentUrl, title: session.title });
|
|
14492
|
+
const state = await syncPageState(session, routed);
|
|
14493
|
+
res.json({ ok: true, url: state.url, title: state.title });
|
|
14161
14494
|
} catch (err) {
|
|
14162
14495
|
res.status(500).json({ error: err.message });
|
|
14163
14496
|
}
|
|
@@ -14166,14 +14499,16 @@ app.post('/api/browser/sessions/:id/fill', async (req, res) => {
|
|
|
14166
14499
|
app.post('/api/browser/sessions/:id/type', async (req, res) => {
|
|
14167
14500
|
const session = browserSessions.get(req.params.id);
|
|
14168
14501
|
if (!session) return res.status(404).json({ error: 'Session not found' });
|
|
14502
|
+
const routed = getTargetPage(session, req);
|
|
14503
|
+
if (!routed) return res.status(404).json({ error: `Tab ${req.body?.tabId} not found in session` });
|
|
14169
14504
|
const { selector: rawTypeSel, text, timeout, nthMatch } = req.body;
|
|
14170
14505
|
try {
|
|
14171
14506
|
if (rawTypeSel) {
|
|
14172
14507
|
const selector = normalizeSelector(rawTypeSel);
|
|
14173
|
-
const loc =
|
|
14508
|
+
const loc = routed.page.locator(selector);
|
|
14174
14509
|
const count = await loc.count().catch(() => -1);
|
|
14175
14510
|
if (count === 0) {
|
|
14176
|
-
const hints = await getInteractiveHints(
|
|
14511
|
+
const hints = await getInteractiveHints(routed.page);
|
|
14177
14512
|
return res.status(400).json({ error: `No elements match selector: ${selector}`, hints });
|
|
14178
14513
|
}
|
|
14179
14514
|
if (count > 1 && nthMatch === undefined) {
|
|
@@ -14183,11 +14518,10 @@ app.post('/api/browser/sessions/:id/type', async (req, res) => {
|
|
|
14183
14518
|
await target.pressSequentially(text ?? '', { timeout: timeout || 5000 });
|
|
14184
14519
|
} else {
|
|
14185
14520
|
// No selector: type into the currently focused element via keyboard
|
|
14186
|
-
await
|
|
14521
|
+
await routed.page.keyboard.type(text ?? '');
|
|
14187
14522
|
}
|
|
14188
|
-
|
|
14189
|
-
|
|
14190
|
-
res.json({ ok: true, url: session.currentUrl, title: session.title });
|
|
14523
|
+
const state = await syncPageState(session, routed);
|
|
14524
|
+
res.json({ ok: true, url: state.url, title: state.title });
|
|
14191
14525
|
} catch (err) {
|
|
14192
14526
|
res.status(500).json({ error: err.message });
|
|
14193
14527
|
}
|
|
@@ -14196,14 +14530,16 @@ app.post('/api/browser/sessions/:id/type', async (req, res) => {
|
|
|
14196
14530
|
app.post('/api/browser/sessions/:id/hover', async (req, res) => {
|
|
14197
14531
|
const session = browserSessions.get(req.params.id);
|
|
14198
14532
|
if (!session) return res.status(404).json({ error: 'Session not found' });
|
|
14533
|
+
const routed = getTargetPage(session, req);
|
|
14534
|
+
if (!routed) return res.status(404).json({ error: `Tab ${req.body?.tabId} not found in session` });
|
|
14199
14535
|
const { selector: rawHoverSel, timeout, nthMatch } = req.body;
|
|
14200
14536
|
if (!rawHoverSel) return res.status(400).json({ error: 'selector required' });
|
|
14201
14537
|
const selector = normalizeSelector(rawHoverSel);
|
|
14202
14538
|
try {
|
|
14203
|
-
const loc =
|
|
14539
|
+
const loc = routed.page.locator(selector);
|
|
14204
14540
|
const count = await loc.count().catch(() => -1);
|
|
14205
14541
|
if (count === 0) {
|
|
14206
|
-
const hints = await getInteractiveHints(
|
|
14542
|
+
const hints = await getInteractiveHints(routed.page);
|
|
14207
14543
|
return res.status(400).json({ error: `No elements match selector: ${selector}`, hints });
|
|
14208
14544
|
}
|
|
14209
14545
|
if (count > 1 && nthMatch === undefined) {
|
|
@@ -14211,9 +14547,8 @@ app.post('/api/browser/sessions/:id/hover', async (req, res) => {
|
|
|
14211
14547
|
}
|
|
14212
14548
|
const target = (count > 1 && nthMatch !== undefined) ? loc.nth(nthMatch) : loc;
|
|
14213
14549
|
await target.hover({ timeout: timeout || 5000 });
|
|
14214
|
-
|
|
14215
|
-
|
|
14216
|
-
res.json({ ok: true, url: session.currentUrl, title: session.title });
|
|
14550
|
+
const state = await syncPageState(session, routed);
|
|
14551
|
+
res.json({ ok: true, url: state.url, title: state.title });
|
|
14217
14552
|
} catch (err) {
|
|
14218
14553
|
res.status(500).json({ error: err.message });
|
|
14219
14554
|
}
|
|
@@ -14222,14 +14557,16 @@ app.post('/api/browser/sessions/:id/hover', async (req, res) => {
|
|
|
14222
14557
|
app.post('/api/browser/sessions/:id/select', async (req, res) => {
|
|
14223
14558
|
const session = browserSessions.get(req.params.id);
|
|
14224
14559
|
if (!session) return res.status(404).json({ error: 'Session not found' });
|
|
14560
|
+
const routed = getTargetPage(session, req);
|
|
14561
|
+
if (!routed) return res.status(404).json({ error: `Tab ${req.body?.tabId} not found in session` });
|
|
14225
14562
|
const { selector: rawSelSel, value, timeout, nthMatch } = req.body;
|
|
14226
14563
|
if (!rawSelSel) return res.status(400).json({ error: 'selector required' });
|
|
14227
14564
|
const selector = normalizeSelector(rawSelSel);
|
|
14228
14565
|
try {
|
|
14229
|
-
const loc =
|
|
14566
|
+
const loc = routed.page.locator(selector);
|
|
14230
14567
|
const count = await loc.count().catch(() => -1);
|
|
14231
14568
|
if (count === 0) {
|
|
14232
|
-
const hints = await getInteractiveHints(
|
|
14569
|
+
const hints = await getInteractiveHints(routed.page);
|
|
14233
14570
|
return res.status(400).json({ error: `No elements match selector: ${selector}`, hints });
|
|
14234
14571
|
}
|
|
14235
14572
|
if (count > 1 && nthMatch === undefined) {
|
|
@@ -14237,9 +14574,8 @@ app.post('/api/browser/sessions/:id/select', async (req, res) => {
|
|
|
14237
14574
|
}
|
|
14238
14575
|
const target = (count > 1 && nthMatch !== undefined) ? loc.nth(nthMatch) : loc;
|
|
14239
14576
|
await target.selectOption(value ?? '', { timeout: timeout || 5000 });
|
|
14240
|
-
|
|
14241
|
-
|
|
14242
|
-
res.json({ ok: true, url: session.currentUrl, title: session.title });
|
|
14577
|
+
const state = await syncPageState(session, routed);
|
|
14578
|
+
res.json({ ok: true, url: state.url, title: state.title });
|
|
14243
14579
|
} catch (err) {
|
|
14244
14580
|
res.status(500).json({ error: err.message });
|
|
14245
14581
|
}
|
|
@@ -14248,13 +14584,14 @@ app.post('/api/browser/sessions/:id/select', async (req, res) => {
|
|
|
14248
14584
|
app.post('/api/browser/sessions/:id/press', async (req, res) => {
|
|
14249
14585
|
const session = browserSessions.get(req.params.id);
|
|
14250
14586
|
if (!session) return res.status(404).json({ error: 'Session not found' });
|
|
14587
|
+
const routed = getTargetPage(session, req);
|
|
14588
|
+
if (!routed) return res.status(404).json({ error: `Tab ${req.body?.tabId} not found in session` });
|
|
14251
14589
|
const { key } = req.body;
|
|
14252
14590
|
if (!key) return res.status(400).json({ error: 'key required' });
|
|
14253
14591
|
try {
|
|
14254
|
-
await
|
|
14255
|
-
|
|
14256
|
-
|
|
14257
|
-
res.json({ ok: true, url: session.currentUrl, title: session.title });
|
|
14592
|
+
await routed.page.keyboard.press(key);
|
|
14593
|
+
const state = await syncPageState(session, routed);
|
|
14594
|
+
res.json({ ok: true, url: state.url, title: state.title });
|
|
14258
14595
|
} catch (err) {
|
|
14259
14596
|
res.status(500).json({ error: err.message });
|
|
14260
14597
|
}
|
|
@@ -14263,10 +14600,12 @@ app.post('/api/browser/sessions/:id/press', async (req, res) => {
|
|
|
14263
14600
|
app.post('/api/browser/sessions/:id/evaluate', async (req, res) => {
|
|
14264
14601
|
const session = browserSessions.get(req.params.id);
|
|
14265
14602
|
if (!session) return res.status(404).json({ error: 'Session not found' });
|
|
14603
|
+
const routed = getTargetPage(session, req);
|
|
14604
|
+
if (!routed) return res.status(404).json({ error: `Tab ${req.body?.tabId} not found in session` });
|
|
14266
14605
|
const { script } = req.body;
|
|
14267
14606
|
if (!script) return res.status(400).json({ error: 'script required' });
|
|
14268
14607
|
try {
|
|
14269
|
-
const result = await
|
|
14608
|
+
const result = await routed.page.evaluate(script);
|
|
14270
14609
|
// Ensure result is JSON-serializable (undefined becomes null)
|
|
14271
14610
|
res.json({ ok: true, result: result === undefined ? null : result });
|
|
14272
14611
|
} catch (err) {
|
|
@@ -14277,21 +14616,22 @@ app.post('/api/browser/sessions/:id/evaluate', async (req, res) => {
|
|
|
14277
14616
|
app.get('/api/browser/sessions/:id/snapshot', async (req, res) => {
|
|
14278
14617
|
const session = browserSessions.get(req.params.id);
|
|
14279
14618
|
if (!session) return res.status(404).json({ error: 'Session not found' });
|
|
14619
|
+
const routed = getTargetPage(session, req);
|
|
14620
|
+
if (!routed) return res.status(404).json({ error: `Tab ${req.query?.tabId} not found in session` });
|
|
14280
14621
|
try {
|
|
14281
14622
|
// page.accessibility was removed in Playwright 1.50+
|
|
14282
14623
|
let tree = null;
|
|
14283
|
-
if (
|
|
14284
|
-
tree = await
|
|
14624
|
+
if (routed.page.accessibility && typeof routed.page.accessibility.snapshot === 'function') {
|
|
14625
|
+
tree = await routed.page.accessibility.snapshot();
|
|
14285
14626
|
} else {
|
|
14286
14627
|
// Fallback: build a tree from ariaSnapshot text
|
|
14287
|
-
const ariaText = await
|
|
14628
|
+
const ariaText = await routed.page.locator('body').ariaSnapshot({ timeout: 5000 }).catch(() => null);
|
|
14288
14629
|
if (ariaText) {
|
|
14289
14630
|
tree = parseAriaSnapshotText(ariaText);
|
|
14290
14631
|
}
|
|
14291
14632
|
}
|
|
14292
|
-
|
|
14293
|
-
|
|
14294
|
-
res.json({ ok: true, url: session.currentUrl, title: session.title, snapshot: tree });
|
|
14633
|
+
const state = await syncPageState(session, routed);
|
|
14634
|
+
res.json({ ok: true, url: state.url, title: state.title, snapshot: tree });
|
|
14295
14635
|
} catch (err) {
|
|
14296
14636
|
res.status(500).json({ error: err.message });
|
|
14297
14637
|
}
|
|
@@ -14300,24 +14640,25 @@ app.get('/api/browser/sessions/:id/snapshot', async (req, res) => {
|
|
|
14300
14640
|
app.post('/api/browser/sessions/:id/snapshot', async (req, res) => {
|
|
14301
14641
|
const session = browserSessions.get(req.params.id);
|
|
14302
14642
|
if (!session) return res.status(404).json({ error: 'Session not found' });
|
|
14643
|
+
const routed = getTargetPage(session, req);
|
|
14644
|
+
if (!routed) return res.status(404).json({ error: `Tab ${req.body?.tabId} not found in session` });
|
|
14303
14645
|
const { selector: rawSel } = req.body;
|
|
14304
14646
|
const scopeSel = rawSel ? normalizeSelector(rawSel) : null;
|
|
14305
14647
|
try {
|
|
14306
14648
|
let tree = null;
|
|
14307
14649
|
if (scopeSel) {
|
|
14308
|
-
const ariaText = await
|
|
14650
|
+
const ariaText = await routed.page.locator(scopeSel).ariaSnapshot({ timeout: 8000 }).catch(() => null);
|
|
14309
14651
|
if (ariaText) tree = parseAriaSnapshotText(ariaText);
|
|
14310
14652
|
} else {
|
|
14311
|
-
if (
|
|
14312
|
-
tree = await
|
|
14653
|
+
if (routed.page.accessibility && typeof routed.page.accessibility.snapshot === 'function') {
|
|
14654
|
+
tree = await routed.page.accessibility.snapshot();
|
|
14313
14655
|
} else {
|
|
14314
|
-
const ariaText = await
|
|
14656
|
+
const ariaText = await routed.page.locator('body').ariaSnapshot({ timeout: 5000 }).catch(() => null);
|
|
14315
14657
|
if (ariaText) tree = parseAriaSnapshotText(ariaText);
|
|
14316
14658
|
}
|
|
14317
14659
|
}
|
|
14318
|
-
|
|
14319
|
-
|
|
14320
|
-
res.json({ ok: true, url: session.currentUrl, title: session.title, snapshot: tree });
|
|
14660
|
+
const state = await syncPageState(session, routed);
|
|
14661
|
+
res.json({ ok: true, url: state.url, title: state.title, snapshot: tree });
|
|
14321
14662
|
} catch (err) {
|
|
14322
14663
|
res.status(500).json({ error: err.message });
|
|
14323
14664
|
}
|
|
@@ -14360,26 +14701,26 @@ function parseAriaSnapshotText(text) {
|
|
|
14360
14701
|
app.post('/api/browser/sessions/:id/wait', async (req, res) => {
|
|
14361
14702
|
const session = browserSessions.get(req.params.id);
|
|
14362
14703
|
if (!session) return res.status(404).json({ error: 'Session not found' });
|
|
14704
|
+
const routed = getTargetPage(session, req);
|
|
14705
|
+
if (!routed) return res.status(404).json({ error: `Tab ${req.body?.tabId} not found in session` });
|
|
14363
14706
|
const { selector, state, loadState, timeout } = req.body;
|
|
14364
14707
|
try {
|
|
14365
14708
|
if (loadState) {
|
|
14366
14709
|
const valid = ['load', 'domcontentloaded', 'networkidle'];
|
|
14367
14710
|
if (!valid.includes(loadState)) return res.status(400).json({ error: `Invalid loadState. Use: ${valid.join(', ')}` });
|
|
14368
|
-
await
|
|
14369
|
-
|
|
14370
|
-
|
|
14371
|
-
res.json({ ok: true, loadState, url: session.currentUrl, title: session.title });
|
|
14711
|
+
await routed.page.waitForLoadState(loadState, { timeout: timeout || 15000 });
|
|
14712
|
+
const ps = await syncPageState(session, routed);
|
|
14713
|
+
res.json({ ok: true, loadState, url: ps.url, title: ps.title });
|
|
14372
14714
|
} else if (selector) {
|
|
14373
|
-
await
|
|
14715
|
+
await routed.page.locator(selector).waitFor({
|
|
14374
14716
|
state: state || 'visible',
|
|
14375
14717
|
timeout: timeout || 10000,
|
|
14376
14718
|
});
|
|
14377
14719
|
res.json({ ok: true, selector, state: state || 'visible' });
|
|
14378
14720
|
} else {
|
|
14379
|
-
await
|
|
14380
|
-
|
|
14381
|
-
|
|
14382
|
-
res.json({ ok: true, url: session.currentUrl, title: session.title });
|
|
14721
|
+
await routed.page.waitForTimeout(timeout || 1000);
|
|
14722
|
+
const ps = await syncPageState(session, routed);
|
|
14723
|
+
res.json({ ok: true, url: ps.url, title: ps.title });
|
|
14383
14724
|
}
|
|
14384
14725
|
} catch (err) {
|
|
14385
14726
|
res.status(500).json({ error: err.message });
|
|
@@ -14389,15 +14730,16 @@ app.post('/api/browser/sessions/:id/wait', async (req, res) => {
|
|
|
14389
14730
|
app.get('/api/browser/sessions/:id/content', async (req, res) => {
|
|
14390
14731
|
const session = browserSessions.get(req.params.id);
|
|
14391
14732
|
if (!session) return res.status(404).json({ error: 'Session not found' });
|
|
14733
|
+
const routed = getTargetPage(session, req);
|
|
14734
|
+
if (!routed) return res.status(404).json({ error: `Tab ${req.query?.tabId} not found in session` });
|
|
14392
14735
|
try {
|
|
14393
|
-
|
|
14394
|
-
session.title = await session.page.title().catch(() => '');
|
|
14736
|
+
const state = await syncPageState(session, routed);
|
|
14395
14737
|
let text = '';
|
|
14396
14738
|
try {
|
|
14397
|
-
text = await
|
|
14739
|
+
text = await routed.page.innerText('body');
|
|
14398
14740
|
if (text.length > 50000) text = text.slice(0, 50000) + '\n... (truncated)';
|
|
14399
14741
|
} catch { text = ''; }
|
|
14400
|
-
res.json({ ok: true, url:
|
|
14742
|
+
res.json({ ok: true, url: state.url, title: state.title, text });
|
|
14401
14743
|
} catch (err) {
|
|
14402
14744
|
res.status(500).json({ error: err.message });
|
|
14403
14745
|
}
|
|
@@ -14417,14 +14759,15 @@ const nhm = new NodeHtmlMarkdown({
|
|
|
14417
14759
|
app.get('/api/browser/sessions/:id/markdown', async (req, res) => {
|
|
14418
14760
|
const session = browserSessions.get(req.params.id);
|
|
14419
14761
|
if (!session) return res.status(404).json({ error: 'Session not found' });
|
|
14762
|
+
const routed = getTargetPage(session, req);
|
|
14763
|
+
if (!routed) return res.status(404).json({ error: `Tab ${req.query?.tabId} not found in session` });
|
|
14420
14764
|
try {
|
|
14421
|
-
|
|
14422
|
-
session.title = await session.page.title().catch(() => '');
|
|
14765
|
+
const state = await syncPageState(session, routed);
|
|
14423
14766
|
|
|
14424
14767
|
// Extract main content HTML — strip nav, header, footer, sidebar, ads
|
|
14425
14768
|
let html = '';
|
|
14426
14769
|
try {
|
|
14427
|
-
html = await
|
|
14770
|
+
html = await routed.page.evaluate(() => {
|
|
14428
14771
|
// Remove noise elements before extraction
|
|
14429
14772
|
const removeSelectors = [
|
|
14430
14773
|
'nav', 'header', 'footer', 'aside',
|
|
@@ -14445,7 +14788,7 @@ app.get('/api/browser/sessions/:id/markdown', async (req, res) => {
|
|
|
14445
14788
|
} catch { html = ''; }
|
|
14446
14789
|
|
|
14447
14790
|
if (!html) {
|
|
14448
|
-
return res.json({ ok: true, url:
|
|
14791
|
+
return res.json({ ok: true, url: state.url, title: state.title, markdown: '', tokens: 0 });
|
|
14449
14792
|
}
|
|
14450
14793
|
|
|
14451
14794
|
let markdown = nhm.translate(html);
|
|
@@ -14455,7 +14798,7 @@ app.get('/api/browser/sessions/:id/markdown', async (req, res) => {
|
|
|
14455
14798
|
markdown = markdown.slice(0, 80000) + '\n\n... (truncated at 80K chars)';
|
|
14456
14799
|
}
|
|
14457
14800
|
|
|
14458
|
-
res.json({ ok: true, url:
|
|
14801
|
+
res.json({ ok: true, url: state.url, title: state.title, markdown, tokens: estimatedTokens });
|
|
14459
14802
|
} catch (err) {
|
|
14460
14803
|
res.status(500).json({ error: err.message });
|
|
14461
14804
|
}
|
|
@@ -14517,11 +14860,12 @@ app.post('/api/fetch-markdown', async (req, res) => {
|
|
|
14517
14860
|
app.get('/api/browser/sessions/:id/screenshot-base64', async (req, res) => {
|
|
14518
14861
|
const session = browserSessions.get(req.params.id);
|
|
14519
14862
|
if (!session) return res.status(404).json({ error: 'Session not found' });
|
|
14863
|
+
const routed = getTargetPage(session, req);
|
|
14864
|
+
if (!routed) return res.status(404).json({ error: `Tab ${req.query?.tabId} not found in session` });
|
|
14520
14865
|
try {
|
|
14521
|
-
const buf = await
|
|
14522
|
-
|
|
14523
|
-
|
|
14524
|
-
res.json({ ok: true, url: session.currentUrl, title: session.title, data: buf.toString('base64') });
|
|
14866
|
+
const buf = await routed.page.screenshot({ type: 'jpeg', quality: 70 });
|
|
14867
|
+
const state = await syncPageState(session, routed);
|
|
14868
|
+
res.json({ ok: true, url: state.url, title: state.title, data: buf.toString('base64') });
|
|
14525
14869
|
} catch (err) {
|
|
14526
14870
|
res.status(500).json({ error: err.message });
|
|
14527
14871
|
}
|
|
@@ -14530,21 +14874,22 @@ app.get('/api/browser/sessions/:id/screenshot-base64', async (req, res) => {
|
|
|
14530
14874
|
app.post('/api/browser/sessions/:id/scroll', async (req, res) => {
|
|
14531
14875
|
const session = browserSessions.get(req.params.id);
|
|
14532
14876
|
if (!session) return res.status(404).json({ error: 'Session not found' });
|
|
14877
|
+
const routed = getTargetPage(session, req);
|
|
14878
|
+
if (!routed) return res.status(404).json({ error: `Tab ${req.body?.tabId} not found in session` });
|
|
14533
14879
|
const { direction = 'down', distance = 500, selector: rawSel } = req.body;
|
|
14534
14880
|
const deltaX = direction === 'right' ? distance : direction === 'left' ? -distance : 0;
|
|
14535
14881
|
const deltaY = direction === 'down' ? distance : direction === 'up' ? -distance : 0;
|
|
14536
14882
|
try {
|
|
14537
14883
|
if (rawSel) {
|
|
14538
|
-
await
|
|
14884
|
+
await routed.page.locator(normalizeSelector(rawSel)).evaluate(
|
|
14539
14885
|
(el, { dx, dy }) => el.scrollBy(dx, dy), { dx: deltaX, dy: deltaY }
|
|
14540
14886
|
);
|
|
14541
14887
|
} else {
|
|
14542
|
-
await
|
|
14888
|
+
await routed.page.evaluate(({ dx, dy }) => window.scrollBy(dx, dy), { dx: deltaX, dy: deltaY });
|
|
14543
14889
|
}
|
|
14544
|
-
await
|
|
14545
|
-
|
|
14546
|
-
|
|
14547
|
-
res.json({ ok: true, url: session.currentUrl, title: session.title });
|
|
14890
|
+
await routed.page.waitForTimeout(300);
|
|
14891
|
+
const state = await syncPageState(session, routed);
|
|
14892
|
+
res.json({ ok: true, url: state.url, title: state.title });
|
|
14548
14893
|
} catch (err) {
|
|
14549
14894
|
res.status(500).json({ error: err.message });
|
|
14550
14895
|
}
|
|
@@ -14553,15 +14898,17 @@ app.post('/api/browser/sessions/:id/scroll', async (req, res) => {
|
|
|
14553
14898
|
app.post('/api/browser/sessions/:id/upload', async (req, res) => {
|
|
14554
14899
|
const session = browserSessions.get(req.params.id);
|
|
14555
14900
|
if (!session) return res.status(404).json({ error: 'Session not found' });
|
|
14901
|
+
const routed = getTargetPage(session, req);
|
|
14902
|
+
if (!routed) return res.status(404).json({ error: `Tab ${req.body?.tabId} not found in session` });
|
|
14556
14903
|
const { selector: rawSel, filePaths, nthMatch } = req.body;
|
|
14557
14904
|
if (!rawSel) return res.status(400).json({ error: 'selector required' });
|
|
14558
14905
|
if (!Array.isArray(filePaths) || !filePaths.length) return res.status(400).json({ error: 'filePaths must be a non-empty array' });
|
|
14559
14906
|
const selector = normalizeSelector(rawSel);
|
|
14560
14907
|
try {
|
|
14561
|
-
const loc =
|
|
14908
|
+
const loc = routed.page.locator(selector);
|
|
14562
14909
|
const count = await loc.count().catch(() => -1);
|
|
14563
14910
|
if (count === 0) {
|
|
14564
|
-
const hints = await getInteractiveHints(
|
|
14911
|
+
const hints = await getInteractiveHints(routed.page);
|
|
14565
14912
|
return res.status(400).json({ error: `No elements match selector: ${selector}`, hints });
|
|
14566
14913
|
}
|
|
14567
14914
|
if (count > 1 && nthMatch === undefined) {
|
|
@@ -14569,10 +14916,9 @@ app.post('/api/browser/sessions/:id/upload', async (req, res) => {
|
|
|
14569
14916
|
}
|
|
14570
14917
|
const target = (count > 1 && nthMatch !== undefined) ? loc.nth(nthMatch) : loc;
|
|
14571
14918
|
await target.setInputFiles(filePaths);
|
|
14572
|
-
await
|
|
14573
|
-
|
|
14574
|
-
|
|
14575
|
-
res.json({ ok: true, url: session.currentUrl, title: session.title });
|
|
14919
|
+
await routed.page.waitForTimeout(500);
|
|
14920
|
+
const state = await syncPageState(session, routed);
|
|
14921
|
+
res.json({ ok: true, url: state.url, title: state.title });
|
|
14576
14922
|
} catch (err) {
|
|
14577
14923
|
res.status(500).json({ error: err.message });
|
|
14578
14924
|
}
|