browser-assistant 2.9.0 → 2.9.1

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
- - Uses question illustrations for Groq vision where available and shows a crop and redaction preview before sending a tab screenshot.
8
+ - Captures the visible browser tab for Groq vision analysis.
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 optionally saves successful scans in local SQLite history.
10
+ - Displays results in an in-page panel, offers code copying, and 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. Generic HTTP/HTTPS pages support manual scans after you choose **Open on this tab** in the toolbar popup.
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.
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, asks for approval to apply and submit a generated solution, and returns to the list only after
24
+ existing code, generates and submits a 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,21 +83,20 @@ 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. 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.
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.
89
88
 
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`.
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.
91
90
 
92
91
  ## Data and permissions
93
92
 
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.
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.
95
94
 
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.
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.
97
96
 
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.
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.
99
98
 
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.
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.
101
100
 
102
101
  ## Development and Docker
103
102
 
@@ -106,8 +105,6 @@ From the repository root:
106
105
  ```bash
107
106
  npm ci
108
107
  npm test
109
- npx playwright install chromium
110
- npm run test:browser
111
108
  python scripts/check_repo.py
112
109
  ```
113
110
 
@@ -64,36 +64,3 @@
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,7 +55,6 @@
55
55
  id: `website:${origin}`,
56
56
  origins: [origin],
57
57
  adapter: 'semantic-mcq',
58
- assistOnly: true,
59
58
  pageTypes: ['practice', 'quiz', 'code'],
60
59
  capabilities: { detect: true, read: true, fill: true, select: true, click: true, navigate: true, validate: true, submit: true },
61
60
  };
@@ -65,7 +64,7 @@
65
64
  return 'ASSIST';
66
65
  if (context.target?.restricted)
67
66
  return 'DISABLED';
68
- if (context.target?.assistOnly || !context.target?.authorized || !context.page?.authorized)
67
+ if (!context.target?.authorized || !context.page?.authorized)
69
68
  return 'ASSIST';
70
69
  return 'FULL';
71
70
  }
@@ -45,33 +45,21 @@ async function checkWorkspaceUpdate() {
45
45
  }
46
46
  }
47
47
  async function attachUpdatedPanels() {
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
- ] });
48
+ const manifest = chrome.runtime.getManifest();
49
+ const tabs = (await chrome.tabs.query({})).filter(tab => /^https?:\/\//.test(tab.url || ''));
51
50
  for (const tab of tabs) {
52
51
  try {
53
- await attachAssistantPanel(tab.id);
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
+ }
54
59
  }
55
60
  catch { /* Chrome may restrict particular sites; leave them alone. */ }
56
61
  }
57
62
  }
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
- });
75
63
  chrome.alarms.create('assistant-workspace-update', { periodInMinutes: 1 });
76
64
  chrome.alarms.onAlarm.addListener(alarm => {
77
65
  if (alarm.name !== 'assistant-workspace-update')
@@ -137,152 +125,29 @@ chrome.storage?.local.onChanged?.addListener(changes => {
137
125
  }
138
126
  });
139
127
  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));
225
128
  chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
226
129
  if (!request || typeof request.action !== 'string') {
227
130
  sendResponse({ error: 'Invalid extension message' });
228
131
  return false;
229
132
  }
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
- }
266
133
  if (request.action === 'journalCountdowns' && sender.id === chrome.runtime.id) {
267
134
  chrome.storage.local.get().then(data => sendResponse(activeJournalTimers(data)))
268
135
  .catch(() => sendResponse([]));
269
136
  return true;
270
137
  }
271
138
  if (request.action === 'questionImage') {
272
- let url, source;
139
+ let url;
273
140
  try {
274
141
  url = new URL(request.url);
275
- source = new URL(sender.url);
276
142
  }
277
143
  catch { }
278
144
  if (sender.id !== chrome.runtime.id || !sender.tab || !/^https?:/.test(sender.url || '')
279
- || !url || !['https:', 'http:'].includes(url.protocol) || url.username || url.password
280
- || !source || url.origin !== source.origin) {
145
+ || !url || !['https:', 'http:'].includes(url.protocol) || url.username || url.password) {
281
146
  sendResponse({ error: 'Question image access is not authorized.' });
282
147
  return false;
283
148
  }
284
149
  (async () => {
285
- const response = await fetch(url.href, { credentials: 'omit', redirect: 'error', signal: AbortSignal.timeout(10000) });
150
+ const response = await fetch(url.href, { credentials: 'omit', signal: AbortSignal.timeout(10000) });
286
151
  if (!response.ok || !response.headers.get('content-type')?.startsWith('image/'))
287
152
  throw new Error('Question image download failed.');
288
153
  if (Number(response.headers.get('content-length')) > 10000000)
@@ -417,39 +282,30 @@ chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
417
282
  sendResponse({ error: 'Screenshot access is not authorized.' });
418
283
  return false;
419
284
  }
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;
285
+ // A tab can lose focus while capture is queued. Never capture another
286
+ // tab/window and send that screenshot with the requesting page's URL.
287
+ chrome.tabs.query({ active: true, windowId: sender.tab.windowId }).then(active => {
288
+ if (active.length !== 1 || active[0].id !== sender.tab.id) {
289
+ sendResponse({ error: 'The requesting tab is no longer active. Focus it and try Vision Scan again.' });
290
+ return;
428
291
  }
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
- });
292
+ chrome.tabs.captureVisibleTab(sender.tab.windowId, { format: "png" }, (dataUrl) => {
293
+ if (chrome.runtime.lastError) {
294
+ console.error("Capture failed:", chrome.runtime.lastError.message);
295
+ sendResponse({ error: chrome.runtime.lastError.message });
296
+ }
297
+ else {
298
+ sendResponse({ dataUrl: dataUrl });
299
+ }
438
300
  });
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;
301
+ }).catch(() => sendResponse({ error: 'Could not verify the active screenshot tab.' }));
302
+ return true; // Keep the message channel open for async response
444
303
  }
445
304
  if (request.action === "apiRequest") {
446
305
  const allowedMethods = { '/health': ['GET'], '/solve': ['POST'], '/solve-vision': ['POST'],
447
- '/history': ['GET', 'POST', 'DELETE'], '/journal': ['POST'], '/provider-status': ['POST'], '/jobs': ['POST'] };
306
+ '/history': ['GET', 'POST', 'DELETE'], '/journal': ['POST'] };
448
307
  const method = request.method || 'POST';
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) {
308
+ if (sender.id !== chrome.runtime.id || !allowedMethods[request.path]?.includes(method)) {
453
309
  sendResponse({ error: "Blocked API sender, path or method" });
454
310
  return false;
455
311
  }
@@ -466,24 +322,13 @@ chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
466
322
  const longRequest = ['/solve', '/solve-vision', '/journal'].includes(request.path);
467
323
  const keepAlive = longRequest && typeof chrome.runtime.getPlatformInfo === 'function'
468
324
  ? setInterval(() => chrome.runtime.getPlatformInfo(() => { void chrome.runtime.lastError; }), 25000) : null;
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
- })()
325
+ fetch(`http://127.0.0.1:8000${request.path}`, {
326
+ signal: AbortSignal.timeout(['/solve', '/solve-vision', '/journal'].includes(request.path) ? 360000 : 8000),
327
+ method,
328
+ headers: { "Content-Type": "application/json" },
329
+ body,
330
+ })
482
331
  .then(async (response) => {
483
- if (!('text' in response)) {
484
- sendResponse(response);
485
- return;
486
- }
487
332
  const text = await response.text();
488
333
  let data;
489
334
  try {