browser-assistant 2.9.37 → 2.9.39

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.
@@ -3,6 +3,45 @@
3
3
  const visible = node => node.getClientRects().length && !node.closest('#assistant-root');
4
4
  const text = node => (node.innerText || node.textContent || '').replace(/\s+/g, ' ').trim();
5
5
  const statusPattern = /^(not attempted|in progress|solved)$/i;
6
+ function openControl(row) {
7
+ const enabled = node => visible(node) && !node.closest('[disabled],[aria-disabled="true"]');
8
+ const label = node => [node.getAttribute('aria-label'), node.getAttribute('title'),
9
+ node.getAttribute('data-testid'), text(node)].filter(Boolean).join(' ');
10
+ const bookmark = node => /bookmark|save|favourite|favorite/i.test(label(node));
11
+ const links = [...row.querySelectorAll('a[href*="/question/"]')].filter(enabled);
12
+ if (links.length === 1)
13
+ return links[0];
14
+ const controls = [...row.querySelectorAll('a[href],button,[role="button"]')].filter(enabled).filter(node => !bookmark(node));
15
+ const named = controls.filter(node => /\b(open|view|start|go to)\b|arrow.*right|right.*arrow/i.test(label(node)));
16
+ if (named.length === 1)
17
+ return named[0];
18
+ // CCBP can put the navigation handler on an unlabelled SVG or its
19
+ // wrapper. Clicking the row itself does not reach that child handler.
20
+ const icons = [...row.querySelectorAll('svg,img')].filter(enabled).filter(node => {
21
+ for (let parent = node; parent && parent !== row; parent = parent.parentElement) {
22
+ if (bookmark(parent))
23
+ return false;
24
+ }
25
+ return true;
26
+ });
27
+ const arrows = icons.filter(node => /arrow.*right|right.*arrow|\b(open|view)\b/i.test(label(node)));
28
+ if (arrows.length === 1)
29
+ return arrows[0];
30
+ if (row.matches('[data-testid="question-list-question"]') && icons.length)
31
+ return icons[icons.length - 1];
32
+ if (controls.length === 1)
33
+ return controls[0];
34
+ if (icons.length === 1)
35
+ return icons[0];
36
+ return row;
37
+ }
38
+ function openQuestion(selected) {
39
+ const action = selected.action;
40
+ if (typeof action.click === 'function')
41
+ action.click();
42
+ else
43
+ action.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, view: window }));
44
+ }
6
45
  function courseFilterStep(doc) {
7
46
  const courses = /^(programming foundations|data structures\s*(?:&|and)\s*algorithms|build your own static website|build your own responsive website|modern responsive web design|build your own dynamic web application)$/i;
8
47
  const choices = [];
@@ -52,7 +91,7 @@
52
91
  const title = portalTitle?.trim() || text(copy);
53
92
  const actions = [...row.querySelectorAll('a[href],button,[role="button"]')].filter(visible);
54
93
  if (title && (actions.length || row.querySelector('svg') || row.matches('[role="row"],tr'))) {
55
- const action = actions.length === 1 ? actions[0] : row;
94
+ const action = openControl(row);
56
95
  const link = row.querySelector('a[href*="/question/"]');
57
96
  found.push({ title, action, href: link?.getAttribute('href') || null });
58
97
  break;
@@ -183,5 +222,5 @@
183
222
  copy.querySelector('#assistant-root')?.remove();
184
223
  return text(copy);
185
224
  }
186
- window.BrowserAssistantCodingBatch = { rows, nextPage, pageKey, pageRange, getBackControl, getSaveBeforeLeaving, matchesQuestion, courseFilterStep };
225
+ window.BrowserAssistantCodingBatch = { rows, openQuestion, nextPage, pageKey, pageRange, getBackControl, getSaveBeforeLeaving, matchesQuestion, courseFilterStep };
187
226
  })();
@@ -1347,7 +1347,10 @@ function mountJournalCountdown(signal) {
1347
1347
  automation.state = 'OPENING_QUESTION';
1348
1348
  automation.pendingNavigation = true;
1349
1349
  updateAutomationUI();
1350
- next.action.click();
1350
+ if (window.BrowserAssistantCodingBatch.openQuestion)
1351
+ window.BrowserAssistantCodingBatch.openQuestion(next);
1352
+ else
1353
+ next.action.click();
1351
1354
  continue;
1352
1355
  }
1353
1356
  const key = window.BrowserAssistantCodingBatch.pageKey(document);
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "manifest_version": 3,
3
3
  "name": "Browser Assistant",
4
- "version": "2.9.37",
4
+ "version": "2.9.39",
5
5
  "description": "Scans webpages for MCQs and coding problems. Powered by Groq (cloud) and Ollama (local fallback).",
6
6
  "permissions": [
7
7
  "activeTab",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "browser-assistant",
3
- "version": "2.9.37",
3
+ "version": "2.9.39",
4
4
  "description": "Chrome extension and local Python backend for exploring webpage questions and coding exercises",
5
5
  "license": "MIT",
6
6
  "repository": {
package/server/main.py CHANGED
@@ -195,7 +195,7 @@ async def lifespan(_app: FastAPI):
195
195
  client.close()
196
196
 
197
197
 
198
- app = FastAPI(title="Browser Assistant API", version="2.9.37", lifespan=lifespan)
198
+ app = FastAPI(title="Browser Assistant API", version="2.9.39", lifespan=lifespan)
199
199
  install_local_guards(app)
200
200
 
201
201
  @app.exception_handler(HTTPException)
@@ -914,6 +914,7 @@ FOR CODING PROBLEMS:
914
914
  8. Write complete, clean, copy-pasteable {language_name} code compatible with the requested version and platform. Do not include TODOs, ellipses, placeholders, pseudo-code, or omitted logic.
915
915
  9. Respect the stated constraints and use appropriate time and space complexity; do not assume O(N) is possible when it is not.
916
916
  10. Trace every supplied sample input against its expected output; also check applicable boundary/edge cases. Correct discrepancies before returning. Never claim a test was executed unless it actually was.
917
+ For printed patterns, derive row counts, leading spaces, interior gaps and separators from the statement and all samples. Preserve significant spaces and blank lines; do not infer a familiar pattern from its title alone.
917
918
  11. If the statement conflicts with examples or leaves material behavior uncertain, follow explicit interface requirements and the strongest evidence in the examples; do not silently fabricate requirements.
918
919
  12. {language_instruction}
919
920
 
@@ -1224,6 +1225,10 @@ Return at most five short actionable issues. For a pass, issues must be [].
1224
1225
  Set verdict to pass only when the algorithm and code satisfy all requirements that can be checked from the question."""
1225
1226
 
1226
1227
 
1228
+ class CodeReviewUnconfirmed(ValueError):
1229
+ """A generated program could not satisfy the independent checks."""
1230
+
1231
+
1227
1232
  async def review_and_correct_code(
1228
1233
  generator,
1229
1234
  original_messages: list,
@@ -1234,9 +1239,9 @@ async def review_and_correct_code(
1234
1239
  review_images: list | None = None,
1235
1240
  samples=(),
1236
1241
  ) -> str:
1237
- """Require an independent review and one correction cycle before returning code."""
1242
+ """Require independent review, with at most two validated correction cycles."""
1238
1243
  review_provider = reviewer or generator
1239
- for review_attempt in range(2):
1244
+ for review_attempt in range(3):
1240
1245
  question_parts = []
1241
1246
  for message in original_messages[1:]:
1242
1247
  content = message.get("content", "")
@@ -1288,13 +1293,20 @@ async def review_and_correct_code(
1288
1293
  issues = [f'Sample {index} with input {value!r} predicts {predicted!r}, expected {expected!r}.'
1289
1294
  for index, ((value, expected), entry) in enumerate(zip(samples, outputs), 1)
1290
1295
  if (predicted := entry['output'].replace('\r\n', '\n').removesuffix('\n')) != expected]
1296
+ if issues:
1297
+ for index, ((_, expected), entry) in enumerate(zip(samples, outputs), 1):
1298
+ predicted = entry['output'].replace('\r\n', '\n').removesuffix('\n')
1299
+ if predicted != expected:
1300
+ issues.append(f'Sample {index} line widths (spaces count): expected '
1301
+ f'{list(map(len, expected.split(chr(10))))}, '
1302
+ f'predicted {list(map(len, predicted.split(chr(10))))}.')
1291
1303
  if not issues:
1292
1304
  for item in json.loads(results_json):
1293
1305
  if language != 'web' and isinstance(item, dict) and item.get('type') == 'code':
1294
1306
  validate_starter_interface(item['code'], starter_code, language)
1295
1307
  return results_json
1296
- if review_attempt:
1297
- raise ValueError(f"Code still failed independent review: {issues}")
1308
+ if review_attempt == 2:
1309
+ raise CodeReviewUnconfirmed(f"Code still failed independent review: {issues}")
1298
1310
 
1299
1311
  repair_messages = [
1300
1312
  *original_messages,
@@ -1309,20 +1321,21 @@ async def review_and_correct_code(
1309
1321
  "when the portal supplies the driver. Return the complete solution in the required JSON-array format only."
1310
1322
  + (build_system_prompt('code', 'web') if language == 'web' else '')
1311
1323
  + starter_interface_instructions(starter_code, language)
1324
+ + '\nReturn a solution, not another review verdict. '
1325
+ + build_system_prompt('code', language).split('OUTPUT FORMAT:')[-1]
1326
+ + ('\nExact sample contract (preserve every space and newline): '
1327
+ + json.dumps([{'input': value, 'output': expected,
1328
+ 'output_lines': [{'text': line, 'width': len(line)} for line in expected.split('\n')]}
1329
+ for value, expected in samples], ensure_ascii=False) if samples else '')
1312
1330
  ),
1313
1331
  },
1314
1332
  ]
1315
- repaired_raw = await generator(repair_messages)
1316
- repaired_json = clean_json(repaired_raw)
1317
- if repaired_json == "[]":
1318
- raise ValueError("Automatic correction returned no usable solution")
1319
- try:
1320
- results_json = validate_code_results(repaired_json, language, require_code=True, starter_code=starter_code)
1321
- for item in json.loads(results_json):
1322
- if isinstance(item, dict) and item.get('type') == 'code':
1323
- validate_starter_interface(item['code'], starter_code, language)
1324
- except (ValueError, json.JSONDecodeError) as exc:
1325
- raise ValueError(f"Automatically corrected code failed validation: {exc}") from exc
1333
+ # A correction can accidentally use the reviewer's verdict schema.
1334
+ # Regenerate unusable code once, then independently review it again.
1335
+ results_json = await generate_validated_result(
1336
+ generator, repair_messages, language, require_code=True,
1337
+ review_code=False, starter_code=starter_code,
1338
+ )
1326
1339
  raise ValueError("Automatic code review did not converge")
1327
1340
 
1328
1341
 
@@ -1417,6 +1430,7 @@ async def solve_questions(content: PageContent):
1417
1430
  ]
1418
1431
 
1419
1432
  errors = []
1433
+ code_review_failed = False
1420
1434
  strict_code_review = require_code and (content.review_before_submit or not FAST_CODE_MODE or STRICT_REPAIR_REVIEW)
1421
1435
  samples = coding_samples(trimmed_text) if strict_code_review and language != 'web' else ()
1422
1436
  checkbox = multiple_choice is not None and not require_code
@@ -1522,6 +1536,7 @@ async def solve_questions(content: PageContent):
1522
1536
  raise
1523
1537
  except Exception as e:
1524
1538
  errors.append(f"{model_id}: {str(e)}")
1539
+ code_review_failed |= isinstance(e, CodeReviewUnconfirmed)
1525
1540
  logger.warning(errors[-1])
1526
1541
 
1527
1542
  # Last resort: Try Ollama (Local fallback)
@@ -1564,6 +1579,7 @@ async def solve_questions(content: PageContent):
1564
1579
  raise
1565
1580
  except Exception as e:
1566
1581
  errors.append(f"Ollama failed: {str(e)}")
1582
+ code_review_failed |= isinstance(e, CodeReviewUnconfirmed)
1567
1583
  logger.warning(errors[-1])
1568
1584
 
1569
1585
  # If all models failed because they couldn't find a question (returned empty results),
@@ -1579,6 +1595,13 @@ async def solve_questions(content: PageContent):
1579
1595
  }
1580
1596
  )
1581
1597
 
1598
+ if code_review_failed:
1599
+ raise HTTPException(422, detail={
1600
+ 'code': 'code_review_unconfirmed',
1601
+ 'message': 'The generated code still failed independent checks after two corrections. '
1602
+ 'No solution was returned. Check the complete problem description and sample formatting, then retry.',
1603
+ })
1604
+
1582
1605
  raise HTTPException(
1583
1606
  status_code=502,
1584
1607
  detail={"errors": errors, "message": "All providers failed"},