browser-assistant 2.9.9 → 2.9.11

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;
@@ -2973,6 +3011,7 @@ function mountJournalCountdown(signal) {
2973
3011
  <span class="assistant-qa-state" id="assistant-automation-state" aria-live="polite">${automation.state}</span>
2974
3012
  </div>
2975
3013
  <div class="assistant-automation-status" id="assistant-automation-status" aria-live="polite"></div>
3014
+ <div class="assistant-automation-status" id="assistant-backend-build" hidden></div>
2976
3015
  <dl class="assistant-qa-details">
2977
3016
  <div class="assistant-qa-wide"><dt>Current page</dt><dd id="assistant-automation-page">—</dd></div>
2978
3017
  <div><dt>Completed</dt><dd id="assistant-automation-completed">0</dd></div>
@@ -3041,7 +3080,7 @@ function mountJournalCountdown(signal) {
3041
3080
  // Escape for safe attribute injection (B7)
3042
3081
  const safeContent = content.replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;');
3043
3082
  root.innerHTML = `
3044
- <button class="assistant-tab collapsed ${content ? 'has-answer' : ''}" id="assistant-trigger" type="button" aria-label="Open Browser Assistant" data-content="${safeContent}">
3083
+ <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
3084
  <span class="assistant-mark" aria-hidden="true">BA</span>
3046
3085
  ${isMinimalMode ? '<div class="assistant-mode-indicator">MIN</div>' : ''}
3047
3086
  </button>
@@ -3062,7 +3101,7 @@ function mountJournalCountdown(signal) {
3062
3101
  <div class="assistant-header">
3063
3102
  <div class="assistant-title-row">
3064
3103
  <span class="assistant-mark" aria-hidden="true">BA</span>
3065
- <h3 class="assistant-title">Browser Assistant</h3>
3104
+ <h3 class="assistant-title">Browser Assistant <span class="assistant-build">v${extensionVersion}</span></h3>
3066
3105
  ${statusDot}
3067
3106
  </div>
3068
3107
  <div class="assistant-header-actions">
@@ -3329,10 +3368,23 @@ function mountJournalCountdown(signal) {
3329
3368
  selectedTab = 'qa';
3330
3369
  automation.state = 'UPDATED';
3331
3370
  }
3371
+ else if (reopen && reopen !== 'false') {
3372
+ const state = JSON.parse(reopen);
3373
+ isCollapsed = state.isCollapsed !== false;
3374
+ isHidden = state.isHidden === true;
3375
+ if (['auto', 'mcq', 'aptitude', 'code', 'qa'].includes(state.selectedTab))
3376
+ selectedTab = state.selectedTab;
3377
+ if (['auto', 'mcq', 'aptitude', 'code'].includes(state.selectedMode))
3378
+ selectedMode = state.selectedMode;
3379
+ if (isHidden)
3380
+ root.style.display = 'none';
3381
+ automation.state = 'UPDATED';
3382
+ }
3332
3383
  }
3333
3384
  catch { }
3334
3385
  render();
3335
3386
  void syncDetachedPanel();
3387
+ requestWorkspaceUpdate();
3336
3388
  function hasDirectRunContinuation() {
3337
3389
  try {
3338
3390
  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.9",
4
+ "version": "2.9.11",
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.9",
3
+ "version": "2.9.11",
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,8 @@ 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
- reading_response_constraints, VisionRateLimitError, VisionUnconfirmedError)
30
+ ordering_question, solve_sorted_list_merge_order, solve_pseudocode_choice, reading_response_constraints,
31
+ VisionRateLimitError, VisionUnconfirmedError)
32
32
 
33
33
  logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")
34
34
  logger = logging.getLogger("browser-assistant")
@@ -191,7 +191,7 @@ async def lifespan(_app: FastAPI):
191
191
  client.close()
192
192
 
193
193
 
194
- app = FastAPI(title="Browser Assistant API", version="2.9.9", lifespan=lifespan)
194
+ app = FastAPI(title="Browser Assistant API", version="2.9.11", lifespan=lifespan)
195
195
  install_local_guards(app)
196
196
 
197
197
  @app.exception_handler(HTTPException)
@@ -1258,6 +1258,9 @@ def local_choice_result(text, language):
1258
1258
  if item is None:
1259
1259
  item = solve_row_parallel_choice(text)
1260
1260
  provider = "local tensor dimension check"
1261
+ if item is None:
1262
+ item = solve_pseudocode_choice(text)
1263
+ provider = "local pseudocode check"
1261
1264
  if item is not None:
1262
1265
  return {"results": json.dumps([item], ensure_ascii=False), "provider": f"{provider} [verified]",
1263
1266
  "language": language, "answer_verified": True, "code_reviewed": False}
@@ -1278,8 +1281,15 @@ async def solve_questions(content: PageContent):
1278
1281
  except ValueError as exc:
1279
1282
  raise HTTPException(status_code=422, detail=str(exc)) from exc
1280
1283
  system_prompt = build_system_prompt(content.practice_type, language)
1284
+ ordering = ordering_question(trimmed_text)
1281
1285
  reading_constraints = reading_response_constraints(trimmed_text) if content.require_answer_agreement else None
1282
- if reading_constraints:
1286
+ if ordering:
1287
+ system_prompt = (
1288
+ 'Arrange all steps in the order required by the problem. Check prerequisites and use each displayed '
1289
+ 'step number once. Return exactly one JSON array item with type "mcq", the question, a brief '
1290
+ 'reasoning string, and an answer array of the original step numbers in their new order.'
1291
+ )
1292
+ elif reading_constraints:
1283
1293
  _, _, keyword = reading_constraints
1284
1294
  rule = (f'Use two to five words including the unchanged word {keyword}. Preserve the meaning of the original sentence. '
1285
1295
  if keyword else 'Use exactly one word. ')
@@ -1317,6 +1327,11 @@ REPAIR MODE:
1317
1327
  )
1318
1328
  strict_code_review = require_code and (content.review_before_submit or not FAST_CODE_MODE or STRICT_REPAIR_REVIEW)
1319
1329
  verify_answers = not require_code and (content.verify_answer or content.require_answer_agreement or not FAST_SCAN_MODE)
1330
+ if ordering and not require_code:
1331
+ item = solve_sorted_list_merge_order(ordering)
1332
+ if item is not None:
1333
+ return {"results": json.dumps([item], ensure_ascii=False), "provider": "local merge-step check [verified]",
1334
+ "language": language, "answer_verified": True, "code_reviewed": False}
1320
1335
  if not require_code and not content.require_answer_agreement and content.practice_type in {'auto', 'mcq', 'math', 'aptitude'}:
1321
1336
  local_result = local_choice_result(trimmed_text, language)
1322
1337
  if local_result is not None:
@@ -1927,4 +1942,7 @@ if __name__ == "__main__":
1927
1942
  # loopback keeps direct local runs unavailable to other network devices.
1928
1943
  # Docker overrides SERVER_HOST because its published port is already bound
1929
1944
  # to the host loopback interface in docker-compose.yml.
1930
- 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
+ ))
@@ -167,6 +167,55 @@ def answer_permutation(value):
167
167
  and sorted(value) == list(range(1, len(value) + 1)))
168
168
 
169
169
 
170
+ def ordering_question(text):
171
+ prompt, separator, block = text.strip().rpartition('\nReorder ALL items.')
172
+ if not separator or not prompt:
173
+ return None
174
+ rows = block.splitlines()[1:]
175
+ if not 2 <= len(rows) <= 30:
176
+ return None
177
+ options = []
178
+ for index, line in enumerate(rows, 1):
179
+ match = re.fullmatch(rf'{index}\.\s+(\S.*)', line.strip())
180
+ if not match:
181
+ return None
182
+ options.append(match[1])
183
+ return prompt, options
184
+
185
+
186
+ def solve_sorted_list_merge_order(ordering):
187
+ if not ordering:
188
+ return None
189
+ prompt, options = ordering
190
+ if prompt.strip().rstrip(':').lower() != 'rearrange the steps to merge two sorted linked lists':
191
+ return None
192
+ steps = (
193
+ 'initialize pointers for the first and second list',
194
+ 'create a dummy node to serve as the head of the merged list',
195
+ 'traverse both lists simultaneously',
196
+ 'compare elements of both lists and link the smaller node to the merged list',
197
+ 'append remaining nodes of either list to the merged list',
198
+ 'return the merged list starting from the next of the dummy node',
199
+ )
200
+ normalized = [' '.join(option.split()).lower().rstrip('.') for option in options]
201
+ if len(normalized) != len(steps) or set(normalized) != set(steps):
202
+ return None
203
+ return {
204
+ 'type': 'mcq', 'question': prompt, 'answer': [normalized.index(step) + 1 for step in steps],
205
+ 'reasoning': 'Initialize both pointers and the dummy head before traversal. Compare and link nodes while both '
206
+ 'lists have items, append the remaining tail, then return the node after the dummy head.',
207
+ }
208
+
209
+
210
+ def ordering_key(value, size):
211
+ if isinstance(value, str):
212
+ try:
213
+ value = json.loads(value)
214
+ except ValueError:
215
+ return None
216
+ return tuple(value) if answer_permutation(value) and len(value) == size else None
217
+
218
+
170
219
  MATRIX_SYNTAX = re.compile(r'\\begin\{(?:[bpBvV]?matrix|smallmatrix)\}')
171
220
 
172
221
 
@@ -392,6 +441,52 @@ def displayed_single_choices(text):
392
441
  return parse_labeled_choices(option_text)
393
442
 
394
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
+
395
490
  def solve_row_parallel_choice(text):
396
491
  """Check the shared multiplication dimension in a row-parallel linear layer."""
397
492
  choices = displayed_single_choices(text)
@@ -449,11 +544,21 @@ async def cross_check_text_answers(messages, results, complete, *, question_text
449
544
  )
450
545
  check_messages = [{'role': 'system', 'content': instruction}, *messages[1:]]
451
546
  matrix_math = matrix_question(messages)
547
+ ordering = ordering_question(question_text)
548
+ if ordering and len(items) != 1:
549
+ raise VisionUnconfirmedError('Expected one answer containing all numbered steps.')
550
+ step_count = len(ordering[1]) if ordering else 0
452
551
  choices = displayed_single_choices(question_text) if len(items) == 1 else {}
453
552
  constraints = reading_response_constraints(question_text) if require_agreement and len(items) == 1 else None
454
- if require_agreement and not (choices or constraints):
553
+ if require_agreement and not (choices or constraints or step_count):
455
554
  raise VisionUnconfirmedError('Expected one linked answer with displayed options or a reading response format.')
456
- if constraints:
555
+ if step_count:
556
+ check_messages[0]['content'] = (
557
+ 'Independently order the displayed steps. Use every original item number once, check all prerequisite '
558
+ f'relationships, and return only JSON with readable=true and one answers entry with id=1. '
559
+ f'The answer value must be a JSON array of all {step_count} original item numbers in the correct order.'
560
+ )
561
+ elif constraints:
457
562
  _, _, keyword = constraints
458
563
  rule = (f'Use two to five words, including the unchanged word {keyword}. Preserve the meaning of the original sentence.'
459
564
  if keyword else 'Return exactly one word.')
@@ -461,6 +566,8 @@ async def cross_check_text_answers(messages, results, complete, *, question_text
461
566
  check_messages[0]['content'] = instruction
462
567
 
463
568
  def answer_key(entries):
569
+ if step_count:
570
+ return ordering_key(entries[0].get('answer'), step_count)
464
571
  if choices:
465
572
  return bind_displayed_choice(entries[0].get('answer'), choices, matrix_math=matrix_math)
466
573
  if constraints:
@@ -486,6 +593,11 @@ async def cross_check_text_answers(messages, results, complete, *, question_text
486
593
  except ValueError:
487
594
  current = None
488
595
  if current is not None and (current == first or current == previous):
596
+ if step_count:
597
+ if current != first:
598
+ items[0].pop('reasoning', None)
599
+ items[0]['answer'] = list(current)
600
+ return json.dumps(items, ensure_ascii=False)
489
601
  if choices:
490
602
  if current != first:
491
603
  items[0].pop('reasoning', None)
@@ -497,7 +609,7 @@ async def cross_check_text_answers(messages, results, complete, *, question_text
497
609
  items[0]['answer'] = ' '.join((items[0] if current == first else verified[0])['answer'].split())
498
610
  return json.dumps(items, ensure_ascii=False)
499
611
  return results
500
- if not (choices or constraints) and current is not None:
612
+ if not (choices or constraints or step_count) and current is not None:
501
613
  break
502
614
  if not attempt:
503
615
  previous = current
@@ -509,16 +621,18 @@ async def cross_check_text_answers(messages, results, complete, *, question_text
509
621
  # primary answer over blocking the automation entirely. The primary solve was
510
622
  # validated and the verification provider returned unusable JSON — a parsing
511
623
  # failure, not a disagreement — so a hard 422 is disproportionate.
512
- if not require_agreement and current is None and previous is None:
624
+ if not require_agreement and not step_count and current is None and previous is None:
513
625
  return results
514
626
  # For multi-answer questions (fill-in-the-blank), accept the primary answers
515
627
  # when the majority of individual answers agree with any independent solve.
516
- if not require_agreement and not choices and first is not None and len(first) > 1:
628
+ if not require_agreement and not choices and not step_count and first is not None and len(first) > 1:
517
629
  best = current or previous
518
630
  if best is not None:
519
631
  agreed = sum(a == b for a, b in zip(first, best))
520
632
  if agreed > len(first) // 2:
521
633
  return results
634
+ if step_count:
635
+ raise VisionUnconfirmedError('The independent checks could not confirm a complete order for the displayed steps.')
522
636
  raise VisionUnconfirmedError('The independent solves could not agree on the answer for this blank.' if constraints
523
637
  else 'The independent solves could not agree on the displayed answer.')
524
638
 
@@ -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