browser-assistant 2.9.3 → 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.
- package/README.md +2 -0
- package/extension/automation-policy.js +21 -2
- package/extension/background.js +13 -5
- package/extension/content.js +389 -53
- package/extension/detached-panel-background.js +101 -0
- package/extension/detached-panel.html +18 -0
- package/extension/detached-panel.js +201 -0
- package/extension/journal-automation.js +11 -6
- package/extension/manifest.json +1 -1
- package/extension/popup.html +2 -0
- package/extension/popup.js +24 -0
- package/extension/styles.css +89 -0
- package/package.json +7 -2
- package/server/main.py +62 -2
package/extension/content.js
CHANGED
|
@@ -9,27 +9,33 @@ function mountJournalCountdown(signal) {
|
|
|
9
9
|
let timers = [];
|
|
10
10
|
let tick;
|
|
11
11
|
let revision = 0;
|
|
12
|
-
function
|
|
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 =
|
|
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
|
-
|
|
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 (
|
|
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
|
|
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(
|
|
95
|
-
y: Math.max(
|
|
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,7 +184,7 @@ 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
|
}
|
|
@@ -209,7 +218,132 @@ function mountJournalCountdown(signal) {
|
|
|
209
218
|
state: 'IDLE', running: false, paused: false, runId: 0,
|
|
210
219
|
processed: new Set(), completed: 0, error: '', currentSignature: '',
|
|
211
220
|
};
|
|
212
|
-
const
|
|
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
|
+
}
|
|
213
347
|
const busy = automation.running || isScanning || Boolean(window.BrowserAssistantJournalBusy);
|
|
214
348
|
if (request.action === 'assistantUpdateStatus') {
|
|
215
349
|
sendResponse({ busy });
|
|
@@ -245,10 +379,7 @@ function mountJournalCountdown(signal) {
|
|
|
245
379
|
if (!window.BrowserAssistantJournal?.matches())
|
|
246
380
|
return;
|
|
247
381
|
selectedTab = 'qa';
|
|
248
|
-
|
|
249
|
-
isHidden = false;
|
|
250
|
-
root.style.display = 'block';
|
|
251
|
-
render();
|
|
382
|
+
openPanel();
|
|
252
383
|
}, { signal: lifecycle.signal });
|
|
253
384
|
function getAutomationContext() {
|
|
254
385
|
const target = automationPolicy?.resolveTarget(window.location, document) || null;
|
|
@@ -429,6 +560,7 @@ function mountJournalCountdown(signal) {
|
|
|
429
560
|
function updateAutomationUI() {
|
|
430
561
|
if (disposed)
|
|
431
562
|
return;
|
|
563
|
+
updateDirectRun();
|
|
432
564
|
const status = document.getElementById('assistant-automation-status');
|
|
433
565
|
const statusBadge = document.getElementById('assistant-automation-state');
|
|
434
566
|
const page = document.getElementById('assistant-automation-page');
|
|
@@ -961,9 +1093,13 @@ function mountJournalCountdown(signal) {
|
|
|
961
1093
|
automation.targetId = context.target.id;
|
|
962
1094
|
automation.batch = batch;
|
|
963
1095
|
automation.completed = batch.completed;
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
1096
|
+
if (!directRun) {
|
|
1097
|
+
isHidden = false;
|
|
1098
|
+
isCollapsed = false;
|
|
1099
|
+
root.style.display = 'block';
|
|
1100
|
+
selectedTab = 'qa';
|
|
1101
|
+
render();
|
|
1102
|
+
}
|
|
967
1103
|
const persist = phase => {
|
|
968
1104
|
batch.phase = phase;
|
|
969
1105
|
batch.updatedAt = Date.now();
|
|
@@ -1322,6 +1458,83 @@ function mountJournalCountdown(signal) {
|
|
|
1322
1458
|
}
|
|
1323
1459
|
return false;
|
|
1324
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
|
+
}
|
|
1325
1538
|
async function startPracticeAutomation() {
|
|
1326
1539
|
if (window.BrowserAssistantJournal?.matches()) {
|
|
1327
1540
|
await window.BrowserAssistantJournal.start();
|
|
@@ -1492,6 +1705,16 @@ function mountJournalCountdown(signal) {
|
|
|
1492
1705
|
await runCodingAutomation(question, runId);
|
|
1493
1706
|
break;
|
|
1494
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
|
+
}
|
|
1495
1718
|
if (automation.deferredQuestions.has(question.signature)) {
|
|
1496
1719
|
automation.currentSignature = question.signature;
|
|
1497
1720
|
if (await continueAfterUnverifiedQuestion(question, runId, 'This question was deferred earlier.', false))
|
|
@@ -2079,31 +2302,119 @@ function mountJournalCountdown(signal) {
|
|
|
2079
2302
|
isHidden = true;
|
|
2080
2303
|
root.style.display = 'none';
|
|
2081
2304
|
}
|
|
2082
|
-
function
|
|
2083
|
-
|
|
2084
|
-
|
|
2085
|
-
|
|
2086
|
-
|
|
2087
|
-
|
|
2088
|
-
|
|
2089
|
-
|
|
2090
|
-
|
|
2091
|
-
|
|
2092
|
-
|
|
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;
|
|
2093
2366
|
const journal = window.BrowserAssistantJournal;
|
|
2094
2367
|
if (journal?.matches() && journal.getState().running) {
|
|
2095
2368
|
journal.pause();
|
|
2096
2369
|
updateAutomationUI();
|
|
2370
|
+
return;
|
|
2097
2371
|
}
|
|
2098
|
-
|
|
2372
|
+
if (automation.running) {
|
|
2099
2373
|
pauseOrResumeAutomation();
|
|
2374
|
+
return;
|
|
2100
2375
|
}
|
|
2101
|
-
|
|
2102
|
-
|
|
2103
|
-
|
|
2104
|
-
|
|
2105
|
-
|
|
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;
|
|
2106
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();
|
|
2107
2418
|
return true;
|
|
2108
2419
|
}
|
|
2109
2420
|
// ── Keyboard shortcuts ────────────────────────────────────────────────────
|
|
@@ -2111,8 +2422,7 @@ function mountJournalCountdown(signal) {
|
|
|
2111
2422
|
// Block held-key auto-repeat to prevent rapid-fire race conditions
|
|
2112
2423
|
if (e.repeat || e.isComposing)
|
|
2113
2424
|
return;
|
|
2114
|
-
|
|
2115
|
-
if (handleAutomationShortcut(e))
|
|
2425
|
+
if (panelToken && (e.key === '`' || e.key === ']' || e.key === '['))
|
|
2116
2426
|
return;
|
|
2117
2427
|
const active = document.activeElement;
|
|
2118
2428
|
const isTyping = active instanceof HTMLInputElement ||
|
|
@@ -2120,6 +2430,12 @@ function mountJournalCountdown(signal) {
|
|
|
2120
2430
|
active instanceof HTMLSelectElement ||
|
|
2121
2431
|
active?.isContentEditable ||
|
|
2122
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;
|
|
2123
2439
|
if (isTyping)
|
|
2124
2440
|
return;
|
|
2125
2441
|
switch (e.key) {
|
|
@@ -2179,8 +2495,9 @@ function mountJournalCountdown(signal) {
|
|
|
2179
2495
|
context.visualSnapshot = snapshot.fingerprint;
|
|
2180
2496
|
}
|
|
2181
2497
|
else {
|
|
2182
|
-
|
|
2183
|
-
|
|
2498
|
+
if (!panelToken)
|
|
2499
|
+
await new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)));
|
|
2500
|
+
const response = await safeSendMessage({ action: "captureVisibleTab", url: context.url });
|
|
2184
2501
|
if (!response?.dataUrl || response.error)
|
|
2185
2502
|
throw new Error(response?.error || 'Screenshot capture failed');
|
|
2186
2503
|
images = [response.dataUrl];
|
|
@@ -2881,8 +3198,10 @@ function mountJournalCountdown(signal) {
|
|
|
2881
3198
|
const isFresh = Number.isFinite(resume?.createdAt) && Date.now() - resume.createdAt < 120000;
|
|
2882
3199
|
if (!isFresh || resume.targetId !== context.target?.id || context.mode !== 'FULL')
|
|
2883
3200
|
return;
|
|
2884
|
-
|
|
2885
|
-
|
|
3201
|
+
if (!directRun) {
|
|
3202
|
+
isCollapsed = false;
|
|
3203
|
+
render();
|
|
3204
|
+
}
|
|
2886
3205
|
const adapter = getAutomationAdapter(context);
|
|
2887
3206
|
if (!adapter)
|
|
2888
3207
|
return;
|
|
@@ -2941,7 +3260,24 @@ function mountJournalCountdown(signal) {
|
|
|
2941
3260
|
}
|
|
2942
3261
|
catch { }
|
|
2943
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 });
|
|
2944
3278
|
if (!reopenedAfterUpdate)
|
|
2945
|
-
void resumeCodingBatch().then(resumed => {
|
|
2946
|
-
|
|
3279
|
+
void resumeCodingBatch().then(resumed => {
|
|
3280
|
+
if (!resumed)
|
|
3281
|
+
return resumeAuthorizedQaAfterNavigation();
|
|
3282
|
+
});
|
|
2947
3283
|
})();
|