aicodeman 1.44.0 → 1.45.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 (211) hide show
  1. package/README.md +6 -2
  2. package/dist/case-rename.d.ts +65 -0
  3. package/dist/case-rename.d.ts.map +1 -0
  4. package/dist/case-rename.js +198 -0
  5. package/dist/case-rename.js.map +1 -0
  6. package/dist/cli-agent.d.ts +60 -1
  7. package/dist/cli-agent.d.ts.map +1 -1
  8. package/dist/cli-agent.js +225 -13
  9. package/dist/cli-agent.js.map +1 -1
  10. package/dist/config/auth-config.d.ts +16 -1
  11. package/dist/config/auth-config.d.ts.map +1 -1
  12. package/dist/config/auth-config.js +16 -1
  13. package/dist/config/auth-config.js.map +1 -1
  14. package/dist/host-sensors.d.ts +115 -0
  15. package/dist/host-sensors.d.ts.map +1 -0
  16. package/dist/host-sensors.js +457 -0
  17. package/dist/host-sensors.js.map +1 -0
  18. package/dist/remote-hosts.d.ts +7 -0
  19. package/dist/remote-hosts.d.ts.map +1 -1
  20. package/dist/remote-hosts.js +17 -3
  21. package/dist/remote-hosts.js.map +1 -1
  22. package/dist/remote-pane-history.d.ts.map +1 -1
  23. package/dist/remote-pane-history.js +2 -2
  24. package/dist/remote-pane-history.js.map +1 -1
  25. package/dist/session.d.ts.map +1 -1
  26. package/dist/session.js +13 -0
  27. package/dist/session.js.map +1 -1
  28. package/dist/tmux-manager.d.ts +7 -3
  29. package/dist/tmux-manager.d.ts.map +1 -1
  30. package/dist/tmux-manager.js +47 -15
  31. package/dist/tmux-manager.js.map +1 -1
  32. package/dist/tmux-prefix-table.d.ts +37 -5
  33. package/dist/tmux-prefix-table.d.ts.map +1 -1
  34. package/dist/tmux-prefix-table.js +40 -5
  35. package/dist/tmux-prefix-table.js.map +1 -1
  36. package/dist/tui/tui-app.d.ts +8 -1
  37. package/dist/tui/tui-app.d.ts.map +1 -1
  38. package/dist/tui/tui-app.js +49 -12
  39. package/dist/tui/tui-app.js.map +1 -1
  40. package/dist/tui/tui-client.d.ts +90 -3
  41. package/dist/tui/tui-client.d.ts.map +1 -1
  42. package/dist/tui/tui-client.js +195 -26
  43. package/dist/tui/tui-client.js.map +1 -1
  44. package/dist/web/agent-inbox-persistence.d.ts +52 -0
  45. package/dist/web/agent-inbox-persistence.d.ts.map +1 -0
  46. package/dist/web/agent-inbox-persistence.js +139 -0
  47. package/dist/web/agent-inbox-persistence.js.map +1 -0
  48. package/dist/web/agent-inbox.d.ts +140 -0
  49. package/dist/web/agent-inbox.d.ts.map +1 -0
  50. package/dist/web/agent-inbox.js +258 -0
  51. package/dist/web/agent-inbox.js.map +1 -0
  52. package/dist/web/middleware/auth.d.ts +2 -0
  53. package/dist/web/middleware/auth.d.ts.map +1 -1
  54. package/dist/web/middleware/auth.js +145 -52
  55. package/dist/web/middleware/auth.js.map +1 -1
  56. package/dist/web/public/admin-ui.js.gz +0 -0
  57. package/dist/web/public/api-client.c9b1cddc.js.gz +0 -0
  58. package/dist/web/public/app.42d0abae.js +43 -0
  59. package/dist/web/public/app.42d0abae.js.br +0 -0
  60. package/dist/web/public/app.42d0abae.js.gz +0 -0
  61. package/dist/web/public/approvals-ui.js.gz +0 -0
  62. package/dist/web/public/{constants.4866ecc3.js → constants.0b3cdde9.js} +11 -0
  63. package/dist/web/public/constants.0b3cdde9.js.br +0 -0
  64. package/dist/web/public/constants.0b3cdde9.js.gz +0 -0
  65. package/dist/web/public/cron-ui.js.gz +0 -0
  66. package/dist/web/public/entrance-animations.js.gz +0 -0
  67. package/dist/web/public/git-status-ui.js.gz +0 -0
  68. package/dist/web/public/header-divider.eb2d2463.js +1 -0
  69. package/dist/web/public/header-divider.eb2d2463.js.br +0 -0
  70. package/dist/web/public/header-divider.eb2d2463.js.gz +0 -0
  71. package/dist/web/public/home-sessions.js.gz +0 -0
  72. package/dist/web/public/host-wake-ui.js.gz +0 -0
  73. package/dist/web/public/i18n.1e68220d.js +2 -0
  74. package/dist/web/public/i18n.1e68220d.js.br +0 -0
  75. package/dist/web/public/i18n.1e68220d.js.gz +0 -0
  76. package/dist/web/public/image-input.941386e7.js.gz +0 -0
  77. package/dist/web/public/index.html +74 -11
  78. package/dist/web/public/index.html.br +0 -0
  79. package/dist/web/public/index.html.gz +0 -0
  80. package/dist/web/public/input-cjk.8bc46081.js.gz +0 -0
  81. package/dist/web/public/keyboard-accessory.4e8b20ac.js.gz +0 -0
  82. package/dist/web/public/{mobile-handlers.44adaa07.js → mobile-handlers.1c0cbcd8.js} +4 -2
  83. package/dist/web/public/mobile-handlers.1c0cbcd8.js.br +0 -0
  84. package/dist/web/public/mobile-handlers.1c0cbcd8.js.gz +0 -0
  85. package/dist/web/public/mobile-ime-preview.2dbaf262.js.gz +0 -0
  86. package/dist/web/public/mobile-overview.js.gz +0 -0
  87. package/dist/web/public/mobile.12fb18de.css.gz +0 -0
  88. package/dist/web/public/notification-manager.feb82c04.js.gz +0 -0
  89. package/dist/web/public/orchestrator-panel.js.gz +0 -0
  90. package/dist/web/public/{panels-ui.cbb24ba1.js → panels-ui.78c3defb.js} +76 -70
  91. package/dist/web/public/panels-ui.78c3defb.js.br +0 -0
  92. package/dist/web/public/panels-ui.78c3defb.js.gz +0 -0
  93. package/dist/web/public/ralph-panel.b350e2ef.js.gz +0 -0
  94. package/dist/web/public/ralph-wizard.b6c0dd19.js.gz +0 -0
  95. package/dist/web/public/readmymind-ui.js.gz +0 -0
  96. package/dist/web/public/reboot-restore-ui.js.gz +0 -0
  97. package/dist/web/public/respawn-ui.d7adcf6a.js.gz +0 -0
  98. package/dist/web/public/sanitize-html.e7147e76.js.gz +0 -0
  99. package/dist/web/public/session-lineage.js.gz +0 -0
  100. package/dist/web/public/{session-ui.9c1f009b.js → session-ui.ea6b1994.js} +28 -26
  101. package/dist/web/public/session-ui.ea6b1994.js.br +0 -0
  102. package/dist/web/public/session-ui.ea6b1994.js.gz +0 -0
  103. package/dist/web/public/{settings-ui.fea9ddae.js → settings-ui.085dd202.js} +3 -3
  104. package/dist/web/public/settings-ui.085dd202.js.br +0 -0
  105. package/dist/web/public/settings-ui.085dd202.js.gz +0 -0
  106. package/dist/web/public/spreadsheet-preview-worker.js.gz +0 -0
  107. package/dist/web/public/spreadsheet-preview.75c751de.js.gz +0 -0
  108. package/dist/web/public/spreadsheet-xlsx-core.js.gz +0 -0
  109. package/dist/web/public/styles.3b59b41d.css +1 -0
  110. package/dist/web/public/styles.3b59b41d.css.br +0 -0
  111. package/dist/web/public/styles.3b59b41d.css.gz +0 -0
  112. package/dist/web/public/subagent-windows.07277a58.js.gz +0 -0
  113. package/dist/web/public/sw.js +2 -2
  114. package/dist/web/public/sw.js.br +0 -0
  115. package/dist/web/public/sw.js.gz +0 -0
  116. package/dist/web/public/tab-layout-browser.2d6189f7.js.gz +0 -0
  117. package/dist/web/public/tab-rail-resize.7157e0bd.js.gz +0 -0
  118. package/dist/web/public/terminal-keycode229-recovery.af09f99a.js.gz +0 -0
  119. package/dist/web/public/terminal-split.js.gz +0 -0
  120. package/dist/web/public/terminal-tile.js +8 -1
  121. package/dist/web/public/terminal-tile.js.br +0 -0
  122. package/dist/web/public/terminal-tile.js.gz +0 -0
  123. package/dist/web/public/terminal-ui.fb2a27f5.js +2 -0
  124. package/dist/web/public/terminal-ui.fb2a27f5.js.br +0 -0
  125. package/dist/web/public/terminal-ui.fb2a27f5.js.gz +0 -0
  126. package/dist/web/public/tile-grid.js.gz +0 -0
  127. package/dist/web/public/ultracode-panel.js.gz +0 -0
  128. package/dist/web/public/ultracode-windows.js.gz +0 -0
  129. package/dist/web/public/vendor/dompurify.min.js.gz +0 -0
  130. package/dist/web/public/vendor/exceljs.min.js.gz +0 -0
  131. package/dist/web/public/vendor/fflate.min.js.gz +0 -0
  132. package/dist/web/public/vendor/marked.min.js.gz +0 -0
  133. package/dist/web/public/vendor/xterm-addon-fit.min.js.gz +0 -0
  134. package/dist/web/public/vendor/xterm-addon-serialize.min.js.gz +0 -0
  135. package/dist/web/public/vendor/xterm-addon-unicode11.min.js.gz +0 -0
  136. package/dist/web/public/vendor/xterm-addon-webgl.min.js.gz +0 -0
  137. package/dist/web/public/vendor/xterm-predictive-echo.ae5e3d5d.js.gz +0 -0
  138. package/dist/web/public/vendor/xterm-zerolag-input.0b69623c.js.gz +0 -0
  139. package/dist/web/public/vendor/xterm.css.gz +0 -0
  140. package/dist/web/public/vendor/xterm.min.js.gz +0 -0
  141. package/dist/web/public/voice-input.2342c37b.js.gz +0 -0
  142. package/dist/web/public/voice-pcm-worklet.js.gz +0 -0
  143. package/dist/web/public/webview-tabs.js.gz +0 -0
  144. package/dist/web/public/whats-new.json +9 -9
  145. package/dist/web/route-helpers.d.ts +57 -6
  146. package/dist/web/route-helpers.d.ts.map +1 -1
  147. package/dist/web/route-helpers.js +72 -4
  148. package/dist/web/route-helpers.js.map +1 -1
  149. package/dist/web/routes/case-routes.d.ts.map +1 -1
  150. package/dist/web/routes/case-routes.js +183 -2
  151. package/dist/web/routes/case-routes.js.map +1 -1
  152. package/dist/web/routes/inbox-routes.d.ts +43 -0
  153. package/dist/web/routes/inbox-routes.d.ts.map +1 -0
  154. package/dist/web/routes/inbox-routes.js +148 -0
  155. package/dist/web/routes/inbox-routes.js.map +1 -0
  156. package/dist/web/routes/index.d.ts +1 -0
  157. package/dist/web/routes/index.d.ts.map +1 -1
  158. package/dist/web/routes/index.js +1 -0
  159. package/dist/web/routes/index.js.map +1 -1
  160. package/dist/web/routes/session-routes.d.ts.map +1 -1
  161. package/dist/web/routes/session-routes.js +25 -47
  162. package/dist/web/routes/session-routes.js.map +1 -1
  163. package/dist/web/routes/system-routes.d.ts.map +1 -1
  164. package/dist/web/routes/system-routes.js +23 -2
  165. package/dist/web/routes/system-routes.js.map +1 -1
  166. package/dist/web/schemas.d.ts +26 -0
  167. package/dist/web/schemas.d.ts.map +1 -1
  168. package/dist/web/schemas.js +48 -0
  169. package/dist/web/schemas.js.map +1 -1
  170. package/dist/web/sensitive-path.d.ts.map +1 -1
  171. package/dist/web/sensitive-path.js +2 -0
  172. package/dist/web/sensitive-path.js.map +1 -1
  173. package/dist/web/server.d.ts +2 -0
  174. package/dist/web/server.d.ts.map +1 -1
  175. package/dist/web/server.js +61 -3
  176. package/dist/web/server.js.map +1 -1
  177. package/dist/web/session-wait-registry.d.ts +48 -4
  178. package/dist/web/session-wait-registry.d.ts.map +1 -1
  179. package/dist/web/session-wait-registry.js +144 -6
  180. package/dist/web/session-wait-registry.js.map +1 -1
  181. package/dist/web/sse-events.d.ts +4 -1
  182. package/dist/web/sse-events.d.ts.map +1 -1
  183. package/dist/web/sse-events.js +4 -1
  184. package/dist/web/sse-events.js.map +1 -1
  185. package/package.json +1 -1
  186. package/skills/codeman/SKILL.md +7 -4
  187. package/skills/codeman/preamble.sh +3 -3
  188. package/skills/codeman/reference/endpoints.md +24 -3
  189. package/skills/codeman/reference/verbs.md +47 -0
  190. package/dist/web/public/app.9314ee60.js +0 -43
  191. package/dist/web/public/app.9314ee60.js.br +0 -0
  192. package/dist/web/public/app.9314ee60.js.gz +0 -0
  193. package/dist/web/public/constants.4866ecc3.js.br +0 -0
  194. package/dist/web/public/constants.4866ecc3.js.gz +0 -0
  195. package/dist/web/public/i18n.22ca902b.js +0 -2
  196. package/dist/web/public/i18n.22ca902b.js.br +0 -0
  197. package/dist/web/public/i18n.22ca902b.js.gz +0 -0
  198. package/dist/web/public/mobile-handlers.44adaa07.js.br +0 -0
  199. package/dist/web/public/mobile-handlers.44adaa07.js.gz +0 -0
  200. package/dist/web/public/panels-ui.cbb24ba1.js.br +0 -0
  201. package/dist/web/public/panels-ui.cbb24ba1.js.gz +0 -0
  202. package/dist/web/public/session-ui.9c1f009b.js.br +0 -0
  203. package/dist/web/public/session-ui.9c1f009b.js.gz +0 -0
  204. package/dist/web/public/settings-ui.fea9ddae.js.br +0 -0
  205. package/dist/web/public/settings-ui.fea9ddae.js.gz +0 -0
  206. package/dist/web/public/styles.e096fcd6.css +0 -1
  207. package/dist/web/public/styles.e096fcd6.css.br +0 -0
  208. package/dist/web/public/styles.e096fcd6.css.gz +0 -0
  209. package/dist/web/public/terminal-ui.68dbd352.js +0 -2
  210. package/dist/web/public/terminal-ui.68dbd352.js.br +0 -0
  211. package/dist/web/public/terminal-ui.68dbd352.js.gz +0 -0
@@ -1,4 +1,4 @@
1
- "use strict";Object.assign(CodemanApp.prototype,{_onHookIdlePrompt(e){e.acknowledgedReason||(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:""}`:"",n=e.source==="screen"&&e.message?e.message:"";this._notifySession(e.sessionId,"critical","hook-permission","Permission Required",t||n||"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.acknowledgedReason||(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"))},populateTerminalFontWeight(e,t){if(!e)return;const n=t==null?"":String(t).trim();if(n&&!Array.from(e.options).some(s=>s.value===n)){const s=document.createElement("option");s.value=n,s.textContent=`${n} (custom)`,e.appendChild(s)}e.value=n},readTerminalFontWeight(e){return e?.value.trim()||""},async checkWhatsNew(e){if(this._whatsNewChecked)return;this._whatsNewChecked=!0;const t="codeman-whats-new-seen";let n=null;try{n=localStorage.getItem(t)}catch{return}const s=()=>{try{localStorage.setItem(t,e)}catch{}},[o,i]=await Promise.all([n&&n!==e?this._fetchWhatsNewNotes():null,this._loadSecurityNotices()]);if(this.isSoloWindow&&i.length)return;const a=window.CodemanSecurityNotices.plan({seenVersion:n,runningVersion:e,notes:o,notices:i});if(a.recordVersion&&s(),a.update){const l=o.highlights.slice(0,3).join(" \xB7 "),d=o.highlights.length>3?` (+${o.highlights.length-3} more)`:"",r=`Codeman updated to v${e}: ${l}${d}`,c=`https://github.com/Ark0N/Codeman/releases/tag/codeman%40${e}`;a.updateNotices.length?this.showUpdateNotice({text:r,releaseUrl:c,notices:a.updateNotices,onNoticeSeen:p=>this._rememberSecurityNotice(p)}):this.showToast(r,"info",{duration:2e4,action:{label:"See what's new",onClick:()=>window.open(c,"_blank","noopener")}})}for(const l of a.cards)this.showSecurityNotice(l,{onClose:()=>this._rememberSecurityNotice(l.id)})},async _fetchWhatsNewNotes(){try{const e=await fetch("/whats-new.json",{cache:"no-cache"});return e.ok?await e.json():null}catch{return null}},async _loadSecurityNotices(){let e;try{e=this._readSecurityNoticesSeen()}catch{return[]}try{const t=await fetch(CodemanBase.url("/security-notices.json"),{cache:"no-cache"});if(!t.ok)return[];const n=await t.json(),s=Array.isArray(n?.notices)?n.notices:[],o=this.isSoloWindow?Object.fromEntries(s.filter(i=>typeof i?.cli=="string").map(i=>[i.cli,!0])):window.__codemanCliAvailable;return window.CodemanSecurityNotices.select(n?.notices,{available:o,seen:e,now:Date.now(),lang:window.CodemanI18n?.language||window.__codemanLanguage})}catch{return[]}},_readSecurityNoticesSeen(){const e=localStorage.getItem("codeman-security-notices-seen");let t=[];try{t=e?JSON.parse(e):[]}catch{}return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]},_rememberSecurityNotice(e){try{const t=this._readSecurityNoticesSeen();t.includes(e)||t.push(e),localStorage.setItem("codeman-security-notices-seen",JSON.stringify(t))}catch{}},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("appSettingsHeaderStatsStyle").value=this.resolveHeaderStatsStyle(e),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("appSettingsCustomModelEndpoints").checked=e.customModelEndpointsEnabled===!0,this.applyCustomModelEndpointsVisibility(),document.getElementById("appSettingsCliManagement").checked=e.cliManagementEnabled===!0,this.applyCliManagementVisibility(),this._mcpSyncSavedOn=e.mcpSyncEnabled===!0,document.getElementById("appSettingsMcpSync").checked=this._mcpSyncSavedOn,this.applyMcpSyncVisibility(),document.getElementById("appSettingsConfigBackup").checked=e.configBackupEnabled!==!1,document.getElementById("appSettingsConfigBackupDir").value=e.configBackupDir||"",document.getElementById("appSettingsConfigBackupKeepCount").value=e.configBackupKeepCount??20,document.getElementById("appSettingsConfigBackupKeepDays").value=e.configBackupKeepDays??30,this.loadConfigBackups(),this._applyDoctorAdminGate(),this.loadWebhook(),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("appSettingsShowSplitButton").checked=e.showSplitButton??t.showSplitButton??!1,document.getElementById("appSettingsShowTileGridButton").checked=e.showTileGridButton??t.showTileGridButton??!0,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,document.getElementById("appSettingsAutoNameSessions").checked=e.autoNameSessions===!0,document.getElementById("appSettingsSpawnedTabsFollowParent").checked=e.spawnedTabsFollowParent===!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,document.getElementById("appSettingsShowGitStatus").checked=e.showGitStatus??t.showGitStatus??!1,document.getElementById("appSettingsGitStatusTree").checked=e.gitStatusTree??t.gitStatusTree??!0,document.getElementById("appSettingsGitStatusMaxRepos").value=e.gitStatusMaxRepos??t.gitStatusMaxRepos??12,document.getElementById("appSettingsGitStatusTimeout").value=e.gitStatusTimeoutSeconds??t.gitStatusTimeoutSeconds??30;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("appSettingsPromptCacheKeepWarm").checked=e.promptCacheKeepWarm===!0,document.getElementById("appSettingsPromptCacheKeepWarmMaxHours").value=e.promptCacheKeepWarmMaxHours??2,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("appSettingsCopyStripMargin").checked=e.copyStripMargin!==!1,document.getElementById("appSettingsTerminalFont").value=e.terminalFontFamily||"",this.populateTerminalFontWeight(document.getElementById("appSettingsTerminalFontWeight"),e.terminalFontWeight),this.populateTerminalFontWeight(document.getElementById("appSettingsTerminalFontWeightBold"),e.terminalFontWeightBold),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("appSettingsShowTabCliLogos").checked=this.tabCliLogosEnabled(e),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("appSettingsTabRailSort").value=e.tabRailSort??t.tabRailSort??"activity",document.getElementById("appSettingsTabArrangement").value=this.resolveTabArrangement(e),document.getElementById("appSettingsTabStateOrder").value=this.resolveTabStateOrder(e),document.getElementById("appSettingsShowTabDetachButton").checked=this.tabDetachButtonEnabled?.(e,t)??e.showTabDetachButton??t.showTabDetachButton??!1,document.getElementById("appSettingsTileDetach").checked=e.tileDetachEnabled===!0;const l=document.getElementById("appSettingsTileDetachItem");l&&(l.style.display=MobileDetection.getDeviceType()==="desktop"?"":"none"),document.getElementById("appSettingsSessionListLayout").value=e.sessionListLayout??t.sessionListLayout??"header";const d=this.resolveSessionSidebarFontSize(e.sessionSidebarFontSize??t.sessionSidebarFontSize);document.getElementById("appSettingsSessionSidebarFontSize").value=String(d),document.getElementById("appSettingsSessionSidebarFontSizeValue").textContent=`${d} px`;const r=document.getElementById("appSettingsClaudeMode"),c=document.getElementById("allowedToolsRow");r.value=e.claudeMode||"dangerously-skip-permissions",document.getElementById("appSettingsAllowedTools").value=e.allowedTools||"",c.style.display=r.value==="allowedTools"?"":"none",r.onchange=()=>{c.style.display=r.value==="allowedTools"?"":"none"},document.getElementById("appSettingsCodexDangerouslyBypassApprovals").checked=e.codexDangerouslyBypassApprovals??!1,document.getElementById("appSettingsCodexAnimations").checked=e.codexAnimationsEnabled??!1,document.getElementById("appSettingsCodexModel").value=e.codexModel??"",document.getElementById("appSettingsCodexReasoningEffort").value=e.codexReasoningEffort??"",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("appSettingsPinCliSessionName").checked=e.pinCliSessionName===!0,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??"",document.getElementById("appSettingsClaudeAdvisor").value=e.claudeAdvisorModel??"";const p=e.nice||{};document.getElementById("appSettingsNiceEnabled").checked=p.enabled??!1,document.getElementById("appSettingsNiceValue").value=p.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("appSettingsNotifToastSecs").value=Math.round((this.notificationManager?.getToastDurationMs?.()??DEFAULT_TOAST_DURATION_MS)/1e3),document.getElementById("appSettingsNotifBrowserSecs").value=Math.round((u.browserAutoCloseMs??AUTO_CLOSE_NOTIFICATION_MS)/1e3),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 m=u.eventTypes||{},f=m.permission_prompt||{};document.getElementById("eventPermissionEnabled").checked=f.enabled??!0,document.getElementById("eventPermissionBrowser").checked=f.browser??!0,document.getElementById("eventPermissionPush").checked=f.push??!1,document.getElementById("eventPermissionAudio").checked=f.audio??!0;const h=m.elicitation_dialog||{};document.getElementById("eventQuestionEnabled").checked=h.enabled??!0,document.getElementById("eventQuestionBrowser").checked=h.browser??!0,document.getElementById("eventQuestionPush").checked=h.push??!1,document.getElementById("eventQuestionAudio").checked=h.audio??!0;const g=m.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 y=m.stop||{};document.getElementById("eventStopEnabled").checked=y.enabled??!1,document.getElementById("eventStopBrowser").checked=y.browser??!1,document.getElementById("eventStopPush").checked=y.push??!1,document.getElementById("eventStopAudio").checked=y.audio??!1;const S=m.respawn_cycle||{};document.getElementById("eventRespawnEnabled").checked=S.enabled??!0,document.getElementById("eventRespawnBrowser").checked=S.browser??!1,document.getElementById("eventRespawnPush").checked=S.push??!1,document.getElementById("eventRespawnAudio").checked=S.audio??!1;const b=m.ralph_complete||{};document.getElementById("eventRalphEnabled").checked=b.enabled??!0,document.getElementById("eventRalphBrowser").checked=b.browser??!0,document.getElementById("eventRalphPush").checked=b.push??!1,document.getElementById("eventRalphAudio").checked=b.audio??!0;const E=m.subagent_spawn||{};document.getElementById("eventSubagentEnabled").checked=E.enabled??!1,document.getElementById("eventSubagentBrowser").checked=E.browser??!1,document.getElementById("eventSubagentPush").checked=E.push??!1,document.getElementById("eventSubagentAudio").checked=E.audio??!1;const w=document.getElementById("notifPermissionStatus");if(w&&typeof Notification<"u"){const I=Notification.permission;w.textContent=I==="granted"?"\u2713":I==="denied"?"\u2717":"?",w.classList.remove("granted","denied"),I==="granted"?w.classList.add("granted"):I==="denied"&&w.classList.add("denied")}const v=VoiceInput._getDeepgramConfig();document.getElementById("voiceDeepgramKey").value=v.apiKey||"",document.getElementById("voiceLanguage").value=v.language||"en-US",document.getElementById("voiceKeyterms").value=v.keyterms||DEFAULT_VOICE_KEYTERMS,document.getElementById("voiceInsertMode").value=v.insertMode||"direct",document.getElementById("voiceProvider").value=v.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._syncAdvisorSegment(),this.switchSettingsTab("settings-updates");const k=document.getElementById("appSettingsModal");k.classList.add("active"),this.activeFocusTrap=new FocusTrap(k),this.activeFocusTrap.activate(),this._captureSettingsFormBaseline()},_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._buildAdvisorSegment(),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 d=i.querySelectorAll("span"),r=(d[d.length-1]?.textContent||"").trim(),c=document.createElement("span");if(c.title=r,a==="header"){const p=i.dataset.previewText;c.className=p?"set-preview-chip":"set-preview-btn",p?c.textContent=p:this._appendPreviewIcon(c,i)}else{c.className=`set-preview-${a}`,this._appendPreviewIcon(c,i);const p=document.createElement("span");p.textContent=r,c.appendChild(p)}l.appendChild(c),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 d=document.createElement("span");d.className="set-mc-ctx",d.textContent="1M capable",s.appendChild(d)}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(d=>{const r=d.dataset.value===n;d.classList.toggle("selected",r),d.setAttribute("aria-checked",r?"true":"false"),r&&(s=d.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 5.5, Opus and Opus 4.6.":"With no model pinned, this starts new sessions on Opus with a 1M window.")},_buildEffortSegment(){this._buildSelectSegment("appSettingsThinkingEffort","appSettingsEffortSegment")},_syncEffortSegment(){this._syncSelectSegment("appSettingsThinkingEffort","appSettingsEffortSegment")},_buildAdvisorSegment(){this._buildSelectSegment("appSettingsClaudeAdvisor","appSettingsAdvisorSegment")},_syncAdvisorSegment(){this._syncSelectSegment("appSettingsClaudeAdvisor","appSettingsAdvisorSegment")},_buildSelectSegment(e,t){const n=document.getElementById(e),s=document.getElementById(t);!n||!s||s.dataset.built==="1"||!n.options||(s.innerHTML="",[...n.options].forEach(o=>{const i=document.createElement("button");i.type="button",i.setAttribute("role","radio"),i.dataset.value=o.value,i.textContent=o.textContent,i.addEventListener("click",()=>{n.value=o.value,this._syncSelectSegment(e,t)}),s.appendChild(i)}),s.dataset.built="1")},_syncSelectSegment(e,t){const n=document.getElementById(e),s=document.getElementById(t);!n||!s||s.querySelectorAll("button").forEach(o=>{const i=o.dataset.value===(n.value||"");o.classList.toggle("selected",i),o.setAttribute("aria-checked",i?"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 r=`${l.dataset?.search||""} ${l.textContent||""}`.toLowerCase().includes(n);l.classList.toggle("set-hit-hidden",!r),r&&(i=!0)}),t.querySelectorAll(".set-chips").forEach(l=>{const d=[...l.querySelectorAll(".set-chip")].some(r=>!r.classList.contains("set-hit-hidden"));l.classList.toggle("set-hit-hidden",!!n&&!d)}),t.querySelectorAll(".set-group").forEach(l=>{const d=[...l.querySelectorAll(s)].some(r=>!r.classList.contains("set-hit-hidden"));l.classList.toggle("set-hit-hidden",!!n&&!d),n&&d&&l.classList.add("open")}),t.querySelectorAll(".set-section").forEach(l=>{const d=[...l.querySelectorAll(".set-group")].some(r=>!r.classList.contains("set-hit-hidden"));l.classList.toggle("set-hit-hidden",!!n&&!d)}),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},keyTesterEvent(e){const t=document.getElementById("keyTesterLog");if(!t)return;const n=["ctrlKey","shiftKey","altKey","metaKey"].filter(i=>e[i]).map(i=>i.replace("Key","")),s=`${e.type.padEnd(8)} key=${JSON.stringify(e.key)} code=${e.code||"-"} mods=${n.join("+")||"none"}`+(e.type==="keypress"?` charCode=${e.charCode}`:"")+(e.repeat?" (repeat)":""),o=(t.textContent?t.textContent.split(`
1
+ "use strict";Object.assign(CodemanApp.prototype,{_onHookIdlePrompt(e){e.acknowledgedReason||(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:""}`:"",n=e.source==="screen"&&e.message?e.message:"";this._notifySession(e.sessionId,"critical","hook-permission","Permission Required",t||n||"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.acknowledgedReason||(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"))},populateTerminalFontWeight(e,t){if(!e)return;const n=t==null?"":String(t).trim();if(n&&!Array.from(e.options).some(s=>s.value===n)){const s=document.createElement("option");s.value=n,s.textContent=`${n} (custom)`,e.appendChild(s)}e.value=n},readTerminalFontWeight(e){return e?.value.trim()||""},async checkWhatsNew(e){if(this._whatsNewChecked)return;this._whatsNewChecked=!0;const t="codeman-whats-new-seen";let n=null;try{n=localStorage.getItem(t)}catch{return}const s=()=>{try{localStorage.setItem(t,e)}catch{}},[o,i]=await Promise.all([n&&n!==e?this._fetchWhatsNewNotes():null,this._loadSecurityNotices()]);if(this.isSoloWindow&&i.length)return;const a=window.CodemanSecurityNotices.plan({seenVersion:n,runningVersion:e,notes:o,notices:i});if(a.recordVersion&&s(),a.update){const l=o.highlights.slice(0,3).join(" \xB7 "),d=o.highlights.length>3?` (+${o.highlights.length-3} more)`:"",r=`Codeman updated to v${e}: ${l}${d}`,c=`https://github.com/Ark0N/Codeman/releases/tag/codeman%40${e}`;a.updateNotices.length?this.showUpdateNotice({text:r,releaseUrl:c,notices:a.updateNotices,onNoticeSeen:p=>this._rememberSecurityNotice(p)}):this.showToast(r,"info",{duration:2e4,action:{label:"See what's new",onClick:()=>window.open(c,"_blank","noopener")}})}for(const l of a.cards)this.showSecurityNotice(l,{onClose:()=>this._rememberSecurityNotice(l.id)})},async _fetchWhatsNewNotes(){try{const e=await fetch("/whats-new.json",{cache:"no-cache"});return e.ok?await e.json():null}catch{return null}},async _loadSecurityNotices(){let e;try{e=this._readSecurityNoticesSeen()}catch{return[]}try{const t=await fetch(CodemanBase.url("/security-notices.json"),{cache:"no-cache"});if(!t.ok)return[];const n=await t.json(),s=Array.isArray(n?.notices)?n.notices:[],o=this.isSoloWindow?Object.fromEntries(s.filter(i=>typeof i?.cli=="string").map(i=>[i.cli,!0])):window.__codemanCliAvailable;return window.CodemanSecurityNotices.select(n?.notices,{available:o,seen:e,now:Date.now(),lang:window.CodemanI18n?.language||window.__codemanLanguage})}catch{return[]}},_readSecurityNoticesSeen(){const e=localStorage.getItem("codeman-security-notices-seen");let t=[];try{t=e?JSON.parse(e):[]}catch{}return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]},_rememberSecurityNotice(e){try{const t=this._readSecurityNoticesSeen();t.includes(e)||t.push(e),localStorage.setItem("codeman-security-notices-seen",JSON.stringify(t))}catch{}},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("appSettingsShowGpuStats").checked=e.showGpuStats??t.showGpuStats??!1,document.getElementById("appSettingsShowCpuMhz").checked=e.showCpuMhz??t.showCpuMhz??!1,document.getElementById("appSettingsHeaderStatsStyle").value=this.resolveHeaderStatsStyle(e),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("appSettingsAgentInboxPersist").checked=e.agentInboxPersistEnabled===!0,document.getElementById("appSettingsCustomModelEndpoints").checked=e.customModelEndpointsEnabled===!0,this.applyCustomModelEndpointsVisibility(),document.getElementById("appSettingsCliManagement").checked=e.cliManagementEnabled===!0,this.applyCliManagementVisibility(),this._mcpSyncSavedOn=e.mcpSyncEnabled===!0,document.getElementById("appSettingsMcpSync").checked=this._mcpSyncSavedOn,this.applyMcpSyncVisibility(),document.getElementById("appSettingsConfigBackup").checked=e.configBackupEnabled!==!1,document.getElementById("appSettingsConfigBackupDir").value=e.configBackupDir||"",document.getElementById("appSettingsConfigBackupKeepCount").value=e.configBackupKeepCount??20,document.getElementById("appSettingsConfigBackupKeepDays").value=e.configBackupKeepDays??30,this.loadConfigBackups(),this._applyDoctorAdminGate(),this.loadWebhook(),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("appSettingsShowSplitButton").checked=e.showSplitButton??t.showSplitButton??!1,document.getElementById("appSettingsShowTileGridButton").checked=e.showTileGridButton??t.showTileGridButton??!0,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,document.getElementById("appSettingsAutoNameSessions").checked=e.autoNameSessions===!0,document.getElementById("appSettingsSpawnedTabsFollowParent").checked=e.spawnedTabsFollowParent===!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,document.getElementById("appSettingsShowGitStatus").checked=e.showGitStatus??t.showGitStatus??!1,document.getElementById("appSettingsGitStatusTree").checked=e.gitStatusTree??t.gitStatusTree??!0,document.getElementById("appSettingsGitStatusMaxRepos").value=e.gitStatusMaxRepos??t.gitStatusMaxRepos??12,document.getElementById("appSettingsGitStatusTimeout").value=e.gitStatusTimeoutSeconds??t.gitStatusTimeoutSeconds??30;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("appSettingsPromptCacheKeepWarm").checked=e.promptCacheKeepWarm===!0,document.getElementById("appSettingsPromptCacheKeepWarmMaxHours").value=e.promptCacheKeepWarmMaxHours??2,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("appSettingsCopyStripMargin").checked=e.copyStripMargin!==!1,document.getElementById("appSettingsTerminalFont").value=e.terminalFontFamily||"",this.populateTerminalFontWeight(document.getElementById("appSettingsTerminalFontWeight"),e.terminalFontWeight),this.populateTerminalFontWeight(document.getElementById("appSettingsTerminalFontWeightBold"),e.terminalFontWeightBold),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("appSettingsShowTabCliLogos").checked=this.tabCliLogosEnabled(e),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("appSettingsTabRailSort").value=e.tabRailSort??t.tabRailSort??"activity",document.getElementById("appSettingsTabArrangement").value=this.resolveTabArrangement(e),document.getElementById("appSettingsTabStateOrder").value=this.resolveTabStateOrder(e),document.getElementById("appSettingsShowTabDetachButton").checked=this.tabDetachButtonEnabled?.(e,t)??e.showTabDetachButton??t.showTabDetachButton??!1,document.getElementById("appSettingsTileDetach").checked=e.tileDetachEnabled===!0;const l=document.getElementById("appSettingsTileDetachItem");l&&(l.style.display=MobileDetection.getDeviceType()==="desktop"?"":"none"),document.getElementById("appSettingsSessionListLayout").value=e.sessionListLayout??t.sessionListLayout??"header";const d=this.resolveSessionSidebarFontSize(e.sessionSidebarFontSize??t.sessionSidebarFontSize);document.getElementById("appSettingsSessionSidebarFontSize").value=String(d),document.getElementById("appSettingsSessionSidebarFontSizeValue").textContent=`${d} px`;const r=document.getElementById("appSettingsClaudeMode"),c=document.getElementById("allowedToolsRow");r.value=e.claudeMode||"dangerously-skip-permissions",document.getElementById("appSettingsAllowedTools").value=e.allowedTools||"",c.style.display=r.value==="allowedTools"?"":"none",r.onchange=()=>{c.style.display=r.value==="allowedTools"?"":"none"},document.getElementById("appSettingsCodexDangerouslyBypassApprovals").checked=e.codexDangerouslyBypassApprovals??!1,document.getElementById("appSettingsCodexAnimations").checked=e.codexAnimationsEnabled??!1,document.getElementById("appSettingsCodexModel").value=e.codexModel??"",document.getElementById("appSettingsCodexReasoningEffort").value=e.codexReasoningEffort??"",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("appSettingsPinCliSessionName").checked=e.pinCliSessionName===!0,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??"",document.getElementById("appSettingsClaudeAdvisor").value=e.claudeAdvisorModel??"";const p=e.nice||{};document.getElementById("appSettingsNiceEnabled").checked=p.enabled??!1,document.getElementById("appSettingsNiceValue").value=p.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("appSettingsNotifToastSecs").value=Math.round((this.notificationManager?.getToastDurationMs?.()??DEFAULT_TOAST_DURATION_MS)/1e3),document.getElementById("appSettingsNotifBrowserSecs").value=Math.round((u.browserAutoCloseMs??AUTO_CLOSE_NOTIFICATION_MS)/1e3),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 m=u.eventTypes||{},f=m.permission_prompt||{};document.getElementById("eventPermissionEnabled").checked=f.enabled??!0,document.getElementById("eventPermissionBrowser").checked=f.browser??!0,document.getElementById("eventPermissionPush").checked=f.push??!1,document.getElementById("eventPermissionAudio").checked=f.audio??!0;const h=m.elicitation_dialog||{};document.getElementById("eventQuestionEnabled").checked=h.enabled??!0,document.getElementById("eventQuestionBrowser").checked=h.browser??!0,document.getElementById("eventQuestionPush").checked=h.push??!1,document.getElementById("eventQuestionAudio").checked=h.audio??!0;const g=m.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 y=m.stop||{};document.getElementById("eventStopEnabled").checked=y.enabled??!1,document.getElementById("eventStopBrowser").checked=y.browser??!1,document.getElementById("eventStopPush").checked=y.push??!1,document.getElementById("eventStopAudio").checked=y.audio??!1;const S=m.respawn_cycle||{};document.getElementById("eventRespawnEnabled").checked=S.enabled??!0,document.getElementById("eventRespawnBrowser").checked=S.browser??!1,document.getElementById("eventRespawnPush").checked=S.push??!1,document.getElementById("eventRespawnAudio").checked=S.audio??!1;const b=m.ralph_complete||{};document.getElementById("eventRalphEnabled").checked=b.enabled??!0,document.getElementById("eventRalphBrowser").checked=b.browser??!0,document.getElementById("eventRalphPush").checked=b.push??!1,document.getElementById("eventRalphAudio").checked=b.audio??!0;const E=m.subagent_spawn||{};document.getElementById("eventSubagentEnabled").checked=E.enabled??!1,document.getElementById("eventSubagentBrowser").checked=E.browser??!1,document.getElementById("eventSubagentPush").checked=E.push??!1,document.getElementById("eventSubagentAudio").checked=E.audio??!1;const w=document.getElementById("notifPermissionStatus");if(w&&typeof Notification<"u"){const I=Notification.permission;w.textContent=I==="granted"?"\u2713":I==="denied"?"\u2717":"?",w.classList.remove("granted","denied"),I==="granted"?w.classList.add("granted"):I==="denied"&&w.classList.add("denied")}const v=VoiceInput._getDeepgramConfig();document.getElementById("voiceDeepgramKey").value=v.apiKey||"",document.getElementById("voiceLanguage").value=v.language||"en-US",document.getElementById("voiceKeyterms").value=v.keyterms||DEFAULT_VOICE_KEYTERMS,document.getElementById("voiceInsertMode").value=v.insertMode||"direct",document.getElementById("voiceProvider").value=v.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._syncAdvisorSegment(),this.switchSettingsTab("settings-updates");const k=document.getElementById("appSettingsModal");k.classList.add("active"),this.activeFocusTrap=new FocusTrap(k),this.activeFocusTrap.activate(),this._captureSettingsFormBaseline()},_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._buildAdvisorSegment(),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 d=i.querySelectorAll("span"),r=(d[d.length-1]?.textContent||"").trim(),c=document.createElement("span");if(c.title=r,a==="header"){const p=i.dataset.previewText;c.className=p?"set-preview-chip":"set-preview-btn",p?c.textContent=p:this._appendPreviewIcon(c,i)}else{c.className=`set-preview-${a}`,this._appendPreviewIcon(c,i);const p=document.createElement("span");p.textContent=r,c.appendChild(p)}l.appendChild(c),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 d=document.createElement("span");d.className="set-mc-ctx",d.textContent="1M capable",s.appendChild(d)}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(d=>{const r=d.dataset.value===n;d.classList.toggle("selected",r),d.setAttribute("aria-checked",r?"true":"false"),r&&(s=d.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 5.5, Opus and Opus 4.6.":"With no model pinned, this starts new sessions on Opus with a 1M window.")},_buildEffortSegment(){this._buildSelectSegment("appSettingsThinkingEffort","appSettingsEffortSegment")},_syncEffortSegment(){this._syncSelectSegment("appSettingsThinkingEffort","appSettingsEffortSegment")},_buildAdvisorSegment(){this._buildSelectSegment("appSettingsClaudeAdvisor","appSettingsAdvisorSegment")},_syncAdvisorSegment(){this._syncSelectSegment("appSettingsClaudeAdvisor","appSettingsAdvisorSegment")},_buildSelectSegment(e,t){const n=document.getElementById(e),s=document.getElementById(t);!n||!s||s.dataset.built==="1"||!n.options||(s.innerHTML="",[...n.options].forEach(o=>{const i=document.createElement("button");i.type="button",i.setAttribute("role","radio"),i.dataset.value=o.value,i.textContent=o.textContent,i.addEventListener("click",()=>{n.value=o.value,this._syncSelectSegment(e,t)}),s.appendChild(i)}),s.dataset.built="1")},_syncSelectSegment(e,t){const n=document.getElementById(e),s=document.getElementById(t);!n||!s||s.querySelectorAll("button").forEach(o=>{const i=o.dataset.value===(n.value||"");o.classList.toggle("selected",i),o.setAttribute("aria-checked",i?"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 r=`${l.dataset?.search||""} ${l.textContent||""}`.toLowerCase().includes(n);l.classList.toggle("set-hit-hidden",!r),r&&(i=!0)}),t.querySelectorAll(".set-chips").forEach(l=>{const d=[...l.querySelectorAll(".set-chip")].some(r=>!r.classList.contains("set-hit-hidden"));l.classList.toggle("set-hit-hidden",!!n&&!d)}),t.querySelectorAll(".set-group").forEach(l=>{const d=[...l.querySelectorAll(s)].some(r=>!r.classList.contains("set-hit-hidden"));l.classList.toggle("set-hit-hidden",!!n&&!d),n&&d&&l.classList.add("open")}),t.querySelectorAll(".set-section").forEach(l=>{const d=[...l.querySelectorAll(".set-group")].some(r=>!r.classList.contains("set-hit-hidden"));l.classList.toggle("set-hit-hidden",!!n&&!d)}),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},keyTesterEvent(e){const t=document.getElementById("keyTesterLog");if(!t)return;const n=["ctrlKey","shiftKey","altKey","metaKey"].filter(i=>e[i]).map(i=>i.replace("Key","")),s=`${e.type.padEnd(8)} key=${JSON.stringify(e.key)} code=${e.code||"-"} mods=${n.join("+")||"none"}`+(e.type==="keypress"?` charCode=${e.charCode}`:"")+(e.repeat?" (repeat)":""),o=(t.textContent?t.textContent.split(`
2
2
  `):[]).concat(s);t.textContent=o.slice(-14).join(`
3
3
  `),t.style.display="block"},applyMcpSyncVisibility(){const e=document.getElementById("appSettingsMcpSync")?.checked??!1,t=document.getElementById("mcpSyncActionRow");t&&(t.style.display=e?"":"none");const n=this.$("mcpSyncResult");!e&&n&&(n.style.display="none",n.innerHTML=""),this._applyMcpSyncAdminGate()},_applyMcpSyncAdminGate(){const e=document.getElementById("mcpSyncGroup");if(!e)return;const t=window.__codemanUser||{};e.style.display=t.multiUser&&t.role!=="admin"?"none":""},_applyDoctorAdminGate(){const e=window.__codemanUser||{};for(const t of["doctorGroup","configBackupGroup"]){const n=document.getElementById(t);n&&(n.style.display=e.multiUser&&e.role!=="admin"?"none":"")}},_configBackupRetentionPayload(e){const t=document.getElementById("appSettingsConfigBackupKeepCount"),n=document.getElementById("appSettingsConfigBackupKeepDays"),s={};if((e.configBackupKeepCount!==void 0||t.dataset.touched)&&(s.configBackupKeepCount=Math.min(500,Math.max(2,parseInt(t.value,10)||20))),e.configBackupKeepDays!==void 0||n.dataset.touched){const o=parseInt(n.value,10);s.configBackupKeepDays=Math.min(3650,Math.max(0,Number.isNaN(o)?30:o))}return s},async loadConfigBackups(){const e=this.$("configBackupList");if(!e)return;const t=await this._api("/api/config-backups");let n=null;try{n=t?await t.json():null}catch{}if(!t||!t.ok||!n||n.success===!1){e.textContent=n?.error||"Backups are not available here (admin only in multi-user mode).";return}const s=n.data,o=this.$("appSettingsConfigBackupDir")||document.getElementById("appSettingsConfigBackupDir");o&&s.defaultDir&&(o.placeholder=`default: ${s.defaultDir}`);const i=this.loadAppSettingsFromStorage(),a=document.getElementById("appSettingsConfigBackupKeepCount"),l=document.getElementById("appSettingsConfigBackupKeepDays");if(a&&i.configBackupKeepCount===void 0&&s.settings&&(a.value=s.settings.keepCount),l&&i.configBackupKeepDays===void 0&&s.settings&&(l.value=s.settings.keepDays),!s.backups.length){e.innerHTML=`No backups yet in <code>${escapeHtml(s.dir)}</code>.`;return}const d=u=>u<1024?`${u} B`:`${(u/1024).toFixed(1)} KB`;this._configBackups=s.backups;const r=s.backups.map((u,m)=>{const f=new Date(u.createdAt).toLocaleString(),h=u.files.map(b=>escapeHtml(b.name)).join(", "),g=escapeHtml(u.id),y=s.backups[m+1],S=y?`<button class="btn-toolbar btn-sm" onclick="app.showConfigDiff('${escapeHtml(y.id)}','${g}')">Changes in this backup</button>`:"";return`<li><b>${escapeHtml(f)}</b> <span class="set-row-desc">(${escapeHtml(u.reason)}, ${d(u.bytes)})</span>
4
4
  <button class="btn-toolbar btn-sm" onclick="app.restoreConfigBackup('${g}')">Restore</button>
@@ -69,7 +69,7 @@ Enable the unauthenticated public tunnel anyway?`))return this._dismissTunnelCon
69
69
  <td style="padding:3px 8px;color:#e0e0e0" title="${r.sessionId}">${u}</td>
70
70
  <td style="padding:3px 8px;color:#aaa">${r.reason||""}</td>
71
71
  <td style="padding:3px 8px;color:#666">${m.join(", ")}</td>
72
- </tr>`}).join("")}catch(s){console.error("Failed to load lifecycle log:",s)}},_renderVoiceProviderStatus(){const e=document.getElementById("voiceProviderStatus");if(e){const o=VoiceInput.getActiveProviderName();e.textContent=o;const i=o.startsWith("Deepgram Nova")||o.startsWith("Claude (this");e.className="voice-provider-status"+(i?" active":"")}const t=document.getElementById("voiceClaudeStatus");if(!t)return;const n=VoiceInput._claudeStatus,s=n?n.available?`Ready${n.subscriptionType?` (${n.subscriptionType})`:""}`:n.reason==="expired"?"Login expired - run a Claude session to refresh":n.reason==="no-credentials"?"No Claude Code login on the server":n.reason==="malformed"?"Claude credentials unreadable":"Off - enable it above":"Checking...";t.textContent=s,t.className="voice-provider-status"+(n?.available?" active":"")},async applyAppSettings(){if(!this._applyInFlight){this._applyInFlight=!0,this._keepSettingsOpenOnce=!0;try{await this.saveAppSettings()}finally{this._applyInFlight=!1,this._keepSettingsOpenOnce=!1}}},async saveAppSettings(){const e=this._keepSettingsOpenOnce===!0;this._keepSettingsOpenOnce=!1;const t=this.loadAppSettingsFromStorage(),n=(t.gestureControlEnabled??!1)===!0,s=(t.webglRendererEnabled??!0)===!0,o={displayName:window.CodemanI18n?.normalizeDisplayName(document.getElementById("appSettingsDisplayName").value)||"Codeman",language:window.CodemanI18n?.normalizeLanguage(document.getElementById("appSettingsLanguage").value)||"en",defaultClaudeMdPath:document.getElementById("appSettingsClaudeMdPath").value.trim(),defaultWorkingDir:document.getElementById("appSettingsDefaultDir").value.trim(),ralphTrackerEnabled:document.getElementById("appSettingsRalphEnabled").checked,showFontControls:document.getElementById("appSettingsShowFontControls").checked,showSystemStats:document.getElementById("appSettingsShowSystemStats").checked,headerStatsStyle:document.getElementById("appSettingsHeaderStatsStyle").value,showLifecycleLog:document.getElementById("appSettingsShowLifecycleLog").checked,showResponseViewer:document.getElementById("appSettingsShowResponseViewer").checked,showFileViewerButton:document.getElementById("appSettingsShowFileViewerButton").checked,showAttachmentsButton:document.getElementById("appSettingsShowAttachmentsButton").checked,showMonitor:document.getElementById("appSettingsShowMonitor").checked,showProjectInsights:document.getElementById("appSettingsShowProjectInsights").checked,showFileBrowser:document.getElementById("appSettingsShowFileBrowser").checked,showSubagents:document.getElementById("appSettingsShowSubagents").checked,showUltracodeAgents:document.getElementById("appSettingsShowUltracodeAgents").checked,approvalsInboxEnabled:document.getElementById("appSettingsApprovalsInbox").checked,customModelEndpointsEnabled:document.getElementById("appSettingsCustomModelEndpoints").checked,cliManagementEnabled:document.getElementById("appSettingsCliManagement").checked,mcpSyncEnabled:document.getElementById("appSettingsMcpSync").checked,configBackupEnabled:document.getElementById("appSettingsConfigBackup").checked,configBackupDir:document.getElementById("appSettingsConfigBackupDir").value.trim(),...this._configBackupRetentionPayload(t),readMyMindEnabled:document.getElementById("appSettingsReadMyMind").checked,ultracodeFloatingWindows:document.getElementById("appSettingsUltracodeFloatingWindows").checked,showMultiMonitorButton:document.getElementById("appSettingsShowMultiMonitorButton").checked,showSplitButton:document.getElementById("appSettingsShowSplitButton").checked,showTileGridButton:document.getElementById("appSettingsShowTileGridButton").checked,showPlanUsageLimits:document.getElementById("appSettingsShowPlanUsageLimits").checked,showRedrawButton:document.getElementById("appSettingsShowRedrawButton").checked,mobileOverviewEnabled:document.getElementById("appSettingsMobileOverview").checked,sessionLineageLines:document.getElementById("appSettingsLineageLines").checked,autoNameSessions:document.getElementById("appSettingsAutoNameSessions").checked,spawnedTabsFollowParent:document.getElementById("appSettingsSpawnedTabsFollowParent").checked,showSessionButton:document.getElementById("appSettingsShowSessionButton").checked,showAwayDigestButton:document.getElementById("appSettingsShowAwayDigestButton").checked,showCronButton:document.getElementById("appSettingsShowCronButton").checked,showGitStatus:document.getElementById("appSettingsShowGitStatus").checked,gitStatusTree:document.getElementById("appSettingsGitStatusTree").checked,gitStatusMaxRepos:Math.min(50,Math.max(1,parseInt(document.getElementById("appSettingsGitStatusMaxRepos").value,10)||12)),gitStatusTimeoutSeconds:Math.min(120,Math.max(5,parseInt(document.getElementById("appSettingsGitStatusTimeout").value,10)||30)),gestureControlEnabled:document.getElementById("appSettingsGestureControl").checked,subagentTrackingEnabled:document.getElementById("appSettingsSubagentTracking").checked,subagentActiveTabOnly:document.getElementById("appSettingsSubagentActiveTabOnly").checked,imageWatcherEnabled:document.getElementById("appSettingsImageWatcherEnabled").checked,promptCacheKeepWarm:document.getElementById("appSettingsPromptCacheKeepWarm").checked,promptCacheKeepWarmMaxHours:Math.min(24,Math.max(.5,parseFloat(document.getElementById("appSettingsPromptCacheKeepWarmMaxHours").value)||2)),tunnelEnabled:document.getElementById("appSettingsTunnelEnabled").checked,localEchoEnabled:document.getElementById("appSettingsLocalEcho").checked,autoCopySelection:document.getElementById("appSettingsAutoCopySelection").checked,copyStripMargin:document.getElementById("appSettingsCopyStripMargin").checked,terminalFontFamily:document.getElementById("appSettingsTerminalFont").value.trim(),terminalFontWeight:this.readTerminalFontWeight(document.getElementById("appSettingsTerminalFontWeight")),terminalFontWeightBold:this.readTerminalFontWeight(document.getElementById("appSettingsTerminalFontWeightBold")),terminalWheelLocalScrollback:document.getElementById("appSettingsTerminalWheelLocal").checked,cjkInputEnabled:document.getElementById("appSettingsCjkInput").checked,webglRendererEnabled:document.getElementById("appSettingsWebglRenderer").checked,extendedKeyboardBar:document.getElementById("appSettingsExtendedKeyboardBar").checked,tabTwoRows:document.getElementById("appSettingsTabTwoRows").checked,showTabCliLogos:document.getElementById("appSettingsShowTabCliLogos").checked,tabOrientation:document.getElementById("appSettingsTabOrientation").value,tabRailWidth:this.readTabRailWidthSetting?.()??256,tabRailDetail:document.getElementById("appSettingsTabRailDetail").value,tabRailSort:document.getElementById("appSettingsTabRailSort").value,tabArrangement:document.getElementById("appSettingsTabArrangement").value,tabStateOrder:document.getElementById("appSettingsTabStateOrder").value,showTabDetachButton:document.getElementById("appSettingsShowTabDetachButton").checked,tileDetachEnabled:document.getElementById("appSettingsTileDetach").checked,sessionListLayout:document.getElementById("appSettingsSessionListLayout").value,sessionSidebarFontSize:this.resolveSessionSidebarFontSize(document.getElementById("appSettingsSessionSidebarFontSize").value),skin:document.getElementById("appSettingsSkin").value,claudeMode:document.getElementById("appSettingsClaudeMode").value,allowedTools:document.getElementById("appSettingsAllowedTools").value.trim(),codexModel:document.getElementById("appSettingsCodexModel").value.trim(),codexReasoningEffort:document.getElementById("appSettingsCodexReasoningEffort").value,codexDangerouslyBypassApprovals:document.getElementById("appSettingsCodexDangerouslyBypassApprovals").checked,codexAnimationsEnabled:document.getElementById("appSettingsCodexAnimations").checked,agentTeamsEnabled:document.getElementById("appSettingsAgentTeams").checked,agentSkillEnabled:document.getElementById("appSettingsAgentSkill").checked,workspaceHooksEnabled:document.getElementById("appSettingsWorkspaceHooks").checked,pinCliSessionName:document.getElementById("appSettingsPinCliSessionName").checked,claudeVoiceEnabled:document.getElementById("appSettingsClaudeVoice").checked,claudeModel:document.getElementById("appSettingsClaudeModel").value,opusContext1mEnabled:document.getElementById("appSettingsOpusContext1m").checked,remoteAutoReconnect:document.getElementById("appSettingsRemoteAutoReconnect").checked,thinkingEffort:document.getElementById("appSettingsThinkingEffort").value,claudeAdvisorModel:document.getElementById("appSettingsClaudeAdvisor").value,nice:{enabled:document.getElementById("appSettingsNiceEnabled").checked,niceValue:parseInt(document.getElementById("appSettingsNiceValue").value)||10}};if(this._readSettingsFormOnce===!0)return this._readSettingsFormOnce=!1,o;if(!/^[A-Za-z0-9._\/-]*$/.test(o.codexModel)){this.showToast('Default Codex model may only contain letters, digits, ".", "_", "-" and "/"',"error"),document.getElementById("appSettingsCodexModel")?.focus();return}t.showTokenCount!==void 0&&(o.showTokenCount=t.showTokenCount),t.showCost!==void 0&&(o.showCost=t.showCost),t.shortcutOverrides!==void 0&&(o.shortcutOverrides=t.shortcutOverrides);const i=this._settingsReadOnly(),a=i&&this._keepServerSyncedSettings(o,t);if(this.saveAppSettingsToStorage(o),this._updateLocalEchoState(),this.applyTerminalFontFamily?.(o.terminalFontFamily),this.applyTerminalFontWeights?.(o),!s&&o.webglRendererEnabled)try{localStorage.removeItem("codeman-webgl-disabled")}catch{}const l={provider:document.getElementById("voiceProvider").value,apiKey:document.getElementById("voiceDeepgramKey").value.trim(),language:document.getElementById("voiceLanguage").value,keyterms:document.getElementById("voiceKeyterms").value.trim(),insertMode:document.getElementById("voiceInsertMode").value};VoiceInput._saveDeepgramConfig(l);const d={enabled:document.getElementById("appSettingsNotifEnabled").checked,browserNotifications:document.getElementById("appSettingsNotifBrowser").checked,audioAlerts:document.getElementById("appSettingsNotifAudio").checked,stuckThresholdMs:(parseInt(document.getElementById("appSettingsNotifStuckMins").value)||10)*6e4,toastDurationMs:(parseInt(document.getElementById("appSettingsNotifToastSecs").value)||3)*1e3,browserAutoCloseMs:(parseInt(document.getElementById("appSettingsNotifBrowserSecs").value)||8)*1e3,muteCritical:!document.getElementById("appSettingsNotifCritical").checked,muteWarning:!document.getElementById("appSettingsNotifWarning").checked,muteInfo:!document.getElementById("appSettingsNotifInfo").checked,eventTypes:{permission_prompt:{enabled:document.getElementById("eventPermissionEnabled").checked,browser:document.getElementById("eventPermissionBrowser").checked,push:document.getElementById("eventPermissionPush").checked,audio:document.getElementById("eventPermissionAudio").checked},elicitation_dialog:{enabled:document.getElementById("eventQuestionEnabled").checked,browser:document.getElementById("eventQuestionBrowser").checked,push:document.getElementById("eventQuestionPush").checked,audio:document.getElementById("eventQuestionAudio").checked},idle_prompt:{enabled:document.getElementById("eventIdleEnabled").checked,browser:document.getElementById("eventIdleBrowser").checked,push:document.getElementById("eventIdlePush").checked,audio:document.getElementById("eventIdleAudio").checked},stop:{enabled:document.getElementById("eventStopEnabled").checked,browser:document.getElementById("eventStopBrowser").checked,push:document.getElementById("eventStopPush").checked,audio:document.getElementById("eventStopAudio").checked},session_error:{enabled:!0,browser:this.notificationManager?.preferences?.eventTypes?.session_error?.browser??!0,push:this.notificationManager?.preferences?.eventTypes?.session_error?.push??!1,audio:!1},respawn_cycle:{enabled:document.getElementById("eventRespawnEnabled").checked,browser:document.getElementById("eventRespawnBrowser").checked,push:document.getElementById("eventRespawnPush").checked,audio:document.getElementById("eventRespawnAudio").checked},token_milestone:{enabled:!0,browser:!1,push:!1,audio:!1},ralph_complete:{enabled:document.getElementById("eventRalphEnabled").checked,browser:document.getElementById("eventRalphBrowser").checked,push:document.getElementById("eventRalphPush").checked,audio:document.getElementById("eventRalphAudio").checked},subagent_spawn:{enabled:document.getElementById("eventSubagentEnabled").checked,browser:document.getElementById("eventSubagentBrowser").checked,push:document.getElementById("eventSubagentPush").checked,audio:document.getElementById("eventSubagentAudio").checked},subagent_complete:{enabled:document.getElementById("eventSubagentEnabled").checked,browser:document.getElementById("eventSubagentBrowser").checked,push:document.getElementById("eventSubagentPush").checked,audio:document.getElementById("eventSubagentAudio").checked}},_version:5};this.notificationManager&&(this.notificationManager.preferences=this.notificationManager.normalizePreferences(d),this.notificationManager.savePreferences()),this._syncPushPreferences(),this.applyHeaderVisibilitySettings(),this.applySkin(),this.applyLocalization(),this.applySessionListLayout(),this.applyTabOrientation({settleRailWidth:!0}),this.applyLineageLineSettings?.(),this._updateTokensImmediate(),this.applyMonitorVisibility(),this.renderApprovals?.(),this.renderProjectInsightsPanel(),this.updateSubagentWindowVisibility(),this._updateCjkInputState(),this.activeSessionId||this.showWelcome(),KeyboardAccessoryBar.setMode(o.extendedKeyboardBar?"extended":"simple");const r=this.planUsageCollectionFlip(t,o.showPlanUsageLimits),{localEchoEnabled:c,cjkInputEnabled:p,extendedKeyboardBar:u,skin:m,language:f,showPlanUsageLimits:h,showAttachmentsButton:g,showFileViewerButton:y,showSplitButton:S,showTileGridButton:b,webglRendererEnabled:E,terminalWheelLocalScrollback:w,autoCopySelection:v,copyStripMargin:B,terminalFontFamily:k,terminalFontWeight:I,terminalFontWeightBold:M,showSessionButton:F,showAwayDigestButton:L,showCronButton:H,showGitStatus:A,gitStatusTree:D,gitStatusMaxRepos:P,gitStatusTimeoutSeconds:O,showTabDetachButton:R,tileDetachEnabled:x,mobileOverviewEnabled:W,sessionLineageLines:$,shortcutOverrides:V,...j}=o;let C="",U=!1;try{const T=i?null:await this._apiPut("/api/settings",{...j,...r!==void 0?{showPlanUsageLimits:r}:{},notificationPreferences:d,voiceSettings:l}),_=!i&&await this._noteSettingsWriteRefusal(T);if(_&&(this._keepServerSyncedSettings(o,t),this.saveAppSettingsToStorage(o)),!_&&o.tunnelEnabled&&await this._handleTunnelEnableRefusal(T)){o.tunnelEnabled=!1,this.saveAppSettingsToStorage(o);const N=document.getElementById("appSettingsTunnelEnabled");N&&(N.checked=!1),e||this.closeAppSettings();return}U=!!T?.ok;const K=await this.saveModelConfigFromSettings()===!0;C=this._webhookPending()?await this.saveWebhook():"",C?this.showToast(`Settings saved, but not the webhook: ${C}`,"warning"):a||K||_?this.showToast("Saved on this device. Server-wide settings can only be changed by an admin.","warning"):this.showToast(e?"Settings applied":"Settings saved","success"),o.tunnelEnabled&&!i&&!_&&this.showToast("Tunnel starting \u2014 QR code will appear when ready...","info")}catch{this.showToast("Settings saved locally","warning")}e&&U&&this._refreshSettingsAfterApply(o),C?document.getElementById("webhookGroup")?.scrollIntoView({block:"center"}):e||this.closeAppSettings(),VoiceInput.refreshClaudeStatus(),(o.gestureControlEnabled??!1)!==n&&(this.showToast(o.gestureControlEnabled?"Enabling gesture control \u2014 reloading\u2026":"Disabling gesture control \u2014 reloading\u2026","info"),setTimeout(()=>location.reload(),400))},_settingsReadOnly(){if(this._settingsWriteForbidden===!0)return!0;const e=typeof window<"u"&&window.__codemanUser||{};return!!(e.multiUser&&e.role!=="admin")},async _noteSettingsWriteRefusal(e){if(!e||e.status!==403)return!1;let t=null;try{t=await(typeof e.clone=="function"?e.clone():e).json()}catch{return!1}return t?.errorCode!=="FORBIDDEN"?!1:(this._settingsWriteForbidden=!0,!0)},_ownSettingsKey(){return`codeman:own-settings:${(typeof window<"u"&&window.__codemanUser||{}).username||""}`},_readOwnSettings(){try{const e=JSON.parse(localStorage.getItem(this._ownSettingsKey())||"{}");return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}catch{return{}}},_rememberOwnSetting(e,t){try{const n=this._readOwnSettings();n[e]=t,localStorage.setItem(this._ownSettingsKey(),JSON.stringify(n))}catch{}},_applyOwnSettings(){if(!this._settingsReadOnly())return;const e=this._readOwnSettings();if(Array.isArray(e.respawnPresets)){this._serverRespawnPresets=e.respawnPresets;try{localStorage.setItem("codeman-respawn-presets",JSON.stringify(e.respawnPresets))}catch{}}if(typeof e.runMode=="string"&&e.runMode){this.runMode=e.runMode;try{localStorage.setItem("codeman_runMode",e.runMode)}catch{}this._applyRunMode?.()}},_captureSettingsFormBaseline(){if(this._settingsFormBaseline=null,!this._settingsReadOnly())return;this._readSettingsFormOnce=!0;let e;try{e=this.saveAppSettings()}finally{this._readSettingsFormOnce=!1}Promise.resolve(e).then(t=>{this._settingsFormBaseline=t&&typeof t=="object"?t:null}).catch(()=>{})},_keepServerSyncedSettings(e,t){const n=this._displaySettingKeySet(),s=this._settingsFormBaseline||t||{};let o=!1;for(const i of Object.keys(e))n.has(i)||i==="shortcutOverrides"||(i in s&&JSON.stringify(e[i])!==JSON.stringify(s[i])&&(o=!0),t&&i in t?e[i]=t[i]:delete e[i]);return o},_refreshSettingsAfterApply(e){this._mcpSyncSavedOn=e.mcpSyncEnabled===!0;const t=this.$("mcpSyncResult");this._mcpSyncSavedOn&&t&&t.dataset?.hint==="save-first"&&(t.style.display="none",t.innerHTML=""),this.applyMcpSyncVisibility(),this.applyCustomModelEndpointsVisibility(),this.applyCliManagementVisibility(),this._applyDoctorAdminGate()},async loadModelConfigForSettings(){try{const t=await(await fetch("/api/execution/model-config")).json();if(t.success&&t.data){const n=t.data,s=document.getElementById("appSettingsDefaultModel");s&&(s.value=n.defaultModel||"");const o=document.getElementById("appSettingsShowModelRecommendations");o&&(o.checked=n.showRecommendations??!0);const i=n.agentTypeOverrides||{},a=document.getElementById("appSettingsModelExplore"),l=document.getElementById("appSettingsModelImplement"),d=document.getElementById("appSettingsModelTest"),r=document.getElementById("appSettingsModelReview");a&&(a.value=i.explore||""),l&&(l.value=i.implement||""),d&&(d.value=i.test||""),r&&(r.value=i.review||"")}}catch(e){console.warn("Failed to load model config:",e)}this._modelConfigBaseline=JSON.stringify(this._modelConfigFromSettingsForm())},_modelConfigFromSettingsForm(){const e=document.getElementById("appSettingsDefaultModel"),t=document.getElementById("appSettingsShowModelRecommendations"),n=document.getElementById("appSettingsModelExplore"),s=document.getElementById("appSettingsModelImplement"),o=document.getElementById("appSettingsModelTest"),i=document.getElementById("appSettingsModelReview"),a={};return n?.value&&(a.explore=n.value),s?.value&&(a.implement=s.value),o?.value&&(a.test=o.value),i?.value&&(a.review=i.value),{defaultModel:e?.value||"",showRecommendations:t?.checked??!0,agentTypeOverrides:a}},async saveModelConfigFromSettings(){const e=this._modelConfigFromSettingsForm();if(this._settingsReadOnly()){const t=this._modelConfigBaseline;return typeof t=="string"&&JSON.stringify(e)!==t}try{await fetch("/api/execution/model-config",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}catch(t){console.warn("Failed to save model config:",t)}},applyCustomModelEndpointsVisibility(){const e=document.getElementById("appSettingsCustomModelEndpoints").checked,t=document.getElementById("customModelEndpointsBody");t&&(t.style.display=e?"":"none"),e?this.loadCustomModelEndpointsForSettings():this.closeCustomModelHostEditor(),this._applyCustomModelAdminGate()},_applyCustomModelAdminGate(){const e=document.getElementById("customModelHostAddBtn");if(!e)return;const t=window.__codemanUser||{},n=t.multiUser&&t.role!=="admin";e.style.display=n?"none":""},async loadCustomModelEndpointsForSettings(){const e=await this._apiJson("/api/model-endpoints");this._customModelHosts=Array.isArray(e)?e:[],this.renderCustomModelHostsList()},renderCustomModelHostsList(){const e=document.getElementById("customModelHostsList");if(!e)return;const t=this._customModelHosts||[];if(t.length===0){e.innerHTML='<p class="set-group-hint">No endpoints yet. Add one below to point a harness at a local or cloud OpenAI-compatible server.</p>';return}e.innerHTML=t.map(n=>{const s=(n.models||[]).length,o=s===0?"No models discovered yet":`${s} model${s===1?"":"s"}${n.defaultModelId?` \xB7 default: ${escapeHtml(n.defaultModelId)}`:" \xB7 no default set"}`,i=escapeHtml(JSON.stringify(n.id));return`
72
+ </tr>`}).join("")}catch(s){console.error("Failed to load lifecycle log:",s)}},_renderVoiceProviderStatus(){const e=document.getElementById("voiceProviderStatus");if(e){const o=VoiceInput.getActiveProviderName();e.textContent=o;const i=o.startsWith("Deepgram Nova")||o.startsWith("Claude (this");e.className="voice-provider-status"+(i?" active":"")}const t=document.getElementById("voiceClaudeStatus");if(!t)return;const n=VoiceInput._claudeStatus,s=n?n.available?`Ready${n.subscriptionType?` (${n.subscriptionType})`:""}`:n.reason==="expired"?"Login expired - run a Claude session to refresh":n.reason==="no-credentials"?"No Claude Code login on the server":n.reason==="malformed"?"Claude credentials unreadable":"Off - enable it above":"Checking...";t.textContent=s,t.className="voice-provider-status"+(n?.available?" active":"")},async applyAppSettings(){if(!this._applyInFlight){this._applyInFlight=!0,this._keepSettingsOpenOnce=!0;try{await this.saveAppSettings()}finally{this._applyInFlight=!1,this._keepSettingsOpenOnce=!1}}},async saveAppSettings(){const e=this._keepSettingsOpenOnce===!0;this._keepSettingsOpenOnce=!1;const t=this.loadAppSettingsFromStorage(),n=(t.gestureControlEnabled??!1)===!0,s=(t.webglRendererEnabled??!0)===!0,o={displayName:window.CodemanI18n?.normalizeDisplayName(document.getElementById("appSettingsDisplayName").value)||"Codeman",language:window.CodemanI18n?.normalizeLanguage(document.getElementById("appSettingsLanguage").value)||"en",defaultClaudeMdPath:document.getElementById("appSettingsClaudeMdPath").value.trim(),defaultWorkingDir:document.getElementById("appSettingsDefaultDir").value.trim(),ralphTrackerEnabled:document.getElementById("appSettingsRalphEnabled").checked,showFontControls:document.getElementById("appSettingsShowFontControls").checked,showSystemStats:document.getElementById("appSettingsShowSystemStats").checked,showGpuStats:document.getElementById("appSettingsShowGpuStats").checked,showCpuMhz:document.getElementById("appSettingsShowCpuMhz").checked,headerStatsStyle:document.getElementById("appSettingsHeaderStatsStyle").value,showLifecycleLog:document.getElementById("appSettingsShowLifecycleLog").checked,showResponseViewer:document.getElementById("appSettingsShowResponseViewer").checked,showFileViewerButton:document.getElementById("appSettingsShowFileViewerButton").checked,showAttachmentsButton:document.getElementById("appSettingsShowAttachmentsButton").checked,showMonitor:document.getElementById("appSettingsShowMonitor").checked,showProjectInsights:document.getElementById("appSettingsShowProjectInsights").checked,showFileBrowser:document.getElementById("appSettingsShowFileBrowser").checked,showSubagents:document.getElementById("appSettingsShowSubagents").checked,showUltracodeAgents:document.getElementById("appSettingsShowUltracodeAgents").checked,approvalsInboxEnabled:document.getElementById("appSettingsApprovalsInbox").checked,customModelEndpointsEnabled:document.getElementById("appSettingsCustomModelEndpoints").checked,cliManagementEnabled:document.getElementById("appSettingsCliManagement").checked,mcpSyncEnabled:document.getElementById("appSettingsMcpSync").checked,configBackupEnabled:document.getElementById("appSettingsConfigBackup").checked,configBackupDir:document.getElementById("appSettingsConfigBackupDir").value.trim(),...this._configBackupRetentionPayload(t),agentInboxPersistEnabled:document.getElementById("appSettingsAgentInboxPersist").checked,readMyMindEnabled:document.getElementById("appSettingsReadMyMind").checked,ultracodeFloatingWindows:document.getElementById("appSettingsUltracodeFloatingWindows").checked,showMultiMonitorButton:document.getElementById("appSettingsShowMultiMonitorButton").checked,showSplitButton:document.getElementById("appSettingsShowSplitButton").checked,showTileGridButton:document.getElementById("appSettingsShowTileGridButton").checked,showPlanUsageLimits:document.getElementById("appSettingsShowPlanUsageLimits").checked,showRedrawButton:document.getElementById("appSettingsShowRedrawButton").checked,mobileOverviewEnabled:document.getElementById("appSettingsMobileOverview").checked,sessionLineageLines:document.getElementById("appSettingsLineageLines").checked,autoNameSessions:document.getElementById("appSettingsAutoNameSessions").checked,spawnedTabsFollowParent:document.getElementById("appSettingsSpawnedTabsFollowParent").checked,showSessionButton:document.getElementById("appSettingsShowSessionButton").checked,showAwayDigestButton:document.getElementById("appSettingsShowAwayDigestButton").checked,showCronButton:document.getElementById("appSettingsShowCronButton").checked,showGitStatus:document.getElementById("appSettingsShowGitStatus").checked,gitStatusTree:document.getElementById("appSettingsGitStatusTree").checked,gitStatusMaxRepos:Math.min(50,Math.max(1,parseInt(document.getElementById("appSettingsGitStatusMaxRepos").value,10)||12)),gitStatusTimeoutSeconds:Math.min(120,Math.max(5,parseInt(document.getElementById("appSettingsGitStatusTimeout").value,10)||30)),gestureControlEnabled:document.getElementById("appSettingsGestureControl").checked,subagentTrackingEnabled:document.getElementById("appSettingsSubagentTracking").checked,subagentActiveTabOnly:document.getElementById("appSettingsSubagentActiveTabOnly").checked,imageWatcherEnabled:document.getElementById("appSettingsImageWatcherEnabled").checked,promptCacheKeepWarm:document.getElementById("appSettingsPromptCacheKeepWarm").checked,promptCacheKeepWarmMaxHours:Math.min(24,Math.max(.5,parseFloat(document.getElementById("appSettingsPromptCacheKeepWarmMaxHours").value)||2)),tunnelEnabled:document.getElementById("appSettingsTunnelEnabled").checked,localEchoEnabled:document.getElementById("appSettingsLocalEcho").checked,autoCopySelection:document.getElementById("appSettingsAutoCopySelection").checked,copyStripMargin:document.getElementById("appSettingsCopyStripMargin").checked,terminalFontFamily:document.getElementById("appSettingsTerminalFont").value.trim(),terminalFontWeight:this.readTerminalFontWeight(document.getElementById("appSettingsTerminalFontWeight")),terminalFontWeightBold:this.readTerminalFontWeight(document.getElementById("appSettingsTerminalFontWeightBold")),terminalWheelLocalScrollback:document.getElementById("appSettingsTerminalWheelLocal").checked,cjkInputEnabled:document.getElementById("appSettingsCjkInput").checked,webglRendererEnabled:document.getElementById("appSettingsWebglRenderer").checked,extendedKeyboardBar:document.getElementById("appSettingsExtendedKeyboardBar").checked,tabTwoRows:document.getElementById("appSettingsTabTwoRows").checked,showTabCliLogos:document.getElementById("appSettingsShowTabCliLogos").checked,tabOrientation:document.getElementById("appSettingsTabOrientation").value,tabRailWidth:this.readTabRailWidthSetting?.()??256,tabRailDetail:document.getElementById("appSettingsTabRailDetail").value,tabRailSort:document.getElementById("appSettingsTabRailSort").value,tabArrangement:document.getElementById("appSettingsTabArrangement").value,tabStateOrder:document.getElementById("appSettingsTabStateOrder").value,showTabDetachButton:document.getElementById("appSettingsShowTabDetachButton").checked,tileDetachEnabled:document.getElementById("appSettingsTileDetach").checked,sessionListLayout:document.getElementById("appSettingsSessionListLayout").value,sessionSidebarFontSize:this.resolveSessionSidebarFontSize(document.getElementById("appSettingsSessionSidebarFontSize").value),skin:document.getElementById("appSettingsSkin").value,claudeMode:document.getElementById("appSettingsClaudeMode").value,allowedTools:document.getElementById("appSettingsAllowedTools").value.trim(),codexModel:document.getElementById("appSettingsCodexModel").value.trim(),codexReasoningEffort:document.getElementById("appSettingsCodexReasoningEffort").value,codexDangerouslyBypassApprovals:document.getElementById("appSettingsCodexDangerouslyBypassApprovals").checked,codexAnimationsEnabled:document.getElementById("appSettingsCodexAnimations").checked,agentTeamsEnabled:document.getElementById("appSettingsAgentTeams").checked,agentSkillEnabled:document.getElementById("appSettingsAgentSkill").checked,workspaceHooksEnabled:document.getElementById("appSettingsWorkspaceHooks").checked,pinCliSessionName:document.getElementById("appSettingsPinCliSessionName").checked,claudeVoiceEnabled:document.getElementById("appSettingsClaudeVoice").checked,claudeModel:document.getElementById("appSettingsClaudeModel").value,opusContext1mEnabled:document.getElementById("appSettingsOpusContext1m").checked,remoteAutoReconnect:document.getElementById("appSettingsRemoteAutoReconnect").checked,thinkingEffort:document.getElementById("appSettingsThinkingEffort").value,claudeAdvisorModel:document.getElementById("appSettingsClaudeAdvisor").value,nice:{enabled:document.getElementById("appSettingsNiceEnabled").checked,niceValue:parseInt(document.getElementById("appSettingsNiceValue").value)||10}};if(this._readSettingsFormOnce===!0)return this._readSettingsFormOnce=!1,o;if(!/^[A-Za-z0-9._\/-]*$/.test(o.codexModel)){this.showToast('Default Codex model may only contain letters, digits, ".", "_", "-" and "/"',"error"),document.getElementById("appSettingsCodexModel")?.focus();return}t.showTokenCount!==void 0&&(o.showTokenCount=t.showTokenCount),t.showCost!==void 0&&(o.showCost=t.showCost),t.shortcutOverrides!==void 0&&(o.shortcutOverrides=t.shortcutOverrides);const i=this._settingsReadOnly(),a=i&&this._keepServerSyncedSettings(o,t);if(this.saveAppSettingsToStorage(o),this._updateLocalEchoState(),this.applyTerminalFontFamily?.(o.terminalFontFamily),this.applyTerminalFontWeights?.(o),!s&&o.webglRendererEnabled)try{localStorage.removeItem("codeman-webgl-disabled")}catch{}const l={provider:document.getElementById("voiceProvider").value,apiKey:document.getElementById("voiceDeepgramKey").value.trim(),language:document.getElementById("voiceLanguage").value,keyterms:document.getElementById("voiceKeyterms").value.trim(),insertMode:document.getElementById("voiceInsertMode").value};VoiceInput._saveDeepgramConfig(l);const d={enabled:document.getElementById("appSettingsNotifEnabled").checked,browserNotifications:document.getElementById("appSettingsNotifBrowser").checked,audioAlerts:document.getElementById("appSettingsNotifAudio").checked,stuckThresholdMs:(parseInt(document.getElementById("appSettingsNotifStuckMins").value)||10)*6e4,toastDurationMs:(parseInt(document.getElementById("appSettingsNotifToastSecs").value)||3)*1e3,browserAutoCloseMs:(parseInt(document.getElementById("appSettingsNotifBrowserSecs").value)||8)*1e3,muteCritical:!document.getElementById("appSettingsNotifCritical").checked,muteWarning:!document.getElementById("appSettingsNotifWarning").checked,muteInfo:!document.getElementById("appSettingsNotifInfo").checked,eventTypes:{permission_prompt:{enabled:document.getElementById("eventPermissionEnabled").checked,browser:document.getElementById("eventPermissionBrowser").checked,push:document.getElementById("eventPermissionPush").checked,audio:document.getElementById("eventPermissionAudio").checked},elicitation_dialog:{enabled:document.getElementById("eventQuestionEnabled").checked,browser:document.getElementById("eventQuestionBrowser").checked,push:document.getElementById("eventQuestionPush").checked,audio:document.getElementById("eventQuestionAudio").checked},idle_prompt:{enabled:document.getElementById("eventIdleEnabled").checked,browser:document.getElementById("eventIdleBrowser").checked,push:document.getElementById("eventIdlePush").checked,audio:document.getElementById("eventIdleAudio").checked},stop:{enabled:document.getElementById("eventStopEnabled").checked,browser:document.getElementById("eventStopBrowser").checked,push:document.getElementById("eventStopPush").checked,audio:document.getElementById("eventStopAudio").checked},session_error:{enabled:!0,browser:this.notificationManager?.preferences?.eventTypes?.session_error?.browser??!0,push:this.notificationManager?.preferences?.eventTypes?.session_error?.push??!1,audio:!1},respawn_cycle:{enabled:document.getElementById("eventRespawnEnabled").checked,browser:document.getElementById("eventRespawnBrowser").checked,push:document.getElementById("eventRespawnPush").checked,audio:document.getElementById("eventRespawnAudio").checked},token_milestone:{enabled:!0,browser:!1,push:!1,audio:!1},ralph_complete:{enabled:document.getElementById("eventRalphEnabled").checked,browser:document.getElementById("eventRalphBrowser").checked,push:document.getElementById("eventRalphPush").checked,audio:document.getElementById("eventRalphAudio").checked},subagent_spawn:{enabled:document.getElementById("eventSubagentEnabled").checked,browser:document.getElementById("eventSubagentBrowser").checked,push:document.getElementById("eventSubagentPush").checked,audio:document.getElementById("eventSubagentAudio").checked},subagent_complete:{enabled:document.getElementById("eventSubagentEnabled").checked,browser:document.getElementById("eventSubagentBrowser").checked,push:document.getElementById("eventSubagentPush").checked,audio:document.getElementById("eventSubagentAudio").checked}},_version:5};this.notificationManager&&(this.notificationManager.preferences=this.notificationManager.normalizePreferences(d),this.notificationManager.savePreferences()),this._syncPushPreferences(),this.applyHeaderVisibilitySettings(),this.applySkin(),this.applyLocalization(),this.applySessionListLayout(),this.applyTabOrientation({settleRailWidth:!0}),this.applyLineageLineSettings?.(),this._updateTokensImmediate(),this.applyMonitorVisibility(),this.renderApprovals?.(),this.renderProjectInsightsPanel(),this.updateSubagentWindowVisibility(),this._updateCjkInputState(),this.activeSessionId||this.showWelcome(),KeyboardAccessoryBar.setMode(o.extendedKeyboardBar?"extended":"simple");const r=this.planUsageCollectionFlip(t,o.showPlanUsageLimits),{localEchoEnabled:c,cjkInputEnabled:p,extendedKeyboardBar:u,skin:m,language:f,showPlanUsageLimits:h,showAttachmentsButton:g,showFileViewerButton:y,showSplitButton:S,showTileGridButton:b,webglRendererEnabled:E,terminalWheelLocalScrollback:w,autoCopySelection:v,copyStripMargin:B,terminalFontFamily:k,terminalFontWeight:I,terminalFontWeightBold:M,showSessionButton:F,showAwayDigestButton:A,showCronButton:H,showGitStatus:L,showGpuStats:D,showCpuMhz:P,gitStatusTree:O,gitStatusMaxRepos:R,gitStatusTimeoutSeconds:x,showTabDetachButton:W,tileDetachEnabled:$,mobileOverviewEnabled:V,sessionLineageLines:q,shortcutOverrides:Q,...j}=o;let C="",U=!1;try{const T=i?null:await this._apiPut("/api/settings",{...j,...r!==void 0?{showPlanUsageLimits:r}:{},notificationPreferences:d,voiceSettings:l}),_=!i&&await this._noteSettingsWriteRefusal(T);if(_&&(this._keepServerSyncedSettings(o,t),this.saveAppSettingsToStorage(o)),!_&&o.tunnelEnabled&&await this._handleTunnelEnableRefusal(T)){o.tunnelEnabled=!1,this.saveAppSettingsToStorage(o);const N=document.getElementById("appSettingsTunnelEnabled");N&&(N.checked=!1),e||this.closeAppSettings();return}U=!!T?.ok;const K=await this.saveModelConfigFromSettings()===!0;C=this._webhookPending()?await this.saveWebhook():"",C?this.showToast(`Settings saved, but not the webhook: ${C}`,"warning"):a||K||_?this.showToast("Saved on this device. Server-wide settings can only be changed by an admin.","warning"):this.showToast(e?"Settings applied":"Settings saved","success"),o.tunnelEnabled&&!i&&!_&&this.showToast("Tunnel starting \u2014 QR code will appear when ready...","info")}catch{this.showToast("Settings saved locally","warning")}e&&U&&this._refreshSettingsAfterApply(o),C?document.getElementById("webhookGroup")?.scrollIntoView({block:"center"}):e||this.closeAppSettings(),VoiceInput.refreshClaudeStatus(),(o.gestureControlEnabled??!1)!==n&&(this.showToast(o.gestureControlEnabled?"Enabling gesture control \u2014 reloading\u2026":"Disabling gesture control \u2014 reloading\u2026","info"),setTimeout(()=>location.reload(),400))},_settingsReadOnly(){if(this._settingsWriteForbidden===!0)return!0;const e=typeof window<"u"&&window.__codemanUser||{};return!!(e.multiUser&&e.role!=="admin")},async _noteSettingsWriteRefusal(e){if(!e||e.status!==403)return!1;let t=null;try{t=await(typeof e.clone=="function"?e.clone():e).json()}catch{return!1}return t?.errorCode!=="FORBIDDEN"?!1:(this._settingsWriteForbidden=!0,!0)},_ownSettingsKey(){return`codeman:own-settings:${(typeof window<"u"&&window.__codemanUser||{}).username||""}`},_readOwnSettings(){try{const e=JSON.parse(localStorage.getItem(this._ownSettingsKey())||"{}");return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}catch{return{}}},_rememberOwnSetting(e,t){try{const n=this._readOwnSettings();n[e]=t,localStorage.setItem(this._ownSettingsKey(),JSON.stringify(n))}catch{}},_applyOwnSettings(){if(!this._settingsReadOnly())return;const e=this._readOwnSettings();if(Array.isArray(e.respawnPresets)){this._serverRespawnPresets=e.respawnPresets;try{localStorage.setItem("codeman-respawn-presets",JSON.stringify(e.respawnPresets))}catch{}}if(typeof e.runMode=="string"&&e.runMode){this.runMode=e.runMode;try{localStorage.setItem("codeman_runMode",e.runMode)}catch{}this._applyRunMode?.()}},_captureSettingsFormBaseline(){if(this._settingsFormBaseline=null,!this._settingsReadOnly())return;this._readSettingsFormOnce=!0;let e;try{e=this.saveAppSettings()}finally{this._readSettingsFormOnce=!1}Promise.resolve(e).then(t=>{this._settingsFormBaseline=t&&typeof t=="object"?t:null}).catch(()=>{})},_keepServerSyncedSettings(e,t){const n=this._displaySettingKeySet(),s=this._settingsFormBaseline||t||{};let o=!1;for(const i of Object.keys(e))n.has(i)||i==="shortcutOverrides"||(i in s&&JSON.stringify(e[i])!==JSON.stringify(s[i])&&(o=!0),t&&i in t?e[i]=t[i]:delete e[i]);return o},_refreshSettingsAfterApply(e){this._mcpSyncSavedOn=e.mcpSyncEnabled===!0;const t=this.$("mcpSyncResult");this._mcpSyncSavedOn&&t&&t.dataset?.hint==="save-first"&&(t.style.display="none",t.innerHTML=""),this.applyMcpSyncVisibility(),this.applyCustomModelEndpointsVisibility(),this.applyCliManagementVisibility(),this._applyDoctorAdminGate()},async loadModelConfigForSettings(){try{const t=await(await fetch("/api/execution/model-config")).json();if(t.success&&t.data){const n=t.data,s=document.getElementById("appSettingsDefaultModel");s&&(s.value=n.defaultModel||"");const o=document.getElementById("appSettingsShowModelRecommendations");o&&(o.checked=n.showRecommendations??!0);const i=n.agentTypeOverrides||{},a=document.getElementById("appSettingsModelExplore"),l=document.getElementById("appSettingsModelImplement"),d=document.getElementById("appSettingsModelTest"),r=document.getElementById("appSettingsModelReview");a&&(a.value=i.explore||""),l&&(l.value=i.implement||""),d&&(d.value=i.test||""),r&&(r.value=i.review||"")}}catch(e){console.warn("Failed to load model config:",e)}this._modelConfigBaseline=JSON.stringify(this._modelConfigFromSettingsForm())},_modelConfigFromSettingsForm(){const e=document.getElementById("appSettingsDefaultModel"),t=document.getElementById("appSettingsShowModelRecommendations"),n=document.getElementById("appSettingsModelExplore"),s=document.getElementById("appSettingsModelImplement"),o=document.getElementById("appSettingsModelTest"),i=document.getElementById("appSettingsModelReview"),a={};return n?.value&&(a.explore=n.value),s?.value&&(a.implement=s.value),o?.value&&(a.test=o.value),i?.value&&(a.review=i.value),{defaultModel:e?.value||"",showRecommendations:t?.checked??!0,agentTypeOverrides:a}},async saveModelConfigFromSettings(){const e=this._modelConfigFromSettingsForm();if(this._settingsReadOnly()){const t=this._modelConfigBaseline;return typeof t=="string"&&JSON.stringify(e)!==t}try{await fetch("/api/execution/model-config",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}catch(t){console.warn("Failed to save model config:",t)}},applyCustomModelEndpointsVisibility(){const e=document.getElementById("appSettingsCustomModelEndpoints").checked,t=document.getElementById("customModelEndpointsBody");t&&(t.style.display=e?"":"none"),e?this.loadCustomModelEndpointsForSettings():this.closeCustomModelHostEditor(),this._applyCustomModelAdminGate()},_applyCustomModelAdminGate(){const e=document.getElementById("customModelHostAddBtn");if(!e)return;const t=window.__codemanUser||{},n=t.multiUser&&t.role!=="admin";e.style.display=n?"none":""},async loadCustomModelEndpointsForSettings(){const e=await this._apiJson("/api/model-endpoints");this._customModelHosts=Array.isArray(e)?e:[],this.renderCustomModelHostsList()},renderCustomModelHostsList(){const e=document.getElementById("customModelHostsList");if(!e)return;const t=this._customModelHosts||[];if(t.length===0){e.innerHTML='<p class="set-group-hint">No endpoints yet. Add one below to point a harness at a local or cloud OpenAI-compatible server.</p>';return}e.innerHTML=t.map(n=>{const s=(n.models||[]).length,o=s===0?"No models discovered yet":`${s} model${s===1?"":"s"}${n.defaultModelId?` \xB7 default: ${escapeHtml(n.defaultModelId)}`:" \xB7 no default set"}`,i=escapeHtml(JSON.stringify(n.id));return`
73
73
  <div class="set-row" data-endpoint-id="${escapeHtml(n.id)}">
74
74
  <div class="set-row-text">
75
75
  <span class="set-row-label">${escapeHtml(n.label)}</span>
@@ -97,7 +97,7 @@ Enable the unauthenticated public tunnel anyway?`))return this._dismissTunnelCon
97
97
  </div>
98
98
  </div>`}).join("")},async toggleCliEnabled(e,t){const n=t.checked,s=await this._api(`/api/clis/${encodeURIComponent(e)}`,{method:"PUT",body:{enabled:n}});if(!s||!s.ok){t.checked=!n;let o="";try{o=(await s?.json())?.error||""}catch{}this.showToast(`Failed to ${n?"enable":"disable"} "${e}"${o?`: ${o}`:""}`,"error");return}await this.loadCliListForSettings()},async installCliEntry(e){const t=(this._cliList||[]).find(a=>a.id===e),n=t?.label||e,s=t?.installCommand,o=s?`Install ${n}? This runs the following on the Codeman server:
99
99
 
100
- ${s}`:`Install ${n}? This runs its official install command on the Codeman server.`;if(!confirm(o))return;const i=document.getElementById(`cliInstallBtn-${e}`);i&&(i.disabled=!0,i.textContent="Installing\u2026");try{const a=await this._api(`/api/clis/${encodeURIComponent(e)}/install`,{method:"POST"});if(!a||!a.ok){let l="";try{l=(await a?.json())?.error||""}catch{}this.showToast(`Installing "${e}" failed${l?`: ${l}`:""}`,"error");return}this.showToast(`Installed "${e}"`,"success")}finally{await this.loadCliListForSettings()}},openCliCustomForm(e){const t=document.getElementById("cliCustomForm"),n=document.getElementById("cliCustomFormError");if(!t)return;const s=e?(this._cliList||[]).find(o=>o.id===e):null;this._editingCliCustomId=s?s.id:null,document.getElementById("cliCustomId").value=s?s.id:"",document.getElementById("cliCustomId").disabled=!!s,document.getElementById("cliCustomLabel").value=s?s.label:"",document.getElementById("cliCustomBadge").value=s?s.shortBadge:"",document.getElementById("cliCustomBinary").value="",document.getElementById("cliCustomArgv").value="",document.getElementById("cliCustomSubmit").textContent=s?"Save":"Create",n&&(n.style.display="none"),t.style.display=""},closeCliCustomForm(){const e=document.getElementById("cliCustomForm");e&&(e.style.display="none"),this._editingCliCustomId=null},async submitCliCustomForm(e){e.preventDefault();const t=document.getElementById("cliCustomFormError"),n=u=>{t&&(t.textContent=u,t.style.display="")},s=document.getElementById("cliCustomId").value.trim(),o=document.getElementById("cliCustomLabel").value.trim(),i=document.getElementById("cliCustomBadge").value.trim(),a=document.getElementById("cliCustomBinary").value.trim().split(/\s+/).filter(Boolean),l=document.getElementById("cliCustomArgv").value.trim().split(/\s+/).filter(Boolean);if(!s||!o||!i||a.length===0||l.length===0){n("All fields are required.");return}const d=this._editingCliCustomId,r=d?`/api/clis/custom/${encodeURIComponent(d)}`:"/api/clis",c=d?"PUT":"POST",p=await this._api(r,{method:c,body:{id:s,label:o,shortBadge:i,binaries:a,argv:l}});if(!p||!p.ok){let u="Request failed";try{u=(await p?.json())?.error||u}catch{}n(u);return}this.closeCliCustomForm(),await this.loadCliListForSettings()},async deleteCliCustom(e){const t=(this._cliList||[]).find(s=>s.id===e);if(!confirm(`Delete custom CLI "${t?.label||e}"? This cannot be undone.`))return;const n=await this._api(`/api/clis/${encodeURIComponent(e)}`,{method:"DELETE"});if(!n||!n.ok){let s="";try{s=(await n?.json())?.error||""}catch{}this.showToast(`Failed to delete "${e}"${s?`: ${s}`:""}`,"error");return}await this.loadCliListForSettings()},isRalphTrackerEnabledByDefault(){return this.loadAppSettingsFromStorage().ralphTrackerEnabled??!1},getSettingsStorageKey(){return MobileDetection.isHandheldDevice?.()??MobileDetection.getDeviceType()==="mobile"?"codeman-app-settings-mobile":"codeman-app-settings"},getDefaultSettings(){return MobileDetection.isHandheldDevice?.()??MobileDetection.getDeviceType()==="mobile"?{showFontControls:!1,showSystemStats:!1,showTokenCount:!1,showCost:!1,showMonitor:!1,showProjectInsights:!1,showFileBrowser:!1,showSubagents:!1,showUltracodeAgents:!1,ultracodeFloatingWindows:!1,showMultiMonitorButton:!1,showSplitButton:!1,showTileGridButton:!1,showPlanUsageLimits:!1,showAttachmentsButton:!1,showFileViewerButton:!1,showRedrawButton:!1,showSessionButton:!1,showAwayDigestButton:!1,showCronButton:!1,mobileOverviewEnabled:!0,remoteAutoReconnect:!0,gestureControlEnabled:!1,subagentTrackingEnabled:!0,subagentActiveTabOnly:!0,imageWatcherEnabled:!1,ralphTrackerEnabled:!1,tabTwoRows:!1,showTabCliLogos:!0,tabOrientation:"horizontal",tabRailWidth:256,tabRailDetail:"rich",tabRailSort:"activity",tabArrangement:"classic",tabStateOrder:"urgent-first",sessionListLayout:"header",sessionSidebarFontSize:12,cjkInputEnabled:!1,terminalWheelLocalScrollback:!1,webglRendererEnabled:!1,skin:"daylight-blue"}:typeof window<"u"&&window.matchMedia?.("(pointer: coarse)")?.matches===!0?{showTileGridButton:!1}:{}},loadAppSettingsFromStorage(){if(this._cachedAppSettings)return this._cachedAppSettings;try{const t=this.getSettingsStorageKey(),n=localStorage.getItem(t);if(n)return this._cachedAppSettings=JSON.parse(n),this._cachedAppSettings}catch(t){console.error("Failed to load app settings:",t)}const e={...this.getDefaultSettings()};return delete e.showTileGridButton,this._cachedAppSettings=e,this._cachedAppSettings},saveAppSettingsToStorage(e){this._cachedAppSettings=e;try{const t=this.getSettingsStorageKey();localStorage.setItem(t,JSON.stringify(e))}catch(t){console.error("Failed to save app settings:",t)}},applySkin(){const e=this.loadAppSettingsFromStorage(),t=this.getDefaultSettings(),n=e.skin??t.skin??"daylight-blue";document.documentElement.setAttribute("data-skin",n),window.__codemanSkin=n;const s=getComputedStyle(document.documentElement).getPropertyValue("--bg-dark").trim();s&&document.querySelector('meta[name="theme-color"]')?.setAttribute("content",s);try{localStorage.setItem("codeman:skin",n)}catch{}typeof this.applyTerminalSkin=="function"&&this.applyTerminalSkin(n)},applyLocalization(){const e=this.loadAppSettingsFromStorage();window.CodemanI18n?.configure({language:e.language,displayName:e.displayName})&&this.notificationManager&&(this.notificationManager.originalTitle=document.title),this._updateConnectionIndicator?.()},planUsageChipEnabled(e=null){return(e??this.loadAppSettingsFromStorage()).showPlanUsageLimits??this.getDefaultSettings().showPlanUsageLimits??!0},planUsageCollectionFlip(e,t){const n=this.planUsageChipEnabled(e??{});return t===n?void 0:t},resolveTabArrangement(e){const t=e?.tabArrangement??this.getDefaultSettings().tabArrangement;return t==="state"||t==="case"||t==="ledger"?t:"classic"},tabCliLogosEnabled(e){return(e?.showTabCliLogos??this.getDefaultSettings().showTabCliLogos)!==!1},resolveTabStateOrder(e){return(e?.tabStateOrder??this.getDefaultSettings().tabStateOrder)==="urgent-last"?"urgent-last":"urgent-first"},resolveHeaderStatsStyle(e){const t=e?.headerStatsStyle??this.getDefaultSettings().headerStatsStyle;return t==="classic"||t==="tiles"?t:"compact"},applyHeaderStatsStyle({style:e,showSystemStats:t}){document.documentElement.dataset.headerStats=e;const n=document.getElementById("headerSystemStats"),s=document.getElementById("connectionIndicator"),o=document.getElementById("planUsageChip");if(!n||!s||!o)return;if(!this._headerStatsAnchors){const l=document.createComment(" connection indicator (classic position) "),d=document.createComment(" plan usage chip (classic position) ");s.before(l),o.before(d),this._headerStatsAnchors={conn:l,plan:d}}const i=this._headerStatsAnchors,a=e!=="classic";a&&t?n.firstElementChild!==s&&n.prepend(s):i.conn.nextSibling!==s&&i.conn.after(s),a?n.nextElementSibling!==o&&n.after(o):i.plan.nextSibling!==o&&i.plan.after(o)},applyHeaderVisibilitySettings(){const e=this.loadAppSettingsFromStorage(),t=this.getDefaultSettings(),n=this.tabDetachButtonEnabled?.(e,t)??e.showTabDetachButton??t.showTabDetachButton??!1;document.documentElement.classList.toggle("tabs-show-detach",n);const s=MobileDetection.getDeviceType()!=="desktop",o=s?!1:e.showFontControls??t.showFontControls??!1,i=s?!1:e.showSystemStats??t.showSystemStats??!0,a=s?!1:e.showTokenCount??t.showTokenCount??!1,l=document.querySelector(".header-font-controls"),d=document.getElementById("headerSystemStats"),r=document.getElementById("headerTokens");l&&(l.style.display=o?"":"none"),d&&(d.style.display=i?"":"none"),r&&(r.style.display=a?"":"none"),this.applyHeaderStatsStyle({style:s||this.isSoloWindow?"classic":this.resolveHeaderStatsStyle(e),showSystemStats:i});const c=e.showLifecycleLog??t.showLifecycleLog??!1,p=document.querySelector(".btn-lifecycle-log");p&&(p.style.display=c?"":"none");const u=e.showResponseViewer??t.showResponseViewer??!1,m=document.querySelector(".btn-response-viewer-header");m&&m.classList.toggle("btn-response-viewer-header--hidden",!u);const f=e.showAttachmentsButton??t.showAttachmentsButton??!1,h=document.getElementById("attachmentsHistoryBtn");h&&h.classList.toggle("btn-attachments-history--hidden",!f);const g=e.showFileViewerButton??t.showFileViewerButton??!0,y=document.querySelector(".btn-file-viewer");y&&y.classList.toggle("btn-file-viewer--hidden",!g);const S=e.showMultiMonitorButton??t.showMultiMonitorButton??!1,b=document.querySelector(".btn-multimonitor");b&&b.classList.toggle("btn-multimonitor--hidden",!S);const E=e.showSplitButton??t.showSplitButton??!1;this._applySplitButtonVisibility?.(E);const w=e.showTileGridButton??t.showTileGridButton??!0;this._applyTileGridButtonVisibility?.(w),this._renderTileChrome?.();const v=e.showUltracodeAgents??t.showUltracodeAgents??!1,B=document.querySelector(".btn-ultracode-agents");B&&B.classList.toggle("btn-ultracode-agents--hidden",!v);const k=document.querySelector(".btn-readmymind");k&&k.classList.toggle("btn-readmymind--hidden",e.readMyMindEnabled!==!0),typeof KeyboardAccessoryBar<"u"&&KeyboardAccessoryBar.syncReadMyMind?.();const I=this.planUsageChipEnabled(e),M=document.getElementById("planUsageChip");M&&M.classList.toggle("header-plan-usage--hidden",!I);const F=e.showRedrawButton??t.showRedrawButton??!1,L=document.querySelector(".btn-redraw-terminal");L&&L.classList.toggle("btn-redraw-terminal--hidden",!F);const H=e.showSessionButton??t.showSessionButton??!1,A=document.querySelector(".btn-session-manager");A&&A.classList.toggle("btn-session-manager--hidden",!H);const D=e.showAwayDigestButton??t.showAwayDigestButton??!1,P=document.querySelector(".btn-away-digest");P&&P.classList.toggle("btn-away-digest--hidden",!D);const O=e.showCronButton??t.showCronButton??!1,R=document.querySelector(".btn-cron");R&&R.classList.toggle("btn-cron--hidden",!O),this.applyGitStatusVisibility?.();const x=document.querySelector(".btn-notifications");if(x&&(x.style.display="none"),!(this.notificationManager?.preferences?.enabled??!0)){const $=document.getElementById("notifDrawer");$&&$.classList.remove("open")}},applyTabOrientation(e={}){const t=this.loadAppSettingsFromStorage(),n=this.getDefaultSettings(),s=this.isSessionSidebarActive?.()===!0,o=!this.isSoloWindow&&!s&&window.CodemanTabOverflow?.resolveTabOrientation?window.CodemanTabOverflow.resolveTabOrientation({deviceType:MobileDetection.getDeviceType(),setting:t.tabOrientation??n.tabOrientation??"horizontal"}):"horizontal";o!=="vertical"&&this._tabRailSearch&&this._resetTabRailSearch?.();const i=document.documentElement,a=i.getAttribute("data-tab-orientation")||"horizontal";i.setAttribute("data-tab-orientation",o);const l=i.dataset.tabRailDetail||"rich",d=(t.tabRailDetail??n.tabRailDetail??"rich")==="simple"?"simple":"rich";i.dataset.tabRailDetail=d;const r=i.dataset.tabRailSort||"activity",c=(t.tabRailSort??n.tabRailSort??"activity")==="manual"?"manual":"activity";i.dataset.tabRailSort=c;const p=i.dataset.tabArrangement||"state",u=this.resolveTabArrangement(t);i.dataset.tabArrangement=u;const m=i.dataset.tabStateOrder||"urgent-first",f=this.resolveTabStateOrder(t);i.dataset.tabStateOrder=f;const h=i.dataset.tabLogos,g=this.tabCliLogosEnabled(t)?"on":"off";i.dataset.tabLogos=g;const y=document.getElementById("sessionTabs"),S=document.getElementById("tabRail"),b=document.getElementById("sessionTabsHost");!s&&y&&S&&b&&(o==="vertical"?y.parentElement!==S&&S.appendChild(y):y.parentElement!==b&&b.appendChild(y)),y&&y.setAttribute("aria-orientation",s||o==="vertical"?"vertical":"horizontal");const E=e.settleRailWidth===!0&&(o==="vertical"||a!==o);this.applyTabRailWidth?.({settle:E});const w=a!==o,v=w||l!==d||r!==c||p!==u||m!==f;w&&(this.updateTabOverflowMode?.(),E||this.syncTerminalGeometry?.());const B=this._tallTabsEnabled;v&&this.applyTabWrapSettings?.(),v?(B!==void 0&&B!==this._tallTabsEnabled||this._fullRenderSessionTabs?.(),this._updateConnectionLinesImmediate?.(),this._refreshHomeSessionsIfVisible?.()):h!==g&&(this.updateTabOverflowMode?.(),this._updateConnectionLinesImmediate?.()),this.isRichTabRows?.()?this._startSidebarRichClock?.():this._stopSidebarRichClock?.()},applyTabWrapSettings(){const e=this.loadAppSettingsFromStorage(),t=this.getDefaultSettings(),n=MobileDetection.getDeviceType(),s=this.isSessionSidebarActive?.()===!0,o=!s&&n==="desktop"?e.tabTwoRows??t.tabTwoRows??!1:!1,i=this.isTabRailRich?.()===!0,a=s||o||i,l=this._tallTabsEnabled;this._tallTabsEnabled=a;const d=document.getElementById("sessionTabs");d&&(d.classList.toggle("tabs-two-rows",o),d.classList.toggle("tabs-show-folder",a)),l!==void 0&&l!==a&&this._fullRenderSessionTabs()},applyMonitorVisibility(){const e=this.loadAppSettingsFromStorage(),t=this.getDefaultSettings(),n=e.showMonitor??t.showMonitor??!1,s=e.showSubagents??t.showSubagents??!1,o=e.showFileBrowser??t.showFileBrowser??!1,i=document.getElementById("monitorPanel");i&&(i.style.display=n?"":"none",n?i.classList.add("open"):i.classList.remove("open"));const a=document.getElementById("subagentsPanel");a&&(s?a.classList.remove("hidden"):a.classList.add("hidden"));const l=e.showUltracodeAgents??t.showUltracodeAgents??!1,d=document.getElementById("ultracodeAgentsPanel");d&&(l?d.classList.remove("hidden"):(d.classList.remove("open"),d.classList.add("hidden"))),e.ultracodeFloatingWindows??t.ultracodeFloatingWindows??!1?typeof this.syncAllUltracodeFloatingWindows=="function"&&this.syncAllUltracodeFloatingWindows():typeof this.removeAllUltracodeWindows=="function"&&this.removeAllUltracodeWindows();const c=document.getElementById("fileBrowserPanel");if(c)if(o&&this.activeSessionId){if(c.classList.add("visible"),this.loadFileBrowser(this.activeSessionId),!this.fileBrowserDragListeners){const p=c.querySelector(".file-browser-header");if(p){const u=()=>{if(!c.style.left){const m=c.getBoundingClientRect();c.style.left=`${m.left}px`,c.style.top=`${m.top}px`,c.style.right="auto"}};p.addEventListener("mousedown",u),p.addEventListener("touchstart",u,{passive:!0}),this.fileBrowserDragListeners=this.makeWindowDraggable(c,p),this.fileBrowserDragListeners._onFirstDrag=u}}}else c.classList.contains("visible")&&(this._resetFileBrowserForHide?.(),c.classList.remove("visible"))},closeMonitor(){const e=document.getElementById("monitorPanel");e&&(e.classList.remove("open"),e.style.display="none");const t=this.loadAppSettingsFromStorage();t.showMonitor=!1,this.saveAppSettingsToStorage(t)},closeSubagentsPanel(){const e=document.getElementById("subagentsPanel");e&&(e.classList.remove("open"),e.classList.add("hidden")),this.subagentPanelVisible=!1;const t=this.loadAppSettingsFromStorage();t.showSubagents=!1,this.saveAppSettingsToStorage(t)},async clearAllSubagents(){const e=this.subagents.size;if(e===0){this.showToast("No subagents to clear","info");return}if(confirm(`Clear all ${e} tracked subagent(s)? This removes them from the UI but does not affect running processes.`))try{const n=await(await fetch("/api/subagents",{method:"DELETE"})).json();n.success?(this.subagents.clear(),this.subagentActivity.clear(),this.subagentToolResults.clear(),this.cleanupAllFloatingWindows(),this.renderSubagentPanel(),this.renderMonitorSubagents(),this.updateSubagentBadge(),this.showToast(`Cleared ${n.data.cleared} subagent(s)`,"success")):this.showToast("Failed to clear subagents: "+n.error,"error")}catch{this.showToast("Failed to clear subagents","error")}},toggleSubagentsPanel(){const e=document.getElementById("subagentsPanel"),t=document.getElementById("subagentsToggleBtn");if(e){if(e.classList.contains("hidden")){e.classList.remove("hidden");const n=this.loadAppSettingsFromStorage();n.showSubagents=!0,this.saveAppSettingsToStorage(n)}e.classList.toggle("open"),this.subagentPanelVisible=e.classList.contains("open"),t&&(t.innerHTML=this.subagentPanelVisible?"&#x25BC;":"&#x25B2;"),this.subagentPanelVisible&&this.renderSubagentPanel()}},_displaySettingKeySet(){return new Set(["showFontControls","showSystemStats","headerStatsStyle","showTokenCount","showCost","showLifecycleLog","showResponseViewer","showRedrawButton","showMonitor","showProjectInsights","showFileBrowser","showSubagents","subagentActiveTabOnly","tabTwoRows","showTabCliLogos","tabOrientation","tabRailWidth","tabRailDetail","tabRailSort","tabArrangement","tabStateOrder","sessionListLayout","sessionSidebarFontSize","localEchoEnabled","cjkInputEnabled","extendedKeyboardBar","skin","showPlanUsageLimits","showAttachmentsButton","showFileViewerButton","webglRendererEnabled","terminalFontFamily","terminalFontWeight","terminalFontWeightBold","language","terminalWheelLocalScrollback","autoCopySelection","copyStripMargin","showSessionButton","showAwayDigestButton","showCronButton","showGitStatus","gitStatusTree","gitStatusMaxRepos","gitStatusTimeoutSeconds","showTabDetachButton","mobileOverviewEnabled","sessionLineageLines","showSplitButton","showTileGridButton","tileDetachEnabled"])},async loadAppSettingsFromServer(e=null){try{if((MobileDetection.isHandheldDevice?.()??MobileDetection.getDeviceType()==="mobile")&&!localStorage.getItem("codeman:planUsagePerDeviceMigrated")){const t=this.loadAppSettingsFromStorage();t&&t.showPlanUsageLimits&&(t.showPlanUsageLimits=!1,this.saveAppSettingsToStorage(t)),localStorage.setItem("codeman:planUsagePerDeviceMigrated","1")}}catch{}try{const t=e?await e:await fetch("/api/settings").then(n=>n.ok?n.json():null).then(n=>n?.success===!0?n.data:n);if(t){const{notificationPreferences:n,voiceSettings:s,respawnPresets:o,runMode:i,...a}=t,l=this._displaySettingKeySet();delete a.showPlanUsageLimits;const d=this.loadAppSettingsFromStorage(),r={...d};for(const[c,p]of Object.entries(a))l.has(c)&&c in d||(r[c]=p);if(this.saveAppSettingsToStorage(r),n&&this.notificationManager&&(localStorage.getItem(this.notificationManager.getStorageKey())||(this.notificationManager.preferences=this.notificationManager.normalizePreferences(n),this.notificationManager.savePreferences())),s){const c=localStorage.getItem("codeman-voice-settings");(!c||!JSON.parse(c).apiKey)&&VoiceInput._saveDeepgramConfig(s)}if(o&&Array.isArray(o))this._serverRespawnPresets=o,localStorage.setItem("codeman-respawn-presets",JSON.stringify(o));else if(!this._settingsReadOnly()){const c=localStorage.getItem("codeman-respawn-presets");if(c){const p=JSON.parse(c);p.length>0&&(this._serverRespawnPresets=p,this._apiPut("/api/settings",{respawnPresets:p}).then(u=>this._noteSettingsWriteRefusal(u)).catch(()=>{}))}}if(i){this.runMode=i;try{localStorage.setItem("codeman_runMode",i)}catch{}this._applyRunMode()}return this._applyOwnSettings(),r}}catch(t){console.error("Failed to load settings from server:",t)}return this.loadAppSettingsFromStorage()},async loadSubagentWindowStates(){let e=null;try{const t=await fetch("/api/subagent-window-states");if(t.ok){const n=await t.json();e=n?.success===!0?n.data:n,localStorage.setItem("codeman-subagent-window-states",JSON.stringify(e))}}catch(t){console.error("Failed to load subagent window states from server:",t)}if(!e)try{const t=localStorage.getItem("codeman-subagent-window-states");t&&(e=JSON.parse(t))}catch(t){console.error("Failed to load subagent window states from localStorage:",t)}return e||{minimized:{},open:[]}},async saveSubagentParentMap(){const e=Object.fromEntries(this.subagentParentMap);try{localStorage.setItem("codeman-subagent-parents",JSON.stringify(e))}catch(t){console.error("Failed to save subagent parents to localStorage:",t)}try{await fetch("/api/subagent-parents",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}catch(t){console.error("Failed to save subagent parents to server:",t)}},async loadSubagentParentMap(){let e=null;try{const t=await fetch("/api/subagent-parents");if(t.ok){const n=await t.json();e=n?.success===!0?n.data:n,localStorage.setItem("codeman-subagent-parents",JSON.stringify(e))}}catch(t){console.error("Failed to load subagent parents from server:",t)}if(!e)try{const t=localStorage.getItem("codeman-subagent-parents");t&&(e=JSON.parse(t))}catch(t){console.error("Failed to load subagent parents from localStorage:",t)}if(e&&typeof e=="object")for(const[t,n]of Object.entries(e))this.sessions.has(n)&&this.subagents.has(t)&&this.subagentParentMap.set(t,n)},getAgentParentSessionId(e){return this.subagentParentMap.get(e)||null},setAgentParentSessionId(e,t){if(!e||!t||this.subagentParentMap.has(e))return;this.subagentParentMap.set(e,t),this.saveSubagentParentMap();const n=this.subagents.get(e);if(n){n.parentSessionId=t;const s=this.sessions.get(t);s&&(n.parentSessionName=this.getSessionName(s)),this.subagents.set(e,n)}},showHelp(){const e=document.getElementById("helpModal");e.classList.add("active"),this.activeFocusTrap=new FocusTrap(e),this.activeFocusTrap.activate()},closeHelp(){document.getElementById("helpModal").classList.remove("active"),this.activeFocusTrap&&(this.activeFocusTrap.deactivate(),this.activeFocusTrap=null)},renderShortcutSettingsList(){const e=document.getElementById("appSettingsShortcutsList");if(!e)return;const t=this.getShortcutRegistry?this.getShortcutRegistry():typeof DEFAULT_SHORTCUTS<"u"?DEFAULT_SHORTCUTS:[],n=this.readShortcutOverridesFromSettings();e.innerHTML=t.map(s=>{const o=s.displayBindings?s.displayBindings.join(" / "):(s.bindings||[]).map(d=>[...d.modifiers||[],d.key||d.code||""].join("+")).join(" / "),i=!!s.action&&Array.isArray(s.bindings),a=!!n[s.id],l=i?`<button type="button" class="shortcut-capture-btn" data-shortcut-action="capture" title="Capture new binding">Edit</button>
100
+ ${s}`:`Install ${n}? This runs its official install command on the Codeman server.`;if(!confirm(o))return;const i=document.getElementById(`cliInstallBtn-${e}`);i&&(i.disabled=!0,i.textContent="Installing\u2026");try{const a=await this._api(`/api/clis/${encodeURIComponent(e)}/install`,{method:"POST"});if(!a||!a.ok){let l="";try{l=(await a?.json())?.error||""}catch{}this.showToast(`Installing "${e}" failed${l?`: ${l}`:""}`,"error");return}this.showToast(`Installed "${e}"`,"success")}finally{await this.loadCliListForSettings()}},openCliCustomForm(e){const t=document.getElementById("cliCustomForm"),n=document.getElementById("cliCustomFormError");if(!t)return;const s=e?(this._cliList||[]).find(o=>o.id===e):null;this._editingCliCustomId=s?s.id:null,document.getElementById("cliCustomId").value=s?s.id:"",document.getElementById("cliCustomId").disabled=!!s,document.getElementById("cliCustomLabel").value=s?s.label:"",document.getElementById("cliCustomBadge").value=s?s.shortBadge:"",document.getElementById("cliCustomBinary").value="",document.getElementById("cliCustomArgv").value="",document.getElementById("cliCustomSubmit").textContent=s?"Save":"Create",n&&(n.style.display="none"),t.style.display=""},closeCliCustomForm(){const e=document.getElementById("cliCustomForm");e&&(e.style.display="none"),this._editingCliCustomId=null},async submitCliCustomForm(e){e.preventDefault();const t=document.getElementById("cliCustomFormError"),n=u=>{t&&(t.textContent=u,t.style.display="")},s=document.getElementById("cliCustomId").value.trim(),o=document.getElementById("cliCustomLabel").value.trim(),i=document.getElementById("cliCustomBadge").value.trim(),a=document.getElementById("cliCustomBinary").value.trim().split(/\s+/).filter(Boolean),l=document.getElementById("cliCustomArgv").value.trim().split(/\s+/).filter(Boolean);if(!s||!o||!i||a.length===0||l.length===0){n("All fields are required.");return}const d=this._editingCliCustomId,r=d?`/api/clis/custom/${encodeURIComponent(d)}`:"/api/clis",c=d?"PUT":"POST",p=await this._api(r,{method:c,body:{id:s,label:o,shortBadge:i,binaries:a,argv:l}});if(!p||!p.ok){let u="Request failed";try{u=(await p?.json())?.error||u}catch{}n(u);return}this.closeCliCustomForm(),await this.loadCliListForSettings()},async deleteCliCustom(e){const t=(this._cliList||[]).find(s=>s.id===e);if(!confirm(`Delete custom CLI "${t?.label||e}"? This cannot be undone.`))return;const n=await this._api(`/api/clis/${encodeURIComponent(e)}`,{method:"DELETE"});if(!n||!n.ok){let s="";try{s=(await n?.json())?.error||""}catch{}this.showToast(`Failed to delete "${e}"${s?`: ${s}`:""}`,"error");return}await this.loadCliListForSettings()},isRalphTrackerEnabledByDefault(){return this.loadAppSettingsFromStorage().ralphTrackerEnabled??!1},getSettingsStorageKey(){return MobileDetection.isHandheldDevice?.()??MobileDetection.getDeviceType()==="mobile"?"codeman-app-settings-mobile":"codeman-app-settings"},getDefaultSettings(){return MobileDetection.isHandheldDevice?.()??MobileDetection.getDeviceType()==="mobile"?{showFontControls:!1,showSystemStats:!1,showGpuStats:!1,showCpuMhz:!1,showTokenCount:!1,showCost:!1,showMonitor:!1,showProjectInsights:!1,showFileBrowser:!1,showSubagents:!1,showUltracodeAgents:!1,ultracodeFloatingWindows:!1,showMultiMonitorButton:!1,showSplitButton:!1,showTileGridButton:!1,showPlanUsageLimits:!1,showAttachmentsButton:!1,showFileViewerButton:!1,showRedrawButton:!1,showSessionButton:!1,showAwayDigestButton:!1,showCronButton:!1,mobileOverviewEnabled:!0,remoteAutoReconnect:!0,gestureControlEnabled:!1,subagentTrackingEnabled:!0,subagentActiveTabOnly:!0,imageWatcherEnabled:!1,ralphTrackerEnabled:!1,tabTwoRows:!1,showTabCliLogos:!0,tabOrientation:"horizontal",tabRailWidth:256,tabRailDetail:"rich",tabRailSort:"activity",tabArrangement:"classic",tabStateOrder:"urgent-first",sessionListLayout:"header",sessionSidebarFontSize:12,cjkInputEnabled:!1,terminalWheelLocalScrollback:!1,webglRendererEnabled:!1,skin:"daylight-blue"}:typeof window<"u"&&window.matchMedia?.("(pointer: coarse)")?.matches===!0?{showTileGridButton:!1}:{}},loadAppSettingsFromStorage(){if(this._cachedAppSettings)return this._cachedAppSettings;try{const t=this.getSettingsStorageKey(),n=localStorage.getItem(t);if(n)return this._cachedAppSettings=JSON.parse(n),this._cachedAppSettings}catch(t){console.error("Failed to load app settings:",t)}const e={...this.getDefaultSettings()};return delete e.showTileGridButton,this._cachedAppSettings=e,this._cachedAppSettings},saveAppSettingsToStorage(e){this._cachedAppSettings=e;try{const t=this.getSettingsStorageKey();localStorage.setItem(t,JSON.stringify(e))}catch(t){console.error("Failed to save app settings:",t)}},applySkin(){const e=this.loadAppSettingsFromStorage(),t=this.getDefaultSettings(),n=e.skin??t.skin??"daylight-blue";document.documentElement.setAttribute("data-skin",n),window.__codemanSkin=n;const s=getComputedStyle(document.documentElement).getPropertyValue("--bg-dark").trim();s&&document.querySelector('meta[name="theme-color"]')?.setAttribute("content",s);try{localStorage.setItem("codeman:skin",n)}catch{}typeof this.applyTerminalSkin=="function"&&this.applyTerminalSkin(n)},applyLocalization(){const e=this.loadAppSettingsFromStorage();window.CodemanI18n?.configure({language:e.language,displayName:e.displayName})&&this.notificationManager&&(this.notificationManager.originalTitle=document.title),this._updateConnectionIndicator?.()},planUsageChipEnabled(e=null){return(e??this.loadAppSettingsFromStorage()).showPlanUsageLimits??this.getDefaultSettings().showPlanUsageLimits??!0},planUsageCollectionFlip(e,t){const n=this.planUsageChipEnabled(e??{});return t===n?void 0:t},resolveTabArrangement(e){const t=e?.tabArrangement??this.getDefaultSettings().tabArrangement;return t==="state"||t==="case"||t==="ledger"?t:"classic"},tabCliLogosEnabled(e){return(e?.showTabCliLogos??this.getDefaultSettings().showTabCliLogos)!==!1},resolveTabStateOrder(e){return(e?.tabStateOrder??this.getDefaultSettings().tabStateOrder)==="urgent-last"?"urgent-last":"urgent-first"},resolveHeaderStatsStyle(e){const t=e?.headerStatsStyle??this.getDefaultSettings().headerStatsStyle;return t==="classic"||t==="tiles"?t:"compact"},applyHeaderStatsStyle({style:e,showSystemStats:t}){document.documentElement.dataset.headerStats=e;const n=document.getElementById("headerSystemStats"),s=document.getElementById("connectionIndicator"),o=document.getElementById("planUsageChip");if(!n||!s||!o)return;if(!this._headerStatsAnchors){const l=document.createComment(" connection indicator (classic position) "),d=document.createComment(" plan usage chip (classic position) ");s.before(l),o.before(d),this._headerStatsAnchors={conn:l,plan:d}}const i=this._headerStatsAnchors,a=e!=="classic";a&&t?n.firstElementChild!==s&&n.prepend(s):i.conn.nextSibling!==s&&i.conn.after(s),a?n.nextElementSibling!==o&&n.after(o):i.plan.nextSibling!==o&&i.plan.after(o)},applyHeaderVisibilitySettings(){const e=this.loadAppSettingsFromStorage(),t=this.getDefaultSettings(),n=this.tabDetachButtonEnabled?.(e,t)??e.showTabDetachButton??t.showTabDetachButton??!1;document.documentElement.classList.toggle("tabs-show-detach",n);const s=MobileDetection.getDeviceType()!=="desktop",o=s?!1:e.showFontControls??t.showFontControls??!1,i=s?!1:e.showSystemStats??t.showSystemStats??!0,a=s?!1:e.showTokenCount??t.showTokenCount??!1,l=document.querySelector(".header-font-controls"),d=document.getElementById("headerSystemStats"),r=document.getElementById("headerTokens");l&&(l.style.display=o?"":"none"),d&&(d.style.display=i?"":"none"),r&&(r.style.display=a?"":"none"),this.applyHeaderStatsStyle({style:s||this.isSoloWindow?"classic":this.resolveHeaderStatsStyle(e),showSystemStats:i});const c=e.showLifecycleLog??t.showLifecycleLog??!1,p=document.querySelector(".btn-lifecycle-log");p&&(p.style.display=c?"":"none");const u=e.showResponseViewer??t.showResponseViewer??!1,m=document.querySelector(".btn-response-viewer-header");m&&m.classList.toggle("btn-response-viewer-header--hidden",!u);const f=e.showAttachmentsButton??t.showAttachmentsButton??!1,h=document.getElementById("attachmentsHistoryBtn");h&&h.classList.toggle("btn-attachments-history--hidden",!f);const g=e.showFileViewerButton??t.showFileViewerButton??!0,y=document.querySelector(".btn-file-viewer");y&&y.classList.toggle("btn-file-viewer--hidden",!g);const S=e.showMultiMonitorButton??t.showMultiMonitorButton??!1,b=document.querySelector(".btn-multimonitor");b&&b.classList.toggle("btn-multimonitor--hidden",!S);const E=e.showSplitButton??t.showSplitButton??!1;this._applySplitButtonVisibility?.(E);const w=e.showTileGridButton??t.showTileGridButton??!0;this._applyTileGridButtonVisibility?.(w),this._renderTileChrome?.();const v=e.showUltracodeAgents??t.showUltracodeAgents??!1,B=document.querySelector(".btn-ultracode-agents");B&&B.classList.toggle("btn-ultracode-agents--hidden",!v);const k=document.querySelector(".btn-readmymind");k&&k.classList.toggle("btn-readmymind--hidden",e.readMyMindEnabled!==!0),typeof KeyboardAccessoryBar<"u"&&KeyboardAccessoryBar.syncReadMyMind?.();const I=this.planUsageChipEnabled(e),M=document.getElementById("planUsageChip");M&&M.classList.toggle("header-plan-usage--hidden",!I);const F=e.showRedrawButton??t.showRedrawButton??!1,A=document.querySelector(".btn-redraw-terminal");A&&A.classList.toggle("btn-redraw-terminal--hidden",!F);const H=e.showSessionButton??t.showSessionButton??!1,L=document.querySelector(".btn-session-manager");L&&L.classList.toggle("btn-session-manager--hidden",!H);const D=e.showAwayDigestButton??t.showAwayDigestButton??!1,P=document.querySelector(".btn-away-digest");P&&P.classList.toggle("btn-away-digest--hidden",!D);const O=e.showCronButton??t.showCronButton??!1,R=document.querySelector(".btn-cron");R&&R.classList.toggle("btn-cron--hidden",!O),this.applyGitStatusVisibility?.();const x=document.querySelector(".btn-notifications");if(x&&(x.style.display="none"),!(this.notificationManager?.preferences?.enabled??!0)){const $=document.getElementById("notifDrawer");$&&$.classList.remove("open")}},applyTabOrientation(e={}){const t=this.loadAppSettingsFromStorage(),n=this.getDefaultSettings(),s=this.isSessionSidebarActive?.()===!0,o=!this.isSoloWindow&&!s&&window.CodemanTabOverflow?.resolveTabOrientation?window.CodemanTabOverflow.resolveTabOrientation({deviceType:MobileDetection.getDeviceType(),setting:t.tabOrientation??n.tabOrientation??"horizontal"}):"horizontal";o!=="vertical"&&this._tabRailSearch&&this._resetTabRailSearch?.();const i=document.documentElement,a=i.getAttribute("data-tab-orientation")||"horizontal";i.setAttribute("data-tab-orientation",o);const l=i.dataset.tabRailDetail||"rich",d=(t.tabRailDetail??n.tabRailDetail??"rich")==="simple"?"simple":"rich";i.dataset.tabRailDetail=d;const r=i.dataset.tabRailSort||"activity",c=(t.tabRailSort??n.tabRailSort??"activity")==="manual"?"manual":"activity";i.dataset.tabRailSort=c;const p=i.dataset.tabArrangement||"state",u=this.resolveTabArrangement(t);i.dataset.tabArrangement=u;const m=i.dataset.tabStateOrder||"urgent-first",f=this.resolveTabStateOrder(t);i.dataset.tabStateOrder=f;const h=i.dataset.tabLogos,g=this.tabCliLogosEnabled(t)?"on":"off";i.dataset.tabLogos=g;const y=document.getElementById("sessionTabs"),S=document.getElementById("tabRail"),b=document.getElementById("sessionTabsHost");!s&&y&&S&&b&&(o==="vertical"?y.parentElement!==S&&S.appendChild(y):y.parentElement!==b&&b.appendChild(y)),y&&y.setAttribute("aria-orientation",s||o==="vertical"?"vertical":"horizontal");const E=e.settleRailWidth===!0&&(o==="vertical"||a!==o);this.applyTabRailWidth?.({settle:E});const w=a!==o,v=w||l!==d||r!==c||p!==u||m!==f;w&&(this.updateTabOverflowMode?.(),E||this.syncTerminalGeometry?.());const B=this._tallTabsEnabled;v&&this.applyTabWrapSettings?.(),v?(B!==void 0&&B!==this._tallTabsEnabled||this._fullRenderSessionTabs?.(),this._updateConnectionLinesImmediate?.(),this._refreshHomeSessionsIfVisible?.()):h!==g&&(this.updateTabOverflowMode?.(),this._updateConnectionLinesImmediate?.()),this.isRichTabRows?.()?this._startSidebarRichClock?.():this._stopSidebarRichClock?.()},applyTabWrapSettings(){const e=this.loadAppSettingsFromStorage(),t=this.getDefaultSettings(),n=MobileDetection.getDeviceType(),s=this.isSessionSidebarActive?.()===!0,o=!s&&n==="desktop"?e.tabTwoRows??t.tabTwoRows??!1:!1,i=this.isTabRailRich?.()===!0,a=s||o||i,l=this._tallTabsEnabled;this._tallTabsEnabled=a;const d=document.getElementById("sessionTabs");d&&(d.classList.toggle("tabs-two-rows",o),d.classList.toggle("tabs-show-folder",a)),l!==void 0&&l!==a&&this._fullRenderSessionTabs()},applyMonitorVisibility(){const e=this.loadAppSettingsFromStorage(),t=this.getDefaultSettings(),n=e.showMonitor??t.showMonitor??!1,s=e.showSubagents??t.showSubagents??!1,o=e.showFileBrowser??t.showFileBrowser??!1,i=document.getElementById("monitorPanel");i&&(i.style.display=n?"":"none",n?i.classList.add("open"):i.classList.remove("open"));const a=document.getElementById("subagentsPanel");a&&(s?a.classList.remove("hidden"):a.classList.add("hidden"));const l=e.showUltracodeAgents??t.showUltracodeAgents??!1,d=document.getElementById("ultracodeAgentsPanel");d&&(l?d.classList.remove("hidden"):(d.classList.remove("open"),d.classList.add("hidden"))),e.ultracodeFloatingWindows??t.ultracodeFloatingWindows??!1?typeof this.syncAllUltracodeFloatingWindows=="function"&&this.syncAllUltracodeFloatingWindows():typeof this.removeAllUltracodeWindows=="function"&&this.removeAllUltracodeWindows();const c=document.getElementById("fileBrowserPanel");if(c)if(o&&this.activeSessionId){if(c.classList.add("visible"),this.loadFileBrowser(this.activeSessionId),!this.fileBrowserDragListeners){const p=c.querySelector(".file-browser-header");if(p){const u=()=>{if(!c.style.left){const m=c.getBoundingClientRect();c.style.left=`${m.left}px`,c.style.top=`${m.top}px`,c.style.right="auto"}};p.addEventListener("mousedown",u),p.addEventListener("touchstart",u,{passive:!0}),this.fileBrowserDragListeners=this.makeWindowDraggable(c,p),this.fileBrowserDragListeners._onFirstDrag=u}}}else c.classList.contains("visible")&&(this._resetFileBrowserForHide?.(),c.classList.remove("visible"))},closeMonitor(){const e=document.getElementById("monitorPanel");e&&(e.classList.remove("open"),e.style.display="none");const t=this.loadAppSettingsFromStorage();t.showMonitor=!1,this.saveAppSettingsToStorage(t)},closeSubagentsPanel(){const e=document.getElementById("subagentsPanel");e&&(e.classList.remove("open"),e.classList.add("hidden")),this.subagentPanelVisible=!1;const t=this.loadAppSettingsFromStorage();t.showSubagents=!1,this.saveAppSettingsToStorage(t)},async clearAllSubagents(){const e=this.subagents.size;if(e===0){this.showToast("No subagents to clear","info");return}if(confirm(`Clear all ${e} tracked subagent(s)? This removes them from the UI but does not affect running processes.`))try{const n=await(await fetch("/api/subagents",{method:"DELETE"})).json();n.success?(this.subagents.clear(),this.subagentActivity.clear(),this.subagentToolResults.clear(),this.cleanupAllFloatingWindows(),this.renderSubagentPanel(),this.renderMonitorSubagents(),this.updateSubagentBadge(),this.showToast(`Cleared ${n.data.cleared} subagent(s)`,"success")):this.showToast("Failed to clear subagents: "+n.error,"error")}catch{this.showToast("Failed to clear subagents","error")}},toggleSubagentsPanel(){const e=document.getElementById("subagentsPanel"),t=document.getElementById("subagentsToggleBtn");if(e){if(e.classList.contains("hidden")){e.classList.remove("hidden");const n=this.loadAppSettingsFromStorage();n.showSubagents=!0,this.saveAppSettingsToStorage(n)}e.classList.toggle("open"),this.subagentPanelVisible=e.classList.contains("open"),t&&(t.innerHTML=this.subagentPanelVisible?"&#x25BC;":"&#x25B2;"),this.subagentPanelVisible&&this.renderSubagentPanel()}},_displaySettingKeySet(){return new Set(["showFontControls","showSystemStats","showGpuStats","showCpuMhz","headerStatsStyle","showTokenCount","showCost","showLifecycleLog","showResponseViewer","showRedrawButton","showMonitor","showProjectInsights","showFileBrowser","showSubagents","subagentActiveTabOnly","tabTwoRows","showTabCliLogos","tabOrientation","tabRailWidth","tabRailDetail","tabRailSort","tabArrangement","tabStateOrder","sessionListLayout","sessionSidebarFontSize","localEchoEnabled","cjkInputEnabled","extendedKeyboardBar","skin","showPlanUsageLimits","showAttachmentsButton","showFileViewerButton","webglRendererEnabled","terminalFontFamily","terminalFontWeight","terminalFontWeightBold","language","terminalWheelLocalScrollback","autoCopySelection","copyStripMargin","showSessionButton","showAwayDigestButton","showCronButton","showGitStatus","gitStatusTree","gitStatusMaxRepos","gitStatusTimeoutSeconds","showTabDetachButton","mobileOverviewEnabled","sessionLineageLines","showSplitButton","showTileGridButton","tileDetachEnabled"])},async loadAppSettingsFromServer(e=null){try{if((MobileDetection.isHandheldDevice?.()??MobileDetection.getDeviceType()==="mobile")&&!localStorage.getItem("codeman:planUsagePerDeviceMigrated")){const t=this.loadAppSettingsFromStorage();t&&t.showPlanUsageLimits&&(t.showPlanUsageLimits=!1,this.saveAppSettingsToStorage(t)),localStorage.setItem("codeman:planUsagePerDeviceMigrated","1")}}catch{}try{const t=e?await e:await fetch("/api/settings").then(n=>n.ok?n.json():null).then(n=>n?.success===!0?n.data:n);if(t){const{notificationPreferences:n,voiceSettings:s,respawnPresets:o,runMode:i,...a}=t,l=this._displaySettingKeySet();delete a.showPlanUsageLimits;const d=this.loadAppSettingsFromStorage(),r={...d};for(const[c,p]of Object.entries(a))l.has(c)&&c in d||(r[c]=p);if(this.saveAppSettingsToStorage(r),n&&this.notificationManager&&(localStorage.getItem(this.notificationManager.getStorageKey())||(this.notificationManager.preferences=this.notificationManager.normalizePreferences(n),this.notificationManager.savePreferences())),s){const c=localStorage.getItem("codeman-voice-settings");(!c||!JSON.parse(c).apiKey)&&VoiceInput._saveDeepgramConfig(s)}if(o&&Array.isArray(o))this._serverRespawnPresets=o,localStorage.setItem("codeman-respawn-presets",JSON.stringify(o));else if(!this._settingsReadOnly()){const c=localStorage.getItem("codeman-respawn-presets");if(c){const p=JSON.parse(c);p.length>0&&(this._serverRespawnPresets=p,this._apiPut("/api/settings",{respawnPresets:p}).then(u=>this._noteSettingsWriteRefusal(u)).catch(()=>{}))}}if(i){this.runMode=i;try{localStorage.setItem("codeman_runMode",i)}catch{}this._applyRunMode()}return this._applyOwnSettings(),r}}catch(t){console.error("Failed to load settings from server:",t)}return this.loadAppSettingsFromStorage()},async loadSubagentWindowStates(){let e=null;try{const t=await fetch("/api/subagent-window-states");if(t.ok){const n=await t.json();e=n?.success===!0?n.data:n,localStorage.setItem("codeman-subagent-window-states",JSON.stringify(e))}}catch(t){console.error("Failed to load subagent window states from server:",t)}if(!e)try{const t=localStorage.getItem("codeman-subagent-window-states");t&&(e=JSON.parse(t))}catch(t){console.error("Failed to load subagent window states from localStorage:",t)}return e||{minimized:{},open:[]}},async saveSubagentParentMap(){const e=Object.fromEntries(this.subagentParentMap);try{localStorage.setItem("codeman-subagent-parents",JSON.stringify(e))}catch(t){console.error("Failed to save subagent parents to localStorage:",t)}try{await fetch("/api/subagent-parents",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}catch(t){console.error("Failed to save subagent parents to server:",t)}},async loadSubagentParentMap(){let e=null;try{const t=await fetch("/api/subagent-parents");if(t.ok){const n=await t.json();e=n?.success===!0?n.data:n,localStorage.setItem("codeman-subagent-parents",JSON.stringify(e))}}catch(t){console.error("Failed to load subagent parents from server:",t)}if(!e)try{const t=localStorage.getItem("codeman-subagent-parents");t&&(e=JSON.parse(t))}catch(t){console.error("Failed to load subagent parents from localStorage:",t)}if(e&&typeof e=="object")for(const[t,n]of Object.entries(e))this.sessions.has(n)&&this.subagents.has(t)&&this.subagentParentMap.set(t,n)},getAgentParentSessionId(e){return this.subagentParentMap.get(e)||null},setAgentParentSessionId(e,t){if(!e||!t||this.subagentParentMap.has(e))return;this.subagentParentMap.set(e,t),this.saveSubagentParentMap();const n=this.subagents.get(e);if(n){n.parentSessionId=t;const s=this.sessions.get(t);s&&(n.parentSessionName=this.getSessionName(s)),this.subagents.set(e,n)}},showHelp(){const e=document.getElementById("helpModal");e.classList.add("active"),this.activeFocusTrap=new FocusTrap(e),this.activeFocusTrap.activate()},closeHelp(){document.getElementById("helpModal").classList.remove("active"),this.activeFocusTrap&&(this.activeFocusTrap.deactivate(),this.activeFocusTrap=null)},renderShortcutSettingsList(){const e=document.getElementById("appSettingsShortcutsList");if(!e)return;const t=this.getShortcutRegistry?this.getShortcutRegistry():typeof DEFAULT_SHORTCUTS<"u"?DEFAULT_SHORTCUTS:[],n=this.readShortcutOverridesFromSettings();e.innerHTML=t.map(s=>{const o=s.displayBindings?s.displayBindings.join(" / "):(s.bindings||[]).map(d=>[...d.modifiers||[],d.key||d.code||""].join("+")).join(" / "),i=!!s.action&&Array.isArray(s.bindings),a=!!n[s.id],l=i?`<button type="button" class="shortcut-capture-btn" data-shortcut-action="capture" title="Capture new binding">Edit</button>
101
101
  <button type="button" class="shortcut-reset-btn" data-shortcut-action="reset" title="Reset to default"${a?"":" disabled"}>Reset</button>
102
102
  <input class="shortcut-enabled-checkbox" type="checkbox" ${s.disabled?"":"checked"} data-shortcut-action="toggle" title="Enable/disable">`:"";return`<div class="shortcut-setting-row${i?"":" shortcut-setting-row--fixed"}" data-shortcut-id="${escapeHtml(s.id)}">
103
103
  <label class="shortcut-setting-label">${escapeHtml(s.label)}</label>