browser-assistant 2.9.21 → 2.9.22

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.
@@ -2790,6 +2790,7 @@ function mountJournalCountdown(signal) {
2790
2790
  practice_type: context.question ? 'mcq' : practiceType,
2791
2791
  language: context.question ? undefined : requestedLanguage,
2792
2792
  verify_answer: true,
2793
+ allow_overview: !context.question && practiceType === 'auto' && !requestedLanguage,
2793
2794
  });
2794
2795
  if (!res.ok) {
2795
2796
  const err = res.data || {};
@@ -3403,6 +3404,15 @@ function mountJournalCountdown(signal) {
3403
3404
  container.appendChild(codeBox);
3404
3405
  document.getElementById(`copy-btn-${index}`).onclick = () => copyToClipboard(codeContent, `copy-btn-${index}`);
3405
3406
  }
3407
+ else if (res.type === 'overview') {
3408
+ const item = document.createElement('div');
3409
+ item.className = 'assistant-answer';
3410
+ item.innerHTML = `
3411
+ <div class="assistant-question-text">${escapeHtml(res.title || 'Visible instructions')}</div>
3412
+ <div class="assistant-reasoning-text">${escapeHtml(res.summary)}</div>
3413
+ `;
3414
+ container.appendChild(item);
3415
+ }
3406
3416
  else {
3407
3417
  const item = document.createElement('div');
3408
3418
  item.className = 'assistant-answer';
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "manifest_version": 3,
3
3
  "name": "Browser Assistant",
4
- "version": "2.9.21",
4
+ "version": "2.9.22",
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.21",
3
+ "version": "2.9.22",
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
@@ -27,6 +27,7 @@ from local_security import install_local_guards, redact, sanitize_data
27
27
  from vision_images import (compress_image_base64, unique_image_blocks, collect_image_evidence,
28
28
  cross_check_visual_answers, relative_percentage_question, RELATIVE_PERCENTAGE_INSTRUCTION,
29
29
  answer_permutation, cross_check_text_answers, solve_matrix_choice, solve_row_parallel_choice,
30
+ solve_relu_parallel_choice,
30
31
  ordering_question, solve_sorted_list_merge_order, solve_stack_empty_order, solve_pseudocode_choice,
31
32
  reading_response_constraints,
32
33
  VisionRateLimitError, VisionUnconfirmedError)
@@ -192,7 +193,7 @@ async def lifespan(_app: FastAPI):
192
193
  client.close()
193
194
 
194
195
 
195
- app = FastAPI(title="Browser Assistant API", version="2.9.21", lifespan=lifespan)
196
+ app = FastAPI(title="Browser Assistant API", version="2.9.22", lifespan=lifespan)
196
197
  install_local_guards(app)
197
198
 
198
199
  @app.exception_handler(HTTPException)
@@ -227,6 +228,7 @@ class VisionContent(BaseModel):
227
228
  language: str | None = None
228
229
  text: str = ""
229
230
  verify_answer: bool = False
231
+ allow_overview: bool = False
230
232
  images: list[str] = [] # Additional complete question/option illustrations.
231
233
 
232
234
  @field_validator("text")
@@ -731,7 +733,14 @@ def normalize_web_response(parsed):
731
733
  return parsed
732
734
 
733
735
 
734
- def validate_code_results(results_json: str, language: str, require_code: bool = False, starter_code: str | None = None) -> str:
736
+ def is_displayable_overview(item: dict) -> bool:
737
+ return item.get('type') == 'overview' and all(
738
+ isinstance(item.get(field), str) and item[field].strip() for field in ('title', 'summary')
739
+ )
740
+
741
+
742
+ def validate_code_results(results_json: str, language: str, require_code: bool = False,
743
+ starter_code: str | None = None, *, allow_overview: bool = False) -> str:
735
744
  """Validate generated code and ensure response metadata matches the locked language."""
736
745
  parsed = json.loads(results_json)
737
746
  if language == 'web':
@@ -749,6 +758,9 @@ def validate_code_results(results_json: str, language: str, require_code: bool =
749
758
  else item for item in parsed]
750
759
  if not isinstance(parsed, list):
751
760
  raise ValueError('Expected a JSON array of solution objects')
761
+ if (allow_overview and not require_code and len(parsed) == 1
762
+ and isinstance(parsed[0], dict) and is_displayable_overview(parsed[0])):
763
+ return json.dumps(parsed)
752
764
  code_items = [item for item in parsed if isinstance(item, dict) and item.get('type') == 'code']
753
765
  if require_code and not code_items:
754
766
  raise ValueError('Code mode response did not contain a code solution')
@@ -987,11 +999,20 @@ def build_ollama_code_messages(text: str, url: str, language: str) -> list:
987
999
  ]
988
1000
 
989
1001
 
990
- def build_vision_system_prompt(language: str | None = None) -> str:
1002
+ def build_vision_system_prompt(language: str | None = None, *, allow_overview: bool = False) -> str:
991
1003
  """Build a vision prompt with the requested language locked for code output."""
992
1004
  language = normalize_language(language) or CODE_DEFAULT_LANGUAGE
993
1005
  language_name = LANGUAGE_NAMES[language]
1006
+ overview_instructions = (
1007
+ '\nFor a readable assignment overview or instruction page without a specific question or '
1008
+ 'standalone coding problem, return one overview object: '
1009
+ '[{"type":"overview","title":"visible topic","summary":"concise summary of the visible requirements and next steps"}]. '
1010
+ 'Describe only what is visible. Ignore unrelated navigation and do not invent missing content. '
1011
+ 'An unreadable or incomplete question still requires [].\n'
1012
+ if allow_overview else ''
1013
+ )
994
1014
  return f"""Analyze a screenshot using only readable visual evidence and the supplied question context.
1015
+ {overview_instructions}
995
1016
 
996
1017
  CRITICAL REASONING RULES — FOLLOW EXACTLY:
997
1018
 
@@ -1067,6 +1088,8 @@ async def generate_validated_result(
1067
1088
  reviewer=None,
1068
1089
  review_code: bool = True,
1069
1090
  starter_code: str | None = None,
1091
+ *,
1092
+ allow_overview: bool = False,
1070
1093
  ) -> str:
1071
1094
  """Generate, repair syntax/language/completeness errors, independently review, then return."""
1072
1095
  raw_result = await generator(messages)
@@ -1074,7 +1097,8 @@ async def generate_validated_result(
1074
1097
  if cleaned == "[]" and not require_code:
1075
1098
  return cleaned
1076
1099
  try:
1077
- validated = validate_code_results(cleaned, language, require_code=require_code, starter_code=starter_code)
1100
+ validated = validate_code_results(cleaned, language, require_code=require_code, starter_code=starter_code,
1101
+ allow_overview=allow_overview)
1078
1102
  for item in json.loads(validated):
1079
1103
  if isinstance(item, dict) and item.get('type') == 'code':
1080
1104
  validate_starter_interface(item['code'], starter_code, language)
@@ -1085,8 +1109,9 @@ async def generate_validated_result(
1085
1109
  "role": "user",
1086
1110
  "content": (
1087
1111
  f"The previous response failed validation: {validation_error}. "
1088
- f"Regenerate the complete solution in {LANGUAGE_NAMES[language]} only. "
1089
- f"Set every code result's language field to {language!r}. Return JSON only."
1112
+ + ("Regenerate a result matching the screenshot and the allowed response formats. "
1113
+ if allow_overview else f"Regenerate the complete solution in {LANGUAGE_NAMES[language]} only. ")
1114
+ + f"Set every code result's language field to {language!r}. Return JSON only."
1090
1115
  + (build_system_prompt('code', 'web') if require_code and language == 'web' else
1091
1116
  f' Required schema: [{{"type":"code","language":"{language}","title":"Solution","code":"complete solution","approach":"brief algorithm","time_complexity":"O(...)","space_complexity":"O(...)"}}]. Do not return MCQ answers or a review verdict.' if require_code else '')
1092
1117
  + starter_interface_instructions(starter_code, language)
@@ -1098,7 +1123,8 @@ async def generate_validated_result(
1098
1123
  if retry_cleaned == "[]":
1099
1124
  raise ValueError(f"Language correction retry returned no usable result: {validation_error}")
1100
1125
  try:
1101
- validated = validate_code_results(retry_cleaned, language, require_code=require_code, starter_code=starter_code)
1126
+ validated = validate_code_results(retry_cleaned, language, require_code=require_code, starter_code=starter_code,
1127
+ allow_overview=allow_overview)
1102
1128
  for item in json.loads(validated):
1103
1129
  if isinstance(item, dict) and item.get('type') == 'code':
1104
1130
  validate_starter_interface(item['code'], starter_code, language)
@@ -1259,6 +1285,9 @@ def local_choice_result(text, language):
1259
1285
  if item is None:
1260
1286
  item = solve_row_parallel_choice(text)
1261
1287
  provider = "local tensor dimension check"
1288
+ if item is None:
1289
+ item = solve_relu_parallel_choice(text)
1290
+ provider = "local ReLU shard check"
1262
1291
  if item is None:
1263
1292
  item = solve_pseudocode_choice(text)
1264
1293
  provider = "local pseudocode check"
@@ -1510,6 +1539,7 @@ async def _solve_vision(content: VisionContent):
1510
1539
  except ValueError as exc:
1511
1540
  raise HTTPException(422, f'Image {index}: {exc}') from exc
1512
1541
  is_code_scan = content.practice_type == "code" or (content.practice_type == "auto" and bool(content.language))
1542
+ allow_overview = content.allow_overview and content.practice_type == 'auto' and not is_code_scan and not content.text.strip()
1513
1543
  if not is_code_scan and content.practice_type in {'auto', 'mcq', 'math', 'aptitude'}:
1514
1544
  local_result = local_choice_result(content.text, content.language or CODE_DEFAULT_LANGUAGE)
1515
1545
  if local_result is not None:
@@ -1622,7 +1652,7 @@ async def _solve_vision(content: VisionContent):
1622
1652
  extracted_text = ocr_payload["text"]
1623
1653
  language = resolve_language(extracted_text)
1624
1654
  logger.info(f"Locked requested code language to {language}")
1625
- system_prompt = build_vision_system_prompt(language)
1655
+ system_prompt = build_vision_system_prompt(language, allow_overview=allow_overview)
1626
1656
  if is_code_scan and language == 'web':
1627
1657
  system_prompt = build_system_prompt('code', 'web') + (
1628
1658
  '\nUse the attached screenshots and supplied context as the original problem. '
@@ -1631,13 +1661,15 @@ async def _solve_vision(content: VisionContent):
1631
1661
  if comparison:
1632
1662
  system_prompt += '\n' + RELATIVE_PERCENTAGE_INSTRUCTION
1633
1663
  vision_prompt = "Identify and solve all visible questions using readable evidence."
1664
+ if allow_overview:
1665
+ vision_prompt += " If the screenshot instead shows an assignment overview or instructions, summarize the visible requirements."
1634
1666
  if is_code_scan:
1635
1667
  vision_prompt += (
1636
1668
  f" The locked code language is {LANGUAGE_NAMES[language]} ({language}); "
1637
1669
  f"generate code in that language only. "
1638
1670
  f"Text transcribed from the screenshot: {extracted_text or '[language supplied by caller]'}"
1639
1671
  )
1640
- if content.text:
1672
+ if content.text.strip():
1641
1673
  vision_prompt += ("\nSolve exactly the following question using the attached complete illustrations. "
1642
1674
  "Use this ordered option list for the answer letter. The image may contain only the chart.\n"
1643
1675
  + content.text)
@@ -1676,6 +1708,7 @@ async def _solve_vision(content: VisionContent):
1676
1708
  require_code=is_code_scan,
1677
1709
  reviewer=vision_reviewer,
1678
1710
  review_code=not content.verify_answer,
1711
+ allow_overview=allow_overview,
1679
1712
  )
1680
1713
  if cleaned != "[]":
1681
1714
  items = json.loads(cleaned)
@@ -1910,6 +1943,8 @@ def has_usable_results(results_json: str) -> bool:
1910
1943
  code = item.get("code") or item.get("answer")
1911
1944
  if not isinstance(code, str) or not code.strip():
1912
1945
  return False
1946
+ elif is_displayable_overview(item):
1947
+ continue
1913
1948
  else:
1914
1949
  return False
1915
1950
  answer = str(item.get("answer", "")).lower()
@@ -530,6 +530,33 @@ def solve_row_parallel_choice(text):
530
530
  }
531
531
 
532
532
 
533
+ def solve_relu_parallel_choice(text):
534
+ """Verify why ReLU can be applied to sharded intermediate activations."""
535
+ choices = displayed_single_choices(text)
536
+ if not choices:
537
+ return None
538
+ question = re.split(r'\n(?:Question format: )?Select one answer\.', text.strip(), maxsplit=1, flags=re.I)[0]
539
+ prompt = ' '.join(question.replace('\x60', '').split())
540
+ if not re.fullmatch(
541
+ r'(?:an? |the )?MLP (?:has|uses) (?:a )?ReLU between (?:two )?matrix multiplications\. '
542
+ r'Why (?:does|can) tensor parallelism (?:still )?work(?: here)?\?', prompt, re.I,
543
+ ):
544
+ return None
545
+ elementwise = r'(?:element[- ]?wise|element by element|pointwise|independently on each element)'
546
+ matches = [(letter, option) for letter, option in choices.items() if re.fullmatch(
547
+ rf'ReLU (?:works|operates|acts) {elementwise}(?:,? so (?:each shard can apply it(?: independently)?|shards (?:can )?apply it))?\.?',
548
+ ' '.join(option.replace('\x60', '').split()), re.I,
549
+ )]
550
+ if len(matches) != 1:
551
+ return None
552
+ letter, option = matches[0]
553
+ return {
554
+ 'type': 'mcq', 'question': question, 'answer': f'Option {letter}: {option}',
555
+ 'reasoning': 'ReLU computes max(0, x) for each activation independently. Each shard can apply it to its '
556
+ 'own intermediate activations before the second multiplication.',
557
+ }
558
+
559
+
533
560
  def bind_displayed_choice(value, choices, *, matrix_math):
534
561
  if type(value) not in (str, int, float):
535
562
  return None