aicodeman 1.24.7 → 1.26.0

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 (195) hide show
  1. package/dist/agent-case-marker.d.ts +91 -0
  2. package/dist/agent-case-marker.d.ts.map +1 -0
  3. package/dist/agent-case-marker.js +151 -0
  4. package/dist/agent-case-marker.js.map +1 -0
  5. package/dist/cli.d.ts.map +1 -1
  6. package/dist/cli.js +17 -2
  7. package/dist/cli.js.map +1 -1
  8. package/dist/config/base-path.d.ts +55 -0
  9. package/dist/config/base-path.d.ts.map +1 -0
  10. package/dist/config/base-path.js +105 -0
  11. package/dist/config/base-path.js.map +1 -0
  12. package/dist/config/cli-registry/schema.d.ts +2 -0
  13. package/dist/config/cli-registry/schema.d.ts.map +1 -1
  14. package/dist/config/cli-registry/schema.js +1 -1
  15. package/dist/config/cli-registry/schema.js.map +1 -1
  16. package/dist/config/cli-registry/stock.d.ts.map +1 -1
  17. package/dist/config/cli-registry/stock.js +4 -1
  18. package/dist/config/cli-registry/stock.js.map +1 -1
  19. package/dist/config/cli-registry/types.d.ts +9 -0
  20. package/dist/config/cli-registry/types.d.ts.map +1 -1
  21. package/dist/daemon-control.d.ts +2 -0
  22. package/dist/daemon-control.d.ts.map +1 -1
  23. package/dist/daemon-control.js +2 -0
  24. package/dist/daemon-control.js.map +1 -1
  25. package/dist/docker-export.d.ts.map +1 -1
  26. package/dist/docker-export.js +8 -1
  27. package/dist/docker-export.js.map +1 -1
  28. package/dist/docker-hosts.d.ts +97 -3
  29. package/dist/docker-hosts.d.ts.map +1 -1
  30. package/dist/docker-hosts.js +260 -4
  31. package/dist/docker-hosts.js.map +1 -1
  32. package/dist/hooks-config.d.ts +25 -0
  33. package/dist/hooks-config.d.ts.map +1 -1
  34. package/dist/hooks-config.js +106 -6
  35. package/dist/hooks-config.js.map +1 -1
  36. package/dist/session.d.ts +31 -1
  37. package/dist/session.d.ts.map +1 -1
  38. package/dist/session.js +101 -5
  39. package/dist/session.js.map +1 -1
  40. package/dist/tmux-manager.d.ts.map +1 -1
  41. package/dist/tmux-manager.js +54 -8
  42. package/dist/tmux-manager.js.map +1 -1
  43. package/dist/types/api.d.ts +51 -1
  44. package/dist/types/api.d.ts.map +1 -1
  45. package/dist/types/api.js.map +1 -1
  46. package/dist/types/session.d.ts +49 -0
  47. package/dist/types/session.d.ts.map +1 -1
  48. package/dist/types/session.js.map +1 -1
  49. package/dist/web/middleware/auth.d.ts +3 -3
  50. package/dist/web/middleware/auth.d.ts.map +1 -1
  51. package/dist/web/middleware/auth.js +13 -11
  52. package/dist/web/middleware/auth.js.map +1 -1
  53. package/dist/web/public/admin-ui.js.gz +0 -0
  54. package/dist/web/public/api-client.c9b1cddc.js.gz +0 -0
  55. package/dist/web/public/app.3a89ac57.js +38 -0
  56. package/dist/web/public/app.3a89ac57.js.br +0 -0
  57. package/dist/web/public/app.3a89ac57.js.gz +0 -0
  58. package/dist/web/public/approvals-ui.js.gz +0 -0
  59. package/dist/web/public/{constants.7bd482dc.js → constants.7a635e34.js} +58 -0
  60. package/dist/web/public/constants.7a635e34.js.br +0 -0
  61. package/dist/web/public/constants.7a635e34.js.gz +0 -0
  62. package/dist/web/public/cron-ui.js.gz +0 -0
  63. package/dist/web/public/entrance-animations.js.gz +0 -0
  64. package/dist/web/public/home-sessions.js.gz +0 -0
  65. package/dist/web/public/i18n.9db8c4e0.js +1 -0
  66. package/dist/web/public/i18n.9db8c4e0.js.br +0 -0
  67. package/dist/web/public/i18n.9db8c4e0.js.gz +0 -0
  68. package/dist/web/public/image-input.ee16ad88.js.gz +0 -0
  69. package/dist/web/public/index.html +46 -17
  70. package/dist/web/public/index.html.br +0 -0
  71. package/dist/web/public/index.html.gz +0 -0
  72. package/dist/web/public/input-cjk.87f14251.js.gz +0 -0
  73. package/dist/web/public/{keyboard-accessory.0454a3e9.js → keyboard-accessory.daf18302.js} +8 -4
  74. package/dist/web/public/keyboard-accessory.daf18302.js.br +0 -0
  75. package/dist/web/public/keyboard-accessory.daf18302.js.gz +0 -0
  76. package/dist/web/public/manifest.json +2 -1
  77. package/dist/web/public/mobile-handlers.0f83a608.js.gz +0 -0
  78. package/dist/web/public/mobile-overview.js.gz +0 -0
  79. package/dist/web/public/{mobile.87674154.css → mobile.7112f27d.css} +1 -1
  80. package/dist/web/public/{mobile.87674154.css.br → mobile.7112f27d.css.br} +0 -0
  81. package/dist/web/public/mobile.7112f27d.css.gz +0 -0
  82. package/dist/web/public/{notification-manager.5d229063.js → notification-manager.36ea4624.js} +1 -1
  83. package/dist/web/public/notification-manager.36ea4624.js.br +0 -0
  84. package/dist/web/public/notification-manager.36ea4624.js.gz +0 -0
  85. package/dist/web/public/orchestrator-panel.js.gz +0 -0
  86. package/dist/web/public/{panels-ui.e6e06034.js → panels-ui.db4785bf.js} +8 -8
  87. package/dist/web/public/panels-ui.db4785bf.js.br +0 -0
  88. package/dist/web/public/panels-ui.db4785bf.js.gz +0 -0
  89. package/dist/web/public/ralph-panel.6de2d0f8.js.gz +0 -0
  90. package/dist/web/public/ralph-wizard.13a1831e.js.gz +0 -0
  91. package/dist/web/public/readmymind-ui.js.gz +0 -0
  92. package/dist/web/public/respawn-ui.ff0dae4c.js.gz +0 -0
  93. package/dist/web/public/sanitize-html.bc7078d6.js.gz +0 -0
  94. package/dist/web/public/session-lineage.js.gz +0 -0
  95. package/dist/web/public/session-ui.a9c126c6.js +77 -0
  96. package/dist/web/public/session-ui.a9c126c6.js.br +0 -0
  97. package/dist/web/public/session-ui.a9c126c6.js.gz +0 -0
  98. package/dist/web/public/{settings-ui.1ed208dd.js → settings-ui.554f9cdd.js} +1 -1
  99. package/dist/web/public/settings-ui.554f9cdd.js.br +0 -0
  100. package/dist/web/public/settings-ui.554f9cdd.js.gz +0 -0
  101. package/dist/web/public/styles.298f81f2.css +1 -0
  102. package/dist/web/public/styles.298f81f2.css.br +0 -0
  103. package/dist/web/public/{styles.421b36d4.css.gz → styles.298f81f2.css.gz} +0 -0
  104. package/dist/web/public/subagent-windows.e6ca799f.js.gz +0 -0
  105. package/dist/web/public/sw.js +13 -6
  106. package/dist/web/public/sw.js.br +0 -0
  107. package/dist/web/public/sw.js.gz +0 -0
  108. package/dist/web/public/tab-rail-resize.42c24949.js.gz +0 -0
  109. package/dist/web/public/terminal-ui.70445f81.js.gz +0 -0
  110. package/dist/web/public/ultracode-panel.js.gz +0 -0
  111. package/dist/web/public/ultracode-windows.js.gz +0 -0
  112. package/dist/web/public/upload.html.gz +0 -0
  113. package/dist/web/public/vendor/dompurify.min.js.gz +0 -0
  114. package/dist/web/public/vendor/marked.min.js.gz +0 -0
  115. package/dist/web/public/vendor/xterm-addon-fit.min.js.gz +0 -0
  116. package/dist/web/public/vendor/xterm-addon-serialize.min.js.gz +0 -0
  117. package/dist/web/public/vendor/xterm-addon-unicode11.min.js.gz +0 -0
  118. package/dist/web/public/vendor/xterm-addon-webgl.min.js.gz +0 -0
  119. package/dist/web/public/vendor/xterm-predictive-echo.bd6882b8.js.gz +0 -0
  120. package/dist/web/public/vendor/xterm-zerolag-input.6fee72f2.js.gz +0 -0
  121. package/dist/web/public/vendor/xterm.css.gz +0 -0
  122. package/dist/web/public/vendor/xterm.min.js.gz +0 -0
  123. package/dist/web/public/{voice-input.4ec670b0.js → voice-input.c4b51eb6.js} +1 -1
  124. package/dist/web/public/voice-input.c4b51eb6.js.br +0 -0
  125. package/dist/web/public/voice-input.c4b51eb6.js.gz +0 -0
  126. package/dist/web/public/voice-pcm-worklet.js.gz +0 -0
  127. package/dist/web/public/webview-tabs.js +3 -1
  128. package/dist/web/public/webview-tabs.js.br +0 -0
  129. package/dist/web/public/webview-tabs.js.gz +0 -0
  130. package/dist/web/route-helpers.d.ts +18 -0
  131. package/dist/web/route-helpers.d.ts.map +1 -1
  132. package/dist/web/route-helpers.js +28 -0
  133. package/dist/web/route-helpers.js.map +1 -1
  134. package/dist/web/routes/case-routes.d.ts.map +1 -1
  135. package/dist/web/routes/case-routes.js +261 -6
  136. package/dist/web/routes/case-routes.js.map +1 -1
  137. package/dist/web/routes/file-routes.d.ts.map +1 -1
  138. package/dist/web/routes/file-routes.js +62 -4
  139. package/dist/web/routes/file-routes.js.map +1 -1
  140. package/dist/web/routes/hook-event-routes.d.ts.map +1 -1
  141. package/dist/web/routes/hook-event-routes.js +29 -3
  142. package/dist/web/routes/hook-event-routes.js.map +1 -1
  143. package/dist/web/routes/session-routes.d.ts.map +1 -1
  144. package/dist/web/routes/session-routes.js +139 -59
  145. package/dist/web/routes/session-routes.js.map +1 -1
  146. package/dist/web/routes/webview-routes.d.ts +2 -2
  147. package/dist/web/routes/webview-routes.d.ts.map +1 -1
  148. package/dist/web/routes/webview-routes.js +23 -21
  149. package/dist/web/routes/webview-routes.js.map +1 -1
  150. package/dist/web/schemas.d.ts +30 -0
  151. package/dist/web/schemas.d.ts.map +1 -1
  152. package/dist/web/schemas.js +78 -0
  153. package/dist/web/schemas.js.map +1 -1
  154. package/dist/web/server.d.ts +4 -2
  155. package/dist/web/server.d.ts.map +1 -1
  156. package/dist/web/server.js +75 -12
  157. package/dist/web/server.js.map +1 -1
  158. package/dist/web/sse-events.d.ts +4 -2
  159. package/dist/web/sse-events.d.ts.map +1 -1
  160. package/dist/web/sse-events.js +4 -2
  161. package/dist/web/sse-events.js.map +1 -1
  162. package/dist/web/webview-proxy.d.ts +16 -7
  163. package/dist/web/webview-proxy.d.ts.map +1 -1
  164. package/dist/web/webview-proxy.js +28 -15
  165. package/dist/web/webview-proxy.js.map +1 -1
  166. package/package.json +8 -7
  167. package/skills/codeman/SKILL.md +14 -10
  168. package/skills/codeman/preamble.sh +6 -3
  169. package/skills/codeman/reference/endpoints.md +10 -0
  170. package/skills/codeman/reference/recipes.md +1 -1
  171. package/skills/codeman/reference/verbs.md +26 -1
  172. package/dist/web/public/app.a5d2fc08.js +0 -38
  173. package/dist/web/public/app.a5d2fc08.js.br +0 -0
  174. package/dist/web/public/app.a5d2fc08.js.gz +0 -0
  175. package/dist/web/public/constants.7bd482dc.js.br +0 -0
  176. package/dist/web/public/constants.7bd482dc.js.gz +0 -0
  177. package/dist/web/public/i18n.9ae15b51.js +0 -1
  178. package/dist/web/public/i18n.9ae15b51.js.br +0 -0
  179. package/dist/web/public/i18n.9ae15b51.js.gz +0 -0
  180. package/dist/web/public/keyboard-accessory.0454a3e9.js.br +0 -0
  181. package/dist/web/public/keyboard-accessory.0454a3e9.js.gz +0 -0
  182. package/dist/web/public/mobile.87674154.css.gz +0 -0
  183. package/dist/web/public/notification-manager.5d229063.js.br +0 -0
  184. package/dist/web/public/notification-manager.5d229063.js.gz +0 -0
  185. package/dist/web/public/panels-ui.e6e06034.js.br +0 -0
  186. package/dist/web/public/panels-ui.e6e06034.js.gz +0 -0
  187. package/dist/web/public/session-ui.c558f981.js +0 -68
  188. package/dist/web/public/session-ui.c558f981.js.br +0 -0
  189. package/dist/web/public/session-ui.c558f981.js.gz +0 -0
  190. package/dist/web/public/settings-ui.1ed208dd.js.br +0 -0
  191. package/dist/web/public/settings-ui.1ed208dd.js.gz +0 -0
  192. package/dist/web/public/styles.421b36d4.css +0 -1
  193. package/dist/web/public/styles.421b36d4.css.br +0 -0
  194. package/dist/web/public/voice-input.4ec670b0.js.br +0 -0
  195. package/dist/web/public/voice-input.4ec670b0.js.gz +0 -0
@@ -0,0 +1,77 @@
1
+ "use strict";Object.assign(CodemanApp.prototype,{buildEnvOverrides(e,t){const s={};return(e?.agentTeams||t?.agentTeamsEnabled)&&(s.CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS="1"),s},getEffortSetting(e){const t=e?.thinkingEffort;return["low","medium","high","xhigh","max","ultracode"].includes(t)?t:void 0},formatCasePickerLabel(e){return e?.location==="remote"&&e.remote?.hostId?`${e.name} @ ${e.remote.hostId}`:e?.location==="docker"?`${e.name} (${this.dockerCaseTag(e.docker?.hostId)})`:e?.name||""},dockerCaseTag(e){return!e||e==="default"||e==="local"||/^q-/.test(e)?"docker":e},buildCasePickerOptions(e=[]){const t=[],s=new Set;for(const n of e)!n?.name||s.has(n.name)||(s.add(n.name),t.push(n));return s.has("testcase")||t.push({name:"testcase"}),t.map(n=>{const a=this.formatCasePickerLabel(n),i=[n.name,a,n.path,n.location,n.remote?.hostId,n.remote?.label,n.remote?.path,n.docker?.container,n.docker?.image,n.docker?.path].filter(Boolean).join(" ").toLowerCase();return{name:n.name,label:a,case:n,searchText:i}}).sort((n,a)=>n.label.localeCompare(a.label,void 0,{sensitivity:"base",numeric:!0}))},filterCasePickerOptions(e,t){const s=String(t||"").trim().toLowerCase().split(/\s+/).filter(Boolean);return s.length===0?e:e.filter(n=>s.every(a=>n.searchText.includes(a)))},getCasePickerOptions(){return this.buildCasePickerOptions(this.cases||[])},updateCasePickerInput(e){const t=document.getElementById("quickStartCaseSearch");if(!t)return;const s=this.getCasePickerOptions().find(n=>n.name===e);t.value=s?.label||e||"testcase",t.title=s?.label||t.value},renderQuickStartCaseSelectOptions(e,t){e&&(e.innerHTML=t.map(s=>`<option value="${escapeHtml(s.name)}">${escapeHtml(s.label)}</option>`).join(""))},openCasePicker(e=""){const t=document.getElementById("quickStartCaseSearch"),s=document.getElementById("quickStartCaseList");!t||!s||(this._casePickerOpen=!0,this._casePickerFilter=e,this._casePickerActiveIndex=0,t.setAttribute("aria-expanded","true"),this.renderCasePickerList())},closeCasePicker(){const e=document.getElementById("quickStartCaseSearch"),t=document.getElementById("quickStartCaseList");this._casePickerOpen=!1,this._casePickerFilter="",e?.setAttribute("aria-expanded","false"),e?.removeAttribute("aria-activedescendant"),t?.classList.add("hidden")},renderCasePickerList(){const e=document.getElementById("quickStartCaseSearch"),t=document.getElementById("quickStartCaseList"),s=document.getElementById("quickStartCase");if(!e||!t||!s)return;const n=this.filterCasePickerOptions(this.getCasePickerOptions(),this._casePickerFilter||""),a=s.value||"testcase",i=Math.max(0,n.length-1);if(this._casePickerActiveIndex=Math.min(Math.max(this._casePickerActiveIndex||0,0),i),n.length===0){t.innerHTML='<div class="case-combobox-empty">No cases match</div>',t.classList.remove("hidden"),e.removeAttribute("aria-activedescendant");return}t.innerHTML=n.map((o,r)=>{const c=r===this._casePickerActiveIndex,d=o.name===a;return`
2
+ <button
3
+ type="button"
4
+ id="${`quickStartCaseOption-${r}`}"
5
+ class="case-combobox-option ${c?"active":""} ${d?"selected":""}"
6
+ role="option"
7
+ aria-selected="${d?"true":"false"}"
8
+ data-case="${escapeHtml(o.name)}"
9
+ title="${escapeHtml(o.label)}">
10
+ <span class="case-combobox-check">${d?"\u2713":""}</span>
11
+ <span class="case-combobox-option-label">${escapeHtml(o.label)}</span>
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");if(!s)return;s.value=e||"testcase",this.updateCasePickerInput(s.value),this.closeCasePicker(),this.updateDirDisplayForCase(s.value),this.updateMobileCaseLabel(s.value);const n=(this.cases||[]).find(a=>a.name===s.value);n?.location==="docker"&&this._probeDockerCaseModes(n,null),t&&this.saveLastUsedCase(s.value)},setupQuickStartCasePicker(){const e=document.getElementById("quickStartCase"),t=document.getElementById("quickStartCaseSearch"),s=document.getElementById("quickStartCaseList"),n=document.getElementById("quickStartCasePicker");!e||!t||!s||!n||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",a=>{const i=this.filterCasePickerOptions(this.getCasePickerOptions(),this._casePickerFilter||t.value);if(a.key==="ArrowDown")a.preventDefault(),this._casePickerActiveIndex=Math.min((this._casePickerActiveIndex||0)+1,Math.max(0,i.length-1)),this._casePickerOpen?this.renderCasePickerList():this.openCasePicker(t.value);else if(a.key==="ArrowUp")a.preventDefault(),this._casePickerActiveIndex=Math.max((this._casePickerActiveIndex||0)-1,0),this._casePickerOpen?this.renderCasePickerList():this.openCasePicker(t.value);else if(a.key==="Enter"){const o=i[this._casePickerActiveIndex||0];o&&(a.preventDefault(),this.selectQuickStartCase(o.name),this.run?.())}else a.key==="Escape"?(a.preventDefault(),this.updateCasePickerInput(e.value),this.closeCasePicker()):a.key==="Tab"&&(this.updateCasePickerInput(e.value),this.closeCasePicker())}),s.addEventListener("mousedown",a=>a.preventDefault()),s.addEventListener("click",a=>{const i=a.target.closest?.(".case-combobox-option");i?.dataset?.case&&this.selectQuickStartCase(i.dataset.case)}),document.addEventListener&&!this._casePickerDocumentListenerAdded&&(document.addEventListener("pointerdown",a=>{n.contains(a.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 a=(await(await fetch("/api/cases")).json()).data;this.cases=a,console.log("[loadQuickStartCases] Loaded cases:",a.map(r=>r.name),"lastUsedCase:",s);const i=document.getElementById("quickStartCase"),o=this.getCasePickerOptions();if(this.renderQuickStartCaseSelectOptions(i,o),console.log("[loadQuickStartCases] Set options:",i.innerHTML.substring(0,200)),e)i.value=e,this.updateDirDisplayForCase(e),this.updateMobileCaseLabel(e);else if(s&&a.some(r=>r.name===s))i.value=s,this.updateDirDisplayForCase(s),this.updateMobileCaseLabel(s);else if(a.length>0){const r=a.find(c=>c.name==="testcase")||a[0];i.value=r.name,this.updateDirDisplayForCase(r.name),this.updateMobileCaseLabel(r.name)}else i.value="testcase",document.getElementById("dirDisplay").textContent="~/codeman-cases/testcase",this.updateMobileCaseLabel("testcase");this.updateCasePickerInput(i.value),this.renderCasePickerList(),this.closeCasePicker(),i.dataset.listenerAdded||(i.addEventListener("change",()=>{this.updateDirDisplayForCase(i.value),this.saveLastUsedCase(i.value),this.updateMobileCaseLabel(i.value),this.updateCasePickerInput(i.value)}),i.dataset.listenerAdded="true"),this.setupQuickStartCasePicker(),this._refreshMobileOverviewIfVisible?.()}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 a=await(await fetch(`/api/sessions/${encodeURIComponent(e)}`)).json();if(!a.success)throw new Error(a.error||"Failed to load the new session");s=a.data?.session||a.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 n=this._runMode||"claude";return n==="opencode"?await this.runOpenCode():n==="codex"?await this.runCodex():n==="gemini"?await this.runGemini():n==="antigravity"?await this.runAntigravity():n==="omp"?await this.runOmp():n==="pi"?await this.runPi():n==="grok"?await this.runGrok():n==="deepseek"?await this.runDeepSeek():n==="shell"?await this.runShell():await this.runClaude()}finally{const n=t-(Date.now()-e);n>0&&await new Promise(a=>setTimeout(a,n)),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(),this._refreshRunModeAvailability(t);const s=n=>{t.contains(n.target)||(t.classList.remove("active"),document.removeEventListener("click",s))};setTimeout(()=>document.addEventListener("click",s),0)}},_refreshRunModeAvailability(e){const t=document.getElementById("quickStartCase")?.value,s=t?(this.cases||[]).find(d=>d.name===t):null,n=s?.location==="docker",a=n&&(this._dockerCaseModes?.[t]||s.docker?.availableModes)||null;n&&!this._dockerCaseModes?.[t]&&this._probeDockerCaseModes(s,e);const i=n?this._dockerCaseProbeError?.[t]:null;for(const d of["claude","opencode","codex","gemini","antigravity","pi","grok","deepseek","omp"]){const l=e.querySelector(`.run-mode-option[data-mode="${d}"]`);if(!l)continue;let m;n?m=i?!1:a?a.includes(d):!0:m=this.isCliAvailable(d),l.style.display=m?"flex":"none"}this._renderRunModeNotice(e,i);const o=window.__codemanCliAvailable||{},r=e.querySelector("#runModeDeepSeekInstall");r&&(r.style.display=!o.deepseek&&o.deepseekBinary?"flex":"none");const c=e.querySelector("#runModeDeepSeekWeb");c&&(c.style.display=o.deepseekBinary?"flex":"none")},async runDeepSeekWeb(){document.getElementById("runModeMenu")?.classList.remove("active");const e=this._beginSessionLaunchStatus("Starting the DeepSeek web UI...");try{const s=await(await fetch("/api/deepseek/web",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({authority:location.host})})).json();if(!s.success)throw new Error(s.error||"Failed to start the DeepSeek web UI");const n=s.data.url;let a=[...this.webviews?.values()||[]].find(i=>i.managed==="deepseek-web");if(a){const o=await(await fetch(`/api/webviews/${a.id}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({url:n,trusted:!0})})).json();if(!o.success)throw new Error(o.error||"Failed to update the web tab");a=o.data.webview||o.data}else{const o=await(await fetch("/api/webviews",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:"DeepSeek Harness",url:n,icon:"\u{1F433}",managed:"deepseek-web",trusted:!0})})).json();if(!o.success)throw new Error(o.error||"Failed to save the web tab");a=o.data.webview||o.data}await this.refreshWebviews?.(),this._appendSessionLaunchStatus(e,`Serving on ${n} - opening it as a tab.`),a?.id&&await this.openWebview(a.id)}catch(t){this._reportSessionLaunchError(e,t.message)}},async installDeepSeekProfile(){const t=this._beginSessionLaunchStatus("Installing a DeepSeek terminal profile (this can take a minute)...");try{const n=await(await fetch("/api/deepseek/install-profile",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({})})).json();if(!n.success)throw new Error(n.error||"Failed to install the profile");window.__codemanCliAvailable={...window.__codemanCliAvailable||{},deepseek:!!n.data.runnable},this._appendSessionLaunchStatus(t,`Installed ${n.data.package} into profile "${n.data.profile}".`),this.showToast?.(`DeepSeek profile "${n.data.profile}" installed`,"success");const a=document.getElementById("runModeMenu");a&&this._refreshRunModeAvailability(a)}catch(s){this._reportSessionLaunchError(t,s.message)}},_renderRunModeNotice(e,t){if(!e)return;let s=e.querySelector(".run-mode-notice");if(!t){s?.remove();return}s||(s=document.createElement("div"),s.className="run-mode-notice",e.prepend(s)),s.textContent=t},async _probeDockerCaseModes(e,t){const s=e?.name,n=e?.docker?.container,a=e?.docker?.hostId;if(!(!s||!n||!a)&&(this._dockerCaseModes=this._dockerCaseModes||{},!this._dockerModeProbeInFlight?.[s])){this._dockerModeProbeInFlight=this._dockerModeProbeInFlight||{},this._dockerModeProbeInFlight[s]=!0;try{const i=await this._apiJson("/api/docker-cases/adopt-preflight",{method:"POST",body:{hostId:a,container:n}});i?.ok&&Array.isArray(i.availableModes)?(this._dockerCaseModes[s]=i.availableModes,delete this._dockerCaseProbeError?.[s]):(e?.docker?.owned===!1&&(this._dockerCaseProbeError=this._dockerCaseProbeError||{},this._dockerCaseProbeError[s]=i?.error||`Could not read container "${n}".`),delete this._dockerCaseModes[s]),t?.classList.contains("active")&&this._refreshRunModeAvailability(t)}finally{delete this._dockerModeProbeInFlight[s]}}},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 n=new Date(s.lastModified),a=n.toLocaleDateString("en",{month:"short",day:"numeric"})+" "+n.toLocaleTimeString("en",{hour:"2-digit",minute:"2-digit",hour12:!1}),i=this._shortenHomePath(s.workingDir),o=i.lastIndexOf("/"),r=o===-1?i:i.slice(o+1),c=(o===-1?"":i.slice(0,o)).replace(/\/\.claude\/worktrees$/,""),d=document.createElement("button");d.className="run-mode-option run-mode-hist-row",d.title=s.workingDir,d.dataset.sessionId=s.sessionId,d.dataset.workingDir=s.workingDir;const l=document.createElement("span");l.className="hist-name",l.textContent=r;const m=[l],h=this._worktreeLabel?this._worktreeLabel(s):"";if(h){const u=document.createElement("span");u.className="hist-wt",u.textContent=h,m.push(u)}if(c){const u=document.createElement("span");u.className="hist-dir",u.textContent=c,m.push(u)}const C=document.createElement("span");C.className="hist-meta",C.textContent=a,m.push(C),d.append(...m),d.addEventListener("click",u=>{u.stopPropagation(),this.resumeHistorySession(s.sessionId,s.workingDir,s.name,s.mode)}),e.appendChild(d)}}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,n=document.getElementById("runBtnLabel");t&&(t.className=`btn-toolbar btn-run mode-${e}`),s&&(s.className=`btn-toolbar btn-run-gear mode-${e}`),n&&(n.textContent=e==="opencode"?"Run OC":e==="codex"?"Run CX":e==="gemini"?"Run GM":e==="antigravity"?"Run AG":e==="pi"?"Run PI":e==="grok"?"Run GK":e==="deepseek"?"Run DS":e==="omp"?"Run OMP":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 n=1;for(const[,a]of this.sessions||[]){const i=a.name&&a.name.match(s);if(i&&i[2]===e){const o=parseInt(i[1]);o>=n&&(n=o+1)}}return n},_beginSessionLaunchStatus(e,t="1;32"){const s=!this.activeSessionId;return s?(this.terminal.clear(),this.terminal.writeln(`\x1B[${t}m ${e}\x1B[0m`),this.terminal.writeln("")):this.showToast?.(e,"info"),s},_appendSessionLaunchStatus(e,t,s="90"){!e||this.activeSessionId||this.terminal.writeln(`\x1B[${s}m ${t}\x1B[0m`)},_reportSessionLaunchError(e,t){e&&!this.activeSessionId?this.terminal.writeln(`\x1B[1;31m Error: ${t}\x1B[0m`):this.showToast?.(t,"error")},async runClaude(){const e=document.getElementById("quickStartCase").value||"testcase",t=Math.min(20,Math.max(1,parseInt(document.getElementById("tabCount").value)||1)),s=this._beginSessionLaunchStatus(`Starting ${t} Claude session(s) in ${e}...`);this.terminal.focus();try{let a=(await(await fetch(`/api/cases/${e}`)).json())?.data??{};if(!a.path){const S=await(await fetch("/api/cases",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:e,description:""})})).json();if(!S.success)throw new Error(S.error||"Failed to create case");a=S.data.case}const i=a.path;if(!i)throw new Error("Case path not found");if(a.location==="remote"||a.location==="docker"){const g=this._nextCaseSessionStartNumber(e);let S;if(a.location==="docker"){const E=this.loadAppSettingsFromStorage(),I=this.getCaseSettings(e).opusContext1m||E.opusContext1mEnabled;S=E.claudeModel||(I?"opus[1m]":"")}const b=[];let T=!1;for(let E=0;E<t;E++){const B=JSON.stringify({caseName:e,mode:"claude",sessionName:`w${g+E}-${e}`,...S!==void 0?{modelOverride:S}:{}}),I=async()=>(await fetch("/api/quick-start",{method:"POST",headers:{"Content-Type":"application/json"},body:B})).json();let v=await I();if(!v.success&&v.errorCode==="CONFLICT"&&a.location==="docker"&&!T&&(T=!0,confirm(`Container config for "${e}" changed since its container was created.
14
+
15
+ Recreate the container to apply the new config? Workspace files and the conversation survive (the conversation resumes on launch).`))){const _=await(await fetch(`/api/docker-cases/${encodeURIComponent(e)}/recreate`,{method:"POST"})).json();if(!_.success)throw new Error(_.error||"Failed to recreate container");v=await I()}if(!v.success)throw new Error(v.error||"Failed to start remote Claude session");await this._ensureCreatedSessionVisible(v.data.sessionId,v.data.session),b.push(v.data.sessionId)}this._appendSessionLaunchStatus(s,`All ${t} remote session(s) ready`),b[0]&&(await this.selectSession(b[0]),this.loadQuickStartCases()),this.terminal.focus();return}let o=null;const r=this._nextCaseSessionStartNumber(e),c=this.isRalphTrackerEnabledByDefault(),d=[];for(let g=0;g<t;g++)d.push(`w${r+g}-${e}`);const l=this.getCaseSettings(e),m=this.loadAppSettingsFromStorage(),h=this.buildEnvOverrides(l,m),C=Object.keys(h).length>0,u=this.getEffortSetting(m),f=l.opusContext1m||m.opusContext1mEnabled,y=m.claudeModel||(f?"opus[1m]":"");this._appendSessionLaunchStatus(s,`Creating ${t} session(s)...`);const k=d.map(g=>fetch("/api/sessions",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({workingDir:i,name:g,...C?{envOverrides:h}:{},...u?{effort:u}:{},...y!==void 0?{modelOverride:y}:{},statusLineTelemetry:this.planUsageChipEnabled(m)})}).then(S=>S.json())),p=await Promise.all(k),w=[];for(const g of p){if(!g.success)throw new Error(g.error);await this._ensureCreatedSessionVisible(g.data.session.id,g.data.session),w.push(g.data.session.id)}o=w[0],await Promise.all(w.map(g=>fetch(`/api/sessions/${g}/ralph-config`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({enabled:c,disableAutoEnable:!c})}))),this._appendSessionLaunchStatus(s,`Starting ${t} session(s) in parallel...`),await Promise.all(w.map(g=>fetch(`/api/sessions/${g}/interactive`,{method:"POST"}))),this._appendSessionLaunchStatus(s,`All ${t} sessions ready`),o&&(await this.selectSession(o),this.loadQuickStartCases()),this.terminal.focus()}catch(n){this._reportSessionLaunchError(s,n.message)}},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)),s=this._beginSessionLaunchStatus(`Starting ${t} Shell session(s) in ${e}...`,"1;33");try{let a=(await(await fetch(`/api/cases/${e}`)).json())?.data??{};if(!a.path){const f=await(await fetch("/api/cases",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:e,description:""})})).json();if(!f.success)throw new Error(f.error||"Failed to create case");a=f.data.case}const i=(this.cases||[]).find(u=>u.name===e),o=a.location==="remote"||a.location==="docker"||i?.location==="remote"||i?.location==="docker",r=a.path;if(!r)throw new Error("Case path not found");if(a.location==="remote"||a.location==="docker"){const u=this._nextCaseSessionStartNumber(e,"s"),f=[];for(let y=0;y<t;y++){const p=await(await fetch("/api/quick-start",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({caseName:e,mode:"shell",sessionName:`s${u+y}-${e}`})})).json();if(!p.success)throw new Error(p.error||"Failed to start remote shell session");await this._ensureCreatedSessionVisible(p.data.sessionId,p.data.session),f.push(p.data.sessionId)}f[0]&&await this.selectSession(f[0]),this.terminal.focus();return}const c=this._nextCaseSessionStartNumber(e,"s"),d=[];for(let u=0;u<t;u++)d.push(`s${c+u}-${e}`);const l=d.map(u=>fetch("/api/sessions",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...o?{caseName:e}:{workingDir:r},mode:"shell",name:u})}).then(f=>f.json())),m=await Promise.all(l),h=[];for(const u of m){if(!u.success)throw new Error(u.error);await this._ensureCreatedSessionVisible(u.data.session.id,u.data.session),h.push(u.data.session.id)}await Promise.all(h.map(u=>fetch(`/api/sessions/${u}/shell`,{method:"POST"})));const C=this.getTerminalDimensions();C&&await Promise.all(h.map(u=>fetch(`/api/sessions/${u}/resize`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(C)}))),h.length>0&&await this.selectSession(h[0]),this.terminal.focus()}catch(n){this._reportSessionLaunchError(s,n.message)}},async runOpenCode(){const e=document.getElementById("quickStartCase").value||"testcase",t=(this.cases||[]).find(a=>a.name===e)?.location,s=t==="remote"||t==="docker",n=this._beginSessionLaunchStatus(`Starting OpenCode session in ${e}...`);this.terminal.focus();try{if(!s&&!(await(await fetch("/api/opencode/status")).json()).data.available){this._reportSessionLaunchError(n,"OpenCode CLI not found. Install with: curl -fsSL https://opencode.ai/install | bash");return}const a=this.buildEnvOverrides(this.getCaseSettings(e),this.loadAppSettingsFromStorage()),o=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(!o.success)throw new Error(o.error||"Failed to start OpenCode");await this._ensureCreatedSessionVisible(o.data.sessionId,o.data.session),o.data.sessionId&&await this.selectSession(o.data.sessionId),this.terminal.focus()}catch(a){this._reportSessionLaunchError(n,a.message)}},async runCodex(){const e=document.getElementById("quickStartCase").value||"testcase",t=(this.cases||[]).find(a=>a.name===e)?.location,s=t==="remote"||t==="docker",n=this._beginSessionLaunchStatus(`Starting Codex session in ${e}...`);this.terminal.focus();try{if(!s&&!(await(await fetch("/api/codex/status")).json()).data.available){this._reportSessionLaunchError(n,"Codex CLI not found. Install with: npm install -g @openai/codex");return}const a=this.loadAppSettingsFromStorage(),i=this.buildEnvOverrides(this.getCaseSettings(e),a),r=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,animations:a.codexAnimationsEnabled??!1,renderMode:"hybrid"},...Object.keys(i).length>0?{envOverrides:i}:{}}})})).json();if(!r.success)throw new Error(r.error||"Failed to start Codex");await this._ensureCreatedSessionVisible(r.data.sessionId,r.data.session),r.data.sessionId&&await this.selectSession(r.data.sessionId),this.terminal.focus()}catch(a){this._reportSessionLaunchError(n,a.message)}},async runGemini(){const e=document.getElementById("quickStartCase").value||"testcase",t=(this.cases||[]).find(a=>a.name===e)?.location,s=t==="remote"||t==="docker",n=this._beginSessionLaunchStatus(`Starting Gemini session in ${e}...`);this.terminal.focus();try{if(!s&&!(await(await fetch("/api/gemini/status")).json()).data.available){this._reportSessionLaunchError(n,"Gemini CLI not found. Install with: npm install -g @google/gemini-cli");return}const a=this.buildEnvOverrides(this.getCaseSettings(e),this.loadAppSettingsFromStorage()),o=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(!o.success)throw new Error(o.error||"Failed to start Gemini");await this._ensureCreatedSessionVisible(o.data.sessionId,o.data.session),o.data.sessionId&&await this.selectSession(o.data.sessionId),this.terminal.focus()}catch(a){this._reportSessionLaunchError(n,a.message)}},async runAntigravity(){const e=document.getElementById("quickStartCase").value||"testcase",t=(this.cases||[]).find(a=>a.name===e)?.location,s=t==="remote"||t==="docker",n=this._beginSessionLaunchStatus(`Starting Antigravity session in ${e}...`);this.terminal.focus();try{if(!s&&!(await(await fetch("/api/antigravity/status")).json()).data.available){this._reportSessionLaunchError(n,"Antigravity CLI not found. Install with: curl -fsSL https://antigravity.google/cli/install.sh | bash");return}const a=this.buildEnvOverrides(this.getCaseSettings(e),this.loadAppSettingsFromStorage()),o=await(await fetch("/api/quick-start",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({caseName:e,mode:"antigravity",sessionName:`w${this._nextCaseSessionStartNumber(e)}-${e}`,...s?{}:{antigravityConfig:{dangerouslySkipPermissions:!0},...Object.keys(a).length>0?{envOverrides:a}:{}}})})).json();if(!o.success)throw new Error(o.error||"Failed to start Antigravity");await this._ensureCreatedSessionVisible(o.data.sessionId,o.data.session),o.data.sessionId&&await this.selectSession(o.data.sessionId),this.terminal.focus()}catch(a){this._reportSessionLaunchError(n,a.message)}},async runPi(){const e=document.getElementById("quickStartCase").value||"testcase",t=(this.cases||[]).find(a=>a.name===e)?.location,s=t==="remote"||t==="docker",n=this._beginSessionLaunchStatus(`Starting Pi session in ${e}...`);this.terminal.focus();try{if(!s&&!(await(await fetch("/api/pi/status")).json()).data.available){this._reportSessionLaunchError(n,"Pi CLI not found. Install with: npm install -g --ignore-scripts @earendil-works/pi-coding-agent");return}const a=this.buildEnvOverrides(this.getCaseSettings(e),this.loadAppSettingsFromStorage()),o=await(await fetch("/api/quick-start",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({caseName:e,mode:"pi",sessionName:`w${this._nextCaseSessionStartNumber(e)}-${e}`,...s||Object.keys(a).length===0?{}:{envOverrides:a}})})).json();if(!o.success)throw new Error(o.error||"Failed to start Pi");await this._ensureCreatedSessionVisible(o.data.sessionId,o.data.session),o.data.sessionId&&await this.selectSession(o.data.sessionId),this.terminal.focus()}catch(a){this._reportSessionLaunchError(n,a.message)}},async runOmp(){const e=document.getElementById("quickStartCase").value||"testcase",t=(this.cases||[]).find(a=>a.name===e)?.location,s=t==="remote"||t==="docker",n=this._beginSessionLaunchStatus(`Starting OMP session in ${e}...`);this.terminal.focus();try{if(!s&&!(await(await fetch("/api/omp/status")).json()).data.available){this._reportSessionLaunchError(n,"OMP CLI not found. Install with: curl -fsSL https://omp.sh/install | sh");return}const a=this.buildEnvOverrides(this.getCaseSettings(e),this.loadAppSettingsFromStorage()),o=await(await fetch("/api/quick-start",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({caseName:e,mode:"omp",sessionName:`w${this._nextCaseSessionStartNumber(e)}-${e}`,...s?{}:{...Object.keys(a).length>0?{envOverrides:a}:{}}})})).json();if(!o.success)throw new Error(o.error||"Failed to start OMP");await this._ensureCreatedSessionVisible(o.data.sessionId,o.data.session),o.data.sessionId&&await this.selectSession(o.data.sessionId),this.terminal.focus()}catch(a){this._reportSessionLaunchError(n,a.message)}},async runGrok(){const e=document.getElementById("quickStartCase").value||"testcase",t=(this.cases||[]).find(a=>a.name===e)?.location,s=t==="remote"||t==="docker",n=this._beginSessionLaunchStatus(`Starting Grok session in ${e}...`);this.terminal.focus();try{if(!s&&!(await(await fetch("/api/grok/status")).json()).data.available){this._reportSessionLaunchError(n,"Grok CLI not found. Install with: curl -fsSL https://x.ai/cli/install.sh | bash");return}const a=this.buildEnvOverrides(this.getCaseSettings(e),this.loadAppSettingsFromStorage()),o=await(await fetch("/api/quick-start",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({caseName:e,mode:"grok",sessionName:`w${this._nextCaseSessionStartNumber(e)}-${e}`,...s?{}:{grokConfig:{alwaysApprove:!0},...Object.keys(a).length>0?{envOverrides:a}:{}}})})).json();if(!o.success)throw new Error(o.error||"Failed to start Grok");await this._ensureCreatedSessionVisible(o.data.sessionId,o.data.session),o.data.sessionId&&await this.selectSession(o.data.sessionId),this.terminal.focus()}catch(a){this._reportSessionLaunchError(n,a.message)}},async runDeepSeek(){const e=document.getElementById("quickStartCase").value||"testcase",t=(this.cases||[]).find(a=>a.name===e)?.location,s=t==="remote"||t==="docker",n=this._beginSessionLaunchStatus(`Starting DeepSeek session in ${e}...`);this.terminal.focus();try{if(!s){const c=(await(await fetch("/api/deepseek/status")).json()).data;if(!c.available){this._reportSessionLaunchError(n,"DeepSeek Harness CLI (dsh) not found. Install with: npm install -g @deepseek-ai/dsh");return}if(!c.runnable){this._reportSessionLaunchError(n,"No interactive DeepSeek Harness profile is installed. DeepSeek ships only web and headless profiles, so the terminal agent comes from a plugin. Install one from the Run menu, or run: dsh plugin --profile dsh-tui add @deepseek-harness-tui/dsh-tui");return}}const a=this.buildEnvOverrides(this.getCaseSettings(e),this.loadAppSettingsFromStorage()),o=await(await fetch("/api/quick-start",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({caseName:e,mode:"deepseek",sessionName:`w${this._nextCaseSessionStartNumber(e)}-${e}`,...s?{}:{deepSeekConfig:{permissionMode:"danger-full-access"},...Object.keys(a).length>0?{envOverrides:a}:{}}})})).json();if(!o.success)throw new Error(o.error||"Failed to start DeepSeek");await this._ensureCreatedSessionVisible(o.data.sessionId,o.data.session),o.data.sessionId&&await this.selectSession(o.data.sessionId),this.terminal.focus()}catch(a){this._reportSessionLaunchError(n,a.message)}},_tabDetachOverrides(){if(this._tabDetachOverrideMap===void 0)try{this._tabDetachOverrideMap=JSON.parse(localStorage.getItem("codeman:tab-detach-overrides")||"{}")||{}}catch{this._tabDetachOverrideMap={}}return this._tabDetachOverrideMap},hasTabDetachOverride(e){return!!this._tabDetachOverrides()[e]},onSessionTabDetachToggle(e){const t=this.editingSessionId;if(!t)return;const s=this._tabDetachOverrides();e?s[t]=1:delete s[t];for(const a of Object.keys(s))a!==t&&this.sessions&&!this.sessions.has(a)&&delete s[a];try{localStorage.setItem("codeman:tab-detach-overrides",JSON.stringify(s))}catch{}const n=document.querySelector(`.session-tab[data-id="${CSS.escape(t)}"]`);n&&n.classList.toggle("tab-show-detach",!!e)},openSessionOptions(e){const t=this.sessions.get(e);if(!t)return;this.editingSessionId=e;const s=document.getElementById("sessionOptShowTabDetach");s&&(s.checked=this.hasTabDetachOverride(e));const n=t.mode==="opencode"||t.mode==="codex"||t.mode==="gemini"||t.mode==="antigravity"||t.mode==="pi"||t.mode==="grok"||t.mode==="deepseek"||t.mode==="omp";this.switchOptionsTab(n?"summary":"respawn");const a=document.getElementById("sessionRespawnStatus"),i=document.getElementById("modalEnableRespawnBtn"),o=document.getElementById("modalStopRespawnBtn");this.respawnStatus[e]?(a.classList.add("active"),a.querySelector(".respawn-status-text").textContent=this.respawnStatus[e].state||"Active",i.style.display="none",o.style.display=""):(a.classList.remove("active"),a.querySelector(".respawn-status-text").textContent="Not active",i.style.display="",o.style.display="none");const r=document.getElementById("sessionRespawnSection");t.mode==="claude"&&t.pid?r.style.display="":r.style.display="none";const c=t.mode==="opencode"||t.mode==="codex"||t.mode==="gemini"||t.mode==="antigravity"||t.mode==="pi"||t.mode==="grok"||t.mode==="deepseek"||t.mode==="omp";document.querySelectorAll("[data-claude-only]").forEach(k=>{k.style.display=c?"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 l=parseSessionPrefix(t.name),m=document.getElementById("modalSessionPrefix");l?(m.textContent=l.prefix+": ",m.style.display="",document.getElementById("modalSessionName").value=l.suffix,document.getElementById("modalSessionName").placeholder="Add description..."):(m.style.display="none",m.textContent="",document.getElementById("modalSessionName").value=t.name||"",document.getElementById("modalSessionName").placeholder="Auto (directory name)");const h=t.color||"default";document.getElementById("sessionColorPicker")?.querySelectorAll(".color-swatch").forEach(k=>{k.classList.toggle("selected",k.dataset.color===h)}),this.renderPresetDropdown(),document.getElementById("respawnPresetSelect").value="",document.getElementById("presetDescriptionHint").textContent="";const u=document.querySelector('#sessionOptionsModal .set-rail-item[data-tab="ralph"]'),f=document.querySelector('#sessionOptionsModal .set-rail-item[data-tab="respawn"]');if(c?(u&&(u.style.display="none"),f&&(f.style.display="none"),this.switchOptionsTab("context")):(u&&(u.style.display=""),f&&(f.style.display="")),!c){const k=this.ralphStates.get(e);this.populateRalphForm({enabled:k?.loop?.enabled??t.ralphLoop?.enabled??!1,completionPhrase:k?.loop?.completionPhrase||t.ralphLoop?.completionPhrase||"",maxIterations:k?.loop?.maxIterations||t.ralphLoop?.maxIterations||0,maxTodos:k?.loop?.maxTodos||t.ralphLoop?.maxTodos,todoExpirationMinutes:k?.loop?.todoExpirationMinutes||t.ralphLoop?.todoExpirationMinutes})}const y=document.getElementById("sessionOptionsModal");y.dataset.chipsReady!=="1"&&(y.dataset.chipsReady="1",y.addEventListener("change",k=>{k.target?.closest?.(".set-chip")&&this._syncSettingsChips()})),this._syncSettingsChips(),y.classList.add("active"),this.activeFocusTrap=new FocusTrap(y),this.activeFocusTrap.activate()},_applyLocalSessionName(e,t){if(typeof t!="string")return;const s=this.sessions.get(e);s&&(s.name=t,this.sessions.set(e,s),this.updateSubagentParentNames?.(e))},async _putSessionName(e,t){const s=await this._apiPut(`/api/sessions/${e}/name`,{name:t});if(!s||!s.ok)return null;let n=null;try{n=await s.json()}catch{return null}if(n&&n.success===!1)return null;const a=n?.data?.name;return typeof a=="string"?a:t},async saveSessionName(){if(!this.editingSessionId)return;const e=this.editingSessionId,t=this.sessions.get(e),s=t?parseSessionPrefix(t.name):null,n=document.getElementById("modalSessionName").value.trim();let a;s?a=s.prefix+(n?": "+n:""):a=n;const i=await this._putSessionName(e,a);if(i===null){this.showToast("Failed to save session name","error");return}this._applyLocalSessionName(e,i),this.renderSessionTabs()},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 n=new Date(s.autoResumeAt).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});t.textContent=`Usage limit pause active \u2014 resumes at ${n}`,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 n=s.data.config;document.getElementById("modalRespawnPrompt").value=n.updatePrompt||"update all the docs and CLAUDE.md",document.getElementById("modalRespawnSendClear").checked=n.sendClear??!0,document.getElementById("modalRespawnSendInit").checked=n.sendInit??!0,document.getElementById("modalRespawnKickstart").value=n.kickstartPrompt||"",document.getElementById("modalRespawnAutoAccept").checked=n.autoAcceptPrompts??!0,n.durationMinutes&&(document.querySelector(`.duration-preset-btn[data-minutes="${n.durationMinutes}"]`)?this.selectDurationPreset(String(n.durationMinutes)):(this.selectDurationPreset("custom"),document.getElementById("modalRespawnDuration").value=n.durationMinutes))}}catch{}},selectDurationPreset(e){document.querySelectorAll(".duration-preset-btn").forEach(a=>a.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"),n=document.getElementById("modalRespawnDuration");e==="custom"?(s.classList.add("visible"),n.focus()):(s.classList.remove("visible"),n.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 n=document.querySelector(".duration-preset-btn.active")?.dataset.minutes;return n?parseInt(n):null}},switchOptionsTab(e){document.querySelectorAll("#sessionOptionsModal .set-rail-item").forEach(s=>{s.classList.toggle("active",s.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");const t=document.getElementById("sessionOptionsDoc");t&&(t.scrollTop=0),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;this._activeRename?.cancel();const s=document.querySelector(`.tab-name[data-session-id="${e}"]`);if(!s)return;this._inlineRenameActive=!0,s.classList.add("tab-name-renaming");const n=this.getSessionName(t),a=parseSessionPrefix(t.name),i=s.textContent,o=[...s.childNodes].map(p=>p.cloneNode(!0)),r=()=>{s.replaceChildren(...o.map(p=>p.cloneNode(!0)))};for(s.textContent="";s.firstChild;)s.removeChild(s.firstChild);if(a){const p=document.createElement("span");p.className="tab-rename-prefix",p.textContent=a.prefix+": ",p.style.cssText="color: var(--text-muted); font-size: 0.75rem; white-space: nowrap;",s.appendChild(p)}const c=document.createElement("input");c.type="text",c.value=a?a.suffix:t.name||"",c.placeholder=a?"Add description...":n,c.className="tab-rename-input";const d=s.closest(".tab-rail")?"auto":this.isSessionSidebarActive?.()?"100%":"80px";c.style.cssText=`width: ${d}; min-width: 0; 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(c),c.focus(),c.select();let l=!1,m=!1,h=!1;const C=()=>{this._activeRename===k&&(this._inlineRenameActive=!1)},u=()=>{this._activeRename===k&&(h=!0,C(),this._activeRename=null,this.renderSessionTabs())},f=()=>{m||h||(m=!0,l=!0,s.classList.remove("tab-name-renaming"),r(),u())},y=async({commit:p})=>{if(l||m)return;if(l=!0,s.classList.remove("tab-name-renaming"),!p){f();return}if(this._activeRename!==k)return;C();const w=c.value.trim(),g=a?a.prefix+(w?": "+w:""):w;if(g===t.name?r():s.textContent=g||i,this.sessions.has(e)&&g!==t.name){const b=await this._putSessionName(e,g);if(m||this._activeRename!==k||!this.sessions.has(e))return;b===null?(r(),this.showToast("Failed to rename","error")):this._applyLocalSessionName(e,b)}u()},k={sessionId:e,cancel:f};this._activeRename=k,c.addEventListener("blur",()=>y({commit:!0})),c.addEventListener("keydown",p=>{p.isComposing||p.keyCode===229||(p.key==="Enter"?(p.preventDefault(),c.blur()):p.key==="Escape"&&(p.preventDefault(),f()))})},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 n=a=>{!e.contains(a.target)&&!a.target.classList.contains("btn-case-settings")&&(e.classList.add("hidden"),document.removeEventListener("click",n))};setTimeout(()=>document.addEventListener("click",n),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 n=document.getElementById("caseOpusContext1mMobile");n&&(n.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 n=a=>{!e.contains(a.target)&&!a.target.classList.contains("btn-case-settings-mobile")&&(e.classList.add("hidden"),document.removeEventListener("click",n))};setTimeout(()=>document.addEventListener("click",n),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 n=document.getElementById("caseOpusContext1m");n&&(n.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(r=>{const c=document.getElementById(r);c&&(c.value="")}),this._resetCloneForm();const t=document.getElementById("caseCloneTabBtn");t&&(t.style.display=this.isCliAvailable("git")?"":"none"),this.caseModalTab="case-create",this.switchCaseModalTab("case-create");const s=document.getElementById("createCaseModal");s.querySelectorAll(".set-rail-item").forEach(r=>{r.onclick=()=>this.switchCaseModalTab(r.dataset.tab)});const n=document.getElementById("dockerAdoptExisting");n&&(n.onchange=()=>this._syncDockerAdoptMode());const a=document.getElementById("dockerAdoptCheckBtn");a&&(a.onclick=()=>this._dockerAdoptPreflight());const i=document.getElementById("dockerAdoptJumpBtn");i&&(i.onclick=()=>this.jumpToDockerAdopt());const o=document.getElementById("dockerHostId");o&&(o.onchange=()=>{delete document.getElementById("dockerContainerList")?.dataset.loadedFor,document.getElementById("dockerAdoptExisting")?.checked&&this._loadDockerContainerOptions()}),delete document.getElementById("dockerContainerList")?.dataset.loadedFor,this._syncDockerAdoptMode(),s.querySelectorAll('input[type="text"]').forEach(r=>{r._mobileScrollWired||(r._mobileScrollWired=!0,r.addEventListener("focus",()=>{window.innerWidth<=430&&setTimeout(()=>r.scrollIntoView({behavior:"smooth",block:"center"}),300)}))}),s.classList.add("active"),document.getElementById("newCaseName").focus()},switchCaseModalTab(e){this.caseModalTab=e;const t=document.getElementById("createCaseModal");t.querySelectorAll(".set-rail-item").forEach(a=>{a.classList.toggle("active",a.dataset.tab===e)}),t.querySelectorAll(".set-section").forEach(a=>{a.classList.toggle("hidden",a.id!==e)});const s=document.getElementById("createCaseDoc");s&&(s.scrollTop=0);const n=["caseModalSubmit","caseModalSubmitMobile"].map(a=>document.getElementById(a)).filter(Boolean);if(e==="case-manage")n.forEach(a=>{a.style.display="none"}),this.renderCaseManageList(),this.refreshDockerExports();else{const a=e==="case-create"?"Create":e==="case-clone"?"Clone":e==="case-remote"?"Link Remote":e==="case-docker"?"Link Docker":"Link";n.forEach(i=>{i.style.display="",i.textContent=a})}e==="case-create"?document.getElementById("newCaseName").focus():e==="case-clone"?document.getElementById("cloneRepoUrl").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=["caseModalSubmit","caseModalSubmitMobile"].map(n=>document.getElementById(n)).filter(Boolean),t=e.map(n=>n.textContent),s=this.caseModalTab==="case-create"?"Creating...":this.caseModalTab==="case-clone"?"Cloning...":"Linking...";e.forEach(n=>{n.classList.add("loading"),n.textContent=s,n.disabled=!0});try{this.caseModalTab==="case-create"?await this.createCase():this.caseModalTab==="case-clone"?await this.cloneCase():this.caseModalTab==="case-remote"?await this.linkRemoteCase():this.caseModalTab==="case-docker"?await this.linkDockerCase():await this.linkCase()}finally{e.forEach((n,a)=>{n.classList.remove("loading"),n.disabled=!1,n.textContent=t[a]})}},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,n=s?"/api/cases/docker-quickcreate":"/api/cases",a=s?{name:e,description:t,...this._collectDockerQuickSettings()}:{name:e,description:t};try{const o=await(await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)})).json();if(o.success)if(this.closeCreateCaseModal(),await this.loadQuickStartCases(e),await this.saveLastUsedCase(e),s){const r=o.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(o.error||"Failed to create case","error")}catch(i){console.error("Failed to create case:",i),this.showToast("Failed to create case: "+i.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 n=(a,i)=>{const o=document.getElementById(a);o&&(o.value=i)};n("quickDockerMemory",s.m),n("quickDockerCpus",s.c),n("quickDockerGpus",s.g)},_collectDockerQuickSettings(){const e=c=>(document.getElementById(c)?.value||"").trim(),t={},s=e("quickDockerMemory");s&&(t.memory=s);const n=e("quickDockerCpus");n&&(t.cpus=n);const a=e("quickDockerGpus");a&&a.toLowerCase()!=="none"&&(t.gpus=a);const i=document.getElementById("quickDockerNetwork")?.value;i&&i!=="bridge"&&(t.network=i);const o=e("quickDockerImage");o&&(t.image=o);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 n=await(await fetch("/api/cases/link",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:e,path:t})})).json();n.success?(this.closeCreateCaseModal(),this.showToast(`Case "${e}" linked to ${t}`,"success"),await this.loadQuickStartCases(e),await this.saveLastUsedCase(e)):this.showToast(n.error||"Failed to link case","error")}catch(s){console.error("Failed to link case:",s),this.showToast("Failed to link case: "+s.message,"error")}},_resetCloneForm(){const e=(o,r)=>{const c=document.getElementById(o);c&&(c.value=r)};e("cloneRepoUrl",""),e("cloneCaseName",""),e("cloneRepoRef","");const t=document.getElementById("cloneShallow");t&&(t.checked=!1);const s=document.getElementById("cloneStartSession");s&&(s.checked=!1);const n=document.getElementById("cloneRepoRefOptions");n&&n.replaceChildren();const a=document.getElementById("cloneRefHint");a&&(a.textContent="Leave blank for the repository's default branch."),this._cloneNameEdited=!1,this._clonePreflight=null,clearTimeout(this._clonePreflightTimer),this._clonePreflightAbort?.abort(),this._clonePreflightAbort=null,this._setCloneStatus("Public repositories only: Codeman clones with no credentials.","");const i=document.getElementById("cloneCaseBrain");if(i){for(const r of i.options){const c=r.dataset.cli;r.hidden=!!c&&!this.isCliAvailable(c)}const o=this.runMode||"claude";i.value=[...i.options].some(r=>r.value===o&&!r.hidden)?o:""}},_setCloneStatus(e,t){const s=document.getElementById("cloneRepoStatus");s&&(s.textContent=e,s.className=`form-hint clone-status${t?" clone-status-"+t:""}`)},_repoNameFromUrl(e){const t=(e||"").trim().replace(/\/+$/,"");return t?(t.replace(/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//,"").replace(/^[^@/]*@/,"").split(/[/:]/).filter(Boolean).pop()||"").replace(/\.git$/i,"").replace(/[^a-zA-Z0-9_-]+/g,"-").replace(/-{2,}/g,"-").replace(/^[-_]+|[-_]+$/g,"").slice(0,64):""},onCloneNameEdited(){this._cloneNameEdited=!!document.getElementById("cloneCaseName")?.value.trim()},onCloneUrlInput(){const e=document.getElementById("cloneRepoUrl")?.value.trim()||"",t=document.getElementById("cloneCaseName");if(t&&!this._cloneNameEdited&&(t.value=this._repoNameFromUrl(e)),clearTimeout(this._clonePreflightTimer),this._clonePreflightAbort?.abort(),this._clonePreflightAbort=null,!e){this._setCloneStatus("Public repositories only: Codeman clones with no credentials.","");return}if(this.isCliAvailable("git")===!1){this._setCloneStatus("git is not installed on the Codeman host, so cloning is unavailable.","err");return}this._setCloneStatus("Checking the repository\u2026",""),this._clonePreflightTimer=setTimeout(()=>this._runClonePreflight(e),450)},async _runClonePreflight(e){const t=new AbortController;this._clonePreflightAbort=t;try{const n=await(await fetch("/api/cases/clone-preflight",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({repository:e}),signal:t.signal})).json();if(document.getElementById("cloneRepoUrl")?.value.trim()!==e)return;if(!n.success){this._setCloneStatus(n.error||"Could not check that URL.","err");return}this._applyClonePreflight(n.data,e)}catch(s){if(s.name==="AbortError")return;this._setCloneStatus("Could not reach Codeman to check that URL.","err")}},_applyClonePreflight(e,t){this._clonePreflight=e;const s=e?.parse;if(!s?.cloneable){this._setCloneStatus(s?.message||"That URL cannot be cloned.","err");return}const n=document.getElementById("cloneCaseName");n&&!this._cloneNameEdited&&s.suggestedName&&(n.value=s.suggestedName);const a=s.owner?`${s.provider} ${s.owner}/${s.repo}`:`${s.provider} ${s.repo}`;if(e.gitAvailable===!1){this._setCloneStatus(`${a}: git is not installed on the Codeman host.`,"err");return}const i=e.remote;if(i&&!i.reachable){this._setCloneStatus(`${a}: ${i.failure?.message||"the remote could not be read."}`,"err");return}const o=document.getElementById("cloneRefHint"),r=document.getElementById("cloneRepoRefOptions");if(i&&r){r.replaceChildren();for(const d of[...i.branches||[],...i.tags||[]]){const l=document.createElement("option");l.value=d,r.appendChild(l)}if(o){const d=`${i.branches?.length||0} branches, ${i.tags?.length||0} tags`;o.textContent=i.defaultBranch?`Blank clones the default branch (${i.defaultBranch}). ${d} available.`:`Blank clones the default branch. ${d} available.`}}const c=s.warnings?.[0];this._setCloneStatus(c?`${a}: ${c}`:`${a}: ready to clone.`,c?"warn":"ok")},async cloneCase(){const e=document.getElementById("cloneRepoUrl").value.trim(),t=document.getElementById("cloneCaseName").value.trim(),s=document.getElementById("cloneRepoRef").value.trim(),n=!!document.getElementById("cloneShallow")?.checked,a=document.getElementById("cloneCaseBrain")?.value||"",i=!!document.getElementById("cloneStartSession")?.checked;if(!e){this.showToast("Please enter a repository URL","error");return}if(!t){this.showToast("Please enter a case name","error");return}if(!/^[a-zA-Z0-9_-]+$/.test(t)){this.showToast("Invalid name. Use only letters, numbers, hyphens, underscores.","error");return}this._setCloneStatus(`Cloning ${e}\u2026 this can take a while for a large repository.`,"");try{const r=await(await fetch("/api/cases/clone",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:t,repository:e,...s?{ref:s}:{},...n?{shallow:!0}:{}})})).json();if(!r.success){this._setCloneStatus(r.error||"Clone failed.","err"),this.showToast(r.error||"Failed to clone repository","error");return}a&&this.setRunMode(a),this.closeCreateCaseModal(),await this.loadQuickStartCases(t),await this.saveLastUsedCase(t),this.showToast(`Cloned into case "${t}"`,"success");for(const c of r.data?.warnings||[])this.showToast(c,"warning");i&&await this.run()}catch(o){console.error("Failed to clone repository:",o),this._setCloneStatus(`Lost the connection while cloning: ${o.message}. If git finishes, the case still appears in the list.`,"warn"),this.showToast("Clone request interrupted \u2014 watch the case list","error")}},openLinkCasePathPicker(){const e=document.getElementById("linkCasePath");PathPicker.open({title:"Select Existing Project Folder",initialPath:e.value.trim(),directoriesOnly:!0,onSelect:t=>{e.value=t;const s=document.getElementById("linkCaseName");if(!s.value.trim()){const n=t.split("/").filter(Boolean).pop()||"";/^[\p{L}\p{N}_-]+$/u.test(n)&&(s.value=n)}e.focus(),e.setSelectionRange(t.length,t.length)}})},openDockerWorkspacePathPicker(){const e=document.getElementById("dockerWorkspacePath");PathPicker.open({title:"Select Host Workspace Folder",initialPath:e.value.trim(),directoriesOnly:!0,onSelect:t=>{e.value=t;const s=document.getElementById("dockerCaseName");if(s&&!s.value.trim()){const n=t.split("/").filter(Boolean).pop()||"";/^[a-zA-Z0-9_-]+$/.test(n)&&(s.value=n)}}})},openDockerWorkdirPicker(){const e=document.getElementById("dockerAdoptWorkdir"),t=document.getElementById("dockerContainerName")?.value.trim(),s=document.getElementById("dockerHostId")?.value.trim()||"local";if(!t){this.showToast("Enter the container name first","error");return}PathPicker.open({title:`Select Folder Inside ${t}`,initialPath:e.value.trim()||"/",directoriesOnly:!0,fetchListing:async n=>{const a=await this._apiJson("/api/docker-cases/browse",{method:"POST",body:{hostId:s,container:t,path:n||"/"}});return a?a.error?{success:!1,error:a.error}:{success:!0,data:{...a,root:"/",roots:[{label:t,path:"/"}],truncated:!1}}:{success:!1,error:`Could not read ${t}. Is it running?`}},onSelect:n=>{e.value=n}})},async linkRemoteCase(){const e=document.getElementById("remoteCaseName").value.trim(),t=document.getElementById("remoteCasePath").value.trim(),s=document.getElementById("remoteHostId").value.trim(),n=document.getElementById("remoteHostAddress").value.trim(),a=document.getElementById("remoteHostUsername").value.trim(),i=document.getElementById("remoteHostCodexCommand").value.trim(),o=document.getElementById("remoteHostPort").value.trim(),r=document.getElementById("remoteHostIdentityFile").value.trim(),c=document.getElementById("remoteHostSocksProxy").value.trim(),d=document.getElementById("remoteHostJumpHost").value.trim(),l=document.getElementById("remoteHostExtraSshOptions").value.split(`
16
+ `).map(h=>h.trim()).filter(h=>h.length>0);if(!e||!t||!s||!n||!a){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 m;if(o&&(m=Number(o),!Number.isInteger(m)||m<1||m>65535)){this.showToast("SSH port must be a number between 1 and 65535","error");return}try{const h={id:s,label:s,host:n,username:a,...m?{port:m}:{},...r?{identityFile:r}:{},...c?{socksProxy:c}:{},...d?{jumpHost:d}:{},...l.length?{extraSshOptions:l}:{},...i?{commands:{codex:i}}:{}},u=await(await fetch("/api/remote-hosts",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(h)})).json();if(!u.success&&u.errorCode!=="ALREADY_EXISTS")throw new Error(u.error||"Failed to save remote host");const y=await(await fetch("/api/cases/remote-link",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:e,hostId:s,remotePath:t})})).json();y.success?(this.closeCreateCaseModal(),this.showToast(`Remote case "${e}" linked`,"success"),await this.loadQuickStartCases(e),await this.saveLastUsedCase(e)):this.showToast(y.error||"Failed to link remote case","error")}catch(h){console.error("Failed to link remote case:",h),this.showToast("Failed to link remote case: "+h.message,"error")}},_syncDockerAdoptMode(){const e=document.getElementById("createCaseModal");if(!e)return;const t=document.getElementById("dockerAdoptExisting")?.checked;t?e.setAttribute("data-docker-adopt","1"):e.removeAttribute("data-docker-adopt"),t&&this._loadDockerContainerOptions()},async _loadDockerContainerOptions(){const e=document.getElementById("dockerContainerList");if(!e)return;const t=document.getElementById("dockerHostId")?.value.trim()||"local";if(e.dataset.loadedFor===t)return;const n=(await this._apiJson(`/api/docker-hosts/${encodeURIComponent(t)}/containers`))?.containers||[];e.textContent="";for(const a of n){const i=document.createElement("option");i.value=a.name,i.textContent=a.running?`${a.image} \xB7 ${a.status}`:`${a.image} \xB7 ${a.status} (not running)`,e.appendChild(i)}e.dataset.loadedFor=t},jumpToDockerAdopt(){this.switchCaseModalTab("case-docker");const e=document.getElementById("dockerAdoptExisting");e&&(e.checked=!0),this._syncDockerAdoptMode(),document.getElementById("dockerContainerName")?.focus()},async _dockerAdoptPreflight(){const e=document.getElementById("dockerLinkStatus"),t=document.getElementById("dockerContainerName")?.value.trim(),s=document.getElementById("dockerAdoptWorkdir")?.value.trim(),n=document.getElementById("dockerHostId").value.trim()||"local";if(!t){e&&(e.textContent="Enter a container name first.");return}e&&(e.textContent="Inspecting container...");const a=await this._apiJson("/api/docker-cases/adopt-preflight",{method:"POST",body:{hostId:n,container:t,...s?{containerWorkdir:s}:{}}});if(!e)return;if(!a){e.textContent="Could not reach the docker host profile. Save a Host ID first.";return}if(!a.ok){e.textContent=a.error||"Container is not adoptable.";return}const i=(a.availableModes||[]).filter(o=>o!=="shell");e.textContent=i.length?`Running (${a.image||"unknown image"}). Available: ${i.join(", ")}.`:`Running (${a.image||"unknown image"}), but no agent CLI found inside \u2014 only Shell will work.`},async linkDockerCase(){const e=document.getElementById("dockerCaseName").value.trim(),t=document.getElementById("dockerWorkspacePath").value.trim(),s=document.getElementById("dockerHostId").value.trim()||"local",n=!!document.getElementById("dockerAdoptExisting")?.checked,a=document.getElementById("dockerContainerName")?.value.trim()||"",i=document.getElementById("dockerAdoptWorkdir")?.value.trim()||"",o=document.getElementById("dockerImage").value.trim()||"codeman/agent:base",r=document.getElementById("dockerNetwork").value,c=document.getElementById("dockerMemory").value.trim(),d=document.getElementById("dockerCpus").value.trim(),l=document.getElementById("dockerMountCredentials").checked,m=document.getElementById("dockerResumeOnStart").checked,h=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}if(n&&!a){this.showToast("Enter the name of the running container to attach to","error");return}try{h&&(h.textContent=n?"Inspecting the existing container...":"Checking docker daemon + base image...");const C={};c&&(C.memory=c),d&&(C.cpus=d);const u={id:s,label:s,image:o,network:r,mountCredentials:l,resumeOnStart:m,...Object.keys(C).length?{resources:C}:{}};let f=await fetch("/api/docker-hosts",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(u)}),y=await f.json();if(!y.success&&y.errorCode==="ALREADY_EXISTS"&&(f=await fetch(`/api/docker-hosts/${encodeURIComponent(s)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(u)}),y=await f.json()),!y.success)throw new Error(y.error||"Failed to save docker host");const p=await(await fetch(n?"/api/cases/docker-adopt":"/api/cases/docker-link",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n?{name:e,hostId:s,hostWorkspacePath:t,container:a,...i?{containerWorkdir:i}:{}}:{name:e,hostId:s,hostWorkspacePath:t})})).json();if(p.success){this.closeCreateCaseModal();const w=p.data?.capsEnforced===!1?" (resource caps are advisory on this engine)":"",g=(p.data?.availableModes||[]).filter(b=>b!=="shell"),S=n&&g.length?` \u2014 found ${g.join(", ")}`:"";this.showToast(`Docker case "${e}" ${n?"attached":"linked"}${w}${S}`,"success"),await this.loadQuickStartCases(e),await this.saveLastUsedCase(e)}else h&&(h.textContent=p.error||"Failed to link docker case"),this.showToast(p.error||"Failed to link docker case","error")}catch(C){console.error("Failed to link docker case:",C),h&&(h.textContent=C.message),this.showToast("Failed to link docker case: "+C.message,"error")}},async refreshDockerExports(){const e=document.getElementById("dockerExportsList");if(e)try{const n=(await(await fetch("/api/docker-exports")).json())?.data?.exports||[];if(n.length===0){e.innerHTML='<span class="form-hint">No exports yet. Export a docker case from its tab.</span>';return}e.innerHTML=n.map(a=>{const i=(a.sizeBytes/1e6).toFixed(1),o=escapeHtml(a.name);return`<div class="case-manage-item" style="display:flex; align-items:center; gap:8px; justify-content:space-between;">
17
+ <span style="overflow:hidden; text-overflow:ellipsis; white-space:nowrap;" title="${o}">${o} <span class="form-hint">(${i} MB)</span></span>
18
+ <span style="flex-shrink:0;">
19
+ <a class="btn-toolbar" href="${CodemanBase.url(`/api/docker-exports/${encodeURIComponent(a.name)}`)}" download>Download</a>
20
+ <button class="btn-toolbar" onclick="app.importDockerBundle('${o.replace(/'/g,"\\'")}')">Import</button>
21
+ <button class="btn-toolbar" onclick="app.deleteDockerExport('${o.replace(/'/g,"\\'")}')">Delete</button>
22
+ </span>
23
+ </div>`}).join("")}catch(t){e.innerHTML=`<span class="form-hint">Failed to load exports: ${t.message}</span>`}},async exportDockerCaseBundle(e,t="full"){try{const n=await(await fetch(`/api/docker-cases/${encodeURIComponent(e)}/export`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({mode:t})})).json();n.success?this.showToast(`Exporting "${e}" (${t})... you'll be notified when the bundle is ready`,"info"):this.showToast(n.error||"Export failed","error")}catch(s){this.showToast("Export failed: "+s.message,"error")}},async importDockerBundle(e){const t=prompt("New case name for the imported bundle:",e.split("-")[0]+"-imported");if(!t)return;const s=prompt("Absolute host directory to restore the workspace into:","");if(s)try{const a=await(await fetch("/api/docker-cases/import",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({bundle:e,newCaseName:t,destWorkspacePath:s})})).json();a.success?(this.showToast(`Imported as "${t}"`,"success"),await this.loadQuickStartCases(t)):this.showToast(a.error||"Import failed","error")}catch(n){this.showToast("Import failed: "+n.message,"error")}},async deleteDockerExport(e){if(confirm(`Delete export bundle "${e}"?`))try{const s=await(await fetch(`/api/docker-exports/${encodeURIComponent(e)}`,{method:"DELETE"})).json();s.success?(this.showToast("Export deleted","success"),this.refreshDockerExports()):this.showToast(s.error||"Delete failed","error")}catch(t){this.showToast("Delete failed: "+t.message,"error")}},_readRemoteHostFromForm(){const e=document.getElementById("remoteHostId").value.trim(),t=document.getElementById("remoteHostAddress").value.trim(),s=document.getElementById("remoteHostUsername").value.trim(),n=document.getElementById("remoteHostPort").value.trim(),a=document.getElementById("remoteHostIdentityFile").value.trim(),i=document.getElementById("remoteHostSocksProxy").value.trim(),o=document.getElementById("remoteHostJumpHost").value.trim(),r=document.getElementById("remoteHostCodexCommand").value.trim(),c=document.getElementById("remoteHostExtraSshOptions").value.split(`
24
+ `).map(l=>l.trim()).filter(l=>l.length>0);let d;if(n){const l=Number(n);Number.isInteger(l)&&l>=1&&l<=65535&&(d=l)}return{id:e,label:e,host:t,username:s,...d?{port:d}:{},...a?{identityFile:a}:{},...i?{socksProxy:i}:{},...o?{jumpHost:o}:{},...c.length?{extraSshOptions:c}:{},...r?{commands:{codex:r}}:{}}},async discoverRemoteSessions(){const e=document.getElementById("remoteDiscoverResults"),t=document.getElementById("remoteDiscoverBtn"),s=this._readRemoteHostFromForm();if(!s.id||!s.host||!s.username){this.showToast("Fill in Host ID, address, and username first","error");return}if(!/^[a-zA-Z0-9_-]+$/.test(s.id)){this.showToast("Invalid Host ID. Use letters, numbers, hyphens, underscores.","error");return}t&&(t.disabled=!0),e&&(e.innerHTML='<div class="form-hint">Discovering\u2026</div>');try{const a=await(await fetch("/api/remote-hosts",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)})).json();if(!a.success&&a.errorCode!=="ALREADY_EXISTS")throw new Error(a.error||"Failed to save remote host");const o=await(await fetch(`/api/remote-hosts/${encodeURIComponent(s.id)}/sessions`)).json();if(!o.success)throw new Error(o.error||"Discovery failed");this._renderDiscoveredSessions(s.id,o.data.sessions||[])}catch(n){console.error("Discover remote sessions failed:",n),e&&(e.innerHTML=`<div class="form-hint" style="color: var(--error, #e06c75);">${escapeHtml(n.message)}</div>`)}finally{t&&(t.disabled=!1)}},_renderDiscoveredSessions(e,t){const s=document.getElementById("remoteDiscoverResults");if(!s)return;if(!t.length){s.innerHTML='<div class="form-hint">No <code>codeman-*</code> sessions running on this host (or it is unreachable).</div>';return}const n=Math.floor(Date.now()/1e3),a=t.map(i=>{const o=Math.max(0,n-(i.created||0)),r=o<3600?`${Math.floor(o/60)}m`:o<86400?`${Math.floor(o/3600)}h`:`${Math.floor(o/86400)}d`,c=i.attachedClients!=null?i.attachedClients:i.attached?1:0,d=c>1?`<span class="case-location-badge" style="background: var(--warning, #e5c07b); color: #000;">shared \xB7 ${c} clients</span>`:c===1?'<span class="case-location-badge" style="background: var(--accent, #61afef);">attached</span>':"";return`
25
+ <div class="remote-discover-item">
26
+ <div class="remote-discover-info">
27
+ <span class="remote-discover-name">${escapeHtml(i.name)} ${d}</span>
28
+ <span class="form-hint">age ${r} \xB7 ${i.windows||1} window(s)</span>
29
+ </div>
30
+ <button type="button" class="btn-toolbar" onclick="app.attachDiscoveredSession('${escapeHtml(e)}', '${escapeHtml(i.name)}')">Attach</button>
31
+ </div>`}).join("");s.innerHTML=a},async attachDiscoveredSession(e,t){try{const n=await(await fetch("/api/sessions",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({mode:"shell",name:t,attachRemoteSession:{hostId:e,remoteSessionName:t}})})).json();if(!n.success)throw new Error(n.error||"Failed to create session");const a=n.data.session.id;await fetch(`/api/sessions/${a}/shell`,{method:"POST"});const i=this.getTerminalDimensions();i&&await fetch(`/api/sessions/${a}/resize`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)}),this.closeCreateCaseModal(),this.showToast(`Attached to ${t} (detach on close)`,"success"),this.activeSessionId=a,await this.selectSession(a),this.terminal&&typeof this.terminal.focus=="function"&&this.terminal.focus()}catch(s){console.error("Attach discovered session failed:",s),this.showToast("Failed to attach: "+s.message,"error")}},renderCaseManageList(){const e=document.getElementById("caseManageList"),t=this.cases||[];if(t.length===0){e.innerHTML='<div class="form-hint" style="text-align: center; padding: 2rem 0;">No cases yet</div>';return}const s=t.filter(a=>a.agentCreated);let n=s.length>0?`<div class="case-manage-agent-bar">
32
+ <span class="case-manage-agent-count">${s.length} case${s.length===1?"":"s"} created by agent workers</span>
33
+ <button class="case-manage-btn case-manage-btn-cleanup" onclick="app.cleanupAgentCases()"
34
+ title="Review and delete the scratch cases agent workers left behind">Clean up</button>
35
+ </div>`:"";t.forEach((a,i)=>{const o=i===0,r=i===t.length-1,c=a.path?this._shortenHomePath(a.path):"",d=a.agentCreated?`Created by an agent worker${a.agentCreated.parentSessionName?` from ${a.agentCreated.parentSessionName}`:""} (${a.agentCreated.createdBy})${a.agentCreated.createdAt?` on ${new Date(a.agentCreated.createdAt).toLocaleString()}`:""}`:"";n+=`
36
+ <div class="case-manage-item" data-case="${escapeHtml(a.name)}">
37
+ <div class="case-manage-info">
38
+ <span class="case-manage-name">${escapeHtml(a.name)}${a.agentCreated?`<span class="case-manage-tag-agent" title="${escapeHtml(d)}" data-i18n-skip>agent</span>`:""}</span>
39
+ <span class="case-manage-path">${escapeHtml(c)}</span>
40
+ </div>
41
+ <div class="case-manage-actions">
42
+ ${a.location==="docker"?`<button class="case-manage-btn" onclick="app.exportDockerCaseBundle(${escapeHtml(JSON.stringify(a.name))}, 'full')"
43
+ title="Export container (full image + workspace) to move to another machine">&#x1F4E6;</button>`:""}
44
+ <button class="case-manage-btn" onclick="app.moveCaseUp(${escapeHtml(JSON.stringify(a.name))})"
45
+ title="Move up" ${o?"disabled":""}>&#x25B2;</button>
46
+ <button class="case-manage-btn" onclick="app.moveCaseDown(${escapeHtml(JSON.stringify(a.name))})"
47
+ title="Move down" ${r?"disabled":""}>&#x25BC;</button>
48
+ <button class="case-manage-btn case-manage-btn-delete" onclick="app.deleteCase(${escapeHtml(JSON.stringify(a.name))})"
49
+ title="Delete case">&#x2715;</button>
50
+ </div>
51
+ </div>
52
+ `}),e.innerHTML=n},async moveCaseUp(e){const t=this.cases||[],s=t.findIndex(a=>a.name===e);if(s<=0)return;const n=[...t];[n[s-1],n[s]]=[n[s],n[s-1]],this.cases=n,this.renderCaseManageList(),await this.saveCaseOrder(n.map(a=>a.name))},async moveCaseDown(e){const t=this.cases||[],s=t.findIndex(a=>a.name===e);if(s<0||s>=t.length-1)return;const n=[...t];[n[s],n[s+1]]=[n[s+1],n[s]],this.cases=n,this.renderCaseManageList(),await this.saveCaseOrder(n.map(a=>a.name))},async deleteCase(e){if(confirm(`Delete case "${e}"? Linked cases will only be unlinked (folder preserved). Created cases will be permanently deleted.`))try{const s=await(await fetch(`/api/cases/${encodeURIComponent(e)}`,{method:"DELETE"})).json();if(s.success){this.showToast(`Case "${e}" ${s.data?.type==="unlinked"?"unlinked":"deleted"}`,"success"),this.cases=(this.cases||[]).filter(i=>i.name!==e),this.renderCaseManageList();const n=document.getElementById("quickStartCase"),a=n.value;a===e&&n.blur?.(),await this.loadQuickStartCases(a===e?null:a),a===e&&await this.saveLastUsedCase(document.getElementById("quickStartCase")?.value||"testcase")}else this.showToast(s.error||"Failed to delete case","error")}catch(t){this.showToast("Failed to delete case: "+t.message,"error")}},async cleanupAgentCases(){let e;try{const m=await(await fetch("/api/cases/agent-created")).json();if(!m.success){this.showToast(m.error||"Failed to list agent cases","error");return}e=m.data.cases||[]}catch(l){this.showToast("Failed to list agent cases: "+l.message,"error");return}const t=e.filter(l=>l.inUse),s=e.filter(l=>!l.inUse);if(s.length===0){this.showToast(t.length>0?`All ${t.length} agent case(s) are still in use by a running session`:"No agent-created cases to clean up","info");return}const n=s.map(l=>` ${l.name}`).join(`
53
+ `),a=t.length>0?`
54
+
55
+ Skipping ${t.length} case(s) still in use by a running session.`:"";if(!confirm(`Permanently delete ${s.length} agent-created case folder(s) and everything in them?
56
+
57
+ ${n}${a}`))return;let i=0;const o=[];for(const l of s)try{(await(await fetch(`/api/cases/${encodeURIComponent(l.name)}`,{method:"DELETE"})).json()).success?i++:o.push(l.name)}catch{o.push(l.name)}this.showToast(o.length===0?`Deleted ${i} agent case(s)`:`Deleted ${i}, failed: ${o.join(", ")}`,o.length===0?"success":"error");const r=document.getElementById("quickStartCase"),c=r?.value,d=s.some(l=>l.name===c);d&&r?.blur?.(),await this.loadQuickStartCases(d?null:c),d&&await this.saveLastUsedCase(document.getElementById("quickStartCase")?.value||"testcase"),this.renderCaseManageList()},async saveCaseOrder(e){try{await fetch("/api/cases/order",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({order:e})});const s=document.getElementById("quickStartCase").value;await this.loadQuickStartCases(s)}catch(t){this.showToast("Failed to save case order: "+t.message,"error")}},showMobileCasePicker(){const e=document.getElementById("mobileCasePickerModal"),t=document.getElementById("mobileCaseList"),n=document.getElementById("quickStartCase").value;let a="";const i=this.getCasePickerOptions();for(const o of i){const r=o.name===n;a+=`
58
+ <button class="mobile-case-item ${r?"selected":""}"
59
+ onclick="app.selectMobileCase(${escapeHtml(JSON.stringify(o.name))})">
60
+ <span class="mobile-case-item-icon">
61
+ <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
62
+ <path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"/>
63
+ </svg>
64
+ </span>
65
+ <span class="mobile-case-item-name">${escapeHtml(o.label)}</span>
66
+ <span class="mobile-case-item-delete" onclick="event.stopPropagation(); app.deleteCaseMobile(${escapeHtml(JSON.stringify(o.name))})" title="Delete">
67
+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
68
+ <line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/>
69
+ </svg>
70
+ </span>
71
+ <span class="mobile-case-item-check">
72
+ <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5">
73
+ <polyline points="20 6 9 17 4 12"/>
74
+ </svg>
75
+ </span>
76
+ </button>
77
+ `}t.innerHTML=a,e.classList.add("active")},closeMobileCasePicker(){document.getElementById("mobileCasePickerModal").classList.remove("active")},selectMobileCase(e){const t=document.getElementById("quickStartCase");t.value=e,this.updateMobileCaseLabel(e),this.updateDirDisplayForCase(e),this.saveLastUsedCase(e),this.closeMobileCasePicker(),this.showToast(`Selected: ${e}`,"success")},updateMobileCaseLabel(e){const t=document.getElementById("mobileCaseName");t&&(t.textContent=e)},async deleteCaseMobile(e){if(confirm(`Delete case "${e}"?`))try{const s=await(await fetch(`/api/cases/${encodeURIComponent(e)}`,{method:"DELETE"})).json();s.success?(this.showToast(`Case "${e}" ${s.data?.type==="unlinked"?"unlinked":"deleted"}`,"success"),this.cases=(this.cases||[]).filter(n=>n.name!==e),this.closeMobileCasePicker(),await this.loadQuickStartCases()):this.showToast(s.error||"Failed to delete case","error")}catch(t){this.showToast("Failed to delete case: "+t.message,"error")}},showCreateCaseFromMobile(){this.closeMobileCasePicker(),this.showCreateCaseModal();const e=document.getElementById("createCaseModal");e.classList.add("from-mobile"),setTimeout(()=>e.classList.remove("from-mobile"),300)}}),Object.defineProperty(CodemanApp.prototype,"runMode",{configurable:!0,enumerable:!0,get(){return this._runMode||"claude"},set(e){this._runMode=e==="opencode"||e==="codex"||e==="gemini"||e==="antigravity"||e==="pi"||e==="grok"||e==="deepseek"||e==="omp"||e==="claude"?e:"claude"}});
@@ -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")},_onHookElicitationComplete(e){e.sessionId&&(this.clearPendingHooks(e.sessionId,"elicitation_dialog"),this.clearPendingHooks(e.sessionId,"permission_prompt"))},_onHookElicitationResponse(e){this._onHookElicitationComplete(e)},_onHookStop(e){e.sessionId&&this.clearPendingHooks(e.sessionId),this._notifySession(e.sessionId,"info","hook-stop","Response Complete",e.reason||"Claude has finished responding")},_onHookAgentWorking(e){e.sessionId&&(this.clearPendingHooks(e.sessionId,"elicitation_dialog"),this.clearPendingHooks(e.sessionId,"permission_prompt"),this.clearPendingHooks(e.sessionId,"idle_prompt"))},_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,action:s,approvalId:o}=t.data;s?this.handleNotificationAction?.(s,o,n):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",this._syncEntranceAnimSetting?.(),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("appSettingsApprovalsInbox").checked=e.approvalsInboxEnabled===!0,document.getElementById("appSettingsReadMyMind").checked=e.readMyMindEnabled===!0,document.getElementById("appSettingsUltracodeFloatingWindows").checked=e.ultracodeFloatingWindows??t.ultracodeFloatingWindows??!1,document.getElementById("appSettingsShowMultiMonitorButton").checked=e.showMultiMonitorButton??t.showMultiMonitorButton??!1,document.getElementById("appSettingsShowPlanUsageLimits").checked=this.planUsageChipEnabled(e),document.getElementById("appSettingsShowRedrawButton").checked=e.showRedrawButton??t.showRedrawButton??!1,document.getElementById("appSettingsLineageLines").checked=e.sessionLineageLines??t.sessionLineageLines??!0;const s=document.getElementById("appSettingsLineageLinesItem");s&&(s.style.display=MobileDetection.getDeviceType()==="desktop"?"":"none"),document.getElementById("appSettingsMobileOverview").checked=e.mobileOverviewEnabled??t.mobileOverviewEnabled??!1;const o=document.getElementById("appSettingsMobileOverviewItem");o&&(o.style.display=MobileDetection.getDeviceType()==="mobile"?"":"none"),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 i=document.getElementById("appSettingsGestureControlItem");i&&(i.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("appSettingsAutoCopySelection").checked=e.autoCopySelection===!0,document.getElementById("appSettingsTerminalFont").value=e.terminalFontFamily||"",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,document.getElementById("appSettingsTabOrientation").value=e.tabOrientation??t.tabOrientation??"horizontal";const a=window.CodemanTabRail?.resolveWidth({width:e.tabRailWidth??this._defaultTabRailWidth?.()??t.tabRailWidth??256})??256;this.syncTabRailWidthSetting?.(a),document.getElementById("appSettingsTabRailDetail").value=e.tabRailDetail??t.tabRailDetail??"rich",document.getElementById("appSettingsShowTabDetachButton").checked=e.showTabDetachButton??t.showTabDetachButton??!1,document.getElementById("appSettingsSessionListLayout").value=e.sessionListLayout??t.sessionListLayout??"header";const l=this.resolveSessionSidebarFontSize(e.sessionSidebarFontSize??t.sessionSidebarFontSize);document.getElementById("appSettingsSessionSidebarFontSize").value=String(l),document.getElementById("appSettingsSessionSidebarFontSizeValue").textContent=`${l} px`;const c=document.getElementById("appSettingsClaudeMode"),d=document.getElementById("allowedToolsRow");c.value=e.claudeMode||"dangerously-skip-permissions",document.getElementById("appSettingsAllowedTools").value=e.allowedTools||"",d.style.display=c.value==="allowedTools"?"":"none",c.onchange=()=>{d.style.display=c.value==="allowedTools"?"":"none"},document.getElementById("appSettingsCodexDangerouslyBypassApprovals").checked=e.codexDangerouslyBypassApprovals??!1,document.getElementById("appSettingsCodexAnimations").checked=e.codexAnimationsEnabled??!1,this._applyCodexSettingsVisibility(),document.getElementById("appSettingsAgentTeams").checked=e.agentTeamsEnabled??!1,document.getElementById("appSettingsAgentSkill").checked=e.agentSkillEnabled??!1,document.getElementById("appSettingsWorkspaceHooks").checked=e.workspaceHooksEnabled!==!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 r=e.nice||{};document.getElementById("appSettingsNiceEnabled").checked=r.enabled??!1,document.getElementById("appSettingsNiceValue").value=r.niceValue??10,this.loadModelConfigForSettings();const u=this.notificationManager?.preferences||{};document.getElementById("appSettingsNotifEnabled").checked=u.enabled??!0,document.getElementById("appSettingsNotifBrowser").checked=u.browserNotifications??!1,document.getElementById("appSettingsNotifAudio").checked=u.audioAlerts??!1,document.getElementById("appSettingsNotifStuckMins").value=Math.round((u.stuckThresholdMs||6e5)/6e4),document.getElementById("appSettingsNotifCritical").checked=!u.muteCritical,document.getElementById("appSettingsNotifWarning").checked=!u.muteWarning,document.getElementById("appSettingsNotifInfo").checked=!u.muteInfo,document.getElementById("appSettingsPushEnabled").checked=!!this._pushSubscription,this._updatePushUI(!!this._pushSubscription);const p=u.eventTypes||{},h=p.permission_prompt||{};document.getElementById("eventPermissionEnabled").checked=h.enabled??!0,document.getElementById("eventPermissionBrowser").checked=h.browser??!0,document.getElementById("eventPermissionPush").checked=h.push??!1,document.getElementById("eventPermissionAudio").checked=h.audio??!0;const m=p.elicitation_dialog||{};document.getElementById("eventQuestionEnabled").checked=m.enabled??!0,document.getElementById("eventQuestionBrowser").checked=m.browser??!0,document.getElementById("eventQuestionPush").checked=m.push??!1,document.getElementById("eventQuestionAudio").checked=m.audio??!0;const g=p.idle_prompt||{};document.getElementById("eventIdleEnabled").checked=g.enabled??!0,document.getElementById("eventIdleBrowser").checked=g.browser??!0,document.getElementById("eventIdlePush").checked=g.push??!1,document.getElementById("eventIdleAudio").checked=g.audio??!1;const S=p.stop||{};document.getElementById("eventStopEnabled").checked=S.enabled??!1,document.getElementById("eventStopBrowser").checked=S.browser??!1,document.getElementById("eventStopPush").checked=S.push??!1,document.getElementById("eventStopAudio").checked=S.audio??!1;const b=p.respawn_cycle||{};document.getElementById("eventRespawnEnabled").checked=b.enabled??!0,document.getElementById("eventRespawnBrowser").checked=b.browser??!1,document.getElementById("eventRespawnPush").checked=b.push??!1,document.getElementById("eventRespawnAudio").checked=b.audio??!1;const E=p.ralph_complete||{};document.getElementById("eventRalphEnabled").checked=E.enabled??!0,document.getElementById("eventRalphBrowser").checked=E.browser??!0,document.getElementById("eventRalphPush").checked=E.push??!1,document.getElementById("eventRalphAudio").checked=E.audio??!0;const w=p.subagent_spawn||{};document.getElementById("eventSubagentEnabled").checked=w.enabled??!1,document.getElementById("eventSubagentBrowser").checked=w.browser??!1,document.getElementById("eventSubagentPush").checked=w.push??!1,document.getElementById("eventSubagentAudio").checked=w.audio??!1;const v=document.getElementById("notifPermissionStatus");if(v&&typeof Notification<"u"){const f=Notification.permission;v.textContent=f==="granted"?"\u2713":f==="denied"?"\u2717":"?",v.classList.remove("granted","denied"),f==="granted"?v.classList.add("granted"):f==="denied"&&v.classList.add("denied")}const y=VoiceInput._getDeepgramConfig();document.getElementById("voiceDeepgramKey").value=y.apiKey||"",document.getElementById("voiceLanguage").value=y.language||"en-US",document.getElementById("voiceKeyterms").value=y.keyterms||DEFAULT_VOICE_KEYTERMS,document.getElementById("voiceInsertMode").value=y.insertMode||"direct",document.getElementById("voiceProvider").value=y.provider||"auto",document.getElementById("appSettingsClaudeVoice").checked=e.claudeVoiceEnabled??!1;const B=document.getElementById("voiceDeepgramKey");B.type="password",document.getElementById("voiceKeyToggleBtn").textContent="Show",this._renderVoiceProviderStatus(),VoiceInput.refreshClaudeStatus().then(()=>this._renderVoiceProviderStatus()),this._initUpdatesSection(),this._initSettingsNav(),this._syncSettingsChips(),this._syncModelCards(),this._syncEffortSegment(),this.switchSettingsTab("settings-updates");const I=document.getElementById("appSettingsModal");I.classList.add("active"),this.activeFocusTrap=new FocusTrap(I),this.activeFocusTrap.activate()},_applyCodexSettingsVisibility(){const e=document.getElementById("appSettingsCodexGroup");e&&(e.style.display=window.__codemanCliAvailable?.codex===!0?"":"none")},switchSettingsTab(e){e==="settings-shortcuts"&&this.renderShortcutSettingsList?.();const t=document.getElementById("appSettingsDoc"),n=document.getElementById(e);if(t&&n&&typeof n.offsetTop=="number"){const s=document.getElementById("appSettingsJump"),o=s&&s.offsetParent?s.offsetHeight+16:6;t.scrollTop=Math.max(0,n.offsetTop-o)}this._setActiveSettingsSection(e)},_setActiveSettingsSection(e){const t=document.getElementById("appSettingsModal");if(!t||typeof t.querySelectorAll!="function")return;let n=null;t.querySelectorAll(".set-rail-item").forEach(a=>{const l=a.dataset.section===e;a.classList.toggle("active",l),l&&(n=a)}),t.querySelectorAll(".set-jump-row").forEach(a=>{a.classList.toggle("active",a.dataset.section===e)});const s=document.getElementById("appSettingsJump")?.querySelector(".set-jump-label");s&&n&&(s.textContent=n.textContent.trim());const o=document.getElementById("appSettingsJump")?.querySelector(".set-jump-ico"),i=n?.querySelector("svg");o&&i&&(o.innerHTML=i.innerHTML)},_initSettingsNav(){const e=document.getElementById("appSettingsModal"),t=document.getElementById("appSettingsDoc");if(!e||!t||typeof e.querySelectorAll!="function"||(this._buildModelCards(),this._buildEffortSegment(),this._buildSettingsJumpMenu(),e.dataset.navReady==="1"))return;e.dataset.navReady="1",e.querySelector(".set-rail-items")?.addEventListener("click",i=>{const a=i.target.closest?.(".set-rail-item");a?.dataset.section&&this.switchSettingsTab(a.dataset.section)}),document.getElementById("appSettingsJumpMenu")?.addEventListener("click",i=>{const a=i.target.closest?.(".set-jump-row");a?.dataset.section&&(this._toggleSettingsJump(!1),this.switchSettingsTab(a.dataset.section))}),document.getElementById("appSettingsJump")?.addEventListener("click",()=>this._toggleSettingsJump()),document.getElementById("appSettingsJumpVeil")?.addEventListener("click",()=>this._toggleSettingsJump(!1)),t.addEventListener("scroll",()=>{this._settingsSpyQueued||(this._settingsSpyQueued=!0,requestAnimationFrame(()=>{this._settingsSpyQueued=!1;const i=[...t.querySelectorAll(".set-section")].filter(l=>l.offsetParent!==null);if(!i.length)return;let a=i[0].id;for(const l of i)l.offsetTop-t.scrollTop<=140&&(a=l.id);this._setActiveSettingsSection(a)}))});const n=document.getElementById("appSettingsSearch");n?.addEventListener("input",()=>this._filterSettings(n.value)),e.querySelectorAll(".set-chip input").forEach(i=>{i.addEventListener("change",()=>this._syncSettingsChips())});const s=e.querySelector(".set-group-head-toggle"),o=s?.closest(".set-group-advanced");if(s&&o){const i=()=>{const a=o.classList.toggle("open");s.setAttribute("aria-expanded",a?"true":"false")};s.addEventListener("click",i),s.addEventListener("keydown",a=>{(a.key==="Enter"||a.key===" ")&&(a.preventDefault(),i())})}document.getElementById("appSettingsOpusContext1m")?.addEventListener("change",()=>this._applyModelSelection())},_buildSettingsJumpMenu(){const e=document.getElementById("appSettingsModal"),t=document.getElementById("appSettingsJumpMenu");!e||!t||(t.innerHTML="",e.querySelectorAll(".set-rail-item").forEach(n=>{const s=document.createElement("button");s.type="button",s.className="set-jump-row",s.dataset.section=n.dataset.section,s.innerHTML=n.innerHTML;const o=document.getElementById(n.dataset.section),i=o?o.querySelectorAll("input, select").length:0;if(i){const a=document.createElement("span");a.className="set-jump-count",a.textContent=String(i),s.appendChild(a)}t.appendChild(s)}))},_toggleSettingsJump(e){const t=document.getElementById("appSettingsModal");if(!t)return;const n=e===void 0?!t.classList.contains("jump-open"):e;t.classList.toggle("jump-open",n),document.getElementById("appSettingsJump")?.setAttribute("aria-expanded",n?"true":"false")},_syncSettingsChips(){document.querySelectorAll("#appSettingsModal .set-chip, #sessionOptionsModal .set-chip").forEach(e=>{e.classList.toggle("is-on",!!e.querySelector("input")?.checked)}),this._syncLayoutPreview()},_syncLayoutPreview(){const e=document.getElementById("appSettingsModal");if(!e||typeof e.querySelectorAll!="function")return;const t={header:document.getElementById("appSettingsPreviewHeader"),panel:document.getElementById("appSettingsPreviewPanels"),toolbar:document.getElementById("appSettingsPreviewToolbar"),float:document.getElementById("appSettingsPreviewFloats")};if(!t.header)return;Object.values(t).forEach(i=>{i&&(i.innerHTML="")});const n=[...e.querySelectorAll(".set-chip[data-preview]")].filter(i=>i.querySelector("input")?.checked).sort((i,a)=>(Number(i.dataset.previewOrder)||0)-(Number(a.dataset.previewOrder)||0));let s=0;for(const i of n){const a=i.dataset.preview,l=t[a];if(!l)continue;const c=i.querySelectorAll("span"),d=(c[c.length-1]?.textContent||"").trim(),r=document.createElement("span");if(r.title=d,a==="header"){const u=i.dataset.previewText;r.className=u?"set-preview-chip":"set-preview-btn",u?r.textContent=u:this._appendPreviewIcon(r,i)}else{r.className=`set-preview-${a}`,this._appendPreviewIcon(r,i);const u=document.createElement("span");u.textContent=d,r.appendChild(u)}l.appendChild(r),s++}const o=document.getElementById("appSettingsPreviewEmpty");o&&(o.hidden=s>0)},_appendPreviewIcon(e,t){const n=t.querySelector(".set-chip-ico");if(!n)return;const s=n.cloneNode(!0);s.classList.remove("set-chip-ico"),s.classList.add("set-preview-ico"),e.appendChild(s)},_buildModelCards(){const e=document.getElementById("appSettingsClaudeModel"),t=document.getElementById("appSettingsModelCards");!e||!t||t.dataset.built==="1"||!e.options||(t.innerHTML="",[...e.options].filter(n=>n.dataset.variant!=="1m").forEach(n=>{const s=document.createElement("button");s.type="button",s.className="set-modelcard",s.setAttribute("role","radio"),s.dataset.value=n.value,n.dataset.ctx==="1"&&(s.dataset.ctx="1");const o=document.createElement("span");o.className="set-mc-top";const i=document.createElement("span");i.className="set-mc-name",i.textContent=n.textContent,o.appendChild(i);const a=document.createElement("span");a.className="set-mc-dot",o.appendChild(a),s.appendChild(o);const l=document.createElement("span");if(l.className="set-mc-meta",l.textContent=n.dataset.meta||"",s.appendChild(l),n.dataset.ctx==="1"){const c=document.createElement("span");c.className="set-mc-ctx",c.textContent="1M capable",s.appendChild(c)}s.addEventListener("click",()=>{this._settingsModelBase=n.value,this._applyModelSelection()}),t.appendChild(s)}),t.dataset.built="1")},_syncModelCards(){const e=document.getElementById("appSettingsClaudeModel");if(!e)return;const t=e.value||"";if(this._settingsModelBase=t.endsWith("[1m]")?t.slice(0,-4):t,t.endsWith("[1m]")){const n=document.getElementById("appSettingsOpusContext1m");n&&(n.checked=!0)}this._applyModelSelection()},_applyModelSelection(){const e=document.getElementById("appSettingsClaudeModel"),t=document.getElementById("appSettingsModelCards");if(!e||!t)return;const n=this._settingsModelBase||"";let s=!1;t.querySelectorAll(".set-modelcard").forEach(c=>{const d=c.dataset.value===n;c.classList.toggle("selected",d),c.setAttribute("aria-checked",d?"true":"false"),d&&(s=c.dataset.ctx==="1")});const o=!!document.getElementById("appSettingsOpusContext1m")?.checked;e.value=n&&s&&o?`${n}[1m]`:n;const i=document.getElementById("appSettingsContextRow"),a=document.getElementById("appSettingsContextDesc"),l=!!n&&!s;i?.classList.toggle("set-row-disabled",l),a&&(a.textContent=l?"The selected model has no 1M variant.":n?"Available for Fable 5.1, Fable 5, Opus and Opus 4.6.":"With no model pinned, this starts new sessions on Opus with a 1M window.")},_buildEffortSegment(){const e=document.getElementById("appSettingsThinkingEffort"),t=document.getElementById("appSettingsEffortSegment");!e||!t||t.dataset.built==="1"||!e.options||(t.innerHTML="",[...e.options].forEach(n=>{const s=document.createElement("button");s.type="button",s.setAttribute("role","radio"),s.dataset.value=n.value,s.textContent=n.textContent,s.addEventListener("click",()=>{e.value=n.value,this._syncEffortSegment()}),t.appendChild(s)}),t.dataset.built="1")},_syncEffortSegment(){const e=document.getElementById("appSettingsThinkingEffort"),t=document.getElementById("appSettingsEffortSegment");!e||!t||t.querySelectorAll("button").forEach(n=>{const s=n.dataset.value===(e.value||"");n.classList.toggle("selected",s),n.setAttribute("aria-checked",s?"true":"false")})},_filterSettings(e){const t=document.getElementById("appSettingsDoc");if(!t)return;const n=(e||"").trim().toLowerCase(),s=".set-row, .set-chip, .set-modelgrid, .set-minigrid, .event-type-grid, #appSettingsShortcutsList",o=[...t.querySelectorAll(s)];let i=!1;o.forEach(l=>{if(!n){l.classList.remove("set-hit-hidden");return}const d=`${l.dataset?.search||""} ${l.textContent||""}`.toLowerCase().includes(n);l.classList.toggle("set-hit-hidden",!d),d&&(i=!0)}),t.querySelectorAll(".set-chips").forEach(l=>{const c=[...l.querySelectorAll(".set-chip")].some(d=>!d.classList.contains("set-hit-hidden"));l.classList.toggle("set-hit-hidden",!!n&&!c)}),t.querySelectorAll(".set-group").forEach(l=>{const c=[...l.querySelectorAll(s)].some(d=>!d.classList.contains("set-hit-hidden"));l.classList.toggle("set-hit-hidden",!!n&&!c),n&&c&&l.classList.add("open")}),t.querySelectorAll(".set-section").forEach(l=>{const c=[...l.querySelectorAll(".set-group")].some(d=>!d.classList.contains("set-hit-hidden"));l.classList.toggle("set-hit-hidden",!!n&&!c)}),t.querySelectorAll(".set-preview").forEach(l=>l.classList.toggle("set-hit-hidden",!!n));const a=document.getElementById("appSettingsSearchEmpty");a&&(a.hidden=!n||i),n||t.querySelectorAll(".set-group-advanced").forEach(l=>l.classList.remove("open"))},closeAppSettings(){this._toggleSettingsJump(!1),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"&&t.installKind!=="docker-compose"){const a=t.supervisor==="docker-compose"?"Update from the Docker host with <code>docker/Start-Codeman.sh</code>.":"Update with <code>npm i -g aicodeman@latest</code>.";this._setUpdateResult(`This install can't update itself (${escapeHtml(t.installKind)}). ${a}`);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}const i=t.environment?.blockers||[];if(t.updateAvailable&&i.length>0){const a=i.map(l=>{const c=l.details?.length?`<br><code>${escapeHtml(l.details.join(" "))}</code>`:"";return`<li>${escapeHtml(l.message)}${c}</li>`}).join("");this._setUpdateResult(`<strong>v${escapeHtml(t.latestVersion||"")}</strong> needs a rebuild on the Docker host (current v${escapeHtml(t.currentVersion||"")}):<ul>${a}</ul>Run <code>${escapeHtml(t.environment?.hostCommand||"docker/Start-Codeman.sh")}</code> there to apply it.`),s&&t.notes&&(s.style.display="block",s.textContent=t.notes);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 l=this.$("updateNowBtn");l&&(l.disabled=!1,l.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 i="Failed to start the update.";try{const a=await n.json();typeof a?.error=="string"&&a.error&&(i=a.error)}catch{}this._setUpdateProgress(`<span style="color:var(--danger,#e5534b)">${escapeHtml(i)}</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"),i=this.$("updateActionRow");o&&(o.disabled=!1,o.textContent="Try again"),i&&(i.style.display="flex")}};t(),this._updatePollTimer=setInterval(t,1500)},isCliAvailable(e){const t=window.__codemanCliAvailable;return!t||typeof t!="object"?!0:t[e]!==!1},applyWelcomeCliVisibility(){const e=[["welcomeClaudeBtn","claude"],["welcomeOpencodeBtn","opencode"],["welcomeAntigravityBtn","antigravity"],["welcomeOmpBtn","omp"],["welcomeGeminiBtn","gemini"],["welcomePiBtn","pi"],["welcomeGrokBtn","grok"],["welcomeDeepSeekBtn","deepseek"],["welcomeTunnelBtn","cloudflared"]];for(const[t,n]of e){const s=document.getElementById(t);s&&(s.style.display=this.isCliAvailable(n)?"flex":"none")}},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),i=document.getElementById(t);if(!(!o||!i))if(n){const a=n+s;o.style.display="",i.textContent=a,i.onclick=()=>{navigator.clipboard.writeText(a).then(()=>{this.showToast(`${s?"Upload":"Tunnel"} URL copied`,"success")})}}else o.style.display="none",i.textContent="",i.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")},_onHookElicitationComplete(e){e.sessionId&&(this.clearPendingHooks(e.sessionId,"elicitation_dialog"),this.clearPendingHooks(e.sessionId,"permission_prompt"))},_onHookElicitationResponse(e){this._onHookElicitationComplete(e)},_onHookStop(e){e.sessionId&&this.clearPendingHooks(e.sessionId),this._notifySession(e.sessionId,"info","hook-stop","Response Complete",e.reason||"Claude has finished responding")},_onHookAgentWorking(e){e.sessionId&&(this.clearPendingHooks(e.sessionId,"elicitation_dialog"),this.clearPendingHooks(e.sessionId,"permission_prompt"),this.clearPendingHooks(e.sessionId,"idle_prompt"))},_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(){if(!("serviceWorker"in navigator))return;const e=window.CodemanBase?.base||"";navigator.serviceWorker.register(e+"/sw.js",{scope:e+"/"}).then(t=>{this._swRegistration=t,navigator.serviceWorker.addEventListener("message",n=>{if(n.data?.type==="notification-click"){const{sessionId:s,action:o,approvalId:i}=n.data;o?this.handleNotificationAction?.(o,i,s):s&&this.sessions.has(s)&&this.selectSession(s),window.focus()}}),t.pushManager.getSubscription().then(n=>{n&&(this._pushSubscription=n,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",this._syncEntranceAnimSetting?.(),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("appSettingsApprovalsInbox").checked=e.approvalsInboxEnabled===!0,document.getElementById("appSettingsReadMyMind").checked=e.readMyMindEnabled===!0,document.getElementById("appSettingsUltracodeFloatingWindows").checked=e.ultracodeFloatingWindows??t.ultracodeFloatingWindows??!1,document.getElementById("appSettingsShowMultiMonitorButton").checked=e.showMultiMonitorButton??t.showMultiMonitorButton??!1,document.getElementById("appSettingsShowPlanUsageLimits").checked=this.planUsageChipEnabled(e),document.getElementById("appSettingsShowRedrawButton").checked=e.showRedrawButton??t.showRedrawButton??!1,document.getElementById("appSettingsLineageLines").checked=e.sessionLineageLines??t.sessionLineageLines??!0;const s=document.getElementById("appSettingsLineageLinesItem");s&&(s.style.display=MobileDetection.getDeviceType()==="desktop"?"":"none"),document.getElementById("appSettingsMobileOverview").checked=e.mobileOverviewEnabled??t.mobileOverviewEnabled??!1;const o=document.getElementById("appSettingsMobileOverviewItem");o&&(o.style.display=MobileDetection.getDeviceType()==="mobile"?"":"none"),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 i=document.getElementById("appSettingsGestureControlItem");i&&(i.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("appSettingsAutoCopySelection").checked=e.autoCopySelection===!0,document.getElementById("appSettingsTerminalFont").value=e.terminalFontFamily||"",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,document.getElementById("appSettingsTabOrientation").value=e.tabOrientation??t.tabOrientation??"horizontal";const a=window.CodemanTabRail?.resolveWidth({width:e.tabRailWidth??this._defaultTabRailWidth?.()??t.tabRailWidth??256})??256;this.syncTabRailWidthSetting?.(a),document.getElementById("appSettingsTabRailDetail").value=e.tabRailDetail??t.tabRailDetail??"rich",document.getElementById("appSettingsShowTabDetachButton").checked=e.showTabDetachButton??t.showTabDetachButton??!1,document.getElementById("appSettingsSessionListLayout").value=e.sessionListLayout??t.sessionListLayout??"header";const l=this.resolveSessionSidebarFontSize(e.sessionSidebarFontSize??t.sessionSidebarFontSize);document.getElementById("appSettingsSessionSidebarFontSize").value=String(l),document.getElementById("appSettingsSessionSidebarFontSizeValue").textContent=`${l} px`;const c=document.getElementById("appSettingsClaudeMode"),d=document.getElementById("allowedToolsRow");c.value=e.claudeMode||"dangerously-skip-permissions",document.getElementById("appSettingsAllowedTools").value=e.allowedTools||"",d.style.display=c.value==="allowedTools"?"":"none",c.onchange=()=>{d.style.display=c.value==="allowedTools"?"":"none"},document.getElementById("appSettingsCodexDangerouslyBypassApprovals").checked=e.codexDangerouslyBypassApprovals??!1,document.getElementById("appSettingsCodexAnimations").checked=e.codexAnimationsEnabled??!1,this._applyCodexSettingsVisibility(),document.getElementById("appSettingsAgentTeams").checked=e.agentTeamsEnabled??!1,document.getElementById("appSettingsAgentSkill").checked=e.agentSkillEnabled??!1,document.getElementById("appSettingsWorkspaceHooks").checked=e.workspaceHooksEnabled!==!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 r=e.nice||{};document.getElementById("appSettingsNiceEnabled").checked=r.enabled??!1,document.getElementById("appSettingsNiceValue").value=r.niceValue??10,this.loadModelConfigForSettings();const u=this.notificationManager?.preferences||{};document.getElementById("appSettingsNotifEnabled").checked=u.enabled??!0,document.getElementById("appSettingsNotifBrowser").checked=u.browserNotifications??!1,document.getElementById("appSettingsNotifAudio").checked=u.audioAlerts??!1,document.getElementById("appSettingsNotifStuckMins").value=Math.round((u.stuckThresholdMs||6e5)/6e4),document.getElementById("appSettingsNotifCritical").checked=!u.muteCritical,document.getElementById("appSettingsNotifWarning").checked=!u.muteWarning,document.getElementById("appSettingsNotifInfo").checked=!u.muteInfo,document.getElementById("appSettingsPushEnabled").checked=!!this._pushSubscription,this._updatePushUI(!!this._pushSubscription);const p=u.eventTypes||{},h=p.permission_prompt||{};document.getElementById("eventPermissionEnabled").checked=h.enabled??!0,document.getElementById("eventPermissionBrowser").checked=h.browser??!0,document.getElementById("eventPermissionPush").checked=h.push??!1,document.getElementById("eventPermissionAudio").checked=h.audio??!0;const m=p.elicitation_dialog||{};document.getElementById("eventQuestionEnabled").checked=m.enabled??!0,document.getElementById("eventQuestionBrowser").checked=m.browser??!0,document.getElementById("eventQuestionPush").checked=m.push??!1,document.getElementById("eventQuestionAudio").checked=m.audio??!0;const g=p.idle_prompt||{};document.getElementById("eventIdleEnabled").checked=g.enabled??!0,document.getElementById("eventIdleBrowser").checked=g.browser??!0,document.getElementById("eventIdlePush").checked=g.push??!1,document.getElementById("eventIdleAudio").checked=g.audio??!1;const S=p.stop||{};document.getElementById("eventStopEnabled").checked=S.enabled??!1,document.getElementById("eventStopBrowser").checked=S.browser??!1,document.getElementById("eventStopPush").checked=S.push??!1,document.getElementById("eventStopAudio").checked=S.audio??!1;const b=p.respawn_cycle||{};document.getElementById("eventRespawnEnabled").checked=b.enabled??!0,document.getElementById("eventRespawnBrowser").checked=b.browser??!1,document.getElementById("eventRespawnPush").checked=b.push??!1,document.getElementById("eventRespawnAudio").checked=b.audio??!1;const E=p.ralph_complete||{};document.getElementById("eventRalphEnabled").checked=E.enabled??!0,document.getElementById("eventRalphBrowser").checked=E.browser??!0,document.getElementById("eventRalphPush").checked=E.push??!1,document.getElementById("eventRalphAudio").checked=E.audio??!0;const w=p.subagent_spawn||{};document.getElementById("eventSubagentEnabled").checked=w.enabled??!1,document.getElementById("eventSubagentBrowser").checked=w.browser??!1,document.getElementById("eventSubagentPush").checked=w.push??!1,document.getElementById("eventSubagentAudio").checked=w.audio??!1;const v=document.getElementById("notifPermissionStatus");if(v&&typeof Notification<"u"){const f=Notification.permission;v.textContent=f==="granted"?"\u2713":f==="denied"?"\u2717":"?",v.classList.remove("granted","denied"),f==="granted"?v.classList.add("granted"):f==="denied"&&v.classList.add("denied")}const y=VoiceInput._getDeepgramConfig();document.getElementById("voiceDeepgramKey").value=y.apiKey||"",document.getElementById("voiceLanguage").value=y.language||"en-US",document.getElementById("voiceKeyterms").value=y.keyterms||DEFAULT_VOICE_KEYTERMS,document.getElementById("voiceInsertMode").value=y.insertMode||"direct",document.getElementById("voiceProvider").value=y.provider||"auto",document.getElementById("appSettingsClaudeVoice").checked=e.claudeVoiceEnabled??!1;const B=document.getElementById("voiceDeepgramKey");B.type="password",document.getElementById("voiceKeyToggleBtn").textContent="Show",this._renderVoiceProviderStatus(),VoiceInput.refreshClaudeStatus().then(()=>this._renderVoiceProviderStatus()),this._initUpdatesSection(),this._initSettingsNav(),this._syncSettingsChips(),this._syncModelCards(),this._syncEffortSegment(),this.switchSettingsTab("settings-updates");const I=document.getElementById("appSettingsModal");I.classList.add("active"),this.activeFocusTrap=new FocusTrap(I),this.activeFocusTrap.activate()},_applyCodexSettingsVisibility(){const e=document.getElementById("appSettingsCodexGroup");e&&(e.style.display=window.__codemanCliAvailable?.codex===!0?"":"none")},switchSettingsTab(e){e==="settings-shortcuts"&&this.renderShortcutSettingsList?.();const t=document.getElementById("appSettingsDoc"),n=document.getElementById(e);if(t&&n&&typeof n.offsetTop=="number"){const s=document.getElementById("appSettingsJump"),o=s&&s.offsetParent?s.offsetHeight+16:6;t.scrollTop=Math.max(0,n.offsetTop-o)}this._setActiveSettingsSection(e)},_setActiveSettingsSection(e){const t=document.getElementById("appSettingsModal");if(!t||typeof t.querySelectorAll!="function")return;let n=null;t.querySelectorAll(".set-rail-item").forEach(a=>{const l=a.dataset.section===e;a.classList.toggle("active",l),l&&(n=a)}),t.querySelectorAll(".set-jump-row").forEach(a=>{a.classList.toggle("active",a.dataset.section===e)});const s=document.getElementById("appSettingsJump")?.querySelector(".set-jump-label");s&&n&&(s.textContent=n.textContent.trim());const o=document.getElementById("appSettingsJump")?.querySelector(".set-jump-ico"),i=n?.querySelector("svg");o&&i&&(o.innerHTML=i.innerHTML)},_initSettingsNav(){const e=document.getElementById("appSettingsModal"),t=document.getElementById("appSettingsDoc");if(!e||!t||typeof e.querySelectorAll!="function"||(this._buildModelCards(),this._buildEffortSegment(),this._buildSettingsJumpMenu(),e.dataset.navReady==="1"))return;e.dataset.navReady="1",e.querySelector(".set-rail-items")?.addEventListener("click",i=>{const a=i.target.closest?.(".set-rail-item");a?.dataset.section&&this.switchSettingsTab(a.dataset.section)}),document.getElementById("appSettingsJumpMenu")?.addEventListener("click",i=>{const a=i.target.closest?.(".set-jump-row");a?.dataset.section&&(this._toggleSettingsJump(!1),this.switchSettingsTab(a.dataset.section))}),document.getElementById("appSettingsJump")?.addEventListener("click",()=>this._toggleSettingsJump()),document.getElementById("appSettingsJumpVeil")?.addEventListener("click",()=>this._toggleSettingsJump(!1)),t.addEventListener("scroll",()=>{this._settingsSpyQueued||(this._settingsSpyQueued=!0,requestAnimationFrame(()=>{this._settingsSpyQueued=!1;const i=[...t.querySelectorAll(".set-section")].filter(l=>l.offsetParent!==null);if(!i.length)return;let a=i[0].id;for(const l of i)l.offsetTop-t.scrollTop<=140&&(a=l.id);this._setActiveSettingsSection(a)}))});const n=document.getElementById("appSettingsSearch");n?.addEventListener("input",()=>this._filterSettings(n.value)),e.querySelectorAll(".set-chip input").forEach(i=>{i.addEventListener("change",()=>this._syncSettingsChips())});const s=e.querySelector(".set-group-head-toggle"),o=s?.closest(".set-group-advanced");if(s&&o){const i=()=>{const a=o.classList.toggle("open");s.setAttribute("aria-expanded",a?"true":"false")};s.addEventListener("click",i),s.addEventListener("keydown",a=>{(a.key==="Enter"||a.key===" ")&&(a.preventDefault(),i())})}document.getElementById("appSettingsOpusContext1m")?.addEventListener("change",()=>this._applyModelSelection())},_buildSettingsJumpMenu(){const e=document.getElementById("appSettingsModal"),t=document.getElementById("appSettingsJumpMenu");!e||!t||(t.innerHTML="",e.querySelectorAll(".set-rail-item").forEach(n=>{const s=document.createElement("button");s.type="button",s.className="set-jump-row",s.dataset.section=n.dataset.section,s.innerHTML=n.innerHTML;const o=document.getElementById(n.dataset.section),i=o?o.querySelectorAll("input, select").length:0;if(i){const a=document.createElement("span");a.className="set-jump-count",a.textContent=String(i),s.appendChild(a)}t.appendChild(s)}))},_toggleSettingsJump(e){const t=document.getElementById("appSettingsModal");if(!t)return;const n=e===void 0?!t.classList.contains("jump-open"):e;t.classList.toggle("jump-open",n),document.getElementById("appSettingsJump")?.setAttribute("aria-expanded",n?"true":"false")},_syncSettingsChips(){document.querySelectorAll("#appSettingsModal .set-chip, #sessionOptionsModal .set-chip").forEach(e=>{e.classList.toggle("is-on",!!e.querySelector("input")?.checked)}),this._syncLayoutPreview()},_syncLayoutPreview(){const e=document.getElementById("appSettingsModal");if(!e||typeof e.querySelectorAll!="function")return;const t={header:document.getElementById("appSettingsPreviewHeader"),panel:document.getElementById("appSettingsPreviewPanels"),toolbar:document.getElementById("appSettingsPreviewToolbar"),float:document.getElementById("appSettingsPreviewFloats")};if(!t.header)return;Object.values(t).forEach(i=>{i&&(i.innerHTML="")});const n=[...e.querySelectorAll(".set-chip[data-preview]")].filter(i=>i.querySelector("input")?.checked).sort((i,a)=>(Number(i.dataset.previewOrder)||0)-(Number(a.dataset.previewOrder)||0));let s=0;for(const i of n){const a=i.dataset.preview,l=t[a];if(!l)continue;const c=i.querySelectorAll("span"),d=(c[c.length-1]?.textContent||"").trim(),r=document.createElement("span");if(r.title=d,a==="header"){const u=i.dataset.previewText;r.className=u?"set-preview-chip":"set-preview-btn",u?r.textContent=u:this._appendPreviewIcon(r,i)}else{r.className=`set-preview-${a}`,this._appendPreviewIcon(r,i);const u=document.createElement("span");u.textContent=d,r.appendChild(u)}l.appendChild(r),s++}const o=document.getElementById("appSettingsPreviewEmpty");o&&(o.hidden=s>0)},_appendPreviewIcon(e,t){const n=t.querySelector(".set-chip-ico");if(!n)return;const s=n.cloneNode(!0);s.classList.remove("set-chip-ico"),s.classList.add("set-preview-ico"),e.appendChild(s)},_buildModelCards(){const e=document.getElementById("appSettingsClaudeModel"),t=document.getElementById("appSettingsModelCards");!e||!t||t.dataset.built==="1"||!e.options||(t.innerHTML="",[...e.options].filter(n=>n.dataset.variant!=="1m").forEach(n=>{const s=document.createElement("button");s.type="button",s.className="set-modelcard",s.setAttribute("role","radio"),s.dataset.value=n.value,n.dataset.ctx==="1"&&(s.dataset.ctx="1");const o=document.createElement("span");o.className="set-mc-top";const i=document.createElement("span");i.className="set-mc-name",i.textContent=n.textContent,o.appendChild(i);const a=document.createElement("span");a.className="set-mc-dot",o.appendChild(a),s.appendChild(o);const l=document.createElement("span");if(l.className="set-mc-meta",l.textContent=n.dataset.meta||"",s.appendChild(l),n.dataset.ctx==="1"){const c=document.createElement("span");c.className="set-mc-ctx",c.textContent="1M capable",s.appendChild(c)}s.addEventListener("click",()=>{this._settingsModelBase=n.value,this._applyModelSelection()}),t.appendChild(s)}),t.dataset.built="1")},_syncModelCards(){const e=document.getElementById("appSettingsClaudeModel");if(!e)return;const t=e.value||"";if(this._settingsModelBase=t.endsWith("[1m]")?t.slice(0,-4):t,t.endsWith("[1m]")){const n=document.getElementById("appSettingsOpusContext1m");n&&(n.checked=!0)}this._applyModelSelection()},_applyModelSelection(){const e=document.getElementById("appSettingsClaudeModel"),t=document.getElementById("appSettingsModelCards");if(!e||!t)return;const n=this._settingsModelBase||"";let s=!1;t.querySelectorAll(".set-modelcard").forEach(c=>{const d=c.dataset.value===n;c.classList.toggle("selected",d),c.setAttribute("aria-checked",d?"true":"false"),d&&(s=c.dataset.ctx==="1")});const o=!!document.getElementById("appSettingsOpusContext1m")?.checked;e.value=n&&s&&o?`${n}[1m]`:n;const i=document.getElementById("appSettingsContextRow"),a=document.getElementById("appSettingsContextDesc"),l=!!n&&!s;i?.classList.toggle("set-row-disabled",l),a&&(a.textContent=l?"The selected model has no 1M variant.":n?"Available for Fable 5.1, Fable 5, Opus and Opus 4.6.":"With no model pinned, this starts new sessions on Opus with a 1M window.")},_buildEffortSegment(){const e=document.getElementById("appSettingsThinkingEffort"),t=document.getElementById("appSettingsEffortSegment");!e||!t||t.dataset.built==="1"||!e.options||(t.innerHTML="",[...e.options].forEach(n=>{const s=document.createElement("button");s.type="button",s.setAttribute("role","radio"),s.dataset.value=n.value,s.textContent=n.textContent,s.addEventListener("click",()=>{e.value=n.value,this._syncEffortSegment()}),t.appendChild(s)}),t.dataset.built="1")},_syncEffortSegment(){const e=document.getElementById("appSettingsThinkingEffort"),t=document.getElementById("appSettingsEffortSegment");!e||!t||t.querySelectorAll("button").forEach(n=>{const s=n.dataset.value===(e.value||"");n.classList.toggle("selected",s),n.setAttribute("aria-checked",s?"true":"false")})},_filterSettings(e){const t=document.getElementById("appSettingsDoc");if(!t)return;const n=(e||"").trim().toLowerCase(),s=".set-row, .set-chip, .set-modelgrid, .set-minigrid, .event-type-grid, #appSettingsShortcutsList",o=[...t.querySelectorAll(s)];let i=!1;o.forEach(l=>{if(!n){l.classList.remove("set-hit-hidden");return}const d=`${l.dataset?.search||""} ${l.textContent||""}`.toLowerCase().includes(n);l.classList.toggle("set-hit-hidden",!d),d&&(i=!0)}),t.querySelectorAll(".set-chips").forEach(l=>{const c=[...l.querySelectorAll(".set-chip")].some(d=>!d.classList.contains("set-hit-hidden"));l.classList.toggle("set-hit-hidden",!!n&&!c)}),t.querySelectorAll(".set-group").forEach(l=>{const c=[...l.querySelectorAll(s)].some(d=>!d.classList.contains("set-hit-hidden"));l.classList.toggle("set-hit-hidden",!!n&&!c),n&&c&&l.classList.add("open")}),t.querySelectorAll(".set-section").forEach(l=>{const c=[...l.querySelectorAll(".set-group")].some(d=>!d.classList.contains("set-hit-hidden"));l.classList.toggle("set-hit-hidden",!!n&&!c)}),t.querySelectorAll(".set-preview").forEach(l=>l.classList.toggle("set-hit-hidden",!!n));const a=document.getElementById("appSettingsSearchEmpty");a&&(a.hidden=!n||i),n||t.querySelectorAll(".set-group-advanced").forEach(l=>l.classList.remove("open"))},closeAppSettings(){this._toggleSettingsJump(!1),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"&&t.installKind!=="docker-compose"){const a=t.supervisor==="docker-compose"?"Update from the Docker host with <code>docker/Start-Codeman.sh</code>.":"Update with <code>npm i -g aicodeman@latest</code>.";this._setUpdateResult(`This install can't update itself (${escapeHtml(t.installKind)}). ${a}`);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}const i=t.environment?.blockers||[];if(t.updateAvailable&&i.length>0){const a=i.map(l=>{const c=l.details?.length?`<br><code>${escapeHtml(l.details.join(" "))}</code>`:"";return`<li>${escapeHtml(l.message)}${c}</li>`}).join("");this._setUpdateResult(`<strong>v${escapeHtml(t.latestVersion||"")}</strong> needs a rebuild on the Docker host (current v${escapeHtml(t.currentVersion||"")}):<ul>${a}</ul>Run <code>${escapeHtml(t.environment?.hostCommand||"docker/Start-Codeman.sh")}</code> there to apply it.`),s&&t.notes&&(s.style.display="block",s.textContent=t.notes);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 l=this.$("updateNowBtn");l&&(l.disabled=!1,l.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 i="Failed to start the update.";try{const a=await n.json();typeof a?.error=="string"&&a.error&&(i=a.error)}catch{}this._setUpdateProgress(`<span style="color:var(--danger,#e5534b)">${escapeHtml(i)}</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"),i=this.$("updateActionRow");o&&(o.disabled=!1,o.textContent="Try again"),i&&(i.style.display="flex")}};t(),this._updatePollTimer=setInterval(t,1500)},isCliAvailable(e){const t=window.__codemanCliAvailable;return!t||typeof t!="object"?!0:t[e]!==!1},applyWelcomeCliVisibility(){const e=[["welcomeClaudeBtn","claude"],["welcomeOpencodeBtn","opencode"],["welcomeAntigravityBtn","antigravity"],["welcomeOmpBtn","omp"],["welcomeGeminiBtn","gemini"],["welcomePiBtn","pi"],["welcomeGrokBtn","grok"],["welcomeDeepSeekBtn","deepseek"],["welcomeTunnelBtn","cloudflared"]];for(const[t,n]of e){const s=document.getElementById(t);s&&(s.style.display=this.isCliAvailable(n)?"flex":"none")}},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),i=document.getElementById(t);if(!(!o||!i))if(n){const a=n+s;o.style.display="",i.textContent=a,i.onclick=()=>{navigator.clipboard.writeText(a).then(()=>{this.showToast(`${s?"Upload":"Tunnel"} URL copied`,"success")})}}else o.style.display="none",i.textContent="",i.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>