aicodeman 1.8.0 → 1.8.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 (123) hide show
  1. package/README.md +23 -6
  2. package/README.zh-CN.md +22 -5
  3. package/dist/config/webview-limits.d.ts +36 -0
  4. package/dist/config/webview-limits.d.ts.map +1 -0
  5. package/dist/config/webview-limits.js +40 -0
  6. package/dist/config/webview-limits.js.map +1 -0
  7. package/dist/types/index.d.ts +1 -0
  8. package/dist/types/index.d.ts.map +1 -1
  9. package/dist/types/index.js +1 -0
  10. package/dist/types/index.js.map +1 -1
  11. package/dist/types/webview.d.ts +84 -0
  12. package/dist/types/webview.d.ts.map +1 -0
  13. package/dist/types/webview.js +21 -0
  14. package/dist/types/webview.js.map +1 -0
  15. package/dist/web/middleware/auth.d.ts.map +1 -1
  16. package/dist/web/middleware/auth.js +75 -3
  17. package/dist/web/middleware/auth.js.map +1 -1
  18. package/dist/web/public/admin-ui.js.gz +0 -0
  19. package/dist/web/public/api-client.c9b1cddc.js.gz +0 -0
  20. package/dist/web/public/app.adc992cd.js +38 -0
  21. package/dist/web/public/app.adc992cd.js.br +0 -0
  22. package/dist/web/public/app.adc992cd.js.gz +0 -0
  23. package/dist/web/public/{constants.21a0a83e.js → constants.e7175b95.js} +3 -0
  24. package/dist/web/public/constants.e7175b95.js.br +0 -0
  25. package/dist/web/public/{constants.21a0a83e.js.gz → constants.e7175b95.js.gz} +0 -0
  26. package/dist/web/public/cron-ui.js.gz +0 -0
  27. package/dist/web/public/i18n.4dcf1b87.js.gz +0 -0
  28. package/dist/web/public/image-input.ee16ad88.js.gz +0 -0
  29. package/dist/web/public/index.html +86 -12
  30. package/dist/web/public/index.html.br +0 -0
  31. package/dist/web/public/index.html.gz +0 -0
  32. package/dist/web/public/input-cjk.63794d0b.js.gz +0 -0
  33. package/dist/web/public/keyboard-accessory.3f91acef.js.gz +0 -0
  34. package/dist/web/public/mobile-handlers.bc2b8c1d.js.gz +0 -0
  35. package/dist/web/public/mobile.2ebdbb03.css +1 -0
  36. package/dist/web/public/mobile.2ebdbb03.css.br +0 -0
  37. package/dist/web/public/mobile.2ebdbb03.css.gz +0 -0
  38. package/dist/web/public/notification-manager.fca811fd.js.gz +0 -0
  39. package/dist/web/public/orchestrator-panel.js.gz +0 -0
  40. package/dist/web/public/panels-ui.58582d4c.js.gz +0 -0
  41. package/dist/web/public/ralph-panel.6de2d0f8.js.gz +0 -0
  42. package/dist/web/public/ralph-wizard.13a1831e.js.gz +0 -0
  43. package/dist/web/public/respawn-ui.2d249da9.js.gz +0 -0
  44. package/dist/web/public/sanitize-html.bc7078d6.js.gz +0 -0
  45. package/dist/web/public/{session-ui.713c8836.js → session-ui.fd39c53c.js} +2 -2
  46. package/dist/web/public/session-ui.fd39c53c.js.br +0 -0
  47. package/dist/web/public/session-ui.fd39c53c.js.gz +0 -0
  48. package/dist/web/public/{settings-ui.0259fbe8.js → settings-ui.478c8242.js} +2 -2
  49. package/dist/web/public/settings-ui.478c8242.js.br +0 -0
  50. package/dist/web/public/settings-ui.478c8242.js.gz +0 -0
  51. package/dist/web/public/styles.3f797179.css +1 -0
  52. package/dist/web/public/styles.3f797179.css.br +0 -0
  53. package/dist/web/public/styles.3f797179.css.gz +0 -0
  54. package/dist/web/public/subagent-windows.69b60c35.js.gz +0 -0
  55. package/dist/web/public/sw.js.gz +0 -0
  56. package/dist/web/public/terminal-ui.2d582bf6.js +3 -0
  57. package/dist/web/public/terminal-ui.2d582bf6.js.br +0 -0
  58. package/dist/web/public/terminal-ui.2d582bf6.js.gz +0 -0
  59. package/dist/web/public/ultracode-panel.js.gz +0 -0
  60. package/dist/web/public/ultracode-windows.js.gz +0 -0
  61. package/dist/web/public/upload.html.gz +0 -0
  62. package/dist/web/public/vendor/dompurify.min.js.gz +0 -0
  63. package/dist/web/public/vendor/marked.min.js.gz +0 -0
  64. package/dist/web/public/vendor/xterm-addon-fit.min.js.gz +0 -0
  65. package/dist/web/public/vendor/xterm-addon-serialize.min.js.gz +0 -0
  66. package/dist/web/public/vendor/xterm-addon-unicode11.min.js.gz +0 -0
  67. package/dist/web/public/vendor/xterm-addon-webgl.min.js.gz +0 -0
  68. package/dist/web/public/vendor/xterm-zerolag-input.137ad9f0.js.gz +0 -0
  69. package/dist/web/public/vendor/xterm.css.gz +0 -0
  70. package/dist/web/public/vendor/xterm.min.js.gz +0 -0
  71. package/dist/web/public/voice-input.085e9e73.js.gz +0 -0
  72. package/dist/web/public/webview-tabs.js +445 -0
  73. package/dist/web/public/webview-tabs.js.br +0 -0
  74. package/dist/web/public/webview-tabs.js.gz +0 -0
  75. package/dist/web/routes/index.d.ts +1 -0
  76. package/dist/web/routes/index.d.ts.map +1 -1
  77. package/dist/web/routes/index.js +1 -0
  78. package/dist/web/routes/index.js.map +1 -1
  79. package/dist/web/routes/webview-routes.d.ts +50 -0
  80. package/dist/web/routes/webview-routes.d.ts.map +1 -0
  81. package/dist/web/routes/webview-routes.js +541 -0
  82. package/dist/web/routes/webview-routes.js.map +1 -0
  83. package/dist/web/schemas.d.ts +26 -0
  84. package/dist/web/schemas.d.ts.map +1 -1
  85. package/dist/web/schemas.js +34 -0
  86. package/dist/web/schemas.js.map +1 -1
  87. package/dist/web/server.d.ts.map +1 -1
  88. package/dist/web/server.js +11 -5
  89. package/dist/web/server.js.map +1 -1
  90. package/dist/web/sse-events.d.ts +7 -1
  91. package/dist/web/sse-events.d.ts.map +1 -1
  92. package/dist/web/sse-events.js +8 -1
  93. package/dist/web/sse-events.js.map +1 -1
  94. package/dist/web/webview-proxy.d.ts +181 -0
  95. package/dist/web/webview-proxy.d.ts.map +1 -0
  96. package/dist/web/webview-proxy.js +491 -0
  97. package/dist/web/webview-proxy.js.map +1 -0
  98. package/dist/webview-capabilities.d.ts +55 -0
  99. package/dist/webview-capabilities.d.ts.map +1 -0
  100. package/dist/webview-capabilities.js +102 -0
  101. package/dist/webview-capabilities.js.map +1 -0
  102. package/dist/webview-store.d.ts +16 -0
  103. package/dist/webview-store.d.ts.map +1 -0
  104. package/dist/webview-store.js +34 -0
  105. package/dist/webview-store.js.map +1 -0
  106. package/package.json +11 -2
  107. package/dist/web/public/app.2e95c82d.js +0 -38
  108. package/dist/web/public/app.2e95c82d.js.br +0 -0
  109. package/dist/web/public/app.2e95c82d.js.gz +0 -0
  110. package/dist/web/public/constants.21a0a83e.js.br +0 -0
  111. package/dist/web/public/mobile.f2dcfa13.css +0 -1
  112. package/dist/web/public/mobile.f2dcfa13.css.br +0 -0
  113. package/dist/web/public/mobile.f2dcfa13.css.gz +0 -0
  114. package/dist/web/public/session-ui.713c8836.js.br +0 -0
  115. package/dist/web/public/session-ui.713c8836.js.gz +0 -0
  116. package/dist/web/public/settings-ui.0259fbe8.js.br +0 -0
  117. package/dist/web/public/settings-ui.0259fbe8.js.gz +0 -0
  118. package/dist/web/public/styles.d2f415e2.css +0 -1
  119. package/dist/web/public/styles.d2f415e2.css.br +0 -0
  120. package/dist/web/public/styles.d2f415e2.css.gz +0 -0
  121. package/dist/web/public/terminal-ui.9ea677e9.js +0 -3
  122. package/dist/web/public/terminal-ui.9ea677e9.js.br +0 -0
  123. package/dist/web/public/terminal-ui.9ea677e9.js.gz +0 -0
@@ -10,9 +10,9 @@
10
10
  <span class="case-combobox-check">${m?"\u2713":""}</span>
11
11
  <span class="case-combobox-option-label">${escapeHtml(i.label)}</span>
12
12
  </button>
13
- `}).join(""),t.classList.remove("hidden"),e.setAttribute("aria-activedescendant",`quickStartCaseOption-${this._casePickerActiveIndex}`)},selectQuickStartCase(e,{save:t=!0}={}){const s=document.getElementById("quickStartCase");s&&(s.value=e||"testcase",this.updateCasePickerInput(s.value),this.closeCasePicker(),this.updateDirDisplayForCase(s.value),this.updateMobileCaseLabel(s.value),t&&this.saveLastUsedCase(s.value))},setupQuickStartCasePicker(){const e=document.getElementById("quickStartCase"),t=document.getElementById("quickStartCaseSearch"),s=document.getElementById("quickStartCaseList"),a=document.getElementById("quickStartCasePicker");!e||!t||!s||!a||t.dataset.listenerAdded||(t.addEventListener("focus",()=>{t.select?.(),this.openCasePicker("")}),t.addEventListener("click",()=>{t.select?.(),this.openCasePicker("")}),t.addEventListener("input",()=>{this.openCasePicker(t.value)}),t.addEventListener("keydown",o=>{const n=this.filterCasePickerOptions(this.getCasePickerOptions(),this._casePickerFilter||t.value);if(o.key==="ArrowDown")o.preventDefault(),this._casePickerActiveIndex=Math.min((this._casePickerActiveIndex||0)+1,Math.max(0,n.length-1)),this._casePickerOpen?this.renderCasePickerList():this.openCasePicker(t.value);else if(o.key==="ArrowUp")o.preventDefault(),this._casePickerActiveIndex=Math.max((this._casePickerActiveIndex||0)-1,0),this._casePickerOpen?this.renderCasePickerList():this.openCasePicker(t.value);else if(o.key==="Enter"){const i=n[this._casePickerActiveIndex||0];i&&(o.preventDefault(),this.selectQuickStartCase(i.name),this.run?.())}else o.key==="Escape"?(o.preventDefault(),this.updateCasePickerInput(e.value),this.closeCasePicker()):o.key==="Tab"&&(this.updateCasePickerInput(e.value),this.closeCasePicker())}),s.addEventListener("mousedown",o=>o.preventDefault()),s.addEventListener("click",o=>{const n=o.target.closest?.(".case-combobox-option");n?.dataset?.case&&this.selectQuickStartCase(n.dataset.case)}),document.addEventListener&&!this._casePickerDocumentListenerAdded&&(document.addEventListener("pointerdown",o=>{a.contains(o.target)||(this.updateCasePickerInput(e.value),this.closeCasePicker())}),this._casePickerDocumentListenerAdded=!0),t.dataset.listenerAdded="true")},async loadQuickStartCases(e=null,t=null){try{let s=null;try{const r=t?await t:await fetch("/api/settings").then(c=>c.ok?c.json():null).then(c=>c?.data??null);r&&(s=r.lastUsedCase||null)}catch{}const o=(await(await fetch("/api/cases")).json()).data;this.cases=o,console.log("[loadQuickStartCases] Loaded cases:",o.map(r=>r.name),"lastUsedCase:",s);const n=document.getElementById("quickStartCase"),i=this.getCasePickerOptions();if(this.renderQuickStartCaseSelectOptions(n,i),console.log("[loadQuickStartCases] Set options:",n.innerHTML.substring(0,200)),e)n.value=e,this.updateDirDisplayForCase(e),this.updateMobileCaseLabel(e);else if(s&&o.some(r=>r.name===s))n.value=s,this.updateDirDisplayForCase(s),this.updateMobileCaseLabel(s);else if(o.length>0){const r=o.find(c=>c.name==="testcase")||o[0];n.value=r.name,this.updateDirDisplayForCase(r.name),this.updateMobileCaseLabel(r.name)}else n.value="testcase",document.getElementById("dirDisplay").textContent="~/codeman-cases/testcase",this.updateMobileCaseLabel("testcase");this.updateCasePickerInput(n.value),this.renderCasePickerList(),this.closeCasePicker(),n.dataset.listenerAdded||(n.addEventListener("change",()=>{this.updateDirDisplayForCase(n.value),this.saveLastUsedCase(n.value),this.updateMobileCaseLabel(n.value),this.updateCasePickerInput(n.value)}),n.dataset.listenerAdded="true"),this.setupQuickStartCasePicker()}catch(s){console.error("Failed to load cases:",s)}},async updateDirDisplayForCase(e){try{const s=(await(await fetch(`/api/cases/${e}`)).json()).data;s.path&&(document.getElementById("dirDisplay").textContent=s.path,document.getElementById("dirInput").value=s.path)}catch{document.getElementById("dirDisplay").textContent=e}},async saveLastUsedCase(e){try{await fetch("/api/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({lastUsedCase:e})})}catch(t){console.error("Failed to save last used case:",t)}},async quickStart(){return this.run()},async _ensureCreatedSessionVisible(e,t){if(!e)return;let s=t;if(!s&&!this.sessions?.has(e)){const o=await(await fetch(`/api/sessions/${encodeURIComponent(e)}`)).json();if(!o.success)throw new Error(o.error||"Failed to load the new session");s=o.data?.session||o.data}s?.id&&this._onSessionCreated(s),this._renderSessionTabsImmediate?.()},async run(){if(this._runInFlight)return;const e=Date.now(),t=Number.isFinite(this._runMinLockMs)?this._runMinLockMs:500,s=document.getElementById("runBtn");this._runInFlight=!0,s&&(s.disabled=!0,s.setAttribute("aria-busy","true"));try{const a=this._runMode||"claude";return a==="opencode"?await this.runOpenCode():a==="codex"?await this.runCodex():a==="gemini"?await this.runGemini():await this.runClaude()}finally{const a=t-(Date.now()-e);a>0&&await new Promise(o=>setTimeout(o,a)),this._runInFlight=!1,s&&(s.disabled=!1,s.removeAttribute("aria-busy"))}},setRunMode(e){this._runMode=e;try{localStorage.setItem("codeman_runMode",e)}catch{}this._applyRunMode(),this._apiPut("/api/settings",{runMode:e}).catch(()=>{}),document.getElementById("runModeMenu")?.classList.remove("active")},toggleRunModeMenu(e){e?.stopPropagation();const t=document.getElementById("runModeMenu");if(t&&(t.classList.toggle("active"),t.querySelectorAll(".run-mode-option").forEach(s=>{s.classList.toggle("selected",s.dataset.mode===this.runMode)}),t.classList.contains("active"))){this._loadRunModeHistory();const s=a=>{t.contains(a.target)||(t.classList.remove("active"),document.removeEventListener("click",s))};setTimeout(()=>document.addEventListener("click",s),0)}},async _loadRunModeHistory(){const e=document.getElementById("runModeHistory");if(e){e.innerHTML='<div class="run-mode-hist-empty">Loading...</div>';try{const t=await this._fetchHistorySessions(10);if(t.length===0){e.innerHTML='<div class="run-mode-hist-empty">No history</div>';return}e.replaceChildren();for(const s of t){const a=new Date(s.lastModified),o=a.toLocaleDateString("en",{month:"short",day:"numeric"})+" "+a.toLocaleTimeString("en",{hour:"2-digit",minute:"2-digit",hour12:!1}),n=s.workingDir.replace(/^\/home\/[^/]+\//,"~/"),i=document.createElement("button");i.className="run-mode-option",i.title=s.workingDir,i.dataset.sessionId=s.sessionId,i.dataset.workingDir=s.workingDir;const r=document.createElement("span");r.className="hist-dir",r.textContent=n;const c=document.createElement("span");c.className="hist-meta",c.textContent=o,i.append(r,c),i.addEventListener("click",m=>{m.stopPropagation(),this.resumeHistorySession(s.sessionId,s.workingDir,s.name)}),e.appendChild(i)}}catch{e.innerHTML='<div class="run-mode-hist-empty">Failed to load</div>'}}},_applyRunMode(){const e=this.runMode,t=document.getElementById("runBtn"),s=t?.nextElementSibling,a=document.getElementById("runBtnLabel");t&&(t.className=`btn-toolbar btn-run mode-${e}`),s&&(s.className=`btn-toolbar btn-run-gear mode-${e}`),a&&(a.textContent=e==="opencode"?"Run OC":e==="codex"?"Run CX":e==="gemini"?"Run GM":"Run")},_initRunMode(){try{this._runMode=localStorage.getItem("codeman_runMode")||"claude"}catch{this._runMode="claude"}this._applyRunMode()},incrementTabCount(){const e=document.getElementById("tabCount"),t=parseInt(e.value)||1;e.value=Math.min(20,t+1)},decrementTabCount(){const e=document.getElementById("tabCount"),t=parseInt(e.value)||1;e.value=Math.max(1,t-1)},incrementShellCount(){const e=document.getElementById("shellCount"),t=parseInt(e.value)||1;e.value=Math.min(20,t+1)},decrementShellCount(){const e=document.getElementById("shellCount"),t=parseInt(e.value)||1;e.value=Math.max(1,t-1)},_nextCaseSessionStartNumber(e,t="w"){const s=new RegExp(`^${t}(\\d+)-([a-zA-Z0-9_-]+)`);let a=1;for(const[,o]of this.sessions||[]){const n=o.name&&o.name.match(s);if(n&&n[2]===e){const i=parseInt(n[1]);i>=a&&(a=i+1)}}return a},async runClaude(){const e=document.getElementById("quickStartCase").value||"testcase",t=Math.min(20,Math.max(1,parseInt(document.getElementById("tabCount").value)||1));this.terminal.clear(),this.terminal.writeln(`\x1B[1;32m Starting ${t} Claude session(s) in ${e}...\x1B[0m`),this.terminal.writeln(""),this.terminal.focus();try{let a=(await(await fetch(`/api/cases/${e}`)).json())?.data??{};if(!a.path){const C=await(await fetch("/api/cases",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:e,description:""})})).json();if(!C.success)throw new Error(C.error||"Failed to create case");a=C.data.case}const o=a.path;if(!o)throw new Error("Case path not found");if(a.location==="remote"||a.location==="docker"){const f=this._nextCaseSessionStartNumber(e);let C;if(a.location==="docker"){const w=this.loadAppSettingsFromStorage(),S=this.getCaseSettings(e).opusContext1m||w.opusContext1mEnabled;C=w.claudeModel||(S?"opus[1m]":"")}const E=[];let I=!1;for(let w=0;w<t;w++){const x=JSON.stringify({caseName:e,mode:"claude",sessionName:`w${f+w}-${e}`,...C!==void 0?{modelOverride:C}:{}}),S=async()=>(await fetch("/api/quick-start",{method:"POST",headers:{"Content-Type":"application/json"},body:x})).json();let b=await S();if(!b.success&&b.errorCode==="CONFLICT"&&a.location==="docker"&&!I&&(I=!0,confirm(`Container config for "${e}" changed since its container was created.
13
+ `}).join(""),t.classList.remove("hidden"),e.setAttribute("aria-activedescendant",`quickStartCaseOption-${this._casePickerActiveIndex}`)},selectQuickStartCase(e,{save:t=!0}={}){const s=document.getElementById("quickStartCase");s&&(s.value=e||"testcase",this.updateCasePickerInput(s.value),this.closeCasePicker(),this.updateDirDisplayForCase(s.value),this.updateMobileCaseLabel(s.value),t&&this.saveLastUsedCase(s.value))},setupQuickStartCasePicker(){const e=document.getElementById("quickStartCase"),t=document.getElementById("quickStartCaseSearch"),s=document.getElementById("quickStartCaseList"),a=document.getElementById("quickStartCasePicker");!e||!t||!s||!a||t.dataset.listenerAdded||(t.addEventListener("focus",()=>{t.select?.(),this.openCasePicker("")}),t.addEventListener("click",()=>{t.select?.(),this.openCasePicker("")}),t.addEventListener("input",()=>{this.openCasePicker(t.value)}),t.addEventListener("keydown",o=>{const n=this.filterCasePickerOptions(this.getCasePickerOptions(),this._casePickerFilter||t.value);if(o.key==="ArrowDown")o.preventDefault(),this._casePickerActiveIndex=Math.min((this._casePickerActiveIndex||0)+1,Math.max(0,n.length-1)),this._casePickerOpen?this.renderCasePickerList():this.openCasePicker(t.value);else if(o.key==="ArrowUp")o.preventDefault(),this._casePickerActiveIndex=Math.max((this._casePickerActiveIndex||0)-1,0),this._casePickerOpen?this.renderCasePickerList():this.openCasePicker(t.value);else if(o.key==="Enter"){const i=n[this._casePickerActiveIndex||0];i&&(o.preventDefault(),this.selectQuickStartCase(i.name),this.run?.())}else o.key==="Escape"?(o.preventDefault(),this.updateCasePickerInput(e.value),this.closeCasePicker()):o.key==="Tab"&&(this.updateCasePickerInput(e.value),this.closeCasePicker())}),s.addEventListener("mousedown",o=>o.preventDefault()),s.addEventListener("click",o=>{const n=o.target.closest?.(".case-combobox-option");n?.dataset?.case&&this.selectQuickStartCase(n.dataset.case)}),document.addEventListener&&!this._casePickerDocumentListenerAdded&&(document.addEventListener("pointerdown",o=>{a.contains(o.target)||(this.updateCasePickerInput(e.value),this.closeCasePicker())}),this._casePickerDocumentListenerAdded=!0),t.dataset.listenerAdded="true")},async loadQuickStartCases(e=null,t=null){try{let s=null;try{const r=t?await t:await fetch("/api/settings").then(c=>c.ok?c.json():null).then(c=>c?.data??null);r&&(s=r.lastUsedCase||null)}catch{}const o=(await(await fetch("/api/cases")).json()).data;this.cases=o,console.log("[loadQuickStartCases] Loaded cases:",o.map(r=>r.name),"lastUsedCase:",s);const n=document.getElementById("quickStartCase"),i=this.getCasePickerOptions();if(this.renderQuickStartCaseSelectOptions(n,i),console.log("[loadQuickStartCases] Set options:",n.innerHTML.substring(0,200)),e)n.value=e,this.updateDirDisplayForCase(e),this.updateMobileCaseLabel(e);else if(s&&o.some(r=>r.name===s))n.value=s,this.updateDirDisplayForCase(s),this.updateMobileCaseLabel(s);else if(o.length>0){const r=o.find(c=>c.name==="testcase")||o[0];n.value=r.name,this.updateDirDisplayForCase(r.name),this.updateMobileCaseLabel(r.name)}else n.value="testcase",document.getElementById("dirDisplay").textContent="~/codeman-cases/testcase",this.updateMobileCaseLabel("testcase");this.updateCasePickerInput(n.value),this.renderCasePickerList(),this.closeCasePicker(),n.dataset.listenerAdded||(n.addEventListener("change",()=>{this.updateDirDisplayForCase(n.value),this.saveLastUsedCase(n.value),this.updateMobileCaseLabel(n.value),this.updateCasePickerInput(n.value)}),n.dataset.listenerAdded="true"),this.setupQuickStartCasePicker()}catch(s){console.error("Failed to load cases:",s)}},async updateDirDisplayForCase(e){try{const s=(await(await fetch(`/api/cases/${e}`)).json()).data;s.path&&(document.getElementById("dirDisplay").textContent=s.path,document.getElementById("dirInput").value=s.path)}catch{document.getElementById("dirDisplay").textContent=e}},async saveLastUsedCase(e){try{await fetch("/api/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({lastUsedCase:e})})}catch(t){console.error("Failed to save last used case:",t)}},async quickStart(){return this.run()},async _ensureCreatedSessionVisible(e,t){if(!e)return;let s=t;if(!s&&!this.sessions?.has(e)){const o=await(await fetch(`/api/sessions/${encodeURIComponent(e)}`)).json();if(!o.success)throw new Error(o.error||"Failed to load the new session");s=o.data?.session||o.data}s?.id&&this._onSessionCreated(s),this._renderSessionTabsImmediate?.()},async run(){if(this._runInFlight)return;const e=Date.now(),t=Number.isFinite(this._runMinLockMs)?this._runMinLockMs:500,s=document.getElementById("runBtn");this._runInFlight=!0,s&&(s.disabled=!0,s.setAttribute("aria-busy","true"));try{const a=this._runMode||"claude";return a==="opencode"?await this.runOpenCode():a==="codex"?await this.runCodex():a==="gemini"?await this.runGemini():a==="shell"?await this.runShell():await this.runClaude()}finally{const a=t-(Date.now()-e);a>0&&await new Promise(o=>setTimeout(o,a)),this._runInFlight=!1,s&&(s.disabled=!1,s.removeAttribute("aria-busy"))}},setRunMode(e){this._runMode=e;try{localStorage.setItem("codeman_runMode",e)}catch{}this._applyRunMode(),this._apiPut("/api/settings",{runMode:e}).catch(()=>{}),document.getElementById("runModeMenu")?.classList.remove("active")},toggleRunModeMenu(e){e?.stopPropagation();const t=document.getElementById("runModeMenu");if(t&&(t.classList.toggle("active"),t.querySelectorAll(".run-mode-option").forEach(s=>{s.classList.toggle("selected",s.dataset.mode===this.runMode)}),t.classList.contains("active"))){this._loadRunModeHistory();const s=a=>{t.contains(a.target)||(t.classList.remove("active"),document.removeEventListener("click",s))};setTimeout(()=>document.addEventListener("click",s),0)}},async _loadRunModeHistory(){const e=document.getElementById("runModeHistory");if(e){e.innerHTML='<div class="run-mode-hist-empty">Loading...</div>';try{const t=await this._fetchHistorySessions(10);if(t.length===0){e.innerHTML='<div class="run-mode-hist-empty">No history</div>';return}e.replaceChildren();for(const s of t){const a=new Date(s.lastModified),o=a.toLocaleDateString("en",{month:"short",day:"numeric"})+" "+a.toLocaleTimeString("en",{hour:"2-digit",minute:"2-digit",hour12:!1}),n=s.workingDir.replace(/^\/home\/[^/]+\//,"~/"),i=document.createElement("button");i.className="run-mode-option",i.title=s.workingDir,i.dataset.sessionId=s.sessionId,i.dataset.workingDir=s.workingDir;const r=document.createElement("span");r.className="hist-dir",r.textContent=n;const c=document.createElement("span");c.className="hist-meta",c.textContent=o,i.append(r,c),i.addEventListener("click",m=>{m.stopPropagation(),this.resumeHistorySession(s.sessionId,s.workingDir,s.name)}),e.appendChild(i)}}catch{e.innerHTML='<div class="run-mode-hist-empty">Failed to load</div>'}}},_applyRunMode(){const e=this.runMode,t=document.getElementById("runBtn"),s=t?.nextElementSibling,a=document.getElementById("runBtnLabel");t&&(t.className=`btn-toolbar btn-run mode-${e}`),s&&(s.className=`btn-toolbar btn-run-gear mode-${e}`),a&&(a.textContent=e==="opencode"?"Run OC":e==="codex"?"Run CX":e==="gemini"?"Run GM":e==="shell"?"Run SH":"Run")},sendEnterKey(){if(!this.activeSessionId)return;const e=this.terminal?._core?.coreService;if(e&&typeof e.triggerDataEvent=="function"){e.triggerDataEvent("\r",!0);return}this.sendInput("\r")},_initRunMode(){try{this._runMode=localStorage.getItem("codeman_runMode")||"claude"}catch{this._runMode="claude"}this._applyRunMode()},incrementTabCount(){const e=document.getElementById("tabCount"),t=parseInt(e.value)||1;e.value=Math.min(20,t+1)},decrementTabCount(){const e=document.getElementById("tabCount"),t=parseInt(e.value)||1;e.value=Math.max(1,t-1)},incrementShellCount(){const e=document.getElementById("shellCount"),t=parseInt(e.value)||1;e.value=Math.min(20,t+1)},decrementShellCount(){const e=document.getElementById("shellCount"),t=parseInt(e.value)||1;e.value=Math.max(1,t-1)},_nextCaseSessionStartNumber(e,t="w"){const s=new RegExp(`^${t}(\\d+)-([a-zA-Z0-9_-]+)`);let a=1;for(const[,o]of this.sessions||[]){const n=o.name&&o.name.match(s);if(n&&n[2]===e){const i=parseInt(n[1]);i>=a&&(a=i+1)}}return a},async runClaude(){const e=document.getElementById("quickStartCase").value||"testcase",t=Math.min(20,Math.max(1,parseInt(document.getElementById("tabCount").value)||1));this.terminal.clear(),this.terminal.writeln(`\x1B[1;32m Starting ${t} Claude session(s) in ${e}...\x1B[0m`),this.terminal.writeln(""),this.terminal.focus();try{let a=(await(await fetch(`/api/cases/${e}`)).json())?.data??{};if(!a.path){const C=await(await fetch("/api/cases",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:e,description:""})})).json();if(!C.success)throw new Error(C.error||"Failed to create case");a=C.data.case}const o=a.path;if(!o)throw new Error("Case path not found");if(a.location==="remote"||a.location==="docker"){const f=this._nextCaseSessionStartNumber(e);let C;if(a.location==="docker"){const k=this.loadAppSettingsFromStorage(),S=this.getCaseSettings(e).opusContext1m||k.opusContext1mEnabled;C=k.claudeModel||(S?"opus[1m]":"")}const E=[];let I=!1;for(let k=0;k<t;k++){const x=JSON.stringify({caseName:e,mode:"claude",sessionName:`w${f+k}-${e}`,...C!==void 0?{modelOverride:C}:{}}),S=async()=>(await fetch("/api/quick-start",{method:"POST",headers:{"Content-Type":"application/json"},body:x})).json();let b=await S();if(!b.success&&b.errorCode==="CONFLICT"&&a.location==="docker"&&!I&&(I=!0,confirm(`Container config for "${e}" changed since its container was created.
14
14
 
15
- Recreate the container to apply the new config? Workspace files and the conversation survive (the conversation resumes on launch).`))){const T=await(await fetch(`/api/docker-cases/${encodeURIComponent(e)}/recreate`,{method:"POST"})).json();if(!T.success)throw new Error(T.error||"Failed to recreate container");b=await S()}if(!b.success)throw new Error(b.error||"Failed to start remote Claude session");await this._ensureCreatedSessionVisible(b.data.sessionId,b.data.session),E.push(b.data.sessionId)}this.terminal.writeln(`\x1B[90m All ${t} remote session(s) ready\x1B[0m`),E[0]&&(await this.selectSession(E[0]),this.loadQuickStartCases()),this.terminal.focus();return}let n=null;const i=this._nextCaseSessionStartNumber(e),r=this.isRalphTrackerEnabledByDefault(),c=[];for(let f=0;f<t;f++)c.push(`w${i+f}-${e}`);const m=this.getCaseSettings(e),l=this.loadAppSettingsFromStorage(),u=this.buildEnvOverrides(m,l),p=Object.keys(u).length>0,d=this.getEffortSetting(l),h=m.opusContext1m||l.opusContext1mEnabled,y=l.claudeModel||(h?"opus[1m]":"");this.terminal.writeln(`\x1B[90m Creating ${t} session(s)...\x1B[0m`);const g=c.map(f=>fetch("/api/sessions",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({workingDir:o,name:f,...p?{envOverrides:u}:{},...d?{effort:d}:{},...y!==void 0?{modelOverride:y}:{},statusLineTelemetry:l.showPlanUsageLimits===!0})}).then(C=>C.json())),k=await Promise.all(g),v=[];for(const f of k){if(!f.success)throw new Error(f.error);await this._ensureCreatedSessionVisible(f.data.session.id,f.data.session),v.push(f.data.session.id)}n=v[0],await Promise.all(v.map(f=>fetch(`/api/sessions/${f}/ralph-config`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({enabled:r,disableAutoEnable:!r})}))),this.terminal.writeln(`\x1B[90m Starting ${t} session(s) in parallel...\x1B[0m`),await Promise.all(v.map(f=>fetch(`/api/sessions/${f}/interactive`,{method:"POST"}))),this.terminal.writeln(`\x1B[90m All ${t} sessions ready\x1B[0m`),n&&(await this.selectSession(n),this.loadQuickStartCases()),this.terminal.focus()}catch(s){this.terminal.writeln(`\x1B[1;31m Error: ${s.message}\x1B[0m`)}},stopClaude(){if(!this.activeSessionId)return;const e=document.querySelector(".btn-toolbar.btn-stop");e&&(this._stopConfirmTimer?(clearTimeout(this._stopConfirmTimer),this._stopConfirmTimer=null,e.innerHTML=e.dataset.origHtml,delete e.dataset.origHtml,e.classList.remove("confirming"),fetch(`/api/sessions/${this.activeSessionId}/input`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({input:""})})):(e.dataset.origHtml=e.innerHTML,e.textContent="Tap again",e.classList.add("confirming"),this._stopConfirmTimer=setTimeout(()=>{this._stopConfirmTimer=null,e.dataset.origHtml&&(e.innerHTML=e.dataset.origHtml,delete e.dataset.origHtml),e.classList.remove("confirming")},2e3)))},async runShell(){const e=document.getElementById("quickStartCase").value||"testcase",t=Math.min(20,Math.max(1,parseInt(document.getElementById("shellCount").value)||1));this.terminal.clear(),this.terminal.writeln(`\x1B[1;33m Starting ${t} Shell session(s) in ${e}...\x1B[0m`),this.terminal.writeln("");try{let a=(await(await fetch(`/api/cases/${e}`)).json())?.data??{};if(!a.path){const h=await(await fetch("/api/cases",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:e,description:""})})).json();if(!h.success)throw new Error(h.error||"Failed to create case");a=h.data.case}const o=(this.cases||[]).find(d=>d.name===e),n=a.location==="remote"||a.location==="docker"||o?.location==="remote"||o?.location==="docker",i=a.path;if(!i)throw new Error("Case path not found");if(a.location==="remote"||a.location==="docker"){const d=this._nextCaseSessionStartNumber(e,"s"),h=[];for(let y=0;y<t;y++){const k=await(await fetch("/api/quick-start",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({caseName:e,mode:"shell",sessionName:`s${d+y}-${e}`})})).json();if(!k.success)throw new Error(k.error||"Failed to start remote shell session");await this._ensureCreatedSessionVisible(k.data.sessionId,k.data.session),h.push(k.data.sessionId)}h[0]&&await this.selectSession(h[0]),this.terminal.focus();return}const r=this._nextCaseSessionStartNumber(e,"s"),c=[];for(let d=0;d<t;d++)c.push(`s${r+d}-${e}`);const m=c.map(d=>fetch("/api/sessions",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...n?{caseName:e}:{workingDir:i},mode:"shell",name:d})}).then(h=>h.json())),l=await Promise.all(m),u=[];for(const d of l){if(!d.success)throw new Error(d.error);await this._ensureCreatedSessionVisible(d.data.session.id,d.data.session),u.push(d.data.session.id)}await Promise.all(u.map(d=>fetch(`/api/sessions/${d}/shell`,{method:"POST"})));const p=this.getTerminalDimensions();p&&await Promise.all(u.map(d=>fetch(`/api/sessions/${d}/resize`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(p)}))),u.length>0&&await this.selectSession(u[0]),this.terminal.focus()}catch(s){this.terminal.writeln(`\x1B[1;31m Error: ${s.message}\x1B[0m`)}},async runOpenCode(){const e=document.getElementById("quickStartCase").value||"testcase",t=(this.cases||[]).find(a=>a.name===e)?.location,s=t==="remote"||t==="docker";this.terminal.clear(),this.terminal.writeln(`\x1B[1;32m Starting OpenCode session in ${e}...\x1B[0m`),this.terminal.writeln(""),this.terminal.focus();try{if(!s&&!(await(await fetch("/api/opencode/status")).json()).data.available){this.terminal.writeln("\x1B[1;31m OpenCode CLI not found.\x1B[0m"),this.terminal.writeln("\x1B[90m Install with: curl -fsSL https://opencode.ai/install | bash\x1B[0m");return}const a=this.buildEnvOverrides(this.getCaseSettings(e),this.loadAppSettingsFromStorage()),n=await(await fetch("/api/quick-start",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({caseName:e,mode:"opencode",sessionName:`w${this._nextCaseSessionStartNumber(e)}-${e}`,...s?{}:{openCodeConfig:{autoAllowTools:!0},...Object.keys(a).length>0?{envOverrides:a}:{}}})})).json();if(!n.success)throw new Error(n.error||"Failed to start OpenCode");await this._ensureCreatedSessionVisible(n.data.sessionId,n.data.session),n.data.sessionId&&await this.selectSession(n.data.sessionId),this.terminal.focus()}catch(a){this.terminal.writeln(`\x1B[1;31m Error: ${a.message}\x1B[0m`)}},async runCodex(){const e=document.getElementById("quickStartCase").value||"testcase",t=(this.cases||[]).find(a=>a.name===e)?.location,s=t==="remote"||t==="docker";this.terminal.clear(),this.terminal.writeln(`\x1B[1;32m Starting Codex session in ${e}...\x1B[0m`),this.terminal.writeln(""),this.terminal.focus();try{if(!s&&!(await(await fetch("/api/codex/status")).json()).data.available){this.terminal.writeln("\x1B[1;31m Codex CLI not found.\x1B[0m"),this.terminal.writeln("\x1B[90m Install with: npm install -g @openai/codex\x1B[0m");return}const a=this.loadAppSettingsFromStorage(),o=this.buildEnvOverrides(this.getCaseSettings(e),a),i=await(await fetch("/api/quick-start",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({caseName:e,mode:"codex",sessionName:`w${this._nextCaseSessionStartNumber(e)}-${e}`,...s?{}:{codexConfig:{dangerouslyBypassApprovals:a.codexDangerouslyBypassApprovals??!1,renderMode:"hybrid"},...Object.keys(o).length>0?{envOverrides:o}:{}}})})).json();if(!i.success)throw new Error(i.error||"Failed to start Codex");await this._ensureCreatedSessionVisible(i.data.sessionId,i.data.session),i.data.sessionId&&await this.selectSession(i.data.sessionId),this.terminal.focus()}catch(a){this.terminal.writeln(`\x1B[1;31m Error: ${a.message}\x1B[0m`)}},async runGemini(){const e=document.getElementById("quickStartCase").value||"testcase",t=(this.cases||[]).find(a=>a.name===e)?.location,s=t==="remote"||t==="docker";this.terminal.clear(),this.terminal.writeln(`\x1B[1;32m Starting Gemini session in ${e}...\x1B[0m`),this.terminal.writeln(""),this.terminal.focus();try{if(!s&&!(await(await fetch("/api/gemini/status")).json()).data.available){this.terminal.writeln("\x1B[1;31m Gemini CLI not found.\x1B[0m"),this.terminal.writeln("\x1B[90m Install with: npm install -g @google/gemini-cli\x1B[0m");return}const a=this.buildEnvOverrides(this.getCaseSettings(e),this.loadAppSettingsFromStorage()),n=await(await fetch("/api/quick-start",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({caseName:e,mode:"gemini",sessionName:`w${this._nextCaseSessionStartNumber(e)}-${e}`,...s?{}:{geminiConfig:{approvalMode:"yolo"},...Object.keys(a).length>0?{envOverrides:a}:{}}})})).json();if(!n.success)throw new Error(n.error||"Failed to start Gemini");await this._ensureCreatedSessionVisible(n.data.sessionId,n.data.session),n.data.sessionId&&await this.selectSession(n.data.sessionId),this.terminal.focus()}catch(a){this.terminal.writeln(`\x1B[1;31m Error: ${a.message}\x1B[0m`)}},openSessionOptions(e){const t=this.sessions.get(e);if(!t)return;this.editingSessionId=e;const s=t.mode==="opencode"||t.mode==="codex"||t.mode==="gemini";this.switchOptionsTab(s?"summary":"respawn");const a=document.getElementById("sessionRespawnStatus"),o=document.getElementById("modalEnableRespawnBtn"),n=document.getElementById("modalStopRespawnBtn");this.respawnStatus[e]?(a.classList.add("active"),a.querySelector(".respawn-status-text").textContent=this.respawnStatus[e].state||"Active",o.style.display="none",n.style.display=""):(a.classList.remove("active"),a.querySelector(".respawn-status-text").textContent="Not active",o.style.display="",n.style.display="none");const i=document.getElementById("sessionRespawnSection");t.mode==="claude"&&t.pid?i.style.display="":i.style.display="none";const r=t.mode==="opencode"||t.mode==="codex"||t.mode==="gemini";document.querySelectorAll("[data-claude-only]").forEach(g=>{g.style.display=r?"none":""}),this.selectDurationPreset(""),this.loadSavedRespawnConfig(e),document.getElementById("modalAutoCompactEnabled").checked=t.autoCompactEnabled??!1,document.getElementById("modalAutoCompactThreshold").value=t.autoCompactThreshold??11e4,document.getElementById("modalAutoCompactPrompt").value=t.autoCompactPrompt??"",document.getElementById("modalAutoClearEnabled").checked=t.autoClearEnabled??!1,document.getElementById("modalAutoClearThreshold").value=t.autoClearThreshold??14e4,document.getElementById("modalAutoResumeEnabled").checked=t.autoResumeEnabled??!1,this.updateAutoResumeStatus(e),document.getElementById("modalImageWatcherEnabled").checked=t.imageWatcherEnabled??!0,document.getElementById("modalFlickerFilterEnabled").checked=t.flickerFilterEnabled??!1;const m=parseSessionPrefix(t.name),l=document.getElementById("modalSessionPrefix");m?(l.textContent=m.prefix+": ",l.style.display="",document.getElementById("modalSessionName").value=m.suffix,document.getElementById("modalSessionName").placeholder="Add description..."):(l.style.display="none",l.textContent="",document.getElementById("modalSessionName").value=t.name||"",document.getElementById("modalSessionName").placeholder="Auto (directory name)");const u=t.color||"default";document.getElementById("sessionColorPicker")?.querySelectorAll(".color-swatch").forEach(g=>{g.classList.toggle("selected",g.dataset.color===u)}),this.renderPresetDropdown(),document.getElementById("respawnPresetSelect").value="",document.getElementById("presetDescriptionHint").textContent="";const d=document.querySelector('#sessionOptionsModal .modal-tab-btn[data-tab="ralph"]'),h=document.querySelector('#sessionOptionsModal .modal-tab-btn[data-tab="respawn"]');if(r?(d&&(d.style.display="none"),h&&(h.style.display="none"),this.switchOptionsTab("context")):(d&&(d.style.display=""),h&&(h.style.display="")),!r){const g=this.ralphStates.get(e);this.populateRalphForm({enabled:g?.loop?.enabled??t.ralphLoop?.enabled??!1,completionPhrase:g?.loop?.completionPhrase||t.ralphLoop?.completionPhrase||"",maxIterations:g?.loop?.maxIterations||t.ralphLoop?.maxIterations||0,maxTodos:g?.loop?.maxTodos||t.ralphLoop?.maxTodos,todoExpirationMinutes:g?.loop?.todoExpirationMinutes||t.ralphLoop?.todoExpirationMinutes})}const y=document.getElementById("sessionOptionsModal");y.classList.add("active"),this.activeFocusTrap=new FocusTrap(y),this.activeFocusTrap.activate()},async saveSessionName(){if(!this.editingSessionId)return;const e=this.sessions.get(this.editingSessionId),t=e?parseSessionPrefix(e.name):null,s=document.getElementById("modalSessionName").value.trim();let a;t?a=t.prefix+(s?": "+s:""):a=s;try{await this._apiPut(`/api/sessions/${this.editingSessionId}/name`,{name:a})}catch(o){this.showToast("Failed to save session name: "+o.message,"error")}},async autoSaveAutoCompact(){if(this.editingSessionId)try{await this._apiPost(`/api/sessions/${this.editingSessionId}/auto-compact`,{enabled:document.getElementById("modalAutoCompactEnabled").checked,threshold:parseInt(document.getElementById("modalAutoCompactThreshold").value)||11e4,prompt:document.getElementById("modalAutoCompactPrompt").value.trim()||void 0})}catch{}},async autoSaveAutoClear(){if(this.editingSessionId)try{await this._apiPost(`/api/sessions/${this.editingSessionId}/auto-clear`,{enabled:document.getElementById("modalAutoClearEnabled").checked,threshold:parseInt(document.getElementById("modalAutoClearThreshold").value)||14e4})}catch{}},async autoSaveAutoResume(){if(!this.editingSessionId)return;const e=document.getElementById("modalAutoResumeEnabled").checked;try{await this._apiPost(`/api/sessions/${this.editingSessionId}/auto-resume`,{enabled:e});const t=this.sessions.get(this.editingSessionId);t&&(t.autoResumeEnabled=e,e||(t.autoResumeAt=void 0)),this.updateAutoResumeStatus(this.editingSessionId),this.showToast(`Auto-resume on usage limit ${e?"enabled":"disabled"}`,"success")}catch(t){this.showToast("Failed to toggle auto-resume: "+t.message,"error")}},updateAutoResumeStatus(e){const t=document.getElementById("autoResumeStatus");if(!t||this.editingSessionId!==e)return;const s=this.sessions.get(e);if(s?.autoResumeAt&&s.autoResumeAt>Date.now()){const a=new Date(s.autoResumeAt).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});t.textContent=`Usage limit pause active \u2014 resumes at ${a}`,t.classList.add("active")}else t.textContent="",t.classList.remove("active")},async toggleSessionImageWatcher(){if(!this.editingSessionId)return;const e=document.getElementById("modalImageWatcherEnabled").checked;try{await this._apiPost(`/api/sessions/${this.editingSessionId}/image-watcher`,{enabled:e});const t=this.sessions.get(this.editingSessionId);t&&(t.imageWatcherEnabled=e),this.showToast(`Image watcher ${e?"enabled":"disabled"}`,"success")}catch{this.showToast("Failed to toggle image watcher","error")}},async toggleFlickerFilter(){if(!this.editingSessionId)return;const e=document.getElementById("modalFlickerFilterEnabled").checked;try{await this._apiPost(`/api/sessions/${this.editingSessionId}/flicker-filter`,{enabled:e});const t=this.sessions.get(this.editingSessionId);t&&(t.flickerFilterEnabled=e),this.showToast(`Flicker filter ${e?"enabled":"disabled"}`,"success")}catch{this.showToast("Failed to toggle flicker filter","error")}},async autoSaveRespawnConfig(){if(!this.editingSessionId)return;const e={updatePrompt:document.getElementById("modalRespawnPrompt").value,sendClear:document.getElementById("modalRespawnSendClear").checked,sendInit:document.getElementById("modalRespawnSendInit").checked,kickstartPrompt:document.getElementById("modalRespawnKickstart").value.trim()||void 0,autoAcceptPrompts:document.getElementById("modalRespawnAutoAccept").checked};try{await this._apiPut(`/api/sessions/${this.editingSessionId}/respawn/config`,e)}catch{}},async loadSavedRespawnConfig(e){try{const s=await(await fetch(`/api/sessions/${e}/respawn/config`)).json();if(s.success&&s.data&&s.data.config){const a=s.data.config;document.getElementById("modalRespawnPrompt").value=a.updatePrompt||"update all the docs and CLAUDE.md",document.getElementById("modalRespawnSendClear").checked=a.sendClear??!0,document.getElementById("modalRespawnSendInit").checked=a.sendInit??!0,document.getElementById("modalRespawnKickstart").value=a.kickstartPrompt||"",document.getElementById("modalRespawnAutoAccept").checked=a.autoAcceptPrompts??!0,a.durationMinutes&&(document.querySelector(`.duration-preset-btn[data-minutes="${a.durationMinutes}"]`)?this.selectDurationPreset(String(a.durationMinutes)):(this.selectDurationPreset("custom"),document.getElementById("modalRespawnDuration").value=a.durationMinutes))}}catch{}},selectDurationPreset(e){document.querySelectorAll(".duration-preset-btn").forEach(o=>o.classList.remove("active"));const t=document.querySelector(`.duration-preset-btn[data-minutes="${e}"]`);t&&t.classList.add("active");const s=document.querySelector(".duration-custom-input"),a=document.getElementById("modalRespawnDuration");e==="custom"?(s.classList.add("visible"),a.focus()):(s.classList.remove("visible"),a.value="")},getSelectedDuration(){const e=document.querySelector(".duration-custom-input"),t=document.getElementById("modalRespawnDuration");if(e.classList.contains("visible"))return t.value?parseInt(t.value):null;{const a=document.querySelector(".duration-preset-btn.active")?.dataset.minutes;return a?parseInt(a):null}},switchOptionsTab(e){document.querySelectorAll("#sessionOptionsModal .modal-tab-btn").forEach(t=>{t.classList.toggle("active",t.dataset.tab===e)}),document.getElementById("respawn-tab").classList.toggle("hidden",e!=="respawn"),document.getElementById("context-tab").classList.toggle("hidden",e!=="context"),document.getElementById("ralph-tab").classList.toggle("hidden",e!=="ralph"),document.getElementById("summary-tab").classList.toggle("hidden",e!=="summary"),e==="summary"&&this.editingSessionId&&this.loadRunSummary(this.editingSessionId)},getRalphConfig(){return{enabled:document.getElementById("modalRalphEnabled").checked,completionPhrase:document.getElementById("modalRalphPhrase").value.trim(),maxIterations:parseInt(document.getElementById("modalRalphMaxIterations").value)||0,maxTodos:parseInt(document.getElementById("modalRalphMaxTodos").value)||50,todoExpirationMinutes:parseInt(document.getElementById("modalRalphTodoExpiration").value)||60}},populateRalphForm(e){document.getElementById("modalRalphEnabled").checked=e?.enabled??!1,document.getElementById("modalRalphPhrase").value=e?.completionPhrase||"",document.getElementById("modalRalphMaxIterations").value=e?.maxIterations||0,document.getElementById("modalRalphMaxTodos").value=e?.maxTodos||50,document.getElementById("modalRalphTodoExpiration").value=e?.todoExpirationMinutes||60},async saveRalphConfig(){if(!this.editingSessionId){this.showToast("No session selected","warning");return}const e=this.getRalphConfig();e.enabled&&this.ralphClosedSessions.delete(this.editingSessionId);try{const s=await(await fetch(`/api/sessions/${this.editingSessionId}/ralph-config`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})).json();if(s.error)throw new Error(s.error);this.showToast("Ralph config saved","success")}catch(t){this.showToast("Failed to save Ralph config: "+t.message,"error")}},startInlineRename(e){const t=this.sessions.get(e);if(!t)return;const s=document.querySelector(`.tab-name[data-session-id="${e}"]`);if(!s)return;this._inlineRenameActive=!0;const a=this.getSessionName(t),o=parseSessionPrefix(t.name),n=s.textContent;for(s.textContent="";s.firstChild;)s.removeChild(s.firstChild);if(o){const c=document.createElement("span");c.textContent=o.prefix+": ",c.style.cssText="color: var(--text-muted); font-size: 0.75rem; white-space: nowrap;",s.appendChild(c)}const i=document.createElement("input");i.type="text",i.value=o?o.suffix:t.name||"",i.placeholder=o?"Add description...":a,i.className="tab-rename-input",i.style.cssText="width: 80px; font-size: 0.75rem; padding: 2px 4px; background: var(--bg-input); border: 1px solid var(--accent); border-radius: 3px; color: var(--text); outline: none;",s.appendChild(i),i.focus(),i.select();const r=async({commit:c})=>{if(!this._inlineRenameActive)return;if(this._inlineRenameActive=!1,this._activeRename=null,!c){this.renderSessionTabs();return}const m=i.value.trim(),l=o?o.prefix+(m?": "+m:""):m;if(s.textContent=l||n,this.sessions.has(e)&&l!==t.name)try{await fetch(`/api/sessions/${e}/name`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:l})})}catch{s.textContent=n,this.showToast("Failed to rename","error")}this.renderSessionTabs()};this._activeRename={sessionId:e,cancel:()=>r({commit:!1})},i.addEventListener("blur",()=>r({commit:!0})),i.addEventListener("keydown",c=>{c.isComposing||c.keyCode===229||(c.key==="Enter"?(c.preventDefault(),i.blur()):c.key==="Escape"&&(i.value="",i.blur()))})},toggleCaseSettings(){const e=document.getElementById("caseSettingsPopover");if(e.classList.contains("hidden")){const t=document.getElementById("quickStartCase").value||"testcase",s=this.getCaseSettings(t);document.getElementById("caseAgentTeams").checked=s.agentTeams,document.getElementById("caseOpusContext1m").checked=s.opusContext1m,e.classList.remove("hidden");const a=o=>{!e.contains(o.target)&&!o.target.classList.contains("btn-case-settings")&&(e.classList.add("hidden"),document.removeEventListener("click",a))};setTimeout(()=>document.addEventListener("click",a),0)}else e.classList.add("hidden")},getCaseSettings(e){try{const t=localStorage.getItem("caseSettings_"+e);if(t)return JSON.parse(t)}catch{}return{agentTeams:!1,opusContext1m:!0}},saveCaseSettings(e,t){localStorage.setItem("caseSettings_"+e,JSON.stringify(t))},onCaseSettingChanged(){const e=document.getElementById("quickStartCase").value||"testcase",t=this.getCaseSettings(e);t.agentTeams=document.getElementById("caseAgentTeams").checked,t.opusContext1m=document.getElementById("caseOpusContext1m").checked,this.saveCaseSettings(e,t);const s=document.getElementById("caseAgentTeamsMobile");s&&(s.checked=t.agentTeams);const a=document.getElementById("caseOpusContext1mMobile");a&&(a.checked=t.opusContext1m)},toggleCaseSettingsMobile(){const e=document.getElementById("caseSettingsPopoverMobile");if(e.classList.contains("hidden")){const t=document.getElementById("quickStartCase").value||"testcase",s=this.getCaseSettings(t);document.getElementById("caseAgentTeamsMobile").checked=s.agentTeams,document.getElementById("caseOpusContext1mMobile").checked=s.opusContext1m,e.classList.remove("hidden");const a=o=>{!e.contains(o.target)&&!o.target.classList.contains("btn-case-settings-mobile")&&(e.classList.add("hidden"),document.removeEventListener("click",a))};setTimeout(()=>document.addEventListener("click",a),0)}else e.classList.add("hidden")},onCaseSettingChangedMobile(){const e=document.getElementById("quickStartCase").value||"testcase",t=this.getCaseSettings(e);t.agentTeams=document.getElementById("caseAgentTeamsMobile").checked,t.opusContext1m=document.getElementById("caseOpusContext1mMobile").checked,this.saveCaseSettings(e,t);const s=document.getElementById("caseAgentTeams");s&&(s.checked=t.agentTeams);const a=document.getElementById("caseOpusContext1m");a&&(a.checked=t.opusContext1m)},showCreateCaseModal(){document.getElementById("newCaseName").value="",document.getElementById("newCaseDescription").value="",document.getElementById("linkCaseName").value="",document.getElementById("linkCasePath").value="",["remoteCaseName","remoteCasePath","remoteHostId","remoteHostAddress","remoteHostUsername","remoteHostPort","remoteHostCodexCommand","remoteHostIdentityFile","remoteHostSocksProxy","remoteHostJumpHost","remoteHostExtraSshOptions"].forEach(s=>{const a=document.getElementById(s);a&&(a.value="")}),this.caseModalTab="case-create",this.switchCaseModalTab("case-create");const t=document.getElementById("createCaseModal");t.querySelectorAll(".modal-tabs .modal-tab-btn").forEach(s=>{s.onclick=()=>this.switchCaseModalTab(s.dataset.tab)}),t.querySelectorAll('input[type="text"]').forEach(s=>{s._mobileScrollWired||(s._mobileScrollWired=!0,s.addEventListener("focus",()=>{window.innerWidth<=430&&setTimeout(()=>s.scrollIntoView({behavior:"smooth",block:"center"}),300)}))}),t.classList.add("active"),document.getElementById("newCaseName").focus()},switchCaseModalTab(e){this.caseModalTab=e;const t=document.getElementById("createCaseModal");t.querySelectorAll(".modal-tabs .modal-tab-btn").forEach(a=>{a.classList.toggle("active",a.dataset.tab===e)}),t.querySelectorAll(".modal-tab-content").forEach(a=>{a.classList.toggle("hidden",a.id!==e)});const s=document.getElementById("caseModalSubmit");e==="case-manage"?(s.style.display="none",this.renderCaseManageList(),this.refreshDockerExports()):(s.style.display="",s.textContent=e==="case-create"?"Create":e==="case-remote"?"Link Remote":e==="case-docker"?"Link Docker":"Link"),e==="case-create"?document.getElementById("newCaseName").focus():e==="case-link"?document.getElementById("linkCaseName").focus():e==="case-remote"?document.getElementById("remoteCaseName").focus():e==="case-docker"&&document.getElementById("dockerCaseName").focus()},closeCreateCaseModal(){document.getElementById("createCaseModal").classList.remove("active")},async submitCaseModal(){const e=document.getElementById("caseModalSubmit"),t=e.textContent;e.classList.add("loading"),e.textContent=this.caseModalTab==="case-create"?"Creating...":"Linking...";try{this.caseModalTab==="case-create"?await this.createCase():this.caseModalTab==="case-remote"?await this.linkRemoteCase():this.caseModalTab==="case-docker"?await this.linkDockerCase():await this.linkCase()}finally{e.classList.remove("loading"),e.textContent=t}},async createCase(){const e=document.getElementById("newCaseName").value.trim(),t=document.getElementById("newCaseDescription").value.trim();if(!e){this.showToast("Please enter a case name","error");return}if(!/^[a-zA-Z0-9_-]+$/.test(e)){this.showToast("Invalid name. Use only letters, numbers, hyphens, underscores.","error");return}const s=document.getElementById("newCaseDocker")?.checked,a=s?"/api/cases/docker-quickcreate":"/api/cases",o=s?{name:e,description:t,...this._collectDockerQuickSettings()}:{name:e,description:t};try{const i=await(await fetch(a,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)})).json();if(i.success)if(this.closeCreateCaseModal(),await this.loadQuickStartCases(e),await this.saveLastUsedCase(e),s){const r=i.data?.capsEnforced===!1?" (resource caps advisory on this engine)":"";this.showToast(`Docker case "${e}" created${r} \u2014 starting session\u2026`,"success"),await this.runClaude()}else this.showToast(`Case "${e}" created`,"success");else this.showToast(i.error||"Failed to create case","error")}catch(n){console.error("Failed to create case:",n),this.showToast("Failed to create case: "+n.message,"error")}},applyDockerTemplate(){const e=document.getElementById("quickDockerTemplate")?.value,s={small:{m:"2g",c:"1",g:""},medium:{m:"",c:"",g:""},large:{m:"8g",c:"4",g:""},gpu:{m:"8g",c:"4",g:"all"}}[e];if(!s)return;const a=(o,n)=>{const i=document.getElementById(o);i&&(i.value=n)};a("quickDockerMemory",s.m),a("quickDockerCpus",s.c),a("quickDockerGpus",s.g)},_collectDockerQuickSettings(){const e=c=>(document.getElementById(c)?.value||"").trim(),t={},s=e("quickDockerMemory");s&&(t.memory=s);const a=e("quickDockerCpus");a&&(t.cpus=a);const o=e("quickDockerGpus");o&&o.toLowerCase()!=="none"&&(t.gpus=o);const n=document.getElementById("quickDockerNetwork")?.value;n&&n!=="bridge"&&(t.network=n);const i=e("quickDockerImage");i&&(t.image=i);const r=document.getElementById("quickDockerMountCreds");return r&&!r.checked&&(t.mountCredentials=!1),t},async linkCase(){const e=document.getElementById("linkCaseName").value.trim(),t=document.getElementById("linkCasePath").value.trim();if(!e){this.showToast("Please enter a case name","error");return}if(!/^[a-zA-Z0-9_-]+$/.test(e)){this.showToast("Invalid name. Use only letters, numbers, hyphens, underscores.","error");return}if(!t){this.showToast("Please enter a folder path","error");return}try{const a=await(await fetch("/api/cases/link",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:e,path:t})})).json();a.success?(this.closeCreateCaseModal(),this.showToast(`Case "${e}" linked to ${t}`,"success"),await this.loadQuickStartCases(e),await this.saveLastUsedCase(e)):this.showToast(a.error||"Failed to link case","error")}catch(s){console.error("Failed to link case:",s),this.showToast("Failed to link case: "+s.message,"error")}},async linkRemoteCase(){const e=document.getElementById("remoteCaseName").value.trim(),t=document.getElementById("remoteCasePath").value.trim(),s=document.getElementById("remoteHostId").value.trim(),a=document.getElementById("remoteHostAddress").value.trim(),o=document.getElementById("remoteHostUsername").value.trim(),n=document.getElementById("remoteHostCodexCommand").value.trim(),i=document.getElementById("remoteHostPort").value.trim(),r=document.getElementById("remoteHostIdentityFile").value.trim(),c=document.getElementById("remoteHostSocksProxy").value.trim(),m=document.getElementById("remoteHostJumpHost").value.trim(),l=document.getElementById("remoteHostExtraSshOptions").value.split(`
15
+ Recreate the container to apply the new config? Workspace files and the conversation survive (the conversation resumes on launch).`))){const T=await(await fetch(`/api/docker-cases/${encodeURIComponent(e)}/recreate`,{method:"POST"})).json();if(!T.success)throw new Error(T.error||"Failed to recreate container");b=await S()}if(!b.success)throw new Error(b.error||"Failed to start remote Claude session");await this._ensureCreatedSessionVisible(b.data.sessionId,b.data.session),E.push(b.data.sessionId)}this.terminal.writeln(`\x1B[90m All ${t} remote session(s) ready\x1B[0m`),E[0]&&(await this.selectSession(E[0]),this.loadQuickStartCases()),this.terminal.focus();return}let n=null;const i=this._nextCaseSessionStartNumber(e),r=this.isRalphTrackerEnabledByDefault(),c=[];for(let f=0;f<t;f++)c.push(`w${i+f}-${e}`);const m=this.getCaseSettings(e),l=this.loadAppSettingsFromStorage(),u=this.buildEnvOverrides(m,l),p=Object.keys(u).length>0,d=this.getEffortSetting(l),h=m.opusContext1m||l.opusContext1mEnabled,y=l.claudeModel||(h?"opus[1m]":"");this.terminal.writeln(`\x1B[90m Creating ${t} session(s)...\x1B[0m`);const g=c.map(f=>fetch("/api/sessions",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({workingDir:o,name:f,...p?{envOverrides:u}:{},...d?{effort:d}:{},...y!==void 0?{modelOverride:y}:{},statusLineTelemetry:l.showPlanUsageLimits===!0})}).then(C=>C.json())),w=await Promise.all(g),v=[];for(const f of w){if(!f.success)throw new Error(f.error);await this._ensureCreatedSessionVisible(f.data.session.id,f.data.session),v.push(f.data.session.id)}n=v[0],await Promise.all(v.map(f=>fetch(`/api/sessions/${f}/ralph-config`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({enabled:r,disableAutoEnable:!r})}))),this.terminal.writeln(`\x1B[90m Starting ${t} session(s) in parallel...\x1B[0m`),await Promise.all(v.map(f=>fetch(`/api/sessions/${f}/interactive`,{method:"POST"}))),this.terminal.writeln(`\x1B[90m All ${t} sessions ready\x1B[0m`),n&&(await this.selectSession(n),this.loadQuickStartCases()),this.terminal.focus()}catch(s){this.terminal.writeln(`\x1B[1;31m Error: ${s.message}\x1B[0m`)}},stopClaude(){if(!this.activeSessionId)return;const e=document.querySelector(".btn-toolbar.btn-stop");e&&(this._stopConfirmTimer?(clearTimeout(this._stopConfirmTimer),this._stopConfirmTimer=null,e.innerHTML=e.dataset.origHtml,delete e.dataset.origHtml,e.classList.remove("confirming"),fetch(`/api/sessions/${this.activeSessionId}/input`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({input:""})})):(e.dataset.origHtml=e.innerHTML,e.textContent="Tap again",e.classList.add("confirming"),this._stopConfirmTimer=setTimeout(()=>{this._stopConfirmTimer=null,e.dataset.origHtml&&(e.innerHTML=e.dataset.origHtml,delete e.dataset.origHtml),e.classList.remove("confirming")},2e3)))},async runShell(){const e=document.getElementById("quickStartCase").value||"testcase",t=Math.min(20,Math.max(1,parseInt(document.getElementById("shellCount").value)||1));this.terminal.clear(),this.terminal.writeln(`\x1B[1;33m Starting ${t} Shell session(s) in ${e}...\x1B[0m`),this.terminal.writeln("");try{let a=(await(await fetch(`/api/cases/${e}`)).json())?.data??{};if(!a.path){const h=await(await fetch("/api/cases",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:e,description:""})})).json();if(!h.success)throw new Error(h.error||"Failed to create case");a=h.data.case}const o=(this.cases||[]).find(d=>d.name===e),n=a.location==="remote"||a.location==="docker"||o?.location==="remote"||o?.location==="docker",i=a.path;if(!i)throw new Error("Case path not found");if(a.location==="remote"||a.location==="docker"){const d=this._nextCaseSessionStartNumber(e,"s"),h=[];for(let y=0;y<t;y++){const w=await(await fetch("/api/quick-start",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({caseName:e,mode:"shell",sessionName:`s${d+y}-${e}`})})).json();if(!w.success)throw new Error(w.error||"Failed to start remote shell session");await this._ensureCreatedSessionVisible(w.data.sessionId,w.data.session),h.push(w.data.sessionId)}h[0]&&await this.selectSession(h[0]),this.terminal.focus();return}const r=this._nextCaseSessionStartNumber(e,"s"),c=[];for(let d=0;d<t;d++)c.push(`s${r+d}-${e}`);const m=c.map(d=>fetch("/api/sessions",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...n?{caseName:e}:{workingDir:i},mode:"shell",name:d})}).then(h=>h.json())),l=await Promise.all(m),u=[];for(const d of l){if(!d.success)throw new Error(d.error);await this._ensureCreatedSessionVisible(d.data.session.id,d.data.session),u.push(d.data.session.id)}await Promise.all(u.map(d=>fetch(`/api/sessions/${d}/shell`,{method:"POST"})));const p=this.getTerminalDimensions();p&&await Promise.all(u.map(d=>fetch(`/api/sessions/${d}/resize`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(p)}))),u.length>0&&await this.selectSession(u[0]),this.terminal.focus()}catch(s){this.terminal.writeln(`\x1B[1;31m Error: ${s.message}\x1B[0m`)}},async runOpenCode(){const e=document.getElementById("quickStartCase").value||"testcase",t=(this.cases||[]).find(a=>a.name===e)?.location,s=t==="remote"||t==="docker";this.terminal.clear(),this.terminal.writeln(`\x1B[1;32m Starting OpenCode session in ${e}...\x1B[0m`),this.terminal.writeln(""),this.terminal.focus();try{if(!s&&!(await(await fetch("/api/opencode/status")).json()).data.available){this.terminal.writeln("\x1B[1;31m OpenCode CLI not found.\x1B[0m"),this.terminal.writeln("\x1B[90m Install with: curl -fsSL https://opencode.ai/install | bash\x1B[0m");return}const a=this.buildEnvOverrides(this.getCaseSettings(e),this.loadAppSettingsFromStorage()),n=await(await fetch("/api/quick-start",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({caseName:e,mode:"opencode",sessionName:`w${this._nextCaseSessionStartNumber(e)}-${e}`,...s?{}:{openCodeConfig:{autoAllowTools:!0},...Object.keys(a).length>0?{envOverrides:a}:{}}})})).json();if(!n.success)throw new Error(n.error||"Failed to start OpenCode");await this._ensureCreatedSessionVisible(n.data.sessionId,n.data.session),n.data.sessionId&&await this.selectSession(n.data.sessionId),this.terminal.focus()}catch(a){this.terminal.writeln(`\x1B[1;31m Error: ${a.message}\x1B[0m`)}},async runCodex(){const e=document.getElementById("quickStartCase").value||"testcase",t=(this.cases||[]).find(a=>a.name===e)?.location,s=t==="remote"||t==="docker";this.terminal.clear(),this.terminal.writeln(`\x1B[1;32m Starting Codex session in ${e}...\x1B[0m`),this.terminal.writeln(""),this.terminal.focus();try{if(!s&&!(await(await fetch("/api/codex/status")).json()).data.available){this.terminal.writeln("\x1B[1;31m Codex CLI not found.\x1B[0m"),this.terminal.writeln("\x1B[90m Install with: npm install -g @openai/codex\x1B[0m");return}const a=this.loadAppSettingsFromStorage(),o=this.buildEnvOverrides(this.getCaseSettings(e),a),i=await(await fetch("/api/quick-start",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({caseName:e,mode:"codex",sessionName:`w${this._nextCaseSessionStartNumber(e)}-${e}`,...s?{}:{codexConfig:{dangerouslyBypassApprovals:a.codexDangerouslyBypassApprovals??!1,renderMode:"hybrid"},...Object.keys(o).length>0?{envOverrides:o}:{}}})})).json();if(!i.success)throw new Error(i.error||"Failed to start Codex");await this._ensureCreatedSessionVisible(i.data.sessionId,i.data.session),i.data.sessionId&&await this.selectSession(i.data.sessionId),this.terminal.focus()}catch(a){this.terminal.writeln(`\x1B[1;31m Error: ${a.message}\x1B[0m`)}},async runGemini(){const e=document.getElementById("quickStartCase").value||"testcase",t=(this.cases||[]).find(a=>a.name===e)?.location,s=t==="remote"||t==="docker";this.terminal.clear(),this.terminal.writeln(`\x1B[1;32m Starting Gemini session in ${e}...\x1B[0m`),this.terminal.writeln(""),this.terminal.focus();try{if(!s&&!(await(await fetch("/api/gemini/status")).json()).data.available){this.terminal.writeln("\x1B[1;31m Gemini CLI not found.\x1B[0m"),this.terminal.writeln("\x1B[90m Install with: npm install -g @google/gemini-cli\x1B[0m");return}const a=this.buildEnvOverrides(this.getCaseSettings(e),this.loadAppSettingsFromStorage()),n=await(await fetch("/api/quick-start",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({caseName:e,mode:"gemini",sessionName:`w${this._nextCaseSessionStartNumber(e)}-${e}`,...s?{}:{geminiConfig:{approvalMode:"yolo"},...Object.keys(a).length>0?{envOverrides:a}:{}}})})).json();if(!n.success)throw new Error(n.error||"Failed to start Gemini");await this._ensureCreatedSessionVisible(n.data.sessionId,n.data.session),n.data.sessionId&&await this.selectSession(n.data.sessionId),this.terminal.focus()}catch(a){this.terminal.writeln(`\x1B[1;31m Error: ${a.message}\x1B[0m`)}},openSessionOptions(e){const t=this.sessions.get(e);if(!t)return;this.editingSessionId=e;const s=t.mode==="opencode"||t.mode==="codex"||t.mode==="gemini";this.switchOptionsTab(s?"summary":"respawn");const a=document.getElementById("sessionRespawnStatus"),o=document.getElementById("modalEnableRespawnBtn"),n=document.getElementById("modalStopRespawnBtn");this.respawnStatus[e]?(a.classList.add("active"),a.querySelector(".respawn-status-text").textContent=this.respawnStatus[e].state||"Active",o.style.display="none",n.style.display=""):(a.classList.remove("active"),a.querySelector(".respawn-status-text").textContent="Not active",o.style.display="",n.style.display="none");const i=document.getElementById("sessionRespawnSection");t.mode==="claude"&&t.pid?i.style.display="":i.style.display="none";const r=t.mode==="opencode"||t.mode==="codex"||t.mode==="gemini";document.querySelectorAll("[data-claude-only]").forEach(g=>{g.style.display=r?"none":""}),this.selectDurationPreset(""),this.loadSavedRespawnConfig(e),document.getElementById("modalAutoCompactEnabled").checked=t.autoCompactEnabled??!1,document.getElementById("modalAutoCompactThreshold").value=t.autoCompactThreshold??11e4,document.getElementById("modalAutoCompactPrompt").value=t.autoCompactPrompt??"",document.getElementById("modalAutoClearEnabled").checked=t.autoClearEnabled??!1,document.getElementById("modalAutoClearThreshold").value=t.autoClearThreshold??14e4,document.getElementById("modalAutoResumeEnabled").checked=t.autoResumeEnabled??!1,this.updateAutoResumeStatus(e),document.getElementById("modalImageWatcherEnabled").checked=t.imageWatcherEnabled??!0,document.getElementById("modalFlickerFilterEnabled").checked=t.flickerFilterEnabled??!1;const m=parseSessionPrefix(t.name),l=document.getElementById("modalSessionPrefix");m?(l.textContent=m.prefix+": ",l.style.display="",document.getElementById("modalSessionName").value=m.suffix,document.getElementById("modalSessionName").placeholder="Add description..."):(l.style.display="none",l.textContent="",document.getElementById("modalSessionName").value=t.name||"",document.getElementById("modalSessionName").placeholder="Auto (directory name)");const u=t.color||"default";document.getElementById("sessionColorPicker")?.querySelectorAll(".color-swatch").forEach(g=>{g.classList.toggle("selected",g.dataset.color===u)}),this.renderPresetDropdown(),document.getElementById("respawnPresetSelect").value="",document.getElementById("presetDescriptionHint").textContent="";const d=document.querySelector('#sessionOptionsModal .modal-tab-btn[data-tab="ralph"]'),h=document.querySelector('#sessionOptionsModal .modal-tab-btn[data-tab="respawn"]');if(r?(d&&(d.style.display="none"),h&&(h.style.display="none"),this.switchOptionsTab("context")):(d&&(d.style.display=""),h&&(h.style.display="")),!r){const g=this.ralphStates.get(e);this.populateRalphForm({enabled:g?.loop?.enabled??t.ralphLoop?.enabled??!1,completionPhrase:g?.loop?.completionPhrase||t.ralphLoop?.completionPhrase||"",maxIterations:g?.loop?.maxIterations||t.ralphLoop?.maxIterations||0,maxTodos:g?.loop?.maxTodos||t.ralphLoop?.maxTodos,todoExpirationMinutes:g?.loop?.todoExpirationMinutes||t.ralphLoop?.todoExpirationMinutes})}const y=document.getElementById("sessionOptionsModal");y.classList.add("active"),this.activeFocusTrap=new FocusTrap(y),this.activeFocusTrap.activate()},async saveSessionName(){if(!this.editingSessionId)return;const e=this.sessions.get(this.editingSessionId),t=e?parseSessionPrefix(e.name):null,s=document.getElementById("modalSessionName").value.trim();let a;t?a=t.prefix+(s?": "+s:""):a=s;try{await this._apiPut(`/api/sessions/${this.editingSessionId}/name`,{name:a})}catch(o){this.showToast("Failed to save session name: "+o.message,"error")}},async autoSaveAutoCompact(){if(this.editingSessionId)try{await this._apiPost(`/api/sessions/${this.editingSessionId}/auto-compact`,{enabled:document.getElementById("modalAutoCompactEnabled").checked,threshold:parseInt(document.getElementById("modalAutoCompactThreshold").value)||11e4,prompt:document.getElementById("modalAutoCompactPrompt").value.trim()||void 0})}catch{}},async autoSaveAutoClear(){if(this.editingSessionId)try{await this._apiPost(`/api/sessions/${this.editingSessionId}/auto-clear`,{enabled:document.getElementById("modalAutoClearEnabled").checked,threshold:parseInt(document.getElementById("modalAutoClearThreshold").value)||14e4})}catch{}},async autoSaveAutoResume(){if(!this.editingSessionId)return;const e=document.getElementById("modalAutoResumeEnabled").checked;try{await this._apiPost(`/api/sessions/${this.editingSessionId}/auto-resume`,{enabled:e});const t=this.sessions.get(this.editingSessionId);t&&(t.autoResumeEnabled=e,e||(t.autoResumeAt=void 0)),this.updateAutoResumeStatus(this.editingSessionId),this.showToast(`Auto-resume on usage limit ${e?"enabled":"disabled"}`,"success")}catch(t){this.showToast("Failed to toggle auto-resume: "+t.message,"error")}},updateAutoResumeStatus(e){const t=document.getElementById("autoResumeStatus");if(!t||this.editingSessionId!==e)return;const s=this.sessions.get(e);if(s?.autoResumeAt&&s.autoResumeAt>Date.now()){const a=new Date(s.autoResumeAt).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});t.textContent=`Usage limit pause active \u2014 resumes at ${a}`,t.classList.add("active")}else t.textContent="",t.classList.remove("active")},async toggleSessionImageWatcher(){if(!this.editingSessionId)return;const e=document.getElementById("modalImageWatcherEnabled").checked;try{await this._apiPost(`/api/sessions/${this.editingSessionId}/image-watcher`,{enabled:e});const t=this.sessions.get(this.editingSessionId);t&&(t.imageWatcherEnabled=e),this.showToast(`Image watcher ${e?"enabled":"disabled"}`,"success")}catch{this.showToast("Failed to toggle image watcher","error")}},async toggleFlickerFilter(){if(!this.editingSessionId)return;const e=document.getElementById("modalFlickerFilterEnabled").checked;try{await this._apiPost(`/api/sessions/${this.editingSessionId}/flicker-filter`,{enabled:e});const t=this.sessions.get(this.editingSessionId);t&&(t.flickerFilterEnabled=e),this.showToast(`Flicker filter ${e?"enabled":"disabled"}`,"success")}catch{this.showToast("Failed to toggle flicker filter","error")}},async autoSaveRespawnConfig(){if(!this.editingSessionId)return;const e={updatePrompt:document.getElementById("modalRespawnPrompt").value,sendClear:document.getElementById("modalRespawnSendClear").checked,sendInit:document.getElementById("modalRespawnSendInit").checked,kickstartPrompt:document.getElementById("modalRespawnKickstart").value.trim()||void 0,autoAcceptPrompts:document.getElementById("modalRespawnAutoAccept").checked};try{await this._apiPut(`/api/sessions/${this.editingSessionId}/respawn/config`,e)}catch{}},async loadSavedRespawnConfig(e){try{const s=await(await fetch(`/api/sessions/${e}/respawn/config`)).json();if(s.success&&s.data&&s.data.config){const a=s.data.config;document.getElementById("modalRespawnPrompt").value=a.updatePrompt||"update all the docs and CLAUDE.md",document.getElementById("modalRespawnSendClear").checked=a.sendClear??!0,document.getElementById("modalRespawnSendInit").checked=a.sendInit??!0,document.getElementById("modalRespawnKickstart").value=a.kickstartPrompt||"",document.getElementById("modalRespawnAutoAccept").checked=a.autoAcceptPrompts??!0,a.durationMinutes&&(document.querySelector(`.duration-preset-btn[data-minutes="${a.durationMinutes}"]`)?this.selectDurationPreset(String(a.durationMinutes)):(this.selectDurationPreset("custom"),document.getElementById("modalRespawnDuration").value=a.durationMinutes))}}catch{}},selectDurationPreset(e){document.querySelectorAll(".duration-preset-btn").forEach(o=>o.classList.remove("active"));const t=document.querySelector(`.duration-preset-btn[data-minutes="${e}"]`);t&&t.classList.add("active");const s=document.querySelector(".duration-custom-input"),a=document.getElementById("modalRespawnDuration");e==="custom"?(s.classList.add("visible"),a.focus()):(s.classList.remove("visible"),a.value="")},getSelectedDuration(){const e=document.querySelector(".duration-custom-input"),t=document.getElementById("modalRespawnDuration");if(e.classList.contains("visible"))return t.value?parseInt(t.value):null;{const a=document.querySelector(".duration-preset-btn.active")?.dataset.minutes;return a?parseInt(a):null}},switchOptionsTab(e){document.querySelectorAll("#sessionOptionsModal .modal-tab-btn").forEach(t=>{t.classList.toggle("active",t.dataset.tab===e)}),document.getElementById("respawn-tab").classList.toggle("hidden",e!=="respawn"),document.getElementById("context-tab").classList.toggle("hidden",e!=="context"),document.getElementById("ralph-tab").classList.toggle("hidden",e!=="ralph"),document.getElementById("summary-tab").classList.toggle("hidden",e!=="summary"),e==="summary"&&this.editingSessionId&&this.loadRunSummary(this.editingSessionId)},getRalphConfig(){return{enabled:document.getElementById("modalRalphEnabled").checked,completionPhrase:document.getElementById("modalRalphPhrase").value.trim(),maxIterations:parseInt(document.getElementById("modalRalphMaxIterations").value)||0,maxTodos:parseInt(document.getElementById("modalRalphMaxTodos").value)||50,todoExpirationMinutes:parseInt(document.getElementById("modalRalphTodoExpiration").value)||60}},populateRalphForm(e){document.getElementById("modalRalphEnabled").checked=e?.enabled??!1,document.getElementById("modalRalphPhrase").value=e?.completionPhrase||"",document.getElementById("modalRalphMaxIterations").value=e?.maxIterations||0,document.getElementById("modalRalphMaxTodos").value=e?.maxTodos||50,document.getElementById("modalRalphTodoExpiration").value=e?.todoExpirationMinutes||60},async saveRalphConfig(){if(!this.editingSessionId){this.showToast("No session selected","warning");return}const e=this.getRalphConfig();e.enabled&&this.ralphClosedSessions.delete(this.editingSessionId);try{const s=await(await fetch(`/api/sessions/${this.editingSessionId}/ralph-config`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})).json();if(s.error)throw new Error(s.error);this.showToast("Ralph config saved","success")}catch(t){this.showToast("Failed to save Ralph config: "+t.message,"error")}},startInlineRename(e){const t=this.sessions.get(e);if(!t)return;const s=document.querySelector(`.tab-name[data-session-id="${e}"]`);if(!s)return;this._inlineRenameActive=!0;const a=this.getSessionName(t),o=parseSessionPrefix(t.name),n=s.textContent;for(s.textContent="";s.firstChild;)s.removeChild(s.firstChild);if(o){const c=document.createElement("span");c.textContent=o.prefix+": ",c.style.cssText="color: var(--text-muted); font-size: 0.75rem; white-space: nowrap;",s.appendChild(c)}const i=document.createElement("input");i.type="text",i.value=o?o.suffix:t.name||"",i.placeholder=o?"Add description...":a,i.className="tab-rename-input",i.style.cssText="width: 80px; font-size: 0.75rem; padding: 2px 4px; background: var(--bg-input); border: 1px solid var(--accent); border-radius: 3px; color: var(--text); outline: none;",s.appendChild(i),i.focus(),i.select();const r=async({commit:c})=>{if(!this._inlineRenameActive)return;if(this._inlineRenameActive=!1,this._activeRename=null,!c){this.renderSessionTabs();return}const m=i.value.trim(),l=o?o.prefix+(m?": "+m:""):m;if(s.textContent=l||n,this.sessions.has(e)&&l!==t.name)try{await fetch(`/api/sessions/${e}/name`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:l})})}catch{s.textContent=n,this.showToast("Failed to rename","error")}this.renderSessionTabs()};this._activeRename={sessionId:e,cancel:()=>r({commit:!1})},i.addEventListener("blur",()=>r({commit:!0})),i.addEventListener("keydown",c=>{c.isComposing||c.keyCode===229||(c.key==="Enter"?(c.preventDefault(),i.blur()):c.key==="Escape"&&(i.value="",i.blur()))})},toggleCaseSettings(){const e=document.getElementById("caseSettingsPopover");if(e.classList.contains("hidden")){const t=document.getElementById("quickStartCase").value||"testcase",s=this.getCaseSettings(t);document.getElementById("caseAgentTeams").checked=s.agentTeams,document.getElementById("caseOpusContext1m").checked=s.opusContext1m,e.classList.remove("hidden");const a=o=>{!e.contains(o.target)&&!o.target.classList.contains("btn-case-settings")&&(e.classList.add("hidden"),document.removeEventListener("click",a))};setTimeout(()=>document.addEventListener("click",a),0)}else e.classList.add("hidden")},getCaseSettings(e){try{const t=localStorage.getItem("caseSettings_"+e);if(t)return JSON.parse(t)}catch{}return{agentTeams:!1,opusContext1m:!0}},saveCaseSettings(e,t){localStorage.setItem("caseSettings_"+e,JSON.stringify(t))},onCaseSettingChanged(){const e=document.getElementById("quickStartCase").value||"testcase",t=this.getCaseSettings(e);t.agentTeams=document.getElementById("caseAgentTeams").checked,t.opusContext1m=document.getElementById("caseOpusContext1m").checked,this.saveCaseSettings(e,t);const s=document.getElementById("caseAgentTeamsMobile");s&&(s.checked=t.agentTeams);const a=document.getElementById("caseOpusContext1mMobile");a&&(a.checked=t.opusContext1m)},toggleCaseSettingsMobile(){const e=document.getElementById("caseSettingsPopoverMobile");if(e.classList.contains("hidden")){const t=document.getElementById("quickStartCase").value||"testcase",s=this.getCaseSettings(t);document.getElementById("caseAgentTeamsMobile").checked=s.agentTeams,document.getElementById("caseOpusContext1mMobile").checked=s.opusContext1m,e.classList.remove("hidden");const a=o=>{!e.contains(o.target)&&!o.target.classList.contains("btn-case-settings-mobile")&&(e.classList.add("hidden"),document.removeEventListener("click",a))};setTimeout(()=>document.addEventListener("click",a),0)}else e.classList.add("hidden")},onCaseSettingChangedMobile(){const e=document.getElementById("quickStartCase").value||"testcase",t=this.getCaseSettings(e);t.agentTeams=document.getElementById("caseAgentTeamsMobile").checked,t.opusContext1m=document.getElementById("caseOpusContext1mMobile").checked,this.saveCaseSettings(e,t);const s=document.getElementById("caseAgentTeams");s&&(s.checked=t.agentTeams);const a=document.getElementById("caseOpusContext1m");a&&(a.checked=t.opusContext1m)},showCreateCaseModal(){document.getElementById("newCaseName").value="",document.getElementById("newCaseDescription").value="",document.getElementById("linkCaseName").value="",document.getElementById("linkCasePath").value="",["remoteCaseName","remoteCasePath","remoteHostId","remoteHostAddress","remoteHostUsername","remoteHostPort","remoteHostCodexCommand","remoteHostIdentityFile","remoteHostSocksProxy","remoteHostJumpHost","remoteHostExtraSshOptions"].forEach(s=>{const a=document.getElementById(s);a&&(a.value="")}),this.caseModalTab="case-create",this.switchCaseModalTab("case-create");const t=document.getElementById("createCaseModal");t.querySelectorAll(".modal-tabs .modal-tab-btn").forEach(s=>{s.onclick=()=>this.switchCaseModalTab(s.dataset.tab)}),t.querySelectorAll('input[type="text"]').forEach(s=>{s._mobileScrollWired||(s._mobileScrollWired=!0,s.addEventListener("focus",()=>{window.innerWidth<=430&&setTimeout(()=>s.scrollIntoView({behavior:"smooth",block:"center"}),300)}))}),t.classList.add("active"),document.getElementById("newCaseName").focus()},switchCaseModalTab(e){this.caseModalTab=e;const t=document.getElementById("createCaseModal");t.querySelectorAll(".modal-tabs .modal-tab-btn").forEach(a=>{a.classList.toggle("active",a.dataset.tab===e)}),t.querySelectorAll(".modal-tab-content").forEach(a=>{a.classList.toggle("hidden",a.id!==e)});const s=document.getElementById("caseModalSubmit");e==="case-manage"?(s.style.display="none",this.renderCaseManageList(),this.refreshDockerExports()):(s.style.display="",s.textContent=e==="case-create"?"Create":e==="case-remote"?"Link Remote":e==="case-docker"?"Link Docker":"Link"),e==="case-create"?document.getElementById("newCaseName").focus():e==="case-link"?document.getElementById("linkCaseName").focus():e==="case-remote"?document.getElementById("remoteCaseName").focus():e==="case-docker"&&document.getElementById("dockerCaseName").focus()},closeCreateCaseModal(){document.getElementById("createCaseModal").classList.remove("active")},async submitCaseModal(){const e=document.getElementById("caseModalSubmit"),t=e.textContent;e.classList.add("loading"),e.textContent=this.caseModalTab==="case-create"?"Creating...":"Linking...";try{this.caseModalTab==="case-create"?await this.createCase():this.caseModalTab==="case-remote"?await this.linkRemoteCase():this.caseModalTab==="case-docker"?await this.linkDockerCase():await this.linkCase()}finally{e.classList.remove("loading"),e.textContent=t}},async createCase(){const e=document.getElementById("newCaseName").value.trim(),t=document.getElementById("newCaseDescription").value.trim();if(!e){this.showToast("Please enter a case name","error");return}if(!/^[a-zA-Z0-9_-]+$/.test(e)){this.showToast("Invalid name. Use only letters, numbers, hyphens, underscores.","error");return}const s=document.getElementById("newCaseDocker")?.checked,a=s?"/api/cases/docker-quickcreate":"/api/cases",o=s?{name:e,description:t,...this._collectDockerQuickSettings()}:{name:e,description:t};try{const i=await(await fetch(a,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)})).json();if(i.success)if(this.closeCreateCaseModal(),await this.loadQuickStartCases(e),await this.saveLastUsedCase(e),s){const r=i.data?.capsEnforced===!1?" (resource caps advisory on this engine)":"";this.showToast(`Docker case "${e}" created${r} \u2014 starting session\u2026`,"success"),await this.runClaude()}else this.showToast(`Case "${e}" created`,"success");else this.showToast(i.error||"Failed to create case","error")}catch(n){console.error("Failed to create case:",n),this.showToast("Failed to create case: "+n.message,"error")}},applyDockerTemplate(){const e=document.getElementById("quickDockerTemplate")?.value,s={small:{m:"2g",c:"1",g:""},medium:{m:"",c:"",g:""},large:{m:"8g",c:"4",g:""},gpu:{m:"8g",c:"4",g:"all"}}[e];if(!s)return;const a=(o,n)=>{const i=document.getElementById(o);i&&(i.value=n)};a("quickDockerMemory",s.m),a("quickDockerCpus",s.c),a("quickDockerGpus",s.g)},_collectDockerQuickSettings(){const e=c=>(document.getElementById(c)?.value||"").trim(),t={},s=e("quickDockerMemory");s&&(t.memory=s);const a=e("quickDockerCpus");a&&(t.cpus=a);const o=e("quickDockerGpus");o&&o.toLowerCase()!=="none"&&(t.gpus=o);const n=document.getElementById("quickDockerNetwork")?.value;n&&n!=="bridge"&&(t.network=n);const i=e("quickDockerImage");i&&(t.image=i);const r=document.getElementById("quickDockerMountCreds");return r&&!r.checked&&(t.mountCredentials=!1),t},async linkCase(){const e=document.getElementById("linkCaseName").value.trim(),t=document.getElementById("linkCasePath").value.trim();if(!e){this.showToast("Please enter a case name","error");return}if(!/^[a-zA-Z0-9_-]+$/.test(e)){this.showToast("Invalid name. Use only letters, numbers, hyphens, underscores.","error");return}if(!t){this.showToast("Please enter a folder path","error");return}try{const a=await(await fetch("/api/cases/link",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:e,path:t})})).json();a.success?(this.closeCreateCaseModal(),this.showToast(`Case "${e}" linked to ${t}`,"success"),await this.loadQuickStartCases(e),await this.saveLastUsedCase(e)):this.showToast(a.error||"Failed to link case","error")}catch(s){console.error("Failed to link case:",s),this.showToast("Failed to link case: "+s.message,"error")}},async linkRemoteCase(){const e=document.getElementById("remoteCaseName").value.trim(),t=document.getElementById("remoteCasePath").value.trim(),s=document.getElementById("remoteHostId").value.trim(),a=document.getElementById("remoteHostAddress").value.trim(),o=document.getElementById("remoteHostUsername").value.trim(),n=document.getElementById("remoteHostCodexCommand").value.trim(),i=document.getElementById("remoteHostPort").value.trim(),r=document.getElementById("remoteHostIdentityFile").value.trim(),c=document.getElementById("remoteHostSocksProxy").value.trim(),m=document.getElementById("remoteHostJumpHost").value.trim(),l=document.getElementById("remoteHostExtraSshOptions").value.split(`
16
16
  `).map(p=>p.trim()).filter(p=>p.length>0);if(!e||!t||!s||!a||!o){this.showToast("Please complete all required remote fields","error");return}if(!/^[a-zA-Z0-9_-]+$/.test(e)||!/^[a-zA-Z0-9_-]+$/.test(s)){this.showToast("Invalid name. Use only letters, numbers, hyphens, underscores.","error");return}if(!t.startsWith("/")){this.showToast("Remote path must be absolute","error");return}let u;if(i&&(u=Number(i),!Number.isInteger(u)||u<1||u>65535)){this.showToast("SSH port must be a number between 1 and 65535","error");return}try{const p={id:s,label:s,host:a,username:o,...u?{port:u}:{},...r?{identityFile:r}:{},...c?{socksProxy:c}:{},...m?{jumpHost:m}:{},...l.length?{extraSshOptions:l}:{},...n?{commands:{codex:n}}:{}},h=await(await fetch("/api/remote-hosts",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(p)})).json();if(!h.success&&h.errorCode!=="ALREADY_EXISTS")throw new Error(h.error||"Failed to save remote host");const g=await(await fetch("/api/cases/remote-link",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:e,hostId:s,remotePath:t})})).json();g.success?(this.closeCreateCaseModal(),this.showToast(`Remote case "${e}" linked`,"success"),await this.loadQuickStartCases(e),await this.saveLastUsedCase(e)):this.showToast(g.error||"Failed to link remote case","error")}catch(p){console.error("Failed to link remote case:",p),this.showToast("Failed to link remote case: "+p.message,"error")}},async linkDockerCase(){const e=document.getElementById("dockerCaseName").value.trim(),t=document.getElementById("dockerWorkspacePath").value.trim(),s=document.getElementById("dockerHostId").value.trim()||"local",a=document.getElementById("dockerImage").value.trim()||"codeman/agent:base",o=document.getElementById("dockerNetwork").value,n=document.getElementById("dockerMemory").value.trim(),i=document.getElementById("dockerCpus").value.trim(),r=document.getElementById("dockerMountCredentials").checked,c=document.getElementById("dockerResumeOnStart").checked,m=document.getElementById("dockerLinkStatus");if(!e||!t){this.showToast("Please enter a case name and workspace path","error");return}if(!/^[a-zA-Z0-9_-]+$/.test(e)||!/^[a-zA-Z0-9_-]+$/.test(s)){this.showToast("Invalid name. Use only letters, numbers, hyphens, underscores.","error");return}if(!t.startsWith("/")){this.showToast("Workspace path must be absolute","error");return}try{m&&(m.textContent="Checking docker daemon + base image...");const l={};n&&(l.memory=n),i&&(l.cpus=i);const u={id:s,label:s,image:a,network:o,mountCredentials:r,resumeOnStart:c,...Object.keys(l).length?{resources:l}:{}};let p=await fetch("/api/docker-hosts",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(u)}),d=await p.json();if(!d.success&&d.errorCode==="ALREADY_EXISTS"&&(p=await fetch(`/api/docker-hosts/${encodeURIComponent(s)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(u)}),d=await p.json()),!d.success)throw new Error(d.error||"Failed to save docker host");const y=await(await fetch("/api/cases/docker-link",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:e,hostId:s,hostWorkspacePath:t})})).json();if(y.success){this.closeCreateCaseModal();const g=y.data?.capsEnforced===!1?" (resource caps are advisory on this engine)":"";this.showToast(`Docker case "${e}" linked${g}`,"success"),await this.loadQuickStartCases(e),await this.saveLastUsedCase(e)}else m&&(m.textContent=y.error||"Failed to link docker case"),this.showToast(y.error||"Failed to link docker case","error")}catch(l){console.error("Failed to link docker case:",l),m&&(m.textContent=l.message),this.showToast("Failed to link docker case: "+l.message,"error")}},async refreshDockerExports(){const e=document.getElementById("dockerExportsList");if(e)try{const a=(await(await fetch("/api/docker-exports")).json())?.data?.exports||[];if(a.length===0){e.innerHTML='<span class="form-hint">No exports yet. Export a docker case from its tab.</span>';return}e.innerHTML=a.map(o=>{const n=(o.sizeBytes/1e6).toFixed(1),i=escapeHtml(o.name);return`<div class="case-manage-item" style="display:flex; align-items:center; gap:8px; justify-content:space-between;">
17
17
  <span style="overflow:hidden; text-overflow:ellipsis; white-space:nowrap;" title="${i}">${i} <span class="form-hint">(${n} MB)</span></span>
18
18
  <span style="flex-shrink:0;">
@@ -1,4 +1,4 @@
1
- "use strict";Object.assign(CodemanApp.prototype,{_onHookIdlePrompt(e){e.sessionId&&this.setPendingHook(e.sessionId,"idle_prompt"),this._notifySession(e.sessionId,"warning","hook-idle","Waiting for Input",e.message||"Claude is idle and waiting for a prompt")},_onHookPermissionPrompt(e){e.sessionId&&this.setPendingHook(e.sessionId,"permission_prompt");const t=e.tool?`${e.tool}${e.command?": "+e.command:e.file?": "+e.file:""}`:"";this._notifySession(e.sessionId,"critical","hook-permission","Permission Required",t||"Claude needs tool approval to continue")},_onHookElicitationDialog(e){e.sessionId&&this.setPendingHook(e.sessionId,"elicitation_dialog"),this._notifySession(e.sessionId,"critical","hook-elicitation","Question Asked",e.question||"Claude is asking a question and waiting for your answer")},_onHookStop(e){e.sessionId&&this.clearPendingHooks(e.sessionId),this._notifySession(e.sessionId,"info","hook-stop","Response Complete",e.reason||"Claude has finished responding")},_onHookTeammateIdle(e){const t=this.sessions.get(e.sessionId);this._notifySession(e.sessionId,"warning","hook-teammate-idle","Teammate Idle",`A teammate is idle in ${t?.name||e.sessionId}`)},_onHookTaskCompleted(e){const t=this.sessions.get(e.sessionId);this._notifySession(e.sessionId,"info","hook-task-completed","Task Completed",`A team task completed in ${t?.name||e.sessionId}`)},_onTunnelStarted(e){console.log("[Tunnel] Started:",e.url),this._tunnelUrl=e.url,this._dismissTunnelConnecting(),this._updateTunnelUrlDisplay(e.url),this._updateTunnelIndicator(!0),document.getElementById("welcomeOverlay")?.classList.contains("visible")?(this._updateWelcomeTunnelBtn(!0,e.url,!0),this.showToast("Tunnel active","success")):(this._updateWelcomeTunnelBtn(!0,e.url),this.showToast(`Tunnel active: ${e.url}`,"success"),this.showTunnelQR())},_onTunnelStopped(){console.log("[Tunnel] Stopped"),this._tunnelUrl=null,this._dismissTunnelConnecting(),this._updateTunnelUrlDisplay(null),this._updateWelcomeTunnelBtn(!1),this._updateTunnelIndicator(!1),this.closeTunnelPanel(),this.closeTunnelQR()},_onTunnelProgress(e){console.log("[Tunnel] Progress:",e.message);const t=document.getElementById("tunnelConnectingToast");t&&(t.innerHTML=`<span class="tunnel-spinner"></span> ${e.message}`);const n=document.getElementById("welcomeTunnelBtn");n?.classList.contains("connecting")&&(n.innerHTML=`<span class="tunnel-spinner"></span> ${e.message}`)},_onTunnelError(e){console.warn("[Tunnel] Error:",e.message),this._dismissTunnelConnecting(),this.showToast(`Tunnel error: ${e.message}`,"error");const t=document.getElementById("welcomeTunnelBtn");t&&(t.disabled=!1,t.classList.remove("connecting"))},_onTunnelQrRotated(e){if(e.svg){const t=document.getElementById("tunnelQrContainer");t&&(t.innerHTML=e.svg);const n=document.getElementById("welcomeQrInner");n&&(n.innerHTML=e.svg)}else this._refreshTunnelQrFromApi();this._resetQrCountdown()},_onTunnelQrRegenerated(e){if(e.svg){const t=document.getElementById("tunnelQrContainer");t&&(t.innerHTML=e.svg);const n=document.getElementById("welcomeQrInner");n&&(n.innerHTML=e.svg)}else this._refreshTunnelQrFromApi();this._resetQrCountdown()},_onTunnelQrAuthUsed(e){const n=(e.ua||"Unknown device").match(/Chrome|Firefox|Safari|Edge|Mobile/)?.[0]||"Browser";this.showToast(`Device authenticated via QR (${n}, ${e.ip}). Not you?`,"warning",{duration:1e4,action:{label:"Revoke All",onClick:()=>{fetch("/api/auth/revoke",{method:"POST",headers:{"Content-Type":"application/json"},body:"{}"}).then(()=>this.showToast("All sessions revoked","success")).catch(()=>this.showToast("Failed to revoke sessions","error"))}}})},registerServiceWorker(){"serviceWorker"in navigator&&navigator.serviceWorker.register("/sw.js").then(e=>{this._swRegistration=e,navigator.serviceWorker.addEventListener("message",t=>{if(t.data?.type==="notification-click"){const{sessionId:n}=t.data;n&&this.sessions.has(n)&&this.selectSession(n),window.focus()}}),e.pushManager.getSubscription().then(t=>{t&&(this._pushSubscription=t,this._updatePushUI(!0))})}).catch(()=>{})},async subscribeToPush(){if(!this._swRegistration){this.showToast("Service worker not available. HTTPS or localhost required.","error");return}try{const e=await this._apiJson("/api/push/vapid-key");if(!e)throw new Error("Failed to get VAPID key");const t=urlBase64ToUint8Array(e.publicKey),n=await this._swRegistration.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:t}),s=n.toJSON(),o=await this._apiJson("/api/push/subscribe",{method:"POST",body:{endpoint:s.endpoint,keys:s.keys,userAgent:navigator.userAgent,pushPreferences:this._buildPushPreferences()}});if(!o)throw new Error("Failed to register subscription");this._pushSubscription=n,this._pushSubscriptionId=o.id,localStorage.setItem("codeman-push-subscription-id",o.id),this._updatePushUI(!0),this.showToast("Push notifications enabled","success")}catch(e){this.showToast("Push subscription failed: "+(e.message||e),"error")}},async unsubscribeFromPush(){try{this._pushSubscription&&await this._pushSubscription.unsubscribe();const e=this._pushSubscriptionId||localStorage.getItem("codeman-push-subscription-id");e&&await fetch(`/api/push/subscribe/${e}`,{method:"DELETE"}).catch(()=>{}),this._pushSubscription=null,this._pushSubscriptionId=null,localStorage.removeItem("codeman-push-subscription-id"),this._updatePushUI(!1),this.showToast("Push notifications disabled","success")}catch(e){this.showToast("Failed to unsubscribe: "+(e.message||e),"error")}},async togglePushSubscription(){this._pushSubscription?await this.unsubscribeFromPush():await this.subscribeToPush()},async _syncPushPreferences(){const e=this._pushSubscriptionId||localStorage.getItem("codeman-push-subscription-id");if(e)try{await fetch(`/api/push/subscribe/${e}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({pushPreferences:this._buildPushPreferences()})})}catch{}},_buildPushPreferences(){const e={},t={"hook:permission_prompt":"eventPermissionPush","hook:elicitation_dialog":"eventQuestionPush","hook:idle_prompt":"eventIdlePush","hook:stop":"eventStopPush","respawn:blocked":"eventRespawnPush","session:ralphCompletionDetected":"eventRalphPush"};for(const[n,s]of Object.entries(t)){const o=document.getElementById(s);e[n]=o?o.checked:!0}return e["session:error"]=!0,e},_updatePushUI(e){const t=document.getElementById("pushSubscribeBtn"),n=document.getElementById("pushSubscriptionStatus");t&&(t.textContent=e?"Unsubscribe":"Subscribe"),n&&(n.textContent=e?"active":"off",n.classList.remove("granted","denied"),e&&n.classList.add("granted"))},openAppSettings(){const e=this.loadAppSettingsFromStorage();document.getElementById("appSettingsDisplayName").value=e.displayName||"Codeman",document.getElementById("appSettingsLanguage").value=e.language==="zh-CN"?"zh-CN":"en",document.getElementById("appSettingsClaudeMdPath").value=e.defaultClaudeMdPath||"",document.getElementById("appSettingsDefaultDir").value=e.defaultWorkingDir||"";const t=this.getDefaultSettings();document.getElementById("appSettingsRalphEnabled").checked=e.ralphTrackerEnabled??t.ralphTrackerEnabled??!1,document.getElementById("appSettingsShowFontControls").checked=e.showFontControls??t.showFontControls??!1,document.getElementById("appSettingsShowSystemStats").checked=e.showSystemStats??t.showSystemStats??!0,document.getElementById("appSettingsShowLifecycleLog").checked=e.showLifecycleLog??t.showLifecycleLog??!0,document.getElementById("appSettingsShowResponseViewer").checked=e.showResponseViewer??t.showResponseViewer??!1,document.getElementById("appSettingsShowFileViewerButton").checked=e.showFileViewerButton??t.showFileViewerButton??!1,document.getElementById("appSettingsShowAttachmentsButton").checked=e.showAttachmentsButton??t.showAttachmentsButton??!1,document.getElementById("appSettingsSkin").value=e.skin??t.skin??"daylight-blue",document.getElementById("appSettingsWebglRenderer").checked=e.webglRendererEnabled??t.webglRendererEnabled??!0;const n=document.getElementById("appSettingsWebglRendererItem");n&&(n.style.display=MobileDetection.getDeviceType()==="desktop"?"":"none"),document.getElementById("appSettingsShowMonitor").checked=e.showMonitor??t.showMonitor??!1,document.getElementById("appSettingsShowProjectInsights").checked=e.showProjectInsights??t.showProjectInsights??!1,document.getElementById("appSettingsShowFileBrowser").checked=e.showFileBrowser??t.showFileBrowser??!1,document.getElementById("appSettingsShowSubagents").checked=e.showSubagents??t.showSubagents??!1,document.getElementById("appSettingsShowUltracodeAgents").checked=e.showUltracodeAgents??t.showUltracodeAgents??!1,document.getElementById("appSettingsUltracodeFloatingWindows").checked=e.ultracodeFloatingWindows??t.ultracodeFloatingWindows??!1,document.getElementById("appSettingsShowMultiMonitorButton").checked=e.showMultiMonitorButton??t.showMultiMonitorButton??!1,document.getElementById("appSettingsShowPlanUsageLimits").checked=e.showPlanUsageLimits??t.showPlanUsageLimits??!1,document.getElementById("appSettingsShowRedrawButton").checked=e.showRedrawButton??t.showRedrawButton??!1,document.getElementById("appSettingsShowSessionButton").checked=e.showSessionButton??t.showSessionButton??!1,document.getElementById("appSettingsShowAwayDigestButton").checked=e.showAwayDigestButton??t.showAwayDigestButton??!1,document.getElementById("appSettingsShowCronButton").checked=e.showCronButton??t.showCronButton??!1;const s=document.getElementById("appSettingsGestureControlItem");s&&(s.style.display=window.__codemanGestureAvailable?"":"none"),document.getElementById("appSettingsGestureControl").checked=e.gestureControlEnabled??t.gestureControlEnabled??!1,document.getElementById("appSettingsSubagentTracking").checked=e.subagentTrackingEnabled??t.subagentTrackingEnabled??!0,document.getElementById("appSettingsSubagentActiveTabOnly").checked=e.subagentActiveTabOnly??t.subagentActiveTabOnly??!0,document.getElementById("appSettingsImageWatcherEnabled").checked=e.imageWatcherEnabled??t.imageWatcherEnabled??!1,document.getElementById("appSettingsTunnelEnabled").checked=e.tunnelEnabled??!1,this.loadTunnelStatus(),document.getElementById("appSettingsLocalEcho").checked=e.localEchoEnabled??MobileDetection.isTouchDevice(),document.getElementById("appSettingsTerminalWheelLocal").checked=e.terminalWheelLocalScrollback??t.terminalWheelLocalScrollback??!1,document.getElementById("appSettingsCjkInput").checked=e.cjkInputEnabled??t.cjkInputEnabled??!1,document.getElementById("appSettingsExtendedKeyboardBar").checked=e.extendedKeyboardBar??!1,document.getElementById("appSettingsTabTwoRows").checked=e.tabTwoRows??t.tabTwoRows??!1;const o=document.getElementById("appSettingsClaudeMode"),a=document.getElementById("allowedToolsRow");o.value=e.claudeMode||"dangerously-skip-permissions",document.getElementById("appSettingsAllowedTools").value=e.allowedTools||"",a.style.display=o.value==="allowedTools"?"":"none",o.onchange=()=>{a.style.display=o.value==="allowedTools"?"":"none"},document.getElementById("appSettingsCodexDangerouslyBypassApprovals").checked=e.codexDangerouslyBypassApprovals??!1,document.getElementById("appSettingsAgentTeams").checked=e.agentTeamsEnabled??!1,document.getElementById("appSettingsClaudeModel").value=e.claudeModel??"",document.getElementById("appSettingsOpusContext1m").checked=e.opusContext1mEnabled??!1,document.getElementById("appSettingsRemoteAutoReconnect").checked=e.remoteAutoReconnect??!0,document.getElementById("appSettingsThinkingEffort").value=e.thinkingEffort??"";const i=e.nice||{};document.getElementById("appSettingsNiceEnabled").checked=i.enabled??!1,document.getElementById("appSettingsNiceValue").value=i.niceValue??10,this.loadModelConfigForSettings();const l=this.notificationManager?.preferences||{};document.getElementById("appSettingsNotifEnabled").checked=l.enabled??!0,document.getElementById("appSettingsNotifBrowser").checked=l.browserNotifications??!1,document.getElementById("appSettingsNotifAudio").checked=l.audioAlerts??!1,document.getElementById("appSettingsNotifStuckMins").value=Math.round((l.stuckThresholdMs||6e5)/6e4),document.getElementById("appSettingsNotifCritical").checked=!l.muteCritical,document.getElementById("appSettingsNotifWarning").checked=!l.muteWarning,document.getElementById("appSettingsNotifInfo").checked=!l.muteInfo,document.getElementById("appSettingsPushEnabled").checked=!!this._pushSubscription,this._updatePushUI(!!this._pushSubscription);const c=l.eventTypes||{},d=c.permission_prompt||{};document.getElementById("eventPermissionEnabled").checked=d.enabled??!0,document.getElementById("eventPermissionBrowser").checked=d.browser??!0,document.getElementById("eventPermissionPush").checked=d.push??!1,document.getElementById("eventPermissionAudio").checked=d.audio??!0;const r=c.elicitation_dialog||{};document.getElementById("eventQuestionEnabled").checked=r.enabled??!0,document.getElementById("eventQuestionBrowser").checked=r.browser??!0,document.getElementById("eventQuestionPush").checked=r.push??!1,document.getElementById("eventQuestionAudio").checked=r.audio??!0;const u=c.idle_prompt||{};document.getElementById("eventIdleEnabled").checked=u.enabled??!0,document.getElementById("eventIdleBrowser").checked=u.browser??!0,document.getElementById("eventIdlePush").checked=u.push??!1,document.getElementById("eventIdleAudio").checked=u.audio??!1;const h=c.stop||{};document.getElementById("eventStopEnabled").checked=h.enabled??!0,document.getElementById("eventStopBrowser").checked=h.browser??!1,document.getElementById("eventStopPush").checked=h.push??!1,document.getElementById("eventStopAudio").checked=h.audio??!1;const p=c.respawn_cycle||{};document.getElementById("eventRespawnEnabled").checked=p.enabled??!0,document.getElementById("eventRespawnBrowser").checked=p.browser??!1,document.getElementById("eventRespawnPush").checked=p.push??!1,document.getElementById("eventRespawnAudio").checked=p.audio??!1;const f=c.ralph_complete||{};document.getElementById("eventRalphEnabled").checked=f.enabled??!0,document.getElementById("eventRalphBrowser").checked=f.browser??!0,document.getElementById("eventRalphPush").checked=f.push??!1,document.getElementById("eventRalphAudio").checked=f.audio??!0;const b=c.subagent_spawn||{};document.getElementById("eventSubagentEnabled").checked=b.enabled??!1,document.getElementById("eventSubagentBrowser").checked=b.browser??!1,document.getElementById("eventSubagentPush").checked=b.push??!1,document.getElementById("eventSubagentAudio").checked=b.audio??!1;const m=document.getElementById("notifPermissionStatus");if(m&&typeof Notification<"u"){const g=Notification.permission;m.textContent=g==="granted"?"\u2713":g==="denied"?"\u2717":"?",m.classList.remove("granted","denied"),g==="granted"?m.classList.add("granted"):g==="denied"&&m.classList.add("denied")}const S=VoiceInput._getDeepgramConfig();document.getElementById("voiceDeepgramKey").value=S.apiKey||"",document.getElementById("voiceLanguage").value=S.language||"en-US",document.getElementById("voiceKeyterms").value=S.keyterms||"refactor, endpoint, middleware, callback, async, regex, TypeScript, npm, API, deploy, config, linter, env, webhook, schema, CLI, JSON, CSS, DOM, SSE, backend, frontend, localhost, dependencies, repository, merge, rebase, diff, commit, com",document.getElementById("voiceInsertMode").value=S.insertMode||"direct";const E=document.getElementById("voiceDeepgramKey");E.type="password",document.getElementById("voiceKeyToggleBtn").textContent="Show";const v=VoiceInput.getActiveProviderName(),y=document.getElementById("voiceProviderStatus");y.textContent=v,y.className="voice-provider-status"+(v.startsWith("Deepgram")?" active":""),this._initUpdatesSection(),this.switchSettingsTab("settings-display");const w=document.getElementById("appSettingsModal");w.querySelectorAll(".modal-tabs .modal-tab-btn").forEach(g=>{g.onclick=()=>this.switchSettingsTab(g.dataset.tab)}),w.classList.add("active"),this.activeFocusTrap=new FocusTrap(w),this.activeFocusTrap.activate()},switchSettingsTab(e){const t=document.getElementById("appSettingsModal");t.querySelectorAll(".modal-tabs .modal-tab-btn").forEach(n=>{n.classList.toggle("active",n.dataset.tab===e)}),t.querySelectorAll(".modal-tab-content").forEach(n=>{n.classList.toggle("hidden",n.id!==e)}),e==="settings-shortcuts"&&this.renderShortcutSettingsList?.()},closeAppSettings(){document.getElementById("appSettingsModal").classList.remove("active"),this.activeFocusTrap&&(this.activeFocusTrap.deactivate(),this.activeFocusTrap=null)},_updatePhaseText(e){return{queued:"Queued\u2026",preparing:"Preparing\u2026",stashing:"Stashing local changes\u2026",fetching:"Fetching release\u2026",checkout:"Checking out release\u2026",installing:"Installing dependencies\u2026",building:"Building\u2026",restarting:"Restarting Codeman\u2026"}[e]||e},_initUpdatesSection(){const e=this.$("updateCurrentVersion");e&&(e.textContent=(this.$("versionDisplay")?.textContent||"").trim()||"\u2014");for(const t of["updateResult","updateActionRow","updateNotes","updateProgress"]){const n=this.$(t);n&&(n.style.display="none")}this._updateCheck=null},_setUpdateResult(e){const t=this.$("updateResult");t&&(t.style.display="block",t.innerHTML=e)},_setUpdateProgress(e){const t=this.$("updateProgress");t&&(t.style.display="block",t.innerHTML=e)},async checkForUpdate(){const e=this.$("updateCheckBtn");e&&(e.disabled=!0,e.textContent="Checking\u2026");const t=await this._apiJson("/api/system/update/check");e&&(e.disabled=!1,e.textContent="Check now");const n=this.$("updateActionRow"),s=this.$("updateNotes");if(n&&(n.style.display="none"),s&&(s.style.display="none"),!t){this._setUpdateResult("Could not check for updates. Try again later.");return}this._updateCheck=t;const o=this.$("updateCurrentVersion");if(o&&t.currentVersion&&(o.textContent=`v${t.currentVersion}`),t.installKind&&t.installKind!=="git"){this._setUpdateResult(`This install can't update itself (${escapeHtml(t.installKind)}). Update with <code>npm i -g aicodeman@latest</code>.`);return}if(t.selfUpdateEnabled===!1){this._setUpdateResult("In-app updates are disabled on this server (CODEMAN_DISABLE_SELF_UPDATE=1).");return}if(t.error&&!t.updateAvailable){this._setUpdateResult(escapeHtml(t.error));return}if(t.updateAvailable&&t.latestVersion){this._setUpdateResult(`Update available: <strong>v${escapeHtml(t.latestVersion)}</strong> &nbsp;(current v${escapeHtml(t.currentVersion||"")})`);const a=this.$("updateActionLabel");a&&(a.textContent=`Update to v${t.latestVersion}`),n&&(n.style.display="flex");const i=this.$("updateNowBtn");i&&(i.disabled=!1,i.textContent="Update now"),s&&t.notes&&(s.style.display="block",s.textContent=t.notes)}else this._setUpdateResult(`You're up to date (v${escapeHtml(t.currentVersion||"")}).`)},async startSelfUpdate(){const e=this._updateCheck?.latestVersion?`v${this._updateCheck.latestVersion}`:"the latest release";if(!confirm(`Update Codeman to ${e}? The server will restart and this page will reload.`))return;const t=this.$("updateNowBtn");t&&(t.disabled=!0,t.textContent="Starting\u2026");const n=await this._apiPost("/api/system/update",{});if(!n||!n.ok){let a="Failed to start the update.";try{const i=await n.json();typeof i?.error=="string"&&i.error&&(a=i.error)}catch{}this._setUpdateProgress(`<span style="color:var(--danger,#e5534b)">${escapeHtml(a)}</span>`),t&&(t.disabled=!1,t.textContent="Update now");return}const s=this.$("updateActionRow");s&&(s.style.display="none");const o=this.$("updateNotes");o&&(o.style.display="none"),this._setUpdateProgress("Starting update\u2026"),this._pollUpdateStatus()},_stopUpdatePolling(){this._updatePollTimer&&(clearInterval(this._updatePollTimer),this._updatePollTimer=null)},_pollUpdateStatus(){this._stopUpdatePolling();const e=new Set(["completed","completed-needs-manual-restart","failed","idle"]),t=async()=>{let n=null;try{const s=await fetch("/api/system/update/status");if(s.ok){const o=await s.json();n=o&&o.success===!0?o.data:o}}catch{}if(!n){this._setUpdateProgress("\u21BB Restarting Codeman\u2026");return}if(!e.has(n.phase)){const s=n.message&&n.message.trim()?n.message.trim():this._updatePhaseText(n.phase);let o="";n.startedAt&&(o=` <span style="color:var(--text-secondary)">\xB7 ${Math.max(0,Math.round((Date.now()-n.startedAt)/1e3))}s</span>`),this._setUpdateProgress(`<span class="tunnel-spinner"></span> ${escapeHtml(s)}${o}`);return}if(this._stopUpdatePolling(),n.phase==="completed"){let s=`<span style="color:var(--success,#3fb950)">\u2713 Updated to v${escapeHtml(n.toVersion||"")}. Reloading\u2026</span>`;n.stashRef&&(s+=`<br><span style="color:var(--text-secondary)">Local changes stashed as <code>${escapeHtml(n.stashRef)}</code> \u2014 run <code>git stash pop</code> to restore.</span>`),this._setUpdateProgress(s),setTimeout(()=>location.reload(),2500)}else if(n.phase==="completed-needs-manual-restart")this._setUpdateProgress(`Update staged. Restart Codeman to apply:<br><code>${escapeHtml(n.manualRestartCommand||"restart codeman web")}</code>`);else if(n.phase==="failed"){let s=`<span style="color:var(--danger,#e5534b)">\u2717 ${escapeHtml(n.message||"Update failed")}.</span>`;n.error&&(s+=`<br><span style="color:var(--text-secondary)">${escapeHtml(n.error)}</span>`),s+='<br><span style="color:var(--text-secondary)">The previous version is still running.</span>',n.stashRef&&(s+=`<br><span style="color:var(--text-secondary)">Local changes stashed as <code>${escapeHtml(n.stashRef)}</code>.</span>`),this._setUpdateProgress(s);const o=this.$("updateNowBtn"),a=this.$("updateActionRow");o&&(o.disabled=!1,o.textContent="Try again"),a&&(a.style.display="flex")}};t(),this._updatePollTimer=setInterval(t,1500)},async loadTunnelStatus(){try{const t=await(await fetch("/api/tunnel/status")).json(),n=t?.success===!0?t.data:t,s=n.running&&n.url;this._tunnelUrl=s?n.url:null,this._updateTunnelUrlDisplay(this._tunnelUrl),this._updateWelcomeTunnelBtn(!!s,this._tunnelUrl),this._updateTunnelIndicator(!!s)}catch{this._tunnelUrl=null,this._updateTunnelUrlDisplay(null),this._updateWelcomeTunnelBtn(!1),this._updateTunnelIndicator(!1)}},_updateTunnelUrlRow(e,t,n,s=""){const o=document.getElementById(e),a=document.getElementById(t);if(!(!o||!a))if(n){const i=n+s;o.style.display="",a.textContent=i,a.onclick=()=>{navigator.clipboard.writeText(i).then(()=>{this.showToast(`${s?"Upload":"Tunnel"} URL copied`,"success")})}}else o.style.display="none",a.textContent="",a.onclick=null},_updateTunnelUrlDisplay(e){this._updateTunnelUrlRow("tunnelUrlRow","tunnelUrlDisplay",e),this._updateTunnelUrlRow("tunnelUploadUrlRow","tunnelUploadUrlDisplay",e,"/upload.html")},showTunnelQR(){this.closeTunnelQR();const e=document.createElement("div");e.id="tunnelQrOverlay",e.style.cssText="position:fixed;inset:0;background:rgba(0,0,0,0.7);z-index:5000;display:flex;align-items:center;justify-content:center;cursor:pointer",e.onclick=n=>{n.target===e&&this.closeTunnelQR()};const t=document.createElement("div");t.style.cssText="background:var(--bg-card);border:1px solid var(--border);border-radius:12px;padding:24px;text-align:center;max-width:340px;width:90vw;box-shadow:var(--shadow-lg);cursor:default",t.innerHTML=`
1
+ "use strict";Object.assign(CodemanApp.prototype,{_onHookIdlePrompt(e){e.sessionId&&this.setPendingHook(e.sessionId,"idle_prompt"),this._notifySession(e.sessionId,"warning","hook-idle","Waiting for Input",e.message||"Claude is idle and waiting for a prompt")},_onHookPermissionPrompt(e){e.sessionId&&this.setPendingHook(e.sessionId,"permission_prompt");const t=e.tool?`${e.tool}${e.command?": "+e.command:e.file?": "+e.file:""}`:"";this._notifySession(e.sessionId,"critical","hook-permission","Permission Required",t||"Claude needs tool approval to continue")},_onHookElicitationDialog(e){e.sessionId&&this.setPendingHook(e.sessionId,"elicitation_dialog"),this._notifySession(e.sessionId,"critical","hook-elicitation","Question Asked",e.question||"Claude is asking a question and waiting for your answer")},_onHookStop(e){e.sessionId&&this.clearPendingHooks(e.sessionId),this._notifySession(e.sessionId,"info","hook-stop","Response Complete",e.reason||"Claude has finished responding")},_onHookTeammateIdle(e){const t=this.sessions.get(e.sessionId);this._notifySession(e.sessionId,"warning","hook-teammate-idle","Teammate Idle",`A teammate is idle in ${t?.name||e.sessionId}`)},_onHookTaskCompleted(e){const t=this.sessions.get(e.sessionId);this._notifySession(e.sessionId,"info","hook-task-completed","Task Completed",`A team task completed in ${t?.name||e.sessionId}`)},_onTunnelStarted(e){console.log("[Tunnel] Started:",e.url),this._tunnelUrl=e.url,this._dismissTunnelConnecting(),this._updateTunnelUrlDisplay(e.url),this._updateTunnelIndicator(!0),document.getElementById("welcomeOverlay")?.classList.contains("visible")?(this._updateWelcomeTunnelBtn(!0,e.url,!0),this.showToast("Tunnel active","success")):(this._updateWelcomeTunnelBtn(!0,e.url),this.showToast(`Tunnel active: ${e.url}`,"success"),this.showTunnelQR())},_onTunnelStopped(){console.log("[Tunnel] Stopped"),this._tunnelUrl=null,this._dismissTunnelConnecting(),this._updateTunnelUrlDisplay(null),this._updateWelcomeTunnelBtn(!1),this._updateTunnelIndicator(!1),this.closeTunnelPanel(),this.closeTunnelQR()},_onTunnelProgress(e){console.log("[Tunnel] Progress:",e.message);const t=document.getElementById("tunnelConnectingToast");t&&(t.innerHTML=`<span class="tunnel-spinner"></span> ${e.message}`);const n=document.getElementById("welcomeTunnelBtn");n?.classList.contains("connecting")&&(n.innerHTML=`<span class="tunnel-spinner"></span> ${e.message}`)},_onTunnelError(e){console.warn("[Tunnel] Error:",e.message),this._dismissTunnelConnecting(),this.showToast(`Tunnel error: ${e.message}`,"error");const t=document.getElementById("welcomeTunnelBtn");t&&(t.disabled=!1,t.classList.remove("connecting"))},_onTunnelQrRotated(e){if(e.svg){const t=document.getElementById("tunnelQrContainer");t&&(t.innerHTML=e.svg);const n=document.getElementById("welcomeQrInner");n&&(n.innerHTML=e.svg)}else this._refreshTunnelQrFromApi();this._resetQrCountdown()},_onTunnelQrRegenerated(e){if(e.svg){const t=document.getElementById("tunnelQrContainer");t&&(t.innerHTML=e.svg);const n=document.getElementById("welcomeQrInner");n&&(n.innerHTML=e.svg)}else this._refreshTunnelQrFromApi();this._resetQrCountdown()},_onTunnelQrAuthUsed(e){const n=(e.ua||"Unknown device").match(/Chrome|Firefox|Safari|Edge|Mobile/)?.[0]||"Browser";this.showToast(`Device authenticated via QR (${n}, ${e.ip}). Not you?`,"warning",{duration:1e4,action:{label:"Revoke All",onClick:()=>{fetch("/api/auth/revoke",{method:"POST",headers:{"Content-Type":"application/json"},body:"{}"}).then(()=>this.showToast("All sessions revoked","success")).catch(()=>this.showToast("Failed to revoke sessions","error"))}}})},registerServiceWorker(){"serviceWorker"in navigator&&navigator.serviceWorker.register("/sw.js").then(e=>{this._swRegistration=e,navigator.serviceWorker.addEventListener("message",t=>{if(t.data?.type==="notification-click"){const{sessionId:n}=t.data;n&&this.sessions.has(n)&&this.selectSession(n),window.focus()}}),e.pushManager.getSubscription().then(t=>{t&&(this._pushSubscription=t,this._updatePushUI(!0))})}).catch(()=>{})},async subscribeToPush(){if(!this._swRegistration){this.showToast("Service worker not available. HTTPS or localhost required.","error");return}try{const e=await this._apiJson("/api/push/vapid-key");if(!e)throw new Error("Failed to get VAPID key");const t=urlBase64ToUint8Array(e.publicKey),n=await this._swRegistration.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:t}),s=n.toJSON(),o=await this._apiJson("/api/push/subscribe",{method:"POST",body:{endpoint:s.endpoint,keys:s.keys,userAgent:navigator.userAgent,pushPreferences:this._buildPushPreferences()}});if(!o)throw new Error("Failed to register subscription");this._pushSubscription=n,this._pushSubscriptionId=o.id,localStorage.setItem("codeman-push-subscription-id",o.id),this._updatePushUI(!0),this.showToast("Push notifications enabled","success")}catch(e){this.showToast("Push subscription failed: "+(e.message||e),"error")}},async unsubscribeFromPush(){try{this._pushSubscription&&await this._pushSubscription.unsubscribe();const e=this._pushSubscriptionId||localStorage.getItem("codeman-push-subscription-id");e&&await fetch(`/api/push/subscribe/${e}`,{method:"DELETE"}).catch(()=>{}),this._pushSubscription=null,this._pushSubscriptionId=null,localStorage.removeItem("codeman-push-subscription-id"),this._updatePushUI(!1),this.showToast("Push notifications disabled","success")}catch(e){this.showToast("Failed to unsubscribe: "+(e.message||e),"error")}},async togglePushSubscription(){this._pushSubscription?await this.unsubscribeFromPush():await this.subscribeToPush()},async _syncPushPreferences(){const e=this._pushSubscriptionId||localStorage.getItem("codeman-push-subscription-id");if(e)try{await fetch(`/api/push/subscribe/${e}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({pushPreferences:this._buildPushPreferences()})})}catch{}},_buildPushPreferences(){const e={},t={"hook:permission_prompt":"eventPermissionPush","hook:elicitation_dialog":"eventQuestionPush","hook:idle_prompt":"eventIdlePush","hook:stop":"eventStopPush","respawn:blocked":"eventRespawnPush","session:ralphCompletionDetected":"eventRalphPush"};for(const[n,s]of Object.entries(t)){const o=document.getElementById(s);e[n]=o?o.checked:!0}return e["session:error"]=!0,e},_updatePushUI(e){const t=document.getElementById("pushSubscribeBtn"),n=document.getElementById("pushSubscriptionStatus");t&&(t.textContent=e?"Unsubscribe":"Subscribe"),n&&(n.textContent=e?"active":"off",n.classList.remove("granted","denied"),e&&n.classList.add("granted"))},openAppSettings(){const e=this.loadAppSettingsFromStorage();document.getElementById("appSettingsDisplayName").value=e.displayName||"Codeman",document.getElementById("appSettingsLanguage").value=e.language==="zh-CN"?"zh-CN":"en",document.getElementById("appSettingsClaudeMdPath").value=e.defaultClaudeMdPath||"",document.getElementById("appSettingsDefaultDir").value=e.defaultWorkingDir||"";const t=this.getDefaultSettings();document.getElementById("appSettingsRalphEnabled").checked=e.ralphTrackerEnabled??t.ralphTrackerEnabled??!1,document.getElementById("appSettingsShowFontControls").checked=e.showFontControls??t.showFontControls??!1,document.getElementById("appSettingsShowSystemStats").checked=e.showSystemStats??t.showSystemStats??!0,document.getElementById("appSettingsShowLifecycleLog").checked=e.showLifecycleLog??t.showLifecycleLog??!1,document.getElementById("appSettingsShowResponseViewer").checked=e.showResponseViewer??t.showResponseViewer??!1,document.getElementById("appSettingsShowFileViewerButton").checked=e.showFileViewerButton??t.showFileViewerButton??!0,document.getElementById("appSettingsShowAttachmentsButton").checked=e.showAttachmentsButton??t.showAttachmentsButton??!1,document.getElementById("appSettingsSkin").value=e.skin??t.skin??"daylight-blue",document.getElementById("appSettingsWebglRenderer").checked=e.webglRendererEnabled??t.webglRendererEnabled??!0;const n=document.getElementById("appSettingsWebglRendererItem");n&&(n.style.display=MobileDetection.getDeviceType()==="desktop"?"":"none"),document.getElementById("appSettingsShowMonitor").checked=e.showMonitor??t.showMonitor??!1,document.getElementById("appSettingsShowProjectInsights").checked=e.showProjectInsights??t.showProjectInsights??!1,document.getElementById("appSettingsShowFileBrowser").checked=e.showFileBrowser??t.showFileBrowser??!1,document.getElementById("appSettingsShowSubagents").checked=e.showSubagents??t.showSubagents??!1,document.getElementById("appSettingsShowUltracodeAgents").checked=e.showUltracodeAgents??t.showUltracodeAgents??!1,document.getElementById("appSettingsUltracodeFloatingWindows").checked=e.ultracodeFloatingWindows??t.ultracodeFloatingWindows??!1,document.getElementById("appSettingsShowMultiMonitorButton").checked=e.showMultiMonitorButton??t.showMultiMonitorButton??!1,document.getElementById("appSettingsShowPlanUsageLimits").checked=e.showPlanUsageLimits??t.showPlanUsageLimits??!1,document.getElementById("appSettingsShowRedrawButton").checked=e.showRedrawButton??t.showRedrawButton??!1,document.getElementById("appSettingsShowSessionButton").checked=e.showSessionButton??t.showSessionButton??!1,document.getElementById("appSettingsShowAwayDigestButton").checked=e.showAwayDigestButton??t.showAwayDigestButton??!1,document.getElementById("appSettingsShowCronButton").checked=e.showCronButton??t.showCronButton??!1;const s=document.getElementById("appSettingsGestureControlItem");s&&(s.style.display=window.__codemanGestureAvailable?"":"none"),document.getElementById("appSettingsGestureControl").checked=e.gestureControlEnabled??t.gestureControlEnabled??!1,document.getElementById("appSettingsSubagentTracking").checked=e.subagentTrackingEnabled??t.subagentTrackingEnabled??!0,document.getElementById("appSettingsSubagentActiveTabOnly").checked=e.subagentActiveTabOnly??t.subagentActiveTabOnly??!0,document.getElementById("appSettingsImageWatcherEnabled").checked=e.imageWatcherEnabled??t.imageWatcherEnabled??!1,document.getElementById("appSettingsTunnelEnabled").checked=e.tunnelEnabled??!1,this.loadTunnelStatus(),document.getElementById("appSettingsLocalEcho").checked=e.localEchoEnabled??MobileDetection.isTouchDevice(),document.getElementById("appSettingsTerminalWheelLocal").checked=e.terminalWheelLocalScrollback??t.terminalWheelLocalScrollback??!1,document.getElementById("appSettingsCjkInput").checked=e.cjkInputEnabled??t.cjkInputEnabled??!1,document.getElementById("appSettingsExtendedKeyboardBar").checked=e.extendedKeyboardBar??!1,document.getElementById("appSettingsTabTwoRows").checked=e.tabTwoRows??t.tabTwoRows??!1;const o=document.getElementById("appSettingsClaudeMode"),a=document.getElementById("allowedToolsRow");o.value=e.claudeMode||"dangerously-skip-permissions",document.getElementById("appSettingsAllowedTools").value=e.allowedTools||"",a.style.display=o.value==="allowedTools"?"":"none",o.onchange=()=>{a.style.display=o.value==="allowedTools"?"":"none"},document.getElementById("appSettingsCodexDangerouslyBypassApprovals").checked=e.codexDangerouslyBypassApprovals??!1,document.getElementById("appSettingsAgentTeams").checked=e.agentTeamsEnabled??!1,document.getElementById("appSettingsClaudeModel").value=e.claudeModel??"",document.getElementById("appSettingsOpusContext1m").checked=e.opusContext1mEnabled??!1,document.getElementById("appSettingsRemoteAutoReconnect").checked=e.remoteAutoReconnect??!0,document.getElementById("appSettingsThinkingEffort").value=e.thinkingEffort??"";const i=e.nice||{};document.getElementById("appSettingsNiceEnabled").checked=i.enabled??!1,document.getElementById("appSettingsNiceValue").value=i.niceValue??10,this.loadModelConfigForSettings();const l=this.notificationManager?.preferences||{};document.getElementById("appSettingsNotifEnabled").checked=l.enabled??!0,document.getElementById("appSettingsNotifBrowser").checked=l.browserNotifications??!1,document.getElementById("appSettingsNotifAudio").checked=l.audioAlerts??!1,document.getElementById("appSettingsNotifStuckMins").value=Math.round((l.stuckThresholdMs||6e5)/6e4),document.getElementById("appSettingsNotifCritical").checked=!l.muteCritical,document.getElementById("appSettingsNotifWarning").checked=!l.muteWarning,document.getElementById("appSettingsNotifInfo").checked=!l.muteInfo,document.getElementById("appSettingsPushEnabled").checked=!!this._pushSubscription,this._updatePushUI(!!this._pushSubscription);const c=l.eventTypes||{},d=c.permission_prompt||{};document.getElementById("eventPermissionEnabled").checked=d.enabled??!0,document.getElementById("eventPermissionBrowser").checked=d.browser??!0,document.getElementById("eventPermissionPush").checked=d.push??!1,document.getElementById("eventPermissionAudio").checked=d.audio??!0;const r=c.elicitation_dialog||{};document.getElementById("eventQuestionEnabled").checked=r.enabled??!0,document.getElementById("eventQuestionBrowser").checked=r.browser??!0,document.getElementById("eventQuestionPush").checked=r.push??!1,document.getElementById("eventQuestionAudio").checked=r.audio??!0;const u=c.idle_prompt||{};document.getElementById("eventIdleEnabled").checked=u.enabled??!0,document.getElementById("eventIdleBrowser").checked=u.browser??!0,document.getElementById("eventIdlePush").checked=u.push??!1,document.getElementById("eventIdleAudio").checked=u.audio??!1;const h=c.stop||{};document.getElementById("eventStopEnabled").checked=h.enabled??!0,document.getElementById("eventStopBrowser").checked=h.browser??!1,document.getElementById("eventStopPush").checked=h.push??!1,document.getElementById("eventStopAudio").checked=h.audio??!1;const p=c.respawn_cycle||{};document.getElementById("eventRespawnEnabled").checked=p.enabled??!0,document.getElementById("eventRespawnBrowser").checked=p.browser??!1,document.getElementById("eventRespawnPush").checked=p.push??!1,document.getElementById("eventRespawnAudio").checked=p.audio??!1;const f=c.ralph_complete||{};document.getElementById("eventRalphEnabled").checked=f.enabled??!0,document.getElementById("eventRalphBrowser").checked=f.browser??!0,document.getElementById("eventRalphPush").checked=f.push??!1,document.getElementById("eventRalphAudio").checked=f.audio??!0;const b=c.subagent_spawn||{};document.getElementById("eventSubagentEnabled").checked=b.enabled??!1,document.getElementById("eventSubagentBrowser").checked=b.browser??!1,document.getElementById("eventSubagentPush").checked=b.push??!1,document.getElementById("eventSubagentAudio").checked=b.audio??!1;const m=document.getElementById("notifPermissionStatus");if(m&&typeof Notification<"u"){const g=Notification.permission;m.textContent=g==="granted"?"\u2713":g==="denied"?"\u2717":"?",m.classList.remove("granted","denied"),g==="granted"?m.classList.add("granted"):g==="denied"&&m.classList.add("denied")}const S=VoiceInput._getDeepgramConfig();document.getElementById("voiceDeepgramKey").value=S.apiKey||"",document.getElementById("voiceLanguage").value=S.language||"en-US",document.getElementById("voiceKeyterms").value=S.keyterms||"refactor, endpoint, middleware, callback, async, regex, TypeScript, npm, API, deploy, config, linter, env, webhook, schema, CLI, JSON, CSS, DOM, SSE, backend, frontend, localhost, dependencies, repository, merge, rebase, diff, commit, com",document.getElementById("voiceInsertMode").value=S.insertMode||"direct";const E=document.getElementById("voiceDeepgramKey");E.type="password",document.getElementById("voiceKeyToggleBtn").textContent="Show";const v=VoiceInput.getActiveProviderName(),y=document.getElementById("voiceProviderStatus");y.textContent=v,y.className="voice-provider-status"+(v.startsWith("Deepgram")?" active":""),this._initUpdatesSection(),this.switchSettingsTab("settings-display");const w=document.getElementById("appSettingsModal");w.querySelectorAll(".modal-tabs .modal-tab-btn").forEach(g=>{g.onclick=()=>this.switchSettingsTab(g.dataset.tab)}),w.classList.add("active"),this.activeFocusTrap=new FocusTrap(w),this.activeFocusTrap.activate()},switchSettingsTab(e){const t=document.getElementById("appSettingsModal");t.querySelectorAll(".modal-tabs .modal-tab-btn").forEach(n=>{n.classList.toggle("active",n.dataset.tab===e)}),t.querySelectorAll(".modal-tab-content").forEach(n=>{n.classList.toggle("hidden",n.id!==e)}),e==="settings-shortcuts"&&this.renderShortcutSettingsList?.()},closeAppSettings(){document.getElementById("appSettingsModal").classList.remove("active"),this.activeFocusTrap&&(this.activeFocusTrap.deactivate(),this.activeFocusTrap=null)},_updatePhaseText(e){return{queued:"Queued\u2026",preparing:"Preparing\u2026",stashing:"Stashing local changes\u2026",fetching:"Fetching release\u2026",checkout:"Checking out release\u2026",installing:"Installing dependencies\u2026",building:"Building\u2026",restarting:"Restarting Codeman\u2026"}[e]||e},_initUpdatesSection(){const e=this.$("updateCurrentVersion");e&&(e.textContent=(this.$("versionDisplay")?.textContent||"").trim()||"\u2014");for(const t of["updateResult","updateActionRow","updateNotes","updateProgress"]){const n=this.$(t);n&&(n.style.display="none")}this._updateCheck=null},_setUpdateResult(e){const t=this.$("updateResult");t&&(t.style.display="block",t.innerHTML=e)},_setUpdateProgress(e){const t=this.$("updateProgress");t&&(t.style.display="block",t.innerHTML=e)},async checkForUpdate(){const e=this.$("updateCheckBtn");e&&(e.disabled=!0,e.textContent="Checking\u2026");const t=await this._apiJson("/api/system/update/check");e&&(e.disabled=!1,e.textContent="Check now");const n=this.$("updateActionRow"),s=this.$("updateNotes");if(n&&(n.style.display="none"),s&&(s.style.display="none"),!t){this._setUpdateResult("Could not check for updates. Try again later.");return}this._updateCheck=t;const o=this.$("updateCurrentVersion");if(o&&t.currentVersion&&(o.textContent=`v${t.currentVersion}`),t.installKind&&t.installKind!=="git"){this._setUpdateResult(`This install can't update itself (${escapeHtml(t.installKind)}). Update with <code>npm i -g aicodeman@latest</code>.`);return}if(t.selfUpdateEnabled===!1){this._setUpdateResult("In-app updates are disabled on this server (CODEMAN_DISABLE_SELF_UPDATE=1).");return}if(t.error&&!t.updateAvailable){this._setUpdateResult(escapeHtml(t.error));return}if(t.updateAvailable&&t.latestVersion){this._setUpdateResult(`Update available: <strong>v${escapeHtml(t.latestVersion)}</strong> &nbsp;(current v${escapeHtml(t.currentVersion||"")})`);const a=this.$("updateActionLabel");a&&(a.textContent=`Update to v${t.latestVersion}`),n&&(n.style.display="flex");const i=this.$("updateNowBtn");i&&(i.disabled=!1,i.textContent="Update now"),s&&t.notes&&(s.style.display="block",s.textContent=t.notes)}else this._setUpdateResult(`You're up to date (v${escapeHtml(t.currentVersion||"")}).`)},async startSelfUpdate(){const e=this._updateCheck?.latestVersion?`v${this._updateCheck.latestVersion}`:"the latest release";if(!confirm(`Update Codeman to ${e}? The server will restart and this page will reload.`))return;const t=this.$("updateNowBtn");t&&(t.disabled=!0,t.textContent="Starting\u2026");const n=await this._apiPost("/api/system/update",{});if(!n||!n.ok){let a="Failed to start the update.";try{const i=await n.json();typeof i?.error=="string"&&i.error&&(a=i.error)}catch{}this._setUpdateProgress(`<span style="color:var(--danger,#e5534b)">${escapeHtml(a)}</span>`),t&&(t.disabled=!1,t.textContent="Update now");return}const s=this.$("updateActionRow");s&&(s.style.display="none");const o=this.$("updateNotes");o&&(o.style.display="none"),this._setUpdateProgress("Starting update\u2026"),this._pollUpdateStatus()},_stopUpdatePolling(){this._updatePollTimer&&(clearInterval(this._updatePollTimer),this._updatePollTimer=null)},_pollUpdateStatus(){this._stopUpdatePolling();const e=new Set(["completed","completed-needs-manual-restart","failed","idle"]),t=async()=>{let n=null;try{const s=await fetch("/api/system/update/status");if(s.ok){const o=await s.json();n=o&&o.success===!0?o.data:o}}catch{}if(!n){this._setUpdateProgress("\u21BB Restarting Codeman\u2026");return}if(!e.has(n.phase)){const s=n.message&&n.message.trim()?n.message.trim():this._updatePhaseText(n.phase);let o="";n.startedAt&&(o=` <span style="color:var(--text-secondary)">\xB7 ${Math.max(0,Math.round((Date.now()-n.startedAt)/1e3))}s</span>`),this._setUpdateProgress(`<span class="tunnel-spinner"></span> ${escapeHtml(s)}${o}`);return}if(this._stopUpdatePolling(),n.phase==="completed"){let s=`<span style="color:var(--success,#3fb950)">\u2713 Updated to v${escapeHtml(n.toVersion||"")}. Reloading\u2026</span>`;n.stashRef&&(s+=`<br><span style="color:var(--text-secondary)">Local changes stashed as <code>${escapeHtml(n.stashRef)}</code> \u2014 run <code>git stash pop</code> to restore.</span>`),this._setUpdateProgress(s),setTimeout(()=>location.reload(),2500)}else if(n.phase==="completed-needs-manual-restart")this._setUpdateProgress(`Update staged. Restart Codeman to apply:<br><code>${escapeHtml(n.manualRestartCommand||"restart codeman web")}</code>`);else if(n.phase==="failed"){let s=`<span style="color:var(--danger,#e5534b)">\u2717 ${escapeHtml(n.message||"Update failed")}.</span>`;n.error&&(s+=`<br><span style="color:var(--text-secondary)">${escapeHtml(n.error)}</span>`),s+='<br><span style="color:var(--text-secondary)">The previous version is still running.</span>',n.stashRef&&(s+=`<br><span style="color:var(--text-secondary)">Local changes stashed as <code>${escapeHtml(n.stashRef)}</code>.</span>`),this._setUpdateProgress(s);const o=this.$("updateNowBtn"),a=this.$("updateActionRow");o&&(o.disabled=!1,o.textContent="Try again"),a&&(a.style.display="flex")}};t(),this._updatePollTimer=setInterval(t,1500)},async loadTunnelStatus(){try{const t=await(await fetch("/api/tunnel/status")).json(),n=t?.success===!0?t.data:t,s=n.running&&n.url;this._tunnelUrl=s?n.url:null,this._updateTunnelUrlDisplay(this._tunnelUrl),this._updateWelcomeTunnelBtn(!!s,this._tunnelUrl),this._updateTunnelIndicator(!!s)}catch{this._tunnelUrl=null,this._updateTunnelUrlDisplay(null),this._updateWelcomeTunnelBtn(!1),this._updateTunnelIndicator(!1)}},_updateTunnelUrlRow(e,t,n,s=""){const o=document.getElementById(e),a=document.getElementById(t);if(!(!o||!a))if(n){const i=n+s;o.style.display="",a.textContent=i,a.onclick=()=>{navigator.clipboard.writeText(i).then(()=>{this.showToast(`${s?"Upload":"Tunnel"} URL copied`,"success")})}}else o.style.display="none",a.textContent="",a.onclick=null},_updateTunnelUrlDisplay(e){this._updateTunnelUrlRow("tunnelUrlRow","tunnelUrlDisplay",e),this._updateTunnelUrlRow("tunnelUploadUrlRow","tunnelUploadUrlDisplay",e,"/upload.html")},showTunnelQR(){this.closeTunnelQR();const e=document.createElement("div");e.id="tunnelQrOverlay",e.style.cssText="position:fixed;inset:0;background:rgba(0,0,0,0.7);z-index:5000;display:flex;align-items:center;justify-content:center;cursor:pointer",e.onclick=n=>{n.target===e&&this.closeTunnelQR()};const t=document.createElement("div");t.style.cssText="background:var(--bg-card);border:1px solid var(--border);border-radius:12px;padding:24px;text-align:center;max-width:340px;width:90vw;box-shadow:var(--shadow-lg);cursor:default",t.innerHTML=`
2
2
  <div style="font-size:14px;font-weight:600;color:var(--text-primary);margin-bottom:16px">Scan to connect</div>
3
3
  <div id="tunnelQrContainer" style="background:#fff;border-radius:8px;padding:16px;display:inline-block">
4
4
  <div style="color:#666;font-size:12px">Loading...</div>
@@ -58,7 +58,7 @@ Enable the unauthenticated public tunnel anyway?`))return this._dismissTunnelCon
58
58
  <td style="padding:3px 8px;color:#e0e0e0" title="${d.sessionId}">${h}</td>
59
59
  <td style="padding:3px 8px;color:#aaa">${d.reason||""}</td>
60
60
  <td style="padding:3px 8px;color:#666">${p.join(", ")}</td>
61
- </tr>`}).join("")}catch(s){console.error("Failed to load lifecycle log:",s)}},async saveAppSettings(){const e=this.loadAppSettingsFromStorage(),t=(e.gestureControlEnabled??!1)===!0,n=(e.webglRendererEnabled??!0)===!0,s={displayName:window.CodemanI18n?.normalizeDisplayName(document.getElementById("appSettingsDisplayName").value)||"Codeman",language:window.CodemanI18n?.normalizeLanguage(document.getElementById("appSettingsLanguage").value)||"en",defaultClaudeMdPath:document.getElementById("appSettingsClaudeMdPath").value.trim(),defaultWorkingDir:document.getElementById("appSettingsDefaultDir").value.trim(),ralphTrackerEnabled:document.getElementById("appSettingsRalphEnabled").checked,showFontControls:document.getElementById("appSettingsShowFontControls").checked,showSystemStats:document.getElementById("appSettingsShowSystemStats").checked,showLifecycleLog:document.getElementById("appSettingsShowLifecycleLog").checked,showResponseViewer:document.getElementById("appSettingsShowResponseViewer").checked,showFileViewerButton:document.getElementById("appSettingsShowFileViewerButton").checked,showAttachmentsButton:document.getElementById("appSettingsShowAttachmentsButton").checked,showMonitor:document.getElementById("appSettingsShowMonitor").checked,showProjectInsights:document.getElementById("appSettingsShowProjectInsights").checked,showFileBrowser:document.getElementById("appSettingsShowFileBrowser").checked,showSubagents:document.getElementById("appSettingsShowSubagents").checked,showUltracodeAgents:document.getElementById("appSettingsShowUltracodeAgents").checked,ultracodeFloatingWindows:document.getElementById("appSettingsUltracodeFloatingWindows").checked,showMultiMonitorButton:document.getElementById("appSettingsShowMultiMonitorButton").checked,showPlanUsageLimits:document.getElementById("appSettingsShowPlanUsageLimits").checked,showRedrawButton:document.getElementById("appSettingsShowRedrawButton").checked,showSessionButton:document.getElementById("appSettingsShowSessionButton").checked,showAwayDigestButton:document.getElementById("appSettingsShowAwayDigestButton").checked,showCronButton:document.getElementById("appSettingsShowCronButton").checked,gestureControlEnabled:document.getElementById("appSettingsGestureControl").checked,subagentTrackingEnabled:document.getElementById("appSettingsSubagentTracking").checked,subagentActiveTabOnly:document.getElementById("appSettingsSubagentActiveTabOnly").checked,imageWatcherEnabled:document.getElementById("appSettingsImageWatcherEnabled").checked,tunnelEnabled:document.getElementById("appSettingsTunnelEnabled").checked,localEchoEnabled:document.getElementById("appSettingsLocalEcho").checked,terminalWheelLocalScrollback:document.getElementById("appSettingsTerminalWheelLocal").checked,cjkInputEnabled:document.getElementById("appSettingsCjkInput").checked,webglRendererEnabled:document.getElementById("appSettingsWebglRenderer").checked,extendedKeyboardBar:document.getElementById("appSettingsExtendedKeyboardBar").checked,tabTwoRows:document.getElementById("appSettingsTabTwoRows").checked,skin:document.getElementById("appSettingsSkin").value,claudeMode:document.getElementById("appSettingsClaudeMode").value,allowedTools:document.getElementById("appSettingsAllowedTools").value.trim(),codexDangerouslyBypassApprovals:document.getElementById("appSettingsCodexDangerouslyBypassApprovals").checked,agentTeamsEnabled:document.getElementById("appSettingsAgentTeams").checked,claudeModel:document.getElementById("appSettingsClaudeModel").value,opusContext1mEnabled:document.getElementById("appSettingsOpusContext1m").checked,remoteAutoReconnect:document.getElementById("appSettingsRemoteAutoReconnect").checked,thinkingEffort:document.getElementById("appSettingsThinkingEffort").value,nice:{enabled:document.getElementById("appSettingsNiceEnabled").checked,niceValue:parseInt(document.getElementById("appSettingsNiceValue").value)||10}};if(e.showTokenCount!==void 0&&(s.showTokenCount=e.showTokenCount),e.showCost!==void 0&&(s.showCost=e.showCost),e.shortcutOverrides!==void 0&&(s.shortcutOverrides=e.shortcutOverrides),this.saveAppSettingsToStorage(s),this._updateLocalEchoState(),!n&&s.webglRendererEnabled)try{localStorage.removeItem("codeman-webgl-disabled")}catch{}const o={apiKey:document.getElementById("voiceDeepgramKey").value.trim(),language:document.getElementById("voiceLanguage").value,keyterms:document.getElementById("voiceKeyterms").value.trim(),insertMode:document.getElementById("voiceInsertMode").value};VoiceInput._saveDeepgramConfig(o);const a={enabled:document.getElementById("appSettingsNotifEnabled").checked,browserNotifications:document.getElementById("appSettingsNotifBrowser").checked,audioAlerts:document.getElementById("appSettingsNotifAudio").checked,stuckThresholdMs:(parseInt(document.getElementById("appSettingsNotifStuckMins").value)||10)*6e4,muteCritical:!document.getElementById("appSettingsNotifCritical").checked,muteWarning:!document.getElementById("appSettingsNotifWarning").checked,muteInfo:!document.getElementById("appSettingsNotifInfo").checked,eventTypes:{permission_prompt:{enabled:document.getElementById("eventPermissionEnabled").checked,browser:document.getElementById("eventPermissionBrowser").checked,push:document.getElementById("eventPermissionPush").checked,audio:document.getElementById("eventPermissionAudio").checked},elicitation_dialog:{enabled:document.getElementById("eventQuestionEnabled").checked,browser:document.getElementById("eventQuestionBrowser").checked,push:document.getElementById("eventQuestionPush").checked,audio:document.getElementById("eventQuestionAudio").checked},idle_prompt:{enabled:document.getElementById("eventIdleEnabled").checked,browser:document.getElementById("eventIdleBrowser").checked,push:document.getElementById("eventIdlePush").checked,audio:document.getElementById("eventIdleAudio").checked},stop:{enabled:document.getElementById("eventStopEnabled").checked,browser:document.getElementById("eventStopBrowser").checked,push:document.getElementById("eventStopPush").checked,audio:document.getElementById("eventStopAudio").checked},session_error:{enabled:!0,browser:this.notificationManager?.preferences?.eventTypes?.session_error?.browser??!0,push:this.notificationManager?.preferences?.eventTypes?.session_error?.push??!1,audio:!1},respawn_cycle:{enabled:document.getElementById("eventRespawnEnabled").checked,browser:document.getElementById("eventRespawnBrowser").checked,push:document.getElementById("eventRespawnPush").checked,audio:document.getElementById("eventRespawnAudio").checked},token_milestone:{enabled:!0,browser:!1,push:!1,audio:!1},ralph_complete:{enabled:document.getElementById("eventRalphEnabled").checked,browser:document.getElementById("eventRalphBrowser").checked,push:document.getElementById("eventRalphPush").checked,audio:document.getElementById("eventRalphAudio").checked},subagent_spawn:{enabled:document.getElementById("eventSubagentEnabled").checked,browser:document.getElementById("eventSubagentBrowser").checked,push:document.getElementById("eventSubagentPush").checked,audio:document.getElementById("eventSubagentAudio").checked},subagent_complete:{enabled:document.getElementById("eventSubagentEnabled").checked,browser:document.getElementById("eventSubagentBrowser").checked,push:document.getElementById("eventSubagentPush").checked,audio:document.getElementById("eventSubagentAudio").checked}},_version:4};this.notificationManager&&(this.notificationManager.preferences=a,this.notificationManager.savePreferences()),this._syncPushPreferences(),this.applyHeaderVisibilitySettings(),this.applySkin(),this.applyLocalization(),this.applyTabWrapSettings(),this._updateTokensImmediate(),this.applyMonitorVisibility(),this.renderProjectInsightsPanel(),this.updateSubagentWindowVisibility(),this._updateCjkInputState(),KeyboardAccessoryBar.setMode(s.extendedKeyboardBar?"extended":"simple");const{localEchoEnabled:i,cjkInputEnabled:l,extendedKeyboardBar:c,skin:d,language:r,showPlanUsageLimits:u,showAttachmentsButton:h,showFileViewerButton:p,webglRendererEnabled:f,terminalWheelLocalScrollback:b,showSessionButton:m,showAwayDigestButton:S,showCronButton:E,...v}=s;try{const y=await this._apiPut("/api/settings",{...v,...s.showPlanUsageLimits?{statusLineTelemetry:!0}:{},notificationPreferences:a,voiceSettings:o});if(s.tunnelEnabled&&await this._handleTunnelEnableRefusal(y)){s.tunnelEnabled=!1,this.saveAppSettingsToStorage(s);const w=document.getElementById("appSettingsTunnelEnabled");w&&(w.checked=!1),this.closeAppSettings();return}await this.saveModelConfigFromSettings(),this.showToast("Settings saved","success"),s.tunnelEnabled&&this.showToast("Tunnel starting \u2014 QR code will appear when ready...","info")}catch{this.showToast("Settings saved locally","warning")}this.closeAppSettings(),s.gestureControlEnabled!==t&&(this.showToast(s.gestureControlEnabled?"Enabling gesture control \u2014 reloading\u2026":"Disabling gesture control \u2014 reloading\u2026","info"),setTimeout(()=>location.reload(),400))},async loadModelConfigForSettings(){try{const t=await(await fetch("/api/execution/model-config")).json();if(t.success&&t.data){const n=t.data,s=document.getElementById("appSettingsDefaultModel");s&&(s.value=n.defaultModel||"");const o=document.getElementById("appSettingsShowModelRecommendations");o&&(o.checked=n.showRecommendations??!0);const a=n.agentTypeOverrides||{},i=document.getElementById("appSettingsModelExplore"),l=document.getElementById("appSettingsModelImplement"),c=document.getElementById("appSettingsModelTest"),d=document.getElementById("appSettingsModelReview");i&&(i.value=a.explore||""),l&&(l.value=a.implement||""),c&&(c.value=a.test||""),d&&(d.value=a.review||"")}}catch(e){console.warn("Failed to load model config:",e)}},async saveModelConfigFromSettings(){const e=document.getElementById("appSettingsDefaultModel"),t=document.getElementById("appSettingsShowModelRecommendations"),n=document.getElementById("appSettingsModelExplore"),s=document.getElementById("appSettingsModelImplement"),o=document.getElementById("appSettingsModelTest"),a=document.getElementById("appSettingsModelReview"),i={};n?.value&&(i.explore=n.value),s?.value&&(i.implement=s.value),o?.value&&(i.test=o.value),a?.value&&(i.review=a.value);const l={defaultModel:e?.value||"",showRecommendations:t?.checked??!0,agentTypeOverrides:i};try{await fetch("/api/execution/model-config",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)})}catch(c){console.warn("Failed to save model config:",c)}},isRalphTrackerEnabledByDefault(){return this.loadAppSettingsFromStorage().ralphTrackerEnabled??!1},getSettingsStorageKey(){return MobileDetection.isHandheldDevice?.()??MobileDetection.getDeviceType()==="mobile"?"codeman-app-settings-mobile":"codeman-app-settings"},getDefaultSettings(){return MobileDetection.isHandheldDevice?.()??MobileDetection.getDeviceType()==="mobile"?{showFontControls:!1,showSystemStats:!1,showTokenCount:!1,showCost:!1,showMonitor:!1,showProjectInsights:!1,showFileBrowser:!1,showSubagents:!1,showUltracodeAgents:!1,ultracodeFloatingWindows:!1,showMultiMonitorButton:!1,showPlanUsageLimits:!1,showAttachmentsButton:!1,showFileViewerButton:!1,showRedrawButton:!1,showSessionButton:!1,showAwayDigestButton:!1,showCronButton:!1,remoteAutoReconnect:!0,gestureControlEnabled:!1,subagentTrackingEnabled:!0,subagentActiveTabOnly:!0,imageWatcherEnabled:!1,ralphTrackerEnabled:!1,tabTwoRows:!1,cjkInputEnabled:!1,terminalWheelLocalScrollback:!1,webglRendererEnabled:!1,skin:"daylight-blue"}:{}},loadAppSettingsFromStorage(){if(this._cachedAppSettings)return this._cachedAppSettings;try{const e=this.getSettingsStorageKey(),t=localStorage.getItem(e);if(t)return this._cachedAppSettings=JSON.parse(t),this._cachedAppSettings}catch(e){console.error("Failed to load app settings:",e)}return this._cachedAppSettings=this.getDefaultSettings(),this._cachedAppSettings},saveAppSettingsToStorage(e){this._cachedAppSettings=e;try{const t=this.getSettingsStorageKey();localStorage.setItem(t,JSON.stringify(e))}catch(t){console.error("Failed to save app settings:",t)}},applySkin(){const e=this.loadAppSettingsFromStorage(),t=this.getDefaultSettings(),n=e.skin??t.skin??"daylight-blue";document.documentElement.setAttribute("data-skin",n),window.__codemanSkin=n;try{localStorage.setItem("codeman:skin",n)}catch{}typeof this.applyTerminalSkin=="function"&&this.applyTerminalSkin(n)},applyLocalization(){const e=this.loadAppSettingsFromStorage();window.CodemanI18n?.configure({language:e.language,displayName:e.displayName})&&this.notificationManager&&(this.notificationManager.originalTitle=document.title)},applyHeaderVisibilitySettings(){const e=this.loadAppSettingsFromStorage(),t=this.getDefaultSettings(),n=MobileDetection.getDeviceType()!=="desktop",s=n?!1:e.showFontControls??t.showFontControls??!1,o=n?!1:e.showSystemStats??t.showSystemStats??!0,a=n?!1:e.showTokenCount??t.showTokenCount??!0,i=document.querySelector(".header-font-controls"),l=document.getElementById("headerSystemStats"),c=document.getElementById("headerTokens");i&&(i.style.display=s?"":"none"),l&&(l.style.display=o?"":"none"),c&&(c.style.display=a?"":"none");const d=e.showLifecycleLog??t.showLifecycleLog??!0,r=document.querySelector(".btn-lifecycle-log");r&&(r.style.display=d?"":"none");const u=e.showResponseViewer??t.showResponseViewer??!1,h=document.querySelector(".btn-response-viewer-header");h&&h.classList.toggle("btn-response-viewer-header--hidden",!u);const p=e.showAttachmentsButton??t.showAttachmentsButton??!1,f=document.getElementById("attachmentsHistoryBtn");f&&f.classList.toggle("btn-attachments-history--hidden",!p);const b=e.showFileViewerButton??t.showFileViewerButton??!1,m=document.querySelector(".btn-file-viewer");m&&m.classList.toggle("btn-file-viewer--hidden",!b);const S=e.showMultiMonitorButton??t.showMultiMonitorButton??!1,E=document.querySelector(".btn-multimonitor");E&&E.classList.toggle("btn-multimonitor--hidden",!S);const v=e.showUltracodeAgents??t.showUltracodeAgents??!1,y=document.querySelector(".btn-ultracode-agents");y&&y.classList.toggle("btn-ultracode-agents--hidden",!v);const w=e.showPlanUsageLimits??t.showPlanUsageLimits??!1,g=document.getElementById("planUsageChip");g&&g.classList.toggle("header-plan-usage--hidden",!w);const P=e.showRedrawButton??t.showRedrawButton??!1,B=document.querySelector(".btn-redraw-terminal");B&&B.classList.toggle("btn-redraw-terminal--hidden",!P);const L=e.showSessionButton??t.showSessionButton??!1,I=document.querySelector(".btn-session-manager");I&&I.classList.toggle("btn-session-manager--hidden",!L);const A=e.showAwayDigestButton??t.showAwayDigestButton??!1,T=document.querySelector(".btn-away-digest");T&&T.classList.toggle("btn-away-digest--hidden",!A);const M=e.showCronButton??t.showCronButton??!1,k=document.querySelector(".btn-cron");k&&k.classList.toggle("btn-cron--hidden",!M);const _=document.querySelector(".btn-notifications");if(_&&(_.style.display="none"),!(this.notificationManager?.preferences?.enabled??!0)){const C=document.getElementById("notifDrawer");C&&C.classList.remove("open")}},applyTabWrapSettings(){const e=this.loadAppSettingsFromStorage(),t=this.getDefaultSettings(),s=MobileDetection.getDeviceType()==="desktop"?e.tabTwoRows??t.tabTwoRows??!1:!1,o=this._tallTabsEnabled;this._tallTabsEnabled=s;const a=document.getElementById("sessionTabs");a&&(a.classList.toggle("tabs-two-rows",s),a.classList.toggle("tabs-show-folder",s)),o!==void 0&&o!==s&&this._fullRenderSessionTabs()},applyMonitorVisibility(){const e=this.loadAppSettingsFromStorage(),t=this.getDefaultSettings(),n=e.showMonitor??t.showMonitor??!1,s=e.showSubagents??t.showSubagents??!1,o=e.showFileBrowser??t.showFileBrowser??!1,a=document.getElementById("monitorPanel");a&&(a.style.display=n?"":"none",n?a.classList.add("open"):a.classList.remove("open"));const i=document.getElementById("subagentsPanel");i&&(s?i.classList.remove("hidden"):i.classList.add("hidden"));const l=e.showUltracodeAgents??t.showUltracodeAgents??!1,c=document.getElementById("ultracodeAgentsPanel");c&&(l?c.classList.remove("hidden"):(c.classList.remove("open"),c.classList.add("hidden"))),e.ultracodeFloatingWindows??t.ultracodeFloatingWindows??!1?typeof this.syncAllUltracodeFloatingWindows=="function"&&this.syncAllUltracodeFloatingWindows():typeof this.removeAllUltracodeWindows=="function"&&this.removeAllUltracodeWindows();const r=document.getElementById("fileBrowserPanel");if(r)if(o&&this.activeSessionId){if(r.classList.add("visible"),this.loadFileBrowser(this.activeSessionId),!this.fileBrowserDragListeners){const u=r.querySelector(".file-browser-header");if(u){const h=()=>{if(!r.style.left){const p=r.getBoundingClientRect();r.style.left=`${p.left}px`,r.style.top=`${p.top}px`,r.style.right="auto"}};u.addEventListener("mousedown",h),u.addEventListener("touchstart",h,{passive:!0}),this.fileBrowserDragListeners=this.makeWindowDraggable(r,u),this.fileBrowserDragListeners._onFirstDrag=h}}}else r.classList.remove("visible")},closeMonitor(){const e=document.getElementById("monitorPanel");e&&(e.classList.remove("open"),e.style.display="none");const t=this.loadAppSettingsFromStorage();t.showMonitor=!1,this.saveAppSettingsToStorage(t)},closeSubagentsPanel(){const e=document.getElementById("subagentsPanel");e&&(e.classList.remove("open"),e.classList.add("hidden")),this.subagentPanelVisible=!1;const t=this.loadAppSettingsFromStorage();t.showSubagents=!1,this.saveAppSettingsToStorage(t)},async clearAllSubagents(){const e=this.subagents.size;if(e===0){this.showToast("No subagents to clear","info");return}if(confirm(`Clear all ${e} tracked subagent(s)? This removes them from the UI but does not affect running processes.`))try{const n=await(await fetch("/api/subagents",{method:"DELETE"})).json();n.success?(this.subagents.clear(),this.subagentActivity.clear(),this.subagentToolResults.clear(),this.cleanupAllFloatingWindows(),this.renderSubagentPanel(),this.renderMonitorSubagents(),this.updateSubagentBadge(),this.showToast(`Cleared ${n.data.cleared} subagent(s)`,"success")):this.showToast("Failed to clear subagents: "+n.error,"error")}catch{this.showToast("Failed to clear subagents","error")}},toggleSubagentsPanel(){const e=document.getElementById("subagentsPanel"),t=document.getElementById("subagentsToggleBtn");if(e){if(e.classList.contains("hidden")){e.classList.remove("hidden");const n=this.loadAppSettingsFromStorage();n.showSubagents=!0,this.saveAppSettingsToStorage(n)}e.classList.toggle("open"),this.subagentPanelVisible=e.classList.contains("open"),t&&(t.innerHTML=this.subagentPanelVisible?"&#x25BC;":"&#x25B2;"),this.subagentPanelVisible&&this.renderSubagentPanel()}},async loadAppSettingsFromServer(e=null){try{if((MobileDetection.isHandheldDevice?.()??MobileDetection.getDeviceType()==="mobile")&&!localStorage.getItem("codeman:planUsagePerDeviceMigrated")){const t=this.loadAppSettingsFromStorage();t&&t.showPlanUsageLimits&&(t.showPlanUsageLimits=!1,this.saveAppSettingsToStorage(t)),localStorage.setItem("codeman:planUsagePerDeviceMigrated","1")}}catch{}try{const t=e?await e:await fetch("/api/settings").then(n=>n.ok?n.json():null).then(n=>n?.success===!0?n.data:n);if(t){const{notificationPreferences:n,voiceSettings:s,respawnPresets:o,runMode:a,...i}=t,l=new Set(["showFontControls","showSystemStats","showTokenCount","showCost","showLifecycleLog","showResponseViewer","showRedrawButton","showMonitor","showProjectInsights","showFileBrowser","showSubagents","subagentActiveTabOnly","tabTwoRows","localEchoEnabled","cjkInputEnabled","extendedKeyboardBar","skin","showPlanUsageLimits","showAttachmentsButton","showFileViewerButton","webglRendererEnabled","language","terminalWheelLocalScrollback","showSessionButton","showAwayDigestButton","showCronButton"]);delete i.showPlanUsageLimits;const c=this.loadAppSettingsFromStorage(),d={...c};for(const[r,u]of Object.entries(i))l.has(r)&&r in c||(d[r]=u);if(this.saveAppSettingsToStorage(d),n&&this.notificationManager&&(localStorage.getItem(this.notificationManager.getStorageKey())||(this.notificationManager.preferences=n,this.notificationManager.savePreferences())),s){const r=localStorage.getItem("codeman-voice-settings");(!r||!JSON.parse(r).apiKey)&&VoiceInput._saveDeepgramConfig(s)}if(o&&Array.isArray(o))this._serverRespawnPresets=o,localStorage.setItem("codeman-respawn-presets",JSON.stringify(o));else{const r=localStorage.getItem("codeman-respawn-presets");if(r){const u=JSON.parse(r);u.length>0&&(this._serverRespawnPresets=u,this._apiPut("/api/settings",{respawnPresets:u}).catch(()=>{}))}}if(a){this.runMode=a;try{localStorage.setItem("codeman_runMode",a)}catch{}this._applyRunMode()}return d}}catch(t){console.error("Failed to load settings from server:",t)}return this.loadAppSettingsFromStorage()},async loadSubagentWindowStates(){let e=null;try{const t=await fetch("/api/subagent-window-states");if(t.ok){const n=await t.json();e=n?.success===!0?n.data:n,localStorage.setItem("codeman-subagent-window-states",JSON.stringify(e))}}catch(t){console.error("Failed to load subagent window states from server:",t)}if(!e)try{const t=localStorage.getItem("codeman-subagent-window-states");t&&(e=JSON.parse(t))}catch(t){console.error("Failed to load subagent window states from localStorage:",t)}return e||{minimized:{},open:[]}},async saveSubagentParentMap(){const e=Object.fromEntries(this.subagentParentMap);try{localStorage.setItem("codeman-subagent-parents",JSON.stringify(e))}catch(t){console.error("Failed to save subagent parents to localStorage:",t)}try{await fetch("/api/subagent-parents",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}catch(t){console.error("Failed to save subagent parents to server:",t)}},async loadSubagentParentMap(){let e=null;try{const t=await fetch("/api/subagent-parents");if(t.ok){const n=await t.json();e=n?.success===!0?n.data:n,localStorage.setItem("codeman-subagent-parents",JSON.stringify(e))}}catch(t){console.error("Failed to load subagent parents from server:",t)}if(!e)try{const t=localStorage.getItem("codeman-subagent-parents");t&&(e=JSON.parse(t))}catch(t){console.error("Failed to load subagent parents from localStorage:",t)}if(e&&typeof e=="object")for(const[t,n]of Object.entries(e))this.sessions.has(n)&&this.subagents.has(t)&&this.subagentParentMap.set(t,n)},getAgentParentSessionId(e){return this.subagentParentMap.get(e)||null},setAgentParentSessionId(e,t){if(!e||!t||this.subagentParentMap.has(e))return;this.subagentParentMap.set(e,t),this.saveSubagentParentMap();const n=this.subagents.get(e);if(n){n.parentSessionId=t;const s=this.sessions.get(t);s&&(n.parentSessionName=this.getSessionName(s)),this.subagents.set(e,n)}},showHelp(){const e=document.getElementById("helpModal");e.classList.add("active"),this.activeFocusTrap=new FocusTrap(e),this.activeFocusTrap.activate()},closeHelp(){document.getElementById("helpModal").classList.remove("active"),this.activeFocusTrap&&(this.activeFocusTrap.deactivate(),this.activeFocusTrap=null)},renderShortcutSettingsList(){const e=document.getElementById("appSettingsShortcutsList");if(!e)return;const t=this.getShortcutRegistry?this.getShortcutRegistry():typeof DEFAULT_SHORTCUTS<"u"?DEFAULT_SHORTCUTS:[],n=this.readShortcutOverridesFromSettings();e.innerHTML=t.map(s=>{const o=s.displayBindings?s.displayBindings.join(" / "):(s.bindings||[]).map(c=>[...c.modifiers||[],c.key||c.code||""].join("+")).join(" / "),a=!!s.action&&Array.isArray(s.bindings),i=!!n[s.id],l=a?`<button type="button" class="shortcut-capture-btn" data-shortcut-action="capture" title="Capture new binding">Edit</button>
61
+ </tr>`}).join("")}catch(s){console.error("Failed to load lifecycle log:",s)}},async saveAppSettings(){const e=this.loadAppSettingsFromStorage(),t=(e.gestureControlEnabled??!1)===!0,n=(e.webglRendererEnabled??!0)===!0,s={displayName:window.CodemanI18n?.normalizeDisplayName(document.getElementById("appSettingsDisplayName").value)||"Codeman",language:window.CodemanI18n?.normalizeLanguage(document.getElementById("appSettingsLanguage").value)||"en",defaultClaudeMdPath:document.getElementById("appSettingsClaudeMdPath").value.trim(),defaultWorkingDir:document.getElementById("appSettingsDefaultDir").value.trim(),ralphTrackerEnabled:document.getElementById("appSettingsRalphEnabled").checked,showFontControls:document.getElementById("appSettingsShowFontControls").checked,showSystemStats:document.getElementById("appSettingsShowSystemStats").checked,showLifecycleLog:document.getElementById("appSettingsShowLifecycleLog").checked,showResponseViewer:document.getElementById("appSettingsShowResponseViewer").checked,showFileViewerButton:document.getElementById("appSettingsShowFileViewerButton").checked,showAttachmentsButton:document.getElementById("appSettingsShowAttachmentsButton").checked,showMonitor:document.getElementById("appSettingsShowMonitor").checked,showProjectInsights:document.getElementById("appSettingsShowProjectInsights").checked,showFileBrowser:document.getElementById("appSettingsShowFileBrowser").checked,showSubagents:document.getElementById("appSettingsShowSubagents").checked,showUltracodeAgents:document.getElementById("appSettingsShowUltracodeAgents").checked,ultracodeFloatingWindows:document.getElementById("appSettingsUltracodeFloatingWindows").checked,showMultiMonitorButton:document.getElementById("appSettingsShowMultiMonitorButton").checked,showPlanUsageLimits:document.getElementById("appSettingsShowPlanUsageLimits").checked,showRedrawButton:document.getElementById("appSettingsShowRedrawButton").checked,showSessionButton:document.getElementById("appSettingsShowSessionButton").checked,showAwayDigestButton:document.getElementById("appSettingsShowAwayDigestButton").checked,showCronButton:document.getElementById("appSettingsShowCronButton").checked,gestureControlEnabled:document.getElementById("appSettingsGestureControl").checked,subagentTrackingEnabled:document.getElementById("appSettingsSubagentTracking").checked,subagentActiveTabOnly:document.getElementById("appSettingsSubagentActiveTabOnly").checked,imageWatcherEnabled:document.getElementById("appSettingsImageWatcherEnabled").checked,tunnelEnabled:document.getElementById("appSettingsTunnelEnabled").checked,localEchoEnabled:document.getElementById("appSettingsLocalEcho").checked,terminalWheelLocalScrollback:document.getElementById("appSettingsTerminalWheelLocal").checked,cjkInputEnabled:document.getElementById("appSettingsCjkInput").checked,webglRendererEnabled:document.getElementById("appSettingsWebglRenderer").checked,extendedKeyboardBar:document.getElementById("appSettingsExtendedKeyboardBar").checked,tabTwoRows:document.getElementById("appSettingsTabTwoRows").checked,skin:document.getElementById("appSettingsSkin").value,claudeMode:document.getElementById("appSettingsClaudeMode").value,allowedTools:document.getElementById("appSettingsAllowedTools").value.trim(),codexDangerouslyBypassApprovals:document.getElementById("appSettingsCodexDangerouslyBypassApprovals").checked,agentTeamsEnabled:document.getElementById("appSettingsAgentTeams").checked,claudeModel:document.getElementById("appSettingsClaudeModel").value,opusContext1mEnabled:document.getElementById("appSettingsOpusContext1m").checked,remoteAutoReconnect:document.getElementById("appSettingsRemoteAutoReconnect").checked,thinkingEffort:document.getElementById("appSettingsThinkingEffort").value,nice:{enabled:document.getElementById("appSettingsNiceEnabled").checked,niceValue:parseInt(document.getElementById("appSettingsNiceValue").value)||10}};if(e.showTokenCount!==void 0&&(s.showTokenCount=e.showTokenCount),e.showCost!==void 0&&(s.showCost=e.showCost),e.shortcutOverrides!==void 0&&(s.shortcutOverrides=e.shortcutOverrides),this.saveAppSettingsToStorage(s),this._updateLocalEchoState(),!n&&s.webglRendererEnabled)try{localStorage.removeItem("codeman-webgl-disabled")}catch{}const o={apiKey:document.getElementById("voiceDeepgramKey").value.trim(),language:document.getElementById("voiceLanguage").value,keyterms:document.getElementById("voiceKeyterms").value.trim(),insertMode:document.getElementById("voiceInsertMode").value};VoiceInput._saveDeepgramConfig(o);const a={enabled:document.getElementById("appSettingsNotifEnabled").checked,browserNotifications:document.getElementById("appSettingsNotifBrowser").checked,audioAlerts:document.getElementById("appSettingsNotifAudio").checked,stuckThresholdMs:(parseInt(document.getElementById("appSettingsNotifStuckMins").value)||10)*6e4,muteCritical:!document.getElementById("appSettingsNotifCritical").checked,muteWarning:!document.getElementById("appSettingsNotifWarning").checked,muteInfo:!document.getElementById("appSettingsNotifInfo").checked,eventTypes:{permission_prompt:{enabled:document.getElementById("eventPermissionEnabled").checked,browser:document.getElementById("eventPermissionBrowser").checked,push:document.getElementById("eventPermissionPush").checked,audio:document.getElementById("eventPermissionAudio").checked},elicitation_dialog:{enabled:document.getElementById("eventQuestionEnabled").checked,browser:document.getElementById("eventQuestionBrowser").checked,push:document.getElementById("eventQuestionPush").checked,audio:document.getElementById("eventQuestionAudio").checked},idle_prompt:{enabled:document.getElementById("eventIdleEnabled").checked,browser:document.getElementById("eventIdleBrowser").checked,push:document.getElementById("eventIdlePush").checked,audio:document.getElementById("eventIdleAudio").checked},stop:{enabled:document.getElementById("eventStopEnabled").checked,browser:document.getElementById("eventStopBrowser").checked,push:document.getElementById("eventStopPush").checked,audio:document.getElementById("eventStopAudio").checked},session_error:{enabled:!0,browser:this.notificationManager?.preferences?.eventTypes?.session_error?.browser??!0,push:this.notificationManager?.preferences?.eventTypes?.session_error?.push??!1,audio:!1},respawn_cycle:{enabled:document.getElementById("eventRespawnEnabled").checked,browser:document.getElementById("eventRespawnBrowser").checked,push:document.getElementById("eventRespawnPush").checked,audio:document.getElementById("eventRespawnAudio").checked},token_milestone:{enabled:!0,browser:!1,push:!1,audio:!1},ralph_complete:{enabled:document.getElementById("eventRalphEnabled").checked,browser:document.getElementById("eventRalphBrowser").checked,push:document.getElementById("eventRalphPush").checked,audio:document.getElementById("eventRalphAudio").checked},subagent_spawn:{enabled:document.getElementById("eventSubagentEnabled").checked,browser:document.getElementById("eventSubagentBrowser").checked,push:document.getElementById("eventSubagentPush").checked,audio:document.getElementById("eventSubagentAudio").checked},subagent_complete:{enabled:document.getElementById("eventSubagentEnabled").checked,browser:document.getElementById("eventSubagentBrowser").checked,push:document.getElementById("eventSubagentPush").checked,audio:document.getElementById("eventSubagentAudio").checked}},_version:4};this.notificationManager&&(this.notificationManager.preferences=a,this.notificationManager.savePreferences()),this._syncPushPreferences(),this.applyHeaderVisibilitySettings(),this.applySkin(),this.applyLocalization(),this.applyTabWrapSettings(),this._updateTokensImmediate(),this.applyMonitorVisibility(),this.renderProjectInsightsPanel(),this.updateSubagentWindowVisibility(),this._updateCjkInputState(),KeyboardAccessoryBar.setMode(s.extendedKeyboardBar?"extended":"simple");const{localEchoEnabled:i,cjkInputEnabled:l,extendedKeyboardBar:c,skin:d,language:r,showPlanUsageLimits:u,showAttachmentsButton:h,showFileViewerButton:p,webglRendererEnabled:f,terminalWheelLocalScrollback:b,showSessionButton:m,showAwayDigestButton:S,showCronButton:E,...v}=s;try{const y=await this._apiPut("/api/settings",{...v,...s.showPlanUsageLimits?{statusLineTelemetry:!0}:{},notificationPreferences:a,voiceSettings:o});if(s.tunnelEnabled&&await this._handleTunnelEnableRefusal(y)){s.tunnelEnabled=!1,this.saveAppSettingsToStorage(s);const w=document.getElementById("appSettingsTunnelEnabled");w&&(w.checked=!1),this.closeAppSettings();return}await this.saveModelConfigFromSettings(),this.showToast("Settings saved","success"),s.tunnelEnabled&&this.showToast("Tunnel starting \u2014 QR code will appear when ready...","info")}catch{this.showToast("Settings saved locally","warning")}this.closeAppSettings(),s.gestureControlEnabled!==t&&(this.showToast(s.gestureControlEnabled?"Enabling gesture control \u2014 reloading\u2026":"Disabling gesture control \u2014 reloading\u2026","info"),setTimeout(()=>location.reload(),400))},async loadModelConfigForSettings(){try{const t=await(await fetch("/api/execution/model-config")).json();if(t.success&&t.data){const n=t.data,s=document.getElementById("appSettingsDefaultModel");s&&(s.value=n.defaultModel||"");const o=document.getElementById("appSettingsShowModelRecommendations");o&&(o.checked=n.showRecommendations??!0);const a=n.agentTypeOverrides||{},i=document.getElementById("appSettingsModelExplore"),l=document.getElementById("appSettingsModelImplement"),c=document.getElementById("appSettingsModelTest"),d=document.getElementById("appSettingsModelReview");i&&(i.value=a.explore||""),l&&(l.value=a.implement||""),c&&(c.value=a.test||""),d&&(d.value=a.review||"")}}catch(e){console.warn("Failed to load model config:",e)}},async saveModelConfigFromSettings(){const e=document.getElementById("appSettingsDefaultModel"),t=document.getElementById("appSettingsShowModelRecommendations"),n=document.getElementById("appSettingsModelExplore"),s=document.getElementById("appSettingsModelImplement"),o=document.getElementById("appSettingsModelTest"),a=document.getElementById("appSettingsModelReview"),i={};n?.value&&(i.explore=n.value),s?.value&&(i.implement=s.value),o?.value&&(i.test=o.value),a?.value&&(i.review=a.value);const l={defaultModel:e?.value||"",showRecommendations:t?.checked??!0,agentTypeOverrides:i};try{await fetch("/api/execution/model-config",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)})}catch(c){console.warn("Failed to save model config:",c)}},isRalphTrackerEnabledByDefault(){return this.loadAppSettingsFromStorage().ralphTrackerEnabled??!1},getSettingsStorageKey(){return MobileDetection.isHandheldDevice?.()??MobileDetection.getDeviceType()==="mobile"?"codeman-app-settings-mobile":"codeman-app-settings"},getDefaultSettings(){return MobileDetection.isHandheldDevice?.()??MobileDetection.getDeviceType()==="mobile"?{showFontControls:!1,showSystemStats:!1,showTokenCount:!1,showCost:!1,showMonitor:!1,showProjectInsights:!1,showFileBrowser:!1,showSubagents:!1,showUltracodeAgents:!1,ultracodeFloatingWindows:!1,showMultiMonitorButton:!1,showPlanUsageLimits:!1,showAttachmentsButton:!1,showFileViewerButton:!1,showRedrawButton:!1,showSessionButton:!1,showAwayDigestButton:!1,showCronButton:!1,remoteAutoReconnect:!0,gestureControlEnabled:!1,subagentTrackingEnabled:!0,subagentActiveTabOnly:!0,imageWatcherEnabled:!1,ralphTrackerEnabled:!1,tabTwoRows:!1,cjkInputEnabled:!1,terminalWheelLocalScrollback:!1,webglRendererEnabled:!1,skin:"daylight-blue"}:{}},loadAppSettingsFromStorage(){if(this._cachedAppSettings)return this._cachedAppSettings;try{const e=this.getSettingsStorageKey(),t=localStorage.getItem(e);if(t)return this._cachedAppSettings=JSON.parse(t),this._cachedAppSettings}catch(e){console.error("Failed to load app settings:",e)}return this._cachedAppSettings=this.getDefaultSettings(),this._cachedAppSettings},saveAppSettingsToStorage(e){this._cachedAppSettings=e;try{const t=this.getSettingsStorageKey();localStorage.setItem(t,JSON.stringify(e))}catch(t){console.error("Failed to save app settings:",t)}},applySkin(){const e=this.loadAppSettingsFromStorage(),t=this.getDefaultSettings(),n=e.skin??t.skin??"daylight-blue";document.documentElement.setAttribute("data-skin",n),window.__codemanSkin=n;try{localStorage.setItem("codeman:skin",n)}catch{}typeof this.applyTerminalSkin=="function"&&this.applyTerminalSkin(n)},applyLocalization(){const e=this.loadAppSettingsFromStorage();window.CodemanI18n?.configure({language:e.language,displayName:e.displayName})&&this.notificationManager&&(this.notificationManager.originalTitle=document.title)},applyHeaderVisibilitySettings(){const e=this.loadAppSettingsFromStorage(),t=this.getDefaultSettings(),n=MobileDetection.getDeviceType()!=="desktop",s=n?!1:e.showFontControls??t.showFontControls??!1,o=n?!1:e.showSystemStats??t.showSystemStats??!0,a=n?!1:e.showTokenCount??t.showTokenCount??!1,i=document.querySelector(".header-font-controls"),l=document.getElementById("headerSystemStats"),c=document.getElementById("headerTokens");i&&(i.style.display=s?"":"none"),l&&(l.style.display=o?"":"none"),c&&(c.style.display=a?"":"none");const d=e.showLifecycleLog??t.showLifecycleLog??!1,r=document.querySelector(".btn-lifecycle-log");r&&(r.style.display=d?"":"none");const u=e.showResponseViewer??t.showResponseViewer??!1,h=document.querySelector(".btn-response-viewer-header");h&&h.classList.toggle("btn-response-viewer-header--hidden",!u);const p=e.showAttachmentsButton??t.showAttachmentsButton??!1,f=document.getElementById("attachmentsHistoryBtn");f&&f.classList.toggle("btn-attachments-history--hidden",!p);const b=e.showFileViewerButton??t.showFileViewerButton??!0,m=document.querySelector(".btn-file-viewer");m&&m.classList.toggle("btn-file-viewer--hidden",!b);const S=e.showMultiMonitorButton??t.showMultiMonitorButton??!1,E=document.querySelector(".btn-multimonitor");E&&E.classList.toggle("btn-multimonitor--hidden",!S);const v=e.showUltracodeAgents??t.showUltracodeAgents??!1,y=document.querySelector(".btn-ultracode-agents");y&&y.classList.toggle("btn-ultracode-agents--hidden",!v);const w=e.showPlanUsageLimits??t.showPlanUsageLimits??!1,g=document.getElementById("planUsageChip");g&&g.classList.toggle("header-plan-usage--hidden",!w);const P=e.showRedrawButton??t.showRedrawButton??!1,B=document.querySelector(".btn-redraw-terminal");B&&B.classList.toggle("btn-redraw-terminal--hidden",!P);const L=e.showSessionButton??t.showSessionButton??!1,I=document.querySelector(".btn-session-manager");I&&I.classList.toggle("btn-session-manager--hidden",!L);const A=e.showAwayDigestButton??t.showAwayDigestButton??!1,T=document.querySelector(".btn-away-digest");T&&T.classList.toggle("btn-away-digest--hidden",!A);const M=e.showCronButton??t.showCronButton??!1,k=document.querySelector(".btn-cron");k&&k.classList.toggle("btn-cron--hidden",!M);const _=document.querySelector(".btn-notifications");if(_&&(_.style.display="none"),!(this.notificationManager?.preferences?.enabled??!0)){const C=document.getElementById("notifDrawer");C&&C.classList.remove("open")}},applyTabWrapSettings(){const e=this.loadAppSettingsFromStorage(),t=this.getDefaultSettings(),s=MobileDetection.getDeviceType()==="desktop"?e.tabTwoRows??t.tabTwoRows??!1:!1,o=this._tallTabsEnabled;this._tallTabsEnabled=s;const a=document.getElementById("sessionTabs");a&&(a.classList.toggle("tabs-two-rows",s),a.classList.toggle("tabs-show-folder",s)),o!==void 0&&o!==s&&this._fullRenderSessionTabs()},applyMonitorVisibility(){const e=this.loadAppSettingsFromStorage(),t=this.getDefaultSettings(),n=e.showMonitor??t.showMonitor??!1,s=e.showSubagents??t.showSubagents??!1,o=e.showFileBrowser??t.showFileBrowser??!1,a=document.getElementById("monitorPanel");a&&(a.style.display=n?"":"none",n?a.classList.add("open"):a.classList.remove("open"));const i=document.getElementById("subagentsPanel");i&&(s?i.classList.remove("hidden"):i.classList.add("hidden"));const l=e.showUltracodeAgents??t.showUltracodeAgents??!1,c=document.getElementById("ultracodeAgentsPanel");c&&(l?c.classList.remove("hidden"):(c.classList.remove("open"),c.classList.add("hidden"))),e.ultracodeFloatingWindows??t.ultracodeFloatingWindows??!1?typeof this.syncAllUltracodeFloatingWindows=="function"&&this.syncAllUltracodeFloatingWindows():typeof this.removeAllUltracodeWindows=="function"&&this.removeAllUltracodeWindows();const r=document.getElementById("fileBrowserPanel");if(r)if(o&&this.activeSessionId){if(r.classList.add("visible"),this.loadFileBrowser(this.activeSessionId),!this.fileBrowserDragListeners){const u=r.querySelector(".file-browser-header");if(u){const h=()=>{if(!r.style.left){const p=r.getBoundingClientRect();r.style.left=`${p.left}px`,r.style.top=`${p.top}px`,r.style.right="auto"}};u.addEventListener("mousedown",h),u.addEventListener("touchstart",h,{passive:!0}),this.fileBrowserDragListeners=this.makeWindowDraggable(r,u),this.fileBrowserDragListeners._onFirstDrag=h}}}else r.classList.remove("visible")},closeMonitor(){const e=document.getElementById("monitorPanel");e&&(e.classList.remove("open"),e.style.display="none");const t=this.loadAppSettingsFromStorage();t.showMonitor=!1,this.saveAppSettingsToStorage(t)},closeSubagentsPanel(){const e=document.getElementById("subagentsPanel");e&&(e.classList.remove("open"),e.classList.add("hidden")),this.subagentPanelVisible=!1;const t=this.loadAppSettingsFromStorage();t.showSubagents=!1,this.saveAppSettingsToStorage(t)},async clearAllSubagents(){const e=this.subagents.size;if(e===0){this.showToast("No subagents to clear","info");return}if(confirm(`Clear all ${e} tracked subagent(s)? This removes them from the UI but does not affect running processes.`))try{const n=await(await fetch("/api/subagents",{method:"DELETE"})).json();n.success?(this.subagents.clear(),this.subagentActivity.clear(),this.subagentToolResults.clear(),this.cleanupAllFloatingWindows(),this.renderSubagentPanel(),this.renderMonitorSubagents(),this.updateSubagentBadge(),this.showToast(`Cleared ${n.data.cleared} subagent(s)`,"success")):this.showToast("Failed to clear subagents: "+n.error,"error")}catch{this.showToast("Failed to clear subagents","error")}},toggleSubagentsPanel(){const e=document.getElementById("subagentsPanel"),t=document.getElementById("subagentsToggleBtn");if(e){if(e.classList.contains("hidden")){e.classList.remove("hidden");const n=this.loadAppSettingsFromStorage();n.showSubagents=!0,this.saveAppSettingsToStorage(n)}e.classList.toggle("open"),this.subagentPanelVisible=e.classList.contains("open"),t&&(t.innerHTML=this.subagentPanelVisible?"&#x25BC;":"&#x25B2;"),this.subagentPanelVisible&&this.renderSubagentPanel()}},async loadAppSettingsFromServer(e=null){try{if((MobileDetection.isHandheldDevice?.()??MobileDetection.getDeviceType()==="mobile")&&!localStorage.getItem("codeman:planUsagePerDeviceMigrated")){const t=this.loadAppSettingsFromStorage();t&&t.showPlanUsageLimits&&(t.showPlanUsageLimits=!1,this.saveAppSettingsToStorage(t)),localStorage.setItem("codeman:planUsagePerDeviceMigrated","1")}}catch{}try{const t=e?await e:await fetch("/api/settings").then(n=>n.ok?n.json():null).then(n=>n?.success===!0?n.data:n);if(t){const{notificationPreferences:n,voiceSettings:s,respawnPresets:o,runMode:a,...i}=t,l=new Set(["showFontControls","showSystemStats","showTokenCount","showCost","showLifecycleLog","showResponseViewer","showRedrawButton","showMonitor","showProjectInsights","showFileBrowser","showSubagents","subagentActiveTabOnly","tabTwoRows","localEchoEnabled","cjkInputEnabled","extendedKeyboardBar","skin","showPlanUsageLimits","showAttachmentsButton","showFileViewerButton","webglRendererEnabled","language","terminalWheelLocalScrollback","showSessionButton","showAwayDigestButton","showCronButton"]);delete i.showPlanUsageLimits;const c=this.loadAppSettingsFromStorage(),d={...c};for(const[r,u]of Object.entries(i))l.has(r)&&r in c||(d[r]=u);if(this.saveAppSettingsToStorage(d),n&&this.notificationManager&&(localStorage.getItem(this.notificationManager.getStorageKey())||(this.notificationManager.preferences=n,this.notificationManager.savePreferences())),s){const r=localStorage.getItem("codeman-voice-settings");(!r||!JSON.parse(r).apiKey)&&VoiceInput._saveDeepgramConfig(s)}if(o&&Array.isArray(o))this._serverRespawnPresets=o,localStorage.setItem("codeman-respawn-presets",JSON.stringify(o));else{const r=localStorage.getItem("codeman-respawn-presets");if(r){const u=JSON.parse(r);u.length>0&&(this._serverRespawnPresets=u,this._apiPut("/api/settings",{respawnPresets:u}).catch(()=>{}))}}if(a){this.runMode=a;try{localStorage.setItem("codeman_runMode",a)}catch{}this._applyRunMode()}return d}}catch(t){console.error("Failed to load settings from server:",t)}return this.loadAppSettingsFromStorage()},async loadSubagentWindowStates(){let e=null;try{const t=await fetch("/api/subagent-window-states");if(t.ok){const n=await t.json();e=n?.success===!0?n.data:n,localStorage.setItem("codeman-subagent-window-states",JSON.stringify(e))}}catch(t){console.error("Failed to load subagent window states from server:",t)}if(!e)try{const t=localStorage.getItem("codeman-subagent-window-states");t&&(e=JSON.parse(t))}catch(t){console.error("Failed to load subagent window states from localStorage:",t)}return e||{minimized:{},open:[]}},async saveSubagentParentMap(){const e=Object.fromEntries(this.subagentParentMap);try{localStorage.setItem("codeman-subagent-parents",JSON.stringify(e))}catch(t){console.error("Failed to save subagent parents to localStorage:",t)}try{await fetch("/api/subagent-parents",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}catch(t){console.error("Failed to save subagent parents to server:",t)}},async loadSubagentParentMap(){let e=null;try{const t=await fetch("/api/subagent-parents");if(t.ok){const n=await t.json();e=n?.success===!0?n.data:n,localStorage.setItem("codeman-subagent-parents",JSON.stringify(e))}}catch(t){console.error("Failed to load subagent parents from server:",t)}if(!e)try{const t=localStorage.getItem("codeman-subagent-parents");t&&(e=JSON.parse(t))}catch(t){console.error("Failed to load subagent parents from localStorage:",t)}if(e&&typeof e=="object")for(const[t,n]of Object.entries(e))this.sessions.has(n)&&this.subagents.has(t)&&this.subagentParentMap.set(t,n)},getAgentParentSessionId(e){return this.subagentParentMap.get(e)||null},setAgentParentSessionId(e,t){if(!e||!t||this.subagentParentMap.has(e))return;this.subagentParentMap.set(e,t),this.saveSubagentParentMap();const n=this.subagents.get(e);if(n){n.parentSessionId=t;const s=this.sessions.get(t);s&&(n.parentSessionName=this.getSessionName(s)),this.subagents.set(e,n)}},showHelp(){const e=document.getElementById("helpModal");e.classList.add("active"),this.activeFocusTrap=new FocusTrap(e),this.activeFocusTrap.activate()},closeHelp(){document.getElementById("helpModal").classList.remove("active"),this.activeFocusTrap&&(this.activeFocusTrap.deactivate(),this.activeFocusTrap=null)},renderShortcutSettingsList(){const e=document.getElementById("appSettingsShortcutsList");if(!e)return;const t=this.getShortcutRegistry?this.getShortcutRegistry():typeof DEFAULT_SHORTCUTS<"u"?DEFAULT_SHORTCUTS:[],n=this.readShortcutOverridesFromSettings();e.innerHTML=t.map(s=>{const o=s.displayBindings?s.displayBindings.join(" / "):(s.bindings||[]).map(c=>[...c.modifiers||[],c.key||c.code||""].join("+")).join(" / "),a=!!s.action&&Array.isArray(s.bindings),i=!!n[s.id],l=a?`<button type="button" class="shortcut-capture-btn" data-shortcut-action="capture" title="Capture new binding">Edit</button>
62
62
  <button type="button" class="shortcut-reset-btn" data-shortcut-action="reset" title="Reset to default"${i?"":" disabled"}>Reset</button>
63
63
  <input class="shortcut-enabled-checkbox" type="checkbox" ${s.disabled?"":"checked"} data-shortcut-action="toggle" title="Enable/disable">`:"";return`<div class="shortcut-setting-row${a?"":" shortcut-setting-row--fixed"}" data-shortcut-id="${escapeHtml(s.id)}">
64
64
  <label class="shortcut-setting-label">${escapeHtml(s.label)}</label>