browser-assistant 2.9.0 → 2.9.1

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.
@@ -88,8 +88,8 @@ function browserAssistantEditor(operation, selector, expected, value) {
88
88
  return { ok: false, error: error.message };
89
89
  }
90
90
  }
91
- // Run the IDE's normal paste and autosave flow. The terminal verifies the saved
92
- // file and checks syntax. The portal's grading command is a separate user action.
91
+ // Run the IDE's normal paste and autosave flow. The terminal only verifies and
92
+ // grades the saved file; generated source is never passed to the shell.
93
93
  async function browserAssistantOnlineIde(action, workspace, questionId, token, source) {
94
94
  if (location.origin !== 'https://ide.ccbp.in' || location.pathname.replace(/\/$/, '') !== `/playground/${workspace}`)
95
95
  return null;
@@ -116,12 +116,16 @@ async function browserAssistantOnlineIde(action, workspace, questionId, token, s
116
116
  const result = lines.find(line => line.startsWith(`${finishMarker}:`));
117
117
  if (!result)
118
118
  return { ok: true, done: false };
119
- return { ok: true, done: true, saved: result === `${finishMarker}:0`, saveUnconfirmed: lines.includes(saveMarker) };
119
+ const index = lines.findLastIndex(line => line.includes('Open Submission URL'));
120
+ const report = index >= 0 && reports(lines.slice(index)).find(id => !previous.reports.includes(id));
121
+ const passed = result === `${finishMarker}:0` && Boolean(report) && index > 0
122
+ && lines.slice(Math.max(0, index - 3), index).includes('All test cases passed');
123
+ return { ok: true, done: true, passed, submitted: Boolean(report), saveUnconfirmed: lines.includes(saveMarker), url: report ? reportPrefix + report : null };
120
124
  }
121
125
  if (previous?.token === token)
122
126
  return { ok: false, error: 'This IDE run was already started. Check the terminal.' };
123
127
  if (document.visibilityState !== 'visible')
124
- return { ok: false, error: 'Keep the matching IDE tab active to apply code.' };
128
+ return { ok: false, error: 'Keep the matching IDE tab active to submit.' };
125
129
  const before = rows();
126
130
  const prompt = before.at(-1)?.match(/^nxtwave@([a-z0-9]+):~\/nodejs\/coding-practices\/([a-z0-9_-]+)\$$/i);
127
131
  if (!prompt || prompt[1] !== workspace)
@@ -194,15 +198,15 @@ async function browserAssistantOnlineIde(action, workspace, questionId, token, s
194
198
  // All interpolated values have restricted alphabets.
195
199
  const saved = `printf '%s app.js\\n' '${digest}' | sha256sum --check --status`;
196
200
  const echoMarker = `BA_COMMAND_${token}`;
197
- const command = `( for ba_try in 1 2 3 4 5 6 7 8 9 10; do ${saved} && break; sleep 0.5; done; if ${saved}; then node --check app.js; else printf '%s\\n' ${saveMarker}; false; fi ); printf '\\n${finishMarker}:%s\\n' "$?" #${echoMarker}`;
201
+ const command = `( for ba_try in 1 2 3 4 5 6 7 8 9 10; do ${saved} && break; sleep 0.5; done; if ${saved}; then node --check app.js && ccbp submit ${workspace}; else printf '%s\\n' ${saveMarker}; false; fi ); printf '\\n${finishMarker}:%s\\n' "$?" #${echoMarker}`;
198
202
  if (rows().at(-1) !== before.at(-1))
199
- return { ok: false, error: 'Code is in app.js, but the IDE terminal changed before the syntax check.' };
203
+ return { ok: false, error: 'Code is in app.js, but the IDE terminal changed before grading.' };
200
204
  input.focus();
201
205
  if (document.activeElement !== input)
202
206
  return { ok: false, error: 'The IDE terminal could not be focused.' };
203
207
  const data = new DataTransfer();
204
208
  data.setData('text/plain', command);
205
- window[key] = { token };
209
+ window[key] = { token, reports: reports(before) };
206
210
  input.dispatchEvent(new ClipboardEvent('paste', { clipboardData: data, bubbles: true, cancelable: true }));
207
211
  const deadline = Date.now() + 2500;
208
212
  while (Date.now() < deadline && document.activeElement === input && document.visibilityState === 'visible') {
@@ -96,7 +96,19 @@ function browserAssistantJournal(global) {
96
96
  }
97
97
  return values.size === 1 ? [...values][0] : null;
98
98
  }
99
- const api = { validate, metadata, fields, pageText, readField, remainingSeconds };
99
+ function writeField(field, value) {
100
+ const win = field.ownerDocument.defaultView;
101
+ if (field.tagName === 'TEXTAREA') {
102
+ Object.getOwnPropertyDescriptor(win.HTMLTextAreaElement.prototype, 'value').set.call(field, value);
103
+ }
104
+ else {
105
+ field.textContent = value;
106
+ }
107
+ const event = win.InputEvent ? new win.InputEvent('input', { bubbles: true, inputType: 'insertText', data: value }) : new win.Event('input', { bubbles: true });
108
+ field.dispatchEvent(event);
109
+ field.dispatchEvent(new win.Event('change', { bubbles: true }));
110
+ }
111
+ const api = { validate, metadata, fields, pageText, readField, writeField, remainingSeconds };
100
112
  if (typeof module !== 'undefined')
101
113
  module.exports = api;
102
114
  if (!global.document || global.location?.origin !== 'https://admissions.aurora.edu.in')
@@ -111,8 +123,8 @@ function browserAssistantJournal(global) {
111
123
  return;
112
124
  existing?.remove();
113
125
  const storageKey = `assistantJournal:${location.pathname}`;
114
- let info = null, running = false, paused = false, generation = 0, idleState = 'READY';
115
- let activeRequest;
126
+ let info = null, draft = null, running = false, submitting = false, paused = false, starting = false, startIssued = false, generation = 0, idleState = 'READY';
127
+ let filled = false, waitingForTimer = false;
116
128
  try {
117
129
  info = JSON.parse(sessionStorage.getItem(storageKey));
118
130
  }
@@ -121,7 +133,7 @@ function browserAssistantJournal(global) {
121
133
  panel.id = 'assistant-journal';
122
134
  panel.dataset.build = journalBuild;
123
135
  panel.style.cssText = 'position:fixed;right:16px;top:160px;width:290px;z-index:2147483646;background:white;color:#17233d;padding:16px;border:2px solid #7638ff;border-radius:12px;box-shadow:0 4px 20px #0003;font:14px Arial';
124
- panel.innerHTML = '<strong>Reflective Journal</strong><p data-info></p><p data-countdown style="font-weight:600;margin:8px 0"></p><textarea aria-label="Your class experience and feelings" placeholder="Describe your actual class experience and how you felt" rows="3" style="width:100%;box-sizing:border-box"></textarea><button type="button" style="margin-top:8px;padding:10px">Prepare Journal Draft</button><p role="status" aria-live="polite"></p>';
136
+ panel.innerHTML = '<strong>Reflective Journal</strong><p data-info></p><p data-countdown style="font-weight:600;margin:8px 0"></p><textarea aria-label="Your class experience and feelings" placeholder="Your actual class experience / feelings (optional)" rows="3" style="width:100%;box-sizing:border-box"></textarea><button type="button" style="margin-top:8px;padding:10px">Fill &amp; Submit Journal</button><p role="status" aria-live="polite"></p>';
125
137
  document.body.appendChild(panel);
126
138
  const controls = document.createElement('div');
127
139
  controls.innerHTML = '<label>Subject <select data-subject aria-label="Journal subject"><option value="">Detect from page</option><option>Backend Development Fundamentals</option><option>Computer Organization and Architecture</option><option>Advanced Data Structures</option><option>Linear Algebra Essentials</option><option>Fundamentals of Artificial Intelligence</option></select></label><label>Module / Journal <select data-number aria-label="Journal number"><option value="">Detect from page</option>' + Array.from({ length: 10 }, (_, i) => `<option value="${i + 1}">${i + 1}</option>`).join('') + '</select></label>';
@@ -173,8 +185,8 @@ function browserAssistantJournal(global) {
173
185
  countdown.textContent = text;
174
186
  }
175
187
  async function recordJournalConfirmation() {
176
- if (!journalConfirmed && [...document.querySelectorAll('p,h1,h2,h3,[role=status],[role=alert]')].some(node => !node.closest('#assistant-root,#assistant-journal,[contenteditable]') && node.getClientRects().length &&
177
- /^(?:journal (?:has been )?submitted successfully|journal submission successful)[.!]?$/i.test(node.textContent.trim()))) {
188
+ if (!journalConfirmed && (controller.getState().completed === 1 || [...document.querySelectorAll('p,h1,h2,h3,[role=status],[role=alert]')].some(node => !node.closest('#assistant-root,#assistant-journal,[contenteditable]') && node.getClientRects().length &&
189
+ /^(?:journal (?:has been )?submitted successfully|journal submission successful)[.!]?$/i.test(node.textContent.trim())))) {
178
190
  try {
179
191
  await global.chrome?.storage?.local.set({ [`assistantJournalConfirmed:${journalPath}`]: true });
180
192
  journalConfirmed = true;
@@ -218,14 +230,14 @@ function browserAssistantJournal(global) {
218
230
  publishedDeadline = undefined;
219
231
  }
220
232
  }
221
- button.title = 'Prepare Journal Draft (Alt + Shift + J)';
233
+ button.title = 'Fill & Submit Journal (Alt + Shift + J)';
222
234
  button.setAttribute('aria-keyshortcuts', 'Alt+Shift+J');
223
235
  const shortcutHint = document.createElement('p');
224
236
  shortcutHint.textContent = 'Shortcut: Alt + Shift + J';
225
237
  shortcutHint.style.cssText = 'font-size:12px;margin:6px 0;color:#516078';
226
238
  panel.insertBefore(shortcutHint, status);
227
239
  const shortcutListener = event => {
228
- if (!event.isTrusted || !event.altKey || !event.shiftKey || event.ctrlKey || event.metaKey || event.repeat || event.isComposing)
240
+ if (!event.altKey || !event.shiftKey || event.ctrlKey || event.metaKey || event.repeat || event.isComposing)
229
241
  return;
230
242
  if (event.code !== 'KeyJ' && String(event.key).toLowerCase() !== 'j')
231
243
  return;
@@ -233,7 +245,7 @@ function browserAssistantJournal(global) {
233
245
  return;
234
246
  event.preventDefault();
235
247
  if (!running && !button.disabled)
236
- void prepareDraft();
248
+ button.click();
237
249
  };
238
250
  document.addEventListener('keydown', shortcutListener, true);
239
251
  function notify() {
@@ -241,19 +253,23 @@ function browserAssistantJournal(global) {
241
253
  }
242
254
  const controller = {
243
255
  path: location.pathname,
244
- start() { return prepareDraft(); },
256
+ start() { button.click(); },
245
257
  stop() {
246
- activeRequest?.abort();
247
258
  generation++;
259
+ draft = null;
248
260
  running = false;
249
261
  paused = false;
262
+ submitting = false;
263
+ starting = false;
264
+ filled = false;
265
+ waitingForTimer = false;
250
266
  idleState = 'STOPPED';
251
267
  global.BrowserAssistantJournalBusy = false;
252
268
  button.disabled = false;
253
- status.textContent = 'Draft preparation stopped.';
269
+ status.textContent = 'Stopped. Any text already entered is retained. A submission already sent cannot be cancelled.';
254
270
  notify();
255
271
  },
256
- pause() { if (!running)
272
+ pause() { if (!running || submitting)
257
273
  return; paused = !paused; notify(); },
258
274
  mount(slot) {
259
275
  if (!document.getElementById('assistant-root'))
@@ -275,13 +291,11 @@ function browserAssistantJournal(global) {
275
291
  }
276
292
  },
277
293
  getState() {
278
- const completed = journalConfirmed ? 1 : 0;
279
- return { running, paused,
280
- state: completed ? 'COMPLETED' : paused ? 'PAUSED' : running ? 'PREPARING' : idleState,
281
- message: completed ? 'Submission confirmed by the portal.' : paused ? 'Paused. Resume to review the draft.'
282
- : status.textContent || 'Prepare an editable draft before starting the portal assessment.',
283
- title: info ? info.subject + ' · Module ' + info.number : 'Select subject and module',
284
- completed };
294
+ return { running, paused, submitting,
295
+ state: paused ? 'PAUSED' : submitting ? 'SUBMITTING' : starting ? 'STARTING_ASSESSMENT' : waitingForTimer ? 'WAITING_FOR_TIMER' : running ? (draft ? 'WAITING_FOR_FORM' : 'PREPARING') : /confirmed by the page/.test(status.textContent) ? 'COMPLETED' : idleState,
296
+ message: paused ? 'Paused. Resume to continue filling and submission.' : status.textContent || 'Start fills 400 words (80 per section), then submits when the portal timer reaches 30:00 remaining.',
297
+ title: info ? `${info.subject} · Module ${info.number}` : 'Select subject and module',
298
+ completed: /confirmed by the page/.test(status.textContent) ? 1 : 0 };
285
299
  },
286
300
  };
287
301
  if (global.BrowserAssistantJournal) {
@@ -290,7 +304,7 @@ function browserAssistantJournal(global) {
290
304
  }
291
305
  function assertCurrentPage() {
292
306
  if (!document.contains(panel) || storageKey !== `assistantJournal:${location.pathname}`)
293
- throw Error('Journal page changed. Draft preparation stopped.');
307
+ throw Error('Journal page changed. Filling and submission stopped.');
294
308
  if (/assessment not found/i.test(document.querySelector('main')?.textContent || ''))
295
309
  throw Error('Assessment is unavailable. Return to Assessments and check its status.');
296
310
  }
@@ -315,105 +329,213 @@ function browserAssistantJournal(global) {
315
329
  controls.hidden = Boolean(info);
316
330
  panel.querySelector('[data-info]').textContent = info ? `${info.subject} · Module ${info.number} · 400 words (80 per section)` : 'Subject not detected yet. Select the subject and journal number below, or open Module Information.';
317
331
  }
318
- const preview = document.createElement('section');
319
- preview.hidden = true;
320
- preview.setAttribute('aria-label', 'Editable journal draft');
321
- panel.insertBefore(preview, status);
322
- const editors = Object.fromEntries(keys.map((key, index) => {
323
- const group = document.createElement('label');
324
- group.style.display = 'block';
325
- const count = document.createElement('span');
326
- const editor = document.createElement('textarea');
327
- editor.rows = 4;
328
- editor.style.width = '100%';
329
- const updateCount = () => {
330
- const words = editor.value.trim() ? editor.value.trim().split(/\\s+/u).length : 0;
331
- count.textContent = labels[index] + ' (' + words + '/80 words)';
332
- };
333
- editor.addEventListener('input', updateCount);
334
- group.append(count, editor);
335
- preview.appendChild(group);
336
- return [key, { editor, updateCount }];
337
- }));
338
- const copy = document.createElement('button');
339
- copy.type = 'button';
340
- copy.textContent = 'Copy reviewed draft';
341
- copy.addEventListener('click', async (event) => {
342
- if (!event.isTrusted)
332
+ async function fillAndSubmit() {
333
+ if (!draft || submitting || paused || starting)
343
334
  return;
344
- const sections = Object.fromEntries(keys.map(key => [key, editors[key].editor.value]));
345
- try {
346
- validate(sections);
347
- await navigator.clipboard.writeText(keys.map((key, index) => labels[index] + '\n' + sections[key].trim()).join('\n\n'));
348
- status.textContent = 'Draft copied. Review, start and submit in the portal.';
349
- }
350
- catch (error) {
351
- status.textContent = error.message || 'Could not copy the draft.';
335
+ const run = generation;
336
+ assertCurrentPage();
337
+ let inputs = fields(document);
338
+ if (!inputs) {
339
+ starting = true;
340
+ try {
341
+ // The user explicitly requested automatic declaration/start handling.
342
+ const declarations = [...document.querySelectorAll('input[type="checkbox"]')].filter(box => {
343
+ if (box.closest('#assistant-root,#assistant-journal') || box.disabled || !box.getClientRects().length)
344
+ return false;
345
+ const associated = [...(box.labels || []), ...document.querySelectorAll('label')].filter(label => label.contains(box) || (box.id && label.getAttribute('for') === box.id));
346
+ const text = [box.getAttribute('aria-label') || '', ...associated.map(label => label.textContent)].join(' ').replace(/\s+/g, ' ');
347
+ return /I confirm this is my own original work/i.test(text);
348
+ });
349
+ if (!startIssued) {
350
+ if (declarations.length !== 1)
351
+ throw Error('Could not uniquely identify the journal declaration checkbox. Start stopped.');
352
+ if (run !== generation || paused)
353
+ return;
354
+ status.textContent = 'Accepting the journal declaration and starting the assessment…';
355
+ notify();
356
+ if (!declarations[0].checked)
357
+ declarations[0].click();
358
+ await new Promise(resolve => setTimeout(resolve, 250));
359
+ if (run !== generation || paused)
360
+ return;
361
+ assertCurrentPage();
362
+ const starts = [...document.querySelectorAll('button')].filter(b => !b.closest('#assistant-root,#assistant-journal') && b.getClientRects().length && !b.disabled && b.getAttribute('aria-disabled') !== 'true' && /^(?:Start Assessment|Accept Terms to Start)$/i.test(b.textContent.trim()));
363
+ if (starts.length !== 1)
364
+ throw Error('Journal Start Assessment button is unavailable or ambiguous.');
365
+ startIssued = true;
366
+ starts[0].click();
367
+ }
368
+ for (let attempt = 0; attempt < 30; attempt++) {
369
+ if (run !== generation || paused)
370
+ return;
371
+ assertCurrentPage();
372
+ inputs = fields(document);
373
+ if (inputs)
374
+ break;
375
+ await new Promise(resolve => setTimeout(resolve, 500));
376
+ }
377
+ if (!inputs)
378
+ throw Error('The journal started, but all five writing fields did not appear. Submission stopped.');
379
+ }
380
+ finally {
381
+ if (run === generation)
382
+ starting = false;
383
+ }
352
384
  }
353
- notify();
354
- });
355
- preview.appendChild(copy);
356
- async function prepareDraft() {
357
- if (running || journalConfirmed)
385
+ if (run !== generation || paused)
358
386
  return;
359
- refreshInfo();
360
- const notes = panel.querySelector('textarea').value.trim();
361
- if (!info || !notes) {
362
- status.textContent = !info ? 'Select the subject and module first.' : 'Add your own class experience and feelings to prepare a draft.';
363
- notify();
387
+ if (!inputs)
364
388
  return;
365
- }
366
- running = true;
367
- global.BrowserAssistantJournalBusy = true;
368
- button.disabled = true;
369
- paused = false;
370
- const run = ++generation;
371
- status.textContent = 'Preparing the matching module journal…';
372
- notify();
389
+ submitting = true;
373
390
  try {
391
+ validate(draft.sections);
392
+ if (!filled) {
393
+ // Existing complete text is adopted only by an explicit Start.
394
+ if (keys.some(k => readField(inputs[k]).trim()))
395
+ throw Error('Journal already contains text. Nothing was overwritten.');
396
+ for (const key of keys)
397
+ writeField(inputs[key], draft.sections[key]);
398
+ await new Promise(resolve => setTimeout(resolve, 700));
399
+ if (run !== generation)
400
+ return;
401
+ filled = true;
402
+ }
374
403
  assertCurrentPage();
375
- activeRequest = new AbortController();
376
- const response = await browserAssistantLocalInference('/journal', { ...info, notes }, message => chrome.runtime.sendMessage(message), activeRequest.signal);
377
- if (run !== generation)
404
+ const current = fields(document);
405
+ if (!current || keys.some(k => readField(current[k]).trim() !== draft.sections[k].trim()))
406
+ throw Error('The page did not retain all journal fields. Submission stopped.');
407
+ const count = validate(Object.fromEntries(keys.map(k => [k, readField(current[k])])));
408
+ const remaining = remainingSeconds(document);
409
+ if (remaining === null || remaining > 30 * 60) {
410
+ waitingForTimer = true;
411
+ const time = remaining === null ? 'Waiting for the portal timer to become readable.'
412
+ : `Current timer: ${formatJournalTime(remaining)}.`;
413
+ status.textContent = `${count} words ready. Waiting to submit at 30:00 remaining. ${time}`;
378
414
  return;
379
- assertCurrentPage();
380
- if (!response?.ok) {
381
- const detail = response?.data?.detail || response?.error;
382
- throw Error(typeof detail === 'string' ? detail : detail?.message || 'Journal generation failed.');
383
415
  }
384
- validate(response.data.sections);
385
- while (run === generation && paused)
386
- await new Promise(resolve => setTimeout(resolve, 100));
416
+ if (paused)
417
+ return;
418
+ waitingForTimer = false;
419
+ if (remaining === 0)
420
+ throw Error('The portal timer expired. Check the journal status; no automatic click was sent.');
421
+ const candidates = [...document.querySelectorAll('button')].filter(b => !panel.contains(b) && b.getClientRects().length && !b.disabled && b.getAttribute('aria-disabled') !== 'true' && /^Submit Journal$/i.test(b.textContent.trim()));
422
+ if (candidates.length !== 1)
423
+ throw Error('Could not uniquely identify an enabled Submit Journal button. Content is filled; submit manually.');
424
+ // Consume the draft before clicking: observers must never submit twice.
425
+ draft = null;
426
+ candidates[0].click();
427
+ status.textContent = `${count} words filled. Submit clicked; checking the result…`;
428
+ await new Promise(resolve => setTimeout(resolve, 1000));
387
429
  if (run !== generation)
388
430
  return;
389
- assertCurrentPage();
390
- for (const key of keys) {
391
- const { editor, updateCount } = editors[key];
392
- editor.value = response.data.sections[key];
393
- updateCount();
394
- }
395
- preview.hidden = false;
396
- idleState = 'REVIEW_DRAFT';
397
- status.textContent = 'Draft ready. Edit the five sections, then review the declaration and start on the portal.';
431
+ const dialogs = [...document.querySelectorAll('[role=dialog],dialog[open]')].filter(d => d.getClientRects().length);
432
+ const confirm = dialogs.flatMap(d => [...d.querySelectorAll('button')]).filter(b => !b.disabled && /^(?:Confirm(?: Submission| Submit)?|Yes,? Submit|Submit Journal)$/i.test(b.textContent.trim()));
433
+ if (confirm.length === 1)
434
+ confirm[0].click();
435
+ await new Promise(resolve => setTimeout(resolve, 1200));
436
+ if (run !== generation)
437
+ return;
438
+ const page = document.body.cloneNode(true);
439
+ page.querySelector('#assistant-journal')?.remove();
440
+ status.textContent = /(?:journal|reflection)\s+(?:has been\s+)?submitted successfully|successfully submitted|submission successful/i.test(page.textContent)
441
+ ? `${count} words. Submission confirmed by the page.`
442
+ : `${count} words filled; Submit clicked. Check the page for confirmation or any remaining dialog.`;
398
443
  }
399
444
  catch (error) {
400
445
  if (run === generation) {
446
+ draft = null;
447
+ filled = false;
448
+ waitingForTimer = false;
401
449
  idleState = 'ERROR';
402
450
  status.textContent = error.message;
403
451
  }
404
452
  }
405
453
  finally {
406
454
  if (run === generation) {
407
- activeRequest = undefined;
408
- running = false;
409
- global.BrowserAssistantJournalBusy = false;
410
- button.disabled = false;
455
+ submitting = false;
456
+ if (!waitingForTimer) {
457
+ running = false;
458
+ global.BrowserAssistantJournalBusy = false;
459
+ button.disabled = false;
460
+ }
411
461
  notify();
412
462
  }
413
463
  }
414
464
  }
415
- button.addEventListener('click', event => { if (event.isTrusted)
416
- void prepareDraft(); });
465
+ button.addEventListener('click', async () => {
466
+ if (running)
467
+ return;
468
+ try {
469
+ assertCurrentPage();
470
+ }
471
+ catch (error) {
472
+ status.textContent = error.message;
473
+ return;
474
+ }
475
+ refreshInfo();
476
+ const manualSubject = controls.querySelector('[data-subject]').value;
477
+ const manualNumber = controls.querySelector('[data-number]').value;
478
+ if (!controls.hidden && Boolean(manualSubject) !== Boolean(manualNumber)) {
479
+ status.textContent = 'For manual selection, choose both Subject and Module / Journal.';
480
+ return;
481
+ }
482
+ if (!info) {
483
+ status.textContent = 'Select both Subject and Module / Journal above, then click Fill & Submit Journal.';
484
+ return;
485
+ }
486
+ running = true;
487
+ global.BrowserAssistantJournalBusy = true;
488
+ submitting = false;
489
+ button.disabled = true;
490
+ idleState = 'READY';
491
+ paused = false;
492
+ filled = false;
493
+ waitingForTimer = false;
494
+ startIssued = false;
495
+ const run = ++generation;
496
+ status.textContent = 'Preparing the matching module journal…';
497
+ notify();
498
+ try {
499
+ const existingInputs = fields(document);
500
+ if (existingInputs && keys.some(key => readField(existingInputs[key]).trim())) {
501
+ const existingSections = Object.fromEntries(keys.map(key => [key, readField(existingInputs[key]).trim()]));
502
+ validate(existingSections);
503
+ draft = { sections: existingSections };
504
+ filled = true;
505
+ }
506
+ else {
507
+ const response = await chrome.runtime.sendMessage({ action: 'apiRequest', path: '/journal', body: { ...info, notes: panel.querySelector('textarea').value } });
508
+ if (run !== generation)
509
+ return;
510
+ assertCurrentPage();
511
+ if (!response?.ok) {
512
+ const detail = response?.data?.detail || response?.error || 'Journal generation failed.';
513
+ if (typeof detail === 'string' && detail.includes('Subject does not uniquely match the supplied syllabus')) {
514
+ throw Error('The running server could not match this subject. If you just added this syllabus, restart the updated server once, then try again. Otherwise check the selected subject. No journal was submitted.');
515
+ }
516
+ throw Error(typeof detail === 'string' ? detail : detail.message || 'Journal generation failed.');
517
+ }
518
+ validate(response.data.sections);
519
+ draft = response.data;
520
+ }
521
+ status.textContent = 'Content ready. Filling the journal, then waiting for 30:00 remaining before submission…';
522
+ notify();
523
+ await fillAndSubmit();
524
+ }
525
+ catch (error) {
526
+ if (run !== generation)
527
+ return;
528
+ draft = null;
529
+ filled = false;
530
+ waitingForTimer = false;
531
+ running = false;
532
+ idleState = 'ERROR';
533
+ global.BrowserAssistantJournalBusy = false;
534
+ button.disabled = false;
535
+ status.textContent = String(error.message);
536
+ notify();
537
+ }
538
+ });
417
539
  refreshInfo();
418
540
  void loadCountdown();
419
541
  void updateCountdown();
@@ -425,6 +547,14 @@ function browserAssistantJournal(global) {
425
547
  clockObserver?.observe(document.body, { subtree: true, childList: true, characterData: true });
426
548
  controller.mount(document.getElementById('assistant-journal-slot'));
427
549
  document.dispatchEvent(new global.Event('assistant-journal-ready'));
550
+ try {
551
+ const pending = JSON.parse(sessionStorage.getItem('assistantPendingJournal') || 'null');
552
+ if (pending?.path === location.pathname && Date.now() - pending.createdAt < 300000) {
553
+ sessionStorage.removeItem('assistantPendingJournal');
554
+ button.click();
555
+ }
556
+ }
557
+ catch { /* Opening the journal without auto-start remains available. */ }
428
558
  // Poll only the journal page; field discovery never changes platform restrictions.
429
559
  const timer = setInterval(() => {
430
560
  if (global.BrowserAssistantJournal?.current !== controller && global.BrowserAssistantJournal) {
@@ -432,8 +562,7 @@ function browserAssistantJournal(global) {
432
562
  return;
433
563
  }
434
564
  if (!document.contains(panel) || storageKey !== `assistantJournal:${location.pathname}`) {
435
- activeRequest?.abort();
436
- generation++;
565
+ draft = null;
437
566
  global.BrowserAssistantJournalBusy = false;
438
567
  stopWatching();
439
568
  panel.remove();
@@ -444,6 +573,22 @@ function browserAssistantJournal(global) {
444
573
  void updateCountdown();
445
574
  void recordJournalConfirmation();
446
575
  notify();
576
+ if (draft && !submitting && !starting) {
577
+ const run = generation;
578
+ void fillAndSubmit().catch(error => {
579
+ if (run !== generation)
580
+ return;
581
+ draft = null;
582
+ filled = false;
583
+ waitingForTimer = false;
584
+ running = false;
585
+ idleState = 'ERROR';
586
+ global.BrowserAssistantJournalBusy = false;
587
+ button.disabled = false;
588
+ status.textContent = error.message;
589
+ notify();
590
+ });
591
+ }
447
592
  }, 1000);
448
593
  function stopWatching() {
449
594
  clearInterval(timer);
@@ -457,10 +602,13 @@ if (typeof window !== 'undefined' && location.origin === 'https://admissions.aur
457
602
  opening: false,
458
603
  matches: () => /^\/modules\/(?:reflective-journal\/|assessments\/assessments\/?$)/.test(location.pathname),
459
604
  active() { return this.current?.path === location.pathname ? this.current : null; },
460
- getState() { return this.active()?.getState() || { state: this.opening ? 'OPENING_JOURNAL' : 'OPEN_JOURNAL', running: this.opening, completed: 0, message: 'Open the available ongoing journal to prepare a draft. If several are available, select its pencil button first.' }; },
605
+ getState() { return this.active()?.getState() || { state: this.opening ? 'OPENING_JOURNAL' : 'OPEN_JOURNAL', running: this.opening, completed: 0, message: 'Click Start to open the available ongoing journal. If several are available, select its pencil button first.' }; },
461
606
  mount(slot) { this.active()?.mount(slot); },
462
607
  detach() { this.current?.detach(); },
463
- stop() { this.active()?.stop(); this.opening = false; },
608
+ stop() { this.active()?.stop(); this.opening = false; try {
609
+ sessionStorage.removeItem('assistantPendingJournal');
610
+ }
611
+ catch { } },
464
612
  pause() { this.active()?.pause(); },
465
613
  start() {
466
614
  if (this.active())
@@ -476,6 +624,10 @@ if (typeof window !== 'undefined' && location.origin === 'https://admissions.aur
476
624
  && /^\/modules\/reflective-journal\//.test(new URL(link.href, location.origin).pathname));
477
625
  if (links.length === 1) {
478
626
  this.opening = true;
627
+ try {
628
+ sessionStorage.setItem('assistantPendingJournal', JSON.stringify({ path: new URL(links[0].href, location.origin).pathname, createdAt: Date.now() }));
629
+ }
630
+ catch { }
479
631
  links[0].click();
480
632
  }
481
633
  },
@@ -483,7 +635,7 @@ if (typeof window !== 'undefined' && location.origin === 'https://admissions.aur
483
635
  if (!window.BrowserAssistantJournalListShortcut) {
484
636
  window.BrowserAssistantJournalListShortcut = true;
485
637
  document.addEventListener('keydown', event => {
486
- if (!event.isTrusted || !/^\/modules\/assessments\/assessments\/?$/.test(location.pathname) || !event.altKey || !event.shiftKey || event.ctrlKey || event.metaKey || event.repeat || event.isComposing)
638
+ if (!/^\/modules\/assessments\/assessments\/?$/.test(location.pathname) || !event.altKey || !event.shiftKey || event.ctrlKey || event.metaKey || event.repeat || event.isComposing)
487
639
  return;
488
640
  if (event.code !== 'KeyJ' && String(event.key).toLowerCase() !== 'j')
489
641
  return;
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "manifest_version": 3,
3
3
  "name": "Browser Assistant",
4
- "version": "2.9.0",
4
+ "version": "2.9.1",
5
5
  "description": "Scans webpages for MCQs and coding problems. Powered by Groq (cloud) and Ollama (local fallback).",
6
6
  "permissions": [
7
7
  "activeTab",
@@ -20,9 +20,7 @@
20
20
  "content_scripts": [
21
21
  {
22
22
  "matches": [
23
- "https://learning.ccbp.in/*",
24
- "https://admissions.aurora.edu.in/*",
25
- "http://127.0.0.1:8000/*"
23
+ "<all_urls>"
26
24
  ],
27
25
  "js": [
28
26
  "automation-policy.js",
@@ -42,13 +40,6 @@
42
40
  "host_permissions": [
43
41
  "http://localhost:8000/*",
44
42
  "http://127.0.0.1:8000/*",
45
- "https://learning.ccbp.in/*",
46
- "https://ide.ccbp.in/*",
47
- "https://admissions.aurora.edu.in/*"
48
- ],
49
- "commands": {
50
- "toggle-automation": {
51
- "description": "Start, pause or resume Browser Assistant automation"
52
- }
53
- }
43
+ "<all_urls>"
44
+ ]
54
45
  }
@@ -46,26 +46,15 @@
46
46
  <div class="logo-dot"></div>
47
47
  <h3>Browser Assistant</h3>
48
48
  </div>
49
- <p>Open the assistant on the current webpage.</p>
50
- <button id="open-assistant" type="button">Open on this tab</button>
49
+ <p>Extension active. The floating panel appears on every page.</p>
51
50
  <div class="status">Server: <span id="server-status">checking...</span></div>
52
51
  <p id="journal-countdown" hidden></p>
53
- <form id="local-pairing">
54
- <label for="pairing-token">Local server token</label>
55
- <input id="pairing-token" type="password" required autocomplete="off" spellcheck="false">
56
- <button type="submit">Pair</button>
57
- <button id="unpair-server" type="button">Forget</button>
58
- </form>
59
- <p>Run <code>python main.py --show-pairing-token</code> from the backend folder.</p>
60
- <button id="check-provider" type="button">Check provider</button>
61
- <p id="settings-status" role="status"></p>
62
- <label><input id="save-history" type="checkbox"> Save scan history</label>
63
52
  <div class="shortcuts">
64
53
  <div class="shortcut-row"><span>Open panel</span> <kbd>`</kbd></div>
65
54
  <div class="shortcut-row"><span>Close panel</span> <kbd>]</kbd></div>
66
55
  <div class="shortcut-row"><span>Vision scan</span> <kbd>\</kbd></div>
67
56
  <div class="shortcut-row"><span>Minimal mode</span> <kbd>[</kbd></div>
68
- <div class="shortcut-row"><span>Prepare journal</span> <kbd>Alt+Shift+J</kbd></div>
57
+ <div class="shortcut-row"><span>Journal fill &amp; submit</span> <kbd>Alt+Shift+J</kbd></div>
69
58
  <div class="shortcut-row"><span>Automation start / pause / resume</span> <kbd>Alt+A</kbd></div>
70
59
  </div>
71
60
  <script src="popup.js"></script>