@innovatorved/code-lab 0.3.1 → 0.3.2

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.
Files changed (48) hide show
  1. package/ARCHITECTURE.md +4 -2
  2. package/CHANGELOG.md +25 -0
  3. package/README.md +15 -5
  4. package/dist/code-lab.css +52 -2
  5. package/dist/code-lab.d.ts +1 -1
  6. package/dist/code-lab.esm.js +1247 -377
  7. package/dist/code-lab.js +1246 -376
  8. package/dist/diagnostics.d.ts +5 -0
  9. package/dist/extensions/cpp.esm.js +51 -9
  10. package/dist/extensions/cpp.js +51 -9
  11. package/dist/extensions/python.esm.js +116 -103
  12. package/dist/extensions/python.js +116 -103
  13. package/dist/index.d.ts +1 -1
  14. package/dist/preview-sw.js +34 -17
  15. package/dist/runtime.esm.js +38 -31
  16. package/dist/runtime.js +38 -31
  17. package/dist/schemas.d.ts +1 -1
  18. package/dist/scm.d.ts +13 -2
  19. package/dist/search.d.ts +5 -1
  20. package/dist/shell.esm.js +72 -16
  21. package/dist/shell.js +72 -16
  22. package/dist/terminal.esm.js +183 -54
  23. package/dist/terminal.js +183 -54
  24. package/dist/workbench/index.d.ts +1 -1
  25. package/dist/workbench/styles.d.ts +1 -1
  26. package/dist/zip.d.ts +4 -3
  27. package/package.json +1 -1
  28. package/src/code-lab.css +52 -2
  29. package/src/csp.ts +7 -10
  30. package/src/diagnostics.ts +42 -3
  31. package/src/extensions/cpp.ts +47 -9
  32. package/src/extensions/python.ts +128 -116
  33. package/src/index.ts +1 -1
  34. package/src/preview-sw.js +25 -5
  35. package/src/runtime.ts +36 -29
  36. package/src/schemas.ts +1 -1
  37. package/src/scm.ts +106 -19
  38. package/src/search.ts +71 -27
  39. package/src/shell.ts +70 -14
  40. package/src/terminal.ts +181 -52
  41. package/src/workbench/diff-editor.ts +41 -13
  42. package/src/workbench/drawer.ts +17 -4
  43. package/src/workbench/guided-pane.ts +12 -2
  44. package/src/workbench/share.ts +37 -8
  45. package/src/workbench/styles.ts +2 -1
  46. package/src/workbench/toolbar.ts +15 -4
  47. package/src/workbench.ts +482 -79
  48. package/src/zip.ts +29 -7
package/src/shell.ts CHANGED
@@ -2902,6 +2902,13 @@
2902
2902
  return out;
2903
2903
  }
2904
2904
 
2905
+ function quoteShellArg(arg) {
2906
+ const s = String(arg ?? '');
2907
+ if (s.length === 0) return "''";
2908
+ if (!/[\s"'\\$&|;<>()`!*?~#]/.test(s)) return s;
2909
+ return "'" + s.replace(/'/g, "'\\''") + "'";
2910
+ }
2911
+
2905
2912
  async function runPackageScript(scriptName, scriptArgs, ctx) {
2906
2913
  const { data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
2907
2914
  if (!pkgData.scripts || !pkgData.scripts[scriptName]) {
@@ -2909,7 +2916,7 @@
2909
2916
  }
2910
2917
  let cmd = pkgData.scripts[scriptName];
2911
2918
  if (scriptArgs && scriptArgs.length > 0) {
2912
- cmd += ' ' + scriptArgs.join(' ');
2919
+ cmd += ' ' + scriptArgs.map(quoteShellArg).join(' ');
2913
2920
  }
2914
2921
  const fallback = tryDevScriptFallback(scriptName, cmd, ctx);
2915
2922
  if (fallback) return fallback;
@@ -3162,6 +3169,11 @@
3162
3169
  const isFile = (p) => exists(p) && !isDir(p);
3163
3170
  const readText = (p) => { try { return ctx.vfs.readFileSync(p, 'utf8'); } catch (_) { return null; } };
3164
3171
 
3172
+ const isWithinRoot = (p) => {
3173
+ const rootPrefix = rootDir === '/' ? '/' : rootDir + '/';
3174
+ return p === rootDir || p.startsWith(rootPrefix);
3175
+ };
3176
+
3165
3177
  const resolveLocalTarget = (baseDir, rawSpec) => {
3166
3178
  if (!rawSpec || typeof rawSpec !== 'string') return null;
3167
3179
  const clean = rawSpec.split(/[?#]/)[0].trim();
@@ -3169,6 +3181,7 @@
3169
3181
  const candidateBase = clean.startsWith('/')
3170
3182
  ? PosixPath.join(rootDir, clean.replace(/^\/+/, ''))
3171
3183
  : PosixPath.join(baseDir, clean);
3184
+ if (!isWithinRoot(candidateBase)) return null;
3172
3185
  if (isFile(candidateBase)) return candidateBase;
3173
3186
  const cands = [
3174
3187
  candidateBase + '.tsx', candidateBase + '.ts', candidateBase + '.jsx', candidateBase + '.js',
@@ -3177,7 +3190,7 @@
3177
3190
  PosixPath.join(candidateBase, 'index.jsx'), PosixPath.join(candidateBase, 'index.js')
3178
3191
  ];
3179
3192
  for (const c of cands) {
3180
- if (isFile(c)) return c;
3193
+ if (isWithinRoot(c) && isFile(c)) return c;
3181
3194
  }
3182
3195
  return null;
3183
3196
  };
@@ -3306,7 +3319,7 @@
3306
3319
  if (/@import\s+['"]tailwindcss['"]/i.test(cssContent)) {
3307
3320
  needsTailwindBrowser = true;
3308
3321
  }
3309
- const resolvedCss = inlineLocalCssImports(cssContent, PosixPath.dirname(cssTarget));
3322
+ const resolvedCss = inlineLocalCssImports(cssContent, PosixPath.dirname(cssTarget)).replace(/<\/style/gi, '<\\/style');
3310
3323
  return `<style data-codelab-href="${hrefMatch[1].replace(/"/g, '&quot;')}">\n${resolvedCss}\n</style>`;
3311
3324
  });
3312
3325
 
@@ -3318,7 +3331,7 @@
3318
3331
  if (!scriptTarget || !isPreviewScriptPath(scriptTarget)) return fullTag;
3319
3332
  const rawScript = readText(scriptTarget);
3320
3333
  if (rawScript === null) return fullTag;
3321
- const compiled = transpileAndRewriteLocalImports(rawScript, scriptTarget);
3334
+ const compiled = transpileAndRewriteLocalImports(rawScript, scriptTarget).replace(/<\/script/gi, '<\\/script');
3322
3335
  const isMod = /\btype\s*=\s*["']module["']/i.test(attrs) || /\.(?:tsx|ts|jsx|mjs)$/i.test(scriptTarget) || /^\s*(?:import|export)\b/m.test(rawScript);
3323
3336
  const typeAttr = isMod ? ' type="module"' : '';
3324
3337
  return `<script${typeAttr} data-codelab-src="${srcMatch[1].replace(/"/g, '&quot;')}">\n${compiled}\n</script>`;
@@ -3341,6 +3354,12 @@
3341
3354
  try { pathname = decodeURIComponent(new URL(request.url).pathname); } catch (err) { _shellLogger.debug('Preview URL decode failed.', err); }
3342
3355
  const rel = pathname.replace(/^\/+/, '');
3343
3356
  let target = PosixPath.join(rootDir, rel);
3357
+ if (!isWithinRoot(target)) {
3358
+ return new Response(
3359
+ '<!doctype html><meta charset="utf-8"><title>403</title><h1>403 Forbidden</h1>',
3360
+ { status: 403, headers: { 'content-type': 'text/html; charset=utf-8' } }
3361
+ );
3362
+ }
3344
3363
  const hasExt = /\.[A-Za-z0-9]+$/.test(rel);
3345
3364
 
3346
3365
  if (!rel || pathname.endsWith('/') || isDir(target)) {
@@ -3365,8 +3384,13 @@
3365
3384
  target = (!exists(rootIdx) && exists(pubIdx)) ? pubIdx : rootIdx; // SPA fallback
3366
3385
  }
3367
3386
  if (!exists(target)) {
3387
+ const safePath = String(pathname)
3388
+ .replace(/&/g, '&amp;')
3389
+ .replace(/</g, '&lt;')
3390
+ .replace(/>/g, '&gt;')
3391
+ .replace(/"/g, '&quot;');
3368
3392
  return new Response(
3369
- `<!doctype html><meta charset="utf-8"><title>404</title><h1>404 Not Found</h1><p>${pathname}</p>`,
3393
+ `<!doctype html><meta charset="utf-8"><title>404</title><h1>404 Not Found</h1><p>${safePath}</p>`,
3370
3394
  { status: 404, headers: { 'content-type': 'text/html; charset=utf-8' } }
3371
3395
  );
3372
3396
  }
@@ -5517,13 +5541,17 @@
5517
5541
 
5518
5542
  const count = Math.max(1, result.filesWritten);
5519
5543
  const kb = Math.max(0.1, result.totalBytes / 1024).toFixed(1);
5544
+ if (!enumeratedEmitted) {
5545
+ streamLine(`remote: Enumerating objects: ${count}, done.\n`);
5546
+ streamLine(`remote: Counting objects: 100% (${count}/${count}), done.\n`);
5547
+ }
5520
5548
  streamLine(`Receiving objects: 100% (${count}/${count}), ${kb} KiB, done.\n`);
5521
5549
  const stdout =
5522
5550
  `Cloning into '${dirDisplayName}'...\n` +
5523
5551
  `remote: Enumerating objects: ${count}, done.\n` +
5524
5552
  `remote: Counting objects: 100% (${count}/${count}), done.\n` +
5525
5553
  `Receiving objects: 100% (${count}/${count}), ${kb} KiB, done.\n`;
5526
- return { code: 0, stdout, stderr: '' };
5554
+ return { code: 0, stdout, stderr: '', alreadyStreamed: canStream };
5527
5555
  } catch (err) {
5528
5556
  if (ctx.signal && ctx.signal.aborted) {
5529
5557
  return { code: 130, stdout: '', stderr: '', aborted: true };
@@ -6586,7 +6614,8 @@
6586
6614
  if (ctx.vfs.existsSync(binPath)) {
6587
6615
  return await ctx.commands.node([binPath, ...cmdArgs], ctx);
6588
6616
  }
6589
- return await ctx.shell.execute(cmd + (cmdArgs.length ? ' ' + cmdArgs.join(' ') : ''));
6617
+ const cmdStr = [cmd, ...cmdArgs].map(quoteShellArg).join(' ');
6618
+ return await ctx.shell.execute(cmdStr, { cwd: ctx.cwd, env: ctx.env, signal: ctx.signal });
6590
6619
  },
6591
6620
 
6592
6621
  async bunx(args, ctx) {
@@ -6657,7 +6686,8 @@
6657
6686
  if (!cmd) return { code: 1, stdout: '', stderr: 'pnpm: exec requires a command\n' };
6658
6687
  const binPath = PosixPath.join('/workspace/node_modules/.bin', cmd);
6659
6688
  if (ctx.vfs.existsSync(binPath)) return await ctx.commands.node([binPath, ...args.slice(2)], ctx);
6660
- return await ctx.shell.execute([cmd, ...args.slice(2)].join(' '));
6689
+ const cmdStr = [cmd, ...args.slice(2)].map(quoteShellArg).join(' ');
6690
+ return await ctx.shell.execute(cmdStr, { cwd: ctx.cwd, env: ctx.env, signal: ctx.signal });
6661
6691
  }
6662
6692
 
6663
6693
  if (sub === 'dlx') {
@@ -7840,18 +7870,27 @@
7840
7870
  if (item.background) {
7841
7871
  const pid = this.nextPid++;
7842
7872
  const jobId = this.nextJobId++;
7873
+ const jobAbortCtrl = typeof AbortController !== 'undefined' ? new AbortController() : null;
7843
7874
  const job = {
7844
7875
  id: jobId,
7845
7876
  pid,
7846
7877
  command: trimmed,
7847
7878
  status: 'Running',
7848
- startTime: Date.now()
7879
+ startTime: Date.now(),
7880
+ abort: () => { if (jobAbortCtrl) jobAbortCtrl.abort(); }
7849
7881
  };
7850
7882
  this.jobs.set(jobId, job);
7851
7883
  if (typeof this.options.onJobStart === 'function') this.options.onJobStart(job);
7852
7884
 
7853
- // Run in background promise
7854
- this._executeAstNode(item.node, { ...execOptions, env: Object.assign({}, this.env, currentEnv), cwd: this.cwd, pid, isBackground: true })
7885
+ // Run in background promise with its own independent AbortSignal
7886
+ this._executeAstNode(item.node, {
7887
+ ...execOptions,
7888
+ signal: jobAbortCtrl ? jobAbortCtrl.signal : undefined,
7889
+ env: Object.assign({}, this.env, currentEnv),
7890
+ cwd: this.cwd,
7891
+ pid,
7892
+ isBackground: true
7893
+ })
7855
7894
  .then(res => {
7856
7895
  if (job.status !== 'Terminated') {
7857
7896
  job.status = 'Done';
@@ -8005,17 +8044,24 @@
8005
8044
  if (item.background) {
8006
8045
  const pid = this.nextPid++;
8007
8046
  const jobId = this.nextJobId++;
8047
+ const jobAbortCtrl = typeof AbortController !== 'undefined' ? new AbortController() : null;
8008
8048
  const job = {
8009
8049
  id: jobId,
8010
8050
  pid,
8011
8051
  command: 'background',
8012
8052
  status: 'Running',
8013
- startTime: Date.now()
8053
+ startTime: Date.now(),
8054
+ abort: () => { if (jobAbortCtrl) jobAbortCtrl.abort(); }
8014
8055
  };
8015
8056
  this.jobs.set(jobId, job);
8016
8057
  if (typeof this.options.onJobStart === 'function') this.options.onJobStart(job);
8017
8058
 
8018
- this._executeAstNode(item.node, { ...context, pid, isBackground: true })
8059
+ this._executeAstNode(item.node, {
8060
+ ...context,
8061
+ signal: jobAbortCtrl ? jobAbortCtrl.signal : undefined,
8062
+ pid,
8063
+ isBackground: true
8064
+ })
8019
8065
  .then(res => {
8020
8066
  if (job.status !== 'Terminated') {
8021
8067
  job.status = 'Done';
@@ -8131,7 +8177,11 @@
8131
8177
  wordItems.push(...(innerCtx.positionalArgs || []));
8132
8178
  }
8133
8179
 
8180
+ let loopIter = 0;
8134
8181
  for (const val of wordItems) {
8182
+ if (++loopIter % 250 === 0 && typeof setTimeout === 'function') {
8183
+ await new Promise((r) => setTimeout(r, 0));
8184
+ }
8135
8185
  if (innerCtx.signal && innerCtx.signal.aborted) {
8136
8186
  return { code: 130, stdout: combinedStdout, stderr: combinedStderr, aborted: true };
8137
8187
  }
@@ -8176,7 +8226,11 @@
8176
8226
  let combinedStderr = '';
8177
8227
  let lastCode = 0;
8178
8228
 
8229
+ let loopIter = 0;
8179
8230
  while (true) {
8231
+ if (++loopIter % 250 === 0 && typeof setTimeout === 'function') {
8232
+ await new Promise((r) => setTimeout(r, 0));
8233
+ }
8180
8234
  if (innerCtx.signal && innerCtx.signal.aborted) {
8181
8235
  return { code: 130, stdout: combinedStdout, stderr: combinedStderr, aborted: true };
8182
8236
  }
@@ -8643,7 +8697,9 @@
8643
8697
 
8644
8698
  // Route any remaining unstreamed output
8645
8699
  if (res.stdout) {
8646
- if (streamedStdoutBytes > 0) {
8700
+ if (res.alreadyStreamed) {
8701
+ stdoutOut = res.stdout;
8702
+ } else if (streamedStdoutBytes > 0) {
8647
8703
  if (res.stdout.length > streamedStdoutBytes) {
8648
8704
  routeOutput(fd1, res.stdout.slice(streamedStdoutBytes), true);
8649
8705
  }
package/src/terminal.ts CHANGED
@@ -303,6 +303,14 @@
303
303
 
304
304
  const parseAnsiToHtml = ansiToHtml;
305
305
 
306
+ const MAX_SCROLLBACK = 2000;
307
+ const VALID_LOG_TYPES = new Set(['stdout', 'stderr', 'system', 'info', 'warn', 'error', 'success']);
308
+
309
+ function sanitizeLogType(type) {
310
+ const t = String(type || 'stdout').trim();
311
+ return VALID_LOG_TYPES.has(t) ? t : 'stdout';
312
+ }
313
+
306
314
  class PTYTerminalEngine {
307
315
  constructor(container, options = {}) {
308
316
  if (
@@ -317,6 +325,9 @@
317
325
  }
318
326
  this.container = container || null;
319
327
  this.options = options || {};
328
+ this.maxScrollback = typeof this.options.maxScrollback === 'number' && this.options.maxScrollback > 0
329
+ ? this.options.maxScrollback
330
+ : MAX_SCROLLBACK;
320
331
  this.logs = Array.isArray(this.options.logs) ? this.options.logs : [];
321
332
  this.cwd = this.options.cwd || '/workspace';
322
333
  this.replMode = Boolean(this.options.replMode);
@@ -330,6 +341,7 @@
330
341
  this.searchQuery = '';
331
342
  this.searchMatchIdx = -1;
332
343
  this._readLineQueue = [];
344
+ this.isBusy = false;
333
345
  this.onCommand = typeof this.options.onCommand === 'function' ? this.options.onCommand : null;
334
346
  this.getCompletions = typeof this.options.getCompletions === 'function' ? this.options.getCompletions : null;
335
347
  this.onKey = typeof this.options.onKey === 'function' ? this.options.onKey : null;
@@ -480,13 +492,40 @@
480
492
  this.writeStreamChunk(String(data) + '\n', type);
481
493
  }
482
494
 
495
+ isCommandRunning() {
496
+ return Boolean(this.isBusy && (!this._readLineQueue || this._readLineQueue.length === 0));
497
+ }
498
+
499
+ _pushLog(entry) {
500
+ const normalized = {
501
+ type: sanitizeLogType(entry && entry.type),
502
+ text: String(entry && entry.text != null ? entry.text : '')
503
+ };
504
+ this.logs.push(normalized);
505
+ if (this.logs.length > this.maxScrollback) {
506
+ const excess = this.logs.length - this.maxScrollback;
507
+ this.logs.splice(0, excess);
508
+ if (this._targetLineIdx >= 0) {
509
+ this._targetLineIdx = Math.max(0, this._targetLineIdx - excess);
510
+ }
511
+ if (this.container && typeof this.container.querySelector === 'function') {
512
+ const logEl = this.container.querySelector('#cl-terminal-log');
513
+ if (logEl && logEl.children && logEl.children.length > this.maxScrollback) {
514
+ while (logEl.children.length > this.maxScrollback && typeof logEl.removeChild === 'function' && logEl.firstChild) {
515
+ logEl.removeChild(logEl.firstChild);
516
+ }
517
+ }
518
+ }
519
+ }
520
+ return normalized;
521
+ }
522
+
483
523
  _getActiveLine(type) {
484
524
  if (this._targetLineIdx >= 0 && this._targetLineIdx < this.logs.length) {
485
525
  return this.logs[this._targetLineIdx];
486
526
  }
487
527
  if (this._activeLineCommitted || this.logs.length === 0) {
488
- const newLine = { text: '', type };
489
- this.logs.push(newLine);
528
+ const newLine = this._pushLog({ text: '', type });
490
529
  this._activeLineCommitted = false;
491
530
  this._cursorCol = 0;
492
531
  this._targetLineIdx = this.logs.length - 1;
@@ -503,7 +542,7 @@
503
542
  const logEl = this.container.querySelector('#cl-terminal-log');
504
543
  if (!logEl) return;
505
544
  const lineEl = document.createElement('div');
506
- lineEl.className = 'codelab-log-line ' + (line.type || 'stdout');
545
+ lineEl.className = 'codelab-log-line ' + sanitizeLogType(line.type);
507
546
  lineEl.innerHTML = ansiToHtml(line.text);
508
547
  logEl.appendChild(lineEl);
509
548
  this._activeLineEl = lineEl;
@@ -526,7 +565,7 @@
526
565
  }
527
566
  }
528
567
  if (lineEl) {
529
- lineEl.className = 'codelab-log-line ' + (line.type || 'stdout');
568
+ lineEl.className = 'codelab-log-line ' + sanitizeLogType(line.type);
530
569
  lineEl.innerHTML = ansiToHtml(line.text);
531
570
  }
532
571
  }
@@ -565,17 +604,29 @@
565
604
  return [...this.history];
566
605
  }
567
606
 
568
- readLine(promptText = '') {
569
- const prevPrompt = this.promptOverride;
570
- if (promptText) {
571
- this.setPrompt(promptText);
607
+ _activateNextReadLine() {
608
+ if (!this._readLineQueue || this._readLineQueue.length === 0) return;
609
+ const head = this._readLineQueue[0];
610
+ if (head && typeof head === 'object' && !head._activated) {
611
+ head._activated = true;
612
+ head.prevPrompt = this.promptOverride;
613
+ if (head.promptText) {
614
+ this.promptOverride = head.promptText;
615
+ }
572
616
  }
617
+ }
618
+
619
+ readLine(promptText = '') {
573
620
  return new Promise((resolve) => {
574
- this._readLineQueue.push((line) => {
575
- this.promptOverride = prevPrompt;
576
- this.updateActiveLine();
577
- resolve(line);
578
- });
621
+ const item = {
622
+ promptText: String(promptText || ''),
623
+ prevPrompt: null,
624
+ _activated: false,
625
+ resolve
626
+ };
627
+ this._readLineQueue.push(item);
628
+ this._activateNextReadLine();
629
+ this.updateActiveLine();
579
630
  });
580
631
  }
581
632
 
@@ -645,6 +696,10 @@
645
696
  if (input) {
646
697
  this._addListener(input, 'keydown', (e) => this.handleKeyDown(e));
647
698
  this._addListener(input, 'input', () => {
699
+ if (this.isCommandRunning()) {
700
+ input.value = '';
701
+ return;
702
+ }
648
703
  if (input.value !== this.buffer) {
649
704
  this.buffer = input.value;
650
705
  this.cursor = typeof input.selectionStart === 'number' ? input.selectionStart : this.buffer.length;
@@ -686,6 +741,35 @@
686
741
  const key = e.key;
687
742
  const isCtrl = Boolean(e.ctrlKey || e.metaKey);
688
743
 
744
+ if (isCtrl && (key === 'l' || key === 'L')) {
745
+ if (e.preventDefault) e.preventDefault();
746
+ this.clear();
747
+ return;
748
+ }
749
+
750
+ if (isCtrl && (key === 'c' || key === 'C')) {
751
+ if (e.preventDefault) e.preventDefault();
752
+ const wasBusy = this.isBusy;
753
+ this.isBusy = false;
754
+ this._pushLog({ type: 'system', text: wasBusy ? '^C' : `${this.getPrompt()}${this.buffer}^C` });
755
+ this.buffer = '';
756
+ this.cursor = 0;
757
+ this.historyIdx = -1;
758
+ if (this.replMode) {
759
+ this.replMode = false;
760
+ }
761
+ if (this.onInterrupt) {
762
+ try { this.onInterrupt(); } catch (err) { _terminalLogger.warn('Terminal onInterrupt callback threw.', err); }
763
+ }
764
+ this.render();
765
+ return;
766
+ }
767
+
768
+ if (this.isCommandRunning()) {
769
+ if (e.preventDefault) e.preventDefault();
770
+ return;
771
+ }
772
+
689
773
  if (isCtrl && (key === 'r' || key === 'R')) {
690
774
  if (e.preventDefault) e.preventDefault();
691
775
  if (!this.searchMode) {
@@ -817,33 +901,11 @@
817
901
  return;
818
902
  }
819
903
 
820
- if (isCtrl && (key === 'l' || key === 'L')) {
821
- if (e.preventDefault) e.preventDefault();
822
- this.clear();
823
- return;
824
- }
825
-
826
- if (isCtrl && (key === 'c' || key === 'C')) {
827
- if (e.preventDefault) e.preventDefault();
828
- this.logs.push({ type: 'system', text: `${this.getPrompt()}${this.buffer}^C` });
829
- this.buffer = '';
830
- this.cursor = 0;
831
- this.historyIdx = -1;
832
- if (this.replMode) {
833
- this.replMode = false;
834
- }
835
- if (this.onInterrupt) {
836
- try { this.onInterrupt(); } catch (err) { _terminalLogger.warn('Terminal onInterrupt callback threw.', err); }
837
- }
838
- this.render();
839
- return;
840
- }
841
-
842
904
  if (isCtrl && (key === 'd' || key === 'D')) {
843
905
  if (this.buffer === '') {
844
906
  if (e.preventDefault) e.preventDefault();
845
907
  if (this.replMode) {
846
- this.logs.push({ type: 'system', text: `${this.getPrompt()}.exit` });
908
+ this._pushLog({ type: 'system', text: `${this.getPrompt()}.exit` });
847
909
  this.replMode = false;
848
910
  this.render();
849
911
  return;
@@ -937,14 +999,41 @@
937
999
  }
938
1000
 
939
1001
  // Print candidate matches
940
- this.logs.push({ type: 'system', text: `${this.getPrompt()}${this.buffer}` });
941
- this.logs.push({ type: 'stdout', text: matches.join(' ') });
1002
+ this._pushLog({ type: 'system', text: `${this.getPrompt()}${this.buffer}` });
1003
+ this._pushLog({ type: 'stdout', text: matches.join(' ') });
942
1004
  this.render();
943
1005
  }
944
1006
  }
945
1007
 
946
1008
  submitLine() {
1009
+ if (this._readLineQueue && this._readLineQueue.length > 0) {
1010
+ const line = this.buffer;
1011
+ this.buffer = '';
1012
+ this.cursor = 0;
1013
+ this.historyIdx = -1;
1014
+ this.searchMode = false;
1015
+ this.searchQuery = '';
1016
+ this.searchMatchIdx = -1;
1017
+
1018
+ const entry = this._readLineQueue.shift();
1019
+ if (typeof entry === 'function') {
1020
+ this.updateActiveLine();
1021
+ entry(line);
1022
+ } else if (entry && typeof entry.resolve === 'function') {
1023
+ this.promptOverride = entry.prevPrompt;
1024
+ this._activateNextReadLine();
1025
+ this.updateActiveLine();
1026
+ entry.resolve(line);
1027
+ }
1028
+ return;
1029
+ }
1030
+
1031
+ if (this.isBusy) {
1032
+ return;
1033
+ }
1034
+
947
1035
  const line = this.buffer;
1036
+ const promptSnap = this.getPrompt();
948
1037
  this.buffer = '';
949
1038
  this.cursor = 0;
950
1039
  this.historyIdx = -1;
@@ -952,22 +1041,49 @@
952
1041
  this.searchQuery = '';
953
1042
  this.searchMatchIdx = -1;
954
1043
 
1044
+ const echoed = this._pushLog({ type: 'system', text: `${promptSnap}${line}` });
1045
+ this._activeLineCommitted = true;
1046
+ this._cursorCol = 0;
1047
+ this._targetLineIdx = -1;
1048
+ this._needsRewrite = false;
1049
+ this._appendDomLine(echoed);
1050
+ this._activeLineEl = null;
1051
+
955
1052
  if (line.trim()) {
956
1053
  if (this.history[this.history.length - 1] !== line.trim()) {
957
1054
  this.history.push(line.trim());
958
1055
  }
959
1056
  }
960
1057
 
961
- if (this._readLineQueue && this._readLineQueue.length > 0) {
962
- const resolver = this._readLineQueue.shift();
1058
+ if (!this.onCommand) {
963
1059
  this.updateActiveLine();
964
- resolver(line);
965
1060
  return;
966
1061
  }
967
1062
 
1063
+ this.isBusy = true;
968
1064
  this.updateActiveLine();
969
- if (this.onCommand) {
970
- this.onCommand(line);
1065
+
1066
+ let cmdResult;
1067
+ try {
1068
+ cmdResult = this.onCommand(line);
1069
+ } catch (err) {
1070
+ this.isBusy = false;
1071
+ this.updateActiveLine();
1072
+ throw err;
1073
+ }
1074
+
1075
+ if (cmdResult && typeof cmdResult.then === 'function') {
1076
+ Promise.resolve(cmdResult)
1077
+ .catch((err) => {
1078
+ _terminalLogger.debug('Terminal onCommand promise rejected.', err);
1079
+ })
1080
+ .finally(() => {
1081
+ this.isBusy = false;
1082
+ this.updateActiveLine();
1083
+ });
1084
+ } else {
1085
+ this.isBusy = false;
1086
+ this.updateActiveLine();
971
1087
  }
972
1088
  }
973
1089
 
@@ -980,6 +1096,16 @@
980
1096
  const lineEl = this.container.querySelector('#cl-pty-active-line');
981
1097
  if (!lineEl) return;
982
1098
 
1099
+ if (this.isCommandRunning()) {
1100
+ if (typeof lineEl.setAttribute === 'function') lineEl.setAttribute('data-busy', 'true');
1101
+ if (lineEl.style) lineEl.style.display = 'none';
1102
+ lineEl.innerHTML = `<span class="codelab-pty__prompt"></span><span class="codelab-pty__before"></span><span class="codelab-pty__cursor"></span><span class="codelab-pty__after"></span>`;
1103
+ return;
1104
+ }
1105
+
1106
+ if (typeof lineEl.removeAttribute === 'function') lineEl.removeAttribute('data-busy');
1107
+ if (lineEl.style) lineEl.style.display = '';
1108
+
983
1109
  const prompt = this.searchMode
984
1110
  ? `(reverse-i-search)\`${this.searchQuery}\`: `
985
1111
  : this.getPrompt();
@@ -1000,21 +1126,24 @@
1000
1126
  );
1001
1127
 
1002
1128
  const logsHtml = this.logs
1003
- .map(item => `<div class="codelab-log-line ${escapeHtml(item.type || '')}">${ansiToHtml(item.text)}</div>`)
1129
+ .map(item => `<div class="codelab-log-line ${sanitizeLogType(item.type)}">${ansiToHtml(item.text)}</div>`)
1004
1130
  .join('');
1005
1131
 
1006
- const prompt = this.searchMode
1007
- ? `(reverse-i-search)\`${this.searchQuery}\`: `
1008
- : this.getPrompt();
1009
- const before = this.buffer.slice(0, this.cursor);
1010
- const cursorChar = this.cursor < this.buffer.length ? this.buffer[this.cursor] : ' ';
1011
- const after = this.cursor < this.buffer.length ? this.buffer.slice(this.cursor + 1) : '';
1132
+ const busy = this.isCommandRunning();
1133
+ const prompt = busy
1134
+ ? ''
1135
+ : (this.searchMode ? `(reverse-i-search)\`${this.searchQuery}\`: ` : this.getPrompt());
1136
+ const before = busy ? '' : this.buffer.slice(0, this.cursor);
1137
+ const cursorChar = busy ? '' : (this.cursor < this.buffer.length ? this.buffer[this.cursor] : ' ');
1138
+ const after = busy ? '' : (this.cursor < this.buffer.length ? this.buffer.slice(this.cursor + 1) : '');
1139
+ const busyAttr = busy ? ' data-busy="true" style="display:none;"' : '';
1140
+ const cursorClass = busy ? 'codelab-pty__cursor' : 'codelab-pty__cursor blink';
1012
1141
 
1013
1142
  this.container.innerHTML = `
1014
1143
  <div class="codelab-terminal" id="cl-terminal-surface" tabindex="0">
1015
1144
  <div class="codelab-terminal__log" id="cl-terminal-log">${logsHtml}</div>
1016
- <div class="codelab-pty__active-line" id="cl-pty-active-line">
1017
- <span class="codelab-pty__prompt">${escapeHtml(prompt)}</span><span class="codelab-pty__before">${escapeHtml(before)}</span><span class="codelab-pty__cursor blink">${escapeHtml(cursorChar)}</span><span class="codelab-pty__after">${escapeHtml(after)}</span>
1145
+ <div class="codelab-pty__active-line" id="cl-pty-active-line"${busyAttr}>
1146
+ <span class="codelab-pty__prompt">${escapeHtml(prompt)}</span><span class="codelab-pty__before">${escapeHtml(before)}</span><span class="${cursorClass}">${escapeHtml(cursorChar)}</span><span class="codelab-pty__after">${escapeHtml(after)}</span>
1018
1147
  </div>
1019
1148
  <form class="codelab-repl" id="cl-repl-form" style="position:absolute;opacity:0;pointer-events:none;height:0;overflow:hidden;">
1020
1149
  <input type="text" class="codelab-repl__input" id="cl-repl-input" autocomplete="off" spellcheck="false" aria-label="Terminal command input" value="${escapeHtml(this.buffer)}">
@@ -4,6 +4,15 @@
4
4
 
5
5
  import { CL_ICONS } from './icons';
6
6
 
7
+ function escapeHtml(str: unknown): string {
8
+ return String(str ?? '')
9
+ .replace(/&/g, '&amp;')
10
+ .replace(/</g, '&lt;')
11
+ .replace(/>/g, '&gt;')
12
+ .replace(/"/g, '&quot;')
13
+ .replace(/'/g, '&#39;');
14
+ }
15
+
7
16
  export interface DiffComputeResult {
8
17
  hunks: Array<{ type: 'context' | 'add' | 'del'; text: string; oldLine: number | null; newLine: number | null }>;
9
18
  added: number;
@@ -115,11 +124,25 @@ export class CodeLabDiffEditorManager {
115
124
  if (editorHost) editorHost.style.display = 'none';
116
125
  if (fallbackTextarea) fallbackTextarea.style.display = 'none';
117
126
 
127
+ if (this.diffEditor) {
128
+ this.diffEditor.dispose();
129
+ this.diffEditor = null;
130
+ }
131
+ if (this.originalModel) {
132
+ this.originalModel.dispose();
133
+ this.originalModel = null;
134
+ }
135
+ if (this.modifiedModel) {
136
+ this.modifiedModel.dispose();
137
+ this.modifiedModel = null;
138
+ }
139
+
140
+ const safeFile = escapeHtml(file);
118
141
  diffContainer.innerHTML = `
119
142
  <div class="codelab-diff-toolbar">
120
143
  <span style="font-weight:600;display:inline-flex;align-items:center;gap:6px;">
121
144
  ${CL_ICONS.diff}
122
- <span>Diff: <code>${file}</code> (${isStarter ? 'Current vs Starter' : 'Current vs Solution'})</span>
145
+ <span>Diff: <code>${safeFile}</code> (${isStarter ? 'Current vs Starter' : 'Current vs Solution'})</span>
123
146
  </span>
124
147
  <div class="codelab-segmented" style="margin-left:16px;">
125
148
  <button type="button" class="codelab-segmented__btn ${target === 'starter' ? 'active' : ''}" id="cl-diff-toggle-starter">Starter</button>
@@ -135,16 +158,14 @@ export class CodeLabDiffEditorManager {
135
158
  `;
136
159
 
137
160
  const slot = diffContainer.querySelector('#cl-diff-editor-slot');
138
- if (!this.diffEditor) {
139
- this.diffEditor = monaco.editor.createDiffEditor(slot, {
140
- readOnly: false,
141
- originalEditable: false,
142
- theme: this.workbench.theme === 'light' ? 'vs' : 'vs-dark',
143
- renderSideBySide: true,
144
- automaticLayout: true,
145
- minimap: { enabled: false }
146
- });
147
- }
161
+ this.diffEditor = monaco.editor.createDiffEditor(slot, {
162
+ readOnly: false,
163
+ originalEditable: false,
164
+ theme: this.workbench.theme === 'light' ? 'vs' : 'vs-dark',
165
+ renderSideBySide: true,
166
+ automaticLayout: true,
167
+ minimap: { enabled: false }
168
+ });
148
169
 
149
170
  const lang = file.endsWith('.ts') ? 'typescript' : file.endsWith('.cpp') ? 'cpp' : file.endsWith('.py') ? 'python' : 'javascript';
150
171
  this.originalModel = monaco.editor.createModel(refCode, lang);
@@ -172,13 +193,20 @@ export class CodeLabDiffEditorManager {
172
193
  this.openInlineDiff(file, 'solution');
173
194
  });
174
195
  diffContainer.querySelector('#cl-diff-revert-btn')?.addEventListener('click', () => {
175
- const starterCode = (this.workbench.starterFiles && this.workbench.starterFiles[file]) || '';
196
+ const starterMap = this.workbench.starterFiles || (typeof this.workbench._getBaseFilesForModeAndLang === 'function' ? this.workbench._getBaseFilesForModeAndLang('guided', this.workbench.lang) : {});
197
+ const starterCode = (starterMap && starterMap[file]) || '';
176
198
  this.workbench.files[file] = starterCode;
177
199
  this.closeInlineDiff();
178
200
  this.workbench.openFile(file);
179
201
  });
180
202
  diffContainer.querySelector('#cl-diff-apply-btn')?.addEventListener('click', () => {
181
- const solutionCode = (this.workbench.solutionFiles && this.workbench.solutionFiles[file]) || '';
203
+ if (typeof this.workbench.applyReferenceSolution === 'function') {
204
+ this.closeInlineDiff();
205
+ this.workbench.applyReferenceSolution();
206
+ return;
207
+ }
208
+ const solutionMap = this.workbench.solutionFiles || (typeof this.workbench._getBaseFilesForModeAndLang === 'function' ? this.workbench._getBaseFilesForModeAndLang('sandbox', this.workbench.lang) : {});
209
+ const solutionCode = (solutionMap && solutionMap[file]) || '';
182
210
  this.workbench.files[file] = solutionCode;
183
211
  this.closeInlineDiff();
184
212
  this.workbench.openFile(file);