-
Notifications
You must be signed in to change notification settings - Fork 44
Expand file tree
/
Copy pathbackground.js
More file actions
191 lines (159 loc) · 5.53 KB
/
background.js
File metadata and controls
191 lines (159 loc) · 5.53 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
// AI Panel - Background Service Worker
// URL patterns for each AI
const AI_URL_PATTERNS = {
claude: ['claude.ai'],
chatgpt: ['chat.openai.com', 'chatgpt.com'],
gemini: ['gemini.google.com']
};
// Store latest responses using chrome.storage.session (persists across service worker restarts)
async function getStoredResponses() {
const result = await chrome.storage.session.get('latestResponses');
return result.latestResponses || { claude: null, chatgpt: null, gemini: null };
}
async function setStoredResponse(aiType, content) {
const responses = await getStoredResponses();
responses[aiType] = content;
await chrome.storage.session.set({ latestResponses: responses });
}
// Open side panel when extension icon is clicked
chrome.action.onClicked.addListener((tab) => {
chrome.sidePanel.open({ windowId: tab.windowId });
});
// Set side panel behavior
chrome.sidePanel.setPanelBehavior({ openPanelOnActionClick: true });
// Listen for messages from side panel and content scripts
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
handleMessage(message, sender).then(sendResponse);
return true; // Keep channel open for async response
});
async function handleMessage(message, sender) {
switch (message.type) {
case 'SEND_MESSAGE':
return await sendMessageToAI(message.aiType, message.message);
case 'SEND_FILES':
return await sendFilesToAI(message.aiType, message.files);
case 'GET_RESPONSE':
// Query content script directly for real-time response (not from storage)
return await getResponseFromContentScript(message.aiType);
case 'RESPONSE_CAPTURED':
// Content script captured a response
await setStoredResponse(message.aiType, message.content);
// Forward to side panel (include content for discussion mode)
notifySidePanel('RESPONSE_CAPTURED', { aiType: message.aiType, content: message.content });
return { success: true };
case 'CONTENT_SCRIPT_READY':
// Content script loaded and ready
const aiType = getAITypeFromUrl(sender.tab?.url);
if (aiType) {
notifySidePanel('TAB_STATUS_UPDATE', { aiType, connected: true });
}
return { success: true };
default:
return { error: 'Unknown message type' };
}
}
async function getResponseFromContentScript(aiType) {
try {
const tab = await findAITab(aiType);
if (!tab) {
// Fallback to stored response if tab not found
const responses = await getStoredResponses();
return { content: responses[aiType] };
}
// Query content script for real-time DOM content
const response = await chrome.tabs.sendMessage(tab.id, {
type: 'GET_LATEST_RESPONSE'
});
return { content: response?.content || null };
} catch (err) {
// Fallback to stored response on error
console.log('[AI Panel] Failed to get response from content script:', err.message);
const responses = await getStoredResponses();
return { content: responses[aiType] };
}
}
async function sendMessageToAI(aiType, message) {
try {
// Find the tab for this AI
const tab = await findAITab(aiType);
if (!tab) {
return { success: false, error: `No ${aiType} tab found` };
}
// Send message to content script
const response = await chrome.tabs.sendMessage(tab.id, {
type: 'INJECT_MESSAGE',
message
});
// Notify side panel
notifySidePanel('SEND_RESULT', {
aiType,
success: response?.success,
error: response?.error
});
return response;
} catch (err) {
return { success: false, error: err.message };
}
}
async function sendFilesToAI(aiType, files) {
console.log('[AI Panel] Background: sendFilesToAI called for', aiType, 'files:', files?.length);
try {
const tab = await findAITab(aiType);
if (!tab) {
console.log('[AI Panel] Background: No tab found for', aiType);
return { success: false, error: `No ${aiType} tab found` };
}
console.log('[AI Panel] Background: Sending INJECT_FILES to tab', tab.id);
// Send files to content script
const response = await chrome.tabs.sendMessage(tab.id, {
type: 'INJECT_FILES',
files
});
console.log('[AI Panel] Background: Response from content script:', response);
return response;
} catch (err) {
console.log('[AI Panel] Background: sendFilesToAI error:', err.message);
return { success: false, error: err.message };
}
}
async function findAITab(aiType) {
const patterns = AI_URL_PATTERNS[aiType];
if (!patterns) return null;
const tabs = await chrome.tabs.query({});
for (const tab of tabs) {
if (tab.url && patterns.some(p => tab.url.includes(p))) {
return tab;
}
}
return null;
}
function getAITypeFromUrl(url) {
if (!url) return null;
for (const [aiType, patterns] of Object.entries(AI_URL_PATTERNS)) {
if (patterns.some(p => url.includes(p))) {
return aiType;
}
}
return null;
}
async function notifySidePanel(type, data) {
try {
await chrome.runtime.sendMessage({ type, ...data });
} catch (err) {
// Side panel might not be open, ignore
}
}
// Track tab updates
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
if (changeInfo.status === 'complete' && tab.url) {
const aiType = getAITypeFromUrl(tab.url);
if (aiType) {
notifySidePanel('TAB_STATUS_UPDATE', { aiType, connected: true });
}
}
});
// Track tab closures
chrome.tabs.onRemoved.addListener((tabId) => {
// We'd need to track which tabs were AI tabs to notify properly
// For now, side panel will re-check on next action
});