-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcontent.js
More file actions
298 lines (252 loc) · 9.46 KB
/
Copy pathcontent.js
File metadata and controls
298 lines (252 loc) · 9.46 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
// Track images in the conversation
let conversationImages = new Set();
// Listen for messages from the popup
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.action === 'processMessage') {
console.log('📥 Received message to process:', request.message);
console.log('🎨 Image queue mode:', request.imageQueueMode);
// Validate message before processing
if (!request.message || typeof request.message !== 'string' || request.message.trim().length === 0) {
console.error('❌ Invalid message: empty or not a string');
sendResponse({ success: false, error: 'Invalid message: cannot be empty' });
return false;
}
// Check if we're on ChatGPT
if (!window.location.hostname.includes('chatgpt.com')) {
console.error('❌ Not on ChatGPT domain');
sendResponse({ success: false, error: 'Not on ChatGPT website' });
return false;
}
// Count current images before processing
if (request.imageQueueMode) {
countCurrentImages();
}
processMessage(request.message, request.imageQueueMode)
.then(() => {
console.log('✅ Message processed successfully');
sendResponse({ success: true });
})
.catch((error) => {
console.error('❌ Error processing message:', error);
sendResponse({ success: false, error: error.message });
});
return true; // Required for async response
}
});
async function processMessage(message, imageQueueMode) {
console.log('🔍 Looking for ChatGPT input...');
// Try multiple selectors for better compatibility
const selectors = [
'#prompt-textarea[contenteditable="true"]',
'div[contenteditable="true"][data-placeholder]',
'textarea[data-id="prompt-textarea"]',
'.text-base[contenteditable="true"]'
];
let textarea = null;
for (const selector of selectors) {
textarea = document.querySelector(selector);
if (textarea) {
console.log(`✅ Found input using selector: ${selector}`);
break;
}
}
if (!textarea) {
console.error('❌ ChatGPT input not found with any selector');
throw new Error('ChatGPT input not found. The ChatGPT interface may have changed.');
}
// Focus and click the input first
console.log('🎯 Focusing input...');
textarea.focus();
textarea.click();
console.log('✅ Input focused');
// Set the message in the contenteditable div
console.log('📝 Setting message in input...');
// Clear existing content
textarea.innerHTML = '';
// Set new content
textarea.innerHTML = message;
// Create and dispatch proper input event
const inputEvent = new InputEvent('input', {
bubbles: true,
cancelable: true,
inputType: 'insertText',
data: message
});
textarea.dispatchEvent(inputEvent);
// Simulate text change events
const textChangeEvent = new Event('textChange', { bubbles: true });
textarea.dispatchEvent(textChangeEvent);
// Create a new keyboard event for Enter
const enterKeyEvent = new KeyboardEvent('keydown', {
bubbles: true,
cancelable: true,
key: 'Enter',
code: 'Enter',
keyCode: 13,
which: 13,
shiftKey: false,
ctrlKey: false,
altKey: false,
metaKey: false
});
console.log('✅ Message set in input');
// Wait 1 second after setting text
console.log('⏳ Waiting 1 second after text input...');
await new Promise(resolve => setTimeout(resolve, 1000));
console.log('✅ Wait complete');
// Find and click the send button using multiple selectors
console.log('🔍 Looking for send button...');
const buttonSelectors = [
'#composer-submit-button',
'button[data-testid="send-button"]',
'button[aria-label="Send message"]',
'button[aria-label="Send prompt"]',
'button svg.icon-2xl'
];
let sendButton = null;
for (const selector of buttonSelectors) {
if (selector.includes('svg')) {
// For SVG selector, find the parent button
const svg = document.querySelector(selector);
sendButton = svg?.closest('button');
} else {
sendButton = document.querySelector(selector);
}
if (sendButton && !sendButton.disabled) {
console.log(`✅ Found send button using selector: ${selector}`);
break;
}
}
if (!sendButton) {
console.error('❌ Send button not found with any selector');
throw new Error('Send button not found. The ChatGPT interface may have changed.');
}
// Small delay to ensure events are processed
await new Promise(resolve => setTimeout(resolve, 100));
console.log('🚀 Clicking send button...');
sendButton.click();
console.log('✅ Send button clicked');
// Wait for the response to complete
console.log('⏳ Waiting for response...');
await waitForResponse(imageQueueMode);
console.log('✅ Response complete');
}
async function waitForResponse(imageQueueMode) {
return new Promise((resolve, reject) => {
const maxWaitTime = 120000; // 2 minutes timeout
const startTime = Date.now();
let checkCount = 0;
let lastMessageCount = 0;
const checkCompletion = () => {
checkCount++;
// Multiple ways to detect if response is complete
const streamingIndicators = [
'button[aria-label="Stop streaming"]',
'button[aria-label="Stop generating"]',
'.result-streaming',
'[data-testid="stop-button"]'
];
let isStreaming = false;
for (const selector of streamingIndicators) {
if (document.querySelector(selector)) {
isStreaming = true;
break;
}
}
// Also check if new messages are being added
const messages = document.querySelectorAll('[data-message-author-role="assistant"]');
const currentMessageCount = messages.length;
const messageCountChanged = currentMessageCount !== lastMessageCount;
lastMessageCount = currentMessageCount;
if (!isStreaming && !messageCountChanged) {
// No streaming indicators and message count stable
if (Date.now() - startTime > 2000) { // Wait at least 2 seconds
// If image queue mode, check for new images
if (imageQueueMode) {
console.log('🎨 Checking for image generation...');
waitForImageGeneration()
.then(() => {
console.log(`✅ Response complete with image after ${checkCount} checks (${Date.now() - startTime}ms)`);
resolve();
})
.catch((error) => {
console.error('❌ Image wait failed:', error);
resolve(); // Continue anyway
});
} else {
console.log(`✅ Response complete after ${checkCount} checks (${Date.now() - startTime}ms)`);
resolve();
}
} else {
console.log('⏳ Waiting for response stabilization...');
setTimeout(checkCompletion, 300);
}
} else {
// Still streaming or messages changing
if (checkCount % 10 === 0) {
console.log(`⏳ AI still responding... (${Math.round((Date.now() - startTime) / 1000)}s elapsed)`);
}
setTimeout(checkCompletion, 500);
}
};
// Start checking
console.log('🔄 Starting response check...');
checkCompletion();
// Set timeout
setTimeout(() => {
console.error(`❌ Response timeout after ${maxWaitTime/1000} seconds`);
reject(new Error('Response timeout'));
}, maxWaitTime);
});
}
function countCurrentImages() {
// Clear previous count and recount all images in the conversation
conversationImages.clear();
// Find all images in the conversation
const imageSelectors = [
'img[alt*="Generated"]',
'img[alt*="Image"]',
'[data-message-author-role="assistant"] img',
'.markdown img',
'img[src*="dalle"]',
'img[src*="oaiusercontent"]'
];
imageSelectors.forEach(selector => {
const images = document.querySelectorAll(selector);
images.forEach(img => {
if (img.src && !img.src.includes('avatar') && !img.src.includes('logo')) {
conversationImages.add(img.src);
}
});
});
console.log(`📸 Current image count: ${conversationImages.size}`);
}
async function waitForImageGeneration() {
return new Promise((resolve, reject) => {
const maxRetries = 10; // 10 retries = 1 minute total
const retryDelay = 6000; // 6 seconds between retries
let retryCount = 0;
const initialImageCount = conversationImages.size;
console.log(`🎨 Initial image count: ${initialImageCount}`);
const checkForNewImage = () => {
retryCount++;
// Count current images again
const previousCount = conversationImages.size;
countCurrentImages();
const currentCount = conversationImages.size;
console.log(`🔍 Image check ${retryCount}/${maxRetries}: ${currentCount} images (was ${previousCount})`);
if (currentCount > initialImageCount) {
console.log(`✅ New image detected! (${currentCount - initialImageCount} new)`);
resolve();
} else if (retryCount >= maxRetries) {
console.log(`⏱️ Image generation timeout after ${maxRetries} attempts`);
reject(new Error('Image generation timeout'));
} else {
console.log(`⏳ No new image yet, waiting ${retryDelay/1000}s before retry...`);
setTimeout(checkForNewImage, retryDelay);
}
};
// Start checking after a small initial delay
setTimeout(checkForNewImage, 2000);
});
}