browser-assistant 2.9.2 → 2.9.4

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.
@@ -9,27 +9,33 @@ function mountJournalCountdown(signal) {
9
9
  let timers = [];
10
10
  let tick;
11
11
  let revision = 0;
12
- function renderCountdown() {
13
- window.clearTimeout(tick);
14
- if (signal.aborted)
15
- return;
12
+ function getCountdownLabel() {
16
13
  const now = Date.now();
17
- const active = timers.filter(timer => timer.deadline > now);
18
14
  const path = location.pathname.replace(/\/$/, '');
19
15
  const aurora = location.origin === 'https://admissions.aurora.edu.in';
20
- const visible = active.filter(timer => !aurora || (path.startsWith('/modules/reflective-journal/') && timer.path !== path));
16
+ const visible = timers.filter(timer => timer.deadline > now
17
+ && (!aurora || (path.startsWith('/modules/reflective-journal/') && timer.path !== path)));
21
18
  if (!visible.length)
19
+ return '';
20
+ const times = visible.map(timer => {
21
+ const seconds = Math.ceil((timer.deadline - now) / 1000);
22
+ return `${String(Math.floor(seconds / 60)).padStart(2, '0')}:${String(seconds % 60).padStart(2, '0')}`;
23
+ });
24
+ return `${times.length === 1 ? 'Journal time left' : 'Journal times left'} ≈ ${times.join(' · ')}`;
25
+ }
26
+ function renderCountdown() {
27
+ window.clearTimeout(tick);
28
+ if (signal.aborted)
29
+ return;
30
+ const label = getCountdownLabel();
31
+ if (!label)
22
32
  badge.remove();
23
33
  else {
24
- const times = visible.map(timer => {
25
- const seconds = Math.ceil((timer.deadline - now) / 1000);
26
- return `${String(Math.floor(seconds / 60)).padStart(2, '0')}:${String(seconds % 60).padStart(2, '0')}`;
27
- });
28
- clock.textContent = `${times.length === 1 ? 'Journal time left' : 'Journal times left'} ≈ ${times.join(' · ')}`;
34
+ clock.textContent = label;
29
35
  if (!badge.isConnected)
30
36
  document.body.appendChild(badge);
31
37
  }
32
- if (active.length && !document.hidden)
38
+ if (label && !document.hidden)
33
39
  tick = window.setTimeout(renderCountdown, 1000);
34
40
  }
35
41
  async function refreshCountdown() {
@@ -56,11 +62,11 @@ function mountJournalCountdown(signal) {
56
62
  badge.remove();
57
63
  }, { once: true });
58
64
  void refreshCountdown();
59
- return badge;
65
+ return { badge, getCountdownLabel };
60
66
  }
61
67
  (function () {
62
68
  // Abort on pages without a body (about:blank, PDFs, XML docs, etc.)
63
- if (!document.body)
69
+ if (!document.body || document.getElementById('assistant-root'))
64
70
  return;
65
71
  const extensionVersion = chrome.runtime.getManifest().version;
66
72
  const lifecycle = new AbortController();
@@ -80,9 +86,12 @@ function mountJournalCountdown(signal) {
80
86
  const SERVER = 'http://localhost:8000';
81
87
  const root = document.createElement('div');
82
88
  root.id = 'assistant-root';
89
+ root.classList.add('assistant-panel-initializing');
83
90
  document.body.appendChild(root);
84
- const journalCountdownBadge = ['http:', 'https:'].includes(location.protocol)
91
+ const journalCountdown = ['http:', 'https:'].includes(location.protocol)
85
92
  ? mountJournalCountdown(lifecycle.signal) : null;
93
+ const journalCountdownBadge = journalCountdown?.badge;
94
+ journalCountdownBadge?.classList.add('assistant-panel-initializing');
86
95
  // ── Move panel ───────────────────────────────────────────────────────────
87
96
  // Drag the header to put the panel anywhere on the current page. The saved
88
97
  // location is restored after a refresh on that site.
@@ -91,8 +100,8 @@ function mountJournalCountdown(signal) {
91
100
  let suppressNextClick = false;
92
101
  function clampPanelPosition(x, y) {
93
102
  return {
94
- x: Math.max(0, Math.min(window.innerWidth - root.offsetWidth, x)),
95
- y: Math.max(0, Math.min(window.innerHeight - root.offsetHeight, y)),
103
+ x: Math.max(4, Math.min(window.innerWidth - root.offsetWidth - 4, x)),
104
+ y: Math.max(4, Math.min(window.innerHeight - root.offsetHeight - 4, y)),
96
105
  };
97
106
  }
98
107
  function setPanelPosition(x, y) {
@@ -142,7 +151,7 @@ function mountJournalCountdown(signal) {
142
151
  }
143
152
  setPanelPosition(dragState.origX + event.clientX - dragState.startX, dragState.origY + event.clientY - dragState.startY);
144
153
  });
145
- const stopDragging = () => {
154
+ const stopDragging = (event) => {
146
155
  if (!dragState.dragging)
147
156
  return;
148
157
  suppressNextClick = dragState.moved;
@@ -161,7 +170,7 @@ function mountJournalCountdown(signal) {
161
170
  }
162
171
  // Pointer capture retargets the eventual click to the root, so a
163
172
  // stationary badge press must open here rather than lose its click.
164
- if (!dragState.moved && dragState.collapsedBadge)
173
+ if (event.type === 'pointerup' && !dragState.moved && dragState.collapsedBadge)
165
174
  openPanel();
166
175
  };
167
176
  root.addEventListener('pointerup', stopDragging);
@@ -175,12 +184,22 @@ function mountJournalCountdown(signal) {
175
184
  }, true);
176
185
  window.addEventListener('resize', () => {
177
186
  const rect = root.getBoundingClientRect();
178
- if (root.style.left)
187
+ if (root.style.left && root.offsetWidth)
179
188
  setPanelPosition(rect.left, rect.top);
180
189
  }, { signal: lifecycle.signal });
181
190
  }
182
191
  initDrag();
183
192
  restorePanelPosition();
193
+ const panelResizeObserver = new ResizeObserver(() => {
194
+ if (!root.style.left || !root.offsetWidth || dragState.dragging)
195
+ return;
196
+ const { left, top } = root.getBoundingClientRect();
197
+ const { x, y } = clampPanelPosition(left, top);
198
+ if (left !== x || top !== y)
199
+ setPanelPosition(left, top);
200
+ });
201
+ panelResizeObserver.observe(root);
202
+ lifecycle.signal.addEventListener('abort', () => panelResizeObserver.disconnect(), { once: true });
184
203
  let isCollapsed = true;
185
204
  // Scan type and visible tab are intentionally separate. Switching away
186
205
  // from QA Control must never stop an authorized automation run.
@@ -199,7 +218,132 @@ function mountJournalCountdown(signal) {
199
218
  state: 'IDLE', running: false, paused: false, runId: 0,
200
219
  processed: new Set(), completed: 0, error: '', currentSignature: '',
201
220
  };
202
- const updateListener = (request, _sender, sendResponse) => {
221
+ const directRunKey = 'browserAssistantDirectRun';
222
+ let directRun = null;
223
+ let directRunStarting = false;
224
+ let noticeTimer;
225
+ let automationNotice = '';
226
+ try {
227
+ const saved = JSON.parse(sessionStorage.getItem(directRunKey) || 'null');
228
+ if (saved?.status === 'Running' && new URL(saved.url).origin === location.origin
229
+ && Date.now() - Date.parse(saved.started_at) < 8 * 60 * 60 * 1000)
230
+ directRun = saved;
231
+ }
232
+ catch { /* The shortcut still works when storage is unavailable. */ }
233
+ let panelToken = '';
234
+ let floatingMinimal = false;
235
+ const panelControlSelector = 'button,select,textarea,summary';
236
+ const panelControls = new WeakMap();
237
+ const panelDocumentId = crypto.randomUUID();
238
+ let panelControlId = 0;
239
+ function setDetachedPanel(token) {
240
+ if (token && !panelToken) {
241
+ floatingMinimal = isMinimalMode;
242
+ isMinimalMode = false;
243
+ openPanel();
244
+ }
245
+ else if (!token && panelToken) {
246
+ isMinimalMode = floatingMinimal;
247
+ }
248
+ panelToken = token;
249
+ root.classList.toggle('assistant-detached', Boolean(token));
250
+ journalCountdownBadge?.classList.toggle('assistant-detached', Boolean(token));
251
+ }
252
+ function panelSnapshot() {
253
+ const copy = root.cloneNode(true);
254
+ const copies = copy.querySelectorAll(panelControlSelector);
255
+ root.querySelectorAll(panelControlSelector).forEach((control, index) => {
256
+ let id = panelControls.get(control);
257
+ if (!id) {
258
+ id = panelDocumentId + ':' + ++panelControlId;
259
+ panelControls.set(control, id);
260
+ }
261
+ const clone = copies[index];
262
+ clone.setAttribute('data-panel-control', id);
263
+ if (control instanceof HTMLTextAreaElement)
264
+ clone.textContent = control.value;
265
+ if (control instanceof HTMLSelectElement) {
266
+ clone.querySelectorAll('option').forEach((option, optionIndex) => {
267
+ option.toggleAttribute('selected', control.options[optionIndex].selected);
268
+ });
269
+ }
270
+ });
271
+ return { ok: true, html: copy.innerHTML, countdown: journalCountdown?.getCountdownLabel() || '', notice: automationNotice };
272
+ }
273
+ function panelAction(request) {
274
+ if (request.operation === 'vision') {
275
+ void visionScan();
276
+ return { ok: true };
277
+ }
278
+ if (request.operation === 'automation') {
279
+ toggleDirectAutomation();
280
+ return { ok: true };
281
+ }
282
+ if (request.operation === 'journal') {
283
+ if (window.BrowserAssistantJournal?.matches())
284
+ void window.BrowserAssistantJournal.start();
285
+ return { ok: true };
286
+ }
287
+ const control = [...root.querySelectorAll(panelControlSelector)]
288
+ .find(element => panelControls.get(element) === request.panelControl);
289
+ if (!control || control.closest('[hidden]') || control.matches(':disabled')) {
290
+ return { error: 'The panel changed. Try the control again.' };
291
+ }
292
+ if (request.operation === 'click' && control.matches('button,summary')) {
293
+ control.click();
294
+ }
295
+ else if (request.operation === 'value' && typeof request.value === 'string' && request.value.length <= 20000
296
+ && (control instanceof HTMLSelectElement || control instanceof HTMLTextAreaElement)) {
297
+ if (control instanceof HTMLSelectElement && ![...control.options].some(option => option.value === request.value)) {
298
+ return { error: 'That choice is no longer available.' };
299
+ }
300
+ control.value = request.value;
301
+ control.dispatchEvent(new Event(control instanceof HTMLSelectElement ? 'change' : 'input', { bubbles: true }));
302
+ }
303
+ else {
304
+ return { error: 'Unsupported panel control.' };
305
+ }
306
+ return { ok: true };
307
+ }
308
+ async function syncDetachedPanel() {
309
+ const previous = panelToken;
310
+ try {
311
+ const result = await chrome.runtime.sendMessage({ action: 'panel:target-status' });
312
+ if (typeof result?.token === 'string' && panelToken === previous && result.token !== previous) {
313
+ setDetachedPanel(result.token);
314
+ }
315
+ }
316
+ catch { /* The toolbar can reconnect after a reload. */ }
317
+ finally {
318
+ root.classList.remove('assistant-panel-initializing');
319
+ journalCountdownBadge?.classList.remove('assistant-panel-initializing');
320
+ }
321
+ }
322
+ document.addEventListener('visibilitychange', () => {
323
+ if (!document.hidden)
324
+ void syncDetachedPanel();
325
+ }, { signal: lifecycle.signal });
326
+ const updateListener = (request, sender, sendResponse) => {
327
+ if (request.action?.startsWith('assistantPanel')) {
328
+ if (sender.id !== chrome.runtime.id || sender.tab)
329
+ return false;
330
+ if (request.action === 'assistantPanelPing')
331
+ sendResponse({ ok: true });
332
+ if (request.action === 'assistantPanelSnapshot' && typeof request.token === 'string' && request.token) {
333
+ if (panelToken !== request.token)
334
+ setDetachedPanel(request.token);
335
+ sendResponse(panelSnapshot());
336
+ }
337
+ if (panelToken && request.token === panelToken) {
338
+ if (request.action === 'assistantPanelDetach') {
339
+ setDetachedPanel('');
340
+ sendResponse({ ok: true });
341
+ }
342
+ if (request.action === 'assistantPanelAction')
343
+ sendResponse(panelAction(request));
344
+ }
345
+ return false;
346
+ }
203
347
  const busy = automation.running || isScanning || Boolean(window.BrowserAssistantJournalBusy);
204
348
  if (request.action === 'assistantUpdateStatus') {
205
349
  sendResponse({ busy });
@@ -235,10 +379,7 @@ function mountJournalCountdown(signal) {
235
379
  if (!window.BrowserAssistantJournal?.matches())
236
380
  return;
237
381
  selectedTab = 'qa';
238
- isCollapsed = false;
239
- isHidden = false;
240
- root.style.display = 'block';
241
- render();
382
+ openPanel();
242
383
  }, { signal: lifecycle.signal });
243
384
  function getAutomationContext() {
244
385
  const target = automationPolicy?.resolveTarget(window.location, document) || null;
@@ -419,6 +560,7 @@ function mountJournalCountdown(signal) {
419
560
  function updateAutomationUI() {
420
561
  if (disposed)
421
562
  return;
563
+ updateDirectRun();
422
564
  const status = document.getElementById('assistant-automation-status');
423
565
  const statusBadge = document.getElementById('assistant-automation-state');
424
566
  const page = document.getElementById('assistant-automation-page');
@@ -951,9 +1093,13 @@ function mountJournalCountdown(signal) {
951
1093
  automation.targetId = context.target.id;
952
1094
  automation.batch = batch;
953
1095
  automation.completed = batch.completed;
954
- isCollapsed = false;
955
- selectedTab = 'qa';
956
- render();
1096
+ if (!directRun) {
1097
+ isHidden = false;
1098
+ isCollapsed = false;
1099
+ root.style.display = 'block';
1100
+ selectedTab = 'qa';
1101
+ render();
1102
+ }
957
1103
  const persist = phase => {
958
1104
  batch.phase = phase;
959
1105
  batch.updatedAt = Date.now();
@@ -1312,6 +1458,83 @@ function mountJournalCountdown(signal) {
1312
1458
  }
1313
1459
  return false;
1314
1460
  }
1461
+ async function solveCompoundMcq(compound, runId, adapter) {
1462
+ const findCurrent = (original) => {
1463
+ const fresh = getAuthorizedQuestion();
1464
+ return fresh?.compoundQuestions?.find(candidate => hasSameQuestionOptions(original, candidate)) || null;
1465
+ };
1466
+ for (const original of compound.compoundQuestions || []) {
1467
+ if (!(await waitWhilePaused(runId)))
1468
+ return false;
1469
+ let question = findCurrent(original);
1470
+ if (!question)
1471
+ throw new Error('A linked question changed before its answer was selected. Nothing else was submitted.');
1472
+ if (question.options.some(option => option.isSelected?.() || option.input?.checked))
1473
+ continue;
1474
+ automation.state = 'SOLVING';
1475
+ updateAutomationUI();
1476
+ const prompt = `${compound.compoundContext || ''}\n\nAnswer only this linked question: ${question.text}\nQuestion format: select one answer.\n${question.options.map((option, index) => `${String.fromCharCode(65 + index)}. ${option.text}`).join('\n')}`;
1477
+ const response = await window.BrowserAssistantAnswerRequests.run({
1478
+ request: () => apiRequest('/solve', 'POST', { text: prompt, url: window.location.href, practice_type: 'mcq', verify_answer: true }),
1479
+ active: () => automation.running && automation.runId === runId,
1480
+ ready: () => waitWhilePaused(runId),
1481
+ current: () => Boolean(findCurrent(original)),
1482
+ onRetry: ({ attempt, attempts, message }) => {
1483
+ automation.state = 'RETRYING_REQUEST';
1484
+ automation.error = `Temporary answer service issue. Retrying ${attempt}/${attempts}: ${message}`;
1485
+ updateAutomationUI();
1486
+ },
1487
+ sleep: ms => new Promise(resolve => setTimeout(resolve, ms)),
1488
+ });
1489
+ if (!response?.data?.answer_verified)
1490
+ throw new Error('Answer verification is required for every linked question.');
1491
+ let results;
1492
+ try {
1493
+ results = JSON.parse(response.data.results);
1494
+ }
1495
+ catch {
1496
+ throw new Error('The answer service returned invalid linked-question data.');
1497
+ }
1498
+ const answerIndexes = answerIndexesFromResult(results, question);
1499
+ if (!answerIndexes.length)
1500
+ throw new Error('The verified answer did not match this linked question’s displayed options.');
1501
+ automation.state = 'SELECTING';
1502
+ updateAutomationUI();
1503
+ for (const index of answerIndexes) {
1504
+ question = findCurrent(original);
1505
+ const option = question?.options[index];
1506
+ if (!option)
1507
+ throw new Error('A linked question option disappeared before selection.');
1508
+ if (!(option.isSelected?.() || option.input?.checked))
1509
+ (option.input || option.control)?.click();
1510
+ let selected = false;
1511
+ for (let attempt = 0; attempt < 50 && await waitWhilePaused(runId); attempt++) {
1512
+ question = findCurrent(original);
1513
+ const current = question?.options[index];
1514
+ if (current?.isSelected?.() || current?.input?.checked) {
1515
+ selected = true;
1516
+ break;
1517
+ }
1518
+ await new Promise(resolve => setTimeout(resolve, 50));
1519
+ }
1520
+ if (!selected)
1521
+ throw new Error('A linked answer could not be verified after selection.');
1522
+ }
1523
+ }
1524
+ const current = getAuthorizedQuestion();
1525
+ const submitQuestion = current?.compoundQuestions?.[0] || compound.compoundQuestions?.[0];
1526
+ const submit = submitQuestion && adapter.getSubmit(document, submitQuestion);
1527
+ if (!submit?.isConnected || submit.disabled || submit.getAttribute('aria-disabled') === 'true') {
1528
+ throw new Error('All linked answers were selected, but the portal did not enable a unique Submit button.');
1529
+ }
1530
+ automation.state = 'SUBMITTING';
1531
+ updateAutomationUI();
1532
+ automation.processed.add(compound.signature);
1533
+ submit.click();
1534
+ automation.state = 'WAITING_FOR_NEXT';
1535
+ updateAutomationUI();
1536
+ return true;
1537
+ }
1315
1538
  async function startPracticeAutomation() {
1316
1539
  if (window.BrowserAssistantJournal?.matches()) {
1317
1540
  await window.BrowserAssistantJournal.start();
@@ -1482,6 +1705,16 @@ function mountJournalCountdown(signal) {
1482
1705
  await runCodingAutomation(question, runId);
1483
1706
  break;
1484
1707
  }
1708
+ if (question.type === 'compound-mcq') {
1709
+ try {
1710
+ await solveCompoundMcq(question, runId, adapter);
1711
+ }
1712
+ catch (error) {
1713
+ automation.error = error.message || 'Linked questions could not be completed.';
1714
+ stopAutomation('PAUSED');
1715
+ }
1716
+ break;
1717
+ }
1485
1718
  if (automation.deferredQuestions.has(question.signature)) {
1486
1719
  automation.currentSignature = question.signature;
1487
1720
  if (await continueAfterUnverifiedQuestion(question, runId, 'This question was deferred earlier.', false))
@@ -2069,31 +2302,119 @@ function mountJournalCountdown(signal) {
2069
2302
  isHidden = true;
2070
2303
  root.style.display = 'none';
2071
2304
  }
2072
- function handleAutomationShortcut(e) {
2073
- if (e.repeat || e.isComposing || e.defaultPrevented || !e.altKey || e.ctrlKey || e.metaKey
2074
- || (e.code !== 'KeyA' && String(e.key).toLowerCase() !== 'a'))
2075
- return false;
2076
- e.preventDefault();
2077
- e.stopPropagation();
2078
- selectedTab = 'qa';
2079
- isHidden = false;
2080
- isCollapsed = false;
2081
- root.style.display = 'block';
2082
- render();
2305
+ function showAutomationNotice(message) {
2306
+ automationNotice = message;
2307
+ window.clearTimeout(noticeTimer);
2308
+ const element = document.getElementById('assistant-automation-notice') || document.createElement('div');
2309
+ element.id = 'assistant-automation-notice';
2310
+ element.setAttribute('role', 'status');
2311
+ element.textContent = message;
2312
+ if (!element.isConnected)
2313
+ document.body.appendChild(element);
2314
+ noticeTimer = window.setTimeout(() => { automationNotice = ''; element.remove(); }, 5000);
2315
+ }
2316
+ function saveDirectRun() {
2317
+ if (!directRun)
2318
+ return;
2319
+ const record = { ...directRun, revision: ++directRun.revision };
2320
+ try {
2321
+ if (record.status === 'Running')
2322
+ sessionStorage.setItem(directRunKey, JSON.stringify(record));
2323
+ else
2324
+ sessionStorage.removeItem(directRunKey);
2325
+ }
2326
+ catch { /* Storage is optional for runs on the current document. */ }
2327
+ void apiRequest('/automation-history', 'PUT', record).then(response => {
2328
+ if (!response.ok)
2329
+ throw Error('History write failed');
2330
+ }).catch(() => {
2331
+ if (!directRun || directRun.id === record.id)
2332
+ showAutomationNotice('Automation history could not be saved.');
2333
+ });
2334
+ }
2335
+ function finishDirectRun(status) {
2336
+ if (!directRun)
2337
+ return;
2338
+ directRun.status = status;
2339
+ directRun.ended_at = new Date().toISOString();
2340
+ saveDirectRun();
2341
+ directRun = null;
2342
+ }
2343
+ function updateDirectRun() {
2344
+ if (!directRun || directRunStarting)
2345
+ return;
2346
+ const journal = directRun.type === 'Journal' ? window.BrowserAssistantJournal?.getState() : null;
2347
+ const current = journal || automation;
2348
+ const completed = Math.max(directRun.completed, current.completed || 0);
2349
+ const failed = Math.max(directRun.failed, journal ? 0 : automation.deferredQuestions?.size || 0);
2350
+ const changed = directRun.completed !== completed || directRun.failed !== failed;
2351
+ Object.assign(directRun, { completed, failed });
2352
+ if (current.running || ['STARTING_PRACTICE', 'OPENING_NEXT_PRACTICE'].includes(current.state)) {
2353
+ if (changed)
2354
+ saveDirectRun();
2355
+ return;
2356
+ }
2357
+ const status = current.state === 'COMPLETED' ? 'Completed' : current.state === 'STOPPED' ? 'Stopped' : 'Failed';
2358
+ if (status === 'Failed' && directRun.failed === 0)
2359
+ directRun.failed = 1;
2360
+ showAutomationNotice(status === 'Failed' ? (journal?.message || automation.error || 'Automation could not continue.') : 'Automation ' + status.toLowerCase() + '.');
2361
+ finishDirectRun(status);
2362
+ }
2363
+ function toggleDirectAutomation() {
2364
+ if (directRunStarting)
2365
+ return;
2083
2366
  const journal = window.BrowserAssistantJournal;
2084
2367
  if (journal?.matches() && journal.getState().running) {
2085
2368
  journal.pause();
2086
2369
  updateAutomationUI();
2370
+ return;
2087
2371
  }
2088
- else if (automation.running) {
2372
+ if (automation.running) {
2089
2373
  pauseOrResumeAutomation();
2374
+ return;
2090
2375
  }
2091
- else {
2092
- void startPracticeAutomation().catch(error => {
2093
- automation.error = error.message || 'Automation could not start.';
2094
- stopAutomation('ERROR');
2095
- });
2376
+ if (directRun)
2377
+ return;
2378
+ const context = getAutomationContext();
2379
+ const adapter = getAutomationAdapter(context);
2380
+ const question = getAuthorizedQuestion(context);
2381
+ const batch = location.origin === 'https://learning.ccbp.in' && /^\/problems-set\/?$/.test(location.pathname);
2382
+ const ide = window.BrowserAssistantCoding?.getOnlineIdeQuestion?.(document, location);
2383
+ const journalPage = Boolean(journal?.matches());
2384
+ const canNavigate = automationPolicy?.canExecute('navigate', context);
2385
+ const type = journalPage ? 'Journal' : batch && canNavigate ? 'Batch Coding'
2386
+ : question?.type === 'code' || (ide && canNavigate) ? 'Coding'
2387
+ : question || (canNavigate && adapter?.getStartPractice?.(document)) ? (/quiz/i.test(location.pathname) ? 'Quiz' : 'MCQ')
2388
+ : null;
2389
+ if (!type) {
2390
+ showAutomationNotice('Automation is unavailable on this page.');
2391
+ return;
2096
2392
  }
2393
+ if (context.target.id !== 'local-practice'
2394
+ && !window.confirm('Start ' + type + ' automation on this page? It can enter and submit answers as it runs.'))
2395
+ return;
2396
+ const progress = document.querySelector('[data-practice-quiz] #progress')?.textContent;
2397
+ const total = type === 'Journal' || type === 'Coding' ? 1 : Number(progress?.match(/\bof\s+(\d+)/i)?.[1]) || null;
2398
+ directRun = { id: crypto.randomUUID(), type, url: location.origin + location.pathname,
2399
+ started_at: new Date().toISOString(), ended_at: null, total, completed: 0, failed: 0, status: 'Running', revision: 0 };
2400
+ directRunStarting = true;
2401
+ saveDirectRun();
2402
+ showAutomationNotice(type + ' automation started.');
2403
+ const started = startPracticeAutomation();
2404
+ directRunStarting = false;
2405
+ updateDirectRun();
2406
+ void started.catch(error => {
2407
+ automation.error = error.message || 'Automation could not start.';
2408
+ stopAutomation('ERROR');
2409
+ });
2410
+ }
2411
+ function handleAutomationShortcut(e, isTyping = false) {
2412
+ if (isTyping || e.repeat || e.isComposing || e.defaultPrevented || !e.altKey || e.ctrlKey || e.metaKey
2413
+ || (e.code !== 'KeyA' && String(e.key).toLowerCase() !== 'a'))
2414
+ return false;
2415
+ e.preventDefault();
2416
+ e.stopPropagation();
2417
+ toggleDirectAutomation();
2097
2418
  return true;
2098
2419
  }
2099
2420
  // ── Keyboard shortcuts ────────────────────────────────────────────────────
@@ -2101,8 +2422,7 @@ function mountJournalCountdown(signal) {
2101
2422
  // Block held-key auto-repeat to prevent rapid-fire race conditions
2102
2423
  if (e.repeat || e.isComposing)
2103
2424
  return;
2104
- // Explicit automation chord also works while the code editor has focus.
2105
- if (handleAutomationShortcut(e))
2425
+ if (panelToken && (e.key === '`' || e.key === ']' || e.key === '['))
2106
2426
  return;
2107
2427
  const active = document.activeElement;
2108
2428
  const isTyping = active instanceof HTMLInputElement ||
@@ -2110,6 +2430,12 @@ function mountJournalCountdown(signal) {
2110
2430
  active instanceof HTMLSelectElement ||
2111
2431
  active?.isContentEditable ||
2112
2432
  active?.getAttribute?.('role') === 'textbox';
2433
+ const editorSelector = 'input,textarea,select,[contenteditable]:not([contenteditable="false"]),[role="textbox"],.monaco-editor,.CodeMirror,.ace_editor';
2434
+ const shortcutTyping = isTyping
2435
+ || Boolean(active?.closest?.(editorSelector))
2436
+ || e.composedPath().some(node => node instanceof Element && node.matches(editorSelector));
2437
+ if (handleAutomationShortcut(e, shortcutTyping))
2438
+ return;
2113
2439
  if (isTyping)
2114
2440
  return;
2115
2441
  switch (e.key) {
@@ -2169,8 +2495,9 @@ function mountJournalCountdown(signal) {
2169
2495
  context.visualSnapshot = snapshot.fingerprint;
2170
2496
  }
2171
2497
  else {
2172
- await new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)));
2173
- const response = await safeSendMessage({ action: "captureVisibleTab" });
2498
+ if (!panelToken)
2499
+ await new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)));
2500
+ const response = await safeSendMessage({ action: "captureVisibleTab", url: context.url });
2174
2501
  if (!response?.dataUrl || response.error)
2175
2502
  throw new Error(response?.error || 'Screenshot capture failed');
2176
2503
  images = [response.dataUrl];
@@ -2552,7 +2879,7 @@ function mountJournalCountdown(signal) {
2552
2879
  }
2553
2880
  function scanPanelMarkup() {
2554
2881
  return `
2555
- <section class="assistant-scan-panel" id="assistant-scan-panel" role="tabpanel" aria-labelledby="mode-${selectedTab}">
2882
+ <section class="assistant-scan-panel" id="assistant-scan-panel" role="tabpanel" aria-labelledby="mode-${selectedTab === 'aptitude' ? 'apt' : selectedTab}">
2556
2883
  <div class="assistant-btn-row">
2557
2884
  <button class="assistant-btn" id="assistant-scan-btn">⚡ Scan (Text)</button>
2558
2885
  <button class="assistant-btn secondary" id="assistant-vision-btn">⌁ Scan (Vision)</button>
@@ -2643,6 +2970,7 @@ function mountJournalCountdown(signal) {
2643
2970
  const safeContent = content.replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;');
2644
2971
  root.innerHTML = `
2645
2972
  <button class="assistant-tab collapsed ${content ? 'has-answer' : ''}" id="assistant-trigger" type="button" aria-label="Open Browser Assistant" data-content="${safeContent}">
2973
+ <span class="assistant-mark" aria-hidden="true">BA</span>
2646
2974
  ${isMinimalMode ? '<div class="assistant-mode-indicator">MIN</div>' : ''}
2647
2975
  </button>
2648
2976
  `;
@@ -2661,8 +2989,9 @@ function mountJournalCountdown(signal) {
2661
2989
  <div class="assistant-tab" id="assistant-panel">
2662
2990
  <div class="assistant-header">
2663
2991
  <div class="assistant-title-row">
2664
- ${statusDot}
2992
+ <span class="assistant-mark" aria-hidden="true">BA</span>
2665
2993
  <h3 class="assistant-title">Browser Assistant</h3>
2994
+ ${statusDot}
2666
2995
  </div>
2667
2996
  <div class="assistant-header-actions">
2668
2997
  <button class="assistant-icon-btn" id="assistant-history-btn" type="button" aria-label="Open Scan History" title="Scan History">
@@ -2869,8 +3198,10 @@ function mountJournalCountdown(signal) {
2869
3198
  const isFresh = Number.isFinite(resume?.createdAt) && Date.now() - resume.createdAt < 120000;
2870
3199
  if (!isFresh || resume.targetId !== context.target?.id || context.mode !== 'FULL')
2871
3200
  return;
2872
- isCollapsed = false;
2873
- render();
3201
+ if (!directRun) {
3202
+ isCollapsed = false;
3203
+ render();
3204
+ }
2874
3205
  const adapter = getAutomationAdapter(context);
2875
3206
  if (!adapter)
2876
3207
  return;
@@ -2929,7 +3260,24 @@ function mountJournalCountdown(signal) {
2929
3260
  }
2930
3261
  catch { }
2931
3262
  render();
3263
+ void syncDetachedPanel();
3264
+ function hasDirectRunContinuation() {
3265
+ try {
3266
+ return [AUTO_RESUME_KEY, CODING_BATCH_KEY, 'assistantPendingJournal'].some(key => sessionStorage.getItem(key));
3267
+ }
3268
+ catch {
3269
+ return false;
3270
+ }
3271
+ }
3272
+ if (directRun && !hasDirectRunContinuation())
3273
+ finishDirectRun('Stopped');
3274
+ window.addEventListener('pagehide', () => {
3275
+ if (!hasDirectRunContinuation())
3276
+ finishDirectRun('Stopped');
3277
+ }, { signal: lifecycle.signal });
2932
3278
  if (!reopenedAfterUpdate)
2933
- void resumeCodingBatch().then(resumed => { if (!resumed)
2934
- void resumeAuthorizedQaAfterNavigation(); });
3279
+ void resumeCodingBatch().then(resumed => {
3280
+ if (!resumed)
3281
+ return resumeAuthorizedQaAfterNavigation();
3282
+ });
2935
3283
  })();