@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/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.1';
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() {
@@ -2391,6 +2410,7 @@ int main() {
2391
2410
 
2392
2411
  let stdinTab = drawerTabs.querySelector('[data-cl-drawertab="stdin"]');
2393
2412
  if (!stdinTab) {
2413
+ const testTab = drawerTabs.querySelector('[data-cl-drawertab="tests"]');
2394
2414
  const afterTab = testTab || drawerTabs.querySelector('[data-cl-drawertab="problems"]') || drawerTabs.querySelector('[data-cl-drawertab="terminal"]');
2395
2415
  if (afterTab) {
2396
2416
  afterTab.insertAdjacentHTML('afterend', `
@@ -2639,6 +2659,8 @@ int main() {
2639
2659
  </div>
2640
2660
  <div class="codelab-hud-pill" id="cl-telemetry-hud" style="display:none;" title="Last Execution Telemetry"></div>
2641
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>
2642
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>
2643
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>
2644
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>
@@ -3727,16 +3749,27 @@ int main() {
3727
3749
  ${problems.map(p => {
3728
3750
  const icon = p.severity === 'error' ? '✖' : (p.severity === 'warning' ? '⚠' : 'ℹ');
3729
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;
3730
3753
  return `
3731
- <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">
3732
3755
  <span class="codelab-problem-item__icon">${icon}</span>
3733
3756
  <span class="codelab-problem-item__msg">${escapeHtml(p.message || '')}</span>
3734
- <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>
3735
3758
  </div>
3736
3759
  `;
3737
3760
  }).join('')}
3738
3761
  </div>
3739
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
+ }
3740
3773
  return;
3741
3774
  }
3742
3775
 
@@ -3808,6 +3841,7 @@ int main() {
3808
3841
  }
3809
3842
 
3810
3843
  if (this.drawerTab === 'terminal') {
3844
+ this._renderTerminalSessionsBar();
3811
3845
  const logsHtml = this.terminalLogs
3812
3846
  .map(item => {
3813
3847
  const html = ansiToHtml ? ansiToHtml(item.text || '') : escapeHtml(item.text || '');
@@ -3816,7 +3850,13 @@ int main() {
3816
3850
  .join('');
3817
3851
  const cwdShort = (this.cwd || '/workspace').replace(/^\/workspace\/?/, '') || '~';
3818
3852
  const promptLabel = this.inRepl ? '> ' : `codelab:${cwdShort}$`;
3819
- 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>`;
3820
3860
  bodyEl.scrollTop = bodyEl.scrollHeight;
3821
3861
  const termSurface = bodyEl.querySelector('#cl-terminal-surface');
3822
3862
  const input = bodyEl.querySelector('#cl-repl-input');
@@ -3828,15 +3868,43 @@ int main() {
3828
3868
  });
3829
3869
  }
3830
3870
  if (input) {
3831
- input.value = (this._ptyInputBeforeCursor || '') + (this._ptyInputAfterCursor || '');
3832
- 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
+ }
3833
3877
  const val = input.value || '';
3834
3878
  const pos = (input.selectionStart !== undefined && input.selectionStart !== null) ? input.selectionStart : val.length;
3835
3879
  this._ptyInputBeforeCursor = val.slice(0, pos);
3836
3880
  this._ptyInputAfterCursor = val.slice(pos);
3837
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
+ }
3838
3889
  });
3839
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
+ }
3840
3908
  if (e.key === 'Tab') {
3841
3909
  e.preventDefault();
3842
3910
  this._handlePtyTabCompletion(input);
@@ -3867,9 +3935,6 @@ int main() {
3867
3935
  this._ptyInputAfterCursor = '';
3868
3936
  this._updatePtyActiveLine();
3869
3937
  }
3870
- } else if (e.ctrlKey && !e.metaKey && e.key.toLowerCase() === 'c') {
3871
- e.preventDefault();
3872
- this._handleInterrupt();
3873
3938
  } else if (e.ctrlKey && !e.metaKey && e.key.toLowerCase() === 'd') {
3874
3939
  e.preventDefault();
3875
3940
  if (this.inRepl) {
@@ -3879,12 +3944,6 @@ int main() {
3879
3944
  const nextInput = this.container.querySelector('#cl-repl-input');
3880
3945
  if (nextInput && typeof nextInput.focus === 'function') nextInput.focus();
3881
3946
  }
3882
- } else if (e.ctrlKey && !e.metaKey && e.key.toLowerCase() === 'l') {
3883
- e.preventDefault();
3884
- this.terminalLogs = [];
3885
- this._renderDrawerBody();
3886
- const nextInput = this.container.querySelector('#cl-repl-input');
3887
- if (nextInput && typeof nextInput.focus === 'function') nextInput.focus();
3888
3947
  } else if (e.ctrlKey && e.key.toLowerCase() === 'u') {
3889
3948
  e.preventDefault();
3890
3949
  this._ptyInputBeforeCursor = '';
@@ -3915,6 +3974,7 @@ int main() {
3915
3974
  if (replForm) {
3916
3975
  replForm.addEventListener('submit', e => {
3917
3976
  e.preventDefault();
3977
+ if (this.isRunning) return;
3918
3978
  const rawCmd = (input && input.value !== undefined ? input.value : '') ||
3919
3979
  ((this._ptyInputBeforeCursor || '') + (this._ptyInputAfterCursor || ''));
3920
3980
  const cmd = rawCmd.trim();
@@ -3996,7 +4056,7 @@ int main() {
3996
4056
  if (chunk === null || chunk === undefined || chunk === '') return;
3997
4057
  const rawText = String(chunk);
3998
4058
 
3999
- if (this.ptyEngine && typeof this.ptyEngine.writeStreamChunk === 'function') {
4059
+ if (this.ptyEngine && this.ptyEngine.container && typeof this.ptyEngine.writeStreamChunk === 'function') {
4000
4060
  try {
4001
4061
  this.ptyEngine.writeStreamChunk(rawText, type);
4002
4062
  } catch (err) {
@@ -4037,6 +4097,14 @@ int main() {
4037
4097
  // A newline completes the current line: commit it to the log + DOM, then begin a fresh line.
4038
4098
  const commitActiveLine = () => {
4039
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
+ }
4040
4108
  patchLineInDom(this._activeStreamLine);
4041
4109
  this._activeStreamLine = '';
4042
4110
  this._activeStreamEl = null;
@@ -4204,15 +4272,39 @@ int main() {
4204
4272
 
4205
4273
  _updatePtyActiveLine() {
4206
4274
  if (!this.container) return;
4275
+ const activeLine = this.container.querySelector('#cl-pty-active-line');
4207
4276
  const beforeEl = this.container.querySelector('.codelab-pty__before');
4208
4277
  const afterEl = this.container.querySelector('.codelab-pty__after');
4209
4278
  const promptEl = this.container.querySelector('.codelab-pty__prompt');
4279
+ const cursorEl = this.container.querySelector('.codelab-pty__cursor');
4210
4280
  const cwdShort = (this.cwd || '/workspace').replace(/^\/workspace\/?/, '') || '~';
4211
4281
  const promptLabel = this.inRepl ? '> ' : `codelab:${cwdShort}$`;
4212
4282
 
4213
- if (promptEl) promptEl.textContent = promptLabel + ' ';
4214
- if (beforeEl) beforeEl.textContent = this._ptyInputBeforeCursor || '';
4215
- 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
+ }
4216
4308
  }
4217
4309
 
4218
4310
  _handlePtyTabCompletion(input) {
@@ -5193,9 +5285,10 @@ int main() {
5193
5285
  _injectPreviewCsp(html, port) {
5194
5286
  if (typeof html !== 'string' || !html) return html;
5195
5287
 
5288
+ const csp = String(this._previewPolicy() || '').replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
5196
5289
  const tags = [];
5197
5290
  if (!/<meta[^>]+http-equiv=["']?content-security-policy/i.test(html)) {
5198
- tags.push(`<meta http-equiv="Content-Security-Policy" content="${this._previewPolicy()}">`);
5291
+ tags.push(`<meta http-equiv="Content-Security-Policy" content="${csp}">`);
5199
5292
  }
5200
5293
  if (!/<base\b/i.test(html)) {
5201
5294
  tags.push(`<base href="/__preview/${Number(port) || 3000}/">`);
@@ -6761,21 +6854,29 @@ int main() {
6761
6854
  if (splitTrigger) {
6762
6855
  e.stopPropagation();
6763
6856
  const menu = this.container.querySelector('#cl-split-run-menu');
6764
- 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
+ }
6765
6862
  return;
6766
6863
  }
6767
6864
 
6768
6865
  const splitMenu = this.container.querySelector('#cl-split-run-menu');
6769
- 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')) {
6770
6867
  splitMenu.classList.remove('active');
6868
+ splitMenu.classList.remove('open');
6771
6869
  }
6772
6870
 
6773
- const problemItem = e.target.closest('[data-cl-problem-file]');
6871
+ const problemItem = e.target.closest('[data-cl-problem-file], [data-problem-file]');
6774
6872
  if (problemItem) {
6775
6873
  e.stopPropagation();
6776
- const pFile = problemItem.dataset.clProblemFile;
6777
- const pLine = Number(problemItem.dataset.clProblemLine || 1);
6778
- 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
+ }
6779
6880
  if (pFile) {
6780
6881
  this.openFile(pFile);
6781
6882
  if (this.editor && typeof this.editor.revealLineInCenter === 'function') {
@@ -6787,6 +6888,24 @@ int main() {
6787
6888
  return;
6788
6889
  }
6789
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
+
6790
6909
  const drawerTabBtn = e.target.closest('[data-cl-drawertab]');
6791
6910
  if (drawerTabBtn) {
6792
6911
  this.switchDrawerTab(drawerTabBtn.dataset.clDrawertab);
@@ -6795,8 +6914,9 @@ int main() {
6795
6914
 
6796
6915
  const actionBtn = e.target.closest('[data-cl-action], [data-action]');
6797
6916
  if (actionBtn) {
6798
- if (splitMenu && splitMenu.classList.contains('active')) {
6917
+ if (splitMenu && (splitMenu.classList.contains('active') || splitMenu.classList.contains('open'))) {
6799
6918
  splitMenu.classList.remove('active');
6919
+ splitMenu.classList.remove('open');
6800
6920
  }
6801
6921
  const action = actionBtn.dataset.clAction || actionBtn.dataset.action;
6802
6922
  if (action === 'run-code') this.runCode();
@@ -6899,9 +7019,49 @@ int main() {
6899
7019
  if (drawer) drawer.classList.toggle('is-minimized');
6900
7020
  if (this.editor) setTimeout(() => this.editor.layout(), 50);
6901
7021
  } else if (action === 'clear-terminal') {
6902
- this.terminalLogs = [];
7022
+ this._clearTerminalLogs();
6903
7023
  this.lastTestResults = [];
6904
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
+ }
6905
7065
  } else if (action === 'toggle-hint') {
6906
7066
  const box = this.container.querySelector('#cl-hint-box');
6907
7067
  if (box) box.classList.toggle('open');
@@ -8545,6 +8705,7 @@ int main() {
8545
8705
  }
8546
8706
 
8547
8707
  async _handleReplCommand(cmd) {
8708
+ if (this.isRunning) return;
8548
8709
  const trimmed = (cmd || '').trim();
8549
8710
  if (!trimmed) return;
8550
8711
  if (this.replHistory[this.replHistory.length - 1] !== trimmed) {
@@ -8553,7 +8714,19 @@ int main() {
8553
8714
  this.replHistoryIdx = -1;
8554
8715
  const cwdShort = (this.cwd || '/workspace').replace(/^\/workspace\/?/, '') || '~';
8555
8716
  const promptPrefix = this.inRepl ? '> ' : `codelab:${cwdShort}$ `;
8556
- 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
+ }
8557
8730
 
8558
8731
  if (this.inRepl) {
8559
8732
  if (trimmed === '.exit' || trimmed === 'exit') {
@@ -8563,7 +8736,7 @@ int main() {
8563
8736
  return;
8564
8737
  }
8565
8738
  if (trimmed === '.clear' || trimmed === 'clear') {
8566
- this.terminalLogs = [];
8739
+ this._clearTerminalLogs();
8567
8740
  this._renderDrawerBody();
8568
8741
  return;
8569
8742
  }
@@ -8616,7 +8789,7 @@ int main() {
8616
8789
  }
8617
8790
 
8618
8791
  if (trimmed === 'clear' || trimmed === 'cls') {
8619
- this.terminalLogs = [];
8792
+ this._clearTerminalLogs();
8620
8793
  this._renderDrawerBody();
8621
8794
  return;
8622
8795
  }
@@ -8676,7 +8849,7 @@ int main() {
8676
8849
  this._syncVfsSnapshot(null, true);
8677
8850
 
8678
8851
  if (shellRes && shellRes.clear) {
8679
- this.terminalLogs = [];
8852
+ this._clearTerminalLogs();
8680
8853
  this._renderDrawerBody();
8681
8854
  return;
8682
8855
  }
@@ -8889,6 +9062,10 @@ int main() {
8889
9062
  return bytes;
8890
9063
  }
8891
9064
 
9065
+ exportZip(options = {}) {
9066
+ return this.exportProjectZip(options);
9067
+ }
9068
+
8892
9069
  importProjectZip(zipBytes) {
8893
9070
  const zipMod = root.CodeLabZip;
8894
9071
  if (!zipMod || typeof zipMod.extractZip !== 'function') {
@@ -8901,6 +9078,42 @@ int main() {
8901
9078
  return true;
8902
9079
  }
8903
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
+
8904
9117
  searchWorkspace(options) {
8905
9118
  const searchMod = root.CodeLabSearch;
8906
9119
  if (!searchMod || typeof searchMod.searchInFiles !== 'function') {
@@ -8914,21 +9127,113 @@ int main() {
8914
9127
  if (!searchMod || typeof searchMod.replaceInFiles !== 'function') {
8915
9128
  throw new Error('CodeLabSearch engine is not loaded');
8916
9129
  }
8917
- const res = searchMod.replaceInFiles(this.files || {}, options);
8918
- if (res && res.files && res.filesModified > 0) {
8919
- 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);
8920
9135
  this._syncFilesToShellVfs();
8921
9136
  }
8922
9137
  return res;
8923
9138
  }
8924
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
+
8925
9151
  getGitStatus() {
8926
9152
  const scmMod = root.CodeLabScm;
8927
9153
  if (!scmMod || typeof scmMod.computeGitStatus !== 'function') {
8928
9154
  return [];
8929
9155
  }
8930
- const gs = (this.shell && this.shell.gitState) ? this.shell.gitState : scmMod.createGitState(this.files || {});
8931
- 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;
8932
9237
  }
8933
9238
 
8934
9239
  getDiagnostics() {
@@ -8946,12 +9251,20 @@ int main() {
8946
9251
  const slot = this.container ? this.container.querySelector('#cl-modal-slot') : null;
8947
9252
  if (!slot) return;
8948
9253
  const q = String(initialQuery || '');
8949
- const results = q ? this.searchWorkspace({ query: q }) : { matches: [], totalMatches: 0, filesMatched: 0 };
8950
- const rowsHtml = (results.matches || []).map((m) => `
8951
- <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;">
8952
- <strong>${escapeHtml(m.file)}:${m.line}:${m.column}</strong> — <span>${escapeHtml(m.lineText)}</span>
8953
- </div>
8954
- `).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
+ };
8955
9268
  slot.innerHTML = `
8956
9269
  <div class="codelab-modal-backdrop">
8957
9270
  <div class="codelab-modal" role="dialog" aria-modal="true" aria-label="Search Across Workspace">
@@ -8960,36 +9273,82 @@ int main() {
8960
9273
  <button type="button" class="codelab-btn" data-cl-action="close-modal">Close (Esc)</button>
8961
9274
  </div>
8962
9275
  <div class="codelab-modal__body">
8963
- <div style="display:flex;gap:8px;margin-bottom:8px;">
8964
- <input id="cl-search-query-input" type="text" value="${escapeHtml(q)}" placeholder="Search text or regex..." style="flex:1;padding:6px 8px;" />
8965
- <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>
8966
9280
  </div>
8967
- <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>
8968
9282
  </div>
8969
9283
  </div>
8970
9284
  </div>
8971
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
+ }
8972
9311
  }
8973
9312
 
8974
9313
  showScmModal() {
8975
9314
  const slot = this.container ? this.container.querySelector('#cl-modal-slot') : null;
8976
9315
  if (!slot) return;
8977
9316
  const statusList = this.getGitStatus();
8978
- const rowsHtml = statusList.map((entry) => `
8979
- <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;">
8980
- <span>${escapeHtml(entry.path)}</span>
8981
- <span>${escapeHtml(entry.worktree !== ' ' ? entry.worktree : entry.index)}</span>
8982
- </div>
8983
- `).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('');
8984
9336
  slot.innerHTML = `
8985
9337
  <div class="codelab-modal-backdrop">
8986
9338
  <div class="codelab-modal" role="dialog" aria-modal="true" aria-label="Source Control">
8987
9339
  <div class="codelab-modal__header">
8988
- <span>Source Control (Git Status)</span>
8989
- <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>
8990
9345
  </div>
8991
9346
  <div class="codelab-modal__body">
8992
- <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>
8993
9352
  </div>
8994
9353
  </div>
8995
9354
  </div>
@@ -9001,11 +9360,14 @@ int main() {
9001
9360
  const slot = this.container ? this.container.querySelector('#cl-modal-slot') : null;
9002
9361
  if (!slot) return;
9003
9362
  const items = this.getDiagnostics();
9004
- const rowsHtml = items.map((d) => `
9005
- <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;">
9006
- <strong>[${escapeHtml(d.severity)}] ${escapeHtml(d.file)}:${d.line}:${d.column}</strong> — ${escapeHtml(d.message)}
9007
- </div>
9008
- `).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('');
9009
9371
  slot.innerHTML = `
9010
9372
  <div class="codelab-modal-backdrop">
9011
9373
  <div class="codelab-modal" role="dialog" aria-modal="true" aria-label="Problems and Diagnostics">
@@ -9021,6 +9383,40 @@ int main() {
9021
9383
  `;
9022
9384
  }
9023
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
+
9024
9420
  _ensureTerminalSessions() {
9025
9421
  if (!Array.isArray(this._terminalSessions) || this._terminalSessions.length === 0) {
9026
9422
  this._terminalSessions = [
@@ -9433,6 +9829,13 @@ int main() {
9433
9829
  this._editorResizeObserver.disconnect();
9434
9830
  this._editorResizeObserver = null;
9435
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
+ }
9436
9839
  if (this.editor) {
9437
9840
  this.editor.dispose();
9438
9841
  this.editor = null;