browser-assistant 2.9.46 → 2.9.47

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.
@@ -265,7 +265,7 @@ chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
265
265
  .catch(error => sendResponse({ ok: false, error: error.message }));
266
266
  return true;
267
267
  }
268
- if (['focusOnlineIde', 'runOnlineIde', 'onlineIdeStatus'].includes(request.action)) {
268
+ if (['focusOnlineIde', 'inspectOnlineIde', 'runOnlineIde', 'onlineIdeStatus'].includes(request.action)) {
269
269
  const questionPath = /^\/question\/([a-f0-9-]{36})\/?$/i;
270
270
  let questionId;
271
271
  try {
@@ -298,15 +298,28 @@ chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
298
298
  return { ok: false, error: 'A unique IDE tab for this question is required.' };
299
299
  const workspace = new URL(ide.url || ide.pendingUrl).pathname.split('/')[2];
300
300
  if (request.workspace !== workspace || !/^[a-z0-9]{6,24}$/i.test(workspace)
301
- || !/^[a-f0-9-]{36}$/.test(request.token || ''))
301
+ || request.token?.length !== 36 || !/^[a-f0-9-]{36}$/.test(request.token || ''))
302
302
  return { ok: false, error: 'The portal submit command and IDE workspace do not match.' };
303
+ if (request.action !== 'onlineIdeStatus' && !ide.active) {
304
+ return { ok: false, error: 'Keep the matching IDE tab active while inspecting or updating its code.' };
305
+ }
306
+ const validFile = typeof request.targetFile === 'string'
307
+ && request.targetFile === request.targetFile.trim()
308
+ && !request.targetFile.includes('..')
309
+ && /^[A-Za-z0-9][A-Za-z0-9_.-]{0,79}\.js$/.test(request.targetFile);
310
+ if (request.targetFile !== undefined && !validFile) {
311
+ return { ok: false, error: 'A safe JavaScript filename in the current workspace is required.' };
312
+ }
303
313
  if (request.action === 'runOnlineIde' && (!ide.active || typeof request.code !== 'string'
304
- || !request.code.trim() || new TextEncoder().encode(request.code).length > 12000)) {
305
- return { ok: false, error: 'The matching IDE must be active and the app.js source must be at most 12 KB.' };
314
+ || !request.code.trim() || new TextEncoder().encode(request.code).length > 12000
315
+ || !validFile || typeof request.expected !== 'string'
316
+ || new TextEncoder().encode(request.expected).length > 12000)) {
317
+ return { ok: false, error: 'A verified target filename and original source are required; source must be at most 12 KB.' };
306
318
  }
307
319
  const results = await chrome.scripting.executeScript({ target: { tabId: ide.id, allFrames: true }, world: 'MAIN',
308
320
  func: browserAssistantOnlineIde,
309
- args: [request.action, workspace, questionId, request.token, request.action === 'runOnlineIde' ? request.code : null] });
321
+ args: [request.action, workspace, questionId, request.token, request.action === 'runOnlineIde' ? request.code : null,
322
+ request.targetFile, request.action === 'runOnlineIde' ? request.expected : null] });
310
323
  const frameResults = results.map(entry => entry.result).filter(Boolean);
311
324
  return frameResults.length === 1 ? frameResults[0] : { ok: false, retry: true, error: 'The IDE workspace is still opening.' };
312
325
  }
@@ -198,15 +198,51 @@
198
198
  if (!description || !visible(description) || buttons.length !== 1)
199
199
  return null;
200
200
  const requirements = text(description);
201
- if (!/\bapp\.js\b/i.test(requirements) || !/\b(?:express|common\s*js|node\.?js)\b/i.test(requirements))
202
- return null;
203
201
  const title = text(description.querySelector('h1,h2')) || 'Node.js IDE assignment';
204
202
  const panel = doc.querySelector('#codingQuestionInfoContainer');
205
203
  const solved = [...panel.querySelectorAll('span,div')].some(node => !node.children.length && visible(node) && /^solved$/i.test(text(node)));
206
204
  const commands = new Set([...doc.querySelectorAll('code,span,div,p,input')]
207
205
  .filter(node => visible(node) && !description.contains(node))
208
206
  .map(node => (node.value || text(node)).match(/^ccbp\s+submit\s+([a-z0-9]{6,24})$/i)?.[1]).filter(Boolean));
209
- return { title, text: requirements, button: buttons[0], solved, workspace: commands.size === 1 ? [...commands][0] : null };
207
+ if (commands.size !== 1)
208
+ return null;
209
+ const workspace = [...commands][0];
210
+ const nodeLanguage = /\b(?:javascript|express|common\s*js|node(?:\.?js)?)\b/i.test(requirements);
211
+ const fileScript = /\bscript\b/i.test(requirements) && /\b(?:directory|files?|folders?)\b/i.test(requirements)
212
+ && /\b(?:read|print|log|list|write)\b/i.test(requirements);
213
+ // A generic filesystem script is Node-specific only when the portal's
214
+ // submit workspace identifies its Node.js course. Never convert a
215
+ // Python/shell exercise merely because it also reads files.
216
+ if (!nodeLanguage && (!(fileScript && /^NJS/i.test(workspace)) || /\b(?:python|bash|shell|ruby|java)\b/i.test(requirements)))
217
+ return null;
218
+ const fileReferences = value => [...value.matchAll(/\x60[^\x60]*\.js[^\x60]*\x60|"[^"]*\.js[^"]*"|'[^']*\.js[^']*'|[^\s\x60"'<>]*\.js[^\s\x60"'<>]*/gi)]
219
+ .map(match => {
220
+ const token = match[0];
221
+ // Quoted names are exact. Only unquoted prose loses its final
222
+ // punctuation; do not turn index.js.txt or src/index.js into index.js.
223
+ return /^[\x60"']/.test(token) ? token.slice(1, -1)
224
+ : token.replace(/^[([{]+/, '').replace(/[)\]},;:!?]+$/, '').replace(/\.$/, '');
225
+ }).filter(name => !/^node\.js$/i.test(name));
226
+ const fileNames = new Set();
227
+ let targetFileUnsupported = false;
228
+ const recordFile = name => {
229
+ if (name !== name.trim() || !/^[A-Za-z0-9][A-Za-z0-9_.-]{0,79}\.js$/.test(name) || name.includes('..'))
230
+ targetFileUnsupported = true;
231
+ else
232
+ fileNames.add(name);
233
+ };
234
+ // Read complete references in each instruction sentence, including
235
+ // lists such as "Write first.js and second.js". This one-file flow must
236
+ // stop on named paths or additional suffixes instead of discovering an
237
+ // unrelated root file after silently dropping the instruction.
238
+ const instructions = [...requirements.matchAll(/\b(?:write|create|implement|complete|update|edit|modify|save|into|in)\s+(.+?)(?=[.!?;](?:\s|$)|$)/gi)];
239
+ instructions.forEach(instruction => fileReferences(instruction[1]).forEach(recordFile));
240
+ if (!fileNames.size && !targetFileUnsupported && /\bexpress\b/i.test(requirements)) {
241
+ fileReferences(requirements).filter(name => /app\.js/i.test(name)).forEach(recordFile);
242
+ }
243
+ const targetFile = !targetFileUnsupported && fileNames.size === 1 ? [...fileNames][0] : undefined;
244
+ return { title, text: requirements, button: buttons[0], solved, workspace, targetFile,
245
+ targetFileAmbiguous: fileNames.size > 1, targetFileUnsupported };
210
246
  }
211
247
  function getSubmit(doc) {
212
248
  const buttons = [...doc.querySelectorAll('button:not(:disabled),[role="button"]:not([aria-disabled="true"])')]
@@ -1423,7 +1423,7 @@ function mountJournalCountdown(signal) {
1423
1423
  automation.completed = 0;
1424
1424
  automation.error = '';
1425
1425
  automation.codingQuestionText = question.title;
1426
- automation.state = 'PREPARING_APP_JS';
1426
+ automation.state = 'OPENING_IDE';
1427
1427
  updateAutomationUI();
1428
1428
  const current = () => location.href === url && automation.runId === runId;
1429
1429
  async function openOnlineIde() {
@@ -1432,10 +1432,10 @@ function mountJournalCountdown(signal) {
1432
1432
  return;
1433
1433
  if (!ide?.found) {
1434
1434
  const fresh = window.BrowserAssistantCoding.getOnlineIdeQuestion(document, location);
1435
- if (!fresh || fresh.text !== question.text)
1435
+ if (!fresh || fresh.text !== question.text || fresh.workspace !== question.workspace)
1436
1436
  throw new Error('The IDE question changed before opening.');
1437
1437
  fresh.button.click();
1438
- const deadline = Date.now() + 10000;
1438
+ const deadline = Date.now() + 120000;
1439
1439
  do {
1440
1440
  if (!(await waitWhilePaused(runId)) || !current())
1441
1441
  return;
@@ -1448,10 +1448,52 @@ function mountJournalCountdown(signal) {
1448
1448
  return ide;
1449
1449
  }
1450
1450
  try {
1451
- const [ide, response] = await Promise.all([openOnlineIde(), apiRequest('/solve', 'POST', {
1452
- url, practice_type: 'code', language: 'javascript', review_before_submit: true,
1453
- text: `${question.text}\n\nGenerate the complete app.js for the online Node.js IDE. Use the stated database, route methods, response bodies and module format. Use parameterized SQL where applicable. Return source code for app.js only.`,
1454
- })]);
1451
+ if (!question.workspace)
1452
+ throw new Error('The portal must provide one unambiguous IDE submit command.');
1453
+ if (question.targetFileAmbiguous)
1454
+ throw new Error('The question requires several JavaScript files. Review its file instructions before continuing; automatic IDE editing supports one target file.');
1455
+ if (question.targetFileUnsupported)
1456
+ throw new Error('The question names a nested path or unsupported JavaScript filename. Review its file instructions before continuing; automatic IDE editing supports one JavaScript file in the question folder.');
1457
+ const token = crypto.randomUUID();
1458
+ const target = { workspace: question.workspace, token };
1459
+ const ide = await openOnlineIde();
1460
+ if (!(await waitWhilePaused(runId)) || !current())
1461
+ return;
1462
+ if (!ide?.found)
1463
+ throw new Error('The matching IDE did not open within two minutes. Open it from the portal, then retry.');
1464
+ automation.state = 'READING_IDE_FILE';
1465
+ updateAutomationUI();
1466
+ const inspectDeadline = Date.now() + 120000;
1467
+ let inspected;
1468
+ do {
1469
+ if (!(await waitWhilePaused(runId)) || !current())
1470
+ return;
1471
+ inspected = await safeSendMessage({ action: 'inspectOnlineIde', ...target, targetFile: question.targetFile });
1472
+ if (!inspected?.retry)
1473
+ break;
1474
+ await new Promise(resolve => setTimeout(resolve, 1000));
1475
+ } while (Date.now() < inspectDeadline);
1476
+ if (!current())
1477
+ return;
1478
+ if (inspected?.alreadyPassed) {
1479
+ stopAutomation('ALREADY_SOLVED');
1480
+ return;
1481
+ }
1482
+ const targetFile = inspected?.targetFile;
1483
+ if (!inspected?.ok || typeof targetFile !== 'string' || targetFile !== targetFile.trim()
1484
+ || !/^[A-Za-z0-9][A-Za-z0-9_.-]{0,79}\.js$/.test(targetFile)
1485
+ || targetFile.includes('..') || typeof inspected.source !== 'string'
1486
+ || new TextEncoder().encode(inspected.source).length > 12000
1487
+ || (question.targetFile && targetFile !== question.targetFile)) {
1488
+ throw new Error(inspected?.error || 'The correct JavaScript file could not be identified. Select its Explorer file, then retry.');
1489
+ }
1490
+ const expected = inspected.source;
1491
+ automation.state = 'PREPARING_CODE';
1492
+ updateAutomationUI();
1493
+ const response = await apiRequest('/solve', 'POST', {
1494
+ url, practice_type: 'code', language: 'javascript', review_before_submit: true,
1495
+ text: `${question.text}\n\nThe verified target file in the online Node.js IDE is ${targetFile}. Generate the complete source for that file only. Follow the exact file paths, output messages, APIs and module format stated in the question. Do not add Express routes, database operations or module.exports unless the question requires them. Preserve any required interfaces and the existing CommonJS or ES module style.\nCurrent code:\n${expected}`,
1496
+ });
1455
1497
  if (!(await waitWhilePaused(runId)) || !current())
1456
1498
  return;
1457
1499
  if (!response?.ok)
@@ -1459,17 +1501,15 @@ function mountJournalCountdown(signal) {
1459
1501
  const solutions = JSON.parse(response.data.results);
1460
1502
  if (!Array.isArray(solutions) || solutions.length !== 1 || solutions[0].type !== 'code'
1461
1503
  || typeof solutions[0].code !== 'string' || !solutions[0].code.trim()) {
1462
- throw new Error('The server did not return a complete app.js solution.');
1504
+ throw new Error(`The server did not return a complete ${targetFile} solution.`);
1463
1505
  }
1464
1506
  const solution = solutions[0];
1465
- let instructions = ide?.found
1466
- ? 'Copy into app.js in the IDE tab after the workspace is ready, then save.'
1467
- : 'Use the portal Open IDE button, then copy into app.js and save.';
1507
+ if (solution.language && solution.language !== 'javascript')
1508
+ throw new Error('The IDE solution did not use the required JavaScript language.');
1509
+ let instructions = `Copy into ${targetFile} in the matching IDE tab, then save.`;
1468
1510
  const context = getAutomationContext();
1469
1511
  if (ide?.found && question.workspace && response.data.code_reviewed === true
1470
1512
  && automationPolicy.canExecute('fill', context) && automationPolicy.canExecute('submit', context)) {
1471
- const token = crypto.randomUUID();
1472
- const target = { workspace: question.workspace, token };
1473
1513
  automation.state = 'WAITING_FOR_IDE';
1474
1514
  updateAutomationUI();
1475
1515
  const deadline = Date.now() + 120000;
@@ -1477,7 +1517,7 @@ function mountJournalCountdown(signal) {
1477
1517
  do {
1478
1518
  if (!(await waitWhilePaused(runId)) || !current())
1479
1519
  return;
1480
- launched = await safeSendMessage({ action: 'runOnlineIde', ...target, code: solution.code });
1520
+ launched = await safeSendMessage({ action: 'runOnlineIde', ...target, targetFile, expected, code: solution.code });
1481
1521
  if (!launched?.retry)
1482
1522
  break;
1483
1523
  await new Promise(resolve => setTimeout(resolve, 1000));
@@ -1502,7 +1542,7 @@ function mountJournalCountdown(signal) {
1502
1542
  if (result.passed)
1503
1543
  automation.completed = 1;
1504
1544
  else if (result.saveUnconfirmed)
1505
- automation.error = 'Code was pasted into app.js, but the saved file did not match. Check app.js and save before running it.';
1545
+ automation.error = `Code was written to ${targetFile}, but the saved file did not match. Check that file and save before running it.`;
1506
1546
  else
1507
1547
  automation.error = result.submitted ? 'Grading finished. Review the test results in the IDE.' : 'The IDE command finished without a confirmed submission. Check the terminal.';
1508
1548
  stopAutomation(result.passed ? 'COMPLETED' : 'CHECK_IDE_RESULT');
@@ -1522,7 +1562,7 @@ function mountJournalCountdown(signal) {
1522
1562
  instructions = `${launched.error} ${instructions}`;
1523
1563
  }
1524
1564
  stopAutomation('CODE_READY');
1525
- displayResults([{ ...solution, title: 'app.js', approach: [instructions, solution.approach].filter(Boolean).join(' ') }], response.data.provider);
1565
+ displayResults([{ ...solution, title: targetFile, approach: [instructions, solution.approach].filter(Boolean).join(' ') }], response.data.provider);
1526
1566
  }
1527
1567
  catch (error) {
1528
1568
  if (current()) {
@@ -90,9 +90,17 @@ function browserAssistantEditor(operation, selector, expected, value) {
90
90
  }
91
91
  // Run the IDE's normal paste and autosave flow. The terminal only verifies and
92
92
  // grades the saved file; generated source is never passed to the shell.
93
- async function browserAssistantOnlineIde(action, workspace, questionId, token, source) {
93
+ async function browserAssistantOnlineIde(action, workspace, questionId, token, source, targetFile, expected) {
94
94
  if (location.origin !== 'https://ide.ccbp.in' || location.pathname.replace(/\/$/, '') !== `/playground/${workspace}`)
95
95
  return null;
96
+ if (workspace !== workspace.trim() || !/^[a-z0-9]{6,24}$/i.test(workspace) || questionId?.length !== 36 || !/^[a-f0-9-]{36}$/i.test(questionId)
97
+ || token?.length !== 36 || !/^[a-f0-9-]{36}$/i.test(token))
98
+ return { ok: false, error: 'Invalid IDE workspace or run identifier.' };
99
+ const safeFile = value => typeof value === 'string' && value === value.trim() && /^[A-Za-z0-9][A-Za-z0-9_.-]{0,79}\.js$/.test(value) && !value.includes('..');
100
+ if (targetFile !== undefined && !safeFile(targetFile))
101
+ return { ok: false, error: 'A safe JavaScript target filename is required.' };
102
+ if (action === 'runOnlineIde' && (!safeFile(targetFile) || typeof expected !== 'string'))
103
+ return { ok: false, error: 'Inspect the target JavaScript file before generating or writing code.' };
96
104
  const visible = node => node.getClientRects().length > 0;
97
105
  const inputs = [...document.querySelectorAll('.xterm-helper-textarea[aria-label="Terminal input"]')].filter(visible);
98
106
  if (inputs.length !== 1)
@@ -108,6 +116,7 @@ async function browserAssistantOnlineIde(action, workspace, questionId, token, s
108
116
  return text.split(reportPrefix).slice(1).map(fragment => fragment.match(/^[a-f0-9-]{36}/i)?.[0]).filter(Boolean);
109
117
  };
110
118
  const key = '__browserAssistantOnlineIdeRun';
119
+ const inspectionKey = '__browserAssistantOnlineIdeInspection';
111
120
  const previous = window[key];
112
121
  if (action === 'onlineIdeStatus') {
113
122
  if (previous?.token !== token)
@@ -132,36 +141,65 @@ async function browserAssistantOnlineIde(action, workspace, questionId, token, s
132
141
  return { ok: false, retry: true, error: 'Waiting for the correct workspace shell prompt.' };
133
142
  if (reports(before).length && before.includes('All test cases passed'))
134
143
  return { ok: true, alreadyPassed: true };
135
- const findFile = () => [...document.querySelectorAll('div[title="app.js"]')].filter(visible);
136
- let files = findFile();
137
- if (!files.length) {
144
+ let filename = targetFile;
145
+ const discover = () => {
146
+ const names = new Set();
147
+ for (const node of [...document.querySelectorAll('div[title]')].filter(visible)) {
148
+ const name = node.getAttribute('title');
149
+ if (safeFile(name) && !/(?:^|[._-])(?:test|spec|config|bundle)(?:[._-]|$)/i.test(name))
150
+ names.add(name);
151
+ }
152
+ const models = window.monaco?.editor?.getModels?.() || [];
153
+ const uris = [...models.map(model => model.uri?.toString()),
154
+ ...[...document.querySelectorAll('.monaco-editor[data-uri]')].filter(visible).map(node => node.getAttribute('data-uri'))];
155
+ for (const uri of uris) {
156
+ const match = typeof uri === 'string' && uri.match(new RegExp('/' + prompt[2] + '/([^/]+)$'));
157
+ if (uri?.startsWith('file:///') && match && safeFile(match[1])
158
+ && !/(?:^|[._-])(?:test|spec|config|bundle)(?:[._-]|$)/i.test(match[1]))
159
+ names.add(match[1]);
160
+ }
161
+ return [...names];
162
+ };
163
+ let candidates = filename ? [filename] : discover();
164
+ if (!candidates.length) {
138
165
  const folders = [...document.querySelectorAll('div[title=""] span')]
139
166
  .filter(node => visible(node) && node.textContent.trim() === prompt[2]);
140
167
  if (folders.length === 1) {
141
168
  folders[0].click();
142
169
  await new Promise(resolve => setTimeout(resolve, 150));
143
- files = findFile();
170
+ candidates = filename ? [filename] : discover();
144
171
  }
145
172
  }
146
- if (files.length !== 1)
147
- return { ok: false, retry: true, error: 'Waiting for the workspace app.js file in Explorer.' };
148
- files[0].click();
149
- await new Promise(resolve => setTimeout(resolve, 200));
173
+ if (candidates.length !== 1)
174
+ return { ok: false, retry: candidates.length === 0, error: candidates.length ? 'Several JavaScript files are available. Specify the required file before continuing.' : 'Waiting for the workspace JavaScript file in Explorer.' };
175
+ filename = candidates[0];
176
+ const findFile = () => [...document.querySelectorAll(`div[title="${filename}"]`)].filter(visible);
150
177
  const findEditor = () => {
151
- const editors = [...document.querySelectorAll('.monaco-editor[data-uri]')].filter(visible);
152
- const node = editors.length === 1 && editors[0];
153
- const uri = node && node.getAttribute('data-uri');
154
- return uri && uri.startsWith('file:') && uri.endsWith(`/${prompt[2]}/app.js`) ? node : null;
178
+ const editors = [...document.querySelectorAll('.monaco-editor[data-uri]')].filter(node => {
179
+ const uri = node.getAttribute('data-uri');
180
+ return visible(node) && uri?.startsWith('file:///') && uri.endsWith(`/${prompt[2]}/${filename}`);
181
+ });
182
+ return editors.length === 1 ? editors[0] : null;
155
183
  };
184
+ const files = findFile();
185
+ if (files.length > 1)
186
+ return { ok: false, error: 'The target file is ambiguous in Explorer.' };
187
+ if (files.length === 1) {
188
+ files[0].click();
189
+ await new Promise(resolve => setTimeout(resolve, 200));
190
+ }
156
191
  const editor = findEditor();
157
192
  if (!editor) {
158
- return { ok: false, retry: true, error: 'Waiting for the app.js editor.' };
193
+ return { ok: false, retry: true, error: `Waiting for the correct workspace ${filename} editor.` };
159
194
  }
160
195
  const editorInput = editor.querySelector('textarea.inputarea');
161
196
  const renderedCode = editor.querySelector('.view-lines');
162
197
  if (!editorInput || !renderedCode?.querySelector('.view-line'))
163
- return { ok: false, retry: true, error: 'Waiting for the app.js editor input.' };
164
- const model = window.monaco?.editor?.getEditors?.().find(instance => instance.getDomNode() === editor)?.getModel();
198
+ return { ok: false, retry: true, error: `Waiting for the ${filename} editor input.` };
199
+ const instance = window.monaco?.editor?.getEditors?.().find(instance => instance.getDomNode() === editor);
200
+ const model = instance?.getModel();
201
+ if (model?.uri && model.uri.toString() !== editor.getAttribute('data-uri'))
202
+ return { ok: false, error: 'The editor model does not match the inspected workspace file.' };
165
203
  const isEmpty = () => {
166
204
  if (model)
167
205
  return model.getValue() === '';
@@ -171,36 +209,66 @@ async function browserAssistantOnlineIde(action, workspace, questionId, token, s
171
209
  return lineNumbers.length === 1 && lineNumbers[0].textContent.trim() === '1'
172
210
  && renderedCode.querySelectorAll('.view-line').length === 1 && !renderedCode.textContent.trim();
173
211
  };
174
- if (!isEmpty())
175
- return { ok: false, error: 'app.js is not empty or its contents could not be checked. Review the code in the editor.' };
212
+ const read = () => model ? (typeof model.getValue() === 'string' ? model.getValue() : null) : isEmpty() ? '' : null;
213
+ const currentSource = read();
214
+ if (action === 'inspectOnlineIde') {
215
+ if (currentSource === null)
216
+ return { ok: false, error: `The complete contents of ${filename} cannot be read safely. Open the file and review it.` };
217
+ if (new TextEncoder().encode(currentSource).length > 12000)
218
+ return { ok: false, error: 'The starter file exceeds the 12 KB inspection limit. Review it before continuing.' };
219
+ window[inspectionKey] = { token, workspace, questionId, filename, source: currentSource, uri: editor.getAttribute('data-uri') };
220
+ return { ok: true, targetFile: filename, source: currentSource };
221
+ }
222
+ const inspected = window[inspectionKey];
223
+ if (!inspected || inspected.token !== token || inspected.workspace !== workspace || inspected.questionId !== questionId
224
+ || inspected.filename !== filename || inspected.source !== expected || inspected.uri !== editor.getAttribute('data-uri')
225
+ || currentSource !== expected)
226
+ return { ok: false, error: 'The target file changed or was not inspected before generating code.' };
227
+ if (instance && window.monaco?.editor?.EditorOption?.readOnly !== undefined
228
+ && instance.getOption(window.monaco.editor.EditorOption.readOnly))
229
+ return { ok: false, error: `The ${filename} editor is read-only.` };
230
+ if (typeof source !== 'string' || !source.trim() || new TextEncoder().encode(source).length > 12000)
231
+ return { ok: false, error: 'A complete JavaScript source of at most 12 KB is required.' };
232
+ const canReplace = currentSource !== '' && model && instance
233
+ && window.monaco?.editor?.EditorOption?.readOnly !== undefined
234
+ && !instance.getOption(window.monaco.editor.EditorOption.readOnly);
235
+ if (currentSource !== '' && !canReplace)
236
+ return { ok: false, error: `The complete ${filename} model is not available for a safe replacement.` };
176
237
  const code = source.replace(/\r\n?/g, '\n');
177
238
  const bytes = new TextEncoder().encode(code);
178
239
  const digest = Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256', bytes)), byte => byte.toString(16).padStart(2, '0')).join('');
179
- if (document.visibilityState !== 'visible' || findEditor() !== editor || !isEmpty()) {
180
- return { ok: false, error: 'The app.js editor changed before pasting.' };
240
+ if (document.visibilityState !== 'visible' || findEditor() !== editor || read() !== currentSource) {
241
+ return { ok: false, error: `The ${filename} editor changed before pasting.` };
181
242
  }
182
243
  editorInput.focus();
183
244
  if (document.activeElement !== editorInput || editorInput.readOnly || editorInput.disabled) {
184
- return { ok: false, error: 'The app.js editor is not available for editing.' };
245
+ return { ok: false, error: `The ${filename} editor is not available for editing.` };
246
+ }
247
+ if (canReplace) {
248
+ instance.pushUndoStop();
249
+ instance.executeEdits('browser-assistant', [{ range: model.getFullModelRange(), text: code }]);
250
+ instance.pushUndoStop();
251
+ }
252
+ else {
253
+ const pasteData = new DataTransfer();
254
+ pasteData.setData('text/plain', code);
255
+ editorInput.dispatchEvent(new ClipboardEvent('paste', { clipboardData: pasteData, bubbles: true, cancelable: true, composed: true }));
185
256
  }
186
- const pasteData = new DataTransfer();
187
- pasteData.setData('text/plain', code);
188
- editorInput.dispatchEvent(new ClipboardEvent('paste', { clipboardData: pasteData, bubbles: true, cancelable: true, composed: true }));
189
257
  const pasteDeadline = Date.now() + 1500;
190
258
  const didPaste = () => model ? model.getValue() === code : Boolean(renderedCode.textContent.trim());
191
259
  while (!didPaste() && Date.now() < pasteDeadline && document.activeElement === editorInput && findEditor() === editor) {
192
260
  await new Promise(resolve => setTimeout(resolve, 50));
193
261
  }
194
262
  if (!didPaste() || findEditor() !== editor || document.activeElement !== editorInput || document.visibilityState !== 'visible') {
195
- return { ok: false, error: 'The IDE did not confirm the paste into app.js. Check the editor before trying again.' };
263
+ return { ok: false, error: `The IDE did not confirm the paste into ${filename}. Check the editor before trying again.` };
196
264
  }
197
265
  // Check exact saved bytes before grading; allow time for the IDE's autosave.
198
266
  // All interpolated values have restricted alphabets.
199
- const saved = `printf '%s app.js\\n' '${digest}' | sha256sum --check --status`;
267
+ const saved = `printf '%s ${filename}\\n' '${digest}' | sha256sum --check --status`;
200
268
  const echoMarker = `BA_COMMAND_${token}`;
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}`;
269
+ 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 ${filename} && ccbp submit ${workspace}; else printf '%s\\n' ${saveMarker}; false; fi ); printf '\\n${finishMarker}:%s\\n' "$?" #${echoMarker}`;
202
270
  if (rows().at(-1) !== before.at(-1))
203
- return { ok: false, error: 'Code is in app.js, but the IDE terminal changed before grading.' };
271
+ return { ok: false, error: `Code is in ${filename}, but the IDE terminal changed before grading.` };
204
272
  input.focus();
205
273
  if (document.activeElement !== input)
206
274
  return { ok: false, error: 'The IDE terminal could not be focused.' };
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "manifest_version": 3,
3
3
  "name": "Browser Assistant",
4
- "version": "2.9.46",
4
+ "version": "2.9.47",
5
5
  "description": "Scans webpages for MCQs and coding problems. Powered by Groq (cloud) and Ollama (local fallback).",
6
6
  "permissions": [
7
7
  "activeTab",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "browser-assistant",
3
- "version": "2.9.46",
3
+ "version": "2.9.47",
4
4
  "description": "Chrome extension and local Python backend for exploring webpage questions and coding exercises",
5
5
  "license": "MIT",
6
6
  "repository": {
package/server/main.py CHANGED
@@ -201,7 +201,7 @@ async def lifespan(_app: FastAPI):
201
201
  client.close()
202
202
 
203
203
 
204
- app = FastAPI(title="Browser Assistant API", version="2.9.46", lifespan=lifespan)
204
+ app = FastAPI(title="Browser Assistant API", version="2.9.47", lifespan=lifespan)
205
205
  install_local_guards(app)
206
206
 
207
207
  @app.exception_handler(HTTPException)