aicodeman 1.45.0 → 1.46.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.
- package/README.md +26 -6
- package/dist/agent-codex-identity.d.ts +26 -0
- package/dist/agent-codex-identity.d.ts.map +1 -0
- package/dist/agent-codex-identity.js +253 -0
- package/dist/agent-codex-identity.js.map +1 -0
- package/dist/agent-inspection.d.ts +32 -0
- package/dist/agent-inspection.d.ts.map +1 -0
- package/dist/agent-inspection.js +196 -0
- package/dist/agent-inspection.js.map +1 -0
- package/dist/agent-staging.d.ts +130 -0
- package/dist/agent-staging.d.ts.map +1 -0
- package/dist/agent-staging.js +312 -0
- package/dist/agent-staging.js.map +1 -0
- package/dist/cli-agent.d.ts +31 -2
- package/dist/cli-agent.d.ts.map +1 -1
- package/dist/cli-agent.js +279 -34
- package/dist/cli-agent.js.map +1 -1
- package/dist/cli-history.d.ts +20 -0
- package/dist/cli-history.d.ts.map +1 -0
- package/dist/cli-history.js +61 -0
- package/dist/cli-history.js.map +1 -0
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +6 -1
- package/dist/cli.js.map +1 -1
- package/dist/codex-rollout-format.d.ts +66 -0
- package/dist/codex-rollout-format.d.ts.map +1 -0
- package/dist/codex-rollout-format.js +111 -0
- package/dist/codex-rollout-format.js.map +1 -0
- package/dist/codex-transcript.d.ts +3 -0
- package/dist/codex-transcript.d.ts.map +1 -1
- package/dist/codex-transcript.js +13 -41
- package/dist/codex-transcript.js.map +1 -1
- package/dist/config/cli-registry/schema.d.ts +12 -7
- package/dist/config/cli-registry/schema.d.ts.map +1 -1
- package/dist/config/cli-registry/schema.js +26 -0
- package/dist/config/cli-registry/schema.js.map +1 -1
- package/dist/config/cli-registry/stock.d.ts.map +1 -1
- package/dist/config/cli-registry/stock.js +40 -1
- package/dist/config/cli-registry/stock.js.map +1 -1
- package/dist/config/cli-registry/types.d.ts +57 -0
- package/dist/config/cli-registry/types.d.ts.map +1 -1
- package/dist/config/server-timing.d.ts +6 -0
- package/dist/config/server-timing.d.ts.map +1 -1
- package/dist/config/server-timing.js +9 -0
- package/dist/config/server-timing.js.map +1 -1
- package/dist/daemon-control.d.ts +1 -0
- package/dist/daemon-control.d.ts.map +1 -1
- package/dist/daemon-control.js +2 -0
- package/dist/daemon-control.js.map +1 -1
- package/dist/deepseek-transcript.d.ts +9 -7
- package/dist/deepseek-transcript.d.ts.map +1 -1
- package/dist/deepseek-transcript.js +9 -7
- package/dist/deepseek-transcript.js.map +1 -1
- package/dist/docker-hosts.d.ts +8 -0
- package/dist/docker-hosts.d.ts.map +1 -1
- package/dist/docker-hosts.js +29 -0
- package/dist/docker-hosts.js.map +1 -1
- package/dist/git-fetch-scheduler.d.ts +124 -0
- package/dist/git-fetch-scheduler.d.ts.map +1 -0
- package/dist/git-fetch-scheduler.js +249 -0
- package/dist/git-fetch-scheduler.js.map +1 -0
- package/dist/git-fetch.d.ts +241 -0
- package/dist/git-fetch.d.ts.map +1 -0
- package/dist/git-fetch.js +392 -0
- package/dist/git-fetch.js.map +1 -0
- package/dist/git-workspace-status.d.ts +36 -1
- package/dist/git-workspace-status.d.ts.map +1 -1
- package/dist/git-workspace-status.js +42 -5
- package/dist/git-workspace-status.js.map +1 -1
- package/dist/hooks-config.d.ts +14 -2
- package/dist/hooks-config.d.ts.map +1 -1
- package/dist/hooks-config.js +39 -3
- package/dist/hooks-config.js.map +1 -1
- package/dist/local-history.d.ts +71 -0
- package/dist/local-history.d.ts.map +1 -0
- package/dist/local-history.js +750 -0
- package/dist/local-history.js.map +1 -0
- package/dist/mcp-server.d.ts.map +1 -1
- package/dist/mcp-server.js +2 -2
- package/dist/mcp-server.js.map +1 -1
- package/dist/mux-interface.d.ts +5 -2
- package/dist/mux-interface.d.ts.map +1 -1
- package/dist/prompt-cache-keepwarm.d.ts.map +1 -1
- package/dist/prompt-cache-keepwarm.js +5 -3
- package/dist/prompt-cache-keepwarm.js.map +1 -1
- package/dist/session.d.ts +113 -0
- package/dist/session.d.ts.map +1 -1
- package/dist/session.js +341 -13
- package/dist/session.js.map +1 -1
- package/dist/terminal-input-classifier.d.ts +8 -0
- package/dist/terminal-input-classifier.d.ts.map +1 -0
- package/dist/terminal-input-classifier.js +60 -0
- package/dist/terminal-input-classifier.js.map +1 -0
- package/dist/tmux-manager.d.ts +23 -1
- package/dist/tmux-manager.d.ts.map +1 -1
- package/dist/tmux-manager.js +54 -6
- package/dist/tmux-manager.js.map +1 -1
- package/dist/types/session.d.ts +15 -0
- package/dist/types/session.d.ts.map +1 -1
- package/dist/types/session.js.map +1 -1
- package/dist/web/network-auth-policy.d.ts +13 -3
- package/dist/web/network-auth-policy.d.ts.map +1 -1
- package/dist/web/network-auth-policy.js +15 -3
- package/dist/web/network-auth-policy.js.map +1 -1
- package/dist/web/ports/infra-port.d.ts +2 -0
- package/dist/web/ports/infra-port.d.ts.map +1 -1
- package/dist/web/public/admin-ui.js.gz +0 -0
- package/dist/web/public/api-client.c9b1cddc.js.gz +0 -0
- package/dist/web/public/app.3093527f.js +43 -0
- package/dist/web/public/app.3093527f.js.br +0 -0
- package/dist/web/public/app.3093527f.js.gz +0 -0
- package/dist/web/public/approvals-ui.js.gz +0 -0
- package/dist/web/public/{constants.0b3cdde9.js → constants.affcdde6.js} +611 -12
- package/dist/web/public/constants.affcdde6.js.br +0 -0
- package/dist/web/public/constants.affcdde6.js.gz +0 -0
- package/dist/web/public/cron-ui.js.gz +0 -0
- package/dist/web/public/entrance-animations.js.gz +0 -0
- package/dist/web/public/git-status-ui.js +88 -5
- package/dist/web/public/git-status-ui.js.br +0 -0
- package/dist/web/public/git-status-ui.js.gz +0 -0
- package/dist/web/public/header-divider.eb2d2463.js.gz +0 -0
- package/dist/web/public/home-sessions.js.gz +0 -0
- package/dist/web/public/host-wake-ui.js.gz +0 -0
- package/dist/web/public/i18n.70265257.js +2 -0
- package/dist/web/public/i18n.70265257.js.br +0 -0
- package/dist/web/public/i18n.70265257.js.gz +0 -0
- package/dist/web/public/image-input.941386e7.js.gz +0 -0
- package/dist/web/public/index.html +107 -16
- package/dist/web/public/index.html.br +0 -0
- package/dist/web/public/index.html.gz +0 -0
- package/dist/web/public/input-cjk.8bc46081.js.gz +0 -0
- package/dist/web/public/keyboard-accessory.4e8b20ac.js.gz +0 -0
- package/dist/web/public/{mobile-handlers.1c0cbcd8.js → mobile-handlers.f7c3f692.js} +22 -0
- package/dist/web/public/mobile-handlers.f7c3f692.js.br +0 -0
- package/dist/web/public/mobile-handlers.f7c3f692.js.gz +0 -0
- package/dist/web/public/mobile-ime-preview.2dbaf262.js.gz +0 -0
- package/dist/web/public/mobile-overview.js.gz +0 -0
- package/dist/web/public/mobile.1bbd2d67.css +1 -0
- package/dist/web/public/mobile.1bbd2d67.css.br +0 -0
- package/dist/web/public/mobile.1bbd2d67.css.gz +0 -0
- package/dist/web/public/notification-manager.feb82c04.js.gz +0 -0
- package/dist/web/public/orchestrator-panel.js.gz +0 -0
- package/dist/web/public/{panels-ui.78c3defb.js → panels-ui.4a56ee63.js} +1 -1
- package/dist/web/public/panels-ui.4a56ee63.js.br +0 -0
- package/dist/web/public/panels-ui.4a56ee63.js.gz +0 -0
- package/dist/web/public/ralph-panel.b350e2ef.js.gz +0 -0
- package/dist/web/public/ralph-wizard.b6c0dd19.js.gz +0 -0
- package/dist/web/public/readmymind-ui.js.gz +0 -0
- package/dist/web/public/reboot-restore-ui.js.gz +0 -0
- package/dist/web/public/respawn-ui.d7adcf6a.js.gz +0 -0
- package/dist/web/public/sanitize-html.e7147e76.js.gz +0 -0
- package/dist/web/public/session-lineage.js.gz +0 -0
- package/dist/web/public/{session-ui.ea6b1994.js → session-ui.186f9419.js} +8 -8
- package/dist/web/public/session-ui.186f9419.js.br +0 -0
- package/dist/web/public/session-ui.186f9419.js.gz +0 -0
- package/dist/web/public/{settings-ui.085dd202.js → settings-ui.a191154e.js} +11 -11
- package/dist/web/public/settings-ui.a191154e.js.br +0 -0
- package/dist/web/public/settings-ui.a191154e.js.gz +0 -0
- package/dist/web/public/spreadsheet-preview-worker.js.gz +0 -0
- package/dist/web/public/spreadsheet-preview.75c751de.js.gz +0 -0
- package/dist/web/public/spreadsheet-xlsx-core.js.gz +0 -0
- package/dist/web/public/styles.7238eae8.css +1 -0
- package/dist/web/public/styles.7238eae8.css.br +0 -0
- package/dist/web/public/styles.7238eae8.css.gz +0 -0
- package/dist/web/public/subagent-windows.07277a58.js.gz +0 -0
- package/dist/web/public/sw.js +2 -2
- package/dist/web/public/sw.js.br +0 -0
- package/dist/web/public/sw.js.gz +0 -0
- package/dist/web/public/tab-layout-browser.2d6189f7.js.gz +0 -0
- package/dist/web/public/{tab-rail-resize.7157e0bd.js → tab-rail-resize.b5cdceaf.js} +1 -1
- package/dist/web/public/tab-rail-resize.b5cdceaf.js.br +0 -0
- package/dist/web/public/tab-rail-resize.b5cdceaf.js.gz +0 -0
- package/dist/web/public/terminal-keycode229-recovery.af09f99a.js.gz +0 -0
- package/dist/web/public/terminal-split.js.gz +0 -0
- package/dist/web/public/terminal-tile.js +2 -0
- package/dist/web/public/terminal-tile.js.br +0 -0
- package/dist/web/public/terminal-tile.js.gz +0 -0
- package/dist/web/public/terminal-ui.7e787829.js +4 -0
- package/dist/web/public/terminal-ui.7e787829.js.br +0 -0
- package/dist/web/public/terminal-ui.7e787829.js.gz +0 -0
- package/dist/web/public/tile-grid.js.gz +0 -0
- package/dist/web/public/ultracode-panel.js.gz +0 -0
- package/dist/web/public/ultracode-windows.js.gz +0 -0
- package/dist/web/public/vendor/dompurify.min.js.gz +0 -0
- package/dist/web/public/vendor/exceljs.min.js.gz +0 -0
- package/dist/web/public/vendor/fflate.min.js.gz +0 -0
- package/dist/web/public/vendor/marked.min.js.gz +0 -0
- package/dist/web/public/vendor/xterm-addon-fit.min.js.gz +0 -0
- package/dist/web/public/vendor/xterm-addon-serialize.min.js.gz +0 -0
- package/dist/web/public/vendor/xterm-addon-unicode11.min.js.gz +0 -0
- package/dist/web/public/vendor/xterm-addon-webgl.min.js.gz +0 -0
- package/dist/web/public/vendor/{xterm-predictive-echo.ae5e3d5d.js → xterm-predictive-echo.276b11d9.js} +1 -1
- package/dist/web/public/vendor/xterm-predictive-echo.276b11d9.js.br +0 -0
- package/dist/web/public/vendor/xterm-predictive-echo.276b11d9.js.gz +0 -0
- package/dist/web/public/vendor/xterm-zerolag-input.1be42307.js +5 -0
- package/dist/web/public/vendor/xterm-zerolag-input.1be42307.js.br +0 -0
- package/dist/web/public/vendor/xterm-zerolag-input.1be42307.js.gz +0 -0
- package/dist/web/public/vendor/xterm.css.gz +0 -0
- package/dist/web/public/vendor/xterm.min.js.gz +0 -0
- package/dist/web/public/voice-input.2342c37b.js.gz +0 -0
- package/dist/web/public/voice-pcm-worklet.js.gz +0 -0
- package/dist/web/public/webview-tabs.js.gz +0 -0
- package/dist/web/public/whats-new.json +9 -9
- package/dist/web/routes/agent-session-routes.d.ts +20 -0
- package/dist/web/routes/agent-session-routes.d.ts.map +1 -0
- package/dist/web/routes/agent-session-routes.js +160 -0
- package/dist/web/routes/agent-session-routes.js.map +1 -0
- package/dist/web/routes/case-routes.d.ts.map +1 -1
- package/dist/web/routes/case-routes.js +32 -26
- package/dist/web/routes/case-routes.js.map +1 -1
- package/dist/web/routes/config-backup-routes.js +2 -2
- package/dist/web/routes/config-backup-routes.js.map +1 -1
- package/dist/web/routes/git-status-routes.d.ts +21 -7
- package/dist/web/routes/git-status-routes.d.ts.map +1 -1
- package/dist/web/routes/git-status-routes.js +78 -12
- package/dist/web/routes/git-status-routes.js.map +1 -1
- package/dist/web/routes/index.d.ts +1 -0
- package/dist/web/routes/index.d.ts.map +1 -1
- package/dist/web/routes/index.js +1 -0
- package/dist/web/routes/index.js.map +1 -1
- package/dist/web/routes/ralph-routes.d.ts.map +1 -1
- package/dist/web/routes/ralph-routes.js +7 -16
- package/dist/web/routes/ralph-routes.js.map +1 -1
- package/dist/web/routes/session-routes.d.ts.map +1 -1
- package/dist/web/routes/session-routes.js +96 -28
- package/dist/web/routes/session-routes.js.map +1 -1
- package/dist/web/routes/system-routes.d.ts.map +1 -1
- package/dist/web/routes/system-routes.js +84 -57
- package/dist/web/routes/system-routes.js.map +1 -1
- package/dist/web/routes/ws-routes.d.ts +5 -0
- package/dist/web/routes/ws-routes.d.ts.map +1 -1
- package/dist/web/routes/ws-routes.js +84 -47
- package/dist/web/routes/ws-routes.js.map +1 -1
- package/dist/web/schemas.d.ts +30 -7
- package/dist/web/schemas.d.ts.map +1 -1
- package/dist/web/schemas.js +40 -1
- package/dist/web/schemas.js.map +1 -1
- package/dist/web/server.d.ts +5 -2
- package/dist/web/server.d.ts.map +1 -1
- package/dist/web/server.js +84 -14
- package/dist/web/server.js.map +1 -1
- package/dist/web/settings-writer.d.ts +47 -0
- package/dist/web/settings-writer.d.ts.map +1 -0
- package/dist/web/settings-writer.js +110 -0
- package/dist/web/settings-writer.js.map +1 -0
- package/package.json +1 -1
- package/skills/codeman/SKILL.md +25 -6
- package/skills/codeman/reference/history.md +84 -0
- package/skills/codeman/reference/inspection-and-staging.md +152 -0
- package/skills/codeman/reference/messaging.md +1 -1
- package/skills/codeman/reference/verbs.md +18 -3
- package/dist/web/public/app.42d0abae.js +0 -43
- package/dist/web/public/app.42d0abae.js.br +0 -0
- package/dist/web/public/app.42d0abae.js.gz +0 -0
- package/dist/web/public/constants.0b3cdde9.js.br +0 -0
- package/dist/web/public/constants.0b3cdde9.js.gz +0 -0
- package/dist/web/public/i18n.1e68220d.js +0 -2
- package/dist/web/public/i18n.1e68220d.js.br +0 -0
- package/dist/web/public/i18n.1e68220d.js.gz +0 -0
- package/dist/web/public/mobile-handlers.1c0cbcd8.js.br +0 -0
- package/dist/web/public/mobile-handlers.1c0cbcd8.js.gz +0 -0
- package/dist/web/public/mobile.12fb18de.css +0 -1
- package/dist/web/public/mobile.12fb18de.css.br +0 -0
- package/dist/web/public/mobile.12fb18de.css.gz +0 -0
- package/dist/web/public/panels-ui.78c3defb.js.br +0 -0
- package/dist/web/public/panels-ui.78c3defb.js.gz +0 -0
- package/dist/web/public/session-ui.ea6b1994.js.br +0 -0
- package/dist/web/public/session-ui.ea6b1994.js.gz +0 -0
- package/dist/web/public/settings-ui.085dd202.js.br +0 -0
- package/dist/web/public/settings-ui.085dd202.js.gz +0 -0
- package/dist/web/public/styles.3b59b41d.css +0 -1
- package/dist/web/public/styles.3b59b41d.css.br +0 -0
- package/dist/web/public/styles.3b59b41d.css.gz +0 -0
- package/dist/web/public/tab-rail-resize.7157e0bd.js.br +0 -0
- package/dist/web/public/tab-rail-resize.7157e0bd.js.gz +0 -0
- package/dist/web/public/terminal-ui.fb2a27f5.js +0 -2
- package/dist/web/public/terminal-ui.fb2a27f5.js.br +0 -0
- package/dist/web/public/terminal-ui.fb2a27f5.js.gz +0 -0
- package/dist/web/public/vendor/xterm-predictive-echo.ae5e3d5d.js.br +0 -0
- package/dist/web/public/vendor/xterm-predictive-echo.ae5e3d5d.js.gz +0 -0
- package/dist/web/public/vendor/xterm-zerolag-input.0b69623c.js +0 -4
- package/dist/web/public/vendor/xterm-zerolag-input.0b69623c.js.br +0 -0
- package/dist/web/public/vendor/xterm-zerolag-input.0b69623c.js.gz +0 -0
|
@@ -1,22 +1,22 @@
|
|
|
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(`
|
|
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("appSettingsAgentCoordination").checked=e.agentCoordinationEnabled===!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,document.getElementById("appSettingsGitFetchEnabled").checked=e.gitFetchEnabled===!0,document.getElementById("appSettingsGitFetchIntervalSeconds").value=e.gitFetchIntervalSeconds??300;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("appSettingsKeyboardHoldsRows").checked=e.keyboardHoldsRows!==!1,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("appSettingsShowTabNewButton").checked=e.showTabNewButton===!0,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 h=u.eventTypes||{},f=h.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 m=h.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=h.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=h.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=h.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=h.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=h.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
|
-
`),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,
|
|
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,h)=>{const f=new Date(u.createdAt).toLocaleString(),m=u.files.map(b=>escapeHtml(b.name)).join(", "),g=escapeHtml(u.id),y=s.backups[h+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>
|
|
5
5
|
<button class="btn-toolbar btn-sm" onclick="app.showConfigDiff('${g}','current')">Compare with current</button>
|
|
6
6
|
${S}
|
|
7
|
-
<div class="set-row-desc">${
|
|
8
|
-
<button class="btn-toolbar btn-sm" onclick="app.showConfigDiff(app.$('configDiffFrom').value, app.$('configDiffTo').value)">Show changes</button></div>`:"";e.innerHTML=`<div>${s.backups.length} backup${s.backups.length===1?"":"s"} in <code>${escapeHtml(s.dir)}</code></div>${p}<ul>${r.join("")}</ul><div id="configBackupDiff"></div>`},async showConfigDiff(e,t){const n=this.$("configBackupDiff");if(!n)return;n.textContent="Comparing\u2026";const s=await this._api(`/api/config-backups/diff?from=${encodeURIComponent(e)}&to=${encodeURIComponent(t)}`);let o=null;try{o=s?await s.json():null}catch{}if(!s||!s.ok||!o||o.success===!1){n.textContent=o?.error||"Could not compare these";return}const i=c=>{if(c==="current")return"the current config";const p=(this._configBackups||[]).find(u=>u.id===c);return p?new Date(p.createdAt).toLocaleString():c},a=o.data,l={added:"added",removed:"removed",changed:"changed"},d=a.files.filter(c=>c.status!=="unchanged").map(c=>{let p;if(c.detail==="bytes")p='<div class="set-row-desc">Differs (not a key/value file, so no detail).</div>';else{const
|
|
7
|
+
<div class="set-row-desc">${m}</div></li>`}),c=u=>[`<option value="current"${u==="current"?" selected":""}>Current config</option>`].concat(s.backups.map(h=>`<option value="${escapeHtml(h.id)}"${u===h.id?" selected":""}>${escapeHtml(new Date(h.createdAt).toLocaleString())} (${escapeHtml(h.reason)})</option>`)).join(""),p=s.backups.length?`<div class="set-row-desc">Compare <select id="configDiffFrom">${c(s.backups[0].id)}</select> with <select id="configDiffTo">${c("current")}</select>
|
|
8
|
+
<button class="btn-toolbar btn-sm" onclick="app.showConfigDiff(app.$('configDiffFrom').value, app.$('configDiffTo').value)">Show changes</button></div>`:"";e.innerHTML=`<div>${s.backups.length} backup${s.backups.length===1?"":"s"} in <code>${escapeHtml(s.dir)}</code></div>${p}<ul>${r.join("")}</ul><div id="configBackupDiff"></div>`},async showConfigDiff(e,t){const n=this.$("configBackupDiff");if(!n)return;n.textContent="Comparing\u2026";const s=await this._api(`/api/config-backups/diff?from=${encodeURIComponent(e)}&to=${encodeURIComponent(t)}`);let o=null;try{o=s?await s.json():null}catch{}if(!s||!s.ok||!o||o.success===!1){n.textContent=o?.error||"Could not compare these";return}const i=c=>{if(c==="current")return"the current config";const p=(this._configBackups||[]).find(u=>u.id===c);return p?new Date(p.createdAt).toLocaleString():c},a=o.data,l={added:"added",removed:"removed",changed:"changed"},d=a.files.filter(c=>c.status!=="unchanged").map(c=>{let p;if(c.detail==="bytes")p='<div class="set-row-desc">Differs (not a key/value file, so no detail).</div>';else{const h=c.changes.map(m=>{const g=S=>`<code>${escapeHtml(S??"")}</code>`,y=m.redacted?`${l[m.kind]} <span class="set-row-desc">(value hidden: credential)</span>`:m.kind==="added"?`added ${g(m.after)}`:m.kind==="removed"?`removed (was ${g(m.before)})`:`${g(m.before)} \u2192 ${g(m.after)}`;return`<li><code>${escapeHtml(m.path)}</code>: ${y}</li>`}),f=c.truncated?'<li class="set-row-desc">More changes not shown.</li>':"";p=c.changes.length?`<ul>${h.join("")}${f}</ul>`:""}const u=c.status==="added"?" (new file)":c.status==="removed"?" (file gone)":"";return`<div><b>${escapeHtml(c.name)}</b>${u}${p}</div>`}),r=a.files.filter(c=>c.status==="unchanged").map(c=>escapeHtml(c.name));n.innerHTML=`<div><b>${escapeHtml(i(a.from))}</b> \u2192 <b>${escapeHtml(i(a.to))}</b>: ${a.changed?`${a.changed} file${a.changed===1?"":"s"} differ`:"no differences"}</div>${d.join("")}${r.length?`<div class="set-row-desc">Unchanged: ${r.join(", ")}</div>`:""}`},async backupConfigNow(){const e=this.$("configBackupNowBtn");e&&(e.disabled=!0);try{const t=await this._apiPost("/api/config-backups",{});let n=null;try{n=t?await t.json():null}catch{}!t||!t.ok||!n||n.success===!1?this.showToast(n?.error||"Backup failed","error"):n.data.status==="empty"?this.showToast("Nothing to back up yet","warning"):this.showToast(`Backed up ${n.data.files} file${n.data.files===1?"":"s"}`,"success")}finally{e&&(e.disabled=!1),this.loadConfigBackups()}},async restoreConfigBackup(e){const t=((this._configBackups||[]).find(c=>c.id===e)?.files||[]).map(c=>c.name),n=t.filter(c=>[".env","users.json","push-keys.json","custom-model-hosts.json","webhook.json"].includes(c)),s=t.length?`
|
|
9
9
|
|
|
10
10
|
Files replaced: ${t.join(", ")}`:"",o=n.length?`
|
|
11
11
|
|
|
12
|
-
This rolls back credentials and accounts (${n.join(", ")}): passwords, disabled accounts and keys return to how they were then.`:"";if(!confirm(`Restore this backup? Its files replace the current ones (a copy of the current files is made first). Some files only take effect after a restart.${s}${o}`))return;const i=await this._apiPost(`/api/config-backups/${encodeURIComponent(e)}/restore`,{});let a=null;try{a=i?await i.json():null}catch{}const l=i&&i.ok&&a&&a.success!==!1,d=a?.data;if(!l&&!Array.isArray(d?.restored)){this.showToast(a?.error||"Restore failed","error");return}const r=d.restartRequired?.length?` Restart Codeman to apply: ${d.restartRequired.join(", ")}.`:"";d.restored.includes("settings.json")&&(await this.loadAppSettingsFromServer(),this.openAppSettings()),l?this.showToast(`Restored ${d.restored.length} file${d.restored.length===1?"":"s"}.${r}`,"success"):this.showToast(`${a.error||"Restore failed partway"}.${r}`,"error"),this.loadConfigBackups()},async mcpSync(e){const t=this.$("mcpSyncResult"),n=(c,p="")=>{t&&(t.style.display="block",t.innerHTML=c,t.dataset.hint=p)};if(!this._mcpSyncSavedOn){n("Apply or Save settings to turn MCP sync on first, then preview or sync.","save-first");return}if(e&&!confirm("Add missing MCP servers to every installed, enabled CLI's config file (and GitHub Copilot CLI's, when it is installed)? Env values and headers on those servers are copied too."))return;n("Working\u2026");const s=e?await this._apiPost("/api/mcp-sync",{}):await this._api("/api/mcp-sync");let o=null;try{o=s?await s.json():null}catch{}if(!s||!s.ok||!o||o.success===!1){n(escapeHtml(o?.error||"MCP sync failed."));return}const i=o.data,a=i.targets.map(c=>{if(c.status==="absent")return`<li><b>${escapeHtml(c.label)}</b>: not installed, skipped</li>`;if(c.status==="skipped")return`<li><b>${escapeHtml(c.label)}</b>: not touched (${escapeHtml(c.error||"config location unknown")})</li>`;if(c.status==="unreadable")return`<li><b>${escapeHtml(c.label)}</b>: not touched, file can't be read safely (${escapeHtml(c.error||"unreadable")})</li>`;if(c.status==="failed")return`<li><b>${escapeHtml(c.label)}</b>: failed (${escapeHtml(c.error||"error")}); the file may be unchanged</li>`;const p=i.applied?"added":"would add",u=[c.added.length?`${p} ${c.added.map(escapeHtml).join(", ")}`:"up to date"];c.skipped.length&&u.push(`can't express ${c.skipped.map(escapeHtml).join(", ")}`);const m=`${c.servers.length} server${c.servers.length===1?"":"s"}`;return`<li><b>${escapeHtml(c.label)}</b> (${m}): ${u.join("; ")}</li>`}),l=i.conflicts.length?`<p>Defined differently across CLIs (each existing definition is kept; the first CLI's is copied where the name is missing): ${i.conflicts.map(escapeHtml).join(", ")}</p>`:"",d=i.disabled?.length?`<p>Switched off in their own CLI, so not copied: ${i.disabled.map(escapeHtml).join(", ")}</p>`:"",r=i.unsupported?.length?`<p>No MCP config support for: ${i.unsupported.map(escapeHtml).join(", ")}</p>`:"";n(`<ul>${a.join("")}</ul>${l}${d}${r}`)},_webhookSay(e,t=!1){const n=document.getElementById("webhookResult");n&&(n.textContent=e,n.style.display=e?"block":"none",n.style.color=t?"var(--danger, #e5534b)":"")},async loadWebhook(){const e=document.getElementById("webhookGroup");if(!e)return;const t=await this._api("/api/webhook");if(!t||!t.ok){this._webhookLoaded=null,e.style.display="none";return}let n=null;try{n=await t.json()}catch{}if(!n||n.success===!1){this._webhookLoaded=null,e.style.display="none";return}const s=n.data;e.style.display="",document.getElementById("webhookEnabled").checked=s.enabled===!0,document.getElementById("webhookKind").value=s.kind,document.getElementById("webhookScope").value=s.scope;const o=document.getElementById("webhookUrl");o.value="",o.placeholder=s.hasUrl?"Saved. Paste a new URL to replace it":"https://ntfy.sh/your-topic",document.getElementById("webhookUrlHint").textContent=s.hasUrl?`Saved: ${s.urlMasked}`:"Nothing saved yet.";const i=document.getElementById("webhookClearBtn");if(i&&(i.style.display=s.hasUrl?"":"none"),this._webhookLoaded={enabled:document.getElementById("webhookEnabled").checked,kind:document.getElementById("webhookKind").value,scope:document.getElementById("webhookScope").value},s.lastResult){const a=new Date(s.lastResult.at).toLocaleString();this._webhookSay(s.lastResult.ok?`Last delivery succeeded (${a}).`:`Last delivery failed (${a}): ${s.lastResult.error}`,!s.lastResult.ok)}else this._webhookSay("")},_webhookPending(){const e=document.getElementById("webhookGroup"),t=this._webhookLoaded;return!e||e.style.display==="none"||!t?!1:document.getElementById("webhookUrl").value.trim()!==""||document.getElementById("webhookEnabled").checked!==t.enabled||document.getElementById("webhookKind").value!==t.kind||document.getElementById("webhookScope").value!==t.scope},async saveWebhook(){const e={enabled:document.getElementById("webhookEnabled").checked,kind:document.getElementById("webhookKind").value,scope:document.getElementById("webhookScope").value},t=document.getElementById("webhookUrl").value.trim();t&&(e.url=t);const n=await this._api("/api/webhook",{method:"PUT",body:e});let s=null;try{s=n?await n.json():null}catch{}if(!n||!n.ok||!s||s.success===!1){const o=s?.error||"Could not save the webhook.";return this._webhookSay(o,!0),o}return await this.loadWebhook(),this._webhookSay("Saved."),""},async clearWebhook(){if(!confirm("Remove the saved webhook URL from the server? Webhook alerts stop until you save a new one."))return;const e=await this._api("/api/webhook",{method:"PUT",body:{url:"",enabled:!1}});let t=null;try{t=e?await e.json():null}catch{}if(!e||!e.ok||!t||t.success===!1){this._webhookSay(t?.error||"Could not remove the webhook URL.",!0);return}await this.loadWebhook(),this._webhookSay("Webhook URL removed.")},async testWebhook(){const e=document.getElementById("webhookTestBtn");e&&(e.disabled=!0);try{if(this._webhookPending()&&await this.saveWebhook())return;this._webhookSay("Sending\u2026");const t=await this._apiPost("/api/webhook/test",{});let n=null;try{n=t?await t.json():null}catch{}if(!t||!t.ok||!n||n.success===!1){this._webhookSay(n?.error||"Could not send the test.",!0);return}const s=n.data;this._webhookSay(s.ok?"Test sent. Check your phone or channel.":`Delivery failed: ${s.error}`,!s.ok)}finally{e&&(e.disabled=!1)}},async runDoctor(){const e=document.getElementById("doctorResult"),t=document.getElementById("doctorRunBtn");if(!e)return;const n=s=>{e.replaceChildren(document.createTextNode(s)),e.style.display="block"};t&&(t.disabled=!0),n("Checking\u2026");try{const s=await this._api("/api/doctor");let o=null;try{o=s?await s.json():null}catch{}if(!s||!s.ok||!o||o.success===!1){n(o?.error||"The check failed.");return}const{tools:i,summary:a,platform:l}=o.data,d={ok:"\u2713",missing:"\u2717",outdated:"!",error:"!",skipped:"\u2013"},r=document.createElement("ul");r.style.margin="0",r.style.paddingLeft="1.2em";for(const p of i){const u=document.createElement("li"),m=document.createElement("b"),f=p.status==="missing"&&!p.required?"\u25CB":d[p.status]||"?";m.textContent=`${f} ${p.label}`,u.append(m);const h=[p.status];if(p.version&&h.push(p.version),p.status!=="ok"&&p.status!=="skipped"&&h.push(p.required?"required":"optional"),p.reason&&h.push(p.reason),u.append(document.createTextNode(` ${h.join(" \xB7 ")}`)),p.path){const g=document.createElement("div");g.className="mono",g.textContent=p.path,u.append(g)}if(p.status==="missing"&&p.installHint){const g=document.createElement("div");g.textContent=`Install: ${p.installHint}`,u.append(g)}r.append(u)}const c=document.createElement("p");c.textContent=`${a.ok} ok \xB7 ${a.requiredMissing} required missing \xB7 ${a.optionalMissing} optional missing (${l.environment})`,e.replaceChildren(c,r),e.style.display="block"}finally{t&&(t.disabled=!1)}},_setUpdateResult(e){const t=this.$("updateResult");t&&(t.style.display="block",t.innerHTML=e)},_setUpdateProgress(e){const t=this.$("updateProgress");t&&(t.style.display="block",t.innerHTML=e)},async checkForUpdate(){const e=this.$("updateCheckBtn");e&&(e.disabled=!0,e.textContent="Checking\u2026");const t=await this._apiJson("/api/system/update/check");e&&(e.disabled=!1,e.textContent="Check now");const n=this.$("updateActionRow"),s=this.$("updateNotes");if(n&&(n.style.display="none"),s&&(s.style.display="none"),!t){this._setUpdateResult("Could not check for updates. Try again later.");return}this._updateCheck=t;const o=this.$("updateCurrentVersion");if(o&&t.currentVersion&&(o.textContent=`v${t.currentVersion}`),t.installKind&&t.installKind!=="git"&&t.installKind!=="docker-compose"){const a=t.supervisor==="docker-compose"?"Update from the Docker host with <code>docker/Start-Codeman.sh</code>.":"Update with <code>npm i -g aicodeman@latest</code>.";this._setUpdateResult(`This install can't update itself (${escapeHtml(t.installKind)}). ${a}`);return}if(t.selfUpdateEnabled===!1){this._setUpdateResult("In-app updates are disabled on this server (CODEMAN_DISABLE_SELF_UPDATE=1).");return}if(t.error&&!t.updateAvailable){this._setUpdateResult(escapeHtml(t.error));return}const i=t.environment?.blockers||[];if(t.updateAvailable&&i.length>0){const a=i.map(l=>{const d=l.details?.length?`<br><code>${escapeHtml(l.details.join(" "))}</code>`:"";return`<li>${escapeHtml(l.message)}${d}</li>`}).join("");this._setUpdateResult(`<strong>v${escapeHtml(t.latestVersion||"")}</strong> needs a rebuild on the Docker host (current v${escapeHtml(t.currentVersion||"")}):<ul>${a}</ul>Run <code>${escapeHtml(t.environment?.hostCommand||"docker/Start-Codeman.sh")}</code> there to apply it.`),s&&t.notes&&(s.style.display="block",s.textContent=t.notes);return}if(t.updateAvailable&&t.latestVersion){this._setUpdateResult(`Update available: <strong>v${escapeHtml(t.latestVersion)}</strong> (current v${escapeHtml(t.currentVersion||"")})`);const a=this.$("updateActionLabel");a&&(a.textContent=`Update to v${t.latestVersion}`),n&&(n.style.display="flex");const l=this.$("updateNowBtn");l&&(l.disabled=!1,l.textContent="Update now"),s&&t.notes&&(s.style.display="block",s.textContent=t.notes)}else this._setUpdateResult(`You're up to date (v${escapeHtml(t.currentVersion||"")}).`)},async startSelfUpdate(){const e=this._updateCheck?.latestVersion?`v${this._updateCheck.latestVersion}`:"the latest release";if(!confirm(`Update Codeman to ${e}? The server will restart and this page will reload.`))return;const t=this.$("updateNowBtn");t&&(t.disabled=!0,t.textContent="Starting\u2026");const n=await this._apiPost("/api/system/update",{});if(!n||!n.ok){let i="Failed to start the update.";try{const a=await n.json();typeof a?.error=="string"&&a.error&&(i=a.error)}catch{}this._setUpdateProgress(`<span style="color:var(--danger,#e5534b)">${escapeHtml(i)}</span>`),t&&(t.disabled=!1,t.textContent="Update now");return}const s=this.$("updateActionRow");s&&(s.style.display="none");const o=this.$("updateNotes");o&&(o.style.display="none"),this._setUpdateProgress("Starting update\u2026"),this._pollUpdateStatus()},_stopUpdatePolling(){this._updatePollTimer&&(clearInterval(this._updatePollTimer),this._updatePollTimer=null)},_pollUpdateStatus(){this._stopUpdatePolling();const e=new Set(["completed","completed-needs-manual-restart","failed","idle"]),t=async()=>{let n=null;try{const s=await fetch("/api/system/update/status");if(s.ok){const o=await s.json();n=o&&o.success===!0?o.data:o}}catch{}if(!n){this._setUpdateProgress("\u21BB Restarting Codeman\u2026");return}if(!e.has(n.phase)){const s=n.message&&n.message.trim()?n.message.trim():this._updatePhaseText(n.phase);let o="";n.startedAt&&(o=` <span style="color:var(--text-secondary)">\xB7 ${Math.max(0,Math.round((Date.now()-n.startedAt)/1e3))}s</span>`),this._setUpdateProgress(`<span class="tunnel-spinner"></span> ${escapeHtml(s)}${o}`);return}if(this._stopUpdatePolling(),n.phase==="completed"){let s=`<span style="color:var(--success,#3fb950)">\u2713 Updated to v${escapeHtml(n.toVersion||"")}. Reloading\u2026</span>`;n.stashRef&&(s+=`<br><span style="color:var(--text-secondary)">Local changes stashed as <code>${escapeHtml(n.stashRef)}</code> \u2014 run <code>git stash pop</code> to restore.</span>`),this._setUpdateProgress(s),setTimeout(()=>location.reload(),2500)}else if(n.phase==="completed-needs-manual-restart")this._setUpdateProgress(`Update staged. Restart Codeman to apply:<br><code>${escapeHtml(n.manualRestartCommand||"restart codeman web")}</code>`);else if(n.phase==="failed"){let s=`<span style="color:var(--danger,#e5534b)">\u2717 ${escapeHtml(n.message||"Update failed")}.</span>`;n.error&&(s+=`<br><span style="color:var(--text-secondary)">${escapeHtml(n.error)}</span>`),s+='<br><span style="color:var(--text-secondary)">The previous version is still running.</span>',n.stashRef&&(s+=`<br><span style="color:var(--text-secondary)">Local changes stashed as <code>${escapeHtml(n.stashRef)}</code>.</span>`),this._setUpdateProgress(s);const o=this.$("updateNowBtn"),i=this.$("updateActionRow");o&&(o.disabled=!1,o.textContent="Try again"),i&&(i.style.display="flex")}};t(),this._updatePollTimer=setInterval(t,1500)},isCliAvailable(e){const t=window.__codemanCliAvailable;return!t||typeof t!="object"?!0:t[e]!==!1},renderWelcomeCliActions(){const e=document.getElementById("welcomeCliActions");if(!e)return;const n=(Array.isArray(window.__codemanCliCatalog)?window.__codemanCliCatalog:[]).filter(u=>u.enabled&&this.isCliAvailable(u.id)),s=n.find(u=>u.kind!=="shell")||n[0],o=u=>`Run ${u.kind==="shell"?"Shell":u.label}`,i=u=>{const m=document.createElement("span");return m.className=`run-mode-dot ${u.id}`,m.setAttribute("aria-hidden","true"),m},a=u=>()=>{this.setRunMode(u.id),this.run()};if(e.replaceChildren(),!s)return;const l=document.createElement("button");l.type="button",l.className="welcome-primary",l.dataset.mode=s.id;const d=document.createElement("span");d.className="welcome-primary-logo",d.appendChild(i(s)),l.appendChild(d);const r=document.createElement("span");r.className="welcome-label",r.textContent=o(s),l.appendChild(r),l.onclick=a(s),e.appendChild(l);const c=n.filter(u=>u!==s);if(!c.length)return;const p=document.createElement("div");p.className="welcome-chips",p.setAttribute("role","group"),p.setAttribute("aria-label","More tools");for(const u of c){const m=document.createElement("button");m.type="button",m.className="welcome-chip",m.dataset.mode=u.id,m.title=o(u),m.setAttribute("aria-label",o(u)),m.appendChild(i(u));const f=document.createElement("span");f.className="welcome-label",f.textContent=u.kind==="shell"?"Shell":u.label,m.appendChild(f),m.onclick=a(u),p.appendChild(m)}e.appendChild(p)},applyWelcomeCliVisibility(){this.renderWelcomeCliActions();const e=document.getElementById("welcomeTunnelBtn");e&&(e.style.display=this.isCliAvailable("cloudflared")?"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)}},_updateTunnelUrlDisplay(e){const t=document.getElementById("tunnelUrlRow"),n=document.getElementById("tunnelUrlDisplay");!t||!n||(e?(t.style.display="",n.textContent=e,n.onclick=()=>{navigator.clipboard.writeText(e).then(()=>{this.showToast("Tunnel URL copied","success")})}):(t.style.display="none",n.textContent="",n.onclick=null))},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=`
|
|
12
|
+
This rolls back credentials and accounts (${n.join(", ")}): passwords, disabled accounts and keys return to how they were then.`:"";if(!confirm(`Restore this backup? Its files replace the current ones (a copy of the current files is made first). Some files only take effect after a restart.${s}${o}`))return;const i=await this._apiPost(`/api/config-backups/${encodeURIComponent(e)}/restore`,{});let a=null;try{a=i?await i.json():null}catch{}const l=i&&i.ok&&a&&a.success!==!1,d=a?.data;if(!l&&!Array.isArray(d?.restored)){this.showToast(a?.error||"Restore failed","error");return}const r=d.restartRequired?.length?` Restart Codeman to apply: ${d.restartRequired.join(", ")}.`:"";d.restored.includes("settings.json")&&(await this.loadAppSettingsFromServer(),this.openAppSettings()),l?this.showToast(`Restored ${d.restored.length} file${d.restored.length===1?"":"s"}.${r}`,"success"):this.showToast(`${a.error||"Restore failed partway"}.${r}`,"error"),this.loadConfigBackups()},async mcpSync(e){const t=this.$("mcpSyncResult"),n=(c,p="")=>{t&&(t.style.display="block",t.innerHTML=c,t.dataset.hint=p)};if(!this._mcpSyncSavedOn){n("Apply or Save settings to turn MCP sync on first, then preview or sync.","save-first");return}if(e&&!confirm("Add missing MCP servers to every installed, enabled CLI's config file (and GitHub Copilot CLI's, when it is installed)? Env values and headers on those servers are copied too."))return;n("Working\u2026");const s=e?await this._apiPost("/api/mcp-sync",{}):await this._api("/api/mcp-sync");let o=null;try{o=s?await s.json():null}catch{}if(!s||!s.ok||!o||o.success===!1){n(escapeHtml(o?.error||"MCP sync failed."));return}const i=o.data,a=i.targets.map(c=>{if(c.status==="absent")return`<li><b>${escapeHtml(c.label)}</b>: not installed, skipped</li>`;if(c.status==="skipped")return`<li><b>${escapeHtml(c.label)}</b>: not touched (${escapeHtml(c.error||"config location unknown")})</li>`;if(c.status==="unreadable")return`<li><b>${escapeHtml(c.label)}</b>: not touched, file can't be read safely (${escapeHtml(c.error||"unreadable")})</li>`;if(c.status==="failed")return`<li><b>${escapeHtml(c.label)}</b>: failed (${escapeHtml(c.error||"error")}); the file may be unchanged</li>`;const p=i.applied?"added":"would add",u=[c.added.length?`${p} ${c.added.map(escapeHtml).join(", ")}`:"up to date"];c.skipped.length&&u.push(`can't express ${c.skipped.map(escapeHtml).join(", ")}`);const h=`${c.servers.length} server${c.servers.length===1?"":"s"}`;return`<li><b>${escapeHtml(c.label)}</b> (${h}): ${u.join("; ")}</li>`}),l=i.conflicts.length?`<p>Defined differently across CLIs (each existing definition is kept; the first CLI's is copied where the name is missing): ${i.conflicts.map(escapeHtml).join(", ")}</p>`:"",d=i.disabled?.length?`<p>Switched off in their own CLI, so not copied: ${i.disabled.map(escapeHtml).join(", ")}</p>`:"",r=i.unsupported?.length?`<p>No MCP config support for: ${i.unsupported.map(escapeHtml).join(", ")}</p>`:"";n(`<ul>${a.join("")}</ul>${l}${d}${r}`)},_webhookSay(e,t=!1){const n=document.getElementById("webhookResult");n&&(n.textContent=e,n.style.display=e?"block":"none",n.style.color=t?"var(--danger, #e5534b)":"")},async loadWebhook(){const e=document.getElementById("webhookGroup");if(!e)return;const t=await this._api("/api/webhook");if(!t||!t.ok){this._webhookLoaded=null,e.style.display="none";return}let n=null;try{n=await t.json()}catch{}if(!n||n.success===!1){this._webhookLoaded=null,e.style.display="none";return}const s=n.data;e.style.display="",document.getElementById("webhookEnabled").checked=s.enabled===!0,document.getElementById("webhookKind").value=s.kind,document.getElementById("webhookScope").value=s.scope;const o=document.getElementById("webhookUrl");o.value="",o.placeholder=s.hasUrl?"Saved. Paste a new URL to replace it":"https://ntfy.sh/your-topic",document.getElementById("webhookUrlHint").textContent=s.hasUrl?`Saved: ${s.urlMasked}`:"Nothing saved yet.";const i=document.getElementById("webhookClearBtn");if(i&&(i.style.display=s.hasUrl?"":"none"),this._webhookLoaded={enabled:document.getElementById("webhookEnabled").checked,kind:document.getElementById("webhookKind").value,scope:document.getElementById("webhookScope").value},s.lastResult){const a=new Date(s.lastResult.at).toLocaleString();this._webhookSay(s.lastResult.ok?`Last delivery succeeded (${a}).`:`Last delivery failed (${a}): ${s.lastResult.error}`,!s.lastResult.ok)}else this._webhookSay("")},_webhookPending(){const e=document.getElementById("webhookGroup"),t=this._webhookLoaded;return!e||e.style.display==="none"||!t?!1:document.getElementById("webhookUrl").value.trim()!==""||document.getElementById("webhookEnabled").checked!==t.enabled||document.getElementById("webhookKind").value!==t.kind||document.getElementById("webhookScope").value!==t.scope},async saveWebhook(){const e={enabled:document.getElementById("webhookEnabled").checked,kind:document.getElementById("webhookKind").value,scope:document.getElementById("webhookScope").value},t=document.getElementById("webhookUrl").value.trim();t&&(e.url=t);const n=await this._api("/api/webhook",{method:"PUT",body:e});let s=null;try{s=n?await n.json():null}catch{}if(!n||!n.ok||!s||s.success===!1){const o=s?.error||"Could not save the webhook.";return this._webhookSay(o,!0),o}return await this.loadWebhook(),this._webhookSay("Saved."),""},async clearWebhook(){if(!confirm("Remove the saved webhook URL from the server? Webhook alerts stop until you save a new one."))return;const e=await this._api("/api/webhook",{method:"PUT",body:{url:"",enabled:!1}});let t=null;try{t=e?await e.json():null}catch{}if(!e||!e.ok||!t||t.success===!1){this._webhookSay(t?.error||"Could not remove the webhook URL.",!0);return}await this.loadWebhook(),this._webhookSay("Webhook URL removed.")},async testWebhook(){const e=document.getElementById("webhookTestBtn");e&&(e.disabled=!0);try{if(this._webhookPending()&&await this.saveWebhook())return;this._webhookSay("Sending\u2026");const t=await this._apiPost("/api/webhook/test",{});let n=null;try{n=t?await t.json():null}catch{}if(!t||!t.ok||!n||n.success===!1){this._webhookSay(n?.error||"Could not send the test.",!0);return}const s=n.data;this._webhookSay(s.ok?"Test sent. Check your phone or channel.":`Delivery failed: ${s.error}`,!s.ok)}finally{e&&(e.disabled=!1)}},async runDoctor(){const e=document.getElementById("doctorResult"),t=document.getElementById("doctorRunBtn");if(!e)return;const n=s=>{e.replaceChildren(document.createTextNode(s)),e.style.display="block"};t&&(t.disabled=!0),n("Checking\u2026");try{const s=await this._api("/api/doctor");let o=null;try{o=s?await s.json():null}catch{}if(!s||!s.ok||!o||o.success===!1){n(o?.error||"The check failed.");return}const{tools:i,summary:a,platform:l}=o.data,d={ok:"\u2713",missing:"\u2717",outdated:"!",error:"!",skipped:"\u2013"},r=document.createElement("ul");r.style.margin="0",r.style.paddingLeft="1.2em";for(const p of i){const u=document.createElement("li"),h=document.createElement("b"),f=p.status==="missing"&&!p.required?"\u25CB":d[p.status]||"?";h.textContent=`${f} ${p.label}`,u.append(h);const m=[p.status];if(p.version&&m.push(p.version),p.status!=="ok"&&p.status!=="skipped"&&m.push(p.required?"required":"optional"),p.reason&&m.push(p.reason),u.append(document.createTextNode(` ${m.join(" \xB7 ")}`)),p.path){const g=document.createElement("div");g.className="mono",g.textContent=p.path,u.append(g)}if(p.status==="missing"&&p.installHint){const g=document.createElement("div");g.textContent=`Install: ${p.installHint}`,u.append(g)}r.append(u)}const c=document.createElement("p");c.textContent=`${a.ok} ok \xB7 ${a.requiredMissing} required missing \xB7 ${a.optionalMissing} optional missing (${l.environment})`,e.replaceChildren(c,r),e.style.display="block"}finally{t&&(t.disabled=!1)}},_setUpdateResult(e){const t=this.$("updateResult");t&&(t.style.display="block",t.innerHTML=e)},_setUpdateProgress(e){const t=this.$("updateProgress");t&&(t.style.display="block",t.innerHTML=e)},async checkForUpdate(){const e=this.$("updateCheckBtn");e&&(e.disabled=!0,e.textContent="Checking\u2026");const t=await this._apiJson("/api/system/update/check");e&&(e.disabled=!1,e.textContent="Check now");const n=this.$("updateActionRow"),s=this.$("updateNotes");if(n&&(n.style.display="none"),s&&(s.style.display="none"),!t){this._setUpdateResult("Could not check for updates. Try again later.");return}this._updateCheck=t;const o=this.$("updateCurrentVersion");if(o&&t.currentVersion&&(o.textContent=`v${t.currentVersion}`),t.installKind&&t.installKind!=="git"&&t.installKind!=="docker-compose"){const a=t.supervisor==="docker-compose"?"Update from the Docker host with <code>docker/Start-Codeman.sh</code>.":"Update with <code>npm i -g aicodeman@latest</code>.";this._setUpdateResult(`This install can't update itself (${escapeHtml(t.installKind)}). ${a}`);return}if(t.selfUpdateEnabled===!1){this._setUpdateResult("In-app updates are disabled on this server (CODEMAN_DISABLE_SELF_UPDATE=1).");return}if(t.error&&!t.updateAvailable){this._setUpdateResult(escapeHtml(t.error));return}const i=t.environment?.blockers||[];if(t.updateAvailable&&i.length>0){const a=i.map(l=>{const d=l.details?.length?`<br><code>${escapeHtml(l.details.join(" "))}</code>`:"";return`<li>${escapeHtml(l.message)}${d}</li>`}).join("");this._setUpdateResult(`<strong>v${escapeHtml(t.latestVersion||"")}</strong> needs a rebuild on the Docker host (current v${escapeHtml(t.currentVersion||"")}):<ul>${a}</ul>Run <code>${escapeHtml(t.environment?.hostCommand||"docker/Start-Codeman.sh")}</code> there to apply it.`),s&&t.notes&&(s.style.display="block",s.textContent=t.notes);return}if(t.updateAvailable&&t.latestVersion){this._setUpdateResult(`Update available: <strong>v${escapeHtml(t.latestVersion)}</strong> (current v${escapeHtml(t.currentVersion||"")})`);const a=this.$("updateActionLabel");a&&(a.textContent=`Update to v${t.latestVersion}`),n&&(n.style.display="flex");const l=this.$("updateNowBtn");l&&(l.disabled=!1,l.textContent="Update now"),s&&t.notes&&(s.style.display="block",s.textContent=t.notes)}else this._setUpdateResult(`You're up to date (v${escapeHtml(t.currentVersion||"")}).`)},async startSelfUpdate(){const e=this._updateCheck?.latestVersion?`v${this._updateCheck.latestVersion}`:"the latest release";if(!confirm(`Update Codeman to ${e}? The server will restart and this page will reload.`))return;const t=this.$("updateNowBtn");t&&(t.disabled=!0,t.textContent="Starting\u2026");const n=await this._apiPost("/api/system/update",{});if(!n||!n.ok){let i="Failed to start the update.";try{const a=await n.json();typeof a?.error=="string"&&a.error&&(i=a.error)}catch{}this._setUpdateProgress(`<span style="color:var(--danger,#e5534b)">${escapeHtml(i)}</span>`),t&&(t.disabled=!1,t.textContent="Update now");return}const s=this.$("updateActionRow");s&&(s.style.display="none");const o=this.$("updateNotes");o&&(o.style.display="none"),this._setUpdateProgress("Starting update\u2026"),this._pollUpdateStatus()},_stopUpdatePolling(){this._updatePollTimer&&(clearInterval(this._updatePollTimer),this._updatePollTimer=null)},_pollUpdateStatus(){this._stopUpdatePolling();const e=new Set(["completed","completed-needs-manual-restart","failed","idle"]),t=async()=>{let n=null;try{const s=await fetch("/api/system/update/status");if(s.ok){const o=await s.json();n=o&&o.success===!0?o.data:o}}catch{}if(!n){this._setUpdateProgress("\u21BB Restarting Codeman\u2026");return}if(!e.has(n.phase)){const s=n.message&&n.message.trim()?n.message.trim():this._updatePhaseText(n.phase);let o="";n.startedAt&&(o=` <span style="color:var(--text-secondary)">\xB7 ${Math.max(0,Math.round((Date.now()-n.startedAt)/1e3))}s</span>`),this._setUpdateProgress(`<span class="tunnel-spinner"></span> ${escapeHtml(s)}${o}`);return}if(this._stopUpdatePolling(),n.phase==="completed"){let s=`<span style="color:var(--success,#3fb950)">\u2713 Updated to v${escapeHtml(n.toVersion||"")}. Reloading\u2026</span>`;n.stashRef&&(s+=`<br><span style="color:var(--text-secondary)">Local changes stashed as <code>${escapeHtml(n.stashRef)}</code> \u2014 run <code>git stash pop</code> to restore.</span>`),this._setUpdateProgress(s),setTimeout(()=>location.reload(),2500)}else if(n.phase==="completed-needs-manual-restart")this._setUpdateProgress(`Update staged. Restart Codeman to apply:<br><code>${escapeHtml(n.manualRestartCommand||"restart codeman web")}</code>`);else if(n.phase==="failed"){let s=`<span style="color:var(--danger,#e5534b)">\u2717 ${escapeHtml(n.message||"Update failed")}.</span>`;n.error&&(s+=`<br><span style="color:var(--text-secondary)">${escapeHtml(n.error)}</span>`),s+='<br><span style="color:var(--text-secondary)">The previous version is still running.</span>',n.stashRef&&(s+=`<br><span style="color:var(--text-secondary)">Local changes stashed as <code>${escapeHtml(n.stashRef)}</code>.</span>`),this._setUpdateProgress(s);const o=this.$("updateNowBtn"),i=this.$("updateActionRow");o&&(o.disabled=!1,o.textContent="Try again"),i&&(i.style.display="flex")}};t(),this._updatePollTimer=setInterval(t,1500)},isCliAvailable(e){const t=window.__codemanCliAvailable;return!t||typeof t!="object"?!0:t[e]!==!1},renderWelcomeCliActions(){const e=document.getElementById("welcomeCliActions");if(!e)return;const n=(Array.isArray(window.__codemanCliCatalog)?window.__codemanCliCatalog:[]).filter(u=>u.enabled&&this.isCliAvailable(u.id)),s=n.find(u=>u.kind!=="shell")||n[0],o=u=>`Run ${u.kind==="shell"?"Shell":u.label}`,i=u=>{const h=document.createElement("span");return h.className=`run-mode-dot ${u.id}`,h.setAttribute("aria-hidden","true"),h},a=u=>()=>{this.setRunMode(u.id),this.run()};if(e.replaceChildren(),!s)return;const l=document.createElement("button");l.type="button",l.className="welcome-primary",l.dataset.mode=s.id;const d=document.createElement("span");d.className="welcome-primary-logo",d.appendChild(i(s)),l.appendChild(d);const r=document.createElement("span");r.className="welcome-label",r.textContent=o(s),l.appendChild(r),l.onclick=a(s),e.appendChild(l);const c=n.filter(u=>u!==s);if(!c.length)return;const p=document.createElement("div");p.className="welcome-chips",p.setAttribute("role","group"),p.setAttribute("aria-label","More tools");for(const u of c){const h=document.createElement("button");h.type="button",h.className="welcome-chip",h.dataset.mode=u.id,h.title=o(u),h.setAttribute("aria-label",o(u)),h.appendChild(i(u));const f=document.createElement("span");f.className="welcome-label",f.textContent=u.kind==="shell"?"Shell":u.label,h.appendChild(f),h.onclick=a(u),p.appendChild(h)}e.appendChild(p)},applyWelcomeCliVisibility(){this.renderWelcomeCliActions();const e=document.getElementById("welcomeTunnelBtn");e&&(e.style.display=this.isCliAvailable("cloudflared")?"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)}},_updateTunnelUrlDisplay(e){const t=document.getElementById("tunnelUrlRow"),n=document.getElementById("tunnelUrlDisplay");!t||!n||(e?(t.style.display="",n.textContent=e,n.onclick=()=>{navigator.clipboard.writeText(e).then(()=>{this.showToast("Tunnel URL copied","success")})}):(t.style.display="none",n.textContent="",n.onclick=null))},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=`
|
|
13
13
|
<div style="font-size:14px;font-weight:600;color:var(--text-primary);margin-bottom:16px">Scan to connect</div>
|
|
14
14
|
<div id="tunnelQrContainer" style="background:#fff;border-radius:8px;padding:16px;display:inline-block">
|
|
15
15
|
<div style="color:#666;font-size:12px">Loading...</div>
|
|
16
16
|
</div>
|
|
17
17
|
<div id="tunnelQrUrl" style="margin-top:12px;font-family:monospace;font-size:11px;color:var(--text-muted);word-break:break-all;cursor:pointer" title="Click to copy"></div>
|
|
18
18
|
<button onclick="app.closeTunnelQR()" style="margin-top:16px;padding:6px 20px;background:var(--bg-elevated);border:1px solid var(--border);border-radius:6px;color:var(--text-primary);cursor:pointer;font-size:13px">Close</button>
|
|
19
|
-
`,e.appendChild(t),document.body.appendChild(e),fetch("/api/tunnel/qr").then(n=>{if(!n.ok)throw new Error("Tunnel not running");return n.json()}).then(n=>{const s=n?.success===!0?n.data:n,o=document.getElementById("tunnelQrContainer");if(o&&s.svg&&(o.innerHTML=s.svg),s.authEnabled){const i=document.createElement("div");i.id="tunnelQrBadge",i.style.cssText="margin-top:8px;font-size:11px;color:var(--text-muted)",i.textContent="Single-use auth \xB7 expires in 60s";const a=document.createElement("button");a.textContent="Regenerate QR",a.style.cssText="margin-top:8px;padding:4px 12px;background:var(--bg-elevated);border:1px solid var(--border);border-radius:4px;color:var(--text-secondary);cursor:pointer;font-size:11px",a.onclick=()=>{fetch("/api/tunnel/qr/regenerate",{method:"POST"}).then(d=>{if(!d.ok)throw new Error(`HTTP ${d.status}`);this.showToast("QR code regenerated","success")}).catch(()=>this.showToast("Failed to regenerate QR","error"))};const l=o.parentElement;l&&(l.appendChild(i),l.appendChild(a)),this._resetQrCountdown()}}).catch(()=>{const n=document.getElementById("tunnelQrContainer");n&&(n.innerHTML='<div style="color:#c00;font-size:12px;padding:20px">Tunnel not active</div>')}),fetch("/api/tunnel/status").then(n=>n.json()).then(n=>{const s=n?.success===!0?n.data:n,o=document.getElementById("tunnelQrUrl");o&&s.url&&(o.textContent=s.url,o.onclick=()=>{navigator.clipboard.writeText(s.url).then(()=>{this.showToast("Tunnel URL copied","success")})})}).catch(()=>{}),this._tunnelQrEscHandler=n=>{n.key==="Escape"&&this.closeTunnelQR()},document.addEventListener("keydown",this._tunnelQrEscHandler)},closeTunnelQR(){const e=document.getElementById("tunnelQrOverlay");e&&e.remove(),this._tunnelQrEscHandler&&(document.removeEventListener("keydown",this._tunnelQrEscHandler),this._tunnelQrEscHandler=null),this._clearQrCountdown()},_refreshTunnelQrFromApi(){fetch("/api/tunnel/qr").then(e=>e.ok?e.json():null).then(e=>{const t=e?.success===!0?e.data:e;if(!t?.svg)return;const n=document.getElementById("tunnelQrContainer");n&&(n.innerHTML=t.svg);const s=document.getElementById("welcomeQrInner");s&&(s.innerHTML=t.svg)}).catch(()=>{})},_resetQrCountdown(){this._clearQrCountdown(),this._qrCountdownSec=60,this._updateQrCountdownText(),this._qrCountdownTimer=setInterval(()=>{if(this._qrCountdownSec--,this._qrCountdownSec<=0){this._clearQrCountdown();return}this._updateQrCountdownText()},1e3)},_updateQrCountdownText(){const e=document.getElementById("tunnelQrBadge");e&&(e.textContent=`Single-use auth \xB7 expires in ${this._qrCountdownSec}s`)},_clearQrCountdown(){this._qrCountdownTimer&&(clearInterval(this._qrCountdownTimer),this._qrCountdownTimer=null)},async toggleTunnelFromWelcome(){const e=document.getElementById("welcomeTunnelBtn");if(!e)return;if(this._settingsReadOnly()){this.showToast("Server-wide settings can only be changed by an admin","warning");return}const t=e.classList.contains("active");e.disabled=!0;try{const n=!t,s=await fetch("/api/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({tunnelEnabled:n})});if(n&&await this._handleTunnelEnableRefusal(
|
|
19
|
+
`,e.appendChild(t),document.body.appendChild(e),fetch("/api/tunnel/qr").then(n=>{if(!n.ok)throw new Error("Tunnel not running");return n.json()}).then(n=>{const s=n?.success===!0?n.data:n,o=document.getElementById("tunnelQrContainer");if(o&&s.svg&&(o.innerHTML=s.svg),s.authEnabled){const i=document.createElement("div");i.id="tunnelQrBadge",i.style.cssText="margin-top:8px;font-size:11px;color:var(--text-muted)",i.textContent="Single-use auth \xB7 expires in 60s";const a=document.createElement("button");a.textContent="Regenerate QR",a.style.cssText="margin-top:8px;padding:4px 12px;background:var(--bg-elevated);border:1px solid var(--border);border-radius:4px;color:var(--text-secondary);cursor:pointer;font-size:11px",a.onclick=()=>{fetch("/api/tunnel/qr/regenerate",{method:"POST"}).then(d=>{if(!d.ok)throw new Error(`HTTP ${d.status}`);this.showToast("QR code regenerated","success")}).catch(()=>this.showToast("Failed to regenerate QR","error"))};const l=o.parentElement;l&&(l.appendChild(i),l.appendChild(a)),this._resetQrCountdown()}}).catch(()=>{const n=document.getElementById("tunnelQrContainer");n&&(n.innerHTML='<div style="color:#c00;font-size:12px;padding:20px">Tunnel not active</div>')}),fetch("/api/tunnel/status").then(n=>n.json()).then(n=>{const s=n?.success===!0?n.data:n,o=document.getElementById("tunnelQrUrl");o&&s.url&&(o.textContent=s.url,o.onclick=()=>{navigator.clipboard.writeText(s.url).then(()=>{this.showToast("Tunnel URL copied","success")})})}).catch(()=>{}),this._tunnelQrEscHandler=n=>{n.key==="Escape"&&this.closeTunnelQR()},document.addEventListener("keydown",this._tunnelQrEscHandler)},closeTunnelQR(){const e=document.getElementById("tunnelQrOverlay");e&&e.remove(),this._tunnelQrEscHandler&&(document.removeEventListener("keydown",this._tunnelQrEscHandler),this._tunnelQrEscHandler=null),this._clearQrCountdown()},_refreshTunnelQrFromApi(){fetch("/api/tunnel/qr").then(e=>e.ok?e.json():null).then(e=>{const t=e?.success===!0?e.data:e;if(!t?.svg)return;const n=document.getElementById("tunnelQrContainer");n&&(n.innerHTML=t.svg);const s=document.getElementById("welcomeQrInner");s&&(s.innerHTML=t.svg)}).catch(()=>{})},_resetQrCountdown(){this._clearQrCountdown(),this._qrCountdownSec=60,this._updateQrCountdownText(),this._qrCountdownTimer=setInterval(()=>{if(this._qrCountdownSec--,this._qrCountdownSec<=0){this._clearQrCountdown();return}this._updateQrCountdownText()},1e3)},_updateQrCountdownText(){const e=document.getElementById("tunnelQrBadge");e&&(e.textContent=`Single-use auth \xB7 expires in ${this._qrCountdownSec}s`)},_clearQrCountdown(){this._qrCountdownTimer&&(clearInterval(this._qrCountdownTimer),this._qrCountdownTimer=null)},async toggleTunnelFromWelcome(){const e=document.getElementById("welcomeTunnelBtn");if(!e)return;if(this._settingsReadOnly()){this.showToast("Server-wide settings can only be changed by an admin","warning");return}const t=e.classList.contains("active");e.disabled=!0;try{const n=!t,s=n?await this._confirmTunnelEnable():{proceed:!0,acknowledge:!1};if(!s.proceed){this._updateWelcomeTunnelBtn(!1),e.disabled=!1;return}const o=await fetch("/api/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({tunnelEnabled:n,...s.acknowledge?{acknowledgeUnauthTunnel:!0}:{}})});if(n&&await this._handleTunnelEnableRefusal(o)){this._dismissTunnelConnecting(),this._updateWelcomeTunnelBtn(!1),e.disabled=!1;return}n?(this._showTunnelConnecting(),this._pollTunnelStatus()):(this._dismissTunnelConnecting(),this.showToast("Tunnel stopped","info"),this._updateWelcomeTunnelBtn(!1),e.disabled=!1)}catch{this._dismissTunnelConnecting(),this.showToast("Failed to toggle tunnel","error"),e.disabled=!1}},_showTunnelConnecting(){const e=document.getElementById("tunnelConnectingToast");e&&e.remove();const t=document.getElementById("welcomeTunnelBtn");t&&(t.classList.add("connecting"),t.innerHTML=`
|
|
20
20
|
<span class="tunnel-spinner"></span>
|
|
21
21
|
Connecting...`);const n=document.createElement("div");n.className="toast toast-info show",n.id="tunnelConnectingToast",n.innerHTML='<span class="tunnel-spinner"></span> Cloudflare Tunnel connecting...',n.style.pointerEvents="auto",this._toastContainer||(this._toastContainer=document.querySelector(".toast-container"),this._toastContainer||(this._toastContainer=document.createElement("div"),this._toastContainer.className="toast-container",document.body.appendChild(this._toastContainer))),this._toastContainer.appendChild(n)},_dismissTunnelConnecting(){clearTimeout(this._tunnelPollTimer),this._tunnelPollTimer=null;const e=document.getElementById("tunnelConnectingToast");e&&(e.classList.remove("show"),setTimeout(()=>e.remove(),200));const t=document.getElementById("welcomeTunnelBtn");t&&t.classList.remove("connecting")},_pollTunnelStatus(e=0){e>15||(this._tunnelPollTimer=setTimeout(async()=>{try{const n=await(await fetch("/api/tunnel/status")).json(),s=n?.success===!0?n.data:n;if(s.running&&s.url){this._dismissTunnelConnecting(),this._updateTunnelUrlDisplay(s.url),document.getElementById("welcomeOverlay")?.classList.contains("visible")?(this._updateWelcomeTunnelBtn(!0,s.url,!0),this.showToast("Tunnel active","success")):(this._updateWelcomeTunnelBtn(!0,s.url),this.showToast(`Tunnel active: ${s.url}`,"success"),this.showTunnelQR());return}}catch{}this._pollTunnelStatus(e+1)},2e3))},_updateWelcomeTunnelBtn(e,t,n=!1){const s=document.getElementById("welcomeTunnelBtn");s&&(s.disabled=!1,e?(s.classList.remove("connecting"),s.classList.add("active"),s.innerHTML=`
|
|
22
22
|
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 2L2 7l10 5 10-5-10-5z"/><path d="M2 17l10 5 10-5"/><path d="M2 12l10 5 10-5"/></svg>
|
|
@@ -57,19 +57,19 @@ This rolls back credentials and accounts (${n.join(", ")}): passwords, disabled
|
|
|
57
57
|
<button class="tunnel-panel-btn btn-stop" onclick="app._tunnelPanelToggle(false)">Stop Tunnel</button>`:s+='<button class="tunnel-panel-btn btn-start" onclick="app._tunnelPanelToggle(true)">Start Tunnel</button>',s+="</div>",e.authEnabled&&e.authSessions.length>0&&(s+=`
|
|
58
58
|
<div style="padding-top:8px">
|
|
59
59
|
<button class="tunnel-panel-btn btn-revoke" style="width:100%" onclick="app._tunnelPanelRevokeAll()">Revoke All Sessions</button>
|
|
60
|
-
</div>`),n.innerHTML=s;const o=document.getElementById("tunnelPanelUrl");o&&(o.onclick=()=>{navigator.clipboard.writeText(e.url).then(()=>this.showToast("Tunnel URL copied","success"))})},_formatTimeAgo(e){const t=Date.now()-e,n=Math.floor(t/6e4);if(n<1)return"just now";if(n<60)return`${n}m ago`;const s=Math.floor(n/60);return s<24?`${s}h ago`:`${Math.floor(s/24)}d ago`},
|
|
60
|
+
</div>`),n.innerHTML=s;const o=document.getElementById("tunnelPanelUrl");o&&(o.onclick=()=>{navigator.clipboard.writeText(e.url).then(()=>this.showToast("Tunnel URL copied","success"))})},_formatTimeAgo(e){const t=Date.now()-e,n=Math.floor(t/6e4);if(n<1)return"just now";if(n<60)return`${n}m ago`;const s=Math.floor(n/60);return s<24?`${s}h ago`:`${Math.floor(s/24)}d ago`},_abandonTunnelEnable(e,t){e.tunnelEnabled=!1,this.saveAppSettingsToStorage(e);const n=document.getElementById("appSettingsTunnelEnabled");n&&(n.checked=!1),t||this.closeAppSettings()},_askUnauthTunnel(){return confirm(`\u26A0\uFE0F SECURITY WARNING \u2014 no password set
|
|
61
61
|
|
|
62
62
|
Enabling the Cloudflare tunnel will publish THIS machine to a public URL with NO login. Anyone who gets the URL has full terminal control \u2014 effectively remote code execution on your computer.
|
|
63
63
|
|
|
64
64
|
Strongly recommended: set CODEMAN_PASSWORD instead.
|
|
65
65
|
|
|
66
|
-
Enable the unauthenticated public tunnel anyway?`))return this._dismissTunnelConnecting?.(),this.showToast("Tunnel not enabled","info"),!0;try{const o=await fetch("/api/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({tunnelEnabled:!0,acknowledgeUnauthTunnel:!0})});if(o.ok)return this.showToast("Public tunnel enabling \u2014 no password set \u26A0\uFE0F","warning"),!1;let i="Failed to enable tunnel.";try{const a=await o.json();a&&a.error&&(i=a.error)}catch{}return this._dismissTunnelConnecting?.(),this.showToast(i,"error"),!0}catch{return this._dismissTunnelConnecting?.(),this.showToast("Failed to enable tunnel","error"),!0}}return this._dismissTunnelConnecting?.(),this.showToast(t,"error"),!0},async _tunnelPanelToggle(e){if(this._settingsReadOnly()){this.showToast("Server-wide settings can only be changed by an admin","warning"),this.closeTunnelPanel();return}try{const t=await fetch("/api/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({tunnelEnabled:e})});if(e&&await this._handleTunnelEnableRefusal(
|
|
66
|
+
Enable the unauthenticated public tunnel anyway?`)},async _confirmTunnelEnable(){let e=null;try{const t=await fetch("/api/tunnel/status");if(t.ok){const n=await t.json();e=n?.success===!0?n.data:n}}catch{}return!e||e.running||e.loginConfigured!==!1?{proceed:!0,acknowledge:!1}:this._askUnauthTunnel()?{proceed:!0,acknowledge:!0}:(this.showToast("Tunnel not enabled","info"),{proceed:!1,acknowledge:!1})},async _handleTunnelEnableRefusal(e){if(!e||e.ok)return!1;let t="Tunnel refused: set CODEMAN_PASSWORD before exposing Codeman publicly.",n="";try{const s=await e.json();s&&s.error&&(t=s.error),s&&typeof s.errorCode=="string"&&(n=s.errorCode)}catch{}if(e.status===403&&n==="FORBIDDEN")return this._dismissTunnelConnecting?.(),this.showToast("Server-wide settings can only be changed by an admin","warning"),!0;if(e.status===403){if(!this._askUnauthTunnel())return this._dismissTunnelConnecting?.(),this.showToast("Tunnel not enabled","info"),!0;try{const o=await fetch("/api/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({tunnelEnabled:!0,acknowledgeUnauthTunnel:!0})});if(o.ok)return this.showToast("Public tunnel enabling \u2014 no password set \u26A0\uFE0F","warning"),!1;let i="Failed to enable tunnel.";try{const a=await o.json();a&&a.error&&(i=a.error)}catch{}return this._dismissTunnelConnecting?.(),this.showToast(i,"error"),!0}catch{return this._dismissTunnelConnecting?.(),this.showToast("Failed to enable tunnel","error"),!0}}return this._dismissTunnelConnecting?.(),this.showToast(t,"error"),!0},async _tunnelPanelToggle(e){if(this._settingsReadOnly()){this.showToast("Server-wide settings can only be changed by an admin","warning"),this.closeTunnelPanel();return}try{const t=e?await this._confirmTunnelEnable():{proceed:!0,acknowledge:!1};if(!t.proceed){this.closeTunnelPanel();return}const n=await fetch("/api/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({tunnelEnabled:e,...t.acknowledge?{acknowledgeUnauthTunnel:!0}:{}})});if(e&&await this._handleTunnelEnableRefusal(n)){this.closeTunnelPanel();return}if(e){this._updateTunnelIndicator(!1);const s=document.getElementById("tunnelIndicator");s&&(s.style.display="flex",s.classList.add("connecting")),this.showToast("Tunnel starting...","info"),this._showTunnelConnecting(),this._pollTunnelStatus()}else this.showToast("Tunnel stopped","info");this.closeTunnelPanel()}catch{this.showToast("Failed to toggle tunnel","error")}},async _tunnelPanelRevokeAll(){try{await fetch("/api/auth/revoke",{method:"POST",headers:{"Content-Type":"application/json"},body:"{}"}),this.showToast("All sessions revoked","success");const t=await(await fetch("/api/tunnel/info")).json(),n=t?.success===!0?t.data:t;this._renderTunnelPanel(n)}catch{this.showToast("Failed to revoke sessions","error")}},closeTunnelPanel(){const e=document.getElementById("tunnelPanel");e&&e.remove(),this._tunnelPanelClickHandler&&(document.removeEventListener("click",this._tunnelPanelClickHandler),this._tunnelPanelClickHandler=null),this._tunnelPanelEscHandler&&(document.removeEventListener("keydown",this._tunnelPanelEscHandler),this._tunnelPanelEscHandler=null)},toggleDeepgramKeyVisibility(){const e=document.getElementById("voiceDeepgramKey"),t=document.getElementById("voiceKeyToggleBtn");e.type==="password"?(e.type="text",t.textContent="Hide"):(e.type="password",t.textContent="Show")},openLifecycleLog(){const e=document.getElementById("lifecycleWindow");e.style.display="block",e._dragInitialized||(e.style.left="50%",e.style.transform="translateX(-50%)",this._initLifecycleDrag(e),e._dragInitialized=!0),this.loadLifecycleLog()},closeLifecycleLog(){document.getElementById("lifecycleWindow").style.display="none"},_initLifecycleDrag(e){const t=document.getElementById("lifecycleWindowHeader");let n=!1,s,o,i,a;t.addEventListener("mousedown",l=>{if(l.target.tagName==="SELECT"||l.target.tagName==="INPUT"||l.target.tagName==="BUTTON")return;n=!0;const d=e.getBoundingClientRect();e.style.transform="none",e.style.left=d.left+"px",e.style.top=d.top+"px",s=l.clientX,o=l.clientY,i=d.left,a=d.top,l.preventDefault()}),document.addEventListener("mousemove",l=>{n&&(e.style.left=i+l.clientX-s+"px",e.style.top=a+l.clientY-o+"px")}),document.addEventListener("mouseup",()=>{n=!1})},async loadLifecycleLog(){const e=document.getElementById("lifecycleFilterEvent").value,t=document.getElementById("lifecycleFilterSession").value.trim(),n=new URLSearchParams;e&&n.set("event",e),t&&n.set("sessionId",t),n.set("limit","300");try{const o=await(await fetch(`/api/session-lifecycle?${n}`)).json(),i=o?.success===!0?o.data:o,a=document.getElementById("lifecycleTableBody"),l=document.getElementById("lifecycleEmpty");if(!i.entries||i.entries.length===0){a.innerHTML="",l.style.display="";return}l.style.display="none";const d={created:"#4ade80",started:"#4ade80",recovered:"#4ade80",exit:"#fbbf24",mux_died:"#f87171",deleted:"#f87171",stale_cleaned:"#f87171",server_started:"#666",server_stopped:"#666"};a.innerHTML=i.entries.map(r=>{const c=new Date(r.ts).toLocaleString(),p=d[r.event]||"#888",u=r.name||(r.sessionId==="*"?"\u2014":this.getShortId(r.sessionId)),h=[];return r.exitCode!==void 0&&r.exitCode!==null&&h.push(`code=${r.exitCode}`),r.mode&&h.push(r.mode),`<tr style="border-bottom:1px solid #1a1a2e">
|
|
67
67
|
<td style="padding:3px 8px;color:#888;white-space:nowrap">${c}</td>
|
|
68
68
|
<td style="padding:3px 8px;color:${p};font-weight:600">${r.event}</td>
|
|
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
|
-
<td style="padding:3px 8px;color:#666">${
|
|
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`
|
|
71
|
+
<td style="padding:3px 8px;color:#666">${h.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,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,agentCoordinationEnabled:document.getElementById("appSettingsAgentCoordination").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)),gitFetchEnabled:document.getElementById("appSettingsGitFetchEnabled").checked,gitFetchIntervalSeconds:Math.min(3600,Math.max(30,parseInt(document.getElementById("appSettingsGitFetchIntervalSeconds").value,10)||300)),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,keyboardHoldsRows:document.getElementById("appSettingsKeyboardHoldsRows").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,showTabNewButton:document.getElementById("appSettingsShowTabNewButton").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._reconcileKeyboardHold?.(),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,keyboardHoldsRows:p,cjkInputEnabled:u,extendedKeyboardBar:h,skin:f,language:m,showPlanUsageLimits:g,showAttachmentsButton:y,showFileViewerButton:S,showSplitButton:b,showTileGridButton:E,webglRendererEnabled:w,terminalWheelLocalScrollback:v,autoCopySelection:B,copyStripMargin:k,terminalFontFamily:I,terminalFontWeight:_,terminalFontWeightBold:H,showSessionButton:M,showAwayDigestButton:D,showCronButton:A,showGitStatus:O,showGpuStats:L,showCpuMhz:U,gitStatusTree:P,gitStatusMaxRepos:R,gitStatusTimeoutSeconds:W,showTabDetachButton:x,showTabNewButton:V,tileDetachEnabled:q,mobileOverviewEnabled:Q,sessionLineageLines:G,shortcutOverrides:z,...j}=o;let C="",N=!1;try{const $=o.tunnelEnabled&&!i?await this._confirmTunnelEnable():{proceed:!0,acknowledge:!1};if(!$.proceed){this._abandonTunnelEnable(o,e);return}const F=i?null:await this._apiPut("/api/settings",{...j,...r!==void 0?{showPlanUsageLimits:r}:{},...$.acknowledge?{acknowledgeUnauthTunnel:!0}:{},notificationPreferences:d,voiceSettings:l}),T=!i&&await this._noteSettingsWriteRefusal(F);if(T&&(this._keepServerSyncedSettings(o,t),this.saveAppSettingsToStorage(o)),!T&&o.tunnelEnabled&&await this._handleTunnelEnableRefusal(F)){this._abandonTunnelEnable(o,e);return}N=!!F?.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||T?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&&!T&&this.showToast("Tunnel starting \u2014 QR code will appear when ready...","info")}catch{this.showToast("Settings saved locally","warning")}e&&N&&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,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?"▼":"▲"),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>
|
|
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),document.documentElement.classList.toggle("tabs-show-new",e.showTabNewButton===!0);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,h=document.querySelector(".btn-response-viewer-header");h&&h.classList.toggle("btn-response-viewer-header--hidden",!u);const f=e.showAttachmentsButton??t.showAttachmentsButton??!1,m=document.getElementById("attachmentsHistoryBtn");m&&m.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),_=document.getElementById("planUsageChip");_&&_.classList.toggle("header-plan-usage--hidden",!I);const H=e.showRedrawButton??t.showRedrawButton??!1,M=document.querySelector(".btn-redraw-terminal");M&&M.classList.toggle("btn-redraw-terminal--hidden",!H);const D=e.showSessionButton??t.showSessionButton??!1,A=document.querySelector(".btn-session-manager");A&&A.classList.toggle("btn-session-manager--hidden",!D);const O=e.showAwayDigestButton??t.showAwayDigestButton??!1,L=document.querySelector(".btn-away-digest");L&&L.classList.toggle("btn-away-digest--hidden",!O);const U=e.showCronButton??t.showCronButton??!1,P=document.querySelector(".btn-cron");P&&P.classList.toggle("btn-cron--hidden",!U),this.applyGitStatusVisibility?.();const R=document.querySelector(".btn-notifications");if(R&&(R.style.display="none"),!(this.notificationManager?.preferences?.enabled??!0)){const x=document.getElementById("notifDrawer");x&&x.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 h=i.dataset.tabStateOrder||"urgent-first",f=this.resolveTabStateOrder(t);i.dataset.tabStateOrder=f;const m=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||h!==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?.()):m!==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 h=c.getBoundingClientRect();c.style.left=`${h.left}px`,c.style.top=`${h.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?"▼":"▲"),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","keyboardHoldsRows","cjkInputEnabled","extendedKeyboardBar","skin","showPlanUsageLimits","showAttachmentsButton","showFileViewerButton","webglRendererEnabled","terminalFontFamily","terminalFontWeight","terminalFontWeightBold","language","terminalWheelLocalScrollback","autoCopySelection","copyStripMargin","showSessionButton","showAwayDigestButton","showCronButton","showGitStatus","gitStatusTree","gitStatusMaxRepos","gitStatusTimeoutSeconds","showTabDetachButton","showTabNewButton","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>
|