browser-assistant 2.8.25 → 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 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
- - Captures the visible browser tab for Groq vision analysis.
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. The policy includes a general HTTP/HTTPS fallback, so it is not a strict site allowlist.
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, generates and submits a solution, and returns to the list only after
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. Open `http://127.0.0.1:8000/practice`, then use the floating panel's Text Scan. Review the answer before trying automation with Start.
87
- 5. After changing extension files, reload it in the extensions page and refresh the practice tab.
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). They are hardcoded page listeners, not configurable Chrome extension commands.
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` by default and has **no authentication**. Keep it local. Its address is fixed in the extension.
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
- The manifest requests `activeTab`, `tabs`, `scripting`, and `clipboardWrite`, plus access to all URLs and localhost. Content scripts run on matching pages; scripting bridges supported page editors, tabs support capture and messaging, and clipboard access supports code copying. These are broad permissions; install only if you accept page access.
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 scans send extracted text and the current URL to the backend. Groq receives model prompts containing question text; vision scans capture the entire visible tab, compress the image, and send it to Groq. Sensitive content visible in a tab may therefore leave your machine. There is no screenshot redaction step. The application does not explicitly save raw screenshots to disk; request data exists in memory, and providers have their own retention policies.
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
- Successful scans are saved by the extension through `/history`: URL, timestamp, scan type, provider, language, and answer JSON are kept in `server/scan_history.db`, capped at 100 entries. Clear History deletes rows, not a forensic secure erase. Stop the backend and remove the database and its `-wal`/`-shm` companions for file-level removal; backups may still contain data. Panel position uses the page's localStorage, and automation resume state uses its sessionStorage. Clear site data to remove those settings. Minimal/stealth controls change presentation; they do not guarantee invisibility or privacy.
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
  }
@@ -45,30 +45,56 @@ async function checkWorkspaceUpdate() {
45
45
  }
46
46
  }
47
47
  async function attachUpdatedPanels() {
48
- const manifest = chrome.runtime.getManifest();
49
- const tabs = (await chrome.tabs.query({})).filter(tab => /^https?:\/\//.test(tab.url || ''));
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
- const existing = await chrome.scripting.executeScript({ target: { tabId: tab.id }, func: () => Boolean(document.getElementById('assistant-root')) });
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')
66
78
  return;
67
79
  void checkWorkspaceUpdate();
68
- void checkJournalReminder();
69
80
  void updateJournalBadge();
70
81
  });
71
- chrome.runtime.onInstalled.addListener(() => { void attachUpdatedPanels(); });
82
+ chrome.runtime.onInstalled.addListener(details => {
83
+ void attachUpdatedPanels();
84
+ if (details.reason === 'update')
85
+ void clearRetiredReminderSettings();
86
+ });
87
+ async function clearRetiredReminderSettings() {
88
+ try {
89
+ const storage = chrome.storage.local;
90
+ const keys = Object.keys(await storage.get()).filter(key => key === 'assistantJournalReminderConfig' || key.startsWith('assistantJournalReminder:'));
91
+ if (keys.length)
92
+ await storage.remove(keys);
93
+ }
94
+ catch (error) {
95
+ console.warn('Could not remove retired journal reminder settings.', error);
96
+ }
97
+ }
72
98
  let journalBadgeRevision = 0;
73
99
  function activeJournalTimers(data, now = Date.now()) {
74
100
  const prefix = 'assistantJournalTimer:';
@@ -111,85 +137,152 @@ chrome.storage?.local.onChanged?.addListener(changes => {
111
137
  }
112
138
  });
113
139
  void updateJournalBadge();
114
- let checkingJournalReminder = false;
115
- async function checkJournalReminder() {
116
- if (checkingJournalReminder)
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 });
117
148
  return;
118
- checkingJournalReminder = true;
149
+ }
150
+ let page;
119
151
  try {
120
- const storage = chrome.storage.local;
121
- const data = await storage.get();
122
- const config = data.assistantJournalReminderConfig;
123
- if (!config?.url || !config?.token)
124
- return;
125
- await Promise.all(activeJournalTimers(data).map(timer => sendJournalReminder(timer, config)));
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();
126
156
  }
127
- catch { /* The minute alarm keeps timer checks independent of workspace updates. */ }
128
- finally {
129
- checkingJournalReminder = false;
157
+ catch {
158
+ reply({ ok: false });
159
+ return;
130
160
  }
131
- }
132
- async function sendJournalReminder(timer, config) {
133
- try {
134
- const storage = chrome.storage.local;
135
- const remaining = timer.deadline - Date.now();
136
- // Give the portal time to confirm an existing submission at 30:00.
137
- if (remaining > (30 * 60 - 45) * 1000 || remaining <= 0)
138
- return;
139
- const stateKey = `assistantJournalReminder:${timer.path}`;
140
- const confirmationKey = `assistantJournalConfirmed:${timer.path}`;
141
- const previous = await storage.get([stateKey, confirmationKey]);
142
- if (previous[stateKey] || previous[confirmationKey])
143
- return;
144
- // Reserve the one attempt before the network call. A timed-out webhook
145
- // can still have sent a message, so replay would risk a duplicate.
146
- await storage.set({ [stateKey]: 'sending' });
147
- const latest = await storage.get();
148
- const current = activeJournalTimers(latest).find(candidate => candidate.path === timer.path);
149
- if (!current || Math.abs(current.deadline - timer.deadline) > 2000 ||
150
- latest.assistantJournalReminderConfig?.url !== config.url || latest.assistantJournalReminderConfig.token !== config.token) {
151
- await storage.remove(stateKey);
152
- return;
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 });
153
166
  }
154
- let result = 'failed';
155
- try {
156
- const response = await fetch(config.url, {
157
- method: 'POST', credentials: 'omit', redirect: 'error', signal: AbortSignal.timeout(15000),
158
- headers: { 'Content-Type': 'application/json', 'X-Journal-Reminder-Token': config.token },
159
- body: JSON.stringify({ event: 'journal_submission_unconfirmed' }),
160
- });
161
- if (response.ok)
162
- result = 'sent';
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 });
163
180
  }
164
- finally {
165
- await storage.set({ [stateKey]: result });
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 });
166
187
  }
167
- }
168
- catch { /* One failed request does not interrupt the other journals. */ }
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 }); });
169
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));
170
225
  chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
171
226
  if (!request || typeof request.action !== 'string') {
172
227
  sendResponse({ error: 'Invalid extension message' });
173
228
  return false;
174
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
+ }
175
266
  if (request.action === 'journalCountdowns' && sender.id === chrome.runtime.id) {
176
267
  chrome.storage.local.get().then(data => sendResponse(activeJournalTimers(data)))
177
268
  .catch(() => sendResponse([]));
178
269
  return true;
179
270
  }
180
271
  if (request.action === 'questionImage') {
181
- let url;
272
+ let url, source;
182
273
  try {
183
274
  url = new URL(request.url);
275
+ source = new URL(sender.url);
184
276
  }
185
277
  catch { }
186
278
  if (sender.id !== chrome.runtime.id || !sender.tab || !/^https?:/.test(sender.url || '')
187
- || !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) {
188
281
  sendResponse({ error: 'Question image access is not authorized.' });
189
282
  return false;
190
283
  }
191
284
  (async () => {
192
- 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) });
193
286
  if (!response.ok || !response.headers.get('content-type')?.startsWith('image/'))
194
287
  throw new Error('Question image download failed.');
195
288
  if (Number(response.headers.get('content-length')) > 10000000)
@@ -324,30 +417,39 @@ chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
324
417
  sendResponse({ error: 'Screenshot access is not authorized.' });
325
418
  return false;
326
419
  }
327
- // A tab can lose focus while capture is queued. Never capture another
328
- // tab/window and send that screenshot with the requesting page's URL.
329
- chrome.tabs.query({ active: true, windowId: sender.tab.windowId }).then(active => {
330
- if (active.length !== 1 || active[0].id !== sender.tab.id) {
331
- sendResponse({ error: 'The requesting tab is no longer active. Focus it and try Vision Scan again.' });
332
- return;
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;
333
428
  }
334
- chrome.tabs.captureVisibleTab(sender.tab.windowId, { format: "png" }, (dataUrl) => {
335
- if (chrome.runtime.lastError) {
336
- console.error("Capture failed:", chrome.runtime.lastError.message);
337
- sendResponse({ error: chrome.runtime.lastError.message });
338
- }
339
- else {
340
- sendResponse({ dataUrl: dataUrl });
341
- }
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
+ });
342
438
  });
343
- }).catch(() => sendResponse({ error: 'Could not verify the active screenshot tab.' }));
344
- return true; // Keep the message channel open for async response
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;
345
444
  }
346
445
  if (request.action === "apiRequest") {
347
446
  const allowedMethods = { '/health': ['GET'], '/solve': ['POST'], '/solve-vision': ['POST'],
348
- '/history': ['GET', 'POST', 'DELETE'], '/journal': ['POST'] };
447
+ '/history': ['GET', 'POST', 'DELETE'], '/journal': ['POST'], '/provider-status': ['POST'], '/jobs': ['POST'] };
349
448
  const method = request.method || 'POST';
350
- if (sender.id !== chrome.runtime.id || !allowedMethods[request.path]?.includes(method)) {
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) {
351
453
  sendResponse({ error: "Blocked API sender, path or method" });
352
454
  return false;
353
455
  }
@@ -364,13 +466,24 @@ chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
364
466
  const longRequest = ['/solve', '/solve-vision', '/journal'].includes(request.path);
365
467
  const keepAlive = longRequest && typeof chrome.runtime.getPlatformInfo === 'function'
366
468
  ? setInterval(() => chrome.runtime.getPlatformInfo(() => { void chrome.runtime.lastError; }), 25000) : null;
367
- fetch(`http://127.0.0.1:8000${request.path}`, {
368
- signal: AbortSignal.timeout(['/solve', '/solve-vision', '/journal'].includes(request.path) ? 360000 : 8000),
369
- method,
370
- headers: { "Content-Type": "application/json" },
371
- body,
372
- })
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
+ })()
373
482
  .then(async (response) => {
483
+ if (!('text' in response)) {
484
+ sendResponse(response);
485
+ return;
486
+ }
374
487
  const text = await response.text();
375
488
  let data;
376
489
  try {