browser-assistant 2.9.10 → 2.9.12

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
@@ -89,7 +89,7 @@ For local text inference, install [Ollama](https://github.com/ollama/ollama), ru
89
89
  2. Open `chrome://extensions`, enable **Developer mode**, choose **Load unpacked**, and select the prepared folder containing `manifest.json`.
90
90
  3. Open `http://127.0.0.1:8000/health`. A JSON `status: "ok"` confirms the backend is running; it does not test model access.
91
91
  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.
92
- 5. After changing extension files, reload it in the extensions page and refresh the practice tab.
92
+ 5. For a local source checkout, run `npm run build` after updating the project. When the build version changes, Chrome reloads the unpacked extension once Browser Assistant is idle. A backend started with `server/main.py` also switches to the new version in the same terminal. Start it once with the updated launcher if an older backend is still running. For ZIP and npm installs, reload the extension manually after upgrading.
93
93
 
94
94
  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.
95
95
 
@@ -1,26 +1,32 @@
1
1
  // Background script for Browser Assistant
2
2
  importScripts('editor-bridge.js', 'detached-panel-background.js');
3
- // Local unpacked development updates: only reload when the files in Chrome's
4
- // own extension folder match the workspace release, and every running task is idle.
3
+ // A local build writes its release marker after all the scripts are ready.
4
+ // Read the files from Chrome's own extension folder, independently of FastAPI.
5
5
  let updateCheckRunning = false;
6
+ let lastWorkspaceCheck = -Infinity;
7
+ async function workspaceVersionFile(file) {
8
+ const response = await fetch(`${chrome.runtime.getURL(file)}?workspace=${Date.now()}`, {
9
+ cache: 'no-store', signal: AbortSignal.timeout(4000),
10
+ });
11
+ return response.ok ? (await response.json()).version : null;
12
+ }
6
13
  async function checkWorkspaceUpdate() {
7
- if (updateCheckRunning)
14
+ if (updateCheckRunning || Date.now() - lastWorkspaceCheck < 2500)
8
15
  return;
9
16
  updateCheckRunning = true;
17
+ lastWorkspaceCheck = Date.now();
18
+ let preparedAny = false;
10
19
  try {
11
- const release = await fetch('http://127.0.0.1:8000/extension-release', { cache: 'no-store', signal: AbortSignal.timeout(4000) }).then(r => r.ok ? r.json() : null);
12
20
  const current = chrome.runtime.getManifest().version;
13
- if (!release?.version || release.version === current)
21
+ const ready = await workspaceVersionFile('workspace-release.json');
22
+ if (typeof ready !== 'string' || !/^\d+(?:\.\d+){1,3}$/.test(ready) || ready === current)
14
23
  return;
15
- const disk = await fetch(chrome.runtime.getURL('manifest.json'), { cache: 'no-store' }).then(r => r.json());
16
- // Never loop reloading an old ZIP extraction. Load the workspace's
17
- // extension directory once to enable local file updates.
18
- if (disk.version !== release.version)
24
+ if (await workspaceVersionFile('manifest.json') !== ready)
19
25
  return;
20
26
  const tabs = (await chrome.tabs.query({})).filter(tab => /^https?:\/\//.test(tab.url || ''));
21
27
  const states = await Promise.all(tabs.map(async (tab) => {
22
28
  try {
23
- return { tab, state: await chrome.tabs.sendMessage(tab.id, { action: 'assistantUpdateStatus' }) };
29
+ return { tab, state: await chrome.tabs.sendMessage(tab.id, { action: 'assistantUpdateStatus' }, { frameId: 0 }) };
24
30
  }
25
31
  catch {
26
32
  return { tab, state: null };
@@ -31,15 +37,21 @@ async function checkWorkspaceUpdate() {
31
37
  for (const { tab, state } of states) {
32
38
  if (!state)
33
39
  continue;
34
- const prepared = await chrome.tabs.sendMessage(tab.id, { action: 'assistantPrepareUpdate' });
40
+ const prepared = await chrome.tabs.sendMessage(tab.id, { action: 'assistantPrepareUpdate' }, { frameId: 0 });
35
41
  if (!prepared?.ready) {
36
42
  await attachUpdatedPanels();
37
43
  return;
38
44
  }
45
+ preparedAny = true;
39
46
  }
47
+ await rememberDetachedPanelForUpdate(ready);
40
48
  chrome.runtime.reload();
41
49
  }
42
- catch { /* Offline server or restricted tab: retry on the next alarm. */ }
50
+ catch {
51
+ // A tab can navigate between the idle and prepare checks.
52
+ if (preparedAny)
53
+ await attachUpdatedPanels();
54
+ }
43
55
  finally {
44
56
  updateCheckRunning = false;
45
57
  }
@@ -60,7 +72,7 @@ async function attachUpdatedPanels() {
60
72
  catch { /* Chrome may restrict particular sites; leave them alone. */ }
61
73
  }
62
74
  }
63
- chrome.alarms.create('assistant-workspace-update', { periodInMinutes: 1 });
75
+ chrome.alarms.create('assistant-workspace-update', { periodInMinutes: 0.5 });
64
76
  chrome.alarms.onAlarm.addListener(alarm => {
65
77
  if (alarm.name !== 'assistant-workspace-update')
66
78
  return;
@@ -68,7 +80,7 @@ chrome.alarms.onAlarm.addListener(alarm => {
68
80
  void updateJournalBadge();
69
81
  });
70
82
  chrome.runtime.onInstalled.addListener(details => {
71
- void attachUpdatedPanels();
83
+ void attachUpdatedPanels().then(() => restoreDetachedPanelAfterUpdate()).catch(() => { });
72
84
  if (details.reason === 'update')
73
85
  void clearRetiredReminderSettings();
74
86
  });
@@ -130,7 +142,14 @@ chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
130
142
  sendResponse({ error: 'Invalid extension message' });
131
143
  return false;
132
144
  }
145
+ if (request.action === 'checkWorkspaceUpdate' && sender.id === chrome.runtime.id) {
146
+ sendResponse({ ok: true });
147
+ void checkWorkspaceUpdate();
148
+ return false;
149
+ }
133
150
  if (['panel:open', 'panel:snapshot', 'panel:action', 'panel:return', 'panel:target-status'].includes(request.action)) {
151
+ if (request.action === 'panel:snapshot' && sender.id === chrome.runtime.id)
152
+ void checkWorkspaceUpdate();
134
153
  return browserAssistantDetachedMessage(request, sender, sendResponse);
135
154
  }
136
155
  if (request.action === 'journalCountdowns' && sender.id === chrome.runtime.id) {
@@ -86,6 +86,7 @@ function mountJournalCountdown(signal) {
86
86
  const SERVER = 'http://localhost:8000';
87
87
  const root = document.createElement('div');
88
88
  root.id = 'assistant-root';
89
+ root.dataset.build = extensionVersion;
89
90
  root.classList.add('assistant-panel-initializing');
90
91
  document.body.appendChild(root);
91
92
  const journalCountdown = ['http:', 'https:'].includes(location.protocol)
@@ -209,6 +210,7 @@ function mountJournalCountdown(signal) {
209
210
  let lastResultSummary = "";
210
211
  let isHidden = false;
211
212
  let serverOnline = null; // null = unknown, true/false = checked
213
+ let backendVersion = '';
212
214
  let isScanning = false;
213
215
  let extensionAlive = true; // false after extension reload invalidates context
214
216
  let historyItems = [];
@@ -344,7 +346,8 @@ function mountJournalCountdown(signal) {
344
346
  }
345
347
  return false;
346
348
  }
347
- const busy = automation.running || isScanning || Boolean(window.BrowserAssistantJournalBusy);
349
+ const busy = automation.running || isScanning || dragState.dragging || Boolean(window.BrowserAssistantJournalBusy)
350
+ || Boolean(root.contains(document.activeElement) && document.activeElement?.matches('textarea,input,select,[contenteditable="true"]'));
348
351
  if (request.action === 'assistantUpdateStatus') {
349
352
  sendResponse({ busy });
350
353
  return false;
@@ -356,7 +359,9 @@ function mountJournalCountdown(signal) {
356
359
  return false;
357
360
  }
358
361
  try {
359
- sessionStorage.setItem('browserAssistantReopenAfterUpdate', isCollapsed ? 'false' : 'true');
362
+ sessionStorage.setItem('browserAssistantReopenAfterUpdate', JSON.stringify({
363
+ isCollapsed, isHidden, selectedTab, selectedMode,
364
+ }));
360
365
  }
361
366
  catch { }
362
367
  disposed = true;
@@ -374,6 +379,14 @@ function mountJournalCountdown(signal) {
374
379
  return false;
375
380
  };
376
381
  chrome.runtime.onMessage.addListener(updateListener);
382
+ function requestWorkspaceUpdate() {
383
+ if (!document.hidden && !disposed)
384
+ void chrome.runtime.sendMessage({ action: 'checkWorkspaceUpdate' }).catch(() => { });
385
+ }
386
+ document.addEventListener('visibilitychange', requestWorkspaceUpdate, { signal: lifecycle.signal });
387
+ window.addEventListener('focus', requestWorkspaceUpdate, { signal: lifecycle.signal });
388
+ const workspaceUpdateTimer = window.setInterval(requestWorkspaceUpdate, 3000);
389
+ lifecycle.signal.addEventListener('abort', () => window.clearInterval(workspaceUpdateTimer), { once: true });
377
390
  document.addEventListener('assistant-journal-update', updateAutomationUI, { signal: lifecycle.signal });
378
391
  document.addEventListener('assistant-journal-ready', () => {
379
392
  if (!window.BrowserAssistantJournal?.matches())
@@ -587,6 +600,11 @@ function mountJournalCountdown(signal) {
587
600
  const start = document.getElementById('assistant-auto-start-btn');
588
601
  const pause = document.getElementById('assistant-auto-pause-btn');
589
602
  const stop = document.getElementById('assistant-auto-stop-btn');
603
+ const backend = document.getElementById('assistant-backend-build');
604
+ if (backend) {
605
+ backend.hidden = !backendVersion || backendVersion === extensionVersion;
606
+ backend.textContent = backend.hidden ? '' : `Backend ${backendVersion} is running. Restart the backend to load ${extensionVersion}.`;
607
+ }
590
608
  const journal = window.BrowserAssistantJournal;
591
609
  if (journal?.matches()) {
592
610
  const current = journal.getState();
@@ -1843,7 +1861,16 @@ function mountJournalCountdown(signal) {
1843
1861
  let response;
1844
1862
  try {
1845
1863
  let requestText = question.text;
1846
- if (location.origin === 'https://learning.ccbp.in' && /^\/primitive-coding\/practice\//.test(location.pathname)
1864
+ if (question.type === 'ordering') {
1865
+ await checkServer();
1866
+ if (!(await waitWhilePaused(runId)))
1867
+ break;
1868
+ const [major, minor, patch] = backendVersion.split('.').map(Number);
1869
+ if (major === 1 || (major === 2 && (minor < 9 || (minor === 9 && patch < 10)))) {
1870
+ throw new Error(`Drag-and-drop needs backend 2.9.10 or newer. Backend ${backendVersion} is running. Restart it, then start automation again.`);
1871
+ }
1872
+ }
1873
+ if (location.origin === 'https://learning.ccbp.in' && /^\/primitive-coding(?:-review)?\/practice\//.test(location.pathname)
1847
1874
  && document.querySelector('.ace_editor,.monaco-editor,.CodeMirror')) {
1848
1875
  const snapshot = await readMcqSnippetSnapshot(question, runId);
1849
1876
  if (!snapshot?.ok)
@@ -2239,13 +2266,24 @@ function mountJournalCountdown(signal) {
2239
2266
  try {
2240
2267
  const res = await apiRequest('/health', 'GET');
2241
2268
  online = res.ok;
2269
+ const version = res.data?.version;
2270
+ if (online && typeof version === 'string' && /^\d+(?:\.\d+){1,3}$/.test(version))
2271
+ backendVersion = version;
2242
2272
  }
2243
2273
  catch { /* The next request can reconnect when the backend starts. */ }
2244
- if (serverOnline === null)
2274
+ if (!disposed) {
2245
2275
  setServerStatus(online);
2276
+ updateAutomationUI();
2277
+ }
2246
2278
  }
2247
2279
  // Check once on load
2248
2280
  checkServer();
2281
+ const backendStatusTimer = window.setInterval(() => {
2282
+ if (!document.hidden && !isCollapsed && (!serverOnline || (backendVersion && backendVersion !== extensionVersion))) {
2283
+ void checkServer();
2284
+ }
2285
+ }, 6000);
2286
+ lifecycle.signal.addEventListener('abort', () => window.clearInterval(backendStatusTimer), { once: true });
2249
2287
  // ── Smart text extraction ────────────────────────────────────────────────
2250
2288
  function extractSmartText() {
2251
2289
  const textLimit = ['code', 'mcq'].includes(detectPracticeType()) ? 60000 : 12000;
@@ -2462,7 +2500,10 @@ function mountJournalCountdown(signal) {
2462
2500
  showAutomationNotice('Automation is unavailable on this page.');
2463
2501
  return;
2464
2502
  }
2465
- if (context.target.id !== 'local-practice'
2503
+ const startDirectly = context.target.id === 'local-practice'
2504
+ || (type === 'MCQ' && context.target.id === 'ccbp-learning-practice'
2505
+ && /^\/(?:default-question|primitive-coding(?:-review)?)\/practice\//.test(location.pathname));
2506
+ if (!startDirectly
2466
2507
  && !window.confirm('Start ' + type + ' automation on this page? It can enter and submit answers as it runs.'))
2467
2508
  return;
2468
2509
  const progress = document.querySelector('[data-practice-quiz] #progress')?.textContent;
@@ -2471,7 +2512,8 @@ function mountJournalCountdown(signal) {
2471
2512
  started_at: new Date().toISOString(), ended_at: null, total, completed: 0, failed: 0, status: 'Running', revision: 0 };
2472
2513
  directRunStarting = true;
2473
2514
  saveDirectRun();
2474
- showAutomationNotice(type + ' automation started.');
2515
+ if (!startDirectly)
2516
+ showAutomationNotice(type + ' automation started.');
2475
2517
  const started = startPracticeAutomation();
2476
2518
  directRunStarting = false;
2477
2519
  updateDirectRun();
@@ -2973,6 +3015,7 @@ function mountJournalCountdown(signal) {
2973
3015
  <span class="assistant-qa-state" id="assistant-automation-state" aria-live="polite">${automation.state}</span>
2974
3016
  </div>
2975
3017
  <div class="assistant-automation-status" id="assistant-automation-status" aria-live="polite"></div>
3018
+ <div class="assistant-automation-status" id="assistant-backend-build" hidden></div>
2976
3019
  <dl class="assistant-qa-details">
2977
3020
  <div class="assistant-qa-wide"><dt>Current page</dt><dd id="assistant-automation-page">—</dd></div>
2978
3021
  <div><dt>Completed</dt><dd id="assistant-automation-completed">0</dd></div>
@@ -3041,7 +3084,7 @@ function mountJournalCountdown(signal) {
3041
3084
  // Escape for safe attribute injection (B7)
3042
3085
  const safeContent = content.replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;');
3043
3086
  root.innerHTML = `
3044
- <button class="assistant-tab collapsed ${content ? 'has-answer' : ''}" id="assistant-trigger" type="button" aria-label="Open Browser Assistant" data-content="${safeContent}">
3087
+ <button class="assistant-tab collapsed ${content ? 'has-answer' : ''}" id="assistant-trigger" type="button" aria-label="Open Browser Assistant" title="Browser Assistant v${extensionVersion}" data-content="${safeContent}">
3045
3088
  <span class="assistant-mark" aria-hidden="true">BA</span>
3046
3089
  ${isMinimalMode ? '<div class="assistant-mode-indicator">MIN</div>' : ''}
3047
3090
  </button>
@@ -3062,7 +3105,7 @@ function mountJournalCountdown(signal) {
3062
3105
  <div class="assistant-header">
3063
3106
  <div class="assistant-title-row">
3064
3107
  <span class="assistant-mark" aria-hidden="true">BA</span>
3065
- <h3 class="assistant-title">Browser Assistant</h3>
3108
+ <h3 class="assistant-title">Browser Assistant <span class="assistant-build">v${extensionVersion}</span></h3>
3066
3109
  ${statusDot}
3067
3110
  </div>
3068
3111
  <div class="assistant-header-actions">
@@ -3329,10 +3372,23 @@ function mountJournalCountdown(signal) {
3329
3372
  selectedTab = 'qa';
3330
3373
  automation.state = 'UPDATED';
3331
3374
  }
3375
+ else if (reopen && reopen !== 'false') {
3376
+ const state = JSON.parse(reopen);
3377
+ isCollapsed = state.isCollapsed !== false;
3378
+ isHidden = state.isHidden === true;
3379
+ if (['auto', 'mcq', 'aptitude', 'code', 'qa'].includes(state.selectedTab))
3380
+ selectedTab = state.selectedTab;
3381
+ if (['auto', 'mcq', 'aptitude', 'code'].includes(state.selectedMode))
3382
+ selectedMode = state.selectedMode;
3383
+ if (isHidden)
3384
+ root.style.display = 'none';
3385
+ automation.state = 'UPDATED';
3386
+ }
3332
3387
  }
3333
3388
  catch { }
3334
3389
  render();
3335
3390
  void syncDetachedPanel();
3391
+ requestWorkspaceUpdate();
3336
3392
  function hasDirectRunContinuation() {
3337
3393
  try {
3338
3394
  return [AUTO_RESUME_KEY, CODING_BATCH_KEY, 'assistantPendingJournal'].some(key => sessionStorage.getItem(key));
@@ -1,5 +1,6 @@
1
1
  const DETACHED_PANEL_KEY = 'assistantDetachedPanel';
2
2
  const DETACHED_PANEL_MODE = 'assistantPanelMode';
3
+ const DETACHED_UPDATE_KEY = 'assistantDetachedPanelUpdate';
3
4
  const detachedPage = () => chrome.runtime.getURL('detached-panel.html');
4
5
  let detachedPanelQueue = Promise.resolve();
5
6
  function serializeDetachedPanel(action) {
@@ -17,9 +18,9 @@ async function releasePanelTab(session) {
17
18
  await messagePanelTab(session.targetTabId, { action: 'assistantPanelDetach', token: session.token })
18
19
  .catch(() => undefined);
19
20
  }
20
- async function openDetachedPanel(tabId) {
21
+ async function openDetachedPanel(tabId, restore) {
21
22
  const tab = await chrome.tabs.get(tabId);
22
- if (!tab.active || !/^https?:\/\//.test(tab.url || '')) {
23
+ if ((!restore && !tab.active) || !/^https?:\/\//.test(tab.url || '')) {
23
24
  throw Error('Open the toolbar on the web tab you want to control.');
24
25
  }
25
26
  const ready = await messagePanelTab(tabId, { action: 'assistantPanelPing' }).catch(() => null);
@@ -33,7 +34,7 @@ async function openDetachedPanel(tabId) {
33
34
  previous = undefined;
34
35
  }
35
36
  const created = previous ? undefined : await chrome.windows.create({
36
- url: detachedPage(), type: 'popup', width: 420, height: 690, focused: true,
37
+ url: detachedPage(), type: 'popup', width: 420, height: 690, focused: true, ...restore,
37
38
  });
38
39
  const windowId = previous?.windowId ?? created?.id;
39
40
  if (windowId === undefined)
@@ -43,10 +44,31 @@ async function openDetachedPanel(tabId) {
43
44
  const session = previous?.targetTabId === tabId ? previous : { windowId, targetTabId: tabId, token: crypto.randomUUID() };
44
45
  await chrome.storage.session.set({ [DETACHED_PANEL_KEY]: session });
45
46
  await chrome.storage.local.set({ [DETACHED_PANEL_MODE]: 'separate' });
46
- if (previous)
47
+ if (previous && !restore)
47
48
  await chrome.windows.update(windowId, { focused: true, state: 'normal' });
48
49
  return { ok: true };
49
50
  }
51
+ async function rememberDetachedPanelForUpdate(version) {
52
+ const session = await detachedPanelSession();
53
+ if (!session)
54
+ return;
55
+ const panel = await chrome.windows.get(session.windowId).catch(() => null);
56
+ if (!panel)
57
+ return;
58
+ await chrome.storage.local.set({ [DETACHED_UPDATE_KEY]: {
59
+ version, targetTabId: session.targetTabId,
60
+ bounds: { left: panel.left, top: panel.top, width: panel.width, height: panel.height },
61
+ } });
62
+ }
63
+ async function restoreDetachedPanelAfterUpdate() {
64
+ const stored = (await chrome.storage.local.get(DETACHED_UPDATE_KEY))[DETACHED_UPDATE_KEY];
65
+ if (!stored)
66
+ return;
67
+ await chrome.storage.local.remove(DETACHED_UPDATE_KEY);
68
+ if (stored.version !== chrome.runtime.getManifest().version)
69
+ return;
70
+ await serializeDetachedPanel(() => openDetachedPanel(stored.targetTabId, { ...stored.bounds, focused: false }));
71
+ }
50
72
  function browserAssistantDetachedMessage(request, sender, reply) {
51
73
  if (sender.id !== chrome.runtime.id) {
52
74
  reply({ error: 'Extension sender required.' });
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "manifest_version": 3,
3
3
  "name": "Browser Assistant",
4
- "version": "2.9.10",
4
+ "version": "2.9.12",
5
5
  "description": "Scans webpages for MCQs and coding problems. Powered by Groq (cloud) and Ollama (local fallback).",
6
6
  "permissions": [
7
7
  "activeTab",
@@ -144,6 +144,12 @@
144
144
  font: 720 15px/1.2 var(--ui-font);
145
145
  letter-spacing: -.02em;
146
146
  }
147
+ #assistant-root .assistant-build {
148
+ color: var(--muted);
149
+ font-size: 10px;
150
+ font-weight: 650;
151
+ white-space: nowrap;
152
+ }
147
153
  #assistant-root .assistant-title-row .status-dot {
148
154
  width: 8px;
149
155
  height: 8px;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "browser-assistant",
3
- "version": "2.9.10",
3
+ "version": "2.9.12",
4
4
  "description": "Chrome extension and local Python backend for exploring webpage questions and coding exercises",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -36,13 +36,14 @@
36
36
  "server/journal_syllabus.json",
37
37
  "server/local_security.py",
38
38
  "server/main.py",
39
+ "server/workspace_server.py",
39
40
  "server/practice_quiz.html",
40
41
  "server/requirements.lock.txt",
41
42
  "server/requirements.txt",
42
43
  "server/vision_images.py"
43
44
  ],
44
45
  "scripts": {
45
- "build": "tsc --project tsconfig.json",
46
+ "build": "tsc --project tsconfig.json && node scripts/mark_workspace_build.cjs",
46
47
  "prepack": "npm run build",
47
48
  "typecheck": "tsc --project tsconfig.json --noEmit",
48
49
  "test": "npm run build && node --test extension/*.test.cts",
package/server/main.py CHANGED
@@ -1,5 +1,4 @@
1
1
  import os
2
- import uvicorn
3
2
  import json
4
3
  import asyncio
5
4
  import ast
@@ -28,7 +27,7 @@ from local_security import install_local_guards, redact, sanitize_data
28
27
  from vision_images import (compress_image_base64, unique_image_blocks, collect_image_evidence,
29
28
  cross_check_visual_answers, relative_percentage_question, RELATIVE_PERCENTAGE_INSTRUCTION,
30
29
  answer_permutation, cross_check_text_answers, solve_matrix_choice, solve_row_parallel_choice,
31
- ordering_question, solve_sorted_list_merge_order, reading_response_constraints,
30
+ ordering_question, solve_sorted_list_merge_order, solve_pseudocode_choice, reading_response_constraints,
32
31
  VisionRateLimitError, VisionUnconfirmedError)
33
32
 
34
33
  logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")
@@ -192,7 +191,7 @@ async def lifespan(_app: FastAPI):
192
191
  client.close()
193
192
 
194
193
 
195
- app = FastAPI(title="Browser Assistant API", version="2.9.10", lifespan=lifespan)
194
+ app = FastAPI(title="Browser Assistant API", version="2.9.12", lifespan=lifespan)
196
195
  install_local_guards(app)
197
196
 
198
197
  @app.exception_handler(HTTPException)
@@ -1259,6 +1258,9 @@ def local_choice_result(text, language):
1259
1258
  if item is None:
1260
1259
  item = solve_row_parallel_choice(text)
1261
1260
  provider = "local tensor dimension check"
1261
+ if item is None:
1262
+ item = solve_pseudocode_choice(text)
1263
+ provider = "local pseudocode check"
1262
1264
  if item is not None:
1263
1265
  return {"results": json.dumps([item], ensure_ascii=False), "provider": f"{provider} [verified]",
1264
1266
  "language": language, "answer_verified": True, "code_reviewed": False}
@@ -1940,4 +1942,7 @@ if __name__ == "__main__":
1940
1942
  # loopback keeps direct local runs unavailable to other network devices.
1941
1943
  # Docker overrides SERVER_HOST because its published port is already bound
1942
1944
  # to the host loopback interface in docker-compose.yml.
1943
- uvicorn.run(app, host=os.getenv("SERVER_HOST", "127.0.0.1"), port=8000)
1945
+ from workspace_server import run_workspace_server
1946
+ raise SystemExit(run_workspace_server(
1947
+ os.getenv("SERVER_HOST", "127.0.0.1"), int(os.getenv("SERVER_PORT", "8000")), app.version,
1948
+ ))
@@ -441,6 +441,52 @@ def displayed_single_choices(text):
441
441
  return parse_labeled_choices(option_text)
442
442
 
443
443
 
444
+ def solve_pseudocode_choice(text):
445
+ choices = displayed_single_choices(text)
446
+ if not choices:
447
+ return None
448
+ prompt = re.split(r'\n(?:Question format: )?Select one answer\.', text.strip(), maxsplit=1, flags=re.I)[0]
449
+ initial = re.search(r'\binitial value of the\s+\x60?([a-zA-Z_]\w*)\x60?\s+node\s*\?', prompt, re.I)
450
+ if initial:
451
+ variable = re.escape(initial[1])
452
+ constructors = re.findall(rf'^\s*{variable}\s*=\s*new\s+Node\s*\(\s*(-?\d+)\s*\)\s*;?\s*$',
453
+ prompt, re.M)
454
+ if len(constructors) != 1:
455
+ return None
456
+ expected = constructors[0]
457
+ reason = f'The pseudocode initializes {initial[1]} with new Node({expected}).'
458
+ matches = [(letter, option) for letter, option in choices.items()
459
+ if option.strip().strip('\x60').replace('−', '-') == expected]
460
+ elif re.search(r'time complexity of the below pseudo\s*code where size of linked list', prompt, re.I):
461
+ loop = re.search(r'while\s*\(\s*(\w+)\s*!=\s*null\s*\|\|\s*(\w+)\s*!=\s*null\s*\)', prompt)
462
+ if not loop or len(re.findall(r'\b(?:while|for)\s*\(', prompt)) != 1:
463
+ return None
464
+ first, second = loop.groups()
465
+ if first == second or not all(re.search(rf'if\s*\(\s*{re.escape(pointer)}\s*!=\s*null\s*\)' r'[^}]*?'
466
+ rf'\b{re.escape(pointer)}\s*=\s*{re.escape(pointer)}\s*->\s*next\b',
467
+ prompt[loop.end():]) for pointer in (first, second)):
468
+ return None
469
+ matches = [(letter, option) for letter, option in choices.items()
470
+ if re.sub(r'\s+', '', option.strip('\x60')) == 'O(max(m,n))']
471
+ reason = 'Both available pointers advance in each iteration, so the loop runs until the longer list is exhausted.'
472
+ elif 'mergeTwoLists' in prompt and re.search(r'\bwhat happens if\s+temp1\s*(?:->|→)\s*data\s+is less than or equal to\s+'
473
+ r'temp2\s*(?:->|→)\s*data', prompt.replace('\x60', ''), re.I):
474
+ branch = re.search(r'if\s*\(\s*temp1\s*->\s*data\s*<=\s*temp2\s*->\s*data\s*\)\s*\{([^}]+)\}', prompt)
475
+ if not branch or not re.search(r'\bcur\s*->\s*next\s*=\s*temp1?\b', branch[1]) \
476
+ or not re.search(r'\btemp1\s*=\s*temp1\s*->\s*next\b', branch[1]):
477
+ return None
478
+ matches = [(letter, option) for letter, option in choices.items() if re.fullmatch(
479
+ r'temp1 is linked to the merged list and temp1 is moved to the next node\.?',
480
+ ' '.join(option.replace('\x60', '').split()), re.I)]
481
+ reason = 'The <= branch links the first-list node and advances temp1 to temp1->next.'
482
+ else:
483
+ return None
484
+ if len(matches) != 1:
485
+ return None
486
+ letter, option = matches[0]
487
+ return {'type': 'mcq', 'question': prompt, 'answer': f'Option {letter}: {option}', 'reasoning': reason}
488
+
489
+
444
490
  def solve_row_parallel_choice(text):
445
491
  """Check the shared multiplication dimension in a row-parallel linear layer."""
446
492
  choices = displayed_single_choices(text)
@@ -0,0 +1,58 @@
1
+ """Keep the local backend terminal running across completed workspace builds."""
2
+ import json
3
+ import multiprocessing
4
+ from pathlib import Path
5
+ from threading import Event, Thread
6
+
7
+ import uvicorn
8
+
9
+
10
+ def workspace_build(root):
11
+ try:
12
+ extension = root / "extension"
13
+ ready = json.loads((extension / "workspace-release.json").read_text(encoding="utf-8"))["version"]
14
+ manifest = json.loads((extension / "manifest.json").read_text(encoding="utf-8"))["version"]
15
+ return ready if isinstance(ready, str) and ready == manifest else None
16
+ except (OSError, ValueError, KeyError, TypeError):
17
+ return None
18
+
19
+
20
+ def serve(host, port, stop):
21
+ server = uvicorn.Server(uvicorn.Config("main:app", host=host, port=port))
22
+
23
+ def shutdown():
24
+ stop.wait()
25
+ server.should_exit = True
26
+
27
+ Thread(target=shutdown, daemon=True).start()
28
+ server.run()
29
+
30
+
31
+ def run_workspace_server(host, port, version, *, root=None, shutdown=None):
32
+ root = root or Path(__file__).resolve().parent.parent
33
+ shutdown = shutdown or Event()
34
+ context = multiprocessing.get_context("spawn")
35
+ while not shutdown.is_set():
36
+ stop = context.Event()
37
+ process = context.Process(target=serve, args=(host, port, stop))
38
+ process.start()
39
+ next_version = None
40
+ try:
41
+ while process.is_alive() and not shutdown.wait(0.5):
42
+ ready = workspace_build(root)
43
+ if ready and ready != version:
44
+ next_version = ready
45
+ print(f"Updating Browser Assistant backend from {version} to {ready}. Finishing active requests.",
46
+ flush=True)
47
+ break
48
+ except KeyboardInterrupt:
49
+ shutdown.set()
50
+ finally:
51
+ stop.set()
52
+ process.join()
53
+ exit_code = process.exitcode
54
+ process.close()
55
+ if not next_version:
56
+ return 0 if shutdown.is_set() else exit_code
57
+ version = next_version
58
+ return 0