@innovatorved/code-lab 0.3.0 → 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 (57) hide show
  1. package/ARCHITECTURE.md +4 -2
  2. package/CHANGELOG.md +38 -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 +1533 -396
  7. package/dist/code-lab.js +1532 -395
  8. package/dist/diagnostics.d.ts +5 -0
  9. package/dist/extensions/cpp.d.ts +8 -0
  10. package/dist/extensions/cpp.esm.js +333 -10
  11. package/dist/extensions/cpp.js +333 -10
  12. package/dist/extensions/guided-lab.esm.js +1 -1
  13. package/dist/extensions/guided-lab.js +1 -1
  14. package/dist/extensions/python.esm.js +117 -104
  15. package/dist/extensions/python.js +117 -104
  16. package/dist/index.d.ts +1 -1
  17. package/dist/preview-sw.js +34 -17
  18. package/dist/runtime.esm.js +38 -31
  19. package/dist/runtime.js +38 -31
  20. package/dist/schemas.d.ts +4 -4
  21. package/dist/schemas.esm.js +1 -1
  22. package/dist/schemas.js +1 -1
  23. package/dist/scm.d.ts +13 -2
  24. package/dist/search.d.ts +5 -1
  25. package/dist/shell.esm.js +72 -16
  26. package/dist/shell.js +72 -16
  27. package/dist/terminal.esm.js +183 -54
  28. package/dist/terminal.js +183 -54
  29. package/dist/workbench/index.d.ts +1 -1
  30. package/dist/workbench/styles.d.ts +1 -1
  31. package/dist/zip.d.ts +4 -3
  32. package/package.json +1 -1
  33. package/src/code-lab.css +52 -2
  34. package/src/csp.ts +7 -10
  35. package/src/diagnostics.ts +42 -3
  36. package/src/extensions/cpp.ts +303 -9
  37. package/src/extensions/python.ts +128 -116
  38. package/src/index.ts +1 -1
  39. package/src/preview-sw.js +25 -5
  40. package/src/runtime.ts +36 -29
  41. package/src/schemas.ts +2 -2
  42. package/src/scm.ts +106 -19
  43. package/src/search.ts +71 -27
  44. package/src/shell.ts +70 -14
  45. package/src/terminal.ts +181 -52
  46. package/src/workbench/diff-editor.ts +41 -13
  47. package/src/workbench/drawer.ts +17 -8
  48. package/src/workbench/guided-pane.ts +12 -2
  49. package/src/workbench/share.ts +37 -8
  50. package/src/workbench/styles.ts +2 -1
  51. package/src/workbench/toolbar.ts +15 -4
  52. package/src/workbench.ts +484 -91
  53. package/src/zip.ts +29 -7
  54. package/dist/runtime/module-loader.d.ts +0 -11
  55. package/dist/runtime/vfs.d.ts +0 -31
  56. package/dist/runtime/wasi-host.d.ts +0 -33
  57. package/dist/shell/lexer-parser.d.ts +0 -26
package/src/workbench.ts CHANGED
@@ -57,7 +57,7 @@
57
57
 
58
58
  // The bundler rewrites this literal from package.json at build time. Keeping
59
59
  // the fallback in sync lets tests require src/workbench.js directly.
60
- const CODELAB_VERSION = '0.3.0';
60
+ const CODELAB_VERSION = '0.3.2';
61
61
 
62
62
  // Ambient TypeScript declarations for Node.js built-ins inside Monaco
63
63
  const NODE_AMBIENT_DTS = `
@@ -632,11 +632,16 @@ declare module 'bun:sqlite' {
632
632
  if (!str) return '';
633
633
  let text = String(str);
634
634
 
635
- // Markdown Links: [label](url "title") or [label](url) — supports balanced parentheses in URLs
636
- text = text.replace(/\[([^\]]+)\]\(([^()\s]+(?:\((?:[^()\s]+|\([^()\s]*\))*\)[^()\s]*)*)(?:\s+"([^"]*)")?\)/g, (_, label, url, title) => {
635
+ // Markdown Links: [label](url "title") or [label](url) — stash anchors before emphasis regexes
636
+ // so underscores/asterisks inside URLs or titles are not mangled, and use non-nested quantifiers.
637
+ const inlineLinks = [];
638
+ text = text.replace(/\[([^\]]+)\]\(([^\s()]+(?:\([^\s()]*\)[^\s()]*)*)(?:\s+"([^"]*)")?\)/g, (_, label, url, title) => {
637
639
  const cleanUrl = sanitizeUrl(url);
638
640
  const titleAttr = title ? raw(` title="${escapeHtml(title)}"`) : '';
639
- return String(html`<a href="${cleanUrl}" class="codelab-link" target="_blank" rel="noopener noreferrer"${titleAttr}>${label}</a>`);
641
+ const formattedLabel = renderInlineFormatting(label);
642
+ const idx = inlineLinks.length;
643
+ inlineLinks.push(String(html`<a href="${cleanUrl}" class="codelab-link" target="_blank" rel="noopener noreferrer"${titleAttr}>${raw(formattedLabel)}</a>`));
644
+ return `\x00CLLINK${idx}\x00`;
640
645
  });
641
646
 
642
647
  // Strikethrough: ~~del~~
@@ -654,6 +659,10 @@ declare module 'bun:sqlite' {
654
659
  text = text.replace(/\*([^*\n]+)\*/g, '<em>$1</em>');
655
660
  text = text.replace(/(^|[\s(])_([^_]+)_(?=[\s).,!?:;]|$)/g, '$1<em>$2</em>');
656
661
 
662
+ if (inlineLinks.length > 0) {
663
+ text = text.replace(/\x00CLLINK(\d+)\x00/g, (_, i) => inlineLinks[Number(i)] || '');
664
+ }
665
+
657
666
  return text;
658
667
  }
659
668
 
@@ -841,7 +850,7 @@ declare module 'bun:sqlite' {
841
850
  const lang = (info || '').trim().split(/\s+/)[0] || '';
842
851
  const idx = codeBlocks.length;
843
852
  codeBlocks.push(renderCodeBlock(code || '', lang));
844
- return `\n\n\x00CODEBLOCK_${idx}\x00\n\n`;
853
+ return `\n\n\x00CLCODEBLOCK${idx}\x00\n\n`;
845
854
  });
846
855
 
847
856
  // Phase 2: Inline Code Span Extraction
@@ -853,7 +862,7 @@ declare module 'bun:sqlite' {
853
862
  }
854
863
  const idx = inlineCodes.length;
855
864
  inlineCodes.push(`<code class="codelab-inline-code">${escapeHtml(clean)}</code>`);
856
- return `\x00INLINECODE_${idx}\x00`;
865
+ return `\x00CLINLINECODE${idx}\x00`;
857
866
  });
858
867
 
859
868
  // Phase 2b: Autolinks are the only inline construct that uses angle
@@ -866,7 +875,7 @@ declare module 'bun:sqlite' {
866
875
  autolinks.push(
867
876
  `<a href="${escapeHtml(safe)}" class="codelab-link" target="_blank" rel="noopener noreferrer">${escapeHtml(url)}</a>`
868
877
  );
869
- return `\x00AUTOLINK_${idx}\x00`;
878
+ return `\x00CLAUTOLINK${idx}\x00`;
870
879
  });
871
880
 
872
881
  // Phase 2c: Neutralize all remaining raw HTML. Every tag needs a `<`, so
@@ -901,7 +910,7 @@ declare module 'bun:sqlite' {
901
910
  }
902
911
  const idx = calloutBlocks.length;
903
912
  calloutBlocks.push(blockHtml);
904
- return `\n\n\x00CALLOUT_${idx}\x00\n\n`;
913
+ return `\n\n\x00CLCALLOUT${idx}\x00\n\n`;
905
914
  });
906
915
 
907
916
  // Phase 4: GFM Tables with Column Alignments
@@ -911,7 +920,7 @@ declare module 'bun:sqlite' {
911
920
  if (rendered === tableText) return match;
912
921
  const idx = tableBlocks.length;
913
922
  tableBlocks.push(rendered);
914
- return `\n\n\x00TABLE_${idx}\x00\n\n`;
923
+ return `\n\n\x00CLTABLE${idx}\x00\n\n`;
915
924
  });
916
925
 
917
926
  // Phase 5: Task Lists & Nested Lists
@@ -920,7 +929,7 @@ declare module 'bun:sqlite' {
920
929
  text = text.replace(/(?:^[ ]*(?:[-*+]|\d+\.)[ ]+[^\n]*(?:\n[ ]*(?:[-*+]|\d+\.)[ ]+[^\n]*|\n[ ]{2,}[^\n]*)*)+/gm, (match) => {
921
930
  const idx = listBlocks.length;
922
931
  listBlocks.push(renderListBlock(match, taskCounter));
923
- return `\n\n\x00LIST_${idx}\x00\n\n`;
932
+ return `\n\n\x00CLLIST${idx}\x00\n\n`;
924
933
  });
925
934
 
926
935
  // Phase 6: Headings, Horizontal Rules, Paragraphs & Inline Spans
@@ -942,18 +951,18 @@ declare module 'bun:sqlite' {
942
951
  const trimmed = p.trim();
943
952
  if (!trimmed) return '';
944
953
  if (/^<(h[1-6]|hr|pre|div|blockquote|table|ul|ol)/i.test(trimmed)) return trimmed;
945
- if (/^\x00(CODEBLOCK|CALLOUT|TABLE|LIST)_\d+\x00$/.test(trimmed)) return trimmed;
954
+ if (/^\x00CL(CODEBLOCK|CALLOUT|TABLE|LIST)\d+\x00$/.test(trimmed)) return trimmed;
946
955
  return `<p>${renderInlineFormatting(trimmed).replace(/\n/g, '<br>')}</p>`;
947
956
  }).filter(Boolean).join('\n');
948
957
 
949
958
  // Phase 7: Placeholder Restoration (Reverse order)
950
959
  let finalHtml = paras
951
- .replace(/\x00LIST_(\d+)\x00/g, (_, i) => listBlocks[Number(i)] || '')
952
- .replace(/\x00TABLE_(\d+)\x00/g, (_, i) => tableBlocks[Number(i)] || '')
953
- .replace(/\x00CALLOUT_(\d+)\x00/g, (_, i) => calloutBlocks[Number(i)] || '')
954
- .replace(/\x00CODEBLOCK_(\d+)\x00/g, (_, i) => codeBlocks[Number(i)] || '')
955
- .replace(/\x00INLINECODE_(\d+)\x00/g, (_, i) => inlineCodes[Number(i)] || '')
956
- .replace(/\x00AUTOLINK_(\d+)\x00/g, (_, i) => autolinks[Number(i)] || '');
960
+ .replace(/\x00CLLIST(\d+)\x00/g, (_, i) => listBlocks[Number(i)] || '')
961
+ .replace(/\x00CLTABLE(\d+)\x00/g, (_, i) => tableBlocks[Number(i)] || '')
962
+ .replace(/\x00CLCALLOUT(\d+)\x00/g, (_, i) => calloutBlocks[Number(i)] || '')
963
+ .replace(/\x00CLCODEBLOCK(\d+)\x00/g, (_, i) => codeBlocks[Number(i)] || '')
964
+ .replace(/\x00CLINLINECODE(\d+)\x00/g, (_, i) => inlineCodes[Number(i)] || '')
965
+ .replace(/\x00CLAUTOLINK(\d+)\x00/g, (_, i) => autolinks[Number(i)] || '');
957
966
 
958
967
  return finalHtml;
959
968
  }
@@ -1956,9 +1965,18 @@ int main() {
1956
1965
  if (root.CodeLabStorage && typeof root.CodeLabStorage.createWorkspaceStorage === 'function') {
1957
1966
  try {
1958
1967
  if (!this._idbStorage) {
1959
- this._idbStorage = root.CodeLabStorage.createWorkspaceStorage({ keyPrefix: STORAGE_PREFIX });
1968
+ this._idbStorage = root.CodeLabStorage.createWorkspaceStorage();
1960
1969
  }
1961
- if (this._idbStorage && typeof this._idbStorage.save === 'function') {
1970
+ if (this._idbStorage && typeof this._idbStorage.saveProject === 'function') {
1971
+ Promise.resolve(this._idbStorage.saveProject({
1972
+ id: this.labId,
1973
+ name: this.title || this.labId,
1974
+ files: { ...(this.files || {}) },
1975
+ updatedAt: Date.now()
1976
+ })).catch((err) => {
1977
+ this.logger.debug('Async WorkspaceStorage saveProject skipped.', err);
1978
+ });
1979
+ } else if (this._idbStorage && typeof this._idbStorage.save === 'function') {
1962
1980
  Promise.resolve(this._idbStorage.save(this.labId, state)).catch((err) => {
1963
1981
  this.logger.debug('Async WorkspaceStorage save skipped.', err);
1964
1982
  });
@@ -2285,6 +2303,7 @@ int main() {
2285
2303
  this.container.querySelectorAll('[data-cl-action="run-code"], [data-cl-action="run-entry"], [data-cl-action="run-active-file"], [data-cl-action="run-demo"], [data-cl-action="run-tests"], [data-cl-action="verify-step"]').forEach(btn => {
2286
2304
  btn.disabled = this.isRunning;
2287
2305
  });
2306
+ this._updatePtyActiveLine();
2288
2307
  }
2289
2308
 
2290
2309
  _hasWebContent() {
@@ -2388,13 +2407,10 @@ int main() {
2388
2407
  if (countSpan) countSpan.textContent = String(problemsCount);
2389
2408
  }
2390
2409
 
2391
- let testTab = drawerTabs.querySelector('[data-cl-drawertab="tests"]');
2392
- if (testTab) {
2393
- testTab.style.display = showTests ? 'inline-flex' : 'none';
2394
- }
2395
2410
 
2396
2411
  let stdinTab = drawerTabs.querySelector('[data-cl-drawertab="stdin"]');
2397
2412
  if (!stdinTab) {
2413
+ const testTab = drawerTabs.querySelector('[data-cl-drawertab="tests"]');
2398
2414
  const afterTab = testTab || drawerTabs.querySelector('[data-cl-drawertab="problems"]') || drawerTabs.querySelector('[data-cl-drawertab="terminal"]');
2399
2415
  if (afterTab) {
2400
2416
  afterTab.insertAdjacentHTML('afterend', `
@@ -2406,10 +2422,6 @@ int main() {
2406
2422
  }
2407
2423
  }
2408
2424
 
2409
- let previewTab = drawerTabs.querySelector('[data-cl-drawertab="preview"]');
2410
- if (previewTab) {
2411
- previewTab.style.display = hasWeb ? 'inline-flex' : 'none';
2412
- }
2413
2425
  }
2414
2426
 
2415
2427
  // ── Render Workbench DOM ───────────────────────────────────────────────
@@ -2616,13 +2628,11 @@ int main() {
2616
2628
  <span>Problems</span>
2617
2629
  <span class="codelab-badge" id="cl-problems-count" style="margin-left:4px;font-size:10px;padding:1px 5px;border-radius:10px;background:rgba(255,255,255,0.1);color:#fff;">${this._diagnosticsStore ? this._diagnosticsStore.getAll().length : 0}</span>
2618
2630
  </button>
2619
- ${((this.hasGuidedLab && this.mode === 'guided') || this.testSuiteVisible || this.drawerTab === 'tests') ? `
2620
2631
  <button type="button" role="tab" aria-selected="${this.drawerTab === 'tests'}" class="codelab-drawer__tab ${this.drawerTab === 'tests' ? 'active' : ''}" data-cl-drawertab="tests">
2621
2632
  ${CL_ICONS.check}
2622
2633
  <span>Test Suite</span>
2623
2634
  <span class="codelab-drawer__pill" id="cl-test-pill">Ready</span>
2624
2635
  </button>
2625
- ` : ''}
2626
2636
  <button type="button" role="tab" aria-selected="${this.drawerTab === 'stdin'}" class="codelab-drawer__tab ${this.drawerTab === 'stdin' ? 'active' : ''}" data-cl-drawertab="stdin" title="Standard Input">
2627
2637
  ${CL_ICONS.keyboard}
2628
2638
  <span>Stdin</span>
@@ -2632,7 +2642,7 @@ int main() {
2632
2642
  <span>Ports</span>
2633
2643
  <span class="codelab-drawer__pill" id="cl-ports-pill">${this.portTable && typeof this.portTable.listServers === 'function' ? this.portTable.listServers().length : 0} open</span>
2634
2644
  </button>
2635
- <button type="button" role="tab" aria-selected="${this.drawerTab === 'preview'}" class="codelab-drawer__tab ${this.drawerTab === 'preview' ? 'active' : ''}" data-cl-drawertab="preview" title="In-browser Web Preview" style="display: ${this._hasWebContent() ? 'inline-flex' : 'none'}">
2645
+ <button type="button" role="tab" aria-selected="${this.drawerTab === 'preview'}" class="codelab-drawer__tab ${this.drawerTab === 'preview' ? 'active' : ''}" data-cl-drawertab="preview" title="In-browser Web Preview">
2636
2646
  ${CL_ICONS.globe}
2637
2647
  <span>Web Preview</span>
2638
2648
  </button>
@@ -2649,6 +2659,8 @@ int main() {
2649
2659
  </div>
2650
2660
  <div class="codelab-hud-pill" id="cl-telemetry-hud" style="display:none;" title="Last Execution Telemetry"></div>
2651
2661
  <div style="display:flex;align-items:center;gap:6px;">
2662
+ <div class="codelab-terminal-sessions" id="cl-terminal-sessions"></div>
2663
+ <button type="button" class="codelab-btn codelab-btn--icon" id="cl-new-terminal-btn" data-cl-action="new-terminal-session" title="New Terminal Session" aria-label="New Terminal Session" style="padding:2px 6px;font-size:11px;">+</button>
2652
2664
  <button type="button" class="codelab-btn codelab-btn--icon codelab-btn--ctrl-c" id="cl-ctrl-c-btn" data-cl-action="interrupt" title="Send Ctrl+C — interrupt a running command" aria-label="Send Ctrl+C interrupt" style="padding:2px 8px;font-size:11px;font-family:var(--cl-font-mono);">Ctrl+C</button>
2653
2665
  <button type="button" class="codelab-btn codelab-btn--icon" data-cl-action="clear-terminal" title="Clear Output" style="padding:2px 6px;font-size:11px;">Clear</button>
2654
2666
  <button type="button" class="codelab-btn codelab-btn--icon" data-cl-action="toggle-drawer" title="Minimize/Expand Drawer" aria-label="Minimize or Expand Drawer" style="padding:2px 6px;font-size:11px;">${CL_ICONS.chevronsUpDown}</button>
@@ -3737,16 +3749,27 @@ int main() {
3737
3749
  ${problems.map(p => {
3738
3750
  const icon = p.severity === 'error' ? '✖' : (p.severity === 'warning' ? '⚠' : 'ℹ');
3739
3751
  const cls = p.severity === 'error' ? 'codelab-problem-item--error' : (p.severity === 'warning' ? 'codelab-problem-item--warning' : 'codelab-problem-item--info');
3752
+ const col = p.col || p.column || 1;
3740
3753
  return `
3741
- <div class="codelab-problem-item ${cls}" data-cl-problem-file="${escapeHtml(p.file || '')}" data-cl-problem-line="${p.line || 1}" data-cl-problem-col="${p.col || 1}" role="button" tabindex="0">
3754
+ <div class="codelab-problem-item ${cls}" data-cl-problem-file="${escapeHtml(p.file || '')}" data-cl-problem-line="${p.line || 1}" data-cl-problem-col="${col}" role="button" tabindex="0">
3742
3755
  <span class="codelab-problem-item__icon">${icon}</span>
3743
3756
  <span class="codelab-problem-item__msg">${escapeHtml(p.message || '')}</span>
3744
- <span class="codelab-problem-item__loc">${escapeHtml(p.file || '')}:${p.line || 1}:${p.col || 1}</span>
3757
+ <span class="codelab-problem-item__location codelab-problem-item__loc">${escapeHtml(p.file || '')}:${p.line || 1}:${col}</span>
3745
3758
  </div>
3746
3759
  `;
3747
3760
  }).join('')}
3748
3761
  </div>
3749
3762
  `;
3763
+ if (typeof bodyEl.querySelectorAll === 'function') {
3764
+ bodyEl.querySelectorAll('.codelab-problem-item').forEach((item) => {
3765
+ item.addEventListener('keydown', (e) => {
3766
+ if (e.key === 'Enter' || e.key === ' ') {
3767
+ e.preventDefault();
3768
+ item.click();
3769
+ }
3770
+ });
3771
+ });
3772
+ }
3750
3773
  return;
3751
3774
  }
3752
3775
 
@@ -3818,6 +3841,7 @@ int main() {
3818
3841
  }
3819
3842
 
3820
3843
  if (this.drawerTab === 'terminal') {
3844
+ this._renderTerminalSessionsBar();
3821
3845
  const logsHtml = this.terminalLogs
3822
3846
  .map(item => {
3823
3847
  const html = ansiToHtml ? ansiToHtml(item.text || '') : escapeHtml(item.text || '');
@@ -3826,7 +3850,13 @@ int main() {
3826
3850
  .join('');
3827
3851
  const cwdShort = (this.cwd || '/workspace').replace(/^\/workspace\/?/, '') || '~';
3828
3852
  const promptLabel = this.inRepl ? '> ' : `codelab:${cwdShort}$`;
3829
- bodyEl.innerHTML = `<div class="codelab-terminal" id="cl-terminal-surface" tabindex="0"><div class="codelab-terminal__log" id="cl-terminal-log">${logsHtml}</div><div class="codelab-pty__active-line" id="cl-pty-active-line"><span class="codelab-pty__prompt">${escapeHtml(promptLabel)} </span><span class="codelab-pty__before">${escapeHtml(this._ptyInputBeforeCursor || '')}</span><span class="codelab-pty__cursor blink">&#x2588;</span><span class="codelab-pty__after">${escapeHtml(this._ptyInputAfterCursor || '')}</span></div><form class="codelab-repl" id="cl-repl-form" style="position:absolute;width:1px;height:1px;overflow:hidden;opacity:0;"><span class="codelab-repl__prompt">${escapeHtml(promptLabel)}</span><input type="text" class="codelab-repl__input" id="cl-repl-input" placeholder="ls, pwd, cat file.js, node demo.js, node test.js, or JS/TS expression…" autocomplete="off" spellcheck="false" aria-label="REPL command input"></form></div>`;
3853
+ const busyAttr = this.isRunning ? ' data-busy="true" style="display:none;"' : '';
3854
+ const promptHtml = this.isRunning ? '' : `${escapeHtml(promptLabel)} `;
3855
+ const beforeHtml = this.isRunning ? '' : escapeHtml(this._ptyInputBeforeCursor || '');
3856
+ const afterHtml = this.isRunning ? '' : escapeHtml(this._ptyInputAfterCursor || '');
3857
+ const cursorClass = this.isRunning ? 'codelab-pty__cursor' : 'codelab-pty__cursor blink';
3858
+ const cursorCharHtml = this.isRunning ? '' : '&#x2588;';
3859
+ bodyEl.innerHTML = `<div class="codelab-terminal" id="cl-terminal-surface" tabindex="0"><div class="codelab-terminal__log" id="cl-terminal-log">${logsHtml}</div><div class="codelab-pty__active-line" id="cl-pty-active-line"${busyAttr}><span class="codelab-pty__prompt">${promptHtml}</span><span class="codelab-pty__before">${beforeHtml}</span><span class="${cursorClass}">${cursorCharHtml}</span><span class="codelab-pty__after">${afterHtml}</span></div><form class="codelab-repl" id="cl-repl-form" style="position:absolute;width:1px;height:1px;overflow:hidden;opacity:0;"><span class="codelab-repl__prompt">${escapeHtml(promptLabel)}</span><input type="text" class="codelab-repl__input" id="cl-repl-input" placeholder="ls, pwd, cat file.js, node demo.js, node test.js, or JS/TS expression…" autocomplete="off" spellcheck="false" aria-label="REPL command input"></form></div>`;
3830
3860
  bodyEl.scrollTop = bodyEl.scrollHeight;
3831
3861
  const termSurface = bodyEl.querySelector('#cl-terminal-surface');
3832
3862
  const input = bodyEl.querySelector('#cl-repl-input');
@@ -3838,15 +3868,43 @@ int main() {
3838
3868
  });
3839
3869
  }
3840
3870
  if (input) {
3841
- input.value = (this._ptyInputBeforeCursor || '') + (this._ptyInputAfterCursor || '');
3842
- input.addEventListener('input', () => {
3871
+ input.value = this.isRunning ? '' : ((this._ptyInputBeforeCursor || '') + (this._ptyInputAfterCursor || ''));
3872
+ const syncCaretFromInput = () => {
3873
+ if (this.isRunning) {
3874
+ input.value = '';
3875
+ return;
3876
+ }
3843
3877
  const val = input.value || '';
3844
3878
  const pos = (input.selectionStart !== undefined && input.selectionStart !== null) ? input.selectionStart : val.length;
3845
3879
  this._ptyInputBeforeCursor = val.slice(0, pos);
3846
3880
  this._ptyInputAfterCursor = val.slice(pos);
3847
3881
  this._updatePtyActiveLine();
3882
+ };
3883
+ input.addEventListener('input', syncCaretFromInput);
3884
+ input.addEventListener('click', syncCaretFromInput);
3885
+ input.addEventListener('keyup', e => {
3886
+ if (e.key === 'ArrowLeft' || e.key === 'ArrowRight' || e.key === 'Home' || e.key === 'End') {
3887
+ syncCaretFromInput();
3888
+ }
3848
3889
  });
3849
3890
  input.addEventListener('keydown', e => {
3891
+ if (e.ctrlKey && !e.metaKey && e.key.toLowerCase() === 'c') {
3892
+ e.preventDefault();
3893
+ this._handleInterrupt();
3894
+ return;
3895
+ }
3896
+ if (e.ctrlKey && !e.metaKey && e.key.toLowerCase() === 'l') {
3897
+ e.preventDefault();
3898
+ this._clearTerminalLogs();
3899
+ this._renderDrawerBody();
3900
+ const nextInput = this.container.querySelector('#cl-repl-input');
3901
+ if (nextInput && typeof nextInput.focus === 'function') nextInput.focus();
3902
+ return;
3903
+ }
3904
+ if (this.isRunning) {
3905
+ e.preventDefault();
3906
+ return;
3907
+ }
3850
3908
  if (e.key === 'Tab') {
3851
3909
  e.preventDefault();
3852
3910
  this._handlePtyTabCompletion(input);
@@ -3877,9 +3935,6 @@ int main() {
3877
3935
  this._ptyInputAfterCursor = '';
3878
3936
  this._updatePtyActiveLine();
3879
3937
  }
3880
- } else if (e.ctrlKey && !e.metaKey && e.key.toLowerCase() === 'c') {
3881
- e.preventDefault();
3882
- this._handleInterrupt();
3883
3938
  } else if (e.ctrlKey && !e.metaKey && e.key.toLowerCase() === 'd') {
3884
3939
  e.preventDefault();
3885
3940
  if (this.inRepl) {
@@ -3889,12 +3944,6 @@ int main() {
3889
3944
  const nextInput = this.container.querySelector('#cl-repl-input');
3890
3945
  if (nextInput && typeof nextInput.focus === 'function') nextInput.focus();
3891
3946
  }
3892
- } else if (e.ctrlKey && !e.metaKey && e.key.toLowerCase() === 'l') {
3893
- e.preventDefault();
3894
- this.terminalLogs = [];
3895
- this._renderDrawerBody();
3896
- const nextInput = this.container.querySelector('#cl-repl-input');
3897
- if (nextInput && typeof nextInput.focus === 'function') nextInput.focus();
3898
3947
  } else if (e.ctrlKey && e.key.toLowerCase() === 'u') {
3899
3948
  e.preventDefault();
3900
3949
  this._ptyInputBeforeCursor = '';
@@ -3925,6 +3974,7 @@ int main() {
3925
3974
  if (replForm) {
3926
3975
  replForm.addEventListener('submit', e => {
3927
3976
  e.preventDefault();
3977
+ if (this.isRunning) return;
3928
3978
  const rawCmd = (input && input.value !== undefined ? input.value : '') ||
3929
3979
  ((this._ptyInputBeforeCursor || '') + (this._ptyInputAfterCursor || ''));
3930
3980
  const cmd = rawCmd.trim();
@@ -4006,7 +4056,7 @@ int main() {
4006
4056
  if (chunk === null || chunk === undefined || chunk === '') return;
4007
4057
  const rawText = String(chunk);
4008
4058
 
4009
- if (this.ptyEngine && typeof this.ptyEngine.writeStreamChunk === 'function') {
4059
+ if (this.ptyEngine && this.ptyEngine.container && typeof this.ptyEngine.writeStreamChunk === 'function') {
4010
4060
  try {
4011
4061
  this.ptyEngine.writeStreamChunk(rawText, type);
4012
4062
  } catch (err) {
@@ -4047,6 +4097,14 @@ int main() {
4047
4097
  // A newline completes the current line: commit it to the log + DOM, then begin a fresh line.
4048
4098
  const commitActiveLine = () => {
4049
4099
  this.terminalLogs.push({ type: this._activeStreamType || type, text: this._activeStreamLine });
4100
+ if (this.terminalLogs.length > 2000) {
4101
+ this.terminalLogs.splice(0, this.terminalLogs.length - 2000);
4102
+ if (canPatchDom && termLogEl) {
4103
+ while (termLogEl.childElementCount > 2000 && termLogEl.firstElementChild) {
4104
+ termLogEl.removeChild(termLogEl.firstElementChild);
4105
+ }
4106
+ }
4107
+ }
4050
4108
  patchLineInDom(this._activeStreamLine);
4051
4109
  this._activeStreamLine = '';
4052
4110
  this._activeStreamEl = null;
@@ -4214,15 +4272,39 @@ int main() {
4214
4272
 
4215
4273
  _updatePtyActiveLine() {
4216
4274
  if (!this.container) return;
4275
+ const activeLine = this.container.querySelector('#cl-pty-active-line');
4217
4276
  const beforeEl = this.container.querySelector('.codelab-pty__before');
4218
4277
  const afterEl = this.container.querySelector('.codelab-pty__after');
4219
4278
  const promptEl = this.container.querySelector('.codelab-pty__prompt');
4279
+ const cursorEl = this.container.querySelector('.codelab-pty__cursor');
4220
4280
  const cwdShort = (this.cwd || '/workspace').replace(/^\/workspace\/?/, '') || '~';
4221
4281
  const promptLabel = this.inRepl ? '> ' : `codelab:${cwdShort}$`;
4222
4282
 
4223
- if (promptEl) promptEl.textContent = promptLabel + ' ';
4224
- if (beforeEl) beforeEl.textContent = this._ptyInputBeforeCursor || '';
4225
- if (afterEl) afterEl.textContent = this._ptyInputAfterCursor || '';
4283
+ if (this.isRunning) {
4284
+ if (activeLine) {
4285
+ activeLine.setAttribute('data-busy', 'true');
4286
+ if (activeLine.style) activeLine.style.display = 'none';
4287
+ }
4288
+ if (promptEl) promptEl.textContent = '';
4289
+ if (beforeEl) beforeEl.textContent = '';
4290
+ if (cursorEl) {
4291
+ cursorEl.textContent = '';
4292
+ if (cursorEl.classList) cursorEl.classList.remove('blink');
4293
+ }
4294
+ if (afterEl) afterEl.textContent = '';
4295
+ } else {
4296
+ if (activeLine) {
4297
+ activeLine.removeAttribute('data-busy');
4298
+ if (activeLine.style) activeLine.style.display = '';
4299
+ }
4300
+ if (promptEl) promptEl.textContent = promptLabel + ' ';
4301
+ if (beforeEl) beforeEl.textContent = this._ptyInputBeforeCursor || '';
4302
+ if (cursorEl) {
4303
+ if (!cursorEl.textContent) cursorEl.textContent = '\u2588';
4304
+ if (cursorEl.classList) cursorEl.classList.add('blink');
4305
+ }
4306
+ if (afterEl) afterEl.textContent = this._ptyInputAfterCursor || '';
4307
+ }
4226
4308
  }
4227
4309
 
4228
4310
  _handlePtyTabCompletion(input) {
@@ -5203,9 +5285,10 @@ int main() {
5203
5285
  _injectPreviewCsp(html, port) {
5204
5286
  if (typeof html !== 'string' || !html) return html;
5205
5287
 
5288
+ const csp = String(this._previewPolicy() || '').replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
5206
5289
  const tags = [];
5207
5290
  if (!/<meta[^>]+http-equiv=["']?content-security-policy/i.test(html)) {
5208
- tags.push(`<meta http-equiv="Content-Security-Policy" content="${this._previewPolicy()}">`);
5291
+ tags.push(`<meta http-equiv="Content-Security-Policy" content="${csp}">`);
5209
5292
  }
5210
5293
  if (!/<base\b/i.test(html)) {
5211
5294
  tags.push(`<base href="/__preview/${Number(port) || 3000}/">`);
@@ -6771,21 +6854,29 @@ int main() {
6771
6854
  if (splitTrigger) {
6772
6855
  e.stopPropagation();
6773
6856
  const menu = this.container.querySelector('#cl-split-run-menu');
6774
- if (menu) menu.classList.toggle('active');
6857
+ if (menu) {
6858
+ const isOpen = !(menu.classList.contains('active') || menu.classList.contains('open'));
6859
+ menu.classList.toggle('active', isOpen);
6860
+ menu.classList.toggle('open', isOpen);
6861
+ }
6775
6862
  return;
6776
6863
  }
6777
6864
 
6778
6865
  const splitMenu = this.container.querySelector('#cl-split-run-menu');
6779
- if (splitMenu && splitMenu.classList.contains('active') && !e.target.closest('.codelab-btn-split')) {
6866
+ if (splitMenu && (splitMenu.classList.contains('active') || splitMenu.classList.contains('open')) && !e.target.closest('.codelab-btn-split')) {
6780
6867
  splitMenu.classList.remove('active');
6868
+ splitMenu.classList.remove('open');
6781
6869
  }
6782
6870
 
6783
- const problemItem = e.target.closest('[data-cl-problem-file]');
6871
+ const problemItem = e.target.closest('[data-cl-problem-file], [data-problem-file]');
6784
6872
  if (problemItem) {
6785
6873
  e.stopPropagation();
6786
- const pFile = problemItem.dataset.clProblemFile;
6787
- const pLine = Number(problemItem.dataset.clProblemLine || 1);
6788
- const pCol = Number(problemItem.dataset.clProblemCol || 1);
6874
+ const pFile = problemItem.dataset.clProblemFile || problemItem.dataset.problemFile;
6875
+ const pLine = Number(problemItem.dataset.clProblemLine || problemItem.dataset.problemLine || 1);
6876
+ const pCol = Number(problemItem.dataset.clProblemCol || problemItem.dataset.problemCol || 1);
6877
+ if (problemItem.closest('#cl-modal-slot')) {
6878
+ this.closeModal();
6879
+ }
6789
6880
  if (pFile) {
6790
6881
  this.openFile(pFile);
6791
6882
  if (this.editor && typeof this.editor.revealLineInCenter === 'function') {
@@ -6797,6 +6888,24 @@ int main() {
6797
6888
  return;
6798
6889
  }
6799
6890
 
6891
+ const searchMatch = e.target.closest('[data-cl-search-file]');
6892
+ if (searchMatch) {
6893
+ e.stopPropagation();
6894
+ const sFile = searchMatch.dataset.clSearchFile;
6895
+ const sLine = Number(searchMatch.dataset.clSearchLine || 1);
6896
+ const sCol = Number(searchMatch.dataset.clSearchCol || 1);
6897
+ this.closeModal();
6898
+ if (sFile) {
6899
+ this.openFile(sFile);
6900
+ if (this.editor && typeof this.editor.revealLineInCenter === 'function') {
6901
+ this.editor.revealLineInCenter(sLine);
6902
+ this.editor.setPosition({ lineNumber: sLine, column: sCol });
6903
+ this.editor.focus();
6904
+ }
6905
+ }
6906
+ return;
6907
+ }
6908
+
6800
6909
  const drawerTabBtn = e.target.closest('[data-cl-drawertab]');
6801
6910
  if (drawerTabBtn) {
6802
6911
  this.switchDrawerTab(drawerTabBtn.dataset.clDrawertab);
@@ -6805,8 +6914,9 @@ int main() {
6805
6914
 
6806
6915
  const actionBtn = e.target.closest('[data-cl-action], [data-action]');
6807
6916
  if (actionBtn) {
6808
- if (splitMenu && splitMenu.classList.contains('active')) {
6917
+ if (splitMenu && (splitMenu.classList.contains('active') || splitMenu.classList.contains('open'))) {
6809
6918
  splitMenu.classList.remove('active');
6919
+ splitMenu.classList.remove('open');
6810
6920
  }
6811
6921
  const action = actionBtn.dataset.clAction || actionBtn.dataset.action;
6812
6922
  if (action === 'run-code') this.runCode();
@@ -6909,9 +7019,49 @@ int main() {
6909
7019
  if (drawer) drawer.classList.toggle('is-minimized');
6910
7020
  if (this.editor) setTimeout(() => this.editor.layout(), 50);
6911
7021
  } else if (action === 'clear-terminal') {
6912
- this.terminalLogs = [];
7022
+ this._clearTerminalLogs();
6913
7023
  this.lastTestResults = [];
6914
7024
  this._renderDrawerBody();
7025
+ } else if (action === 'new-terminal-session') {
7026
+ this.createTerminalSession();
7027
+ if (this.drawerTab !== 'terminal') this.switchDrawerTab('terminal');
7028
+ } else if (action === 'switch-terminal-session') {
7029
+ const sid = actionBtn.dataset.sessionId;
7030
+ if (sid) this.switchTerminalSession(sid);
7031
+ } else if (action === 'close-terminal-session') {
7032
+ e.stopPropagation();
7033
+ const sid = actionBtn.dataset.sessionId;
7034
+ if (sid) this.closeTerminalSession(sid);
7035
+ } else if (action === 'scm-stage-file') {
7036
+ e.stopPropagation();
7037
+ const p = actionBtn.dataset.scmPath;
7038
+ if (p) {
7039
+ this.stageGitFile(p);
7040
+ this.showScmModal();
7041
+ }
7042
+ } else if (action === 'scm-unstage-file') {
7043
+ e.stopPropagation();
7044
+ const p = actionBtn.dataset.scmPath;
7045
+ if (p) {
7046
+ this.unstageGitFile(p);
7047
+ this.showScmModal();
7048
+ }
7049
+ } else if (action === 'scm-stage-all') {
7050
+ this.stageAllGitFiles();
7051
+ this.showScmModal();
7052
+ } else if (action === 'scm-commit') {
7053
+ const msgInput = this.container.querySelector('#cl-scm-commit-input');
7054
+ const msg = msgInput ? msgInput.value.trim() : '';
7055
+ if (msg) {
7056
+ this.commitGitChanges(msg);
7057
+ this.showScmModal();
7058
+ }
7059
+ } else if (action === 'scm-open-file') {
7060
+ const p = actionBtn.dataset.scmPath;
7061
+ this.closeModal();
7062
+ if (p && Object.prototype.hasOwnProperty.call(this.files, p)) {
7063
+ this.openFile(p);
7064
+ }
6915
7065
  } else if (action === 'toggle-hint') {
6916
7066
  const box = this.container.querySelector('#cl-hint-box');
6917
7067
  if (box) box.classList.toggle('open');
@@ -8332,7 +8482,7 @@ int main() {
8332
8482
  } else {
8333
8483
  window.location.hash = `codelab=${token}`;
8334
8484
  }
8335
- if (navigator.clipboard && typeof navigator.clipboard.writeText === 'function') {
8485
+ if (typeof navigator !== 'undefined' && navigator.clipboard && typeof navigator.clipboard.writeText === 'function') {
8336
8486
  await navigator.clipboard.writeText(newUrl);
8337
8487
  this._showToast('Snapshot link copied to clipboard! (#codelab=...)', 'success');
8338
8488
  } else {
@@ -8555,6 +8705,7 @@ int main() {
8555
8705
  }
8556
8706
 
8557
8707
  async _handleReplCommand(cmd) {
8708
+ if (this.isRunning) return;
8558
8709
  const trimmed = (cmd || '').trim();
8559
8710
  if (!trimmed) return;
8560
8711
  if (this.replHistory[this.replHistory.length - 1] !== trimmed) {
@@ -8563,7 +8714,19 @@ int main() {
8563
8714
  this.replHistoryIdx = -1;
8564
8715
  const cwdShort = (this.cwd || '/workspace').replace(/^\/workspace\/?/, '') || '~';
8565
8716
  const promptPrefix = this.inRepl ? '> ' : `codelab:${cwdShort}$ `;
8566
- this.terminalLogs.push({ type: 'system', text: `${promptPrefix}${trimmed}` });
8717
+ const echoLine = `${promptPrefix}${trimmed}`;
8718
+ this.terminalLogs.push({ type: 'system', text: echoLine });
8719
+ if (this.terminalLogs.length > 2000) {
8720
+ this.terminalLogs.splice(0, this.terminalLogs.length - 2000);
8721
+ }
8722
+ const termLogEl = this.container ? this.container.querySelector('#cl-terminal-log') : null;
8723
+ const ptyOwnsDom = Boolean(this.ptyEngine && this.ptyEngine.container);
8724
+ if (termLogEl && typeof document !== 'undefined' && !ptyOwnsDom) {
8725
+ const echoEl = document.createElement('div');
8726
+ echoEl.className = 'codelab-log-line system';
8727
+ echoEl.innerHTML = ansiToHtml ? ansiToHtml(echoLine) : escapeHtml(echoLine);
8728
+ termLogEl.appendChild(echoEl);
8729
+ }
8567
8730
 
8568
8731
  if (this.inRepl) {
8569
8732
  if (trimmed === '.exit' || trimmed === 'exit') {
@@ -8573,7 +8736,7 @@ int main() {
8573
8736
  return;
8574
8737
  }
8575
8738
  if (trimmed === '.clear' || trimmed === 'clear') {
8576
- this.terminalLogs = [];
8739
+ this._clearTerminalLogs();
8577
8740
  this._renderDrawerBody();
8578
8741
  return;
8579
8742
  }
@@ -8626,7 +8789,7 @@ int main() {
8626
8789
  }
8627
8790
 
8628
8791
  if (trimmed === 'clear' || trimmed === 'cls') {
8629
- this.terminalLogs = [];
8792
+ this._clearTerminalLogs();
8630
8793
  this._renderDrawerBody();
8631
8794
  return;
8632
8795
  }
@@ -8686,7 +8849,7 @@ int main() {
8686
8849
  this._syncVfsSnapshot(null, true);
8687
8850
 
8688
8851
  if (shellRes && shellRes.clear) {
8689
- this.terminalLogs = [];
8852
+ this._clearTerminalLogs();
8690
8853
  this._renderDrawerBody();
8691
8854
  return;
8692
8855
  }
@@ -8899,6 +9062,10 @@ int main() {
8899
9062
  return bytes;
8900
9063
  }
8901
9064
 
9065
+ exportZip(options = {}) {
9066
+ return this.exportProjectZip(options);
9067
+ }
9068
+
8902
9069
  importProjectZip(zipBytes) {
8903
9070
  const zipMod = root.CodeLabZip;
8904
9071
  if (!zipMod || typeof zipMod.extractZip !== 'function') {
@@ -8911,6 +9078,42 @@ int main() {
8911
9078
  return true;
8912
9079
  }
8913
9080
 
9081
+ importZip(zipBytes) {
9082
+ return this.importProjectZip(zipBytes);
9083
+ }
9084
+
9085
+ async saveProjectToStorage(id) {
9086
+ if (!root.CodeLabStorage || typeof root.CodeLabStorage.createWorkspaceStorage !== 'function') {
9087
+ return false;
9088
+ }
9089
+ if (!this._idbStorage) {
9090
+ this._idbStorage = root.CodeLabStorage.createWorkspaceStorage();
9091
+ }
9092
+ const projectId = id || this.labId || 'workspace';
9093
+ return this._idbStorage.saveProject({
9094
+ id: projectId,
9095
+ name: this.title || projectId,
9096
+ files: { ...(this.files || {}) },
9097
+ updatedAt: Date.now()
9098
+ });
9099
+ }
9100
+
9101
+ async loadProjectFromStorage(id) {
9102
+ if (!root.CodeLabStorage || typeof root.CodeLabStorage.createWorkspaceStorage !== 'function') {
9103
+ return null;
9104
+ }
9105
+ if (!this._idbStorage) {
9106
+ this._idbStorage = root.CodeLabStorage.createWorkspaceStorage();
9107
+ }
9108
+ const projectId = id || this.labId || 'workspace';
9109
+ const loaded = await this._idbStorage.loadProject(projectId);
9110
+ if (loaded && loaded.files && typeof loaded.files === 'object') {
9111
+ this.setFiles(loaded.files);
9112
+ this._syncFilesToShellVfs();
9113
+ }
9114
+ return loaded;
9115
+ }
9116
+
8914
9117
  searchWorkspace(options) {
8915
9118
  const searchMod = root.CodeLabSearch;
8916
9119
  if (!searchMod || typeof searchMod.searchInFiles !== 'function') {
@@ -8924,21 +9127,113 @@ int main() {
8924
9127
  if (!searchMod || typeof searchMod.replaceInFiles !== 'function') {
8925
9128
  throw new Error('CodeLabSearch engine is not loaded');
8926
9129
  }
8927
- const res = searchMod.replaceInFiles(this.files || {}, options);
8928
- if (res && res.files && res.filesModified > 0) {
8929
- this.setFiles(res.files);
9130
+ const res = searchMod.replaceInFiles(this.files || {}, options, options && options.replacement);
9131
+ const nextFiles = res && (res.updatedFiles || res.files);
9132
+ const modifiedCount = res && (typeof res.filesModified === 'number' ? res.filesModified : (Array.isArray(res.filesAffected) ? res.filesAffected.length : 0));
9133
+ if (nextFiles && modifiedCount > 0) {
9134
+ this.setFiles(nextFiles);
8930
9135
  this._syncFilesToShellVfs();
8931
9136
  }
8932
9137
  return res;
8933
9138
  }
8934
9139
 
9140
+ _getGitState() {
9141
+ const scmMod = root.CodeLabScm;
9142
+ if (this.shell && this.shell.gitState) {
9143
+ return this.shell.gitState;
9144
+ }
9145
+ if (!this._gitState && scmMod && typeof scmMod.createGitState === 'function') {
9146
+ this._gitState = scmMod.createGitState(this.files || {});
9147
+ }
9148
+ return this._gitState || null;
9149
+ }
9150
+
8935
9151
  getGitStatus() {
8936
9152
  const scmMod = root.CodeLabScm;
8937
9153
  if (!scmMod || typeof scmMod.computeGitStatus !== 'function') {
8938
9154
  return [];
8939
9155
  }
8940
- const gs = (this.shell && this.shell.gitState) ? this.shell.gitState : scmMod.createGitState(this.files || {});
8941
- return scmMod.computeGitStatus(gs, this.files || {});
9156
+ const gs = this._getGitState() || scmMod.createGitState(this.files || {});
9157
+ const res = scmMod.computeGitStatus(this.files || {}, '/workspace', gs);
9158
+ return res && Array.isArray(res.entries) ? res.entries : (Array.isArray(res) ? res : []);
9159
+ }
9160
+
9161
+ stageGitFile(relPath) {
9162
+ if (!relPath) return false;
9163
+ const gs = this._getGitState();
9164
+ if (!gs) return false;
9165
+ const scmMod = root.CodeLabScm;
9166
+ if (gs.staged instanceof Set) {
9167
+ gs.staged.add(relPath);
9168
+ } else if (scmMod && typeof scmMod.stageFile === 'function') {
9169
+ const currentContent = Object.prototype.hasOwnProperty.call(this.files, relPath) ? this.files[relPath] : null;
9170
+ scmMod.stageFile(gs, relPath, currentContent);
9171
+ }
9172
+ return true;
9173
+ }
9174
+
9175
+ unstageGitFile(relPath) {
9176
+ if (!relPath) return false;
9177
+ const gs = this._getGitState();
9178
+ if (!gs || !gs.staged || typeof gs.staged.delete !== 'function') return false;
9179
+ gs.staged.delete(relPath);
9180
+ return true;
9181
+ }
9182
+
9183
+ stageAllGitFiles() {
9184
+ const entries = this.getGitStatus();
9185
+ for (const entry of entries) {
9186
+ if (!entry.staged) {
9187
+ this.stageGitFile(entry.path);
9188
+ }
9189
+ }
9190
+ return true;
9191
+ }
9192
+
9193
+ commitGitChanges(message) {
9194
+ const msg = typeof message === 'string' ? message.trim() : '';
9195
+ if (!msg) return null;
9196
+ const gs = this._getGitState();
9197
+ if (!gs) return null;
9198
+ const scmMod = root.CodeLabScm;
9199
+ if (gs.staged instanceof Set) {
9200
+ if (gs.staged.size === 0) return null;
9201
+ if (!gs.headSnapshot) gs.headSnapshot = {};
9202
+ for (const relPath of gs.staged) {
9203
+ if (Object.prototype.hasOwnProperty.call(this.files, relPath)) {
9204
+ gs.headSnapshot[relPath] = this.files[relPath];
9205
+ } else {
9206
+ delete gs.headSnapshot[relPath];
9207
+ }
9208
+ }
9209
+ gs.headFiles = Object.assign({}, gs.headSnapshot);
9210
+ const hash = scmMod && typeof scmMod.computeShortCommitHash === 'function'
9211
+ ? scmMod.computeShortCommitHash(`${gs.branch || 'main'}:${msg}:${Date.now()}`)
9212
+ : Math.random().toString(16).slice(2, 9);
9213
+ if (!Array.isArray(gs.commits)) gs.commits = [];
9214
+ gs.commits.unshift({
9215
+ hash,
9216
+ author: 'CodeLab Developer <dev@codelab.internal>',
9217
+ date: new Date().toUTCString(),
9218
+ timestamp: Date.now(),
9219
+ message: msg
9220
+ });
9221
+ gs.headCommit = hash;
9222
+ gs.staged.clear();
9223
+ this._syncFilesToShellVfs();
9224
+ return hash;
9225
+ }
9226
+ if (scmMod && typeof scmMod.commitChanges === 'function') {
9227
+ try {
9228
+ const hash = scmMod.commitChanges(gs, msg);
9229
+ if (gs.headFiles) gs.headSnapshot = Object.assign({}, gs.headFiles);
9230
+ this._syncFilesToShellVfs();
9231
+ return hash;
9232
+ } catch (_err) {
9233
+ return null;
9234
+ }
9235
+ }
9236
+ return null;
8942
9237
  }
8943
9238
 
8944
9239
  getDiagnostics() {
@@ -8956,12 +9251,20 @@ int main() {
8956
9251
  const slot = this.container ? this.container.querySelector('#cl-modal-slot') : null;
8957
9252
  if (!slot) return;
8958
9253
  const q = String(initialQuery || '');
8959
- const results = q ? this.searchWorkspace({ query: q }) : { matches: [], totalMatches: 0, filesMatched: 0 };
8960
- const rowsHtml = (results.matches || []).map((m) => `
8961
- <div class="codelab-search-match" data-cl-file="${escapeHtml(m.file)}" style="padding:6px 8px;border-bottom:1px solid var(--cl-border);cursor:pointer;font-family:var(--cl-font-mono);font-size:12px;">
8962
- <strong>${escapeHtml(m.file)}:${m.line}:${m.column}</strong> — <span>${escapeHtml(m.lineText)}</span>
8963
- </div>
8964
- `).join('');
9254
+ const renderRows = (queryText) => {
9255
+ const res = queryText ? this.searchWorkspace({ query: queryText }) : { matches: [], totalMatches: 0, filesMatched: 0 };
9256
+ if (!queryText) {
9257
+ return '<div style="color:var(--cl-fg-muted);font-size:12px;">Enter a query to search across workspace files.</div>';
9258
+ }
9259
+ if (!res.matches || res.matches.length === 0) {
9260
+ return '<div style="color:var(--cl-fg-muted);font-size:12px;">No matches found in workspace.</div>';
9261
+ }
9262
+ return res.matches.map((m) => `
9263
+ <div class="codelab-search-match" data-cl-file="${escapeHtml(m.file)}" data-cl-search-file="${escapeHtml(m.file)}" data-cl-search-line="${m.line || 1}" data-cl-search-col="${m.column || 1}" role="button" tabindex="0" style="padding:6px 8px;border-bottom:1px solid var(--cl-border);cursor:pointer;font-family:var(--cl-font-mono);font-size:12px;">
9264
+ <strong>${escapeHtml(m.file)}:${m.line}:${m.column}</strong> — <span>${escapeHtml(m.lineText)}</span>
9265
+ </div>
9266
+ `).join('');
9267
+ };
8965
9268
  slot.innerHTML = `
8966
9269
  <div class="codelab-modal-backdrop">
8967
9270
  <div class="codelab-modal" role="dialog" aria-modal="true" aria-label="Search Across Workspace">
@@ -8970,36 +9273,82 @@ int main() {
8970
9273
  <button type="button" class="codelab-btn" data-cl-action="close-modal">Close (Esc)</button>
8971
9274
  </div>
8972
9275
  <div class="codelab-modal__body">
8973
- <div style="display:flex;gap:8px;margin-bottom:8px;">
8974
- <input id="cl-search-query-input" type="text" value="${escapeHtml(q)}" placeholder="Search text or regex..." style="flex:1;padding:6px 8px;" />
8975
- <input id="cl-search-replace-input" type="text" placeholder="Replace with..." style="flex:1;padding:6px 8px;" />
9276
+ <div style="display:flex;gap:8px;margin-bottom:8px;align-items:center;">
9277
+ <input id="cl-search-query-input" class="codelab-modal-input" type="text" value="${escapeHtml(q)}" placeholder="Search text or regex..." />
9278
+ <input id="cl-search-replace-input" class="codelab-modal-input" type="text" placeholder="Replace with..." />
9279
+ <button type="button" id="cl-search-replace-all-btn" class="codelab-btn codelab-btn--primary" style="padding:5px 10px;font-size:12px;white-space:nowrap;">Replace All</button>
8976
9280
  </div>
8977
- <div id="cl-search-results-list">${rowsHtml || '<div style="color:var(--cl-fg-muted);font-size:12px;">Enter a query to search across workspace files.</div>'}</div>
9281
+ <div id="cl-search-results-list" style="max-height:320px;overflow-y:auto;">${renderRows(q)}</div>
8978
9282
  </div>
8979
9283
  </div>
8980
9284
  </div>
8981
9285
  `;
9286
+ const queryInput = slot.querySelector('#cl-search-query-input');
9287
+ const replaceInput = slot.querySelector('#cl-search-replace-input');
9288
+ const replaceBtn = slot.querySelector('#cl-search-replace-all-btn');
9289
+ const listEl = slot.querySelector('#cl-search-results-list');
9290
+ if (queryInput && listEl) {
9291
+ queryInput.addEventListener('input', () => {
9292
+ listEl.innerHTML = renderRows(queryInput.value || '');
9293
+ });
9294
+ if (typeof queryInput.focus === 'function') queryInput.focus();
9295
+ }
9296
+ if (replaceBtn && queryInput && replaceInput && listEl) {
9297
+ const triggerReplace = () => {
9298
+ const queryVal = queryInput.value || '';
9299
+ if (!queryVal) return;
9300
+ this.replaceInWorkspace({ query: queryVal, replacement: replaceInput.value || '' });
9301
+ listEl.innerHTML = renderRows(queryVal);
9302
+ };
9303
+ replaceBtn.addEventListener('click', triggerReplace);
9304
+ replaceInput.addEventListener('keydown', (e) => {
9305
+ if (e.key === 'Enter') {
9306
+ e.preventDefault();
9307
+ triggerReplace();
9308
+ }
9309
+ });
9310
+ }
8982
9311
  }
8983
9312
 
8984
9313
  showScmModal() {
8985
9314
  const slot = this.container ? this.container.querySelector('#cl-modal-slot') : null;
8986
9315
  if (!slot) return;
8987
9316
  const statusList = this.getGitStatus();
8988
- const rowsHtml = statusList.map((entry) => `
8989
- <div class="codelab-scm-entry" data-scm-path="${escapeHtml(entry.path)}" style="display:flex;justify-content:space-between;padding:6px 8px;border-bottom:1px solid var(--cl-border);font-family:var(--cl-font-mono);font-size:12px;">
8990
- <span>${escapeHtml(entry.path)}</span>
8991
- <span>${escapeHtml(entry.worktree !== ' ' ? entry.worktree : entry.index)}</span>
8992
- </div>
8993
- `).join('');
9317
+ const gs = this._getGitState();
9318
+ const branch = (gs && gs.branch) ? gs.branch : 'main';
9319
+ const hasStaged = statusList.some((e) => e.staged);
9320
+ const hasUnstaged = statusList.some((e) => !e.staged);
9321
+ const rowsHtml = statusList.map((entry) => {
9322
+ const badge = entry.staged ? `Staged (${entry.index})` : (entry.worktree !== ' ' ? entry.worktree : entry.index);
9323
+ const actionBtn = entry.staged
9324
+ ? `<button type="button" class="codelab-btn" data-cl-action="scm-unstage-file" data-scm-path="${escapeHtml(entry.path)}" style="padding:2px 8px;font-size:11px;">Unstage</button>`
9325
+ : `<button type="button" class="codelab-btn" data-cl-action="scm-stage-file" data-scm-path="${escapeHtml(entry.path)}" style="padding:2px 8px;font-size:11px;">Stage</button>`;
9326
+ return `
9327
+ <div class="codelab-scm-entry" data-scm-path="${escapeHtml(entry.path)}" style="display:flex;justify-content:space-between;align-items:center;padding:6px 8px;border-bottom:1px solid var(--cl-border);font-family:var(--cl-font-mono);font-size:12px;">
9328
+ <span data-cl-action="scm-open-file" data-scm-path="${escapeHtml(entry.path)}" style="cursor:pointer;text-decoration:underline;">${escapeHtml(entry.path)}</span>
9329
+ <span style="display:inline-flex;align-items:center;gap:8px;">
9330
+ <span>${escapeHtml(badge)}</span>
9331
+ ${actionBtn}
9332
+ </span>
9333
+ </div>
9334
+ `;
9335
+ }).join('');
8994
9336
  slot.innerHTML = `
8995
9337
  <div class="codelab-modal-backdrop">
8996
9338
  <div class="codelab-modal" role="dialog" aria-modal="true" aria-label="Source Control">
8997
9339
  <div class="codelab-modal__header">
8998
- <span>Source Control (Git Status)</span>
8999
- <button type="button" class="codelab-btn" data-cl-action="close-modal">Close (Esc)</button>
9340
+ <span>Source Control (Git Status · ${escapeHtml(branch)})</span>
9341
+ <div style="display:flex;gap:6px;align-items:center;">
9342
+ ${hasUnstaged ? `<button type="button" class="codelab-btn" data-cl-action="scm-stage-all" style="padding:3px 8px;font-size:11px;">Stage All</button>` : ''}
9343
+ <button type="button" class="codelab-btn" data-cl-action="close-modal">Close (Esc)</button>
9344
+ </div>
9000
9345
  </div>
9001
9346
  <div class="codelab-modal__body">
9002
- <div id="cl-scm-status-list">${rowsHtml || '<div style="color:var(--cl-fg-muted);font-size:12px;">Working tree clean</div>'}</div>
9347
+ <div style="display:flex;gap:8px;margin-bottom:8px;align-items:center;">
9348
+ <input id="cl-scm-commit-input" class="codelab-modal-input" type="text" placeholder="Commit message (e.g. feat: update module)..." />
9349
+ <button type="button" id="cl-scm-commit-btn" class="codelab-btn codelab-btn--primary" data-cl-action="scm-commit" ${hasStaged ? '' : 'disabled'} style="padding:5px 10px;font-size:12px;white-space:nowrap;">Commit</button>
9350
+ </div>
9351
+ <div id="cl-scm-status-list" style="max-height:300px;overflow-y:auto;">${rowsHtml || '<div style="color:var(--cl-fg-muted);font-size:12px;">Working tree clean</div>'}</div>
9003
9352
  </div>
9004
9353
  </div>
9005
9354
  </div>
@@ -9011,11 +9360,14 @@ int main() {
9011
9360
  const slot = this.container ? this.container.querySelector('#cl-modal-slot') : null;
9012
9361
  if (!slot) return;
9013
9362
  const items = this.getDiagnostics();
9014
- const rowsHtml = items.map((d) => `
9015
- <div class="codelab-problem-entry" data-problem-file="${escapeHtml(d.file)}" style="padding:6px 8px;border-bottom:1px solid var(--cl-border);font-family:var(--cl-font-mono);font-size:12px;">
9016
- <strong>[${escapeHtml(d.severity)}] ${escapeHtml(d.file)}:${d.line}:${d.column}</strong> — ${escapeHtml(d.message)}
9017
- </div>
9018
- `).join('');
9363
+ const rowsHtml = items.map((d) => {
9364
+ const col = d.col || d.column || 1;
9365
+ return `
9366
+ <div class="codelab-problem-entry" data-problem-file="${escapeHtml(d.file || '')}" data-cl-problem-file="${escapeHtml(d.file || '')}" data-cl-problem-line="${d.line || 1}" data-cl-problem-col="${col}" role="button" tabindex="0" style="padding:6px 8px;border-bottom:1px solid var(--cl-border);cursor:pointer;font-family:var(--cl-font-mono);font-size:12px;">
9367
+ <strong>[${escapeHtml(d.severity)}] ${escapeHtml(d.file || '')}:${d.line || 1}:${col}</strong> — ${escapeHtml(d.message || '')}
9368
+ </div>
9369
+ `;
9370
+ }).join('');
9019
9371
  slot.innerHTML = `
9020
9372
  <div class="codelab-modal-backdrop">
9021
9373
  <div class="codelab-modal" role="dialog" aria-modal="true" aria-label="Problems and Diagnostics">
@@ -9031,6 +9383,40 @@ int main() {
9031
9383
  `;
9032
9384
  }
9033
9385
 
9386
+ _clearTerminalLogs() {
9387
+ if (Array.isArray(this.terminalLogs)) {
9388
+ this.terminalLogs.length = 0;
9389
+ } else {
9390
+ this.terminalLogs = [];
9391
+ }
9392
+ if (Array.isArray(this._terminalSessions)) {
9393
+ const active = this._terminalSessions.find((s) => s.id === this._activeTerminalSessionId);
9394
+ if (active) {
9395
+ active.logs = this.terminalLogs;
9396
+ }
9397
+ }
9398
+ }
9399
+
9400
+ _renderTerminalSessionsBar() {
9401
+ if (!this.container || typeof this.container.querySelector !== 'function') return;
9402
+ const bar = this.container.querySelector('#cl-terminal-sessions');
9403
+ if (!bar) return;
9404
+ const sessions = this._ensureTerminalSessions();
9405
+ if (sessions.length <= 1) {
9406
+ bar.innerHTML = '';
9407
+ return;
9408
+ }
9409
+ bar.innerHTML = sessions.map((s) => {
9410
+ const isActive = s.id === this._activeTerminalSessionId;
9411
+ return `
9412
+ <span class="codelab-session-pill ${isActive ? 'active' : ''}" data-cl-action="switch-terminal-session" data-session-id="${escapeHtml(s.id)}" role="button" tabindex="0" title="Switch to ${escapeHtml(s.name)}">
9413
+ <span>${escapeHtml(s.name)}</span>
9414
+ <span data-cl-action="close-terminal-session" data-session-id="${escapeHtml(s.id)}" title="Close session" style="margin-left:2px;opacity:0.75;">&times;</span>
9415
+ </span>
9416
+ `;
9417
+ }).join('');
9418
+ }
9419
+
9034
9420
  _ensureTerminalSessions() {
9035
9421
  if (!Array.isArray(this._terminalSessions) || this._terminalSessions.length === 0) {
9036
9422
  this._terminalSessions = [
@@ -9443,6 +9829,13 @@ int main() {
9443
9829
  this._editorResizeObserver.disconnect();
9444
9830
  this._editorResizeObserver = null;
9445
9831
  }
9832
+ if (this._diffManager && typeof this._diffManager.closeInlineDiff === 'function') {
9833
+ try {
9834
+ this._diffManager.closeInlineDiff();
9835
+ } catch (err) {
9836
+ this.logger.debug('diffManager.closeInlineDiff failed during destroy.', err);
9837
+ }
9838
+ }
9446
9839
  if (this.editor) {
9447
9840
  this.editor.dispose();
9448
9841
  this.editor = null;