Repository navigation
Expand file tree
/
Copy pathslack-remote.js
More file actions
356 lines (307 loc) · 11 KB
/
Copy pathslack-remote.js
File metadata and controls
356 lines (307 loc) · 11 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
'use strict';
// Slack Bot two-way remote control for Cursor.
// Sends screenshots when blocked, receives user replies, injects them into Cursor.
const SLACK_BOT_TOKEN = process.env.SLACK_BOT_TOKEN || '';
const SLACK_CHANNEL = process.env.SLACK_CHANNEL_ID || '';
const SLACK_API = 'https://slack.com/api';
let _getPage = null;
let _pollingStarted = false;
let _lastTs = null; // track latest message timestamp
let _botUserId = null; // to ignore own messages
function enabled() {
return !!(SLACK_BOT_TOKEN && SLACK_CHANNEL);
}
function log(msg) {
console.log(`[${new Date().toLocaleTimeString()}] 💬 Slack: ${msg}`);
}
async function slackApi(method, body, formData) {
const url = `${SLACK_API}/${method}`;
const opts = { method: 'POST' };
if (formData) {
formData.append('token', SLACK_BOT_TOKEN);
opts.body = formData;
} else {
opts.headers = {
'Authorization': `Bearer ${SLACK_BOT_TOKEN}`,
'Content-Type': 'application/json',
};
opts.body = JSON.stringify(body || {});
}
const res = await fetch(url, opts);
return res.json();
}
// ── Send messages ──────────────────────────────────────────────────
async function sendText(text) {
return slackApi('chat.postMessage', { channel: SLACK_CHANNEL, text });
}
async function sendScreenshot(page, caption) {
try {
const buf = await page.screenshot({ encoding: 'binary' });
const bytes = buf.length;
// Step 1: Get upload URL
const urlRes = await fetch(
`${SLACK_API}/files.getUploadURLExternal?filename=cursor.png&length=${bytes}`, {
method: 'GET',
headers: { 'Authorization': `Bearer ${SLACK_BOT_TOKEN}` },
}).then(r => r.json());
if (!urlRes.ok) {
log(`getUploadURL failed: ${urlRes.error}`);
await sendText(`⚠️ Screenshot failed: ${urlRes.error}\n${caption}`);
return;
}
// Step 2: Upload file to the URL
const uploadRes = await fetch(urlRes.upload_url, {
method: 'POST',
headers: { 'Content-Type': 'application/octet-stream' },
body: buf,
});
if (!uploadRes.ok) {
log(`File upload failed: ${uploadRes.status}`);
await sendText(`⚠️ Screenshot upload failed\n${caption}`);
return;
}
// Step 3: Complete the upload and share to channel
const completeRes = await slackApi('files.completeUploadExternal', {
files: [{ id: urlRes.file_id, title: 'Cursor Screenshot' }],
channel_id: SLACK_CHANNEL,
initial_comment: caption || '📸 Cursor screenshot',
});
if (!completeRes.ok) {
log(`completeUpload failed: ${completeRes.error}`);
await sendText(`⚠️ Screenshot share failed: ${completeRes.error}\n${caption}`);
}
} catch (e) {
log(`Screenshot error: ${e.message}`);
await sendText(`⚠️ Screenshot failed: ${e.message}`);
}
}
// ── Cursor interaction via CDP ─────────────────────────────────────
async function typeIntoCursor(text) {
const page = await _getPage();
if (!page) return;
const client = await page.target().createCDPSession();
for (const ch of text) {
await client.send('Input.dispatchKeyEvent', { type: 'char', text: ch });
}
await client.send('Input.dispatchKeyEvent', {
type: 'keyDown', key: 'Enter', code: 'Enter', windowsVirtualKeyCode: 13,
});
await client.send('Input.dispatchKeyEvent', { type: 'keyUp', key: 'Enter', code: 'Enter' });
await client.detach();
}
async function sendKeyCombo(keys) {
const page = await _getPage();
if (!page) return;
const client = await page.target().createCDPSession();
const keyMap = {
cmd: { key: 'Meta', code: 'MetaLeft', mod: 8 },
shift: { key: 'Shift', code: 'ShiftLeft', mod: 2 },
alt: { key: 'Alt', code: 'AltLeft', mod: 4 },
ctrl: { key: 'Control', code: 'ControlLeft', mod: 1 },
enter: { key: 'Enter', code: 'Enter' },
esc: { key: 'Escape', code: 'Escape' },
tab: { key: 'Tab', code: 'Tab' },
};
const parts = keys.toLowerCase().split('+').map(s => s.trim());
const modifiers = [];
let mainKey = null;
for (const p of parts) {
if (keyMap[p] && keyMap[p].mod) modifiers.push(keyMap[p]);
else mainKey = p;
}
const modFlag = modifiers.reduce((f, m) => f | m.mod, 0);
for (const m of modifiers) {
await client.send('Input.dispatchKeyEvent', {
type: 'keyDown', key: m.key, code: m.code, modifiers: modFlag,
});
}
if (mainKey) {
const mapped = keyMap[mainKey];
if (mapped) {
await client.send('Input.dispatchKeyEvent', {
type: 'keyDown', key: mapped.key, code: mapped.code, modifiers: modFlag,
});
await client.send('Input.dispatchKeyEvent', {
type: 'keyUp', key: mapped.key, code: mapped.code, modifiers: modFlag,
});
} else if (mainKey.length === 1) {
await client.send('Input.dispatchKeyEvent', {
type: 'keyDown', key: mainKey, code: `Key${mainKey.toUpperCase()}`,
text: mainKey, modifiers: modFlag,
});
await client.send('Input.dispatchKeyEvent', {
type: 'keyUp', key: mainKey, code: `Key${mainKey.toUpperCase()}`, modifiers: modFlag,
});
}
}
for (const m of modifiers.reverse()) {
await client.send('Input.dispatchKeyEvent', {
type: 'keyUp', key: m.key, code: m.code, modifiers: 0,
});
}
await client.detach();
}
async function clickButtonByText(targetText) {
const page = await _getPage();
if (!page) return false;
const lower = targetText.toLowerCase();
for (const frame of page.frames()) {
try {
const found = await frame.evaluate((target) => {
const els = document.querySelectorAll('button, [role="button"], a.monaco-button, .ui-button, span.truncate');
for (const el of els) {
const text = (el.textContent || '').trim().replace(/\s+/g, ' ').toLowerCase()
.replace(/[\u23CE\u21B5\u238B]/g, '');
if (text.includes(target) && el.offsetParent !== null) {
const clickable = el.closest('button, a, [role="button"], div[class*="cursor-pointer"]') || el;
clickable.click();
return true;
}
}
return false;
}, lower);
if (found) return true;
} catch {}
}
return false;
}
// ── Handle incoming Slack messages ─────────────────────────────────
async function handleMessage(text) {
const page = await _getPage();
if (!text || !page) return;
if (text === 'ss' || text === 'screenshot') {
log('Screenshot requested');
await sendScreenshot(page, '📸 Current Cursor state');
return;
}
if (text === 'status') {
await sendText('✅ Auto-accept script is running.');
return;
}
if (text === 'help') {
await sendText(
'🤖 *Cursor Remote Control*\n\n' +
'`ss` — Screenshot\n' +
'`status` — Check if running\n' +
'`click <text>` — Click button by text\n' +
'`key <combo>` — Key combo (e.g. `cmd+shift+p`, `enter`, `esc`)\n' +
'`type <text>` — Type without pressing Enter\n' +
'`say <text>` — Type into Cursor chat + Enter\n' +
'Any other text — Type into Cursor chat + Enter'
);
return;
}
if (text.startsWith('click ')) {
const target = text.slice(6).trim();
log(`Click requested: "${target}"`);
const ok = await clickButtonByText(target);
await sendText(ok ? `✅ Clicked "${target}"` : `❌ Button "${target}" not found`);
return;
}
if (text.startsWith('key ')) {
const combo = text.slice(4).trim();
log(`Key combo: ${combo}`);
await sendKeyCombo(combo);
await sendText(`⌨️ Sent: ${combo}`);
return;
}
if (text.startsWith('type ')) {
const content = text.slice(5);
log(`Type (no enter): "${content}"`);
const p = await _getPage();
const client = await p.target().createCDPSession();
for (const ch of content) {
await client.send('Input.dispatchKeyEvent', { type: 'char', text: ch });
}
await client.detach();
await sendText(`✅ Typed: ${content}`);
return;
}
if (text.startsWith('say ')) {
const content = text.slice(4);
log(`Typing into Cursor: "${content}"`);
await typeIntoCursor(content);
await sendText(`✅ Sent to Cursor: ${content}`);
return;
}
log(`Typing into Cursor: "${text}"`);
await typeIntoCursor(text);
await sendText(`✅ Sent to Cursor: ${text}`);
}
// ── Polling loop (reads channel history) ───────────────────────────
async function initBot() {
const res = await slackApi('auth.test');
if (res.ok) {
_botUserId = res.user_id;
log(`Bot user ID: ${_botUserId}`);
}
// Set initial timestamp to now so we only process new messages
const hist = await slackApi('conversations.history', {
channel: SLACK_CHANNEL, limit: 1,
});
if (hist.ok && hist.messages?.length) {
_lastTs = hist.messages[0].ts;
} else {
_lastTs = String(Date.now() / 1000);
}
}
async function pollOnce() {
try {
const res = await slackApi('conversations.history', {
channel: SLACK_CHANNEL,
oldest: _lastTs,
limit: 10,
});
if (!res.ok) {
if (res.error !== 'not_authed') log(`Poll error: ${res.error}`);
return;
}
if (!res.messages || res.messages.length === 0) return;
// Messages come newest-first, reverse for chronological order
const msgs = res.messages.reverse();
for (const msg of msgs) {
if (msg.ts === _lastTs) continue;
_lastTs = msg.ts;
// Ignore bot's own messages
if (msg.bot_id || msg.user === _botUserId) continue;
if (!msg.text) continue;
log(`Received: "${msg.text}"`);
try {
await handleMessage(msg.text.trim());
} catch (e) {
log(`Error handling message: ${e.message}`);
}
}
} catch (e) {
log(`Poll error: ${e.message}`);
}
}
async function startPolling() {
await initBot();
log('Slack bot polling started');
await sendText('🤖 Cursor Auto-Accept connected! Send `/help` for commands.');
while (true) {
await pollOnce();
await new Promise(r => setTimeout(r, 2000));
}
}
// ── Public API ─────────────────────────────────────────────────────
async function notifyBlocked(description, buttonLabels) {
if (!enabled()) return;
const page = await _getPage();
const text = `🔔 *Cursor needs attention*\n${description}\n` +
(buttonLabels?.length ? `Buttons: ${buttonLabels.map(b => `\`${b}\``).join(', ')}\nReply \`/click <text>\` to click one.` : '');
if (page) {
await sendScreenshot(page, text);
} else {
await sendText(text);
}
}
function start(pageGetter) {
if (!enabled()) return;
_getPage = pageGetter;
if (_pollingStarted) return;
_pollingStarted = true;
startPolling().catch(e => log(`Fatal: ${e.message}`));
}
module.exports = { enabled, start, notifyBlocked, sendText, sendScreenshot };