Repository navigation
Expand file tree
/
Copy pathauto-accept.js
More file actions
467 lines (421 loc) · 15.5 KB
/
Copy pathauto-accept.js
File metadata and controls
467 lines (421 loc) · 15.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
#!/usr/bin/env node
'use strict';
const puppeteer = require('puppeteer-core');
const tgRemote = require('./telegram-remote');
const slackRemote = require('./slack-remote');
const CDP_PORT = process.env.CDP_PORT || 9222;
const POLL_MS = parseInt(process.env.POLL_MS, 10) || 300;
const RECONNECT_MS = 3000;
// --- Notification config (set via env vars) ---
// Telegram: TELEGRAM_BOT_TOKEN + TELEGRAM_CHAT_ID
// WeChat (via WeCom webhook): WECOM_WEBHOOK_URL
// WeChat (via PushPlus): PUSHPLUS_TOKEN
const TELEGRAM_BOT_TOKEN = process.env.TELEGRAM_BOT_TOKEN || '';
const TELEGRAM_CHAT_ID = process.env.TELEGRAM_CHAT_ID || '';
const WECOM_WEBHOOK_URL = process.env.WECOM_WEBHOOK_URL || '';
const PUSHPLUS_TOKEN = process.env.PUSHPLUS_TOKEN || '';
const NOTIFY_COOLDOWN_MS = parseInt(process.env.NOTIFY_COOLDOWN_MS, 10) || 30000;
let lastNotifyTime = 0;
function ts() {
return new Date().toLocaleTimeString();
}
function log(msg) { console.log(`[${ts()}] ${msg}`); }
function warn(msg) { console.warn(`[${ts()}] ⚠ ${msg}`); }
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
function notifyEnabled() {
return !!(TELEGRAM_BOT_TOKEN && TELEGRAM_CHAT_ID) ||
!!WECOM_WEBHOOK_URL ||
!!PUSHPLUS_TOKEN;
}
async function sendNotification(title, body) {
const now = Date.now();
if (now - lastNotifyTime < NOTIFY_COOLDOWN_MS) return;
lastNotifyTime = now;
const message = `🔔 ${title}\n${body}\n\n⏰ ${new Date().toLocaleString()}`;
log(`📨 Sending notification: ${title}`);
// Telegram
if (TELEGRAM_BOT_TOKEN && TELEGRAM_CHAT_ID) {
try {
const url = `https://api.telegram.org/bot${TELEGRAM_BOT_TOKEN}/sendMessage`;
await fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
chat_id: TELEGRAM_CHAT_ID,
text: message,
parse_mode: 'HTML',
}),
});
} catch (e) {
warn(`Telegram notify failed: ${e.message}`);
}
}
// WeCom (企业微信) webhook
if (WECOM_WEBHOOK_URL) {
try {
await fetch(WECOM_WEBHOOK_URL, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
msgtype: 'text',
text: { content: message },
}),
});
} catch (e) {
warn(`WeCom notify failed: ${e.message}`);
}
}
// PushPlus (微信推送)
if (PUSHPLUS_TOKEN) {
try {
await fetch('https://www.pushplus.plus/send', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
token: PUSHPLUS_TOKEN,
title,
content: body,
}),
});
} catch (e) {
warn(`PushPlus notify failed: ${e.message}`);
}
}
}
// Strip keyboard-shortcut hints like ⏎ Esc ⌘Y ⌘N from button text
function cleanButtonText(raw) {
return raw
.replace(/[\u23CE\u21B5\u238B\u2318\u2325\u21E7\u2303]/g, '') // ⏎ ↵ ⎋ ⌘ ⌥ ⇧ ⌃
.replace(/Esc$/i, '')
.replace(/[⌘⌥⇧⌃][A-Z]$/g, '')
.replace(/\s+/g, ' ')
.trim()
.toLowerCase();
}
async function findAndClickInFrame(frame) {
try {
const clicked = await frame.evaluate(() => {
const results = [];
const unknown = [];
const ALREADY = new Set();
function clean(raw) {
return raw
.replace(/[\u23CE\u21B5\u238B\u2318\u2325\u21E7\u2303]/g, '')
.replace(/Esc$/i, '')
.replace(/[⌘⌥⇧⌃][A-Z]$/g, '')
.replace(/\s+/g, ' ')
.trim()
.toLowerCase();
}
const WL = new Set([
'run', 'keep file', 'keep all', 'accept', 'allow', 'approve',
'run command', 'save all & run', 'accept all', 'continue',
'proceed', 'yes', 'confirm',
]);
const BL = new Set([
'skip', 'undo file', 'undo all', 'undo', 'reject', 'cancel',
'deny', 'no', 'review', 'new agent', 'browse marketplace', 'stop',
]);
const NOISE = new Set([
'cursor_test', 'outline', 'timeline', 'cursor tab',
]);
function tag(el) { return (el || '').tagName?.toLowerCase(); }
function tryClick(el, label) {
const key = `${tag(el)}:${el.className}`;
if (ALREADY.has(key)) return;
ALREADY.add(key);
el.click();
results.push(label);
}
// === Strategy 1: Shell tool-call approval (Run button) ===
// <button class="ui-button"> inside .ui-shell-tool-call__approval-row
const approvalRows = document.querySelectorAll(
'.ui-shell-tool-call__approval-row, .ui-shell-tool-call__approval-row-right'
);
for (const row of approvalRows) {
const btns = row.querySelectorAll('button.ui-button');
for (const btn of btns) {
if (btn.offsetParent === null) continue;
if (btn.classList.contains('ui-shell-tool-call__skip-btn')) continue;
const text = clean(btn.textContent || '');
if (BL.has(text)) continue;
tryClick(btn, `Run (shell: ${text})`);
}
}
// === Strategy 2: Any <button class="ui-button"> with whitelisted text ===
const uiButtons = document.querySelectorAll('button.ui-button');
for (const btn of uiButtons) {
if (btn.offsetParent === null) continue;
if (btn.classList.contains('ui-shell-tool-call__skip-btn')) continue;
const text = clean(btn.textContent || '');
if (BL.has(text)) continue;
if (WL.has(text)) {
tryClick(btn, text);
}
}
// === Strategy 3: Inline-edit accept (⌘Y / partialHoverButton) ===
const partials = document.querySelectorAll(
'button.hoverButton.partialHoverButton'
);
for (const btn of partials) {
if (btn.classList.contains('secondary-button')) continue;
if (btn.offsetParent === null) continue;
tryClick(btn, 'Accept Edit (⌘Y)');
}
// === Strategy 4: <span class="truncate"> text buttons (Keep File, etc.) ===
const spans = document.querySelectorAll('span.truncate');
for (const span of spans) {
const text = clean(span.textContent || '');
if (!text) continue;
if (BL.has(text)) continue;
if (!WL.has(text)) continue;
const clickable = span.closest(
'button, a, [role="button"], .action-label, div[class*="cursor-pointer"]'
) || span.parentElement;
if (!clickable || clickable.offsetParent === null) continue;
tryClick(clickable, text);
}
// === Strategy 5: Monaco dialog buttons (OK, Accept, Allow) ===
const monacoBtns = document.querySelectorAll(
'a.monaco-button.monaco-text-button, button.monaco-button'
);
for (const btn of monacoBtns) {
if (btn.offsetParent === null) continue;
const text = clean(btn.textContent || '');
if (BL.has(text)) continue;
if (WL.has(text)) {
tryClick(btn, text);
}
}
// === Strategy 6: Generic fallback — any visible button with WL text ===
const allBtns = document.querySelectorAll('button, [role="button"]');
for (const btn of allBtns) {
if (btn.offsetParent === null || btn.disabled) continue;
if (btn.classList.contains('partialHoverButton')) continue;
if (btn.classList.contains('ui-shell-tool-call__skip-btn')) continue;
const text = clean(btn.textContent || '');
if (!text || text.length > 30) continue;
if (BL.has(text)) continue;
if (WL.has(text)) {
tryClick(btn, text);
}
}
// === Strategy 7: Detect popups/dialogs needing manual action ===
// Scan overlays, dialogs, quick-input, notifications for unknown buttons
const popupSelectors = [
'.ui-shell-tool-call__approval-row',
'[class*="approval"]',
'[class*="dialog"]',
'[class*="modal"]',
'[class*="overlay"]',
'.quick-input-widget.show-file-icons',
'[class*="notification-toast"]',
'.monaco-dialog-box',
];
for (const sel of popupSelectors) {
const containers = document.querySelectorAll(sel);
for (const container of containers) {
if (container.offsetParent === null && !container.classList.contains('show-file-icons')) continue;
const btns = container.querySelectorAll('button, [role="button"], a.monaco-button');
for (const btn of btns) {
if (btn.offsetParent === null) continue;
const text = clean(btn.textContent || '');
if (!text || text.length > 40) continue;
if (WL.has(text) || BL.has(text) || NOISE.has(text)) continue;
unknown.push(btn.textContent.trim());
}
}
}
// Also detect the mode-switch banner (Cursor-specific)
const switchBanners = document.querySelectorAll(
'[class*="switch-mode"], [class*="mode-switch"], [class*="SwitchMode"]'
);
for (const el of switchBanners) {
if (el.offsetParent === null) continue;
const text = (el.textContent || '').trim().replace(/\s+/g, ' ').slice(0, 60);
if (text) unknown.push('Mode Switch: ' + text);
}
return { clicked: results, unknown };
});
return clicked || { clicked: [], unknown: [] };
} catch {
return { clicked: [], unknown: [] };
}
}
const _recentlyNotified = new Map(); // label -> timestamp
async function pollAllPages(browser) {
let totalClicked = 0;
const allUnknown = [];
const pages = await browser.pages();
for (const page of pages) {
try {
for (const frame of page.frames()) {
const { clicked, unknown } = await findAndClickInFrame(frame);
for (const label of clicked) {
log(`✅ Auto-clicked: "${label}"`);
totalClicked++;
}
if (unknown?.length) {
allUnknown.push(...unknown);
}
}
} catch {
// page may have been closed mid-scan
}
}
if (allUnknown.length > 0) {
const uniqueLabels = [...new Set(allUnknown)];
// Dedup: only notify once per label per 30s
const now = Date.now();
const newLabels = uniqueLabels.filter(l => {
const last = _recentlyNotified.get(l);
return !last || (now - last) > 30000;
});
if (newLabels.length > 0) {
for (const l of newLabels) _recentlyNotified.set(l, now);
warn(`Unknown element(s) detected: ${newLabels.join(', ')}`);
if (slackRemote.enabled()) {
await slackRemote.notifyBlocked(
`🔔 *Unknown element detected*\n${newLabels.join(', ')}\nSend \`ss\` to screenshot, \`click <text>\` to click.`,
newLabels
);
} else if (tgRemote.enabled()) {
await tgRemote.notifyBlocked(
`Unknown element(s): <b>${newLabels.join(', ')}</b>\nReply with text or tap a button below.`,
newLabels
);
} else if (notifyEnabled()) {
await sendNotification(
'Cursor: Unknown element detected',
`Element(s): ${newLabels.join(', ')}\nManual action may be needed.`
);
}
}
}
return totalClicked;
}
async function run() {
log('Cursor Auto-Accept starting...');
log(`CDP port: ${CDP_PORT} | Poll interval: ${POLL_MS}ms`);
if (tgRemote.enabled()) {
log('🤖 Telegram remote control enabled (two-way: screenshot + reply)');
}
if (slackRemote.enabled()) {
log('💬 Slack remote control enabled (two-way: screenshot + reply)');
}
if (notifyEnabled()) {
const channels = [];
if (TELEGRAM_BOT_TOKEN && TELEGRAM_CHAT_ID) channels.push('Telegram');
if (WECOM_WEBHOOK_URL) channels.push('WeCom');
if (PUSHPLUS_TOKEN) channels.push('PushPlus');
log(`📨 Notifications enabled: ${channels.join(', ')} (cooldown: ${NOTIFY_COOLDOWN_MS / 1000}s)`);
} else {
log('📨 Notifications disabled (set TELEGRAM_*, WECOM_*, or PUSHPLUS_* env vars to enable)');
}
const STUCK_TIMEOUT_MS = parseInt(process.env.STUCK_TIMEOUT_MS, 10) || 15000;
if (slackRemote.enabled() || tgRemote.enabled()) {
log(`⏳ Stuck detection: notify after ${STUCK_TIMEOUT_MS / 1000}s idle with visible buttons`);
}
log('Press Ctrl+C to stop.\n');
let browser = null;
let running = true;
let lifetime = 0;
let lastClickTime = Date.now();
let stuckNotified = false;
process.on('SIGINT', () => {
log(`\nStopping. Total auto-clicks this session: ${lifetime}`);
running = false;
if (browser) {
try { browser.disconnect(); } catch {}
}
process.exit(0);
});
while (running) {
if (!browser || !browser.isConnected()) {
try {
browser = await puppeteer.connect({
browserURL: `http://127.0.0.1:${CDP_PORT}`,
defaultViewport: null,
});
log('🔗 Connected to Cursor via CDP');
log('Monitoring for Run / Accept / Keep buttons...\n');
const pageGetter = async () => {
try { return (await browser.pages())[0]; } catch { return null; }
};
tgRemote.start(pageGetter);
slackRemote.start(pageGetter);
browser.on('disconnected', () => {
warn('Lost connection to Cursor. Will retry...');
browser = null;
});
} catch {
warn(
`Cannot reach Cursor on port ${CDP_PORT}. ` +
`Make sure Cursor is running with --remote-debugging-port=${CDP_PORT}`
);
await sleep(RECONNECT_MS);
continue;
}
}
try {
const clicked = await pollAllPages(browser);
lifetime += clicked;
if (clicked > 0) {
lastClickTime = Date.now();
stuckNotified = false;
}
// Stuck detection
const idleMs = Date.now() - lastClickTime;
if (idleMs > STUCK_TIMEOUT_MS && !stuckNotified) {
const page = (await browser.pages())[0];
if (page) {
const stuckInfo = await page.evaluate(() => {
const selectors = [
'.ui-shell-tool-call__approval-row button',
'button.ui-button',
'button.hoverButton.partialHoverButton',
'a.monaco-button.monaco-text-button',
'[class*="switch-mode"]',
'[class*="dialog"] button',
'[class*="notification"] button',
'[class*="modal"] button',
];
const found = [];
for (const sel of selectors) {
const els = document.querySelectorAll(sel);
for (const el of els) {
if (el.offsetParent === null) continue;
const text = (el.textContent || '').trim().replace(/\s+/g, ' ');
if (text && text.length < 50) found.push(text);
}
}
return found;
}).catch(() => []);
const hasInteractive = stuckInfo.length > 0;
if (hasInteractive) {
stuckNotified = true;
const btnList = stuckInfo.slice(0, 8).join(', ');
warn(`Agent appears stuck — visible buttons: ${btnList}`);
const msg = `⏳ Agent may be stuck (idle ${Math.round(idleMs / 1000)}s)\n` +
`Visible buttons: ${btnList}\n` +
'Send `ss` to screenshot, or `click <text>` to unblock.';
if (slackRemote.enabled()) {
await slackRemote.notifyBlocked(msg, stuckInfo.slice(0, 8));
} else if (tgRemote.enabled()) {
await tgRemote.notifyBlocked(msg, stuckInfo.slice(0, 8));
}
}
}
}
} catch {
// will reconnect on next loop
}
await sleep(POLL_MS);
}
}
run().catch(err => {
console.error('Fatal:', err);
process.exit(1);
});