-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpopup.js
245 lines (207 loc) · 6.82 KB
/
popup.js
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
let pageContent = '';
let settings = {
serverUrl: 'http://localhost:11434',
modelName: 'llama3.2'
};
let messageHistory = [];
let autoScroll = true;
document.addEventListener('DOMContentLoaded', () => {
// Initialize markdown-it
window.md = window.markdownit({
html: false,
breaks: true,
linkify: true
});
// Add this line to focus the input when popup opens
document.getElementById('user-input').focus();
// Load settings and initialize message history
chrome.storage.local.get(['serverUrl', 'modelName', 'messageHistory'], (result) => {
if (result.serverUrl) {
settings.serverUrl = result.serverUrl;
}
if (result.modelName) {
settings.modelName = result.modelName;
}
// Initialize message history only if it doesn't exist
messageHistory = [];
});
document.getElementById('send-button').addEventListener('click', sendMessage);
setupTextarea();
// Extract page content
chrome.tabs.query({ active: true, currentWindow: true }, async (tabs) => {
const tab = tabs[0];
try {
const results = await chrome.scripting.executeScript({
target: { tabId: tab.id },
function: () => ({
content: document.body.innerText.replace(/\s+/g, ' ').trim(),
title: document.title
})
});
pageContent = results[0].result.content;
const pageTitle = results[0].result.title;
appendMessage('System', `Connected to page: "${pageTitle}". You can now chat about its contents.`);
} catch (error) {
console.error('Error accessing page content:', error);
appendMessage('System', `Unable to access page content (${error.message}). This is normal for certain pages like chrome:// URLs.`);
pageContent = 'Page content not accessible';
}
});
// Add scroll event listener to chat container
const chatContainer = document.getElementById('chat-container');
chatContainer.addEventListener('scroll', () => {
const isAtBottom = chatContainer.scrollHeight - chatContainer.scrollTop <= chatContainer.clientHeight + 1;
autoScroll = isAtBottom;
});
// Add settings button handler
document.getElementById('settings-button').addEventListener('click', () => {
window.location.href = 'settings.html';
});
});
function setupTextarea() {
const textarea = document.getElementById('user-input');
const resizeTextarea = () => {
textarea.style.height = 'auto';
const maxHeight = 100;
const scrollHeight = Math.min(textarea.scrollHeight, maxHeight);
textarea.style.height = scrollHeight + 'px';
};
textarea.addEventListener('input', resizeTextarea);
textarea.addEventListener('keydown', (e) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
sendMessage();
}
});
}
function appendMessage(sender, content) {
const chatContainer = document.getElementById('chat-container');
const messageDiv = document.createElement('div');
messageDiv.className = `message ${sender.toLowerCase()}-message`;
if (sender === 'Assistant') {
messageDiv.innerHTML = window.md.render(content || '');
} else {
messageDiv.textContent = content;
}
chatContainer.appendChild(messageDiv);
if (autoScroll) {
chatContainer.scrollTop = chatContainer.scrollHeight;
}
if (sender !== 'System') {
messageHistory.push({
role: sender.toLowerCase(),
content: content
});
}
return messageDiv;
}
async function processStreamingResponse(response, messageDiv) {
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = '';
let accumulatedContent = '';
try {
while (true) {
const { value, done } = await reader.read();
if (done) break;
const chunk = decoder.decode(value, { stream: true });
buffer += chunk;
const lines = buffer.split('\n');
buffer = lines.pop() || '';
for (const line of lines) {
if (!line.trim()) continue;
try {
const data = JSON.parse(line);
if (data.message && data.message.content) {
if (messageDiv.textContent === 'Thinking...') {
messageDiv.textContent = '';
}
accumulatedContent += data.message.content;
messageDiv.innerHTML = window.md.render(accumulatedContent);
const chatContainer = document.getElementById('chat-container');
if (autoScroll) {
chatContainer.scrollTop = chatContainer.scrollHeight;
}
}
if (data.done) {
messageHistory.push({
role: 'assistant',
content: accumulatedContent
});
}
} catch (e) {
console.error('JSON Parse Error:', e.message, line);
}
}
}
if (buffer.trim()) {
try {
const data = JSON.parse(buffer);
if (data.message && data.message.content) {
accumulatedContent += data.message.content;
messageDiv.innerHTML = window.md.render(accumulatedContent);
}
} catch (e) {
console.error('Final Buffer Parse Error:', e.message);
}
}
return accumulatedContent;
} catch (error) {
console.error('Stream Processing Error:', error);
messageDiv.textContent = `Error: Failed to process response stream - ${error.message}`;
throw error;
}
}
async function sendMessage() {
const input = document.getElementById('user-input');
const message = input.value.trim();
if (!message) return;
input.disabled = true;
document.getElementById('send-button').disabled = true;
appendMessage('User', message);
input.value = '';
input.style.height = 'auto';
const messageDiv = document.createElement('div');
messageDiv.className = 'message assistant-message';
messageDiv.textContent = 'Thinking...';
document.getElementById('chat-container').appendChild(messageDiv);
try {
// Prepare messages array with system context for this request only
const messages = [
{
role: 'system',
content: 'You are a helpful AI assistant that analyzes web page content.'
},
{
role: 'system',
content: `Page content: ${pageContent}`
},
...messageHistory,
{
role: 'user',
content: message
}
];
const response = await fetch(`${settings.serverUrl}/api/chat`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
model: settings.modelName,
messages: messages,
stream: true
})
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
await processStreamingResponse(response, messageDiv);
} catch (error) {
messageDiv.textContent = `Error: ${error.message}`;
} finally {
input.disabled = false;
document.getElementById('send-button').disabled = false;
input.focus();
}
}