browser-assistant 2.8.26 → 2.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +14 -11
- package/extension/answer-requests.js +33 -0
- package/extension/automation-policy.js +2 -1
- package/extension/background.js +191 -36
- package/extension/content.js +239 -101
- package/extension/editor-bridge.js +7 -11
- package/extension/journal-automation.js +102 -254
- package/extension/manifest.json +13 -4
- package/extension/popup.html +13 -2
- package/extension/popup.js +42 -0
- package/extension/question-visuals.js +80 -1
- package/extension/styles.css +7 -0
- package/package.json +5 -2
- package/server/.env.example +2 -0
- package/server/inference_jobs.py +90 -0
- package/server/journal.py +2 -1
- package/server/local_security.py +74 -1
- package/server/main.py +62 -7
package/README.md
CHANGED
|
@@ -5,14 +5,14 @@ A Chrome Manifest V3 extension with a local Python backend for exploring multipl
|
|
|
5
5
|
## What it does
|
|
6
6
|
|
|
7
7
|
- Extracts page text and requests answers from Groq, with Ollama fallback for text requests.
|
|
8
|
-
-
|
|
8
|
+
- Uses question illustrations for Groq vision where available and shows a crop and redaction preview before sending a tab screenshot.
|
|
9
9
|
- Detects requested programming languages and validates generated code syntax; model review does not prove correctness.
|
|
10
|
-
- Displays results in an in-page panel, offers code copying, and saves successful scans in local SQLite history.
|
|
10
|
+
- Displays results in an in-page panel, offers code copying, and optionally saves successful scans in local SQLite history.
|
|
11
11
|
- Includes a local practice page and automation for selecting answers, filling editors, and submitting supported forms after starting a run.
|
|
12
12
|
- Resumes CCBP practice from an already submitted answer through its submitted-question Next control, without generating or submitting that answer again. Delayed Submit controls are awaited for up to 15 seconds while the question and selected answer remain unchanged.
|
|
13
13
|
- Press **Alt + A** on the webpage to start automation, then press it again to pause or resume. The previous **Alt + Shift + A** shortcut also works. It also works with the code editor focused and opens QA Control. Journal automation uses the same toggle; its existing **Alt + Shift + J** shortcut remains available.
|
|
14
14
|
|
|
15
|
-
AI answers can be wrong. Automation can change or submit page content: use it only where authorized, review results, and avoid restricted assessments. Site detection is heuristic; custom controls, frames, editors, and navigation can fail.
|
|
15
|
+
AI answers can be wrong. Automation can change or submit page content: use it only where authorized, review results, and avoid restricted assessments. Site detection is heuristic; custom controls, frames, editors, and navigation can fail. Generic HTTP/HTTPS pages support manual scans after you choose **Open on this tab** in the toolbar popup.
|
|
16
16
|
|
|
17
17
|
## First run
|
|
18
18
|
|
|
@@ -21,7 +21,7 @@ AI answers can be wrong. Automation can change or submit page content: use it on
|
|
|
21
21
|
On CCBP `/problems-set`, start on page 1 and keep both **Not Attempted** and
|
|
22
22
|
**In Progress** visible in the status filters. Choose **QA Control → Start automation**.
|
|
23
23
|
The batch skips Solved rows, opens an eligible question, reads its language and
|
|
24
|
-
existing code,
|
|
24
|
+
existing code, asks for approval to apply and submit a generated solution, and returns to the list only after
|
|
25
25
|
a confirmed passing result. It follows numbered pages within the selected filters.
|
|
26
26
|
Keep the browser tab and local AI server open; Pause/Resume and Stop are available.
|
|
27
27
|
Failed tests, unsupported layouts, or unconfirmed results stop the batch with a reason.
|
|
@@ -83,20 +83,21 @@ For local text inference, install [Ollama](https://github.com/ollama/ollama), ru
|
|
|
83
83
|
1. Extract the extension ZIP from Releases. If using a clone or the source ZIP, run `npm ci` and `npm run build` from its root to prepare the `extension` folder.
|
|
84
84
|
2. Open `chrome://extensions`, enable **Developer mode**, choose **Load unpacked**, and select the prepared folder containing `manifest.json`.
|
|
85
85
|
3. Open `http://127.0.0.1:8000/health`. A JSON `status: "ok"` confirms the backend is running; it does not test model access.
|
|
86
|
-
4.
|
|
87
|
-
5.
|
|
86
|
+
4. Run the pairing command for your install in [setup](docs/SETUP.md). Paste the token into **Local server token** in the toolbar popup and click **Pair**.
|
|
87
|
+
5. Open `http://127.0.0.1:8000/practice`, then use the floating panel's Text Scan. Review the answer before trying automation with Start.
|
|
88
|
+
6. After changing extension files, reload it in the extensions page and refresh the practice tab.
|
|
88
89
|
|
|
89
|
-
The toolbar popup reports backend status. In-page shortcuts are backtick (open), `]` (close), `\` (vision scan), and `[` (minimal mode).
|
|
90
|
+
The toolbar popup reports backend status. In-page shortcuts are backtick (open), `]` (close), `\` (vision scan), and `[` (minimal mode). You can assign a browser-level automation shortcut at `chrome://extensions/shortcuts`.
|
|
90
91
|
|
|
91
92
|
## Data and permissions
|
|
92
93
|
|
|
93
|
-
The backend binds to `127.0.0.1:8000
|
|
94
|
+
The backend binds to `127.0.0.1:8000`. The extension sends a local pairing token on protected routes. Keep the server on loopback and store the token privately.
|
|
94
95
|
|
|
95
|
-
|
|
96
|
+
Chrome loads the panel automatically on CCBP Learning, Aurora and the bundled local server. The toolbar grants access to the active tab when you explicitly open the panel on another website. Editor integration is limited to supported pages.
|
|
96
97
|
|
|
97
|
-
Text
|
|
98
|
+
Text and image content used for a scan can reach the configured cloud provider. When a tab capture is needed, the preview supports redaction before upload. Review what is visible in the preview. Raw screenshots stay in memory on the local server. Provider retention follows the provider's terms.
|
|
98
99
|
|
|
99
|
-
|
|
100
|
+
History starts disabled. When enabled, SQLite stores the date, scan type, provider, language, answer JSON and URL without its query or fragment, up to 100 entries. Clear History deletes the rows. Extension-owned session storage keeps short-lived automation checkpoints. Page storage keeps panel placement.
|
|
100
101
|
|
|
101
102
|
## Development and Docker
|
|
102
103
|
|
|
@@ -105,6 +106,8 @@ From the repository root:
|
|
|
105
106
|
```bash
|
|
106
107
|
npm ci
|
|
107
108
|
npm test
|
|
109
|
+
npx playwright install chromium
|
|
110
|
+
npm run test:browser
|
|
108
111
|
python scripts/check_repo.py
|
|
109
112
|
```
|
|
110
113
|
|
|
@@ -64,3 +64,36 @@
|
|
|
64
64
|
}
|
|
65
65
|
window.BrowserAssistantAnswerRequests = Object.freeze({ run, failure, temporary });
|
|
66
66
|
})();
|
|
67
|
+
async function browserAssistantLocalInference(route, body, send, signal) {
|
|
68
|
+
const id = crypto.randomUUID();
|
|
69
|
+
const path = '/jobs/' + id;
|
|
70
|
+
const request = (path, method, body) => send({ action: 'apiRequest', path, method, body });
|
|
71
|
+
let finished = false;
|
|
72
|
+
try {
|
|
73
|
+
signal.throwIfAborted();
|
|
74
|
+
const started = await request('/jobs', 'POST', { id, route, body });
|
|
75
|
+
if (!started?.ok)
|
|
76
|
+
return started;
|
|
77
|
+
const deadline = Date.now() + 320000;
|
|
78
|
+
while (Date.now() < deadline) {
|
|
79
|
+
signal.throwIfAborted();
|
|
80
|
+
const response = await request(path, 'GET');
|
|
81
|
+
signal.throwIfAborted();
|
|
82
|
+
if (!response?.ok)
|
|
83
|
+
return response;
|
|
84
|
+
const result = response.data;
|
|
85
|
+
if (result.state === 'finished') {
|
|
86
|
+
finished = true;
|
|
87
|
+
return { ok: result.status === 200, status: result.status, data: result.data };
|
|
88
|
+
}
|
|
89
|
+
if (result.state !== 'running')
|
|
90
|
+
throw Error('Local server returned an invalid inference status.');
|
|
91
|
+
await new Promise(resolve => setTimeout(resolve, 750));
|
|
92
|
+
}
|
|
93
|
+
return { ok: false, status: 504, data: { detail: 'The inference deadline expired.' } };
|
|
94
|
+
}
|
|
95
|
+
finally {
|
|
96
|
+
if (!finished)
|
|
97
|
+
void request(path, 'DELETE').catch(() => { });
|
|
98
|
+
}
|
|
99
|
+
}
|
|
@@ -55,6 +55,7 @@
|
|
|
55
55
|
id: `website:${origin}`,
|
|
56
56
|
origins: [origin],
|
|
57
57
|
adapter: 'semantic-mcq',
|
|
58
|
+
assistOnly: true,
|
|
58
59
|
pageTypes: ['practice', 'quiz', 'code'],
|
|
59
60
|
capabilities: { detect: true, read: true, fill: true, select: true, click: true, navigate: true, validate: true, submit: true },
|
|
60
61
|
};
|
|
@@ -64,7 +65,7 @@
|
|
|
64
65
|
return 'ASSIST';
|
|
65
66
|
if (context.target?.restricted)
|
|
66
67
|
return 'DISABLED';
|
|
67
|
-
if (!context.target?.authorized || !context.page?.authorized)
|
|
68
|
+
if (context.target?.assistOnly || !context.target?.authorized || !context.page?.authorized)
|
|
68
69
|
return 'ASSIST';
|
|
69
70
|
return 'FULL';
|
|
70
71
|
}
|
package/extension/background.js
CHANGED
|
@@ -45,21 +45,33 @@ async function checkWorkspaceUpdate() {
|
|
|
45
45
|
}
|
|
46
46
|
}
|
|
47
47
|
async function attachUpdatedPanels() {
|
|
48
|
-
const
|
|
49
|
-
|
|
48
|
+
const tabs = await chrome.tabs.query({ url: [
|
|
49
|
+
'https://learning.ccbp.in/*', 'https://admissions.aurora.edu.in/*', 'http://127.0.0.1:8000/*',
|
|
50
|
+
] });
|
|
50
51
|
for (const tab of tabs) {
|
|
51
52
|
try {
|
|
52
|
-
|
|
53
|
-
if (existing[0]?.result)
|
|
54
|
-
continue;
|
|
55
|
-
for (const group of manifest.content_scripts) {
|
|
56
|
-
await chrome.scripting.insertCSS({ target: { tabId: tab.id }, files: group.css || [] });
|
|
57
|
-
await chrome.scripting.executeScript({ target: { tabId: tab.id }, files: group.js });
|
|
58
|
-
}
|
|
53
|
+
await attachAssistantPanel(tab.id);
|
|
59
54
|
}
|
|
60
55
|
catch { /* Chrome may restrict particular sites; leave them alone. */ }
|
|
61
56
|
}
|
|
62
57
|
}
|
|
58
|
+
async function attachAssistantPanel(tabId) {
|
|
59
|
+
const target = { tabId };
|
|
60
|
+
const existing = await chrome.scripting.executeScript({ target, func: () => Boolean(document.getElementById('assistant-root')) });
|
|
61
|
+
if (existing[0]?.result)
|
|
62
|
+
return;
|
|
63
|
+
for (const group of chrome.runtime.getManifest().content_scripts || []) {
|
|
64
|
+
if (group.css?.length)
|
|
65
|
+
await chrome.scripting.insertCSS({ target, files: group.css });
|
|
66
|
+
if (group.js?.length)
|
|
67
|
+
await chrome.scripting.executeScript({ target, files: group.js });
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
chrome.commands?.onCommand.addListener((command, tab) => {
|
|
71
|
+
if (command === 'toggle-automation' && tab?.id) {
|
|
72
|
+
void chrome.tabs.sendMessage(tab.id, { action: 'assistantToggleAutomation' }).catch(() => { });
|
|
73
|
+
}
|
|
74
|
+
});
|
|
63
75
|
chrome.alarms.create('assistant-workspace-update', { periodInMinutes: 1 });
|
|
64
76
|
chrome.alarms.onAlarm.addListener(alarm => {
|
|
65
77
|
if (alarm.name !== 'assistant-workspace-update')
|
|
@@ -125,29 +137,152 @@ chrome.storage?.local.onChanged?.addListener(changes => {
|
|
|
125
137
|
}
|
|
126
138
|
});
|
|
127
139
|
void updateJournalBadge();
|
|
140
|
+
// Serialize saves and consumes so a new document cannot replay a checkpoint
|
|
141
|
+
// and Stop cannot race a pending save. Page storage is never read here.
|
|
142
|
+
let checkpointQueue = Promise.resolve();
|
|
143
|
+
function handleAutomationCheckpoint(request, sender, reply) {
|
|
144
|
+
const storage = chrome.storage?.session;
|
|
145
|
+
if (!storage || sender.id !== chrome.runtime.id || !Number.isInteger(sender.tab?.id)
|
|
146
|
+
|| sender.frameId !== 0 || !sender.documentId || !['practice', 'coding'].includes(request.checkpointKind)) {
|
|
147
|
+
reply({ ok: false });
|
|
148
|
+
return;
|
|
149
|
+
}
|
|
150
|
+
let page;
|
|
151
|
+
try {
|
|
152
|
+
const source = new URL(sender.url);
|
|
153
|
+
page = new URL(sender.tab.url || sender.url);
|
|
154
|
+
if (page.origin !== source.origin || !['https://learning.ccbp.in', 'http://127.0.0.1:8000'].includes(page.origin))
|
|
155
|
+
throw Error();
|
|
156
|
+
}
|
|
157
|
+
catch {
|
|
158
|
+
reply({ ok: false });
|
|
159
|
+
return;
|
|
160
|
+
}
|
|
161
|
+
const key = `assistantCheckpoint:${sender.tab.id}:${request.checkpointKind}`;
|
|
162
|
+
checkpointQueue = checkpointQueue.then(async () => {
|
|
163
|
+
if (request.action === 'clearCheckpoint') {
|
|
164
|
+
await storage.remove(key);
|
|
165
|
+
return reply({ ok: true });
|
|
166
|
+
}
|
|
167
|
+
if (request.action === 'saveCheckpoint') {
|
|
168
|
+
const checkpoint = request.checkpoint;
|
|
169
|
+
if (!checkpoint || checkpoint.kind !== request.checkpointKind || JSON.stringify(checkpoint).length > 120000)
|
|
170
|
+
return reply({ ok: false });
|
|
171
|
+
let path;
|
|
172
|
+
if (checkpoint.expectedUrl) {
|
|
173
|
+
const target = new URL(checkpoint.expectedUrl, page);
|
|
174
|
+
if (target.origin !== page.origin)
|
|
175
|
+
return reply({ ok: false });
|
|
176
|
+
path = target.pathname;
|
|
177
|
+
}
|
|
178
|
+
await storage.set({ [key]: { origin: page.origin, path, documentId: sender.documentId, expires: Date.now() + 120000, value: checkpoint.value } });
|
|
179
|
+
return reply({ ok: true });
|
|
180
|
+
}
|
|
181
|
+
const record = (await storage.get(key))[key];
|
|
182
|
+
if (!record)
|
|
183
|
+
return reply({ ok: true });
|
|
184
|
+
if (record.expires <= Date.now() || record.origin !== page.origin) {
|
|
185
|
+
await storage.remove(key);
|
|
186
|
+
return reply({ ok: true });
|
|
187
|
+
}
|
|
188
|
+
if (record.path ? record.path !== page.pathname : record.documentId !== sender.documentId)
|
|
189
|
+
return reply({ ok: true });
|
|
190
|
+
await storage.remove(key);
|
|
191
|
+
reply({ ok: true, checkpoint: record.value });
|
|
192
|
+
}).catch(() => { reply({ ok: false }); });
|
|
193
|
+
}
|
|
194
|
+
const LOCAL_API = 'http://127.0.0.1:8000';
|
|
195
|
+
let pairingDatabase;
|
|
196
|
+
function localPairing(token) {
|
|
197
|
+
pairingDatabase ??= new Promise((resolve, reject) => {
|
|
198
|
+
const request = indexedDB.open('assistant-local-settings', 1);
|
|
199
|
+
request.onupgradeneeded = () => request.result.createObjectStore('settings');
|
|
200
|
+
request.onsuccess = () => resolve(request.result);
|
|
201
|
+
request.onerror = () => reject(request.error);
|
|
202
|
+
}).catch(error => { pairingDatabase = undefined; throw error; });
|
|
203
|
+
return pairingDatabase.then(database => new Promise((resolve, reject) => {
|
|
204
|
+
const transaction = database.transaction('settings', token === undefined ? 'readonly' : 'readwrite');
|
|
205
|
+
const store = transaction.objectStore('settings');
|
|
206
|
+
const request = token === undefined ? store.get('pairing') : token ? store.put(token, 'pairing') : store.delete('pairing');
|
|
207
|
+
transaction.oncomplete = () => resolve(token ?? request.result ?? '');
|
|
208
|
+
transaction.onabort = () => reject(transaction.error);
|
|
209
|
+
}));
|
|
210
|
+
}
|
|
211
|
+
function isAssistantPopup(sender) {
|
|
212
|
+
const popup = chrome.runtime.getURL('popup.html');
|
|
213
|
+
return sender.id === chrome.runtime.id && sender.url?.split('#', 1)[0] === popup;
|
|
214
|
+
}
|
|
215
|
+
const tabCaptureEpoch = new Map();
|
|
216
|
+
function invalidateCapture(windowId) {
|
|
217
|
+
tabCaptureEpoch.set(windowId, (tabCaptureEpoch.get(windowId) || 0) + 1);
|
|
218
|
+
}
|
|
219
|
+
chrome.tabs?.onActivated?.addListener(info => invalidateCapture(info.windowId));
|
|
220
|
+
chrome.tabs?.onUpdated?.addListener((_id, change, tab) => {
|
|
221
|
+
if (tab.active && (change.url || change.status === 'loading'))
|
|
222
|
+
invalidateCapture(tab.windowId);
|
|
223
|
+
});
|
|
224
|
+
chrome.windows?.onRemoved?.addListener(id => tabCaptureEpoch.delete(id));
|
|
128
225
|
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
|
|
129
226
|
if (!request || typeof request.action !== 'string') {
|
|
130
227
|
sendResponse({ error: 'Invalid extension message' });
|
|
131
228
|
return false;
|
|
132
229
|
}
|
|
230
|
+
if (['saveCheckpoint', 'takeCheckpoint', 'clearCheckpoint'].includes(request.action)) {
|
|
231
|
+
handleAutomationCheckpoint(request, sender, sendResponse);
|
|
232
|
+
return true;
|
|
233
|
+
}
|
|
234
|
+
if (['pairLocalServer', 'unpairLocalServer', 'pairingStatus', 'openAssistantOnTab'].includes(request.action)) {
|
|
235
|
+
if (!isAssistantPopup(sender)) {
|
|
236
|
+
sendResponse({ ok: false, error: 'Open the Browser Assistant toolbar popup.' });
|
|
237
|
+
return false;
|
|
238
|
+
}
|
|
239
|
+
(async () => {
|
|
240
|
+
if (request.action === 'openAssistantOnTab') {
|
|
241
|
+
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
|
|
242
|
+
if (!tab?.id || !/^https?:\/\//.test(tab.url || ''))
|
|
243
|
+
throw Error('Open an HTTP or HTTPS page first.');
|
|
244
|
+
await attachAssistantPanel(tab.id);
|
|
245
|
+
await chrome.tabs.sendMessage(tab.id, { action: 'assistantShowPanel' });
|
|
246
|
+
return { ok: true };
|
|
247
|
+
}
|
|
248
|
+
if (request.action === 'pairingStatus')
|
|
249
|
+
return { ok: true, paired: Boolean(await localPairing()) };
|
|
250
|
+
if (request.action === 'unpairLocalServer') {
|
|
251
|
+
await localPairing('');
|
|
252
|
+
return { ok: true };
|
|
253
|
+
}
|
|
254
|
+
if (!/^[A-Za-z0-9_-]{32,128}$/.test(request.token || ''))
|
|
255
|
+
throw Error('Enter the pairing token shown by your local server.');
|
|
256
|
+
const response = await fetch(LOCAL_API + '/history?limit=1', {
|
|
257
|
+
headers: { 'X-Assistant-Token': request.token }, signal: AbortSignal.timeout(4000), redirect: 'error', cache: 'no-store',
|
|
258
|
+
});
|
|
259
|
+
if (!response.ok)
|
|
260
|
+
throw Error(response.status === 401 ? 'The local server rejected the token.' : 'Could not verify local server pairing.');
|
|
261
|
+
await localPairing(request.token);
|
|
262
|
+
return { ok: true, paired: true };
|
|
263
|
+
})().then(sendResponse).catch(error => sendResponse({ ok: false, error: error.message }));
|
|
264
|
+
return true;
|
|
265
|
+
}
|
|
133
266
|
if (request.action === 'journalCountdowns' && sender.id === chrome.runtime.id) {
|
|
134
267
|
chrome.storage.local.get().then(data => sendResponse(activeJournalTimers(data)))
|
|
135
268
|
.catch(() => sendResponse([]));
|
|
136
269
|
return true;
|
|
137
270
|
}
|
|
138
271
|
if (request.action === 'questionImage') {
|
|
139
|
-
let url;
|
|
272
|
+
let url, source;
|
|
140
273
|
try {
|
|
141
274
|
url = new URL(request.url);
|
|
275
|
+
source = new URL(sender.url);
|
|
142
276
|
}
|
|
143
277
|
catch { }
|
|
144
278
|
if (sender.id !== chrome.runtime.id || !sender.tab || !/^https?:/.test(sender.url || '')
|
|
145
|
-
|| !url || !['https:', 'http:'].includes(url.protocol) || url.username || url.password
|
|
279
|
+
|| !url || !['https:', 'http:'].includes(url.protocol) || url.username || url.password
|
|
280
|
+
|| !source || url.origin !== source.origin) {
|
|
146
281
|
sendResponse({ error: 'Question image access is not authorized.' });
|
|
147
282
|
return false;
|
|
148
283
|
}
|
|
149
284
|
(async () => {
|
|
150
|
-
const response = await fetch(url.href, { credentials: 'omit', signal: AbortSignal.timeout(10000) });
|
|
285
|
+
const response = await fetch(url.href, { credentials: 'omit', redirect: 'error', signal: AbortSignal.timeout(10000) });
|
|
151
286
|
if (!response.ok || !response.headers.get('content-type')?.startsWith('image/'))
|
|
152
287
|
throw new Error('Question image download failed.');
|
|
153
288
|
if (Number(response.headers.get('content-length')) > 10000000)
|
|
@@ -282,30 +417,39 @@ chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
|
|
|
282
417
|
sendResponse({ error: 'Screenshot access is not authorized.' });
|
|
283
418
|
return false;
|
|
284
419
|
}
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
420
|
+
(async () => {
|
|
421
|
+
const windowId = sender.tab.windowId;
|
|
422
|
+
const epoch = tabCaptureEpoch.get(windowId);
|
|
423
|
+
const expectedUrl = request.url || sender.tab.url || sender.url;
|
|
424
|
+
async function current() {
|
|
425
|
+
const tabs = await chrome.tabs.query({ active: true, windowId });
|
|
426
|
+
return tabs.length === 1 && tabs[0].id === sender.tab.id
|
|
427
|
+
&& tabs[0].url === expectedUrl && tabCaptureEpoch.get(windowId) === epoch;
|
|
291
428
|
}
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
429
|
+
if (!(await current()))
|
|
430
|
+
throw Error('The requesting tab is no longer active. Focus it and try Vision Scan again.');
|
|
431
|
+
const dataUrl = await new Promise((resolve, reject) => {
|
|
432
|
+
chrome.tabs.captureVisibleTab(windowId, { format: 'png' }, value => {
|
|
433
|
+
if (chrome.runtime.lastError || !value)
|
|
434
|
+
reject(Error('Open the extension toolbar on this tab to allow screenshot capture.'));
|
|
435
|
+
else
|
|
436
|
+
resolve(value);
|
|
437
|
+
});
|
|
300
438
|
});
|
|
301
|
-
|
|
302
|
-
|
|
439
|
+
if (!(await current()))
|
|
440
|
+
throw Error('The tab changed during capture. Try Vision Scan again.');
|
|
441
|
+
return { dataUrl };
|
|
442
|
+
})().then(sendResponse).catch(error => sendResponse({ error: error.message }));
|
|
443
|
+
return true;
|
|
303
444
|
}
|
|
304
445
|
if (request.action === "apiRequest") {
|
|
305
446
|
const allowedMethods = { '/health': ['GET'], '/solve': ['POST'], '/solve-vision': ['POST'],
|
|
306
|
-
'/history': ['GET', 'POST', 'DELETE'], '/journal': ['POST'] };
|
|
447
|
+
'/history': ['GET', 'POST', 'DELETE'], '/journal': ['POST'], '/provider-status': ['POST'], '/jobs': ['POST'] };
|
|
307
448
|
const method = request.method || 'POST';
|
|
308
|
-
|
|
449
|
+
const permitted = Object.hasOwn(allowedMethods, request.path)
|
|
450
|
+
? allowedMethods[request.path].includes(method)
|
|
451
|
+
: /^\/jobs\/[a-f\d]{8}(?:-[a-f\d]{4}){3}-[a-f\d]{12}$/i.test(request.path || '') && ['GET', 'DELETE'].includes(method);
|
|
452
|
+
if (sender.id !== chrome.runtime.id || !permitted) {
|
|
309
453
|
sendResponse({ error: "Blocked API sender, path or method" });
|
|
310
454
|
return false;
|
|
311
455
|
}
|
|
@@ -322,13 +466,24 @@ chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
|
|
|
322
466
|
const longRequest = ['/solve', '/solve-vision', '/journal'].includes(request.path);
|
|
323
467
|
const keepAlive = longRequest && typeof chrome.runtime.getPlatformInfo === 'function'
|
|
324
468
|
? setInterval(() => chrome.runtime.getPlatformInfo(() => { void chrome.runtime.lastError; }), 25000) : null;
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
469
|
+
(async () => {
|
|
470
|
+
const headers = { "Content-Type": "application/json" };
|
|
471
|
+
if (request.path !== '/health') {
|
|
472
|
+
const token = await localPairing();
|
|
473
|
+
if (!token)
|
|
474
|
+
return { status: 401, ok: false, data: { detail: 'Pair the local server in the Browser Assistant toolbar popup.' } };
|
|
475
|
+
headers['X-Assistant-Token'] = token;
|
|
476
|
+
}
|
|
477
|
+
return fetch(`${LOCAL_API}${request.path}`, {
|
|
478
|
+
signal: AbortSignal.timeout(longRequest ? 360000 : 12000),
|
|
479
|
+
method, headers, body, redirect: 'error', cache: 'no-store',
|
|
480
|
+
});
|
|
481
|
+
})()
|
|
331
482
|
.then(async (response) => {
|
|
483
|
+
if (!('text' in response)) {
|
|
484
|
+
sendResponse(response);
|
|
485
|
+
return;
|
|
486
|
+
}
|
|
332
487
|
const text = await response.text();
|
|
333
488
|
let data;
|
|
334
489
|
try {
|