-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.js
More file actions
224 lines (205 loc) · 7.85 KB
/
content.js
File metadata and controls
224 lines (205 loc) · 7.85 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
'use strict';
(function () {
const POLL_INTERVAL_MS = 30 * 1000;
const MIN_WAIT_MS = 2 * 60 * 1000;
const MAX_WAIT_MS = 5 * 60 * 1000;
var INPUT_WAIT_MS = 10000;
var INPUT_POLL_MS = 200;
function findInput() {
var sel = document.getElementById('ask-input') ||
document.querySelector('#ask-input') ||
document.querySelector('[data-testid="chat-input"]') ||
document.querySelector('[data-testid="message-input"]') ||
document.querySelector('.chat-input') ||
document.querySelector('textarea[placeholder*="message" i]') ||
document.querySelector('textarea[placeholder*="Ask" i]') ||
document.querySelector('form textarea');
console.log('[BrowserClaw] Input element', sel ? sel.id || sel.className : 'null');
return sel;
}
function waitForAskInput(onFound, timeoutMs) {
timeoutMs = timeoutMs || INPUT_WAIT_MS;
var start = Date.now();
function tick() {
var el = document.getElementById('ask-input') || document.querySelector('#ask-input');
if (el) {
console.log('[BrowserClaw] ask-input found after', Date.now() - start, 'ms');
onFound(el);
return;
}
if (Date.now() - start >= timeoutMs) {
console.warn('[BrowserClaw] ask-input not found after', timeoutMs, 'ms');
onFound(null);
return;
}
setTimeout(tick, INPUT_POLL_MS);
}
tick();
}
function clearInput(input) {
input.focus();
if (input.contentEditable === 'true' || input.getAttribute('contenteditable') === 'true' || input.id === 'ask-input') {
try {
var sel = window.getSelection();
var range = document.createRange();
range.selectNodeContents(input);
sel.removeAllRanges();
sel.addRange(range);
document.execCommand('delete', false, null);
if (input.innerText !== undefined) input.innerText = '';
if (input.textContent !== undefined) input.textContent = '';
} catch (e) {
input.innerText = '';
input.textContent = '';
}
input.dispatchEvent(new Event('input', { bubbles: true }));
} else {
input.value = '';
input.dispatchEvent(new Event('input', { bubbles: true }));
input.dispatchEvent(new Event('change', { bubbles: true }));
}
}
function setInputValueLexical(input, text, done) {
input.focus();
function tryBeforeInputFull() {
console.log('[BrowserClaw] Trying beforeinput (full text), len=', text.length);
try {
var ev = new InputEvent('beforeinput', { bubbles: true, cancelable: true, inputType: 'insertText', data: text });
input.dispatchEvent(ev);
} catch (e) { console.log('[BrowserClaw] beforeinput full failed', e); }
}
function tryBeforeInputCharByChar(cb) {
var i = 0;
function next() {
if (i >= text.length) { cb(); return; }
try {
var ev = new InputEvent('beforeinput', { bubbles: true, cancelable: true, inputType: 'insertText', data: text[i] });
input.dispatchEvent(ev);
} catch (e) {}
i++;
setTimeout(next, 5);
}
next();
}
function tryClipboardPaste(cb) {
if (!navigator.clipboard || !navigator.clipboard.writeText) { console.log('[BrowserClaw] No clipboard API'); cb(); return; }
console.log('[BrowserClaw] Trying clipboard paste');
navigator.clipboard.writeText(text).then(function () {
setTimeout(function () {
input.focus();
document.execCommand('paste');
setTimeout(cb, 100);
}, 80);
}).catch(function () { cb(); });
}
tryBeforeInputFull();
setTimeout(function () {
var hasText = (input.innerText || input.textContent || '').trim().length > 0;
console.log('[BrowserClaw] After beforeinput full, hasText=', hasText, 'innerText len=', (input.innerText || '').length);
if (hasText) {
done();
return;
}
console.log('[BrowserClaw] Trying beforeinput char-by-char');
tryBeforeInputCharByChar(function () {
if ((input.innerText || input.textContent || '').trim().length > 0) {
done();
return;
}
tryClipboardPaste(done);
});
}, 80);
}
function setInputValue(input, text, onDone) {
onDone = onDone || function () {};
clearInput(input);
input.focus();
if (input.contentEditable === 'true' || input.getAttribute('contenteditable') === 'true' || input.id === 'ask-input') {
setInputValueLexical(input, text, onDone);
} else {
input.value = text;
input.dispatchEvent(new Event('input', { bubbles: true }));
input.dispatchEvent(new Event('change', { bubbles: true }));
onDone();
}
}
function sendEnter(input) {
var opts = { key: 'Enter', code: 'Enter', keyCode: 13, bubbles: true };
input.dispatchEvent(new KeyboardEvent('keydown', opts));
input.dispatchEvent(new KeyboardEvent('keypress', opts));
input.dispatchEvent(new KeyboardEvent('keyup', opts));
}
function findLastAssistantMessage() {
var bubbles = document.querySelectorAll('.message-bubble, [data-testid*="message"], [class*="message"]');
if (!bubbles.length) {
var byRole = document.querySelectorAll('[class*="assistant"], [data-role="assistant"]');
if (byRole.length) return byRole[byRole.length - 1].innerText || byRole[byRole.length - 1].textContent;
return '';
}
var last = bubbles[bubbles.length - 1];
return last.innerText || last.textContent || '';
}
function pollUntilDone(startTime, issueNumber) {
var lastText = '';
var lastStable = 0;
function check() {
var elapsed = Date.now() - startTime;
var text = findLastAssistantMessage();
if (text && text.length > 10) {
if (text === lastText) {
lastStable = lastStable || Date.now();
if (Date.now() - lastStable > POLL_INTERVAL_MS) {
console.log('[BrowserClaw content] Result stable, sending', text.length, 'chars');
chrome.runtime.sendMessage({
action: 'cometResult',
success: true,
result: text,
text: text,
});
return;
}
} else {
lastText = text;
lastStable = 0;
}
}
if (elapsed >= MAX_WAIT_MS) {
console.log('[BrowserClaw content] Max wait reached, sending last');
chrome.runtime.sendMessage({
action: 'cometResult',
success: true,
result: lastText || '(no output captured)',
text: lastText || '(no output captured)',
});
return;
}
setTimeout(check, POLL_INTERVAL_MS);
}
setTimeout(check, POLL_INTERVAL_MS);
}
chrome.runtime.onMessage.addListener(function (msg, sender, sendResponse) {
if (msg.action !== 'sendPrompt') return;
var issue = msg.issue || {};
var prompt = issue.prompt || (issue.title + '\n' + issue.body + '\n' + issue.url);
console.log('[BrowserClaw] sendPrompt received on', window.location.href, '(context: top = this tab)');
waitForAskInput(function (input) {
if (!input) {
console.warn('[BrowserClaw] No #ask-input found (side panel is a different context — use this tab)');
chrome.runtime.sendMessage({ action: 'cometResult', success: false, error: 'Chat input not found' });
sendResponse({ ok: false, error: 'Input not found' });
return;
}
console.log('[BrowserClaw] Inserting text into #ask-input, then Enter');
setInputValue(input, prompt, function () {
setTimeout(function () { sendEnter(input); }, 150);
});
var startTime = Date.now();
setTimeout(function () {
pollUntilDone(startTime, issue.number);
}, MIN_WAIT_MS);
sendResponse({ ok: true });
});
return true;
});
console.log('[BrowserClaw] Content script loaded on', window.location.href, '— use context "top" to see these logs');
})();