aicodeman 1.23.2 → 1.24.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 (154) hide show
  1. package/README.md +10 -10
  2. package/README.zh-CN.md +2 -2
  3. package/dist/config/dependency-registry.d.ts.map +1 -1
  4. package/dist/config/dependency-registry.js +25 -0
  5. package/dist/config/dependency-registry.js.map +1 -1
  6. package/dist/docker-hosts.d.ts.map +1 -1
  7. package/dist/docker-hosts.js +17 -0
  8. package/dist/docker-hosts.js.map +1 -1
  9. package/dist/mux-interface.d.ts +3 -1
  10. package/dist/mux-interface.d.ts.map +1 -1
  11. package/dist/omp-transcript.d.ts +46 -0
  12. package/dist/omp-transcript.d.ts.map +1 -0
  13. package/dist/omp-transcript.js +174 -0
  14. package/dist/omp-transcript.js.map +1 -0
  15. package/dist/remote-hosts.d.ts.map +1 -1
  16. package/dist/remote-hosts.js +2 -0
  17. package/dist/remote-hosts.js.map +1 -1
  18. package/dist/services/unified-session-service.d.ts +7 -0
  19. package/dist/services/unified-session-service.d.ts.map +1 -1
  20. package/dist/services/unified-session-service.js +4 -0
  21. package/dist/services/unified-session-service.js.map +1 -1
  22. package/dist/session.d.ts +29 -1
  23. package/dist/session.d.ts.map +1 -1
  24. package/dist/session.js +119 -6
  25. package/dist/session.js.map +1 -1
  26. package/dist/tmux-manager.d.ts +2 -1
  27. package/dist/tmux-manager.d.ts.map +1 -1
  28. package/dist/tmux-manager.js +45 -5
  29. package/dist/tmux-manager.js.map +1 -1
  30. package/dist/types/session.d.ts +15 -4
  31. package/dist/types/session.d.ts.map +1 -1
  32. package/dist/types/session.js +1 -1
  33. package/dist/types/session.js.map +1 -1
  34. package/dist/utils/index.d.ts +1 -0
  35. package/dist/utils/index.d.ts.map +1 -1
  36. package/dist/utils/index.js +1 -0
  37. package/dist/utils/index.js.map +1 -1
  38. package/dist/utils/omp-cli-resolver.d.ts +50 -0
  39. package/dist/utils/omp-cli-resolver.d.ts.map +1 -0
  40. package/dist/utils/omp-cli-resolver.js +123 -0
  41. package/dist/utils/omp-cli-resolver.js.map +1 -0
  42. package/dist/utils/omp-session-resolver.d.ts +55 -0
  43. package/dist/utils/omp-session-resolver.d.ts.map +1 -0
  44. package/dist/utils/omp-session-resolver.js +195 -0
  45. package/dist/utils/omp-session-resolver.js.map +1 -0
  46. package/dist/web/public/admin-ui.js.gz +0 -0
  47. package/dist/web/public/api-client.c9b1cddc.js.gz +0 -0
  48. package/dist/web/public/{app.3734fd6f.js → app.616de349.js} +7 -7
  49. package/dist/web/public/app.616de349.js.br +0 -0
  50. package/dist/web/public/app.616de349.js.gz +0 -0
  51. package/dist/web/public/approvals-ui.js.gz +0 -0
  52. package/dist/web/public/constants.f4ea0a19.js.gz +0 -0
  53. package/dist/web/public/cron-ui.js.gz +0 -0
  54. package/dist/web/public/entrance-animations.js.gz +0 -0
  55. package/dist/web/public/home-sessions.js +1 -0
  56. package/dist/web/public/home-sessions.js.br +0 -0
  57. package/dist/web/public/home-sessions.js.gz +0 -0
  58. package/dist/web/public/i18n.9ae15b51.js.gz +0 -0
  59. package/dist/web/public/image-input.ee16ad88.js.gz +0 -0
  60. package/dist/web/public/index.html +17 -8
  61. package/dist/web/public/index.html.br +0 -0
  62. package/dist/web/public/index.html.gz +0 -0
  63. package/dist/web/public/input-cjk.87f14251.js.gz +0 -0
  64. package/dist/web/public/keyboard-accessory.0454a3e9.js.gz +0 -0
  65. package/dist/web/public/mobile-handlers.0f83a608.js.gz +0 -0
  66. package/dist/web/public/mobile-overview.js +2 -1
  67. package/dist/web/public/mobile-overview.js.br +0 -0
  68. package/dist/web/public/mobile-overview.js.gz +0 -0
  69. package/dist/web/public/mobile.87674154.css +1 -0
  70. package/dist/web/public/mobile.87674154.css.br +0 -0
  71. package/dist/web/public/mobile.87674154.css.gz +0 -0
  72. package/dist/web/public/notification-manager.5d229063.js.gz +0 -0
  73. package/dist/web/public/orchestrator-panel.js.gz +0 -0
  74. package/dist/web/public/{panels-ui.344de87d.js → panels-ui.e6e06034.js} +2 -2
  75. package/dist/web/public/panels-ui.e6e06034.js.br +0 -0
  76. package/dist/web/public/panels-ui.e6e06034.js.gz +0 -0
  77. package/dist/web/public/ralph-panel.6de2d0f8.js.gz +0 -0
  78. package/dist/web/public/ralph-wizard.13a1831e.js.gz +0 -0
  79. package/dist/web/public/readmymind-ui.js.gz +0 -0
  80. package/dist/web/public/respawn-ui.ff0dae4c.js.gz +0 -0
  81. package/dist/web/public/sanitize-html.bc7078d6.js.gz +0 -0
  82. package/dist/web/public/session-lineage.js.gz +0 -0
  83. package/dist/web/public/session-ui.c558f981.js +68 -0
  84. package/dist/web/public/session-ui.c558f981.js.br +0 -0
  85. package/dist/web/public/session-ui.c558f981.js.gz +0 -0
  86. package/dist/web/public/{settings-ui.3261b896.js → settings-ui.2a814a17.js} +1 -1
  87. package/dist/web/public/settings-ui.2a814a17.js.br +0 -0
  88. package/dist/web/public/settings-ui.2a814a17.js.gz +0 -0
  89. package/dist/web/public/styles.dd7e411f.css +1 -0
  90. package/dist/web/public/styles.dd7e411f.css.br +0 -0
  91. package/dist/web/public/styles.dd7e411f.css.gz +0 -0
  92. package/dist/web/public/subagent-windows.e6ca799f.js.gz +0 -0
  93. package/dist/web/public/sw.js.gz +0 -0
  94. package/dist/web/public/tab-rail-resize.42c24949.js.gz +0 -0
  95. package/dist/web/public/{terminal-ui.5e0c230c.js → terminal-ui.70445f81.js} +2 -2
  96. package/dist/web/public/terminal-ui.70445f81.js.br +0 -0
  97. package/dist/web/public/terminal-ui.70445f81.js.gz +0 -0
  98. package/dist/web/public/ultracode-panel.js.gz +0 -0
  99. package/dist/web/public/ultracode-windows.js.gz +0 -0
  100. package/dist/web/public/upload.html.gz +0 -0
  101. package/dist/web/public/vendor/dompurify.min.js.gz +0 -0
  102. package/dist/web/public/vendor/marked.min.js.gz +0 -0
  103. package/dist/web/public/vendor/xterm-addon-fit.min.js.gz +0 -0
  104. package/dist/web/public/vendor/xterm-addon-serialize.min.js.gz +0 -0
  105. package/dist/web/public/vendor/xterm-addon-unicode11.min.js.gz +0 -0
  106. package/dist/web/public/vendor/xterm-addon-webgl.min.js.gz +0 -0
  107. package/dist/web/public/vendor/xterm-predictive-echo.bd6882b8.js.gz +0 -0
  108. package/dist/web/public/vendor/xterm-zerolag-input.6fee72f2.js.gz +0 -0
  109. package/dist/web/public/vendor/xterm.css.gz +0 -0
  110. package/dist/web/public/vendor/xterm.min.js.gz +0 -0
  111. package/dist/web/public/voice-input.4ec670b0.js.gz +0 -0
  112. package/dist/web/public/voice-pcm-worklet.js.gz +0 -0
  113. package/dist/web/public/webview-tabs.js.gz +0 -0
  114. package/dist/web/route-helpers.d.ts +13 -1
  115. package/dist/web/route-helpers.d.ts.map +1 -1
  116. package/dist/web/route-helpers.js +32 -6
  117. package/dist/web/route-helpers.js.map +1 -1
  118. package/dist/web/routes/session-routes.d.ts +14 -1
  119. package/dist/web/routes/session-routes.d.ts.map +1 -1
  120. package/dist/web/routes/session-routes.js +121 -19
  121. package/dist/web/routes/session-routes.js.map +1 -1
  122. package/dist/web/routes/system-routes.d.ts.map +1 -1
  123. package/dist/web/routes/system-routes.js +9 -0
  124. package/dist/web/routes/system-routes.js.map +1 -1
  125. package/dist/web/schemas.d.ts +14 -0
  126. package/dist/web/schemas.d.ts.map +1 -1
  127. package/dist/web/schemas.js +29 -4
  128. package/dist/web/schemas.js.map +1 -1
  129. package/dist/web/server.d.ts.map +1 -1
  130. package/dist/web/server.js +4 -1
  131. package/dist/web/server.js.map +1 -1
  132. package/package.json +1 -1
  133. package/skills/codeman/SKILL.md +1 -1
  134. package/skills/codeman/reference/endpoints.md +12 -12
  135. package/skills/codeman/reference/messaging.md +2 -2
  136. package/skills/codeman/reference/recipes.md +1 -1
  137. package/skills/codeman/reference/verbs.md +3 -3
  138. package/dist/web/public/app.3734fd6f.js.br +0 -0
  139. package/dist/web/public/app.3734fd6f.js.gz +0 -0
  140. package/dist/web/public/mobile.cab92e3f.css +0 -1
  141. package/dist/web/public/mobile.cab92e3f.css.br +0 -0
  142. package/dist/web/public/mobile.cab92e3f.css.gz +0 -0
  143. package/dist/web/public/panels-ui.344de87d.js.br +0 -0
  144. package/dist/web/public/panels-ui.344de87d.js.gz +0 -0
  145. package/dist/web/public/session-ui.103656d3.js +0 -68
  146. package/dist/web/public/session-ui.103656d3.js.br +0 -0
  147. package/dist/web/public/session-ui.103656d3.js.gz +0 -0
  148. package/dist/web/public/settings-ui.3261b896.js.br +0 -0
  149. package/dist/web/public/settings-ui.3261b896.js.gz +0 -0
  150. package/dist/web/public/styles.0d71ea9a.css +0 -1
  151. package/dist/web/public/styles.0d71ea9a.css.br +0 -0
  152. package/dist/web/public/styles.0d71ea9a.css.gz +0 -0
  153. package/dist/web/public/terminal-ui.5e0c230c.js.br +0 -0
  154. package/dist/web/public/terminal-ui.5e0c230c.js.gz +0 -0
@@ -1,4 +1,4 @@
1
- "use strict";Object.assign(CodemanApp.prototype,{_onHookIdlePrompt(e){e.sessionId&&this.setPendingHook(e.sessionId,"idle_prompt"),this._notifySession(e.sessionId,"warning","hook-idle","Waiting for Input",e.message||"Claude is idle and waiting for a prompt")},_onHookPermissionPrompt(e){e.sessionId&&this.setPendingHook(e.sessionId,"permission_prompt");const t=e.tool?`${e.tool}${e.command?": "+e.command:e.file?": "+e.file:""}`:"";this._notifySession(e.sessionId,"critical","hook-permission","Permission Required",t||"Claude needs tool approval to continue")},_onHookElicitationDialog(e){e.sessionId&&this.setPendingHook(e.sessionId,"elicitation_dialog"),this._notifySession(e.sessionId,"critical","hook-elicitation","Question Asked",e.question||"Claude is asking a question and waiting for your answer")},_onHookElicitationComplete(e){e.sessionId&&(this.clearPendingHooks(e.sessionId,"elicitation_dialog"),this.clearPendingHooks(e.sessionId,"permission_prompt"))},_onHookElicitationResponse(e){this._onHookElicitationComplete(e)},_onHookStop(e){e.sessionId&&this.clearPendingHooks(e.sessionId),this._notifySession(e.sessionId,"info","hook-stop","Response Complete",e.reason||"Claude has finished responding")},_onHookAgentWorking(e){e.sessionId&&(this.clearPendingHooks(e.sessionId,"elicitation_dialog"),this.clearPendingHooks(e.sessionId,"permission_prompt"),this.clearPendingHooks(e.sessionId,"idle_prompt"))},_onHookTeammateIdle(e){const t=this.sessions.get(e.sessionId);this._notifySession(e.sessionId,"warning","hook-teammate-idle","Teammate Idle",`A teammate is idle in ${t?.name||e.sessionId}`)},_onHookTaskCompleted(e){const t=this.sessions.get(e.sessionId);this._notifySession(e.sessionId,"info","hook-task-completed","Task Completed",`A team task completed in ${t?.name||e.sessionId}`)},_onTunnelStarted(e){console.log("[Tunnel] Started:",e.url),this._tunnelUrl=e.url,this._dismissTunnelConnecting(),this._updateTunnelUrlDisplay(e.url),this._updateTunnelIndicator(!0),document.getElementById("welcomeOverlay")?.classList.contains("visible")?(this._updateWelcomeTunnelBtn(!0,e.url,!0),this.showToast("Tunnel active","success")):(this._updateWelcomeTunnelBtn(!0,e.url),this.showToast(`Tunnel active: ${e.url}`,"success"),this.showTunnelQR())},_onTunnelStopped(){console.log("[Tunnel] Stopped"),this._tunnelUrl=null,this._dismissTunnelConnecting(),this._updateTunnelUrlDisplay(null),this._updateWelcomeTunnelBtn(!1),this._updateTunnelIndicator(!1),this.closeTunnelPanel(),this.closeTunnelQR()},_onTunnelProgress(e){console.log("[Tunnel] Progress:",e.message);const t=document.getElementById("tunnelConnectingToast");t&&(t.innerHTML=`<span class="tunnel-spinner"></span> ${e.message}`);const n=document.getElementById("welcomeTunnelBtn");n?.classList.contains("connecting")&&(n.innerHTML=`<span class="tunnel-spinner"></span> ${e.message}`)},_onTunnelError(e){console.warn("[Tunnel] Error:",e.message),this._dismissTunnelConnecting(),this.showToast(`Tunnel error: ${e.message}`,"error");const t=document.getElementById("welcomeTunnelBtn");t&&(t.disabled=!1,t.classList.remove("connecting"))},_onTunnelQrRotated(e){if(e.svg){const t=document.getElementById("tunnelQrContainer");t&&(t.innerHTML=e.svg);const n=document.getElementById("welcomeQrInner");n&&(n.innerHTML=e.svg)}else this._refreshTunnelQrFromApi();this._resetQrCountdown()},_onTunnelQrRegenerated(e){if(e.svg){const t=document.getElementById("tunnelQrContainer");t&&(t.innerHTML=e.svg);const n=document.getElementById("welcomeQrInner");n&&(n.innerHTML=e.svg)}else this._refreshTunnelQrFromApi();this._resetQrCountdown()},_onTunnelQrAuthUsed(e){const n=(e.ua||"Unknown device").match(/Chrome|Firefox|Safari|Edge|Mobile/)?.[0]||"Browser";this.showToast(`Device authenticated via QR (${n}, ${e.ip}). Not you?`,"warning",{duration:1e4,action:{label:"Revoke All",onClick:()=>{fetch("/api/auth/revoke",{method:"POST",headers:{"Content-Type":"application/json"},body:"{}"}).then(()=>this.showToast("All sessions revoked","success")).catch(()=>this.showToast("Failed to revoke sessions","error"))}}})},registerServiceWorker(){"serviceWorker"in navigator&&navigator.serviceWorker.register("/sw.js").then(e=>{this._swRegistration=e,navigator.serviceWorker.addEventListener("message",t=>{if(t.data?.type==="notification-click"){const{sessionId:n,action:s,approvalId:o}=t.data;s?this.handleNotificationAction?.(s,o,n):n&&this.sessions.has(n)&&this.selectSession(n),window.focus()}}),e.pushManager.getSubscription().then(t=>{t&&(this._pushSubscription=t,this._updatePushUI(!0))})}).catch(()=>{})},async subscribeToPush(){if(!this._swRegistration){this.showToast("Service worker not available. HTTPS or localhost required.","error");return}try{const e=await this._apiJson("/api/push/vapid-key");if(!e)throw new Error("Failed to get VAPID key");const t=urlBase64ToUint8Array(e.publicKey),n=await this._swRegistration.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:t}),s=n.toJSON(),o=await this._apiJson("/api/push/subscribe",{method:"POST",body:{endpoint:s.endpoint,keys:s.keys,userAgent:navigator.userAgent,pushPreferences:this._buildPushPreferences()}});if(!o)throw new Error("Failed to register subscription");this._pushSubscription=n,this._pushSubscriptionId=o.id,localStorage.setItem("codeman-push-subscription-id",o.id),this._updatePushUI(!0),this.showToast("Push notifications enabled","success")}catch(e){this.showToast("Push subscription failed: "+(e.message||e),"error")}},async unsubscribeFromPush(){try{this._pushSubscription&&await this._pushSubscription.unsubscribe();const e=this._pushSubscriptionId||localStorage.getItem("codeman-push-subscription-id");e&&await fetch(`/api/push/subscribe/${e}`,{method:"DELETE"}).catch(()=>{}),this._pushSubscription=null,this._pushSubscriptionId=null,localStorage.removeItem("codeman-push-subscription-id"),this._updatePushUI(!1),this.showToast("Push notifications disabled","success")}catch(e){this.showToast("Failed to unsubscribe: "+(e.message||e),"error")}},async togglePushSubscription(){this._pushSubscription?await this.unsubscribeFromPush():await this.subscribeToPush()},async _syncPushPreferences(){const e=this._pushSubscriptionId||localStorage.getItem("codeman-push-subscription-id");if(e)try{await fetch(`/api/push/subscribe/${e}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({pushPreferences:this._buildPushPreferences()})})}catch{}},_buildPushPreferences(){const e={},t={"hook:permission_prompt":"eventPermissionPush","hook:elicitation_dialog":"eventQuestionPush","hook:idle_prompt":"eventIdlePush","hook:stop":"eventStopPush","respawn:blocked":"eventRespawnPush","session:ralphCompletionDetected":"eventRalphPush"};for(const[n,s]of Object.entries(t)){const o=document.getElementById(s);e[n]=o?o.checked:!0}return e["session:error"]=!0,e},_updatePushUI(e){const t=document.getElementById("pushSubscribeBtn"),n=document.getElementById("pushSubscriptionStatus");t&&(t.textContent=e?"Unsubscribe":"Subscribe"),n&&(n.textContent=e?"active":"off",n.classList.remove("granted","denied"),e&&n.classList.add("granted"))},openAppSettings(){const e=this.loadAppSettingsFromStorage();document.getElementById("appSettingsDisplayName").value=e.displayName||"Codeman",document.getElementById("appSettingsLanguage").value=e.language==="zh-CN"?"zh-CN":"en",document.getElementById("appSettingsClaudeMdPath").value=e.defaultClaudeMdPath||"",document.getElementById("appSettingsDefaultDir").value=e.defaultWorkingDir||"";const t=this.getDefaultSettings();document.getElementById("appSettingsRalphEnabled").checked=e.ralphTrackerEnabled??t.ralphTrackerEnabled??!1,document.getElementById("appSettingsShowFontControls").checked=e.showFontControls??t.showFontControls??!1,document.getElementById("appSettingsShowSystemStats").checked=e.showSystemStats??t.showSystemStats??!0,document.getElementById("appSettingsShowLifecycleLog").checked=e.showLifecycleLog??t.showLifecycleLog??!1,document.getElementById("appSettingsShowResponseViewer").checked=e.showResponseViewer??t.showResponseViewer??!1,document.getElementById("appSettingsShowFileViewerButton").checked=e.showFileViewerButton??t.showFileViewerButton??!0,document.getElementById("appSettingsShowAttachmentsButton").checked=e.showAttachmentsButton??t.showAttachmentsButton??!1,document.getElementById("appSettingsSkin").value=e.skin??t.skin??"daylight-blue",this._syncEntranceAnimSetting?.(),document.getElementById("appSettingsWebglRenderer").checked=e.webglRendererEnabled??t.webglRendererEnabled??!0;const n=document.getElementById("appSettingsWebglRendererItem");n&&(n.style.display=MobileDetection.getDeviceType()==="desktop"?"":"none"),document.getElementById("appSettingsShowMonitor").checked=e.showMonitor??t.showMonitor??!1,document.getElementById("appSettingsShowProjectInsights").checked=e.showProjectInsights??t.showProjectInsights??!1,document.getElementById("appSettingsShowFileBrowser").checked=e.showFileBrowser??t.showFileBrowser??!1,document.getElementById("appSettingsShowSubagents").checked=e.showSubagents??t.showSubagents??!1,document.getElementById("appSettingsShowUltracodeAgents").checked=e.showUltracodeAgents??t.showUltracodeAgents??!1,document.getElementById("appSettingsApprovalsInbox").checked=e.approvalsInboxEnabled===!0,document.getElementById("appSettingsReadMyMind").checked=e.readMyMindEnabled===!0,document.getElementById("appSettingsUltracodeFloatingWindows").checked=e.ultracodeFloatingWindows??t.ultracodeFloatingWindows??!1,document.getElementById("appSettingsShowMultiMonitorButton").checked=e.showMultiMonitorButton??t.showMultiMonitorButton??!1,document.getElementById("appSettingsShowPlanUsageLimits").checked=this.planUsageChipEnabled(e),document.getElementById("appSettingsShowRedrawButton").checked=e.showRedrawButton??t.showRedrawButton??!1,document.getElementById("appSettingsLineageLines").checked=e.sessionLineageLines??t.sessionLineageLines??!0;const s=document.getElementById("appSettingsLineageLinesItem");s&&(s.style.display=MobileDetection.getDeviceType()==="desktop"?"":"none"),document.getElementById("appSettingsMobileOverview").checked=e.mobileOverviewEnabled??t.mobileOverviewEnabled??!1;const o=document.getElementById("appSettingsMobileOverviewItem");o&&(o.style.display=MobileDetection.getDeviceType()==="mobile"?"":"none"),document.getElementById("appSettingsShowSessionButton").checked=e.showSessionButton??t.showSessionButton??!1,document.getElementById("appSettingsShowAwayDigestButton").checked=e.showAwayDigestButton??t.showAwayDigestButton??!1,document.getElementById("appSettingsShowCronButton").checked=e.showCronButton??t.showCronButton??!1;const i=document.getElementById("appSettingsGestureControlItem");i&&(i.style.display=window.__codemanGestureAvailable?"":"none"),document.getElementById("appSettingsGestureControl").checked=e.gestureControlEnabled??t.gestureControlEnabled??!1,document.getElementById("appSettingsSubagentTracking").checked=e.subagentTrackingEnabled??t.subagentTrackingEnabled??!0,document.getElementById("appSettingsSubagentActiveTabOnly").checked=e.subagentActiveTabOnly??t.subagentActiveTabOnly??!0,document.getElementById("appSettingsImageWatcherEnabled").checked=e.imageWatcherEnabled??t.imageWatcherEnabled??!1,document.getElementById("appSettingsTunnelEnabled").checked=e.tunnelEnabled??!1,this.loadTunnelStatus(),document.getElementById("appSettingsLocalEcho").checked=e.localEchoEnabled??MobileDetection.isTouchDevice(),document.getElementById("appSettingsAutoCopySelection").checked=e.autoCopySelection===!0,document.getElementById("appSettingsTerminalFont").value=e.terminalFontFamily||"",document.getElementById("appSettingsTerminalWheelLocal").checked=e.terminalWheelLocalScrollback??t.terminalWheelLocalScrollback??!1,document.getElementById("appSettingsCjkInput").checked=e.cjkInputEnabled??t.cjkInputEnabled??!1,document.getElementById("appSettingsExtendedKeyboardBar").checked=e.extendedKeyboardBar??!1,document.getElementById("appSettingsTabTwoRows").checked=e.tabTwoRows??t.tabTwoRows??!1,document.getElementById("appSettingsTabOrientation").value=e.tabOrientation??t.tabOrientation??"horizontal";const a=window.CodemanTabRail?.resolveWidth({width:e.tabRailWidth??this._defaultTabRailWidth?.()??t.tabRailWidth??256})??256;this.syncTabRailWidthSetting?.(a),document.getElementById("appSettingsTabRailDetail").value=e.tabRailDetail??t.tabRailDetail??"rich",document.getElementById("appSettingsShowTabDetachButton").checked=e.showTabDetachButton??t.showTabDetachButton??!1,document.getElementById("appSettingsSessionListLayout").value=e.sessionListLayout??t.sessionListLayout??"header";const l=this.resolveSessionSidebarFontSize(e.sessionSidebarFontSize??t.sessionSidebarFontSize);document.getElementById("appSettingsSessionSidebarFontSize").value=String(l),document.getElementById("appSettingsSessionSidebarFontSizeValue").textContent=`${l} px`;const c=document.getElementById("appSettingsClaudeMode"),d=document.getElementById("allowedToolsRow");c.value=e.claudeMode||"dangerously-skip-permissions",document.getElementById("appSettingsAllowedTools").value=e.allowedTools||"",d.style.display=c.value==="allowedTools"?"":"none",c.onchange=()=>{d.style.display=c.value==="allowedTools"?"":"none"},document.getElementById("appSettingsCodexDangerouslyBypassApprovals").checked=e.codexDangerouslyBypassApprovals??!1,document.getElementById("appSettingsCodexAnimations").checked=e.codexAnimationsEnabled??!1,this._applyCodexSettingsVisibility(),document.getElementById("appSettingsAgentTeams").checked=e.agentTeamsEnabled??!1,document.getElementById("appSettingsAgentSkill").checked=e.agentSkillEnabled??!1,document.getElementById("appSettingsWorkspaceHooks").checked=e.workspaceHooksEnabled!==!1,document.getElementById("appSettingsClaudeModel").value=e.claudeModel??"",document.getElementById("appSettingsOpusContext1m").checked=e.opusContext1mEnabled??!1,document.getElementById("appSettingsRemoteAutoReconnect").checked=e.remoteAutoReconnect??!0,document.getElementById("appSettingsThinkingEffort").value=e.thinkingEffort??"";const r=e.nice||{};document.getElementById("appSettingsNiceEnabled").checked=r.enabled??!1,document.getElementById("appSettingsNiceValue").value=r.niceValue??10,this.loadModelConfigForSettings();const u=this.notificationManager?.preferences||{};document.getElementById("appSettingsNotifEnabled").checked=u.enabled??!0,document.getElementById("appSettingsNotifBrowser").checked=u.browserNotifications??!1,document.getElementById("appSettingsNotifAudio").checked=u.audioAlerts??!1,document.getElementById("appSettingsNotifStuckMins").value=Math.round((u.stuckThresholdMs||6e5)/6e4),document.getElementById("appSettingsNotifCritical").checked=!u.muteCritical,document.getElementById("appSettingsNotifWarning").checked=!u.muteWarning,document.getElementById("appSettingsNotifInfo").checked=!u.muteInfo,document.getElementById("appSettingsPushEnabled").checked=!!this._pushSubscription,this._updatePushUI(!!this._pushSubscription);const p=u.eventTypes||{},h=p.permission_prompt||{};document.getElementById("eventPermissionEnabled").checked=h.enabled??!0,document.getElementById("eventPermissionBrowser").checked=h.browser??!0,document.getElementById("eventPermissionPush").checked=h.push??!1,document.getElementById("eventPermissionAudio").checked=h.audio??!0;const m=p.elicitation_dialog||{};document.getElementById("eventQuestionEnabled").checked=m.enabled??!0,document.getElementById("eventQuestionBrowser").checked=m.browser??!0,document.getElementById("eventQuestionPush").checked=m.push??!1,document.getElementById("eventQuestionAudio").checked=m.audio??!0;const g=p.idle_prompt||{};document.getElementById("eventIdleEnabled").checked=g.enabled??!0,document.getElementById("eventIdleBrowser").checked=g.browser??!0,document.getElementById("eventIdlePush").checked=g.push??!1,document.getElementById("eventIdleAudio").checked=g.audio??!1;const S=p.stop||{};document.getElementById("eventStopEnabled").checked=S.enabled??!1,document.getElementById("eventStopBrowser").checked=S.browser??!1,document.getElementById("eventStopPush").checked=S.push??!1,document.getElementById("eventStopAudio").checked=S.audio??!1;const b=p.respawn_cycle||{};document.getElementById("eventRespawnEnabled").checked=b.enabled??!0,document.getElementById("eventRespawnBrowser").checked=b.browser??!1,document.getElementById("eventRespawnPush").checked=b.push??!1,document.getElementById("eventRespawnAudio").checked=b.audio??!1;const E=p.ralph_complete||{};document.getElementById("eventRalphEnabled").checked=E.enabled??!0,document.getElementById("eventRalphBrowser").checked=E.browser??!0,document.getElementById("eventRalphPush").checked=E.push??!1,document.getElementById("eventRalphAudio").checked=E.audio??!0;const w=p.subagent_spawn||{};document.getElementById("eventSubagentEnabled").checked=w.enabled??!1,document.getElementById("eventSubagentBrowser").checked=w.browser??!1,document.getElementById("eventSubagentPush").checked=w.push??!1,document.getElementById("eventSubagentAudio").checked=w.audio??!1;const v=document.getElementById("notifPermissionStatus");if(v&&typeof Notification<"u"){const f=Notification.permission;v.textContent=f==="granted"?"\u2713":f==="denied"?"\u2717":"?",v.classList.remove("granted","denied"),f==="granted"?v.classList.add("granted"):f==="denied"&&v.classList.add("denied")}const y=VoiceInput._getDeepgramConfig();document.getElementById("voiceDeepgramKey").value=y.apiKey||"",document.getElementById("voiceLanguage").value=y.language||"en-US",document.getElementById("voiceKeyterms").value=y.keyterms||DEFAULT_VOICE_KEYTERMS,document.getElementById("voiceInsertMode").value=y.insertMode||"direct",document.getElementById("voiceProvider").value=y.provider||"auto",document.getElementById("appSettingsClaudeVoice").checked=e.claudeVoiceEnabled??!1;const B=document.getElementById("voiceDeepgramKey");B.type="password",document.getElementById("voiceKeyToggleBtn").textContent="Show",this._renderVoiceProviderStatus(),VoiceInput.refreshClaudeStatus().then(()=>this._renderVoiceProviderStatus()),this._initUpdatesSection(),this._initSettingsNav(),this._syncSettingsChips(),this._syncModelCards(),this._syncEffortSegment(),this.switchSettingsTab("settings-updates");const I=document.getElementById("appSettingsModal");I.classList.add("active"),this.activeFocusTrap=new FocusTrap(I),this.activeFocusTrap.activate()},_applyCodexSettingsVisibility(){const e=document.getElementById("appSettingsCodexGroup");e&&(e.style.display=window.__codemanCliAvailable?.codex===!0?"":"none")},switchSettingsTab(e){e==="settings-shortcuts"&&this.renderShortcutSettingsList?.();const t=document.getElementById("appSettingsDoc"),n=document.getElementById(e);if(t&&n&&typeof n.offsetTop=="number"){const s=document.getElementById("appSettingsJump"),o=s&&s.offsetParent?s.offsetHeight+16:6;t.scrollTop=Math.max(0,n.offsetTop-o)}this._setActiveSettingsSection(e)},_setActiveSettingsSection(e){const t=document.getElementById("appSettingsModal");if(!t||typeof t.querySelectorAll!="function")return;let n=null;t.querySelectorAll(".set-rail-item").forEach(a=>{const l=a.dataset.section===e;a.classList.toggle("active",l),l&&(n=a)}),t.querySelectorAll(".set-jump-row").forEach(a=>{a.classList.toggle("active",a.dataset.section===e)});const s=document.getElementById("appSettingsJump")?.querySelector(".set-jump-label");s&&n&&(s.textContent=n.textContent.trim());const o=document.getElementById("appSettingsJump")?.querySelector(".set-jump-ico"),i=n?.querySelector("svg");o&&i&&(o.innerHTML=i.innerHTML)},_initSettingsNav(){const e=document.getElementById("appSettingsModal"),t=document.getElementById("appSettingsDoc");if(!e||!t||typeof e.querySelectorAll!="function"||(this._buildModelCards(),this._buildEffortSegment(),this._buildSettingsJumpMenu(),e.dataset.navReady==="1"))return;e.dataset.navReady="1",e.querySelector(".set-rail-items")?.addEventListener("click",i=>{const a=i.target.closest?.(".set-rail-item");a?.dataset.section&&this.switchSettingsTab(a.dataset.section)}),document.getElementById("appSettingsJumpMenu")?.addEventListener("click",i=>{const a=i.target.closest?.(".set-jump-row");a?.dataset.section&&(this._toggleSettingsJump(!1),this.switchSettingsTab(a.dataset.section))}),document.getElementById("appSettingsJump")?.addEventListener("click",()=>this._toggleSettingsJump()),document.getElementById("appSettingsJumpVeil")?.addEventListener("click",()=>this._toggleSettingsJump(!1)),t.addEventListener("scroll",()=>{this._settingsSpyQueued||(this._settingsSpyQueued=!0,requestAnimationFrame(()=>{this._settingsSpyQueued=!1;const i=[...t.querySelectorAll(".set-section")].filter(l=>l.offsetParent!==null);if(!i.length)return;let a=i[0].id;for(const l of i)l.offsetTop-t.scrollTop<=140&&(a=l.id);this._setActiveSettingsSection(a)}))});const n=document.getElementById("appSettingsSearch");n?.addEventListener("input",()=>this._filterSettings(n.value)),e.querySelectorAll(".set-chip input").forEach(i=>{i.addEventListener("change",()=>this._syncSettingsChips())});const s=e.querySelector(".set-group-head-toggle"),o=s?.closest(".set-group-advanced");if(s&&o){const i=()=>{const a=o.classList.toggle("open");s.setAttribute("aria-expanded",a?"true":"false")};s.addEventListener("click",i),s.addEventListener("keydown",a=>{(a.key==="Enter"||a.key===" ")&&(a.preventDefault(),i())})}document.getElementById("appSettingsOpusContext1m")?.addEventListener("change",()=>this._applyModelSelection())},_buildSettingsJumpMenu(){const e=document.getElementById("appSettingsModal"),t=document.getElementById("appSettingsJumpMenu");!e||!t||(t.innerHTML="",e.querySelectorAll(".set-rail-item").forEach(n=>{const s=document.createElement("button");s.type="button",s.className="set-jump-row",s.dataset.section=n.dataset.section,s.innerHTML=n.innerHTML;const o=document.getElementById(n.dataset.section),i=o?o.querySelectorAll("input, select").length:0;if(i){const a=document.createElement("span");a.className="set-jump-count",a.textContent=String(i),s.appendChild(a)}t.appendChild(s)}))},_toggleSettingsJump(e){const t=document.getElementById("appSettingsModal");if(!t)return;const n=e===void 0?!t.classList.contains("jump-open"):e;t.classList.toggle("jump-open",n),document.getElementById("appSettingsJump")?.setAttribute("aria-expanded",n?"true":"false")},_syncSettingsChips(){document.querySelectorAll("#appSettingsModal .set-chip, #sessionOptionsModal .set-chip").forEach(e=>{e.classList.toggle("is-on",!!e.querySelector("input")?.checked)}),this._syncLayoutPreview()},_syncLayoutPreview(){const e=document.getElementById("appSettingsModal");if(!e||typeof e.querySelectorAll!="function")return;const t={header:document.getElementById("appSettingsPreviewHeader"),panel:document.getElementById("appSettingsPreviewPanels"),toolbar:document.getElementById("appSettingsPreviewToolbar"),float:document.getElementById("appSettingsPreviewFloats")};if(!t.header)return;Object.values(t).forEach(i=>{i&&(i.innerHTML="")});const n=[...e.querySelectorAll(".set-chip[data-preview]")].filter(i=>i.querySelector("input")?.checked).sort((i,a)=>(Number(i.dataset.previewOrder)||0)-(Number(a.dataset.previewOrder)||0));let s=0;for(const i of n){const a=i.dataset.preview,l=t[a];if(!l)continue;const c=i.querySelectorAll("span"),d=(c[c.length-1]?.textContent||"").trim(),r=document.createElement("span");if(r.title=d,a==="header"){const u=i.dataset.previewText;r.className=u?"set-preview-chip":"set-preview-btn",u?r.textContent=u:this._appendPreviewIcon(r,i)}else{r.className=`set-preview-${a}`,this._appendPreviewIcon(r,i);const u=document.createElement("span");u.textContent=d,r.appendChild(u)}l.appendChild(r),s++}const o=document.getElementById("appSettingsPreviewEmpty");o&&(o.hidden=s>0)},_appendPreviewIcon(e,t){const n=t.querySelector(".set-chip-ico");if(!n)return;const s=n.cloneNode(!0);s.classList.remove("set-chip-ico"),s.classList.add("set-preview-ico"),e.appendChild(s)},_buildModelCards(){const e=document.getElementById("appSettingsClaudeModel"),t=document.getElementById("appSettingsModelCards");!e||!t||t.dataset.built==="1"||!e.options||(t.innerHTML="",[...e.options].filter(n=>n.dataset.variant!=="1m").forEach(n=>{const s=document.createElement("button");s.type="button",s.className="set-modelcard",s.setAttribute("role","radio"),s.dataset.value=n.value,n.dataset.ctx==="1"&&(s.dataset.ctx="1");const o=document.createElement("span");o.className="set-mc-top";const i=document.createElement("span");i.className="set-mc-name",i.textContent=n.textContent,o.appendChild(i);const a=document.createElement("span");a.className="set-mc-dot",o.appendChild(a),s.appendChild(o);const l=document.createElement("span");if(l.className="set-mc-meta",l.textContent=n.dataset.meta||"",s.appendChild(l),n.dataset.ctx==="1"){const c=document.createElement("span");c.className="set-mc-ctx",c.textContent="1M capable",s.appendChild(c)}s.addEventListener("click",()=>{this._settingsModelBase=n.value,this._applyModelSelection()}),t.appendChild(s)}),t.dataset.built="1")},_syncModelCards(){const e=document.getElementById("appSettingsClaudeModel");if(!e)return;const t=e.value||"";if(this._settingsModelBase=t.endsWith("[1m]")?t.slice(0,-4):t,t.endsWith("[1m]")){const n=document.getElementById("appSettingsOpusContext1m");n&&(n.checked=!0)}this._applyModelSelection()},_applyModelSelection(){const e=document.getElementById("appSettingsClaudeModel"),t=document.getElementById("appSettingsModelCards");if(!e||!t)return;const n=this._settingsModelBase||"";let s=!1;t.querySelectorAll(".set-modelcard").forEach(c=>{const d=c.dataset.value===n;c.classList.toggle("selected",d),c.setAttribute("aria-checked",d?"true":"false"),d&&(s=c.dataset.ctx==="1")});const o=!!document.getElementById("appSettingsOpusContext1m")?.checked;e.value=n&&s&&o?`${n}[1m]`:n;const i=document.getElementById("appSettingsContextRow"),a=document.getElementById("appSettingsContextDesc"),l=!!n&&!s;i?.classList.toggle("set-row-disabled",l),a&&(a.textContent=l?"The selected model has no 1M variant.":n?"Available for Fable 5, Opus and Opus 4.6.":"With no model pinned, this starts new sessions on Opus with a 1M window.")},_buildEffortSegment(){const e=document.getElementById("appSettingsThinkingEffort"),t=document.getElementById("appSettingsEffortSegment");!e||!t||t.dataset.built==="1"||!e.options||(t.innerHTML="",[...e.options].forEach(n=>{const s=document.createElement("button");s.type="button",s.setAttribute("role","radio"),s.dataset.value=n.value,s.textContent=n.textContent,s.addEventListener("click",()=>{e.value=n.value,this._syncEffortSegment()}),t.appendChild(s)}),t.dataset.built="1")},_syncEffortSegment(){const e=document.getElementById("appSettingsThinkingEffort"),t=document.getElementById("appSettingsEffortSegment");!e||!t||t.querySelectorAll("button").forEach(n=>{const s=n.dataset.value===(e.value||"");n.classList.toggle("selected",s),n.setAttribute("aria-checked",s?"true":"false")})},_filterSettings(e){const t=document.getElementById("appSettingsDoc");if(!t)return;const n=(e||"").trim().toLowerCase(),s=".set-row, .set-chip, .set-modelgrid, .set-minigrid, .event-type-grid, #appSettingsShortcutsList",o=[...t.querySelectorAll(s)];let i=!1;o.forEach(l=>{if(!n){l.classList.remove("set-hit-hidden");return}const d=`${l.dataset?.search||""} ${l.textContent||""}`.toLowerCase().includes(n);l.classList.toggle("set-hit-hidden",!d),d&&(i=!0)}),t.querySelectorAll(".set-chips").forEach(l=>{const c=[...l.querySelectorAll(".set-chip")].some(d=>!d.classList.contains("set-hit-hidden"));l.classList.toggle("set-hit-hidden",!!n&&!c)}),t.querySelectorAll(".set-group").forEach(l=>{const c=[...l.querySelectorAll(s)].some(d=>!d.classList.contains("set-hit-hidden"));l.classList.toggle("set-hit-hidden",!!n&&!c),n&&c&&l.classList.add("open")}),t.querySelectorAll(".set-section").forEach(l=>{const c=[...l.querySelectorAll(".set-group")].some(d=>!d.classList.contains("set-hit-hidden"));l.classList.toggle("set-hit-hidden",!!n&&!c)}),t.querySelectorAll(".set-preview").forEach(l=>l.classList.toggle("set-hit-hidden",!!n));const a=document.getElementById("appSettingsSearchEmpty");a&&(a.hidden=!n||i),n||t.querySelectorAll(".set-group-advanced").forEach(l=>l.classList.remove("open"))},closeAppSettings(){this._toggleSettingsJump(!1),document.getElementById("appSettingsModal").classList.remove("active"),this.activeFocusTrap&&(this.activeFocusTrap.deactivate(),this.activeFocusTrap=null)},_updatePhaseText(e){return{queued:"Queued\u2026",preparing:"Preparing\u2026",stashing:"Stashing local changes\u2026",fetching:"Fetching release\u2026",checkout:"Checking out release\u2026",installing:"Installing dependencies\u2026",building:"Building\u2026",restarting:"Restarting Codeman\u2026"}[e]||e},_initUpdatesSection(){const e=this.$("updateCurrentVersion");e&&(e.textContent=(this.$("versionDisplay")?.textContent||"").trim()||"\u2014");for(const t of["updateResult","updateActionRow","updateNotes","updateProgress"]){const n=this.$(t);n&&(n.style.display="none")}this._updateCheck=null},_setUpdateResult(e){const t=this.$("updateResult");t&&(t.style.display="block",t.innerHTML=e)},_setUpdateProgress(e){const t=this.$("updateProgress");t&&(t.style.display="block",t.innerHTML=e)},async checkForUpdate(){const e=this.$("updateCheckBtn");e&&(e.disabled=!0,e.textContent="Checking\u2026");const t=await this._apiJson("/api/system/update/check");e&&(e.disabled=!1,e.textContent="Check now");const n=this.$("updateActionRow"),s=this.$("updateNotes");if(n&&(n.style.display="none"),s&&(s.style.display="none"),!t){this._setUpdateResult("Could not check for updates. Try again later.");return}this._updateCheck=t;const o=this.$("updateCurrentVersion");if(o&&t.currentVersion&&(o.textContent=`v${t.currentVersion}`),t.installKind&&t.installKind!=="git"){this._setUpdateResult(`This install can't update itself (${escapeHtml(t.installKind)}). Update with <code>npm i -g aicodeman@latest</code>.`);return}if(t.selfUpdateEnabled===!1){this._setUpdateResult("In-app updates are disabled on this server (CODEMAN_DISABLE_SELF_UPDATE=1).");return}if(t.error&&!t.updateAvailable){this._setUpdateResult(escapeHtml(t.error));return}if(t.updateAvailable&&t.latestVersion){this._setUpdateResult(`Update available: <strong>v${escapeHtml(t.latestVersion)}</strong> &nbsp;(current v${escapeHtml(t.currentVersion||"")})`);const i=this.$("updateActionLabel");i&&(i.textContent=`Update to v${t.latestVersion}`),n&&(n.style.display="flex");const a=this.$("updateNowBtn");a&&(a.disabled=!1,a.textContent="Update now"),s&&t.notes&&(s.style.display="block",s.textContent=t.notes)}else this._setUpdateResult(`You're up to date (v${escapeHtml(t.currentVersion||"")}).`)},async startSelfUpdate(){const e=this._updateCheck?.latestVersion?`v${this._updateCheck.latestVersion}`:"the latest release";if(!confirm(`Update Codeman to ${e}? The server will restart and this page will reload.`))return;const t=this.$("updateNowBtn");t&&(t.disabled=!0,t.textContent="Starting\u2026");const n=await this._apiPost("/api/system/update",{});if(!n||!n.ok){let i="Failed to start the update.";try{const a=await n.json();typeof a?.error=="string"&&a.error&&(i=a.error)}catch{}this._setUpdateProgress(`<span style="color:var(--danger,#e5534b)">${escapeHtml(i)}</span>`),t&&(t.disabled=!1,t.textContent="Update now");return}const s=this.$("updateActionRow");s&&(s.style.display="none");const o=this.$("updateNotes");o&&(o.style.display="none"),this._setUpdateProgress("Starting update\u2026"),this._pollUpdateStatus()},_stopUpdatePolling(){this._updatePollTimer&&(clearInterval(this._updatePollTimer),this._updatePollTimer=null)},_pollUpdateStatus(){this._stopUpdatePolling();const e=new Set(["completed","completed-needs-manual-restart","failed","idle"]),t=async()=>{let n=null;try{const s=await fetch("/api/system/update/status");if(s.ok){const o=await s.json();n=o&&o.success===!0?o.data:o}}catch{}if(!n){this._setUpdateProgress("\u21BB Restarting Codeman\u2026");return}if(!e.has(n.phase)){const s=n.message&&n.message.trim()?n.message.trim():this._updatePhaseText(n.phase);let o="";n.startedAt&&(o=` <span style="color:var(--text-secondary)">\xB7 ${Math.max(0,Math.round((Date.now()-n.startedAt)/1e3))}s</span>`),this._setUpdateProgress(`<span class="tunnel-spinner"></span> ${escapeHtml(s)}${o}`);return}if(this._stopUpdatePolling(),n.phase==="completed"){let s=`<span style="color:var(--success,#3fb950)">\u2713 Updated to v${escapeHtml(n.toVersion||"")}. Reloading\u2026</span>`;n.stashRef&&(s+=`<br><span style="color:var(--text-secondary)">Local changes stashed as <code>${escapeHtml(n.stashRef)}</code> \u2014 run <code>git stash pop</code> to restore.</span>`),this._setUpdateProgress(s),setTimeout(()=>location.reload(),2500)}else if(n.phase==="completed-needs-manual-restart")this._setUpdateProgress(`Update staged. Restart Codeman to apply:<br><code>${escapeHtml(n.manualRestartCommand||"restart codeman web")}</code>`);else if(n.phase==="failed"){let s=`<span style="color:var(--danger,#e5534b)">\u2717 ${escapeHtml(n.message||"Update failed")}.</span>`;n.error&&(s+=`<br><span style="color:var(--text-secondary)">${escapeHtml(n.error)}</span>`),s+='<br><span style="color:var(--text-secondary)">The previous version is still running.</span>',n.stashRef&&(s+=`<br><span style="color:var(--text-secondary)">Local changes stashed as <code>${escapeHtml(n.stashRef)}</code>.</span>`),this._setUpdateProgress(s);const o=this.$("updateNowBtn"),i=this.$("updateActionRow");o&&(o.disabled=!1,o.textContent="Try again"),i&&(i.style.display="flex")}};t(),this._updatePollTimer=setInterval(t,1500)},isCliAvailable(e){const t=window.__codemanCliAvailable;return!t||typeof t!="object"?!0:t[e]!==!1},applyWelcomeCliVisibility(){const e=[["welcomeClaudeBtn","claude"],["welcomeOpencodeBtn","opencode"],["welcomeAntigravityBtn","antigravity"],["welcomeGeminiBtn","gemini"],["welcomePiBtn","pi"],["welcomeGrokBtn","grok"],["welcomeDeepSeekBtn","deepseek"],["welcomeTunnelBtn","cloudflared"]];for(const[t,n]of e){const s=document.getElementById(t);s&&(s.style.display=this.isCliAvailable(n)?"flex":"none")}},async loadTunnelStatus(){try{const t=await(await fetch("/api/tunnel/status")).json(),n=t?.success===!0?t.data:t,s=n.running&&n.url;this._tunnelUrl=s?n.url:null,this._updateTunnelUrlDisplay(this._tunnelUrl),this._updateWelcomeTunnelBtn(!!s,this._tunnelUrl),this._updateTunnelIndicator(!!s)}catch{this._tunnelUrl=null,this._updateTunnelUrlDisplay(null),this._updateWelcomeTunnelBtn(!1),this._updateTunnelIndicator(!1)}},_updateTunnelUrlRow(e,t,n,s=""){const o=document.getElementById(e),i=document.getElementById(t);if(!(!o||!i))if(n){const a=n+s;o.style.display="",i.textContent=a,i.onclick=()=>{navigator.clipboard.writeText(a).then(()=>{this.showToast(`${s?"Upload":"Tunnel"} URL copied`,"success")})}}else o.style.display="none",i.textContent="",i.onclick=null},_updateTunnelUrlDisplay(e){this._updateTunnelUrlRow("tunnelUrlRow","tunnelUrlDisplay",e),this._updateTunnelUrlRow("tunnelUploadUrlRow","tunnelUploadUrlDisplay",e,"/upload.html")},showTunnelQR(){this.closeTunnelQR();const e=document.createElement("div");e.id="tunnelQrOverlay",e.style.cssText="position:fixed;inset:0;background:rgba(0,0,0,0.7);z-index:5000;display:flex;align-items:center;justify-content:center;cursor:pointer",e.onclick=n=>{n.target===e&&this.closeTunnelQR()};const t=document.createElement("div");t.style.cssText="background:var(--bg-card);border:1px solid var(--border);border-radius:12px;padding:24px;text-align:center;max-width:340px;width:90vw;box-shadow:var(--shadow-lg);cursor:default",t.innerHTML=`
1
+ "use strict";Object.assign(CodemanApp.prototype,{_onHookIdlePrompt(e){e.sessionId&&this.setPendingHook(e.sessionId,"idle_prompt"),this._notifySession(e.sessionId,"warning","hook-idle","Waiting for Input",e.message||"Claude is idle and waiting for a prompt")},_onHookPermissionPrompt(e){e.sessionId&&this.setPendingHook(e.sessionId,"permission_prompt");const t=e.tool?`${e.tool}${e.command?": "+e.command:e.file?": "+e.file:""}`:"";this._notifySession(e.sessionId,"critical","hook-permission","Permission Required",t||"Claude needs tool approval to continue")},_onHookElicitationDialog(e){e.sessionId&&this.setPendingHook(e.sessionId,"elicitation_dialog"),this._notifySession(e.sessionId,"critical","hook-elicitation","Question Asked",e.question||"Claude is asking a question and waiting for your answer")},_onHookElicitationComplete(e){e.sessionId&&(this.clearPendingHooks(e.sessionId,"elicitation_dialog"),this.clearPendingHooks(e.sessionId,"permission_prompt"))},_onHookElicitationResponse(e){this._onHookElicitationComplete(e)},_onHookStop(e){e.sessionId&&this.clearPendingHooks(e.sessionId),this._notifySession(e.sessionId,"info","hook-stop","Response Complete",e.reason||"Claude has finished responding")},_onHookAgentWorking(e){e.sessionId&&(this.clearPendingHooks(e.sessionId,"elicitation_dialog"),this.clearPendingHooks(e.sessionId,"permission_prompt"),this.clearPendingHooks(e.sessionId,"idle_prompt"))},_onHookTeammateIdle(e){const t=this.sessions.get(e.sessionId);this._notifySession(e.sessionId,"warning","hook-teammate-idle","Teammate Idle",`A teammate is idle in ${t?.name||e.sessionId}`)},_onHookTaskCompleted(e){const t=this.sessions.get(e.sessionId);this._notifySession(e.sessionId,"info","hook-task-completed","Task Completed",`A team task completed in ${t?.name||e.sessionId}`)},_onTunnelStarted(e){console.log("[Tunnel] Started:",e.url),this._tunnelUrl=e.url,this._dismissTunnelConnecting(),this._updateTunnelUrlDisplay(e.url),this._updateTunnelIndicator(!0),document.getElementById("welcomeOverlay")?.classList.contains("visible")?(this._updateWelcomeTunnelBtn(!0,e.url,!0),this.showToast("Tunnel active","success")):(this._updateWelcomeTunnelBtn(!0,e.url),this.showToast(`Tunnel active: ${e.url}`,"success"),this.showTunnelQR())},_onTunnelStopped(){console.log("[Tunnel] Stopped"),this._tunnelUrl=null,this._dismissTunnelConnecting(),this._updateTunnelUrlDisplay(null),this._updateWelcomeTunnelBtn(!1),this._updateTunnelIndicator(!1),this.closeTunnelPanel(),this.closeTunnelQR()},_onTunnelProgress(e){console.log("[Tunnel] Progress:",e.message);const t=document.getElementById("tunnelConnectingToast");t&&(t.innerHTML=`<span class="tunnel-spinner"></span> ${e.message}`);const n=document.getElementById("welcomeTunnelBtn");n?.classList.contains("connecting")&&(n.innerHTML=`<span class="tunnel-spinner"></span> ${e.message}`)},_onTunnelError(e){console.warn("[Tunnel] Error:",e.message),this._dismissTunnelConnecting(),this.showToast(`Tunnel error: ${e.message}`,"error");const t=document.getElementById("welcomeTunnelBtn");t&&(t.disabled=!1,t.classList.remove("connecting"))},_onTunnelQrRotated(e){if(e.svg){const t=document.getElementById("tunnelQrContainer");t&&(t.innerHTML=e.svg);const n=document.getElementById("welcomeQrInner");n&&(n.innerHTML=e.svg)}else this._refreshTunnelQrFromApi();this._resetQrCountdown()},_onTunnelQrRegenerated(e){if(e.svg){const t=document.getElementById("tunnelQrContainer");t&&(t.innerHTML=e.svg);const n=document.getElementById("welcomeQrInner");n&&(n.innerHTML=e.svg)}else this._refreshTunnelQrFromApi();this._resetQrCountdown()},_onTunnelQrAuthUsed(e){const n=(e.ua||"Unknown device").match(/Chrome|Firefox|Safari|Edge|Mobile/)?.[0]||"Browser";this.showToast(`Device authenticated via QR (${n}, ${e.ip}). Not you?`,"warning",{duration:1e4,action:{label:"Revoke All",onClick:()=>{fetch("/api/auth/revoke",{method:"POST",headers:{"Content-Type":"application/json"},body:"{}"}).then(()=>this.showToast("All sessions revoked","success")).catch(()=>this.showToast("Failed to revoke sessions","error"))}}})},registerServiceWorker(){"serviceWorker"in navigator&&navigator.serviceWorker.register("/sw.js").then(e=>{this._swRegistration=e,navigator.serviceWorker.addEventListener("message",t=>{if(t.data?.type==="notification-click"){const{sessionId:n,action:s,approvalId:o}=t.data;s?this.handleNotificationAction?.(s,o,n):n&&this.sessions.has(n)&&this.selectSession(n),window.focus()}}),e.pushManager.getSubscription().then(t=>{t&&(this._pushSubscription=t,this._updatePushUI(!0))})}).catch(()=>{})},async subscribeToPush(){if(!this._swRegistration){this.showToast("Service worker not available. HTTPS or localhost required.","error");return}try{const e=await this._apiJson("/api/push/vapid-key");if(!e)throw new Error("Failed to get VAPID key");const t=urlBase64ToUint8Array(e.publicKey),n=await this._swRegistration.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:t}),s=n.toJSON(),o=await this._apiJson("/api/push/subscribe",{method:"POST",body:{endpoint:s.endpoint,keys:s.keys,userAgent:navigator.userAgent,pushPreferences:this._buildPushPreferences()}});if(!o)throw new Error("Failed to register subscription");this._pushSubscription=n,this._pushSubscriptionId=o.id,localStorage.setItem("codeman-push-subscription-id",o.id),this._updatePushUI(!0),this.showToast("Push notifications enabled","success")}catch(e){this.showToast("Push subscription failed: "+(e.message||e),"error")}},async unsubscribeFromPush(){try{this._pushSubscription&&await this._pushSubscription.unsubscribe();const e=this._pushSubscriptionId||localStorage.getItem("codeman-push-subscription-id");e&&await fetch(`/api/push/subscribe/${e}`,{method:"DELETE"}).catch(()=>{}),this._pushSubscription=null,this._pushSubscriptionId=null,localStorage.removeItem("codeman-push-subscription-id"),this._updatePushUI(!1),this.showToast("Push notifications disabled","success")}catch(e){this.showToast("Failed to unsubscribe: "+(e.message||e),"error")}},async togglePushSubscription(){this._pushSubscription?await this.unsubscribeFromPush():await this.subscribeToPush()},async _syncPushPreferences(){const e=this._pushSubscriptionId||localStorage.getItem("codeman-push-subscription-id");if(e)try{await fetch(`/api/push/subscribe/${e}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({pushPreferences:this._buildPushPreferences()})})}catch{}},_buildPushPreferences(){const e={},t={"hook:permission_prompt":"eventPermissionPush","hook:elicitation_dialog":"eventQuestionPush","hook:idle_prompt":"eventIdlePush","hook:stop":"eventStopPush","respawn:blocked":"eventRespawnPush","session:ralphCompletionDetected":"eventRalphPush"};for(const[n,s]of Object.entries(t)){const o=document.getElementById(s);e[n]=o?o.checked:!0}return e["session:error"]=!0,e},_updatePushUI(e){const t=document.getElementById("pushSubscribeBtn"),n=document.getElementById("pushSubscriptionStatus");t&&(t.textContent=e?"Unsubscribe":"Subscribe"),n&&(n.textContent=e?"active":"off",n.classList.remove("granted","denied"),e&&n.classList.add("granted"))},openAppSettings(){const e=this.loadAppSettingsFromStorage();document.getElementById("appSettingsDisplayName").value=e.displayName||"Codeman",document.getElementById("appSettingsLanguage").value=e.language==="zh-CN"?"zh-CN":"en",document.getElementById("appSettingsClaudeMdPath").value=e.defaultClaudeMdPath||"",document.getElementById("appSettingsDefaultDir").value=e.defaultWorkingDir||"";const t=this.getDefaultSettings();document.getElementById("appSettingsRalphEnabled").checked=e.ralphTrackerEnabled??t.ralphTrackerEnabled??!1,document.getElementById("appSettingsShowFontControls").checked=e.showFontControls??t.showFontControls??!1,document.getElementById("appSettingsShowSystemStats").checked=e.showSystemStats??t.showSystemStats??!0,document.getElementById("appSettingsShowLifecycleLog").checked=e.showLifecycleLog??t.showLifecycleLog??!1,document.getElementById("appSettingsShowResponseViewer").checked=e.showResponseViewer??t.showResponseViewer??!1,document.getElementById("appSettingsShowFileViewerButton").checked=e.showFileViewerButton??t.showFileViewerButton??!0,document.getElementById("appSettingsShowAttachmentsButton").checked=e.showAttachmentsButton??t.showAttachmentsButton??!1,document.getElementById("appSettingsSkin").value=e.skin??t.skin??"daylight-blue",this._syncEntranceAnimSetting?.(),document.getElementById("appSettingsWebglRenderer").checked=e.webglRendererEnabled??t.webglRendererEnabled??!0;const n=document.getElementById("appSettingsWebglRendererItem");n&&(n.style.display=MobileDetection.getDeviceType()==="desktop"?"":"none"),document.getElementById("appSettingsShowMonitor").checked=e.showMonitor??t.showMonitor??!1,document.getElementById("appSettingsShowProjectInsights").checked=e.showProjectInsights??t.showProjectInsights??!1,document.getElementById("appSettingsShowFileBrowser").checked=e.showFileBrowser??t.showFileBrowser??!1,document.getElementById("appSettingsShowSubagents").checked=e.showSubagents??t.showSubagents??!1,document.getElementById("appSettingsShowUltracodeAgents").checked=e.showUltracodeAgents??t.showUltracodeAgents??!1,document.getElementById("appSettingsApprovalsInbox").checked=e.approvalsInboxEnabled===!0,document.getElementById("appSettingsReadMyMind").checked=e.readMyMindEnabled===!0,document.getElementById("appSettingsUltracodeFloatingWindows").checked=e.ultracodeFloatingWindows??t.ultracodeFloatingWindows??!1,document.getElementById("appSettingsShowMultiMonitorButton").checked=e.showMultiMonitorButton??t.showMultiMonitorButton??!1,document.getElementById("appSettingsShowPlanUsageLimits").checked=this.planUsageChipEnabled(e),document.getElementById("appSettingsShowRedrawButton").checked=e.showRedrawButton??t.showRedrawButton??!1,document.getElementById("appSettingsLineageLines").checked=e.sessionLineageLines??t.sessionLineageLines??!0;const s=document.getElementById("appSettingsLineageLinesItem");s&&(s.style.display=MobileDetection.getDeviceType()==="desktop"?"":"none"),document.getElementById("appSettingsMobileOverview").checked=e.mobileOverviewEnabled??t.mobileOverviewEnabled??!1;const o=document.getElementById("appSettingsMobileOverviewItem");o&&(o.style.display=MobileDetection.getDeviceType()==="mobile"?"":"none"),document.getElementById("appSettingsShowSessionButton").checked=e.showSessionButton??t.showSessionButton??!1,document.getElementById("appSettingsShowAwayDigestButton").checked=e.showAwayDigestButton??t.showAwayDigestButton??!1,document.getElementById("appSettingsShowCronButton").checked=e.showCronButton??t.showCronButton??!1;const i=document.getElementById("appSettingsGestureControlItem");i&&(i.style.display=window.__codemanGestureAvailable?"":"none"),document.getElementById("appSettingsGestureControl").checked=e.gestureControlEnabled??t.gestureControlEnabled??!1,document.getElementById("appSettingsSubagentTracking").checked=e.subagentTrackingEnabled??t.subagentTrackingEnabled??!0,document.getElementById("appSettingsSubagentActiveTabOnly").checked=e.subagentActiveTabOnly??t.subagentActiveTabOnly??!0,document.getElementById("appSettingsImageWatcherEnabled").checked=e.imageWatcherEnabled??t.imageWatcherEnabled??!1,document.getElementById("appSettingsTunnelEnabled").checked=e.tunnelEnabled??!1,this.loadTunnelStatus(),document.getElementById("appSettingsLocalEcho").checked=e.localEchoEnabled??MobileDetection.isTouchDevice(),document.getElementById("appSettingsAutoCopySelection").checked=e.autoCopySelection===!0,document.getElementById("appSettingsTerminalFont").value=e.terminalFontFamily||"",document.getElementById("appSettingsTerminalWheelLocal").checked=e.terminalWheelLocalScrollback??t.terminalWheelLocalScrollback??!1,document.getElementById("appSettingsCjkInput").checked=e.cjkInputEnabled??t.cjkInputEnabled??!1,document.getElementById("appSettingsExtendedKeyboardBar").checked=e.extendedKeyboardBar??!1,document.getElementById("appSettingsTabTwoRows").checked=e.tabTwoRows??t.tabTwoRows??!1,document.getElementById("appSettingsTabOrientation").value=e.tabOrientation??t.tabOrientation??"horizontal";const a=window.CodemanTabRail?.resolveWidth({width:e.tabRailWidth??this._defaultTabRailWidth?.()??t.tabRailWidth??256})??256;this.syncTabRailWidthSetting?.(a),document.getElementById("appSettingsTabRailDetail").value=e.tabRailDetail??t.tabRailDetail??"rich",document.getElementById("appSettingsShowTabDetachButton").checked=e.showTabDetachButton??t.showTabDetachButton??!1,document.getElementById("appSettingsSessionListLayout").value=e.sessionListLayout??t.sessionListLayout??"header";const l=this.resolveSessionSidebarFontSize(e.sessionSidebarFontSize??t.sessionSidebarFontSize);document.getElementById("appSettingsSessionSidebarFontSize").value=String(l),document.getElementById("appSettingsSessionSidebarFontSizeValue").textContent=`${l} px`;const c=document.getElementById("appSettingsClaudeMode"),d=document.getElementById("allowedToolsRow");c.value=e.claudeMode||"dangerously-skip-permissions",document.getElementById("appSettingsAllowedTools").value=e.allowedTools||"",d.style.display=c.value==="allowedTools"?"":"none",c.onchange=()=>{d.style.display=c.value==="allowedTools"?"":"none"},document.getElementById("appSettingsCodexDangerouslyBypassApprovals").checked=e.codexDangerouslyBypassApprovals??!1,document.getElementById("appSettingsCodexAnimations").checked=e.codexAnimationsEnabled??!1,this._applyCodexSettingsVisibility(),document.getElementById("appSettingsAgentTeams").checked=e.agentTeamsEnabled??!1,document.getElementById("appSettingsAgentSkill").checked=e.agentSkillEnabled??!1,document.getElementById("appSettingsWorkspaceHooks").checked=e.workspaceHooksEnabled!==!1,document.getElementById("appSettingsClaudeModel").value=e.claudeModel??"",document.getElementById("appSettingsOpusContext1m").checked=e.opusContext1mEnabled??!1,document.getElementById("appSettingsRemoteAutoReconnect").checked=e.remoteAutoReconnect??!0,document.getElementById("appSettingsThinkingEffort").value=e.thinkingEffort??"";const r=e.nice||{};document.getElementById("appSettingsNiceEnabled").checked=r.enabled??!1,document.getElementById("appSettingsNiceValue").value=r.niceValue??10,this.loadModelConfigForSettings();const u=this.notificationManager?.preferences||{};document.getElementById("appSettingsNotifEnabled").checked=u.enabled??!0,document.getElementById("appSettingsNotifBrowser").checked=u.browserNotifications??!1,document.getElementById("appSettingsNotifAudio").checked=u.audioAlerts??!1,document.getElementById("appSettingsNotifStuckMins").value=Math.round((u.stuckThresholdMs||6e5)/6e4),document.getElementById("appSettingsNotifCritical").checked=!u.muteCritical,document.getElementById("appSettingsNotifWarning").checked=!u.muteWarning,document.getElementById("appSettingsNotifInfo").checked=!u.muteInfo,document.getElementById("appSettingsPushEnabled").checked=!!this._pushSubscription,this._updatePushUI(!!this._pushSubscription);const p=u.eventTypes||{},h=p.permission_prompt||{};document.getElementById("eventPermissionEnabled").checked=h.enabled??!0,document.getElementById("eventPermissionBrowser").checked=h.browser??!0,document.getElementById("eventPermissionPush").checked=h.push??!1,document.getElementById("eventPermissionAudio").checked=h.audio??!0;const m=p.elicitation_dialog||{};document.getElementById("eventQuestionEnabled").checked=m.enabled??!0,document.getElementById("eventQuestionBrowser").checked=m.browser??!0,document.getElementById("eventQuestionPush").checked=m.push??!1,document.getElementById("eventQuestionAudio").checked=m.audio??!0;const g=p.idle_prompt||{};document.getElementById("eventIdleEnabled").checked=g.enabled??!0,document.getElementById("eventIdleBrowser").checked=g.browser??!0,document.getElementById("eventIdlePush").checked=g.push??!1,document.getElementById("eventIdleAudio").checked=g.audio??!1;const S=p.stop||{};document.getElementById("eventStopEnabled").checked=S.enabled??!1,document.getElementById("eventStopBrowser").checked=S.browser??!1,document.getElementById("eventStopPush").checked=S.push??!1,document.getElementById("eventStopAudio").checked=S.audio??!1;const b=p.respawn_cycle||{};document.getElementById("eventRespawnEnabled").checked=b.enabled??!0,document.getElementById("eventRespawnBrowser").checked=b.browser??!1,document.getElementById("eventRespawnPush").checked=b.push??!1,document.getElementById("eventRespawnAudio").checked=b.audio??!1;const E=p.ralph_complete||{};document.getElementById("eventRalphEnabled").checked=E.enabled??!0,document.getElementById("eventRalphBrowser").checked=E.browser??!0,document.getElementById("eventRalphPush").checked=E.push??!1,document.getElementById("eventRalphAudio").checked=E.audio??!0;const w=p.subagent_spawn||{};document.getElementById("eventSubagentEnabled").checked=w.enabled??!1,document.getElementById("eventSubagentBrowser").checked=w.browser??!1,document.getElementById("eventSubagentPush").checked=w.push??!1,document.getElementById("eventSubagentAudio").checked=w.audio??!1;const v=document.getElementById("notifPermissionStatus");if(v&&typeof Notification<"u"){const f=Notification.permission;v.textContent=f==="granted"?"\u2713":f==="denied"?"\u2717":"?",v.classList.remove("granted","denied"),f==="granted"?v.classList.add("granted"):f==="denied"&&v.classList.add("denied")}const y=VoiceInput._getDeepgramConfig();document.getElementById("voiceDeepgramKey").value=y.apiKey||"",document.getElementById("voiceLanguage").value=y.language||"en-US",document.getElementById("voiceKeyterms").value=y.keyterms||DEFAULT_VOICE_KEYTERMS,document.getElementById("voiceInsertMode").value=y.insertMode||"direct",document.getElementById("voiceProvider").value=y.provider||"auto",document.getElementById("appSettingsClaudeVoice").checked=e.claudeVoiceEnabled??!1;const B=document.getElementById("voiceDeepgramKey");B.type="password",document.getElementById("voiceKeyToggleBtn").textContent="Show",this._renderVoiceProviderStatus(),VoiceInput.refreshClaudeStatus().then(()=>this._renderVoiceProviderStatus()),this._initUpdatesSection(),this._initSettingsNav(),this._syncSettingsChips(),this._syncModelCards(),this._syncEffortSegment(),this.switchSettingsTab("settings-updates");const I=document.getElementById("appSettingsModal");I.classList.add("active"),this.activeFocusTrap=new FocusTrap(I),this.activeFocusTrap.activate()},_applyCodexSettingsVisibility(){const e=document.getElementById("appSettingsCodexGroup");e&&(e.style.display=window.__codemanCliAvailable?.codex===!0?"":"none")},switchSettingsTab(e){e==="settings-shortcuts"&&this.renderShortcutSettingsList?.();const t=document.getElementById("appSettingsDoc"),n=document.getElementById(e);if(t&&n&&typeof n.offsetTop=="number"){const s=document.getElementById("appSettingsJump"),o=s&&s.offsetParent?s.offsetHeight+16:6;t.scrollTop=Math.max(0,n.offsetTop-o)}this._setActiveSettingsSection(e)},_setActiveSettingsSection(e){const t=document.getElementById("appSettingsModal");if(!t||typeof t.querySelectorAll!="function")return;let n=null;t.querySelectorAll(".set-rail-item").forEach(a=>{const l=a.dataset.section===e;a.classList.toggle("active",l),l&&(n=a)}),t.querySelectorAll(".set-jump-row").forEach(a=>{a.classList.toggle("active",a.dataset.section===e)});const s=document.getElementById("appSettingsJump")?.querySelector(".set-jump-label");s&&n&&(s.textContent=n.textContent.trim());const o=document.getElementById("appSettingsJump")?.querySelector(".set-jump-ico"),i=n?.querySelector("svg");o&&i&&(o.innerHTML=i.innerHTML)},_initSettingsNav(){const e=document.getElementById("appSettingsModal"),t=document.getElementById("appSettingsDoc");if(!e||!t||typeof e.querySelectorAll!="function"||(this._buildModelCards(),this._buildEffortSegment(),this._buildSettingsJumpMenu(),e.dataset.navReady==="1"))return;e.dataset.navReady="1",e.querySelector(".set-rail-items")?.addEventListener("click",i=>{const a=i.target.closest?.(".set-rail-item");a?.dataset.section&&this.switchSettingsTab(a.dataset.section)}),document.getElementById("appSettingsJumpMenu")?.addEventListener("click",i=>{const a=i.target.closest?.(".set-jump-row");a?.dataset.section&&(this._toggleSettingsJump(!1),this.switchSettingsTab(a.dataset.section))}),document.getElementById("appSettingsJump")?.addEventListener("click",()=>this._toggleSettingsJump()),document.getElementById("appSettingsJumpVeil")?.addEventListener("click",()=>this._toggleSettingsJump(!1)),t.addEventListener("scroll",()=>{this._settingsSpyQueued||(this._settingsSpyQueued=!0,requestAnimationFrame(()=>{this._settingsSpyQueued=!1;const i=[...t.querySelectorAll(".set-section")].filter(l=>l.offsetParent!==null);if(!i.length)return;let a=i[0].id;for(const l of i)l.offsetTop-t.scrollTop<=140&&(a=l.id);this._setActiveSettingsSection(a)}))});const n=document.getElementById("appSettingsSearch");n?.addEventListener("input",()=>this._filterSettings(n.value)),e.querySelectorAll(".set-chip input").forEach(i=>{i.addEventListener("change",()=>this._syncSettingsChips())});const s=e.querySelector(".set-group-head-toggle"),o=s?.closest(".set-group-advanced");if(s&&o){const i=()=>{const a=o.classList.toggle("open");s.setAttribute("aria-expanded",a?"true":"false")};s.addEventListener("click",i),s.addEventListener("keydown",a=>{(a.key==="Enter"||a.key===" ")&&(a.preventDefault(),i())})}document.getElementById("appSettingsOpusContext1m")?.addEventListener("change",()=>this._applyModelSelection())},_buildSettingsJumpMenu(){const e=document.getElementById("appSettingsModal"),t=document.getElementById("appSettingsJumpMenu");!e||!t||(t.innerHTML="",e.querySelectorAll(".set-rail-item").forEach(n=>{const s=document.createElement("button");s.type="button",s.className="set-jump-row",s.dataset.section=n.dataset.section,s.innerHTML=n.innerHTML;const o=document.getElementById(n.dataset.section),i=o?o.querySelectorAll("input, select").length:0;if(i){const a=document.createElement("span");a.className="set-jump-count",a.textContent=String(i),s.appendChild(a)}t.appendChild(s)}))},_toggleSettingsJump(e){const t=document.getElementById("appSettingsModal");if(!t)return;const n=e===void 0?!t.classList.contains("jump-open"):e;t.classList.toggle("jump-open",n),document.getElementById("appSettingsJump")?.setAttribute("aria-expanded",n?"true":"false")},_syncSettingsChips(){document.querySelectorAll("#appSettingsModal .set-chip, #sessionOptionsModal .set-chip").forEach(e=>{e.classList.toggle("is-on",!!e.querySelector("input")?.checked)}),this._syncLayoutPreview()},_syncLayoutPreview(){const e=document.getElementById("appSettingsModal");if(!e||typeof e.querySelectorAll!="function")return;const t={header:document.getElementById("appSettingsPreviewHeader"),panel:document.getElementById("appSettingsPreviewPanels"),toolbar:document.getElementById("appSettingsPreviewToolbar"),float:document.getElementById("appSettingsPreviewFloats")};if(!t.header)return;Object.values(t).forEach(i=>{i&&(i.innerHTML="")});const n=[...e.querySelectorAll(".set-chip[data-preview]")].filter(i=>i.querySelector("input")?.checked).sort((i,a)=>(Number(i.dataset.previewOrder)||0)-(Number(a.dataset.previewOrder)||0));let s=0;for(const i of n){const a=i.dataset.preview,l=t[a];if(!l)continue;const c=i.querySelectorAll("span"),d=(c[c.length-1]?.textContent||"").trim(),r=document.createElement("span");if(r.title=d,a==="header"){const u=i.dataset.previewText;r.className=u?"set-preview-chip":"set-preview-btn",u?r.textContent=u:this._appendPreviewIcon(r,i)}else{r.className=`set-preview-${a}`,this._appendPreviewIcon(r,i);const u=document.createElement("span");u.textContent=d,r.appendChild(u)}l.appendChild(r),s++}const o=document.getElementById("appSettingsPreviewEmpty");o&&(o.hidden=s>0)},_appendPreviewIcon(e,t){const n=t.querySelector(".set-chip-ico");if(!n)return;const s=n.cloneNode(!0);s.classList.remove("set-chip-ico"),s.classList.add("set-preview-ico"),e.appendChild(s)},_buildModelCards(){const e=document.getElementById("appSettingsClaudeModel"),t=document.getElementById("appSettingsModelCards");!e||!t||t.dataset.built==="1"||!e.options||(t.innerHTML="",[...e.options].filter(n=>n.dataset.variant!=="1m").forEach(n=>{const s=document.createElement("button");s.type="button",s.className="set-modelcard",s.setAttribute("role","radio"),s.dataset.value=n.value,n.dataset.ctx==="1"&&(s.dataset.ctx="1");const o=document.createElement("span");o.className="set-mc-top";const i=document.createElement("span");i.className="set-mc-name",i.textContent=n.textContent,o.appendChild(i);const a=document.createElement("span");a.className="set-mc-dot",o.appendChild(a),s.appendChild(o);const l=document.createElement("span");if(l.className="set-mc-meta",l.textContent=n.dataset.meta||"",s.appendChild(l),n.dataset.ctx==="1"){const c=document.createElement("span");c.className="set-mc-ctx",c.textContent="1M capable",s.appendChild(c)}s.addEventListener("click",()=>{this._settingsModelBase=n.value,this._applyModelSelection()}),t.appendChild(s)}),t.dataset.built="1")},_syncModelCards(){const e=document.getElementById("appSettingsClaudeModel");if(!e)return;const t=e.value||"";if(this._settingsModelBase=t.endsWith("[1m]")?t.slice(0,-4):t,t.endsWith("[1m]")){const n=document.getElementById("appSettingsOpusContext1m");n&&(n.checked=!0)}this._applyModelSelection()},_applyModelSelection(){const e=document.getElementById("appSettingsClaudeModel"),t=document.getElementById("appSettingsModelCards");if(!e||!t)return;const n=this._settingsModelBase||"";let s=!1;t.querySelectorAll(".set-modelcard").forEach(c=>{const d=c.dataset.value===n;c.classList.toggle("selected",d),c.setAttribute("aria-checked",d?"true":"false"),d&&(s=c.dataset.ctx==="1")});const o=!!document.getElementById("appSettingsOpusContext1m")?.checked;e.value=n&&s&&o?`${n}[1m]`:n;const i=document.getElementById("appSettingsContextRow"),a=document.getElementById("appSettingsContextDesc"),l=!!n&&!s;i?.classList.toggle("set-row-disabled",l),a&&(a.textContent=l?"The selected model has no 1M variant.":n?"Available for Fable 5, Opus and Opus 4.6.":"With no model pinned, this starts new sessions on Opus with a 1M window.")},_buildEffortSegment(){const e=document.getElementById("appSettingsThinkingEffort"),t=document.getElementById("appSettingsEffortSegment");!e||!t||t.dataset.built==="1"||!e.options||(t.innerHTML="",[...e.options].forEach(n=>{const s=document.createElement("button");s.type="button",s.setAttribute("role","radio"),s.dataset.value=n.value,s.textContent=n.textContent,s.addEventListener("click",()=>{e.value=n.value,this._syncEffortSegment()}),t.appendChild(s)}),t.dataset.built="1")},_syncEffortSegment(){const e=document.getElementById("appSettingsThinkingEffort"),t=document.getElementById("appSettingsEffortSegment");!e||!t||t.querySelectorAll("button").forEach(n=>{const s=n.dataset.value===(e.value||"");n.classList.toggle("selected",s),n.setAttribute("aria-checked",s?"true":"false")})},_filterSettings(e){const t=document.getElementById("appSettingsDoc");if(!t)return;const n=(e||"").trim().toLowerCase(),s=".set-row, .set-chip, .set-modelgrid, .set-minigrid, .event-type-grid, #appSettingsShortcutsList",o=[...t.querySelectorAll(s)];let i=!1;o.forEach(l=>{if(!n){l.classList.remove("set-hit-hidden");return}const d=`${l.dataset?.search||""} ${l.textContent||""}`.toLowerCase().includes(n);l.classList.toggle("set-hit-hidden",!d),d&&(i=!0)}),t.querySelectorAll(".set-chips").forEach(l=>{const c=[...l.querySelectorAll(".set-chip")].some(d=>!d.classList.contains("set-hit-hidden"));l.classList.toggle("set-hit-hidden",!!n&&!c)}),t.querySelectorAll(".set-group").forEach(l=>{const c=[...l.querySelectorAll(s)].some(d=>!d.classList.contains("set-hit-hidden"));l.classList.toggle("set-hit-hidden",!!n&&!c),n&&c&&l.classList.add("open")}),t.querySelectorAll(".set-section").forEach(l=>{const c=[...l.querySelectorAll(".set-group")].some(d=>!d.classList.contains("set-hit-hidden"));l.classList.toggle("set-hit-hidden",!!n&&!c)}),t.querySelectorAll(".set-preview").forEach(l=>l.classList.toggle("set-hit-hidden",!!n));const a=document.getElementById("appSettingsSearchEmpty");a&&(a.hidden=!n||i),n||t.querySelectorAll(".set-group-advanced").forEach(l=>l.classList.remove("open"))},closeAppSettings(){this._toggleSettingsJump(!1),document.getElementById("appSettingsModal").classList.remove("active"),this.activeFocusTrap&&(this.activeFocusTrap.deactivate(),this.activeFocusTrap=null)},_updatePhaseText(e){return{queued:"Queued\u2026",preparing:"Preparing\u2026",stashing:"Stashing local changes\u2026",fetching:"Fetching release\u2026",checkout:"Checking out release\u2026",installing:"Installing dependencies\u2026",building:"Building\u2026",restarting:"Restarting Codeman\u2026"}[e]||e},_initUpdatesSection(){const e=this.$("updateCurrentVersion");e&&(e.textContent=(this.$("versionDisplay")?.textContent||"").trim()||"\u2014");for(const t of["updateResult","updateActionRow","updateNotes","updateProgress"]){const n=this.$(t);n&&(n.style.display="none")}this._updateCheck=null},_setUpdateResult(e){const t=this.$("updateResult");t&&(t.style.display="block",t.innerHTML=e)},_setUpdateProgress(e){const t=this.$("updateProgress");t&&(t.style.display="block",t.innerHTML=e)},async checkForUpdate(){const e=this.$("updateCheckBtn");e&&(e.disabled=!0,e.textContent="Checking\u2026");const t=await this._apiJson("/api/system/update/check");e&&(e.disabled=!1,e.textContent="Check now");const n=this.$("updateActionRow"),s=this.$("updateNotes");if(n&&(n.style.display="none"),s&&(s.style.display="none"),!t){this._setUpdateResult("Could not check for updates. Try again later.");return}this._updateCheck=t;const o=this.$("updateCurrentVersion");if(o&&t.currentVersion&&(o.textContent=`v${t.currentVersion}`),t.installKind&&t.installKind!=="git"){this._setUpdateResult(`This install can't update itself (${escapeHtml(t.installKind)}). Update with <code>npm i -g aicodeman@latest</code>.`);return}if(t.selfUpdateEnabled===!1){this._setUpdateResult("In-app updates are disabled on this server (CODEMAN_DISABLE_SELF_UPDATE=1).");return}if(t.error&&!t.updateAvailable){this._setUpdateResult(escapeHtml(t.error));return}if(t.updateAvailable&&t.latestVersion){this._setUpdateResult(`Update available: <strong>v${escapeHtml(t.latestVersion)}</strong> &nbsp;(current v${escapeHtml(t.currentVersion||"")})`);const i=this.$("updateActionLabel");i&&(i.textContent=`Update to v${t.latestVersion}`),n&&(n.style.display="flex");const a=this.$("updateNowBtn");a&&(a.disabled=!1,a.textContent="Update now"),s&&t.notes&&(s.style.display="block",s.textContent=t.notes)}else this._setUpdateResult(`You're up to date (v${escapeHtml(t.currentVersion||"")}).`)},async startSelfUpdate(){const e=this._updateCheck?.latestVersion?`v${this._updateCheck.latestVersion}`:"the latest release";if(!confirm(`Update Codeman to ${e}? The server will restart and this page will reload.`))return;const t=this.$("updateNowBtn");t&&(t.disabled=!0,t.textContent="Starting\u2026");const n=await this._apiPost("/api/system/update",{});if(!n||!n.ok){let i="Failed to start the update.";try{const a=await n.json();typeof a?.error=="string"&&a.error&&(i=a.error)}catch{}this._setUpdateProgress(`<span style="color:var(--danger,#e5534b)">${escapeHtml(i)}</span>`),t&&(t.disabled=!1,t.textContent="Update now");return}const s=this.$("updateActionRow");s&&(s.style.display="none");const o=this.$("updateNotes");o&&(o.style.display="none"),this._setUpdateProgress("Starting update\u2026"),this._pollUpdateStatus()},_stopUpdatePolling(){this._updatePollTimer&&(clearInterval(this._updatePollTimer),this._updatePollTimer=null)},_pollUpdateStatus(){this._stopUpdatePolling();const e=new Set(["completed","completed-needs-manual-restart","failed","idle"]),t=async()=>{let n=null;try{const s=await fetch("/api/system/update/status");if(s.ok){const o=await s.json();n=o&&o.success===!0?o.data:o}}catch{}if(!n){this._setUpdateProgress("\u21BB Restarting Codeman\u2026");return}if(!e.has(n.phase)){const s=n.message&&n.message.trim()?n.message.trim():this._updatePhaseText(n.phase);let o="";n.startedAt&&(o=` <span style="color:var(--text-secondary)">\xB7 ${Math.max(0,Math.round((Date.now()-n.startedAt)/1e3))}s</span>`),this._setUpdateProgress(`<span class="tunnel-spinner"></span> ${escapeHtml(s)}${o}`);return}if(this._stopUpdatePolling(),n.phase==="completed"){let s=`<span style="color:var(--success,#3fb950)">\u2713 Updated to v${escapeHtml(n.toVersion||"")}. Reloading\u2026</span>`;n.stashRef&&(s+=`<br><span style="color:var(--text-secondary)">Local changes stashed as <code>${escapeHtml(n.stashRef)}</code> \u2014 run <code>git stash pop</code> to restore.</span>`),this._setUpdateProgress(s),setTimeout(()=>location.reload(),2500)}else if(n.phase==="completed-needs-manual-restart")this._setUpdateProgress(`Update staged. Restart Codeman to apply:<br><code>${escapeHtml(n.manualRestartCommand||"restart codeman web")}</code>`);else if(n.phase==="failed"){let s=`<span style="color:var(--danger,#e5534b)">\u2717 ${escapeHtml(n.message||"Update failed")}.</span>`;n.error&&(s+=`<br><span style="color:var(--text-secondary)">${escapeHtml(n.error)}</span>`),s+='<br><span style="color:var(--text-secondary)">The previous version is still running.</span>',n.stashRef&&(s+=`<br><span style="color:var(--text-secondary)">Local changes stashed as <code>${escapeHtml(n.stashRef)}</code>.</span>`),this._setUpdateProgress(s);const o=this.$("updateNowBtn"),i=this.$("updateActionRow");o&&(o.disabled=!1,o.textContent="Try again"),i&&(i.style.display="flex")}};t(),this._updatePollTimer=setInterval(t,1500)},isCliAvailable(e){const t=window.__codemanCliAvailable;return!t||typeof t!="object"?!0:t[e]!==!1},applyWelcomeCliVisibility(){const e=[["welcomeClaudeBtn","claude"],["welcomeOpencodeBtn","opencode"],["welcomeAntigravityBtn","antigravity"],["welcomeOmpBtn","omp"],["welcomeGeminiBtn","gemini"],["welcomePiBtn","pi"],["welcomeGrokBtn","grok"],["welcomeDeepSeekBtn","deepseek"],["welcomeTunnelBtn","cloudflared"]];for(const[t,n]of e){const s=document.getElementById(t);s&&(s.style.display=this.isCliAvailable(n)?"flex":"none")}},async loadTunnelStatus(){try{const t=await(await fetch("/api/tunnel/status")).json(),n=t?.success===!0?t.data:t,s=n.running&&n.url;this._tunnelUrl=s?n.url:null,this._updateTunnelUrlDisplay(this._tunnelUrl),this._updateWelcomeTunnelBtn(!!s,this._tunnelUrl),this._updateTunnelIndicator(!!s)}catch{this._tunnelUrl=null,this._updateTunnelUrlDisplay(null),this._updateWelcomeTunnelBtn(!1),this._updateTunnelIndicator(!1)}},_updateTunnelUrlRow(e,t,n,s=""){const o=document.getElementById(e),i=document.getElementById(t);if(!(!o||!i))if(n){const a=n+s;o.style.display="",i.textContent=a,i.onclick=()=>{navigator.clipboard.writeText(a).then(()=>{this.showToast(`${s?"Upload":"Tunnel"} URL copied`,"success")})}}else o.style.display="none",i.textContent="",i.onclick=null},_updateTunnelUrlDisplay(e){this._updateTunnelUrlRow("tunnelUrlRow","tunnelUrlDisplay",e),this._updateTunnelUrlRow("tunnelUploadUrlRow","tunnelUploadUrlDisplay",e,"/upload.html")},showTunnelQR(){this.closeTunnelQR();const e=document.createElement("div");e.id="tunnelQrOverlay",e.style.cssText="position:fixed;inset:0;background:rgba(0,0,0,0.7);z-index:5000;display:flex;align-items:center;justify-content:center;cursor:pointer",e.onclick=n=>{n.target===e&&this.closeTunnelQR()};const t=document.createElement("div");t.style.cssText="background:var(--bg-card);border:1px solid var(--border);border-radius:12px;padding:24px;text-align:center;max-width:340px;width:90vw;box-shadow:var(--shadow-lg);cursor:default",t.innerHTML=`
2
2
  <div style="font-size:14px;font-weight:600;color:var(--text-primary);margin-bottom:16px">Scan to connect</div>
3
3
  <div id="tunnelQrContainer" style="background:#fff;border-radius:8px;padding:16px;display:inline-block">
4
4
  <div style="color:#666;font-size:12px">Loading...</div>