browser-assistant 2.8.25 → 2.9.0

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.
@@ -191,6 +191,7 @@ function mountJournalCountdown(signal) {
191
191
  let isHidden = false;
192
192
  let serverOnline = null; // null = unknown, true/false = checked
193
193
  let isScanning = false;
194
+ const pendingInference = new Set();
194
195
  let extensionAlive = true; // false after extension reload invalidates context
195
196
  let historyItems = [];
196
197
  let isHistoryOpen = false;
@@ -199,7 +200,17 @@ function mountJournalCountdown(signal) {
199
200
  state: 'IDLE', running: false, paused: false, runId: 0,
200
201
  processed: new Set(), completed: 0, error: '', currentSignature: '',
201
202
  };
202
- const updateListener = (request, _sender, sendResponse) => {
203
+ const updateListener = (request, sender, sendResponse) => {
204
+ if (request.action === 'assistantShowPanel' || request.action === 'assistantToggleAutomation') {
205
+ if (sender.id !== chrome.runtime.id)
206
+ return false;
207
+ if (request.action === 'assistantShowPanel')
208
+ openPanel();
209
+ else
210
+ toggleAutomation();
211
+ sendResponse({ ok: true });
212
+ return false;
213
+ }
203
214
  const busy = automation.running || isScanning || Boolean(window.BrowserAssistantJournalBusy);
204
215
  if (request.action === 'assistantUpdateStatus') {
205
216
  sendResponse({ busy });
@@ -218,6 +229,8 @@ function mountJournalCountdown(signal) {
218
229
  disposed = true;
219
230
  extensionAlive = false;
220
231
  automation.runId++;
232
+ for (const request of pendingInference)
233
+ request.abort();
221
234
  lifecycle.abort();
222
235
  for (const cleanup of navigationCleanup)
223
236
  cleanup();
@@ -267,15 +280,16 @@ function mountJournalCountdown(signal) {
267
280
  return false;
268
281
  return before.options.every((option, index) => normalizeAutomationText(option.identityText || option.text) === normalizeAutomationText(after.options[index]?.identityText || after.options[index]?.text));
269
282
  }
270
- function getAuthorizedQuestion(context = getAutomationContext()) {
283
+ function getAuthorizedQuestion(context = getAutomationContext(), manual = false) {
271
284
  // The dashboard contains mentor feedback radios, not quiz answers.
272
285
  if (window.location.origin === 'https://learning.ccbp.in' && window.location.pathname === '/')
273
286
  return null;
274
287
  // Problem-list filters are checkboxes, not an MCQ question.
275
288
  if (window.location.pathname.replace(/\/$/, '') === '/problems-set')
276
289
  return null;
277
- const adapter = getAutomationAdapter(context);
278
- if (!adapter || !automationPolicy.canExecute('detect', context) || !automationPolicy.canExecute('read', context))
290
+ const readOnly = manual && context.target?.assistOnly === true;
291
+ const adapter = readOnly ? automationPolicy.getAdapter('semantic-mcq') : getAutomationAdapter(context);
292
+ if (!adapter || (!readOnly && (!automationPolicy.canExecute('detect', context) || !automationPolicy.canExecute('read', context))))
279
293
  return null;
280
294
  const coding = window.BrowserAssistantCoding?.getQuestion(document);
281
295
  if (coding) {
@@ -298,7 +312,6 @@ function mountJournalCountdown(signal) {
298
312
  })), signature: questionSignature(question.identityText || question.text, question.options)
299
313
  + (window.BrowserAssistantQuestionVisuals?.nodes(question).length ? `|visual:${window.BrowserAssistantQuestionVisuals.fingerprint(question)}` : '') };
300
314
  }
301
- const AUTO_RESUME_KEY = 'browserAssistantResumeAuthorizedQa';
302
315
  function questionDetectionError() {
303
316
  const codingPage = window.location.origin === 'https://learning.ccbp.in'
304
317
  && /^\/question\//.test(window.location.pathname);
@@ -453,7 +466,7 @@ function mountJournalCountdown(signal) {
453
466
  }
454
467
  if (start) {
455
468
  start.disabled = current.running;
456
- start.textContent = '▶ Start journal automation';
469
+ start.textContent = '▶ Prepare journal draft';
457
470
  }
458
471
  if (pause) {
459
472
  pause.disabled = !current.running || current.submitting;
@@ -530,11 +543,12 @@ function mountJournalCountdown(signal) {
530
543
  updateAutomationUI();
531
544
  return;
532
545
  }
533
- try {
534
- sessionStorage.removeItem('browserAssistantCodingBatch');
546
+ for (const checkpointKind of ['practice', 'coding']) {
547
+ void safeSendMessage({ action: 'clearCheckpoint', checkpointKind }).catch(() => { });
535
548
  }
536
- catch { /* Stop must work when site storage is blocked. */ }
537
549
  automation.batch = null;
550
+ for (const request of pendingInference)
551
+ request.abort();
538
552
  automation.runId += 1;
539
553
  automation.running = false;
540
554
  automation.paused = false;
@@ -737,13 +751,11 @@ function mountJournalCountdown(signal) {
737
751
  }
738
752
  return false;
739
753
  }
740
- function saveCourseResume(stage, context, details = {}) {
741
- try {
742
- sessionStorage.setItem(AUTO_RESUME_KEY, JSON.stringify({
743
- stage, targetId: context.target.id, createdAt: Date.now(), ...details,
744
- }));
745
- }
746
- catch { /* Resuming after a full page navigation is optional. */ }
754
+ async function saveCheckpoint(kind, value, expectedUrl) {
755
+ return safeSendMessage({ action: 'saveCheckpoint', checkpointKind: kind, checkpoint: { kind, value, expectedUrl } });
756
+ }
757
+ function saveCourseResume(stage, context, control, details = {}) {
758
+ return saveCheckpoint('practice', { stage, targetId: context.target.id, ...details }, control.closest?.('a[href]')?.href);
747
759
  }
748
760
  async function waitForCourseAction(getAction, timeoutMs = 12000) {
749
761
  const deadline = Date.now() + timeoutMs;
@@ -755,6 +767,45 @@ function mountJournalCountdown(signal) {
755
767
  }
756
768
  return null;
757
769
  }
770
+ function reviewCodingAction(title, confirmLabel, current, proposed) {
771
+ return new Promise(resolve => {
772
+ const host = document.createElement('div');
773
+ const shadow = host.attachShadow({ mode: 'closed' });
774
+ const dialog = document.createElement('dialog');
775
+ dialog.setAttribute('aria-label', title);
776
+ dialog.style.cssText = 'max-width:92vw;max-height:85vh;padding:16px;color:#17233c;background:white;font:14px system-ui';
777
+ const heading = document.createElement('h2');
778
+ heading.textContent = title;
779
+ dialog.appendChild(heading);
780
+ for (const [label, code] of [['Current code', current], ['Proposed code', proposed]]) {
781
+ if (code === undefined)
782
+ continue;
783
+ const caption = document.createElement('h3');
784
+ caption.textContent = label;
785
+ const block = document.createElement('pre');
786
+ block.textContent = code;
787
+ block.style.cssText = 'max-height:24vh;max-width:82vw;overflow:auto;border:1px solid #aaa;padding:8px';
788
+ block.tabIndex = 0;
789
+ dialog.append(caption, block);
790
+ }
791
+ const cancel = document.createElement('button');
792
+ cancel.textContent = 'Cancel';
793
+ const approve = document.createElement('button');
794
+ approve.textContent = confirmLabel;
795
+ const finish = (accepted) => { clearTimeout(timeout); host.remove(); resolve(accepted); };
796
+ cancel.addEventListener('click', event => { if (event.isTrusted)
797
+ finish(false); });
798
+ approve.addEventListener('click', event => { if (event.isTrusted)
799
+ finish(true); });
800
+ dialog.addEventListener('cancel', event => { event.preventDefault(); finish(false); });
801
+ dialog.append(cancel, approve);
802
+ shadow.appendChild(dialog);
803
+ document.documentElement.appendChild(host);
804
+ const timeout = setTimeout(() => finish(false), 120000);
805
+ dialog.showModal();
806
+ cancel.focus();
807
+ });
808
+ }
758
809
  async function runCodingAutomation(question, runId, repairAttempt = 0, feedback = '', starterCode = null) {
759
810
  automation.codingQuestionText = question.text;
760
811
  const active = () => automation.running && automation.runId === runId;
@@ -789,7 +840,7 @@ function mountJournalCountdown(signal) {
789
840
  if (!webProject && response.data.code_reviewed !== true) {
790
841
  throw new Error('The running server has not enabled code review before submission. Restart the updated Browser Assistant server. No code was submitted.');
791
842
  }
792
- const results = typeof response.data.results === 'string' ? JSON.parse(response.data.results) : response.data.results;
843
+ const results = response.data.items ?? (typeof response.data.results === 'string' ? JSON.parse(response.data.results) : response.data.results);
793
844
  const solutions = results?.filter(item => item.type === 'code' && typeof item.code === 'string' && item.code.trim());
794
845
  if (solutions?.length !== 1)
795
846
  throw new Error('Expected one complete coding solution.');
@@ -810,6 +861,15 @@ function mountJournalCountdown(signal) {
810
861
  throw new Error('Starter code changed while generating the solution. Restart to use the current code.');
811
862
  if (getAuthorizedQuestion()?.signature !== question.signature)
812
863
  throw new Error('Question changed before code insertion.');
864
+ automation.state = 'WAITING_FOR_CODE_REVIEW';
865
+ updateAutomationUI();
866
+ if (!(await reviewCodingAction('Review the code change', 'Apply reviewed code', original.value, code))) {
867
+ if (active())
868
+ stopAutomation('REVIEW_NEEDED');
869
+ return false;
870
+ }
871
+ if (!(await waitWhilePaused(runId)) || getAuthorizedQuestion()?.signature !== question.signature)
872
+ return false;
813
873
  automation.state = 'FILLING_CODE';
814
874
  updateAutomationUI();
815
875
  const filled = await safeSendMessage({ action: 'codingEditor', operation: webProject ? 'writeProject' : 'write', selector: question.editorSelector, expected: original.value, value: code });
@@ -825,6 +885,19 @@ function mountJournalCountdown(signal) {
825
885
  const current = getAutomationContext();
826
886
  if (!verified?.ok || verified.value !== code || getAuthorizedQuestion(current)?.signature !== question.signature)
827
887
  throw new Error('Editor or question changed before submission.');
888
+ automation.state = 'WAITING_FOR_SUBMIT_APPROVAL';
889
+ updateAutomationUI();
890
+ if (!(await reviewCodingAction('Code applied. Submit for portal grading?', 'Submit for grading'))) {
891
+ if (active())
892
+ stopAutomation('REVIEW_NEEDED');
893
+ return false;
894
+ }
895
+ if (!(await waitWhilePaused(runId)))
896
+ return false;
897
+ const latest = await read();
898
+ if (!active() || latest?.value !== code || getAuthorizedQuestion()?.signature !== question.signature) {
899
+ throw Error('Editor or question changed after review.');
900
+ }
828
901
  const submit = window.BrowserAssistantCoding.getSubmit(document);
829
902
  if (!automationPolicy.canExecute('submit', current) || !submit)
830
903
  throw new Error('Code filled. No unique enabled Submit button found.');
@@ -908,7 +981,6 @@ function mountJournalCountdown(signal) {
908
981
  resultObserver?.disconnect();
909
982
  }
910
983
  }
911
- const CODING_BATCH_KEY = 'browserAssistantCodingBatch';
912
984
  function codingQuestionPath(value, baseUrl) {
913
985
  if (!value)
914
986
  return '';
@@ -954,10 +1026,12 @@ function mountJournalCountdown(signal) {
954
1026
  isCollapsed = false;
955
1027
  selectedTab = 'qa';
956
1028
  render();
957
- const persist = phase => {
1029
+ const persist = async (phase) => {
958
1030
  batch.phase = phase;
959
- batch.updatedAt = Date.now();
960
- sessionStorage.setItem(CODING_BATCH_KEY, JSON.stringify(batch));
1031
+ const expected = phase === 'question' ? batch.questionUrl : phase === 'list' ? batch.listUrl : location.href;
1032
+ const saved = await saveCheckpoint('coding', batch, expected);
1033
+ if (!saved?.ok)
1034
+ throw Error('Could not save the coding checkpoint. Restart from the problem list.');
961
1035
  };
962
1036
  const waitFor = async (predicate, timeout = 20000) => {
963
1037
  const deadline = Date.now() + timeout;
@@ -995,7 +1069,7 @@ function mountJournalCountdown(signal) {
995
1069
  return;
996
1070
  if (!question)
997
1071
  throw new Error(window.BrowserAssistantCoding.getDetectionError() || 'Selected coding question did not load or its title did not match.');
998
- persist('busy');
1072
+ await persist('busy');
999
1073
  const passed = await runCodingAutomation(question, runId);
1000
1074
  if (!passed || !automation.running || automation.runId !== runId)
1001
1075
  return;
@@ -1005,13 +1079,15 @@ function mountJournalCountdown(signal) {
1005
1079
  rememberCompletedCodingQuestion(batch);
1006
1080
  batch.completed = automation.completed;
1007
1081
  }
1008
- persist('list');
1082
+ await persist('list');
1009
1083
  automation.state = 'RETURNING_TO_LIST';
1010
1084
  automation.pendingNavigation = true;
1011
1085
  updateAutomationUI();
1012
1086
  const back = window.BrowserAssistantCodingBatch.getBackControl(document, batch.listUrl);
1013
1087
  if (!back)
1014
1088
  throw new Error('Accepted. Question Bank Back button was not found; return to the list to continue.');
1089
+ if (!(await waitWhilePaused(runId)))
1090
+ return;
1015
1091
  back.click();
1016
1092
  let saveConfirmed = false;
1017
1093
  const returned = await waitFor(() => {
@@ -1033,7 +1109,7 @@ function mountJournalCountdown(signal) {
1033
1109
  throw new Error('Accepted. Back was clicked, but the problem list did not load.');
1034
1110
  visited.clear();
1035
1111
  batch.title = '';
1036
- persist('list');
1112
+ await persist('list');
1037
1113
  continue;
1038
1114
  }
1039
1115
  automation.state = 'FINDING_UNSOLVED';
@@ -1061,10 +1137,12 @@ function mountJournalCountdown(signal) {
1061
1137
  if (next) {
1062
1138
  batch.title = next.title;
1063
1139
  batch.questionUrl = next.href || null;
1064
- persist('question');
1140
+ await persist('question');
1065
1141
  automation.state = 'OPENING_QUESTION';
1066
1142
  automation.pendingNavigation = true;
1067
1143
  updateAutomationUI();
1144
+ if (!(await waitWhilePaused(runId)))
1145
+ return;
1068
1146
  next.action.click();
1069
1147
  continue;
1070
1148
  }
@@ -1081,10 +1159,12 @@ function mountJournalCountdown(signal) {
1081
1159
  }
1082
1160
  throw new Error('No Not Attempted or In Progress questions on this page; the next-page control could not be identified.');
1083
1161
  }
1084
- persist('list');
1162
+ await persist('list');
1085
1163
  automation.state = 'NEXT_LIST_PAGE';
1086
1164
  automation.pendingNavigation = true;
1087
1165
  updateAutomationUI();
1166
+ if (!(await waitWhilePaused(runId)))
1167
+ return;
1088
1168
  nextPage.click();
1089
1169
  const changed = await waitFor(() => {
1090
1170
  const updated = window.BrowserAssistantCodingBatch.pageRange(document);
@@ -1104,20 +1184,11 @@ function mountJournalCountdown(signal) {
1104
1184
  }
1105
1185
  }
1106
1186
  async function resumeCodingBatch() {
1107
- let saved;
1108
- try {
1109
- saved = JSON.parse(sessionStorage.getItem(CODING_BATCH_KEY) || 'null');
1110
- }
1111
- catch {
1112
- return false;
1113
- }
1114
- if (!saved)
1187
+ const generation = automation.runId;
1188
+ const response = await safeSendMessage({ action: 'takeCheckpoint', checkpointKind: 'coding' }).catch(() => null);
1189
+ if (!response?.checkpoint || generation !== automation.runId || automation.running)
1115
1190
  return false;
1116
- if (saved.origin !== location.origin || Date.now() - saved.updatedAt > 120000) {
1117
- sessionStorage.removeItem(CODING_BATCH_KEY);
1118
- return false;
1119
- }
1120
- await startCodingBatch(saved);
1191
+ await startCodingBatch(response.checkpoint);
1121
1192
  return true;
1122
1193
  }
1123
1194
  async function runOnlineIdeAutomation(question) {
@@ -1158,20 +1229,32 @@ function mountJournalCountdown(signal) {
1158
1229
  return ide;
1159
1230
  }
1160
1231
  try {
1161
- const [ide, response] = await Promise.all([openOnlineIde(), apiRequest('/solve', 'POST', {
1162
- url, practice_type: 'code', language: 'javascript', review_before_submit: true,
1163
- text: `${question.text}\n\nGenerate the complete app.js for the online Node.js IDE. Use the stated database, route methods, response bodies and module format. Use parameterized SQL where applicable. Return source code for app.js only.`,
1164
- })]);
1232
+ const response = await apiRequest('/solve', 'POST', {
1233
+ url, practice_type: 'code', language: 'javascript', review_before_submit: true,
1234
+ text: `${question.text}\n\nGenerate the complete app.js for the online Node.js IDE. Use the stated database, route methods, response bodies and module format. Use parameterized SQL where applicable. Return source code for app.js only.`,
1235
+ });
1165
1236
  if (!(await waitWhilePaused(runId)) || !current())
1166
1237
  return;
1167
1238
  if (!response?.ok)
1168
1239
  throw window.BrowserAssistantAnswerRequests.failure(response);
1169
- const solutions = JSON.parse(response.data.results);
1240
+ const solutions = response.data.items ?? JSON.parse(response.data.results);
1170
1241
  if (!Array.isArray(solutions) || solutions.length !== 1 || solutions[0].type !== 'code'
1171
1242
  || typeof solutions[0].code !== 'string' || !solutions[0].code.trim()) {
1172
1243
  throw new Error('The server did not return a complete app.js solution.');
1173
1244
  }
1174
1245
  const solution = solutions[0];
1246
+ automation.state = 'WAITING_FOR_CODE_REVIEW';
1247
+ updateAutomationUI();
1248
+ if (!(await reviewCodingAction('Review the proposed app.js', 'Open IDE and apply', undefined, solution.code))) {
1249
+ if (current())
1250
+ stopAutomation('REVIEW_NEEDED');
1251
+ return;
1252
+ }
1253
+ if (!(await waitWhilePaused(runId)) || !current())
1254
+ return;
1255
+ const ide = await openOnlineIde();
1256
+ if (!current())
1257
+ return;
1175
1258
  let instructions = ide?.found
1176
1259
  ? 'Copy into app.js in the IDE tab after the workspace is ready, then save.'
1177
1260
  : 'Use the portal Open IDE button, then copy into app.js and save.';
@@ -1199,7 +1282,7 @@ function mountJournalCountdown(signal) {
1199
1282
  return;
1200
1283
  }
1201
1284
  if (launched?.started) {
1202
- automation.state = 'WAITING_FOR_IDE_GRADING';
1285
+ automation.state = 'VERIFYING_IDE_SAVE';
1203
1286
  updateAutomationUI();
1204
1287
  const resultDeadline = Date.now() + 240000;
1205
1288
  while (current() && Date.now() < resultDeadline) {
@@ -1209,13 +1292,17 @@ function mountJournalCountdown(signal) {
1209
1292
  if (!current())
1210
1293
  return;
1211
1294
  if (result?.done) {
1212
- if (result.passed)
1295
+ if (result.saved) {
1213
1296
  automation.completed = 1;
1214
- else if (result.saveUnconfirmed)
1215
- automation.error = 'Code was pasted into app.js, but the saved file did not match. Check app.js and save before running it.';
1216
- else
1217
- automation.error = result.submitted ? 'Grading finished. Review the test results in the IDE.' : 'The IDE command finished without a confirmed submission. Check the terminal.';
1218
- stopAutomation(result.passed ? 'COMPLETED' : 'CHECK_IDE_RESULT');
1297
+ stopAutomation('IDE_READY_FOR_GRADING');
1298
+ displayResults([{ ...solution, title: 'app.js', approach: 'Saved and syntax checked. Use the portal grading command when you are ready.' }], response.data.provider);
1299
+ }
1300
+ else {
1301
+ automation.error = result.saveUnconfirmed
1302
+ ? 'Code was pasted, but the saved file did not match. Check app.js and save it.'
1303
+ : 'JavaScript syntax check failed. Review the IDE terminal.';
1304
+ stopAutomation('CHECK_IDE_RESULT');
1305
+ }
1219
1306
  return;
1220
1307
  }
1221
1308
  if (result?.ok === false && !result.retry)
@@ -1352,7 +1439,10 @@ function mountJournalCountdown(signal) {
1352
1439
  automation.state = 'STARTING_PRACTICE';
1353
1440
  automation.targetId = initialContext.target.id;
1354
1441
  updateAutomationUI();
1355
- saveCourseResume('solve', initialContext);
1442
+ const generation = ++automation.runId;
1443
+ await saveCourseResume('solve', initialContext, startPractice);
1444
+ if (generation !== automation.runId)
1445
+ return;
1356
1446
  startPractice.click();
1357
1447
  setTimeout(() => { void resumeAuthorizedQaAfterNavigation(); }, 900);
1358
1448
  return;
@@ -1454,10 +1544,9 @@ function mountJournalCountdown(signal) {
1454
1544
  automation.pendingNavigation = true;
1455
1545
  updateAutomationUI();
1456
1546
  const previousUrl = window.location.href;
1457
- try {
1458
- sessionStorage.setItem(AUTO_RESUME_KEY, JSON.stringify({ targetId: automation.targetId, fromUrl: previousUrl, createdAt: Date.now() }));
1459
- }
1460
- catch { /* Resuming after a full page navigation is optional. */ }
1547
+ await saveCourseResume('solve', context, nextPractice);
1548
+ if (!(await waitWhilePaused(runId)))
1549
+ return;
1461
1550
  nextPractice.click();
1462
1551
  if (!(await waitForNextPracticeQuestion(previousUrl, runId))) {
1463
1552
  automation.error = 'Next practice did not load in time.';
@@ -1570,7 +1659,7 @@ function mountJournalCountdown(signal) {
1570
1659
  }
1571
1660
  let results;
1572
1661
  try {
1573
- results = JSON.parse(response.data.results);
1662
+ results = response.data.items ?? JSON.parse(response.data.results);
1574
1663
  }
1575
1664
  catch {
1576
1665
  automation.error = 'AI returned an invalid answer.';
@@ -1730,10 +1819,14 @@ function mountJournalCountdown(signal) {
1730
1819
  automation.state = 'OPENING_COURSE';
1731
1820
  automation.pendingNavigation = true;
1732
1821
  updateAutomationUI();
1733
- saveCourseResume('course', transition.context, {
1822
+ await saveCourseResume('course', transition.context, transition.proceed, {
1734
1823
  currentTitle: currentAdapter.getCurrentPracticeTitle?.(document) || '',
1735
1824
  });
1825
+ if (!(await waitWhilePaused(runId)))
1826
+ return;
1827
+ automation.running = false;
1736
1828
  transition.proceed.click();
1829
+ setTimeout(() => { void resumeAuthorizedQaAfterNavigation(); }, 900);
1737
1830
  return;
1738
1831
  }
1739
1832
  if (transition?.advance) {
@@ -1858,7 +1951,20 @@ function mountJournalCountdown(signal) {
1858
1951
  // Route local API traffic through the extension service worker instead of
1859
1952
  // the page context, so visited sites cannot directly access the API.
1860
1953
  async function apiRequest(path, method = 'POST', body) {
1861
- const response = await safeSendMessage({ action: 'apiRequest', path, method, body }, 370000);
1954
+ let response;
1955
+ if (method === 'POST' && ['/solve', '/solve-vision'].includes(path)) {
1956
+ const request = new AbortController();
1957
+ pendingInference.add(request);
1958
+ try {
1959
+ response = await browserAssistantLocalInference(path, body, msg => safeSendMessage(msg, 15000), request.signal);
1960
+ }
1961
+ finally {
1962
+ pendingInference.delete(request);
1963
+ }
1964
+ }
1965
+ else {
1966
+ response = await safeSendMessage({ action: 'apiRequest', path, method, body }, 15000);
1967
+ }
1862
1968
  if (!response)
1863
1969
  throw new Error('Local server did not respond');
1864
1970
  if (response.error)
@@ -1867,9 +1973,12 @@ function mountJournalCountdown(signal) {
1867
1973
  }
1868
1974
  async function saveScanHistory(results, provider, scanType, language = null) {
1869
1975
  try {
1976
+ if (!(await chrome.storage.local.get({ assistantSaveHistory: false })).assistantSaveHistory)
1977
+ return;
1978
+ const page = new URL(location.href);
1870
1979
  const response = await apiRequest('/history', 'POST', {
1871
1980
  scan_type: scanType,
1872
- url: window.location.href,
1981
+ url: page.origin + page.pathname,
1873
1982
  provider: provider || 'unknown',
1874
1983
  results: JSON.stringify(results),
1875
1984
  language,
@@ -1890,7 +1999,14 @@ function mountJournalCountdown(signal) {
1890
1999
  const response = await apiRequest('/history', 'GET');
1891
2000
  if (!response.ok)
1892
2001
  throw new Error(response.data?.detail || 'Could not load history');
1893
- historyItems = response.data?.items || [];
2002
+ historyItems = (response.data?.items || []).filter(item => {
2003
+ try {
2004
+ return new URL(item.url).origin === location.origin;
2005
+ }
2006
+ catch {
2007
+ return false;
2008
+ }
2009
+ });
1894
2010
  renderHistory();
1895
2011
  }
1896
2012
  catch (error) {
@@ -2058,11 +2174,15 @@ function mountJournalCountdown(signal) {
2058
2174
  root.style.display = 'none';
2059
2175
  }
2060
2176
  function handleAutomationShortcut(e) {
2061
- if (e.repeat || e.isComposing || e.defaultPrevented || !e.altKey || e.ctrlKey || e.metaKey
2177
+ if (!e.isTrusted || e.repeat || e.isComposing || e.defaultPrevented || !e.altKey || e.ctrlKey || e.metaKey
2062
2178
  || (e.code !== 'KeyA' && String(e.key).toLowerCase() !== 'a'))
2063
2179
  return false;
2064
2180
  e.preventDefault();
2065
2181
  e.stopPropagation();
2182
+ toggleAutomation();
2183
+ return true;
2184
+ }
2185
+ function toggleAutomation() {
2066
2186
  selectedTab = 'qa';
2067
2187
  isHidden = false;
2068
2188
  isCollapsed = false;
@@ -2082,12 +2202,11 @@ function mountJournalCountdown(signal) {
2082
2202
  stopAutomation('ERROR');
2083
2203
  });
2084
2204
  }
2085
- return true;
2086
2205
  }
2087
2206
  // ── Keyboard shortcuts ────────────────────────────────────────────────────
2088
2207
  document.addEventListener('keydown', (e) => {
2089
2208
  // Block held-key auto-repeat to prevent rapid-fire race conditions
2090
- if (e.repeat || e.isComposing)
2209
+ if (!e.isTrusted || e.repeat || e.isComposing)
2091
2210
  return;
2092
2211
  // Explicit automation chord also works while the code editor has focus.
2093
2212
  if (handleAutomationShortcut(e))
@@ -2158,10 +2277,18 @@ function mountJournalCountdown(signal) {
2158
2277
  }
2159
2278
  else {
2160
2279
  await new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)));
2161
- const response = await safeSendMessage({ action: "captureVisibleTab" });
2280
+ const response = await safeSendMessage({ action: 'captureVisibleTab', url: context.url });
2162
2281
  if (!response?.dataUrl || response.error)
2163
2282
  throw new Error(response?.error || 'Screenshot capture failed');
2164
- images = [response.dataUrl];
2283
+ root.style.visibility = panelVisibility;
2284
+ if (journalCountdownBadge)
2285
+ journalCountdownBadge.style.visibility = countdownVisibility;
2286
+ const reviewed = await visuals.reviewCapture(response.dataUrl, context.question);
2287
+ if (!reviewed) {
2288
+ render();
2289
+ return;
2290
+ }
2291
+ images = [reviewed];
2165
2292
  }
2166
2293
  root.style.visibility = panelVisibility;
2167
2294
  if (journalCountdownBadge)
@@ -2184,7 +2311,7 @@ function mountJournalCountdown(signal) {
2184
2311
  await assertVisionQuestionCurrent(context);
2185
2312
  let parsed;
2186
2313
  try {
2187
- parsed = JSON.parse(data.results);
2314
+ parsed = data.items ?? JSON.parse(data.results);
2188
2315
  }
2189
2316
  catch (e) {
2190
2317
  throw new Error('Vision returned an invalid answer format. Please scan a clear, complete question again.');
@@ -2233,7 +2360,7 @@ function mountJournalCountdown(signal) {
2233
2360
  }
2234
2361
  }
2235
2362
  async function prepareVisionQuestionContext() {
2236
- const context = { url: location.href, text: '', question: getAuthorizedQuestion() };
2363
+ const context = { url: location.href, text: '', question: getAuthorizedQuestion(undefined, true) };
2237
2364
  if (!context.question || context.question.type === 'code') {
2238
2365
  context.question = null;
2239
2366
  return context;
@@ -2268,7 +2395,7 @@ function mountJournalCountdown(signal) {
2268
2395
  throw new Error('Page changed while scanning. Please scan the current question again.');
2269
2396
  if (!context.question)
2270
2397
  return;
2271
- const fresh = getAuthorizedQuestion();
2398
+ const fresh = getAuthorizedQuestion(undefined, true);
2272
2399
  if (!hasSameQuestionOptions(context.question, fresh)
2273
2400
  || (context.visualSnapshot && window.BrowserAssistantQuestionVisuals.fingerprint(fresh) !== context.visualSnapshot)) {
2274
2401
  throw new Error('Question or illustration changed while scanning. Please scan again.');
@@ -2336,7 +2463,7 @@ function mountJournalCountdown(signal) {
2336
2463
  serverOnline = true;
2337
2464
  let parsed;
2338
2465
  try {
2339
- parsed = JSON.parse(data.results);
2466
+ parsed = data.items ?? JSON.parse(data.results);
2340
2467
  }
2341
2468
  catch (e) {
2342
2469
  if (question || practiceType !== 'code')
@@ -2425,7 +2552,8 @@ function mountJournalCountdown(signal) {
2425
2552
  const retry = document.createElement('button');
2426
2553
  retry.className = 'assistant-history-btn';
2427
2554
  retry.textContent = 'Retry history';
2428
- retry.onclick = openHistory;
2555
+ retry.onclick = event => { if (event.isTrusted)
2556
+ void openHistory(); };
2429
2557
  container.append(error, retry);
2430
2558
  }
2431
2559
  function renderHistory() {
@@ -2436,7 +2564,7 @@ function mountJournalCountdown(signal) {
2436
2564
  const header = document.createElement('div');
2437
2565
  header.className = 'assistant-history-header';
2438
2566
  const title = document.createElement('strong');
2439
- title.textContent = 'Recent scans';
2567
+ title.textContent = 'Recent scans on this site';
2440
2568
  const actions = document.createElement('div');
2441
2569
  const back = document.createElement('button');
2442
2570
  back.className = 'assistant-history-action';
@@ -2447,8 +2575,11 @@ function mountJournalCountdown(signal) {
2447
2575
  const clear = document.createElement('button');
2448
2576
  clear.className = 'assistant-history-action danger';
2449
2577
  clear.id = 'assistant-clear-history-btn';
2450
- clear.textContent = 'Clear';
2451
- clear.onclick = clearHistory;
2578
+ clear.textContent = 'Clear all sites';
2579
+ clear.onclick = event => {
2580
+ if (event.isTrusted && window.confirm('Delete saved scans for all sites?'))
2581
+ void clearHistory();
2582
+ };
2452
2583
  actions.appendChild(clear);
2453
2584
  }
2454
2585
  header.append(title, actions);
@@ -2456,7 +2587,7 @@ function mountJournalCountdown(signal) {
2456
2587
  if (!historyItems.length) {
2457
2588
  const empty = document.createElement('div');
2458
2589
  empty.className = 'assistant-placeholder';
2459
- empty.textContent = 'No saved scans yet. Run Text Scan or Vision Scan to build your history.';
2590
+ empty.textContent = 'No saved scans for this site. Enable Save scan history in the toolbar popup to keep future scans.';
2460
2591
  container.appendChild(empty);
2461
2592
  return;
2462
2593
  }
@@ -2691,10 +2822,19 @@ function mountJournalCountdown(signal) {
2691
2822
  document.getElementById('mode-code').onclick = () => selectTab('code');
2692
2823
  document.getElementById('mode-qa').onclick = () => selectTab('qa');
2693
2824
  bindTabKeyboardNavigation();
2694
- document.getElementById('assistant-history-btn').onclick = openHistory;
2695
- document.getElementById('assistant-scan-btn')?.addEventListener('click', scanPage);
2696
- document.getElementById('assistant-vision-btn')?.addEventListener('click', visionScan);
2697
- document.getElementById('assistant-auto-start-btn')?.addEventListener('click', startPracticeAutomation);
2825
+ document.getElementById('assistant-history-btn').onclick = event => { if (event.isTrusted)
2826
+ void openHistory(); };
2827
+ document.getElementById('assistant-scan-btn')?.addEventListener('click', event => { if (event.isTrusted)
2828
+ void scanPage(); });
2829
+ document.getElementById('assistant-vision-btn')?.addEventListener('click', event => { if (event.isTrusted)
2830
+ void visionScan(); });
2831
+ document.getElementById('assistant-auto-start-btn')?.addEventListener('click', event => {
2832
+ if (event.isTrusted)
2833
+ void startPracticeAutomation().catch(error => {
2834
+ automation.error = error.message;
2835
+ stopAutomation('ERROR');
2836
+ });
2837
+ });
2698
2838
  document.getElementById('assistant-export-question-btn')?.addEventListener('click', exportQuestionDiagnostic);
2699
2839
  document.getElementById('assistant-auto-pause-btn')?.addEventListener('click', pauseOrResumeAutomation);
2700
2840
  document.getElementById('assistant-auto-stop-btn')?.addEventListener('click', () => stopAutomation());
@@ -2757,14 +2897,12 @@ function mountJournalCountdown(signal) {
2757
2897
  }
2758
2898
  }
2759
2899
  function renderFullResults(container, results, provider) {
2760
- // Show provider with verified badge if applicable
2761
2900
  provider = provider || "unknown";
2762
- const isVerified = provider.includes('[verified]');
2763
- const safeProvider = escapeHtml(provider.toUpperCase());
2764
- const providerBadge = isVerified
2765
- ? `<div class="assistant-provider-badge verified">✅ via ${safeProvider}</div>`
2766
- : `<div class="assistant-provider-badge">via ${safeProvider}</div>`;
2767
- container.innerHTML = providerBadge;
2901
+ const evidence = provider.includes('[verified]') ? 'Calculated locally'
2902
+ : provider.includes('[cross-checked]') ? 'Model agreement'
2903
+ : 'Provider result';
2904
+ const safeProvider = escapeHtml(provider.replace(/\s*\[(?:verified|cross-checked)\]/g, ''));
2905
+ container.innerHTML = `<div class="assistant-provider-badge">${evidence} · ${safeProvider}</div>`;
2768
2906
  results.forEach((res, index) => {
2769
2907
  if (res.type === 'code') {
2770
2908
  const codeContent = res.code || res.answer || "";
@@ -2856,17 +2994,12 @@ function mountJournalCountdown(signal) {
2856
2994
  }
2857
2995
  }
2858
2996
  async function resumeAuthorizedQaAfterNavigation() {
2859
- let resume;
2860
- try {
2861
- resume = JSON.parse(sessionStorage.getItem(AUTO_RESUME_KEY) || 'null');
2862
- sessionStorage.removeItem(AUTO_RESUME_KEY);
2863
- }
2864
- catch {
2865
- return;
2866
- }
2997
+ const generation = automation.runId;
2998
+ const response = await safeSendMessage({ action: 'takeCheckpoint', checkpointKind: 'practice' }).catch(() => null);
2999
+ const resume = response?.checkpoint;
2867
3000
  const context = getAutomationContext();
2868
- const isFresh = Number.isFinite(resume?.createdAt) && Date.now() - resume.createdAt < 120000;
2869
- if (!isFresh || resume.targetId !== context.target?.id || context.mode !== 'FULL')
3001
+ if (generation !== automation.runId || automation.running || !resume
3002
+ || resume.targetId !== context.target?.id || context.mode !== 'FULL')
2870
3003
  return;
2871
3004
  isCollapsed = false;
2872
3005
  render();
@@ -2883,9 +3016,11 @@ function mountJournalCountdown(signal) {
2883
3016
  }
2884
3017
  automation.state = 'OPENING_NEXT_PRACTICE';
2885
3018
  updateAutomationUI();
2886
- saveCourseResume('start', context);
2887
- nextPractice.scrollIntoView({ block: 'center', behavior: 'smooth' });
2888
- setTimeout(() => nextPractice.click(), 250);
3019
+ await saveCourseResume('start', context, nextPractice);
3020
+ if (generation !== automation.runId || !nextPractice.isConnected)
3021
+ return;
3022
+ nextPractice.scrollIntoView({ block: 'center' });
3023
+ nextPractice.click();
2889
3024
  setTimeout(() => { void resumeAuthorizedQaAfterNavigation(); }, 900);
2890
3025
  return;
2891
3026
  }
@@ -2899,7 +3034,9 @@ function mountJournalCountdown(signal) {
2899
3034
  }
2900
3035
  automation.state = 'STARTING_PRACTICE';
2901
3036
  updateAutomationUI();
2902
- saveCourseResume('solve', context);
3037
+ await saveCourseResume('solve', context, startPractice);
3038
+ if (generation !== automation.runId || !startPractice.isConnected)
3039
+ return;
2903
3040
  startPractice.click();
2904
3041
  setTimeout(() => { void resumeAuthorizedQaAfterNavigation(); }, 900);
2905
3042
  return;
@@ -2913,7 +3050,8 @@ function mountJournalCountdown(signal) {
2913
3050
  return;
2914
3051
  }
2915
3052
  }
2916
- void startPracticeAutomation();
3053
+ if (generation === automation.runId)
3054
+ void startPracticeAutomation();
2917
3055
  }
2918
3056
  let reopenedAfterUpdate = false;
2919
3057
  try {