aicodeman 1.16.2 → 1.16.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (116) hide show
  1. package/README.md +2 -1
  2. package/dist/search-service.d.ts +9 -1
  3. package/dist/search-service.d.ts.map +1 -1
  4. package/dist/search-service.js +13 -3
  5. package/dist/search-service.js.map +1 -1
  6. package/dist/services/unified-session-service.d.ts +9 -0
  7. package/dist/services/unified-session-service.d.ts.map +1 -1
  8. package/dist/services/unified-session-service.js +4 -1
  9. package/dist/services/unified-session-service.js.map +1 -1
  10. package/dist/types/search.d.ts +17 -3
  11. package/dist/types/search.d.ts.map +1 -1
  12. package/dist/web/public/admin-ui.js +35 -20
  13. package/dist/web/public/admin-ui.js.br +0 -0
  14. package/dist/web/public/admin-ui.js.gz +0 -0
  15. package/dist/web/public/api-client.c9b1cddc.js.gz +0 -0
  16. package/dist/web/public/{app.4d006245.js → app.f9c6aadd.js} +18 -18
  17. package/dist/web/public/app.f9c6aadd.js.br +0 -0
  18. package/dist/web/public/app.f9c6aadd.js.gz +0 -0
  19. package/dist/web/public/approvals-ui.js.gz +0 -0
  20. package/dist/web/public/{constants.7d0f4047.js → constants.53dc0fa1.js} +43 -0
  21. package/dist/web/public/constants.53dc0fa1.js.br +0 -0
  22. package/dist/web/public/constants.53dc0fa1.js.gz +0 -0
  23. package/dist/web/public/cron-ui.js.gz +0 -0
  24. package/dist/web/public/entrance-animations.js.gz +0 -0
  25. package/dist/web/public/home-sessions.js +119 -8
  26. package/dist/web/public/home-sessions.js.br +0 -0
  27. package/dist/web/public/home-sessions.js.gz +0 -0
  28. package/dist/web/public/i18n.1a8b3412.js +1 -0
  29. package/dist/web/public/i18n.1a8b3412.js.br +0 -0
  30. package/dist/web/public/i18n.1a8b3412.js.gz +0 -0
  31. package/dist/web/public/image-input.ee16ad88.js.gz +0 -0
  32. package/dist/web/public/index.html +807 -727
  33. package/dist/web/public/index.html.br +0 -0
  34. package/dist/web/public/index.html.gz +0 -0
  35. package/dist/web/public/input-cjk.63794d0b.js.gz +0 -0
  36. package/dist/web/public/{keyboard-accessory.1f35b482.js → keyboard-accessory.0f524637.js} +207 -5
  37. package/dist/web/public/keyboard-accessory.0f524637.js.br +0 -0
  38. package/dist/web/public/keyboard-accessory.0f524637.js.gz +0 -0
  39. package/dist/web/public/mobile-handlers.32fdd57f.js.gz +0 -0
  40. package/dist/web/public/mobile-overview.js.gz +0 -0
  41. package/dist/web/public/mobile.52b30b35.css +1 -0
  42. package/dist/web/public/mobile.52b30b35.css.br +0 -0
  43. package/dist/web/public/mobile.52b30b35.css.gz +0 -0
  44. package/dist/web/public/notification-manager.5d229063.js.gz +0 -0
  45. package/dist/web/public/orchestrator-panel.js.gz +0 -0
  46. package/dist/web/public/{panels-ui.3df9cd95.js → panels-ui.54b0d004.js} +1 -1
  47. package/dist/web/public/panels-ui.54b0d004.js.br +0 -0
  48. package/dist/web/public/panels-ui.54b0d004.js.gz +0 -0
  49. package/dist/web/public/ralph-panel.6de2d0f8.js.gz +0 -0
  50. package/dist/web/public/ralph-wizard.13a1831e.js.gz +0 -0
  51. package/dist/web/public/readmymind-ui.js +80 -16
  52. package/dist/web/public/readmymind-ui.js.br +0 -0
  53. package/dist/web/public/readmymind-ui.js.gz +0 -0
  54. package/dist/web/public/respawn-ui.ff0dae4c.js.gz +0 -0
  55. package/dist/web/public/sanitize-html.bc7078d6.js.gz +0 -0
  56. package/dist/web/public/session-ui.f4fed187.js.gz +0 -0
  57. package/dist/web/public/{settings-ui.1c15649c.js → settings-ui.c674f367.js} +9 -9
  58. package/dist/web/public/settings-ui.c674f367.js.br +0 -0
  59. package/dist/web/public/settings-ui.c674f367.js.gz +0 -0
  60. package/dist/web/public/styles.2eb23e0f.css +1 -0
  61. package/dist/web/public/styles.2eb23e0f.css.br +0 -0
  62. package/dist/web/public/styles.2eb23e0f.css.gz +0 -0
  63. package/dist/web/public/subagent-windows.4cc8b005.js.gz +0 -0
  64. package/dist/web/public/sw.js.gz +0 -0
  65. package/dist/web/public/terminal-ui.61c7829d.js +4 -0
  66. package/dist/web/public/terminal-ui.61c7829d.js.br +0 -0
  67. package/dist/web/public/terminal-ui.61c7829d.js.gz +0 -0
  68. package/dist/web/public/ultracode-panel.js.gz +0 -0
  69. package/dist/web/public/ultracode-windows.js.gz +0 -0
  70. package/dist/web/public/upload.html.gz +0 -0
  71. package/dist/web/public/vendor/dompurify.min.js.gz +0 -0
  72. package/dist/web/public/vendor/marked.min.js.gz +0 -0
  73. package/dist/web/public/vendor/xterm-addon-fit.min.js.gz +0 -0
  74. package/dist/web/public/vendor/xterm-addon-serialize.min.js.gz +0 -0
  75. package/dist/web/public/vendor/xterm-addon-unicode11.min.js.gz +0 -0
  76. package/dist/web/public/vendor/xterm-addon-webgl.min.js.gz +0 -0
  77. package/dist/web/public/vendor/xterm-predictive-echo.6cec0fba.js.gz +0 -0
  78. package/dist/web/public/vendor/xterm-zerolag-input.137ad9f0.js.gz +0 -0
  79. package/dist/web/public/vendor/xterm.css.gz +0 -0
  80. package/dist/web/public/vendor/xterm.min.js.gz +0 -0
  81. package/dist/web/public/voice-input.e5461859.js.gz +0 -0
  82. package/dist/web/public/webview-tabs.js.gz +0 -0
  83. package/dist/web/routes/search-routes.d.ts +3 -1
  84. package/dist/web/routes/search-routes.d.ts.map +1 -1
  85. package/dist/web/routes/search-routes.js +34 -1
  86. package/dist/web/routes/search-routes.js.map +1 -1
  87. package/dist/web/routes/session-routes.d.ts.map +1 -1
  88. package/dist/web/routes/session-routes.js +151 -9
  89. package/dist/web/routes/session-routes.js.map +1 -1
  90. package/dist/web/session-history-index.d.ts +108 -0
  91. package/dist/web/session-history-index.d.ts.map +1 -0
  92. package/dist/web/session-history-index.js +118 -0
  93. package/dist/web/session-history-index.js.map +1 -0
  94. package/package.json +1 -1
  95. package/dist/web/public/app.4d006245.js.br +0 -0
  96. package/dist/web/public/app.4d006245.js.gz +0 -0
  97. package/dist/web/public/constants.7d0f4047.js.br +0 -0
  98. package/dist/web/public/constants.7d0f4047.js.gz +0 -0
  99. package/dist/web/public/i18n.ef50083f.js +0 -1
  100. package/dist/web/public/i18n.ef50083f.js.br +0 -0
  101. package/dist/web/public/i18n.ef50083f.js.gz +0 -0
  102. package/dist/web/public/keyboard-accessory.1f35b482.js.br +0 -0
  103. package/dist/web/public/keyboard-accessory.1f35b482.js.gz +0 -0
  104. package/dist/web/public/mobile.5d8c896c.css +0 -1
  105. package/dist/web/public/mobile.5d8c896c.css.br +0 -0
  106. package/dist/web/public/mobile.5d8c896c.css.gz +0 -0
  107. package/dist/web/public/panels-ui.3df9cd95.js.br +0 -0
  108. package/dist/web/public/panels-ui.3df9cd95.js.gz +0 -0
  109. package/dist/web/public/settings-ui.1c15649c.js.br +0 -0
  110. package/dist/web/public/settings-ui.1c15649c.js.gz +0 -0
  111. package/dist/web/public/styles.0024c22e.css +0 -1
  112. package/dist/web/public/styles.0024c22e.css.br +0 -0
  113. package/dist/web/public/styles.0024c22e.css.gz +0 -0
  114. package/dist/web/public/terminal-ui.e7c5d233.js +0 -4
  115. package/dist/web/public/terminal-ui.e7c5d233.js.br +0 -0
  116. package/dist/web/public/terminal-ui.e7c5d233.js.gz +0 -0
@@ -2,12 +2,15 @@
2
2
  * @fileoverview Read My Mind UI: predict the prompt you were about to type.
3
3
  *
4
4
  * A 🧠 header button (marker-hidden until the synced opt-in `readMyMindEnabled`
5
- * setting is ON) opens a modal that asks the server for the user's most likely
5
+ * setting is ON; phones get a keyboard-accessory 🧠 key gated on the same
6
+ * setting) opens a modal that asks the server for the user's most likely
6
7
  * next prompt (`POST /api/sessions/:id/readmymind`, one-shot predictor over the
7
8
  * case's intent profile + live session signals). The top suggestion lands in an
8
- * editable single-line field with its rationale below; buttons are Send (with
9
- * Enter), Insert (drop on the CLI composer WITHOUT Enter, for editing), Rethink
10
- * (re-run with the shown suggestion recorded as rejected), Dismiss.
9
+ * editable single-line field with its rationale below; the predictor's other
10
+ * suggestions render as tappable alternate rows that swap into the field
11
+ * without losing edits. Buttons are Send (with Enter), Insert (drop on the CLI
12
+ * composer WITHOUT Enter, for editing), Rethink (re-run with the whole shown
13
+ * set, main + alternates, recorded as rejected), Dismiss.
11
14
  *
12
15
  * Suggestions are NEVER auto-sent: the explicit click here is the security
13
16
  * boundary for observed/injectable predictor inputs, so suggestion text is
@@ -20,6 +23,7 @@
20
23
  *
21
24
  * @mixin Extends CodemanApp.prototype via Object.assign
22
25
  * @dependency app.js (CodemanApp class, this.sessions, this.activeSessionId, showToast)
26
+ * @dependency mobile-handlers.js (MobileDetection.isTouchDevice, focus policy)
23
27
  * @dependency settings-ui.js (loadAppSettingsFromStorage)
24
28
  * @dependency api-client.js at runtime (this._apiJson; loads later but is only called after init)
25
29
  * @loadorder 11.3, after panels-ui.js, before ultracode-panel.js
@@ -44,7 +48,7 @@ Object.assign(CodemanApp.prototype, {
44
48
  return;
45
49
  }
46
50
  // Rethink memory resets on each open (a fresh open is a fresh question).
47
- this._rmm = { sessionId, shown: null, rejected: [], busy: false };
51
+ this._rmm = { sessionId, suggestions: [], selected: 0, rejected: [], busy: false };
48
52
  document.getElementById('readMyMindModal')?.classList.add('active');
49
53
  this._readMyMindPredict();
50
54
  },
@@ -54,7 +58,7 @@ Object.assign(CodemanApp.prototype, {
54
58
  this._rmm = null;
55
59
  },
56
60
 
57
- /** Run (or re-run) the prediction and render the top suggestion. */
61
+ /** Run (or re-run) the prediction and render the suggestion set. */
58
62
  async _readMyMindPredict() {
59
63
  const state = this._rmm;
60
64
  if (!state || state.busy) return;
@@ -69,26 +73,83 @@ Object.assign(CodemanApp.prototype, {
69
73
  if (this._rmm !== state) return;
70
74
  state.busy = false;
71
75
 
72
- const suggestion = data && data.suggestions && data.suggestions[0];
73
- if (!suggestion) {
76
+ const suggestions = (data && Array.isArray(data.suggestions) ? data.suggestions : []).filter(
77
+ (s) => s && typeof s.prompt === 'string' && s.prompt.trim()
78
+ );
79
+ if (suggestions.length === 0) {
74
80
  this._rmmSetPhase('error');
75
81
  return;
76
82
  }
77
- state.shown = suggestion;
83
+ state.suggestions = suggestions.slice(0, 3);
84
+ state.selected = 0;
78
85
  this._rmmSetPhase('ready');
86
+ this._rmmRender();
87
+ this._rmmFocusPrompt();
88
+ },
89
+
90
+ /** Paint the selected suggestion into the editable field, the rest as alternates. */
91
+ _rmmRender() {
92
+ const state = this._rmm;
93
+ const current = state && state.suggestions[state.selected];
94
+ if (!current) return;
79
95
 
80
96
  const input = document.getElementById('readMyMindPrompt');
81
97
  const why = document.getElementById('readMyMindWhy');
82
98
  const kind = document.getElementById('readMyMindKind');
83
99
  // Predictor output is derived from observable (injectable) content:
84
100
  // value/textContent only, never innerHTML.
85
- if (input) input.value = suggestion.prompt;
86
- if (why) why.textContent = suggestion.why || '';
101
+ if (input) input.value = current.prompt;
102
+ if (why) why.textContent = current.why || '';
87
103
  if (kind) {
88
- kind.textContent = suggestion.kind || 'continue';
89
- kind.className = `readmymind-kind readmymind-kind-${suggestion.kind || 'continue'}`;
104
+ kind.textContent = current.kind || 'continue';
105
+ kind.className = `readmymind-kind readmymind-kind-${current.kind || 'continue'}`;
90
106
  }
91
- input?.focus();
107
+
108
+ const alternates = document.getElementById('readMyMindAlternates');
109
+ if (!alternates) return;
110
+ alternates.replaceChildren();
111
+ // The container is data-i18n-skip (suggestion text must never be mistaken
112
+ // for app copy), so the one piece of app copy inside it is pre-translated.
113
+ const translate = window.codemanT || ((s) => s);
114
+ state.suggestions.forEach((suggestion, index) => {
115
+ if (index === state.selected) return;
116
+ const row = document.createElement('button');
117
+ row.type = 'button';
118
+ row.className = 'readmymind-alt';
119
+ row.title = suggestion.why || '';
120
+ row.setAttribute('aria-label', translate('Use this suggestion instead'));
121
+ const badge = document.createElement('span');
122
+ badge.className = `readmymind-kind readmymind-kind-${suggestion.kind || 'continue'}`;
123
+ badge.textContent = suggestion.kind || 'continue';
124
+ const text = document.createElement('span');
125
+ text.className = 'readmymind-alt-text';
126
+ text.textContent = suggestion.prompt;
127
+ row.append(badge, text);
128
+ row.addEventListener('click', () => this._rmmSelect(index));
129
+ alternates.appendChild(row);
130
+ });
131
+ alternates.style.display = alternates.childElementCount > 0 ? '' : 'none';
132
+ },
133
+
134
+ /** Swap an alternate into the field, folding the current edit back first. */
135
+ _rmmSelect(index) {
136
+ const state = this._rmm;
137
+ if (!state || state.busy || !state.suggestions[index]) return;
138
+ const input = document.getElementById('readMyMindPrompt');
139
+ const current = state.suggestions[state.selected];
140
+ // Keep edits: fold the field text back into the suggestion it belongs to,
141
+ // so toggling between alternates never loses typing.
142
+ if (input && current) current.prompt = input.value;
143
+ state.selected = index;
144
+ this._rmmRender();
145
+ this._rmmFocusPrompt();
146
+ },
147
+
148
+ /** Focus the editable field on desktop. On touch devices leave it blurred so
149
+ * the OS keyboard doesn't pop over the alternates that just rendered. */
150
+ _rmmFocusPrompt() {
151
+ if (typeof MobileDetection !== 'undefined' && MobileDetection.isTouchDevice()) return;
152
+ document.getElementById('readMyMindPrompt')?.focus();
92
153
  },
93
154
 
94
155
  /**
@@ -114,11 +175,14 @@ Object.assign(CodemanApp.prototype, {
114
175
  this.showToast(withEnter ? 'Prompt sent' : 'Inserted, press Enter in the terminal to send', 'success');
115
176
  },
116
177
 
117
- /** Re-run with the shown suggestion recorded as a rejection. */
178
+ /** Re-run with the whole shown set (main + alternates) recorded as rejected:
179
+ * the user saw every row and asked for something else. */
118
180
  rethinkReadMyMind() {
119
181
  const state = this._rmm;
120
182
  if (!state || state.busy) return;
121
- if (state.shown && state.shown.prompt) state.rejected.push(state.shown.prompt);
183
+ for (const suggestion of state.suggestions) {
184
+ if (suggestion.prompt && suggestion.prompt.trim()) state.rejected.push(suggestion.prompt);
185
+ }
122
186
  this._readMyMindPredict();
123
187
  },
124
188
 
Binary file
Binary file
@@ -1,4 +1,4 @@
1
- "use strict";Object.assign(CodemanApp.prototype,{_onHookIdlePrompt(e){e.sessionId&&this.setPendingHook(e.sessionId,"idle_prompt"),this._notifySession(e.sessionId,"warning","hook-idle","Waiting for Input",e.message||"Claude is idle and waiting for a prompt")},_onHookPermissionPrompt(e){e.sessionId&&this.setPendingHook(e.sessionId,"permission_prompt");const t=e.tool?`${e.tool}${e.command?": "+e.command:e.file?": "+e.file:""}`:"";this._notifySession(e.sessionId,"critical","hook-permission","Permission Required",t||"Claude needs tool approval to continue")},_onHookElicitationDialog(e){e.sessionId&&this.setPendingHook(e.sessionId,"elicitation_dialog"),this._notifySession(e.sessionId,"critical","hook-elicitation","Question Asked",e.question||"Claude is asking a question and waiting for your answer")},_onHookElicitationComplete(e){e.sessionId&&this.clearPendingHooks(e.sessionId,"elicitation_dialog")},_onHookElicitationResponse(e){this._onHookElicitationComplete(e)},_onHookStop(e){e.sessionId&&this.clearPendingHooks(e.sessionId),this._notifySession(e.sessionId,"info","hook-stop","Response Complete",e.reason||"Claude has finished responding")},_onHookTeammateIdle(e){const t=this.sessions.get(e.sessionId);this._notifySession(e.sessionId,"warning","hook-teammate-idle","Teammate Idle",`A teammate is idle in ${t?.name||e.sessionId}`)},_onHookTaskCompleted(e){const t=this.sessions.get(e.sessionId);this._notifySession(e.sessionId,"info","hook-task-completed","Task Completed",`A team task completed in ${t?.name||e.sessionId}`)},_onTunnelStarted(e){console.log("[Tunnel] Started:",e.url),this._tunnelUrl=e.url,this._dismissTunnelConnecting(),this._updateTunnelUrlDisplay(e.url),this._updateTunnelIndicator(!0),document.getElementById("welcomeOverlay")?.classList.contains("visible")?(this._updateWelcomeTunnelBtn(!0,e.url,!0),this.showToast("Tunnel active","success")):(this._updateWelcomeTunnelBtn(!0,e.url),this.showToast(`Tunnel active: ${e.url}`,"success"),this.showTunnelQR())},_onTunnelStopped(){console.log("[Tunnel] Stopped"),this._tunnelUrl=null,this._dismissTunnelConnecting(),this._updateTunnelUrlDisplay(null),this._updateWelcomeTunnelBtn(!1),this._updateTunnelIndicator(!1),this.closeTunnelPanel(),this.closeTunnelQR()},_onTunnelProgress(e){console.log("[Tunnel] Progress:",e.message);const t=document.getElementById("tunnelConnectingToast");t&&(t.innerHTML=`<span class="tunnel-spinner"></span> ${e.message}`);const n=document.getElementById("welcomeTunnelBtn");n?.classList.contains("connecting")&&(n.innerHTML=`<span class="tunnel-spinner"></span> ${e.message}`)},_onTunnelError(e){console.warn("[Tunnel] Error:",e.message),this._dismissTunnelConnecting(),this.showToast(`Tunnel error: ${e.message}`,"error");const t=document.getElementById("welcomeTunnelBtn");t&&(t.disabled=!1,t.classList.remove("connecting"))},_onTunnelQrRotated(e){if(e.svg){const t=document.getElementById("tunnelQrContainer");t&&(t.innerHTML=e.svg);const n=document.getElementById("welcomeQrInner");n&&(n.innerHTML=e.svg)}else this._refreshTunnelQrFromApi();this._resetQrCountdown()},_onTunnelQrRegenerated(e){if(e.svg){const t=document.getElementById("tunnelQrContainer");t&&(t.innerHTML=e.svg);const n=document.getElementById("welcomeQrInner");n&&(n.innerHTML=e.svg)}else this._refreshTunnelQrFromApi();this._resetQrCountdown()},_onTunnelQrAuthUsed(e){const n=(e.ua||"Unknown device").match(/Chrome|Firefox|Safari|Edge|Mobile/)?.[0]||"Browser";this.showToast(`Device authenticated via QR (${n}, ${e.ip}). Not you?`,"warning",{duration:1e4,action:{label:"Revoke All",onClick:()=>{fetch("/api/auth/revoke",{method:"POST",headers:{"Content-Type":"application/json"},body:"{}"}).then(()=>this.showToast("All sessions revoked","success")).catch(()=>this.showToast("Failed to revoke sessions","error"))}}})},registerServiceWorker(){"serviceWorker"in navigator&&navigator.serviceWorker.register("/sw.js").then(e=>{this._swRegistration=e,navigator.serviceWorker.addEventListener("message",t=>{if(t.data?.type==="notification-click"){const{sessionId:n,action:s,approvalId:o}=t.data;s?this.handleNotificationAction?.(s,o,n):n&&this.sessions.has(n)&&this.selectSession(n),window.focus()}}),e.pushManager.getSubscription().then(t=>{t&&(this._pushSubscription=t,this._updatePushUI(!0))})}).catch(()=>{})},async subscribeToPush(){if(!this._swRegistration){this.showToast("Service worker not available. HTTPS or localhost required.","error");return}try{const e=await this._apiJson("/api/push/vapid-key");if(!e)throw new Error("Failed to get VAPID key");const t=urlBase64ToUint8Array(e.publicKey),n=await this._swRegistration.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:t}),s=n.toJSON(),o=await this._apiJson("/api/push/subscribe",{method:"POST",body:{endpoint:s.endpoint,keys:s.keys,userAgent:navigator.userAgent,pushPreferences:this._buildPushPreferences()}});if(!o)throw new Error("Failed to register subscription");this._pushSubscription=n,this._pushSubscriptionId=o.id,localStorage.setItem("codeman-push-subscription-id",o.id),this._updatePushUI(!0),this.showToast("Push notifications enabled","success")}catch(e){this.showToast("Push subscription failed: "+(e.message||e),"error")}},async unsubscribeFromPush(){try{this._pushSubscription&&await this._pushSubscription.unsubscribe();const e=this._pushSubscriptionId||localStorage.getItem("codeman-push-subscription-id");e&&await fetch(`/api/push/subscribe/${e}`,{method:"DELETE"}).catch(()=>{}),this._pushSubscription=null,this._pushSubscriptionId=null,localStorage.removeItem("codeman-push-subscription-id"),this._updatePushUI(!1),this.showToast("Push notifications disabled","success")}catch(e){this.showToast("Failed to unsubscribe: "+(e.message||e),"error")}},async togglePushSubscription(){this._pushSubscription?await this.unsubscribeFromPush():await this.subscribeToPush()},async _syncPushPreferences(){const e=this._pushSubscriptionId||localStorage.getItem("codeman-push-subscription-id");if(e)try{await fetch(`/api/push/subscribe/${e}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({pushPreferences:this._buildPushPreferences()})})}catch{}},_buildPushPreferences(){const e={},t={"hook:permission_prompt":"eventPermissionPush","hook:elicitation_dialog":"eventQuestionPush","hook:idle_prompt":"eventIdlePush","hook:stop":"eventStopPush","respawn:blocked":"eventRespawnPush","session:ralphCompletionDetected":"eventRalphPush"};for(const[n,s]of Object.entries(t)){const o=document.getElementById(s);e[n]=o?o.checked:!0}return e["session:error"]=!0,e},_updatePushUI(e){const t=document.getElementById("pushSubscribeBtn"),n=document.getElementById("pushSubscriptionStatus");t&&(t.textContent=e?"Unsubscribe":"Subscribe"),n&&(n.textContent=e?"active":"off",n.classList.remove("granted","denied"),e&&n.classList.add("granted"))},openAppSettings(){const e=this.loadAppSettingsFromStorage();document.getElementById("appSettingsDisplayName").value=e.displayName||"Codeman",document.getElementById("appSettingsLanguage").value=e.language==="zh-CN"?"zh-CN":"en",document.getElementById("appSettingsClaudeMdPath").value=e.defaultClaudeMdPath||"",document.getElementById("appSettingsDefaultDir").value=e.defaultWorkingDir||"";const t=this.getDefaultSettings();document.getElementById("appSettingsRalphEnabled").checked=e.ralphTrackerEnabled??t.ralphTrackerEnabled??!1,document.getElementById("appSettingsShowFontControls").checked=e.showFontControls??t.showFontControls??!1,document.getElementById("appSettingsShowSystemStats").checked=e.showSystemStats??t.showSystemStats??!0,document.getElementById("appSettingsShowLifecycleLog").checked=e.showLifecycleLog??t.showLifecycleLog??!1,document.getElementById("appSettingsShowResponseViewer").checked=e.showResponseViewer??t.showResponseViewer??!1,document.getElementById("appSettingsShowFileViewerButton").checked=e.showFileViewerButton??t.showFileViewerButton??!0,document.getElementById("appSettingsShowAttachmentsButton").checked=e.showAttachmentsButton??t.showAttachmentsButton??!1,document.getElementById("appSettingsSkin").value=e.skin??t.skin??"daylight-blue",this._syncEntranceAnimSetting?.(),document.getElementById("appSettingsWebglRenderer").checked=e.webglRendererEnabled??t.webglRendererEnabled??!0;const n=document.getElementById("appSettingsWebglRendererItem");n&&(n.style.display=MobileDetection.getDeviceType()==="desktop"?"":"none"),document.getElementById("appSettingsShowMonitor").checked=e.showMonitor??t.showMonitor??!1,document.getElementById("appSettingsShowProjectInsights").checked=e.showProjectInsights??t.showProjectInsights??!1,document.getElementById("appSettingsShowFileBrowser").checked=e.showFileBrowser??t.showFileBrowser??!1,document.getElementById("appSettingsShowSubagents").checked=e.showSubagents??t.showSubagents??!1,document.getElementById("appSettingsShowUltracodeAgents").checked=e.showUltracodeAgents??t.showUltracodeAgents??!1,document.getElementById("appSettingsApprovalsInbox").checked=e.approvalsInboxEnabled===!0,document.getElementById("appSettingsReadMyMind").checked=e.readMyMindEnabled===!0,document.getElementById("appSettingsUltracodeFloatingWindows").checked=e.ultracodeFloatingWindows??t.ultracodeFloatingWindows??!1,document.getElementById("appSettingsShowMultiMonitorButton").checked=e.showMultiMonitorButton??t.showMultiMonitorButton??!1,document.getElementById("appSettingsShowPlanUsageLimits").checked=this.planUsageChipEnabled(e),document.getElementById("appSettingsShowRedrawButton").checked=e.showRedrawButton??t.showRedrawButton??!1,document.getElementById("appSettingsMobileOverview").checked=e.mobileOverviewEnabled??t.mobileOverviewEnabled??!1;const s=MobileDetection.getDeviceType()==="mobile"?"":"none",o=document.getElementById("appSettingsMobileOverviewItem");o&&(o.style.display=s);const i=document.getElementById("appSettingsPhoneSection");i&&(i.style.display=s),document.getElementById("appSettingsShowSessionButton").checked=e.showSessionButton??t.showSessionButton??!1,document.getElementById("appSettingsShowAwayDigestButton").checked=e.showAwayDigestButton??t.showAwayDigestButton??!1,document.getElementById("appSettingsShowCronButton").checked=e.showCronButton??t.showCronButton??!1;const a=document.getElementById("appSettingsGestureControlItem");a&&(a.style.display=window.__codemanGestureAvailable?"":"none"),document.getElementById("appSettingsGestureControl").checked=e.gestureControlEnabled??t.gestureControlEnabled??!1,document.getElementById("appSettingsSubagentTracking").checked=e.subagentTrackingEnabled??t.subagentTrackingEnabled??!0,document.getElementById("appSettingsSubagentActiveTabOnly").checked=e.subagentActiveTabOnly??t.subagentActiveTabOnly??!0,document.getElementById("appSettingsImageWatcherEnabled").checked=e.imageWatcherEnabled??t.imageWatcherEnabled??!1,document.getElementById("appSettingsTunnelEnabled").checked=e.tunnelEnabled??!1,this.loadTunnelStatus(),document.getElementById("appSettingsLocalEcho").checked=e.localEchoEnabled??MobileDetection.isTouchDevice(),document.getElementById("appSettingsTerminalWheelLocal").checked=e.terminalWheelLocalScrollback??t.terminalWheelLocalScrollback??!1,document.getElementById("appSettingsCjkInput").checked=e.cjkInputEnabled??t.cjkInputEnabled??!1,document.getElementById("appSettingsExtendedKeyboardBar").checked=e.extendedKeyboardBar??!1,document.getElementById("appSettingsTabTwoRows").checked=e.tabTwoRows??t.tabTwoRows??!1,document.getElementById("appSettingsShowTabDetachButton").checked=e.showTabDetachButton??t.showTabDetachButton??!1;const l=document.getElementById("appSettingsClaudeMode"),r=document.getElementById("allowedToolsRow");l.value=e.claudeMode||"dangerously-skip-permissions",document.getElementById("appSettingsAllowedTools").value=e.allowedTools||"",r.style.display=l.value==="allowedTools"?"":"none",l.onchange=()=>{r.style.display=l.value==="allowedTools"?"":"none"},document.getElementById("appSettingsCodexDangerouslyBypassApprovals").checked=e.codexDangerouslyBypassApprovals??!1,document.getElementById("appSettingsCodexAnimations").checked=e.codexAnimationsEnabled??!1,this._applyCodexSettingsVisibility(),document.getElementById("appSettingsAgentTeams").checked=e.agentTeamsEnabled??!1,document.getElementById("appSettingsAgentSkill").checked=e.agentSkillEnabled??!1,document.getElementById("appSettingsClaudeModel").value=e.claudeModel??"",document.getElementById("appSettingsOpusContext1m").checked=e.opusContext1mEnabled??!1,document.getElementById("appSettingsRemoteAutoReconnect").checked=e.remoteAutoReconnect??!0,document.getElementById("appSettingsThinkingEffort").value=e.thinkingEffort??"";const d=e.nice||{};document.getElementById("appSettingsNiceEnabled").checked=d.enabled??!1,document.getElementById("appSettingsNiceValue").value=d.niceValue??10,this.loadModelConfigForSettings();const c=this.notificationManager?.preferences||{};document.getElementById("appSettingsNotifEnabled").checked=c.enabled??!0,document.getElementById("appSettingsNotifBrowser").checked=c.browserNotifications??!1,document.getElementById("appSettingsNotifAudio").checked=c.audioAlerts??!1,document.getElementById("appSettingsNotifStuckMins").value=Math.round((c.stuckThresholdMs||6e5)/6e4),document.getElementById("appSettingsNotifCritical").checked=!c.muteCritical,document.getElementById("appSettingsNotifWarning").checked=!c.muteWarning,document.getElementById("appSettingsNotifInfo").checked=!c.muteInfo,document.getElementById("appSettingsPushEnabled").checked=!!this._pushSubscription,this._updatePushUI(!!this._pushSubscription);const u=c.eventTypes||{},p=u.permission_prompt||{};document.getElementById("eventPermissionEnabled").checked=p.enabled??!0,document.getElementById("eventPermissionBrowser").checked=p.browser??!0,document.getElementById("eventPermissionPush").checked=p.push??!1,document.getElementById("eventPermissionAudio").checked=p.audio??!0;const h=u.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 b=u.idle_prompt||{};document.getElementById("eventIdleEnabled").checked=b.enabled??!0,document.getElementById("eventIdleBrowser").checked=b.browser??!0,document.getElementById("eventIdlePush").checked=b.push??!1,document.getElementById("eventIdleAudio").checked=b.audio??!1;const y=u.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=u.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 f=u.ralph_complete||{};document.getElementById("eventRalphEnabled").checked=f.enabled??!0,document.getElementById("eventRalphBrowser").checked=f.browser??!0,document.getElementById("eventRalphPush").checked=f.push??!1,document.getElementById("eventRalphAudio").checked=f.audio??!0;const v=u.subagent_spawn||{};document.getElementById("eventSubagentEnabled").checked=v.enabled??!1,document.getElementById("eventSubagentBrowser").checked=v.browser??!1,document.getElementById("eventSubagentPush").checked=v.push??!1,document.getElementById("eventSubagentAudio").checked=v.audio??!1;const g=document.getElementById("notifPermissionStatus");if(g&&typeof Notification<"u"){const m=Notification.permission;g.textContent=m==="granted"?"\u2713":m==="denied"?"\u2717":"?",g.classList.remove("granted","denied"),m==="granted"?g.classList.add("granted"):m==="denied"&&g.classList.add("denied")}const E=VoiceInput._getDeepgramConfig();document.getElementById("voiceDeepgramKey").value=E.apiKey||"",document.getElementById("voiceLanguage").value=E.language||"en-US",document.getElementById("voiceKeyterms").value=E.keyterms||"refactor, endpoint, middleware, callback, async, regex, TypeScript, npm, API, deploy, config, linter, env, webhook, schema, CLI, JSON, CSS, DOM, SSE, backend, frontend, localhost, dependencies, repository, merge, rebase, diff, commit, com",document.getElementById("voiceInsertMode").value=E.insertMode||"direct";const I=document.getElementById("voiceDeepgramKey");I.type="password",document.getElementById("voiceKeyToggleBtn").textContent="Show";const w=VoiceInput.getActiveProviderName(),B=document.getElementById("voiceProviderStatus");B.textContent=w,B.className="voice-provider-status"+(w.startsWith("Deepgram")?" active":""),this._initUpdatesSection(),this.switchSettingsTab("settings-display");const T=document.getElementById("appSettingsModal");T.querySelectorAll(".modal-tabs .modal-tab-btn").forEach(m=>{m.onclick=()=>this.switchSettingsTab(m.dataset.tab)}),T.classList.add("active"),this.activeFocusTrap=new FocusTrap(T),this.activeFocusTrap.activate()},_applyCodexSettingsVisibility(){const e=document.querySelector('#appSettingsModal .modal-tab-btn[data-tab="settings-codex"]');e&&(e.style.display=window.__codemanCliAvailable?.codex===!0?"":"none")},switchSettingsTab(e){const t=document.getElementById("appSettingsModal");t.querySelectorAll(".modal-tabs .modal-tab-btn").forEach(n=>{n.classList.toggle("active",n.dataset.tab===e)}),t.querySelectorAll(".modal-tab-content").forEach(n=>{n.classList.toggle("hidden",n.id!==e)}),e==="settings-shortcuts"&&this.renderShortcutSettingsList?.()},closeAppSettings(){document.getElementById("appSettingsModal").classList.remove("active"),this.activeFocusTrap&&(this.activeFocusTrap.deactivate(),this.activeFocusTrap=null)},_updatePhaseText(e){return{queued:"Queued\u2026",preparing:"Preparing\u2026",stashing:"Stashing local changes\u2026",fetching:"Fetching release\u2026",checkout:"Checking out release\u2026",installing:"Installing dependencies\u2026",building:"Building\u2026",restarting:"Restarting Codeman\u2026"}[e]||e},_initUpdatesSection(){const e=this.$("updateCurrentVersion");e&&(e.textContent=(this.$("versionDisplay")?.textContent||"").trim()||"\u2014");for(const t of["updateResult","updateActionRow","updateNotes","updateProgress"]){const n=this.$(t);n&&(n.style.display="none")}this._updateCheck=null},_setUpdateResult(e){const t=this.$("updateResult");t&&(t.style.display="block",t.innerHTML=e)},_setUpdateProgress(e){const t=this.$("updateProgress");t&&(t.style.display="block",t.innerHTML=e)},async checkForUpdate(){const e=this.$("updateCheckBtn");e&&(e.disabled=!0,e.textContent="Checking\u2026");const t=await this._apiJson("/api/system/update/check");e&&(e.disabled=!1,e.textContent="Check now");const n=this.$("updateActionRow"),s=this.$("updateNotes");if(n&&(n.style.display="none"),s&&(s.style.display="none"),!t){this._setUpdateResult("Could not check for updates. Try again later.");return}this._updateCheck=t;const o=this.$("updateCurrentVersion");if(o&&t.currentVersion&&(o.textContent=`v${t.currentVersion}`),t.installKind&&t.installKind!=="git"){this._setUpdateResult(`This install can't update itself (${escapeHtml(t.installKind)}). Update with <code>npm i -g aicodeman@latest</code>.`);return}if(t.selfUpdateEnabled===!1){this._setUpdateResult("In-app updates are disabled on this server (CODEMAN_DISABLE_SELF_UPDATE=1).");return}if(t.error&&!t.updateAvailable){this._setUpdateResult(escapeHtml(t.error));return}if(t.updateAvailable&&t.latestVersion){this._setUpdateResult(`Update available: <strong>v${escapeHtml(t.latestVersion)}</strong> &nbsp;(current v${escapeHtml(t.currentVersion||"")})`);const i=this.$("updateActionLabel");i&&(i.textContent=`Update to v${t.latestVersion}`),n&&(n.style.display="flex");const a=this.$("updateNowBtn");a&&(a.disabled=!1,a.textContent="Update now"),s&&t.notes&&(s.style.display="block",s.textContent=t.notes)}else this._setUpdateResult(`You're up to date (v${escapeHtml(t.currentVersion||"")}).`)},async startSelfUpdate(){const e=this._updateCheck?.latestVersion?`v${this._updateCheck.latestVersion}`:"the latest release";if(!confirm(`Update Codeman to ${e}? The server will restart and this page will reload.`))return;const t=this.$("updateNowBtn");t&&(t.disabled=!0,t.textContent="Starting\u2026");const n=await this._apiPost("/api/system/update",{});if(!n||!n.ok){let i="Failed to start the update.";try{const a=await n.json();typeof a?.error=="string"&&a.error&&(i=a.error)}catch{}this._setUpdateProgress(`<span style="color:var(--danger,#e5534b)">${escapeHtml(i)}</span>`),t&&(t.disabled=!1,t.textContent="Update now");return}const s=this.$("updateActionRow");s&&(s.style.display="none");const o=this.$("updateNotes");o&&(o.style.display="none"),this._setUpdateProgress("Starting update\u2026"),this._pollUpdateStatus()},_stopUpdatePolling(){this._updatePollTimer&&(clearInterval(this._updatePollTimer),this._updatePollTimer=null)},_pollUpdateStatus(){this._stopUpdatePolling();const e=new Set(["completed","completed-needs-manual-restart","failed","idle"]),t=async()=>{let n=null;try{const s=await fetch("/api/system/update/status");if(s.ok){const o=await s.json();n=o&&o.success===!0?o.data:o}}catch{}if(!n){this._setUpdateProgress("\u21BB Restarting Codeman\u2026");return}if(!e.has(n.phase)){const s=n.message&&n.message.trim()?n.message.trim():this._updatePhaseText(n.phase);let o="";n.startedAt&&(o=` <span style="color:var(--text-secondary)">\xB7 ${Math.max(0,Math.round((Date.now()-n.startedAt)/1e3))}s</span>`),this._setUpdateProgress(`<span class="tunnel-spinner"></span> ${escapeHtml(s)}${o}`);return}if(this._stopUpdatePolling(),n.phase==="completed"){let s=`<span style="color:var(--success,#3fb950)">\u2713 Updated to v${escapeHtml(n.toVersion||"")}. Reloading\u2026</span>`;n.stashRef&&(s+=`<br><span style="color:var(--text-secondary)">Local changes stashed as <code>${escapeHtml(n.stashRef)}</code> \u2014 run <code>git stash pop</code> to restore.</span>`),this._setUpdateProgress(s),setTimeout(()=>location.reload(),2500)}else if(n.phase==="completed-needs-manual-restart")this._setUpdateProgress(`Update staged. Restart Codeman to apply:<br><code>${escapeHtml(n.manualRestartCommand||"restart codeman web")}</code>`);else if(n.phase==="failed"){let s=`<span style="color:var(--danger,#e5534b)">\u2717 ${escapeHtml(n.message||"Update failed")}.</span>`;n.error&&(s+=`<br><span style="color:var(--text-secondary)">${escapeHtml(n.error)}</span>`),s+='<br><span style="color:var(--text-secondary)">The previous version is still running.</span>',n.stashRef&&(s+=`<br><span style="color:var(--text-secondary)">Local changes stashed as <code>${escapeHtml(n.stashRef)}</code>.</span>`),this._setUpdateProgress(s);const o=this.$("updateNowBtn"),i=this.$("updateActionRow");o&&(o.disabled=!1,o.textContent="Try again"),i&&(i.style.display="flex")}};t(),this._updatePollTimer=setInterval(t,1500)},isCliAvailable(e){const t=window.__codemanCliAvailable;return!t||typeof t!="object"?!0:t[e]!==!1},applyWelcomeCliVisibility(){const e=[["welcomeClaudeBtn","claude"],["welcomeOpencodeBtn","opencode"],["welcomeAntigravityBtn","antigravity"],["welcomeGeminiBtn","gemini"],["welcomeTunnelBtn","cloudflared"]];for(const[t,n]of e){const s=document.getElementById(t);s&&(s.style.display=this.isCliAvailable(n)?"flex":"none")}},async loadTunnelStatus(){try{const t=await(await fetch("/api/tunnel/status")).json(),n=t?.success===!0?t.data:t,s=n.running&&n.url;this._tunnelUrl=s?n.url:null,this._updateTunnelUrlDisplay(this._tunnelUrl),this._updateWelcomeTunnelBtn(!!s,this._tunnelUrl),this._updateTunnelIndicator(!!s)}catch{this._tunnelUrl=null,this._updateTunnelUrlDisplay(null),this._updateWelcomeTunnelBtn(!1),this._updateTunnelIndicator(!1)}},_updateTunnelUrlRow(e,t,n,s=""){const o=document.getElementById(e),i=document.getElementById(t);if(!(!o||!i))if(n){const a=n+s;o.style.display="",i.textContent=a,i.onclick=()=>{navigator.clipboard.writeText(a).then(()=>{this.showToast(`${s?"Upload":"Tunnel"} URL copied`,"success")})}}else o.style.display="none",i.textContent="",i.onclick=null},_updateTunnelUrlDisplay(e){this._updateTunnelUrlRow("tunnelUrlRow","tunnelUrlDisplay",e),this._updateTunnelUrlRow("tunnelUploadUrlRow","tunnelUploadUrlDisplay",e,"/upload.html")},showTunnelQR(){this.closeTunnelQR();const e=document.createElement("div");e.id="tunnelQrOverlay",e.style.cssText="position:fixed;inset:0;background:rgba(0,0,0,0.7);z-index:5000;display:flex;align-items:center;justify-content:center;cursor:pointer",e.onclick=n=>{n.target===e&&this.closeTunnelQR()};const t=document.createElement("div");t.style.cssText="background:var(--bg-card);border:1px solid var(--border);border-radius:12px;padding:24px;text-align:center;max-width:340px;width:90vw;box-shadow:var(--shadow-lg);cursor:default",t.innerHTML=`
1
+ "use strict";Object.assign(CodemanApp.prototype,{_onHookIdlePrompt(e){e.sessionId&&this.setPendingHook(e.sessionId,"idle_prompt"),this._notifySession(e.sessionId,"warning","hook-idle","Waiting for Input",e.message||"Claude is idle and waiting for a prompt")},_onHookPermissionPrompt(e){e.sessionId&&this.setPendingHook(e.sessionId,"permission_prompt");const t=e.tool?`${e.tool}${e.command?": "+e.command:e.file?": "+e.file:""}`:"";this._notifySession(e.sessionId,"critical","hook-permission","Permission Required",t||"Claude needs tool approval to continue")},_onHookElicitationDialog(e){e.sessionId&&this.setPendingHook(e.sessionId,"elicitation_dialog"),this._notifySession(e.sessionId,"critical","hook-elicitation","Question Asked",e.question||"Claude is asking a question and waiting for your answer")},_onHookElicitationComplete(e){e.sessionId&&this.clearPendingHooks(e.sessionId,"elicitation_dialog")},_onHookElicitationResponse(e){this._onHookElicitationComplete(e)},_onHookStop(e){e.sessionId&&this.clearPendingHooks(e.sessionId),this._notifySession(e.sessionId,"info","hook-stop","Response Complete",e.reason||"Claude has finished responding")},_onHookTeammateIdle(e){const t=this.sessions.get(e.sessionId);this._notifySession(e.sessionId,"warning","hook-teammate-idle","Teammate Idle",`A teammate is idle in ${t?.name||e.sessionId}`)},_onHookTaskCompleted(e){const t=this.sessions.get(e.sessionId);this._notifySession(e.sessionId,"info","hook-task-completed","Task Completed",`A team task completed in ${t?.name||e.sessionId}`)},_onTunnelStarted(e){console.log("[Tunnel] Started:",e.url),this._tunnelUrl=e.url,this._dismissTunnelConnecting(),this._updateTunnelUrlDisplay(e.url),this._updateTunnelIndicator(!0),document.getElementById("welcomeOverlay")?.classList.contains("visible")?(this._updateWelcomeTunnelBtn(!0,e.url,!0),this.showToast("Tunnel active","success")):(this._updateWelcomeTunnelBtn(!0,e.url),this.showToast(`Tunnel active: ${e.url}`,"success"),this.showTunnelQR())},_onTunnelStopped(){console.log("[Tunnel] Stopped"),this._tunnelUrl=null,this._dismissTunnelConnecting(),this._updateTunnelUrlDisplay(null),this._updateWelcomeTunnelBtn(!1),this._updateTunnelIndicator(!1),this.closeTunnelPanel(),this.closeTunnelQR()},_onTunnelProgress(e){console.log("[Tunnel] Progress:",e.message);const t=document.getElementById("tunnelConnectingToast");t&&(t.innerHTML=`<span class="tunnel-spinner"></span> ${e.message}`);const n=document.getElementById("welcomeTunnelBtn");n?.classList.contains("connecting")&&(n.innerHTML=`<span class="tunnel-spinner"></span> ${e.message}`)},_onTunnelError(e){console.warn("[Tunnel] Error:",e.message),this._dismissTunnelConnecting(),this.showToast(`Tunnel error: ${e.message}`,"error");const t=document.getElementById("welcomeTunnelBtn");t&&(t.disabled=!1,t.classList.remove("connecting"))},_onTunnelQrRotated(e){if(e.svg){const t=document.getElementById("tunnelQrContainer");t&&(t.innerHTML=e.svg);const n=document.getElementById("welcomeQrInner");n&&(n.innerHTML=e.svg)}else this._refreshTunnelQrFromApi();this._resetQrCountdown()},_onTunnelQrRegenerated(e){if(e.svg){const t=document.getElementById("tunnelQrContainer");t&&(t.innerHTML=e.svg);const n=document.getElementById("welcomeQrInner");n&&(n.innerHTML=e.svg)}else this._refreshTunnelQrFromApi();this._resetQrCountdown()},_onTunnelQrAuthUsed(e){const n=(e.ua||"Unknown device").match(/Chrome|Firefox|Safari|Edge|Mobile/)?.[0]||"Browser";this.showToast(`Device authenticated via QR (${n}, ${e.ip}). Not you?`,"warning",{duration:1e4,action:{label:"Revoke All",onClick:()=>{fetch("/api/auth/revoke",{method:"POST",headers:{"Content-Type":"application/json"},body:"{}"}).then(()=>this.showToast("All sessions revoked","success")).catch(()=>this.showToast("Failed to revoke sessions","error"))}}})},registerServiceWorker(){"serviceWorker"in navigator&&navigator.serviceWorker.register("/sw.js").then(e=>{this._swRegistration=e,navigator.serviceWorker.addEventListener("message",t=>{if(t.data?.type==="notification-click"){const{sessionId:n,action:s,approvalId:o}=t.data;s?this.handleNotificationAction?.(s,o,n):n&&this.sessions.has(n)&&this.selectSession(n),window.focus()}}),e.pushManager.getSubscription().then(t=>{t&&(this._pushSubscription=t,this._updatePushUI(!0))})}).catch(()=>{})},async subscribeToPush(){if(!this._swRegistration){this.showToast("Service worker not available. HTTPS or localhost required.","error");return}try{const e=await this._apiJson("/api/push/vapid-key");if(!e)throw new Error("Failed to get VAPID key");const t=urlBase64ToUint8Array(e.publicKey),n=await this._swRegistration.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:t}),s=n.toJSON(),o=await this._apiJson("/api/push/subscribe",{method:"POST",body:{endpoint:s.endpoint,keys:s.keys,userAgent:navigator.userAgent,pushPreferences:this._buildPushPreferences()}});if(!o)throw new Error("Failed to register subscription");this._pushSubscription=n,this._pushSubscriptionId=o.id,localStorage.setItem("codeman-push-subscription-id",o.id),this._updatePushUI(!0),this.showToast("Push notifications enabled","success")}catch(e){this.showToast("Push subscription failed: "+(e.message||e),"error")}},async unsubscribeFromPush(){try{this._pushSubscription&&await this._pushSubscription.unsubscribe();const e=this._pushSubscriptionId||localStorage.getItem("codeman-push-subscription-id");e&&await fetch(`/api/push/subscribe/${e}`,{method:"DELETE"}).catch(()=>{}),this._pushSubscription=null,this._pushSubscriptionId=null,localStorage.removeItem("codeman-push-subscription-id"),this._updatePushUI(!1),this.showToast("Push notifications disabled","success")}catch(e){this.showToast("Failed to unsubscribe: "+(e.message||e),"error")}},async togglePushSubscription(){this._pushSubscription?await this.unsubscribeFromPush():await this.subscribeToPush()},async _syncPushPreferences(){const e=this._pushSubscriptionId||localStorage.getItem("codeman-push-subscription-id");if(e)try{await fetch(`/api/push/subscribe/${e}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({pushPreferences:this._buildPushPreferences()})})}catch{}},_buildPushPreferences(){const e={},t={"hook:permission_prompt":"eventPermissionPush","hook:elicitation_dialog":"eventQuestionPush","hook:idle_prompt":"eventIdlePush","hook:stop":"eventStopPush","respawn:blocked":"eventRespawnPush","session:ralphCompletionDetected":"eventRalphPush"};for(const[n,s]of Object.entries(t)){const o=document.getElementById(s);e[n]=o?o.checked:!0}return e["session:error"]=!0,e},_updatePushUI(e){const t=document.getElementById("pushSubscribeBtn"),n=document.getElementById("pushSubscriptionStatus");t&&(t.textContent=e?"Unsubscribe":"Subscribe"),n&&(n.textContent=e?"active":"off",n.classList.remove("granted","denied"),e&&n.classList.add("granted"))},openAppSettings(){const e=this.loadAppSettingsFromStorage();document.getElementById("appSettingsDisplayName").value=e.displayName||"Codeman",document.getElementById("appSettingsLanguage").value=e.language==="zh-CN"?"zh-CN":"en",document.getElementById("appSettingsClaudeMdPath").value=e.defaultClaudeMdPath||"",document.getElementById("appSettingsDefaultDir").value=e.defaultWorkingDir||"";const t=this.getDefaultSettings();document.getElementById("appSettingsRalphEnabled").checked=e.ralphTrackerEnabled??t.ralphTrackerEnabled??!1,document.getElementById("appSettingsShowFontControls").checked=e.showFontControls??t.showFontControls??!1,document.getElementById("appSettingsShowSystemStats").checked=e.showSystemStats??t.showSystemStats??!0,document.getElementById("appSettingsShowLifecycleLog").checked=e.showLifecycleLog??t.showLifecycleLog??!1,document.getElementById("appSettingsShowResponseViewer").checked=e.showResponseViewer??t.showResponseViewer??!1,document.getElementById("appSettingsShowFileViewerButton").checked=e.showFileViewerButton??t.showFileViewerButton??!0,document.getElementById("appSettingsShowAttachmentsButton").checked=e.showAttachmentsButton??t.showAttachmentsButton??!1,document.getElementById("appSettingsSkin").value=e.skin??t.skin??"daylight-blue",this._syncEntranceAnimSetting?.(),document.getElementById("appSettingsWebglRenderer").checked=e.webglRendererEnabled??t.webglRendererEnabled??!0;const n=document.getElementById("appSettingsWebglRendererItem");n&&(n.style.display=MobileDetection.getDeviceType()==="desktop"?"":"none"),document.getElementById("appSettingsShowMonitor").checked=e.showMonitor??t.showMonitor??!1,document.getElementById("appSettingsShowProjectInsights").checked=e.showProjectInsights??t.showProjectInsights??!1,document.getElementById("appSettingsShowFileBrowser").checked=e.showFileBrowser??t.showFileBrowser??!1,document.getElementById("appSettingsShowSubagents").checked=e.showSubagents??t.showSubagents??!1,document.getElementById("appSettingsShowUltracodeAgents").checked=e.showUltracodeAgents??t.showUltracodeAgents??!1,document.getElementById("appSettingsApprovalsInbox").checked=e.approvalsInboxEnabled===!0,document.getElementById("appSettingsReadMyMind").checked=e.readMyMindEnabled===!0,document.getElementById("appSettingsUltracodeFloatingWindows").checked=e.ultracodeFloatingWindows??t.ultracodeFloatingWindows??!1,document.getElementById("appSettingsShowMultiMonitorButton").checked=e.showMultiMonitorButton??t.showMultiMonitorButton??!1,document.getElementById("appSettingsShowPlanUsageLimits").checked=this.planUsageChipEnabled(e),document.getElementById("appSettingsShowRedrawButton").checked=e.showRedrawButton??t.showRedrawButton??!1,document.getElementById("appSettingsMobileOverview").checked=e.mobileOverviewEnabled??t.mobileOverviewEnabled??!1;const s=document.getElementById("appSettingsMobileOverviewItem");s&&(s.style.display=MobileDetection.getDeviceType()==="mobile"?"":"none"),document.getElementById("appSettingsShowSessionButton").checked=e.showSessionButton??t.showSessionButton??!1,document.getElementById("appSettingsShowAwayDigestButton").checked=e.showAwayDigestButton??t.showAwayDigestButton??!1,document.getElementById("appSettingsShowCronButton").checked=e.showCronButton??t.showCronButton??!1;const o=document.getElementById("appSettingsGestureControlItem");o&&(o.style.display=window.__codemanGestureAvailable?"":"none"),document.getElementById("appSettingsGestureControl").checked=e.gestureControlEnabled??t.gestureControlEnabled??!1,document.getElementById("appSettingsSubagentTracking").checked=e.subagentTrackingEnabled??t.subagentTrackingEnabled??!0,document.getElementById("appSettingsSubagentActiveTabOnly").checked=e.subagentActiveTabOnly??t.subagentActiveTabOnly??!0,document.getElementById("appSettingsImageWatcherEnabled").checked=e.imageWatcherEnabled??t.imageWatcherEnabled??!1,document.getElementById("appSettingsTunnelEnabled").checked=e.tunnelEnabled??!1,this.loadTunnelStatus(),document.getElementById("appSettingsLocalEcho").checked=e.localEchoEnabled??MobileDetection.isTouchDevice(),document.getElementById("appSettingsTerminalWheelLocal").checked=e.terminalWheelLocalScrollback??t.terminalWheelLocalScrollback??!1,document.getElementById("appSettingsCjkInput").checked=e.cjkInputEnabled??t.cjkInputEnabled??!1,document.getElementById("appSettingsExtendedKeyboardBar").checked=e.extendedKeyboardBar??!1,document.getElementById("appSettingsTabTwoRows").checked=e.tabTwoRows??t.tabTwoRows??!1,document.getElementById("appSettingsShowTabDetachButton").checked=e.showTabDetachButton??t.showTabDetachButton??!1;const i=document.getElementById("appSettingsClaudeMode"),a=document.getElementById("allowedToolsRow");i.value=e.claudeMode||"dangerously-skip-permissions",document.getElementById("appSettingsAllowedTools").value=e.allowedTools||"",a.style.display=i.value==="allowedTools"?"":"none",i.onchange=()=>{a.style.display=i.value==="allowedTools"?"":"none"},document.getElementById("appSettingsCodexDangerouslyBypassApprovals").checked=e.codexDangerouslyBypassApprovals??!1,document.getElementById("appSettingsCodexAnimations").checked=e.codexAnimationsEnabled??!1,this._applyCodexSettingsVisibility(),document.getElementById("appSettingsAgentTeams").checked=e.agentTeamsEnabled??!1,document.getElementById("appSettingsAgentSkill").checked=e.agentSkillEnabled??!1,document.getElementById("appSettingsClaudeModel").value=e.claudeModel??"",document.getElementById("appSettingsOpusContext1m").checked=e.opusContext1mEnabled??!1,document.getElementById("appSettingsRemoteAutoReconnect").checked=e.remoteAutoReconnect??!0,document.getElementById("appSettingsThinkingEffort").value=e.thinkingEffort??"";const l=e.nice||{};document.getElementById("appSettingsNiceEnabled").checked=l.enabled??!1,document.getElementById("appSettingsNiceValue").value=l.niceValue??10,this.loadModelConfigForSettings();const c=this.notificationManager?.preferences||{};document.getElementById("appSettingsNotifEnabled").checked=c.enabled??!0,document.getElementById("appSettingsNotifBrowser").checked=c.browserNotifications??!1,document.getElementById("appSettingsNotifAudio").checked=c.audioAlerts??!1,document.getElementById("appSettingsNotifStuckMins").value=Math.round((c.stuckThresholdMs||6e5)/6e4),document.getElementById("appSettingsNotifCritical").checked=!c.muteCritical,document.getElementById("appSettingsNotifWarning").checked=!c.muteWarning,document.getElementById("appSettingsNotifInfo").checked=!c.muteInfo,document.getElementById("appSettingsPushEnabled").checked=!!this._pushSubscription,this._updatePushUI(!!this._pushSubscription);const d=c.eventTypes||{},r=d.permission_prompt||{};document.getElementById("eventPermissionEnabled").checked=r.enabled??!0,document.getElementById("eventPermissionBrowser").checked=r.browser??!0,document.getElementById("eventPermissionPush").checked=r.push??!1,document.getElementById("eventPermissionAudio").checked=r.audio??!0;const u=d.elicitation_dialog||{};document.getElementById("eventQuestionEnabled").checked=u.enabled??!0,document.getElementById("eventQuestionBrowser").checked=u.browser??!0,document.getElementById("eventQuestionPush").checked=u.push??!1,document.getElementById("eventQuestionAudio").checked=u.audio??!0;const g=d.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 p=d.stop||{};document.getElementById("eventStopEnabled").checked=p.enabled??!1,document.getElementById("eventStopBrowser").checked=p.browser??!1,document.getElementById("eventStopPush").checked=p.push??!1,document.getElementById("eventStopAudio").checked=p.audio??!1;const w=d.respawn_cycle||{};document.getElementById("eventRespawnEnabled").checked=w.enabled??!0,document.getElementById("eventRespawnBrowser").checked=w.browser??!1,document.getElementById("eventRespawnPush").checked=w.push??!1,document.getElementById("eventRespawnAudio").checked=w.audio??!1;const y=d.ralph_complete||{};document.getElementById("eventRalphEnabled").checked=y.enabled??!0,document.getElementById("eventRalphBrowser").checked=y.browser??!0,document.getElementById("eventRalphPush").checked=y.push??!1,document.getElementById("eventRalphAudio").checked=y.audio??!0;const S=d.subagent_spawn||{};document.getElementById("eventSubagentEnabled").checked=S.enabled??!1,document.getElementById("eventSubagentBrowser").checked=S.browser??!1,document.getElementById("eventSubagentPush").checked=S.push??!1,document.getElementById("eventSubagentAudio").checked=S.audio??!1;const h=document.getElementById("notifPermissionStatus");if(h&&typeof Notification<"u"){const m=Notification.permission;h.textContent=m==="granted"?"\u2713":m==="denied"?"\u2717":"?",h.classList.remove("granted","denied"),m==="granted"?h.classList.add("granted"):m==="denied"&&h.classList.add("denied")}const b=VoiceInput._getDeepgramConfig();document.getElementById("voiceDeepgramKey").value=b.apiKey||"",document.getElementById("voiceLanguage").value=b.language||"en-US",document.getElementById("voiceKeyterms").value=b.keyterms||"refactor, endpoint, middleware, callback, async, regex, TypeScript, npm, API, deploy, config, linter, env, webhook, schema, CLI, JSON, CSS, DOM, SSE, backend, frontend, localhost, dependencies, repository, merge, rebase, diff, commit, com",document.getElementById("voiceInsertMode").value=b.insertMode||"direct";const E=document.getElementById("voiceDeepgramKey");E.type="password",document.getElementById("voiceKeyToggleBtn").textContent="Show";const B=VoiceInput.getActiveProviderName(),v=document.getElementById("voiceProviderStatus");v.textContent=B,v.className="voice-provider-status"+(B.startsWith("Deepgram")?" active":""),this._initUpdatesSection(),this._initSettingsNav(),this._syncSettingsChips(),this._syncModelCards(),this._syncEffortSegment(),this.switchSettingsTab("settings-terminal");const f=document.getElementById("appSettingsModal");f.classList.add("active"),this.activeFocusTrap=new FocusTrap(f),this.activeFocusTrap.activate()},_applyCodexSettingsVisibility(){const e=document.getElementById("appSettingsCodexGroup");e&&(e.style.display=window.__codemanCliAvailable?.codex===!0?"":"none")},switchSettingsTab(e){e==="settings-shortcuts"&&this.renderShortcutSettingsList?.();const t=document.getElementById("appSettingsDoc"),n=document.getElementById(e);if(t&&n&&typeof n.offsetTop=="number"){const s=document.getElementById("appSettingsJump"),o=s&&s.offsetParent?s.offsetHeight+16:6;t.scrollTop=Math.max(0,n.offsetTop-o)}this._setActiveSettingsSection(e)},_setActiveSettingsSection(e){const t=document.getElementById("appSettingsModal");if(!t||typeof t.querySelectorAll!="function")return;let n=null;t.querySelectorAll(".set-rail-item").forEach(a=>{const l=a.dataset.section===e;a.classList.toggle("active",l),l&&(n=a)}),t.querySelectorAll(".set-jump-row").forEach(a=>{a.classList.toggle("active",a.dataset.section===e)});const s=document.getElementById("appSettingsJump")?.querySelector(".set-jump-label");s&&n&&(s.textContent=n.textContent.trim());const o=document.getElementById("appSettingsJump")?.querySelector(".set-jump-ico"),i=n?.querySelector("svg");o&&i&&(o.innerHTML=i.innerHTML)},_initSettingsNav(){const e=document.getElementById("appSettingsModal"),t=document.getElementById("appSettingsDoc");if(!e||!t||typeof e.querySelectorAll!="function"||(this._buildModelCards(),this._buildEffortSegment(),this._buildSettingsJumpMenu(),e.dataset.navReady==="1"))return;e.dataset.navReady="1",e.querySelector(".set-rail-items")?.addEventListener("click",i=>{const a=i.target.closest?.(".set-rail-item");a?.dataset.section&&this.switchSettingsTab(a.dataset.section)}),document.getElementById("appSettingsJumpMenu")?.addEventListener("click",i=>{const a=i.target.closest?.(".set-jump-row");a?.dataset.section&&(this._toggleSettingsJump(!1),this.switchSettingsTab(a.dataset.section))}),document.getElementById("appSettingsJump")?.addEventListener("click",()=>this._toggleSettingsJump()),document.getElementById("appSettingsJumpVeil")?.addEventListener("click",()=>this._toggleSettingsJump(!1)),t.addEventListener("scroll",()=>{this._settingsSpyQueued||(this._settingsSpyQueued=!0,requestAnimationFrame(()=>{this._settingsSpyQueued=!1;const i=[...t.querySelectorAll(".set-section")].filter(l=>l.offsetParent!==null);if(!i.length)return;let a=i[0].id;for(const l of i)l.offsetTop-t.scrollTop<=140&&(a=l.id);this._setActiveSettingsSection(a)}))});const n=document.getElementById("appSettingsSearch");n?.addEventListener("input",()=>this._filterSettings(n.value)),e.querySelectorAll(".set-chip input").forEach(i=>{i.addEventListener("change",()=>this._syncSettingsChips())});const s=e.querySelector(".set-group-head-toggle"),o=s?.closest(".set-group-advanced");if(s&&o){const i=()=>{const a=o.classList.toggle("open");s.setAttribute("aria-expanded",a?"true":"false")};s.addEventListener("click",i),s.addEventListener("keydown",a=>{(a.key==="Enter"||a.key===" ")&&(a.preventDefault(),i())})}document.getElementById("appSettingsOpusContext1m")?.addEventListener("change",()=>this._applyModelSelection())},_buildSettingsJumpMenu(){const e=document.getElementById("appSettingsModal"),t=document.getElementById("appSettingsJumpMenu");!e||!t||(t.innerHTML="",e.querySelectorAll(".set-rail-item").forEach(n=>{const s=document.createElement("button");s.type="button",s.className="set-jump-row",s.dataset.section=n.dataset.section,s.innerHTML=n.innerHTML;const o=document.getElementById(n.dataset.section),i=o?o.querySelectorAll("input, select").length:0;if(i){const a=document.createElement("span");a.className="set-jump-count",a.textContent=String(i),s.appendChild(a)}t.appendChild(s)}))},_toggleSettingsJump(e){const t=document.getElementById("appSettingsModal");if(!t)return;const n=e===void 0?!t.classList.contains("jump-open"):e;t.classList.toggle("jump-open",n),document.getElementById("appSettingsJump")?.setAttribute("aria-expanded",n?"true":"false")},_syncSettingsChips(){document.querySelectorAll("#appSettingsModal .set-chip").forEach(e=>{e.classList.toggle("is-on",!!e.querySelector("input")?.checked)})},_buildModelCards(){const e=document.getElementById("appSettingsClaudeModel"),t=document.getElementById("appSettingsModelCards");!e||!t||t.dataset.built==="1"||!e.options||(t.innerHTML="",[...e.options].filter(n=>n.dataset.variant!=="1m").forEach(n=>{const s=document.createElement("button");s.type="button",s.className="set-modelcard",s.setAttribute("role","radio"),s.dataset.value=n.value,n.dataset.ctx==="1"&&(s.dataset.ctx="1");const o=document.createElement("span");o.className="set-mc-top";const i=document.createElement("span");i.className="set-mc-name",i.textContent=n.textContent,o.appendChild(i);const a=document.createElement("span");a.className="set-mc-dot",o.appendChild(a),s.appendChild(o);const l=document.createElement("span");if(l.className="set-mc-meta",l.textContent=n.dataset.meta||"",s.appendChild(l),n.dataset.ctx==="1"){const c=document.createElement("span");c.className="set-mc-ctx",c.textContent="1M capable",s.appendChild(c)}s.addEventListener("click",()=>{this._settingsModelBase=n.value,this._applyModelSelection()}),t.appendChild(s)}),t.dataset.built="1")},_syncModelCards(){const e=document.getElementById("appSettingsClaudeModel");if(!e)return;const t=e.value||"";if(this._settingsModelBase=t.endsWith("[1m]")?t.slice(0,-4):t,t.endsWith("[1m]")){const n=document.getElementById("appSettingsOpusContext1m");n&&(n.checked=!0)}this._applyModelSelection()},_applyModelSelection(){const e=document.getElementById("appSettingsClaudeModel"),t=document.getElementById("appSettingsModelCards");if(!e||!t)return;const n=this._settingsModelBase||"";let s=!1;t.querySelectorAll(".set-modelcard").forEach(c=>{const d=c.dataset.value===n;c.classList.toggle("selected",d),c.setAttribute("aria-checked",d?"true":"false"),d&&(s=c.dataset.ctx==="1")});const o=!!document.getElementById("appSettingsOpusContext1m")?.checked;e.value=n&&s&&o?`${n}[1m]`:n;const i=document.getElementById("appSettingsContextRow"),a=document.getElementById("appSettingsContextDesc"),l=!!n&&!s;i?.classList.toggle("set-row-disabled",l),a&&(a.textContent=l?"The selected model has no 1M variant.":n?"Available for Fable 5, Opus and Opus 4.6.":"With no model pinned, this starts new sessions on Opus with a 1M window.")},_buildEffortSegment(){const e=document.getElementById("appSettingsThinkingEffort"),t=document.getElementById("appSettingsEffortSegment");!e||!t||t.dataset.built==="1"||!e.options||(t.innerHTML="",[...e.options].forEach(n=>{const s=document.createElement("button");s.type="button",s.setAttribute("role","radio"),s.dataset.value=n.value,s.textContent=n.textContent,s.addEventListener("click",()=>{e.value=n.value,this._syncEffortSegment()}),t.appendChild(s)}),t.dataset.built="1")},_syncEffortSegment(){const e=document.getElementById("appSettingsThinkingEffort"),t=document.getElementById("appSettingsEffortSegment");!e||!t||t.querySelectorAll("button").forEach(n=>{const s=n.dataset.value===(e.value||"");n.classList.toggle("selected",s),n.setAttribute("aria-checked",s?"true":"false")})},_filterSettings(e){const t=document.getElementById("appSettingsDoc");if(!t)return;const n=(e||"").trim().toLowerCase(),s=".set-row, .set-chip, .set-modelgrid, .set-minigrid, .event-type-grid, #appSettingsShortcutsList",o=[...t.querySelectorAll(s)];let i=!1;o.forEach(l=>{if(!n){l.classList.remove("set-hit-hidden");return}const d=`${l.dataset?.search||""} ${l.textContent||""}`.toLowerCase().includes(n);l.classList.toggle("set-hit-hidden",!d),d&&(i=!0)}),t.querySelectorAll(".set-chips").forEach(l=>{const c=[...l.querySelectorAll(".set-chip")].some(d=>!d.classList.contains("set-hit-hidden"));l.classList.toggle("set-hit-hidden",!!n&&!c)}),t.querySelectorAll(".set-group").forEach(l=>{const c=[...l.querySelectorAll(s)].some(d=>!d.classList.contains("set-hit-hidden"));l.classList.toggle("set-hit-hidden",!!n&&!c),n&&c&&l.classList.add("open")}),t.querySelectorAll(".set-section").forEach(l=>{const c=[...l.querySelectorAll(".set-group")].some(d=>!d.classList.contains("set-hit-hidden"));l.classList.toggle("set-hit-hidden",!!n&&!c)});const a=document.getElementById("appSettingsSearchEmpty");a&&(a.hidden=!n||i),n||t.querySelectorAll(".set-group-advanced").forEach(l=>l.classList.remove("open"))},closeAppSettings(){this._toggleSettingsJump(!1),document.getElementById("appSettingsModal").classList.remove("active"),this.activeFocusTrap&&(this.activeFocusTrap.deactivate(),this.activeFocusTrap=null)},_updatePhaseText(e){return{queued:"Queued\u2026",preparing:"Preparing\u2026",stashing:"Stashing local changes\u2026",fetching:"Fetching release\u2026",checkout:"Checking out release\u2026",installing:"Installing dependencies\u2026",building:"Building\u2026",restarting:"Restarting Codeman\u2026"}[e]||e},_initUpdatesSection(){const e=this.$("updateCurrentVersion");e&&(e.textContent=(this.$("versionDisplay")?.textContent||"").trim()||"\u2014");for(const t of["updateResult","updateActionRow","updateNotes","updateProgress"]){const n=this.$(t);n&&(n.style.display="none")}this._updateCheck=null},_setUpdateResult(e){const t=this.$("updateResult");t&&(t.style.display="block",t.innerHTML=e)},_setUpdateProgress(e){const t=this.$("updateProgress");t&&(t.style.display="block",t.innerHTML=e)},async checkForUpdate(){const e=this.$("updateCheckBtn");e&&(e.disabled=!0,e.textContent="Checking\u2026");const t=await this._apiJson("/api/system/update/check");e&&(e.disabled=!1,e.textContent="Check now");const n=this.$("updateActionRow"),s=this.$("updateNotes");if(n&&(n.style.display="none"),s&&(s.style.display="none"),!t){this._setUpdateResult("Could not check for updates. Try again later.");return}this._updateCheck=t;const o=this.$("updateCurrentVersion");if(o&&t.currentVersion&&(o.textContent=`v${t.currentVersion}`),t.installKind&&t.installKind!=="git"){this._setUpdateResult(`This install can't update itself (${escapeHtml(t.installKind)}). Update with <code>npm i -g aicodeman@latest</code>.`);return}if(t.selfUpdateEnabled===!1){this._setUpdateResult("In-app updates are disabled on this server (CODEMAN_DISABLE_SELF_UPDATE=1).");return}if(t.error&&!t.updateAvailable){this._setUpdateResult(escapeHtml(t.error));return}if(t.updateAvailable&&t.latestVersion){this._setUpdateResult(`Update available: <strong>v${escapeHtml(t.latestVersion)}</strong> &nbsp;(current v${escapeHtml(t.currentVersion||"")})`);const i=this.$("updateActionLabel");i&&(i.textContent=`Update to v${t.latestVersion}`),n&&(n.style.display="flex");const a=this.$("updateNowBtn");a&&(a.disabled=!1,a.textContent="Update now"),s&&t.notes&&(s.style.display="block",s.textContent=t.notes)}else this._setUpdateResult(`You're up to date (v${escapeHtml(t.currentVersion||"")}).`)},async startSelfUpdate(){const e=this._updateCheck?.latestVersion?`v${this._updateCheck.latestVersion}`:"the latest release";if(!confirm(`Update Codeman to ${e}? The server will restart and this page will reload.`))return;const t=this.$("updateNowBtn");t&&(t.disabled=!0,t.textContent="Starting\u2026");const n=await this._apiPost("/api/system/update",{});if(!n||!n.ok){let i="Failed to start the update.";try{const a=await n.json();typeof a?.error=="string"&&a.error&&(i=a.error)}catch{}this._setUpdateProgress(`<span style="color:var(--danger,#e5534b)">${escapeHtml(i)}</span>`),t&&(t.disabled=!1,t.textContent="Update now");return}const s=this.$("updateActionRow");s&&(s.style.display="none");const o=this.$("updateNotes");o&&(o.style.display="none"),this._setUpdateProgress("Starting update\u2026"),this._pollUpdateStatus()},_stopUpdatePolling(){this._updatePollTimer&&(clearInterval(this._updatePollTimer),this._updatePollTimer=null)},_pollUpdateStatus(){this._stopUpdatePolling();const e=new Set(["completed","completed-needs-manual-restart","failed","idle"]),t=async()=>{let n=null;try{const s=await fetch("/api/system/update/status");if(s.ok){const o=await s.json();n=o&&o.success===!0?o.data:o}}catch{}if(!n){this._setUpdateProgress("\u21BB Restarting Codeman\u2026");return}if(!e.has(n.phase)){const s=n.message&&n.message.trim()?n.message.trim():this._updatePhaseText(n.phase);let o="";n.startedAt&&(o=` <span style="color:var(--text-secondary)">\xB7 ${Math.max(0,Math.round((Date.now()-n.startedAt)/1e3))}s</span>`),this._setUpdateProgress(`<span class="tunnel-spinner"></span> ${escapeHtml(s)}${o}`);return}if(this._stopUpdatePolling(),n.phase==="completed"){let s=`<span style="color:var(--success,#3fb950)">\u2713 Updated to v${escapeHtml(n.toVersion||"")}. Reloading\u2026</span>`;n.stashRef&&(s+=`<br><span style="color:var(--text-secondary)">Local changes stashed as <code>${escapeHtml(n.stashRef)}</code> \u2014 run <code>git stash pop</code> to restore.</span>`),this._setUpdateProgress(s),setTimeout(()=>location.reload(),2500)}else if(n.phase==="completed-needs-manual-restart")this._setUpdateProgress(`Update staged. Restart Codeman to apply:<br><code>${escapeHtml(n.manualRestartCommand||"restart codeman web")}</code>`);else if(n.phase==="failed"){let s=`<span style="color:var(--danger,#e5534b)">\u2717 ${escapeHtml(n.message||"Update failed")}.</span>`;n.error&&(s+=`<br><span style="color:var(--text-secondary)">${escapeHtml(n.error)}</span>`),s+='<br><span style="color:var(--text-secondary)">The previous version is still running.</span>',n.stashRef&&(s+=`<br><span style="color:var(--text-secondary)">Local changes stashed as <code>${escapeHtml(n.stashRef)}</code>.</span>`),this._setUpdateProgress(s);const o=this.$("updateNowBtn"),i=this.$("updateActionRow");o&&(o.disabled=!1,o.textContent="Try again"),i&&(i.style.display="flex")}};t(),this._updatePollTimer=setInterval(t,1500)},isCliAvailable(e){const t=window.__codemanCliAvailable;return!t||typeof t!="object"?!0:t[e]!==!1},applyWelcomeCliVisibility(){const e=[["welcomeClaudeBtn","claude"],["welcomeOpencodeBtn","opencode"],["welcomeAntigravityBtn","antigravity"],["welcomeGeminiBtn","gemini"],["welcomeTunnelBtn","cloudflared"]];for(const[t,n]of e){const s=document.getElementById(t);s&&(s.style.display=this.isCliAvailable(n)?"flex":"none")}},async loadTunnelStatus(){try{const t=await(await fetch("/api/tunnel/status")).json(),n=t?.success===!0?t.data:t,s=n.running&&n.url;this._tunnelUrl=s?n.url:null,this._updateTunnelUrlDisplay(this._tunnelUrl),this._updateWelcomeTunnelBtn(!!s,this._tunnelUrl),this._updateTunnelIndicator(!!s)}catch{this._tunnelUrl=null,this._updateTunnelUrlDisplay(null),this._updateWelcomeTunnelBtn(!1),this._updateTunnelIndicator(!1)}},_updateTunnelUrlRow(e,t,n,s=""){const o=document.getElementById(e),i=document.getElementById(t);if(!(!o||!i))if(n){const a=n+s;o.style.display="",i.textContent=a,i.onclick=()=>{navigator.clipboard.writeText(a).then(()=>{this.showToast(`${s?"Upload":"Tunnel"} URL copied`,"success")})}}else o.style.display="none",i.textContent="",i.onclick=null},_updateTunnelUrlDisplay(e){this._updateTunnelUrlRow("tunnelUrlRow","tunnelUrlDisplay",e),this._updateTunnelUrlRow("tunnelUploadUrlRow","tunnelUploadUrlDisplay",e,"/upload.html")},showTunnelQR(){this.closeTunnelQR();const e=document.createElement("div");e.id="tunnelQrOverlay",e.style.cssText="position:fixed;inset:0;background:rgba(0,0,0,0.7);z-index:5000;display:flex;align-items:center;justify-content:center;cursor:pointer",e.onclick=n=>{n.target===e&&this.closeTunnelQR()};const t=document.createElement("div");t.style.cssText="background:var(--bg-card);border:1px solid var(--border);border-radius:12px;padding:24px;text-align:center;max-width:340px;width:90vw;box-shadow:var(--shadow-lg);cursor:default",t.innerHTML=`
2
2
  <div style="font-size:14px;font-weight:600;color:var(--text-primary);margin-bottom:16px">Scan to connect</div>
3
3
  <div id="tunnelQrContainer" style="background:#fff;border-radius:8px;padding:16px;display:inline-block">
4
4
  <div style="color:#666;font-size:12px">Loading...</div>
@@ -11,7 +11,7 @@
11
11
  <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>
12
12
  Tunnel Active`):(s.classList.remove("active","connecting"),s.innerHTML=`
13
13
  <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>
14
- Cloudflare Tunnel`));const o=document.getElementById("welcomeQr"),i=document.getElementById("welcomeQrInner"),a=document.getElementById("welcomeQrUrl");!o||!i||(e?(o.classList.add("visible"),n&&(o.classList.add("expanded"),clearTimeout(this._welcomeQrShrinkTimer),this._welcomeQrShrinkTimer=setTimeout(()=>{o.classList.remove("expanded")},8e3)),t&&(a.textContent=t,a.title="Click QR to enlarge"),fetch("/api/tunnel/qr").then(l=>{if(!l.ok)throw new Error;return l.json()}).then(l=>{const r=l?.success===!0?l.data:l;r.svg&&(i.innerHTML=r.svg)}).catch(()=>{i.innerHTML='<div style="color:#999;font-size:11px;padding:20px">QR unavailable</div>'})):(clearTimeout(this._welcomeQrShrinkTimer),o.classList.remove("visible","expanded"),i.innerHTML="",a&&(a.textContent="")))},toggleWelcomeQrSize(){const e=document.getElementById("welcomeQr");e&&(clearTimeout(this._welcomeQrShrinkTimer),e.classList.toggle("expanded"))},_updateTunnelIndicator(e){if(MobileDetection.getDeviceType()==="mobile")return;const t=document.getElementById("tunnelIndicator");t&&(t.style.display=e?"flex":"none",t.classList.remove("connecting"))},toggleTunnelPanel(){if(document.getElementById("tunnelPanel")){this.closeTunnelPanel();return}this._openTunnelPanel()},async _openTunnelPanel(){const e=document.createElement("div");e.className="tunnel-panel",e.id="tunnelPanel",e.innerHTML=`
14
+ Cloudflare Tunnel`));const o=document.getElementById("welcomeQr"),i=document.getElementById("welcomeQrInner"),a=document.getElementById("welcomeQrUrl");!o||!i||(e?(o.classList.add("visible"),n&&(o.classList.add("expanded"),clearTimeout(this._welcomeQrShrinkTimer),this._welcomeQrShrinkTimer=setTimeout(()=>{o.classList.remove("expanded")},8e3)),t&&(a.textContent=t,a.title="Click QR to enlarge"),fetch("/api/tunnel/qr").then(l=>{if(!l.ok)throw new Error;return l.json()}).then(l=>{const c=l?.success===!0?l.data:l;c.svg&&(i.innerHTML=c.svg)}).catch(()=>{i.innerHTML='<div style="color:#999;font-size:11px;padding:20px">QR unavailable</div>'})):(clearTimeout(this._welcomeQrShrinkTimer),o.classList.remove("visible","expanded"),i.innerHTML="",a&&(a.textContent="")))},toggleWelcomeQrSize(){const e=document.getElementById("welcomeQr");e&&(clearTimeout(this._welcomeQrShrinkTimer),e.classList.toggle("expanded"))},_updateTunnelIndicator(e){if(MobileDetection.getDeviceType()==="mobile")return;const t=document.getElementById("tunnelIndicator");t&&(t.style.display=e?"flex":"none",t.classList.remove("connecting"))},toggleTunnelPanel(){if(document.getElementById("tunnelPanel")){this.closeTunnelPanel();return}this._openTunnelPanel()},async _openTunnelPanel(){const e=document.createElement("div");e.className="tunnel-panel",e.id="tunnelPanel",e.innerHTML=`
15
15
  <div class="tunnel-panel-header">
16
16
  <h3>
17
17
  <svg width="14" height="14" 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>
@@ -36,10 +36,10 @@
36
36
  <div class="tunnel-panel-stat">
37
37
  <span>Auth Sessions</span>
38
38
  <span class="tunnel-panel-stat-value">${e.authSessions.length}</span>
39
- </div>`),s+="</div>",e.authEnabled&&e.authSessions.length>0){s+='<div class="tunnel-panel-section"><div class="tunnel-panel-label">Authenticated Devices</div>';for(const i of e.authSessions){const a=i.ua||"Unknown",l=a.match(/Chrome|Firefox|Safari|Edge|Mobile/)?.[0]||"Browser",r=this._formatTimeAgo(i.createdAt);s+=`
39
+ </div>`),s+="</div>",e.authEnabled&&e.authSessions.length>0){s+='<div class="tunnel-panel-section"><div class="tunnel-panel-label">Authenticated Devices</div>';for(const i of e.authSessions){const a=i.ua||"Unknown",l=a.match(/Chrome|Firefox|Safari|Edge|Mobile/)?.[0]||"Browser",c=this._formatTimeAgo(i.createdAt);s+=`
40
40
  <div class="tunnel-panel-session">
41
41
  <span class="tunnel-panel-session-dot"></span>
42
- <span class="tunnel-panel-session-info" title="${escapeHtml(a)}">${escapeHtml(l)} &middot; ${escapeHtml(i.ip)} &middot; ${r}</span>
42
+ <span class="tunnel-panel-session-info" title="${escapeHtml(a)}">${escapeHtml(l)} &middot; ${escapeHtml(i.ip)} &middot; ${c}</span>
43
43
  <span class="tunnel-panel-session-method">${i.method}</span>
44
44
  </div>`}s+="</div>"}s+='<div class="tunnel-panel-actions">',e.running?s+=`
45
45
  <button class="tunnel-panel-btn btn-qr" onclick="app.showTunnelQR();app.closeTunnelPanel()">QR Code</button>
@@ -52,13 +52,13 @@ Enabling the Cloudflare tunnel will publish THIS machine to a public URL with NO
52
52
 
53
53
  Strongly recommended: set CODEMAN_PASSWORD instead.
54
54
 
55
- Enable the unauthenticated public tunnel anyway?`))return this._dismissTunnelConnecting?.(),this.showToast("Tunnel not enabled","info"),!0;try{const s=await fetch("/api/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({tunnelEnabled:!0,acknowledgeUnauthTunnel:!0})});if(s.ok)return this.showToast("Public tunnel enabling \u2014 no password set \u26A0\uFE0F","warning"),!1;let o="Failed to enable tunnel.";try{const i=await s.json();i&&i.error&&(o=i.error)}catch{}return this._dismissTunnelConnecting?.(),this.showToast(o,"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){try{const t=await fetch("/api/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({tunnelEnabled:e})});if(e&&await this._handleTunnelEnableRefusal(t)){this.closeTunnelPanel();return}if(e){this._updateTunnelIndicator(!1);const n=document.getElementById("tunnelIndicator");n&&(n.style.display="flex",n.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 r=e.getBoundingClientRect();e.style.transform="none",e.style.left=r.left+"px",e.style.top=r.top+"px",s=l.clientX,o=l.clientY,i=r.left,a=r.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 r={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(d=>{const c=new Date(d.ts).toLocaleString(),u=r[d.event]||"#888",p=d.name||(d.sessionId==="*"?"\u2014":this.getShortId(d.sessionId)),h=[];return d.exitCode!==void 0&&d.exitCode!==null&&h.push(`code=${d.exitCode}`),d.mode&&h.push(d.mode),`<tr style="border-bottom:1px solid #1a1a2e">
56
- <td style="padding:3px 8px;color:#888;white-space:nowrap">${c}</td>
55
+ Enable the unauthenticated public tunnel anyway?`))return this._dismissTunnelConnecting?.(),this.showToast("Tunnel not enabled","info"),!0;try{const s=await fetch("/api/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({tunnelEnabled:!0,acknowledgeUnauthTunnel:!0})});if(s.ok)return this.showToast("Public tunnel enabling \u2014 no password set \u26A0\uFE0F","warning"),!1;let o="Failed to enable tunnel.";try{const i=await s.json();i&&i.error&&(o=i.error)}catch{}return this._dismissTunnelConnecting?.(),this.showToast(o,"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){try{const t=await fetch("/api/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({tunnelEnabled:e})});if(e&&await this._handleTunnelEnableRefusal(t)){this.closeTunnelPanel();return}if(e){this._updateTunnelIndicator(!1);const n=document.getElementById("tunnelIndicator");n&&(n.style.display="flex",n.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 c=e.getBoundingClientRect();e.style.transform="none",e.style.left=c.left+"px",e.style.top=c.top+"px",s=l.clientX,o=l.clientY,i=c.left,a=c.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 c={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(d=>{const r=new Date(d.ts).toLocaleString(),u=c[d.event]||"#888",g=d.name||(d.sessionId==="*"?"\u2014":this.getShortId(d.sessionId)),p=[];return d.exitCode!==void 0&&d.exitCode!==null&&p.push(`code=${d.exitCode}`),d.mode&&p.push(d.mode),`<tr style="border-bottom:1px solid #1a1a2e">
56
+ <td style="padding:3px 8px;color:#888;white-space:nowrap">${r}</td>
57
57
  <td style="padding:3px 8px;color:${u};font-weight:600">${d.event}</td>
58
- <td style="padding:3px 8px;color:#e0e0e0" title="${d.sessionId}">${p}</td>
58
+ <td style="padding:3px 8px;color:#e0e0e0" title="${d.sessionId}">${g}</td>
59
59
  <td style="padding:3px 8px;color:#aaa">${d.reason||""}</td>
60
- <td style="padding:3px 8px;color:#666">${h.join(", ")}</td>
61
- </tr>`}).join("")}catch(s){console.error("Failed to load lifecycle log:",s)}},async saveAppSettings(){const e=this.loadAppSettingsFromStorage(),t=(e.gestureControlEnabled??!1)===!0,n=(e.webglRendererEnabled??!0)===!0,s={displayName:window.CodemanI18n?.normalizeDisplayName(document.getElementById("appSettingsDisplayName").value)||"Codeman",language:window.CodemanI18n?.normalizeLanguage(document.getElementById("appSettingsLanguage").value)||"en",defaultClaudeMdPath:document.getElementById("appSettingsClaudeMdPath").value.trim(),defaultWorkingDir:document.getElementById("appSettingsDefaultDir").value.trim(),ralphTrackerEnabled:document.getElementById("appSettingsRalphEnabled").checked,showFontControls:document.getElementById("appSettingsShowFontControls").checked,showSystemStats:document.getElementById("appSettingsShowSystemStats").checked,showLifecycleLog:document.getElementById("appSettingsShowLifecycleLog").checked,showResponseViewer:document.getElementById("appSettingsShowResponseViewer").checked,showFileViewerButton:document.getElementById("appSettingsShowFileViewerButton").checked,showAttachmentsButton:document.getElementById("appSettingsShowAttachmentsButton").checked,showMonitor:document.getElementById("appSettingsShowMonitor").checked,showProjectInsights:document.getElementById("appSettingsShowProjectInsights").checked,showFileBrowser:document.getElementById("appSettingsShowFileBrowser").checked,showSubagents:document.getElementById("appSettingsShowSubagents").checked,showUltracodeAgents:document.getElementById("appSettingsShowUltracodeAgents").checked,approvalsInboxEnabled:document.getElementById("appSettingsApprovalsInbox").checked,readMyMindEnabled:document.getElementById("appSettingsReadMyMind").checked,ultracodeFloatingWindows:document.getElementById("appSettingsUltracodeFloatingWindows").checked,showMultiMonitorButton:document.getElementById("appSettingsShowMultiMonitorButton").checked,showPlanUsageLimits:document.getElementById("appSettingsShowPlanUsageLimits").checked,showRedrawButton:document.getElementById("appSettingsShowRedrawButton").checked,mobileOverviewEnabled:document.getElementById("appSettingsMobileOverview").checked,showSessionButton:document.getElementById("appSettingsShowSessionButton").checked,showAwayDigestButton:document.getElementById("appSettingsShowAwayDigestButton").checked,showCronButton:document.getElementById("appSettingsShowCronButton").checked,gestureControlEnabled:document.getElementById("appSettingsGestureControl").checked,subagentTrackingEnabled:document.getElementById("appSettingsSubagentTracking").checked,subagentActiveTabOnly:document.getElementById("appSettingsSubagentActiveTabOnly").checked,imageWatcherEnabled:document.getElementById("appSettingsImageWatcherEnabled").checked,tunnelEnabled:document.getElementById("appSettingsTunnelEnabled").checked,localEchoEnabled:document.getElementById("appSettingsLocalEcho").checked,terminalWheelLocalScrollback:document.getElementById("appSettingsTerminalWheelLocal").checked,cjkInputEnabled:document.getElementById("appSettingsCjkInput").checked,webglRendererEnabled:document.getElementById("appSettingsWebglRenderer").checked,extendedKeyboardBar:document.getElementById("appSettingsExtendedKeyboardBar").checked,tabTwoRows:document.getElementById("appSettingsTabTwoRows").checked,showTabDetachButton:document.getElementById("appSettingsShowTabDetachButton").checked,skin:document.getElementById("appSettingsSkin").value,claudeMode:document.getElementById("appSettingsClaudeMode").value,allowedTools:document.getElementById("appSettingsAllowedTools").value.trim(),codexDangerouslyBypassApprovals:document.getElementById("appSettingsCodexDangerouslyBypassApprovals").checked,codexAnimationsEnabled:document.getElementById("appSettingsCodexAnimations").checked,agentTeamsEnabled:document.getElementById("appSettingsAgentTeams").checked,agentSkillEnabled:document.getElementById("appSettingsAgentSkill").checked,claudeModel:document.getElementById("appSettingsClaudeModel").value,opusContext1mEnabled:document.getElementById("appSettingsOpusContext1m").checked,remoteAutoReconnect:document.getElementById("appSettingsRemoteAutoReconnect").checked,thinkingEffort:document.getElementById("appSettingsThinkingEffort").value,nice:{enabled:document.getElementById("appSettingsNiceEnabled").checked,niceValue:parseInt(document.getElementById("appSettingsNiceValue").value)||10}};if(e.showTokenCount!==void 0&&(s.showTokenCount=e.showTokenCount),e.showCost!==void 0&&(s.showCost=e.showCost),e.shortcutOverrides!==void 0&&(s.shortcutOverrides=e.shortcutOverrides),this.saveAppSettingsToStorage(s),this._updateLocalEchoState(),!n&&s.webglRendererEnabled)try{localStorage.removeItem("codeman-webgl-disabled")}catch{}const o={apiKey:document.getElementById("voiceDeepgramKey").value.trim(),language:document.getElementById("voiceLanguage").value,keyterms:document.getElementById("voiceKeyterms").value.trim(),insertMode:document.getElementById("voiceInsertMode").value};VoiceInput._saveDeepgramConfig(o);const i={enabled:document.getElementById("appSettingsNotifEnabled").checked,browserNotifications:document.getElementById("appSettingsNotifBrowser").checked,audioAlerts:document.getElementById("appSettingsNotifAudio").checked,stuckThresholdMs:(parseInt(document.getElementById("appSettingsNotifStuckMins").value)||10)*6e4,muteCritical:!document.getElementById("appSettingsNotifCritical").checked,muteWarning:!document.getElementById("appSettingsNotifWarning").checked,muteInfo:!document.getElementById("appSettingsNotifInfo").checked,eventTypes:{permission_prompt:{enabled:document.getElementById("eventPermissionEnabled").checked,browser:document.getElementById("eventPermissionBrowser").checked,push:document.getElementById("eventPermissionPush").checked,audio:document.getElementById("eventPermissionAudio").checked},elicitation_dialog:{enabled:document.getElementById("eventQuestionEnabled").checked,browser:document.getElementById("eventQuestionBrowser").checked,push:document.getElementById("eventQuestionPush").checked,audio:document.getElementById("eventQuestionAudio").checked},idle_prompt:{enabled:document.getElementById("eventIdleEnabled").checked,browser:document.getElementById("eventIdleBrowser").checked,push:document.getElementById("eventIdlePush").checked,audio:document.getElementById("eventIdleAudio").checked},stop:{enabled:document.getElementById("eventStopEnabled").checked,browser:document.getElementById("eventStopBrowser").checked,push:document.getElementById("eventStopPush").checked,audio:document.getElementById("eventStopAudio").checked},session_error:{enabled:!0,browser:this.notificationManager?.preferences?.eventTypes?.session_error?.browser??!0,push:this.notificationManager?.preferences?.eventTypes?.session_error?.push??!1,audio:!1},respawn_cycle:{enabled:document.getElementById("eventRespawnEnabled").checked,browser:document.getElementById("eventRespawnBrowser").checked,push:document.getElementById("eventRespawnPush").checked,audio:document.getElementById("eventRespawnAudio").checked},token_milestone:{enabled:!0,browser:!1,push:!1,audio:!1},ralph_complete:{enabled:document.getElementById("eventRalphEnabled").checked,browser:document.getElementById("eventRalphBrowser").checked,push:document.getElementById("eventRalphPush").checked,audio:document.getElementById("eventRalphAudio").checked},subagent_spawn:{enabled:document.getElementById("eventSubagentEnabled").checked,browser:document.getElementById("eventSubagentBrowser").checked,push:document.getElementById("eventSubagentPush").checked,audio:document.getElementById("eventSubagentAudio").checked},subagent_complete:{enabled:document.getElementById("eventSubagentEnabled").checked,browser:document.getElementById("eventSubagentBrowser").checked,push:document.getElementById("eventSubagentPush").checked,audio:document.getElementById("eventSubagentAudio").checked}},_version:5};this.notificationManager&&(this.notificationManager.preferences=i,this.notificationManager.savePreferences()),this._syncPushPreferences(),this.applyHeaderVisibilitySettings(),this.applySkin(),this.applyLocalization(),this.applyTabWrapSettings(),this._updateTokensImmediate(),this.applyMonitorVisibility(),this.renderApprovals?.(),this.renderProjectInsightsPanel(),this.updateSubagentWindowVisibility(),this._updateCjkInputState(),this.activeSessionId||this.showWelcome(),KeyboardAccessoryBar.setMode(s.extendedKeyboardBar?"extended":"simple");const{localEchoEnabled:a,cjkInputEnabled:l,extendedKeyboardBar:r,skin:d,language:c,showPlanUsageLimits:u,showAttachmentsButton:p,showFileViewerButton:h,webglRendererEnabled:b,terminalWheelLocalScrollback:y,showSessionButton:S,showAwayDigestButton:f,showCronButton:v,showTabDetachButton:g,mobileOverviewEnabled:E,...I}=s;try{const w=await this._apiPut("/api/settings",{...I,...s.showPlanUsageLimits?{statusLineTelemetry:!0}:{},notificationPreferences:i,voiceSettings:o});if(s.tunnelEnabled&&await this._handleTunnelEnableRefusal(w)){s.tunnelEnabled=!1,this.saveAppSettingsToStorage(s);const B=document.getElementById("appSettingsTunnelEnabled");B&&(B.checked=!1),this.closeAppSettings();return}await this.saveModelConfigFromSettings(),this.showToast("Settings saved","success"),s.tunnelEnabled&&this.showToast("Tunnel starting \u2014 QR code will appear when ready...","info")}catch{this.showToast("Settings saved locally","warning")}this.closeAppSettings(),s.gestureControlEnabled!==t&&(this.showToast(s.gestureControlEnabled?"Enabling gesture control \u2014 reloading\u2026":"Disabling gesture control \u2014 reloading\u2026","info"),setTimeout(()=>location.reload(),400))},async loadModelConfigForSettings(){try{const t=await(await fetch("/api/execution/model-config")).json();if(t.success&&t.data){const n=t.data,s=document.getElementById("appSettingsDefaultModel");s&&(s.value=n.defaultModel||"");const o=document.getElementById("appSettingsShowModelRecommendations");o&&(o.checked=n.showRecommendations??!0);const i=n.agentTypeOverrides||{},a=document.getElementById("appSettingsModelExplore"),l=document.getElementById("appSettingsModelImplement"),r=document.getElementById("appSettingsModelTest"),d=document.getElementById("appSettingsModelReview");a&&(a.value=i.explore||""),l&&(l.value=i.implement||""),r&&(r.value=i.test||""),d&&(d.value=i.review||"")}}catch(e){console.warn("Failed to load model config:",e)}},async saveModelConfigFromSettings(){const e=document.getElementById("appSettingsDefaultModel"),t=document.getElementById("appSettingsShowModelRecommendations"),n=document.getElementById("appSettingsModelExplore"),s=document.getElementById("appSettingsModelImplement"),o=document.getElementById("appSettingsModelTest"),i=document.getElementById("appSettingsModelReview"),a={};n?.value&&(a.explore=n.value),s?.value&&(a.implement=s.value),o?.value&&(a.test=o.value),i?.value&&(a.review=i.value);const l={defaultModel:e?.value||"",showRecommendations:t?.checked??!0,agentTypeOverrides:a};try{await fetch("/api/execution/model-config",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)})}catch(r){console.warn("Failed to save model config:",r)}},isRalphTrackerEnabledByDefault(){return this.loadAppSettingsFromStorage().ralphTrackerEnabled??!1},getSettingsStorageKey(){return MobileDetection.isHandheldDevice?.()??MobileDetection.getDeviceType()==="mobile"?"codeman-app-settings-mobile":"codeman-app-settings"},getDefaultSettings(){return MobileDetection.isHandheldDevice?.()??MobileDetection.getDeviceType()==="mobile"?{showFontControls:!1,showSystemStats:!1,showTokenCount:!1,showCost:!1,showMonitor:!1,showProjectInsights:!1,showFileBrowser:!1,showSubagents:!1,showUltracodeAgents:!1,ultracodeFloatingWindows:!1,showMultiMonitorButton:!1,showPlanUsageLimits:!1,showAttachmentsButton:!1,showFileViewerButton:!1,showRedrawButton:!1,showSessionButton:!1,showAwayDigestButton:!1,showCronButton:!1,mobileOverviewEnabled:!0,remoteAutoReconnect:!0,gestureControlEnabled:!1,subagentTrackingEnabled:!0,subagentActiveTabOnly:!0,imageWatcherEnabled:!1,ralphTrackerEnabled:!1,tabTwoRows:!1,cjkInputEnabled:!1,terminalWheelLocalScrollback:!1,webglRendererEnabled:!1,skin:"daylight-blue"}:{}},loadAppSettingsFromStorage(){if(this._cachedAppSettings)return this._cachedAppSettings;try{const e=this.getSettingsStorageKey(),t=localStorage.getItem(e);if(t)return this._cachedAppSettings=JSON.parse(t),this._cachedAppSettings}catch(e){console.error("Failed to load app settings:",e)}return this._cachedAppSettings=this.getDefaultSettings(),this._cachedAppSettings},saveAppSettingsToStorage(e){this._cachedAppSettings=e;try{const t=this.getSettingsStorageKey();localStorage.setItem(t,JSON.stringify(e))}catch(t){console.error("Failed to save app settings:",t)}},applySkin(){const e=this.loadAppSettingsFromStorage(),t=this.getDefaultSettings(),n=e.skin??t.skin??"daylight-blue";document.documentElement.setAttribute("data-skin",n),window.__codemanSkin=n;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)},planUsageChipEnabled(e=null){return(e??this.loadAppSettingsFromStorage()).showPlanUsageLimits??this.getDefaultSettings().showPlanUsageLimits??!0},applyHeaderVisibilitySettings(){const e=this.loadAppSettingsFromStorage(),t=this.getDefaultSettings(),n=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"),r=document.getElementById("headerSystemStats"),d=document.getElementById("headerTokens");l&&(l.style.display=o?"":"none"),r&&(r.style.display=i?"":"none"),d&&(d.style.display=a?"":"none");const c=e.showLifecycleLog??t.showLifecycleLog??!1,u=document.querySelector(".btn-lifecycle-log");u&&(u.style.display=c?"":"none");const p=e.showResponseViewer??t.showResponseViewer??!1,h=document.querySelector(".btn-response-viewer-header");h&&h.classList.toggle("btn-response-viewer-header--hidden",!p);const b=e.showAttachmentsButton??t.showAttachmentsButton??!1,y=document.getElementById("attachmentsHistoryBtn");y&&y.classList.toggle("btn-attachments-history--hidden",!b);const S=e.showFileViewerButton??t.showFileViewerButton??!0,f=document.querySelector(".btn-file-viewer");f&&f.classList.toggle("btn-file-viewer--hidden",!S);const v=e.showMultiMonitorButton??t.showMultiMonitorButton??!1,g=document.querySelector(".btn-multimonitor");g&&g.classList.toggle("btn-multimonitor--hidden",!v);const E=e.showUltracodeAgents??t.showUltracodeAgents??!1,I=document.querySelector(".btn-ultracode-agents");I&&I.classList.toggle("btn-ultracode-agents--hidden",!E);const w=document.querySelector(".btn-readmymind");w&&w.classList.toggle("btn-readmymind--hidden",e.readMyMindEnabled!==!0);const B=this.planUsageChipEnabled(e),T=document.getElementById("planUsageChip");T&&T.classList.toggle("header-plan-usage--hidden",!B);const m=e.showRedrawButton??t.showRedrawButton??!1,k=document.querySelector(".btn-redraw-terminal");k&&k.classList.toggle("btn-redraw-terminal--hidden",!m);const M=e.showSessionButton??t.showSessionButton??!1,_=document.querySelector(".btn-session-manager");_&&_.classList.toggle("btn-session-manager--hidden",!M);const x=e.showAwayDigestButton??t.showAwayDigestButton??!1,C=document.querySelector(".btn-away-digest");C&&C.classList.toggle("btn-away-digest--hidden",!x);const R=e.showCronButton??t.showCronButton??!1,P=document.querySelector(".btn-cron");P&&P.classList.toggle("btn-cron--hidden",!R);const A=document.querySelector(".btn-notifications");if(A&&(A.style.display="none"),!(this.notificationManager?.preferences?.enabled??!0)){const L=document.getElementById("notifDrawer");L&&L.classList.remove("open")}},applyTabWrapSettings(){const e=this.loadAppSettingsFromStorage(),t=this.getDefaultSettings(),s=MobileDetection.getDeviceType()==="desktop"?e.tabTwoRows??t.tabTwoRows??!1:!1,o=this._tallTabsEnabled;this._tallTabsEnabled=s;const i=document.getElementById("sessionTabs");i&&(i.classList.toggle("tabs-two-rows",s),i.classList.toggle("tabs-show-folder",s)),o!==void 0&&o!==s&&this._fullRenderSessionTabs()},applyMonitorVisibility(){const e=this.loadAppSettingsFromStorage(),t=this.getDefaultSettings(),n=e.showMonitor??t.showMonitor??!1,s=e.showSubagents??t.showSubagents??!1,o=e.showFileBrowser??t.showFileBrowser??!1,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,r=document.getElementById("ultracodeAgentsPanel");r&&(l?r.classList.remove("hidden"):(r.classList.remove("open"),r.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 u=c.querySelector(".file-browser-header");if(u){const p=()=>{if(!c.style.left){const h=c.getBoundingClientRect();c.style.left=`${h.left}px`,c.style.top=`${h.top}px`,c.style.right="auto"}};u.addEventListener("mousedown",p),u.addEventListener("touchstart",p,{passive:!0}),this.fileBrowserDragListeners=this.makeWindowDraggable(c,u),this.fileBrowserDragListeners._onFirstDrag=p}}}else c.classList.remove("visible")},closeMonitor(){const e=document.getElementById("monitorPanel");e&&(e.classList.remove("open"),e.style.display="none");const t=this.loadAppSettingsFromStorage();t.showMonitor=!1,this.saveAppSettingsToStorage(t)},closeSubagentsPanel(){const e=document.getElementById("subagentsPanel");e&&(e.classList.remove("open"),e.classList.add("hidden")),this.subagentPanelVisible=!1;const t=this.loadAppSettingsFromStorage();t.showSubagents=!1,this.saveAppSettingsToStorage(t)},async clearAllSubagents(){const e=this.subagents.size;if(e===0){this.showToast("No subagents to clear","info");return}if(confirm(`Clear all ${e} tracked subagent(s)? This removes them from the UI but does not affect running processes.`))try{const n=await(await fetch("/api/subagents",{method:"DELETE"})).json();n.success?(this.subagents.clear(),this.subagentActivity.clear(),this.subagentToolResults.clear(),this.cleanupAllFloatingWindows(),this.renderSubagentPanel(),this.renderMonitorSubagents(),this.updateSubagentBadge(),this.showToast(`Cleared ${n.data.cleared} subagent(s)`,"success")):this.showToast("Failed to clear subagents: "+n.error,"error")}catch{this.showToast("Failed to clear subagents","error")}},toggleSubagentsPanel(){const e=document.getElementById("subagentsPanel"),t=document.getElementById("subagentsToggleBtn");if(e){if(e.classList.contains("hidden")){e.classList.remove("hidden");const n=this.loadAppSettingsFromStorage();n.showSubagents=!0,this.saveAppSettingsToStorage(n)}e.classList.toggle("open"),this.subagentPanelVisible=e.classList.contains("open"),t&&(t.innerHTML=this.subagentPanelVisible?"&#x25BC;":"&#x25B2;"),this.subagentPanelVisible&&this.renderSubagentPanel()}},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=new Set(["showFontControls","showSystemStats","showTokenCount","showCost","showLifecycleLog","showResponseViewer","showRedrawButton","showMonitor","showProjectInsights","showFileBrowser","showSubagents","subagentActiveTabOnly","tabTwoRows","localEchoEnabled","cjkInputEnabled","extendedKeyboardBar","skin","showPlanUsageLimits","showAttachmentsButton","showFileViewerButton","webglRendererEnabled","language","terminalWheelLocalScrollback","showSessionButton","showAwayDigestButton","showCronButton","showTabDetachButton","mobileOverviewEnabled"]);delete a.showPlanUsageLimits;const r=this.loadAppSettingsFromStorage(),d={...r};for(const[c,u]of Object.entries(a))l.has(c)&&c in r||(d[c]=u);if(this.saveAppSettingsToStorage(d),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{const c=localStorage.getItem("codeman-respawn-presets");if(c){const u=JSON.parse(c);u.length>0&&(this._serverRespawnPresets=u,this._apiPut("/api/settings",{respawnPresets:u}).catch(()=>{}))}}if(i){this.runMode=i;try{localStorage.setItem("codeman_runMode",i)}catch{}this._applyRunMode()}return d}}catch(t){console.error("Failed to load settings from server:",t)}return this.loadAppSettingsFromStorage()},async loadSubagentWindowStates(){let e=null;try{const t=await fetch("/api/subagent-window-states");if(t.ok){const n=await t.json();e=n?.success===!0?n.data:n,localStorage.setItem("codeman-subagent-window-states",JSON.stringify(e))}}catch(t){console.error("Failed to load subagent window states from server:",t)}if(!e)try{const t=localStorage.getItem("codeman-subagent-window-states");t&&(e=JSON.parse(t))}catch(t){console.error("Failed to load subagent window states from localStorage:",t)}return e||{minimized:{},open:[]}},async saveSubagentParentMap(){const e=Object.fromEntries(this.subagentParentMap);try{localStorage.setItem("codeman-subagent-parents",JSON.stringify(e))}catch(t){console.error("Failed to save subagent parents to localStorage:",t)}try{await fetch("/api/subagent-parents",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}catch(t){console.error("Failed to save subagent parents to server:",t)}},async loadSubagentParentMap(){let e=null;try{const t=await fetch("/api/subagent-parents");if(t.ok){const n=await t.json();e=n?.success===!0?n.data:n,localStorage.setItem("codeman-subagent-parents",JSON.stringify(e))}}catch(t){console.error("Failed to load subagent parents from server:",t)}if(!e)try{const t=localStorage.getItem("codeman-subagent-parents");t&&(e=JSON.parse(t))}catch(t){console.error("Failed to load subagent parents from localStorage:",t)}if(e&&typeof e=="object")for(const[t,n]of Object.entries(e))this.sessions.has(n)&&this.subagents.has(t)&&this.subagentParentMap.set(t,n)},getAgentParentSessionId(e){return this.subagentParentMap.get(e)||null},setAgentParentSessionId(e,t){if(!e||!t||this.subagentParentMap.has(e))return;this.subagentParentMap.set(e,t),this.saveSubagentParentMap();const n=this.subagents.get(e);if(n){n.parentSessionId=t;const s=this.sessions.get(t);s&&(n.parentSessionName=this.getSessionName(s)),this.subagents.set(e,n)}},showHelp(){const e=document.getElementById("helpModal");e.classList.add("active"),this.activeFocusTrap=new FocusTrap(e),this.activeFocusTrap.activate()},closeHelp(){document.getElementById("helpModal").classList.remove("active"),this.activeFocusTrap&&(this.activeFocusTrap.deactivate(),this.activeFocusTrap=null)},renderShortcutSettingsList(){const e=document.getElementById("appSettingsShortcutsList");if(!e)return;const t=this.getShortcutRegistry?this.getShortcutRegistry():typeof DEFAULT_SHORTCUTS<"u"?DEFAULT_SHORTCUTS:[],n=this.readShortcutOverridesFromSettings();e.innerHTML=t.map(s=>{const o=s.displayBindings?s.displayBindings.join(" / "):(s.bindings||[]).map(r=>[...r.modifiers||[],r.key||r.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>
60
+ <td style="padding:3px 8px;color:#666">${p.join(", ")}</td>
61
+ </tr>`}).join("")}catch(s){console.error("Failed to load lifecycle log:",s)}},async saveAppSettings(){const e=this.loadAppSettingsFromStorage(),t=(e.gestureControlEnabled??!1)===!0,n=(e.webglRendererEnabled??!0)===!0,s={displayName:window.CodemanI18n?.normalizeDisplayName(document.getElementById("appSettingsDisplayName").value)||"Codeman",language:window.CodemanI18n?.normalizeLanguage(document.getElementById("appSettingsLanguage").value)||"en",defaultClaudeMdPath:document.getElementById("appSettingsClaudeMdPath").value.trim(),defaultWorkingDir:document.getElementById("appSettingsDefaultDir").value.trim(),ralphTrackerEnabled:document.getElementById("appSettingsRalphEnabled").checked,showFontControls:document.getElementById("appSettingsShowFontControls").checked,showSystemStats:document.getElementById("appSettingsShowSystemStats").checked,showLifecycleLog:document.getElementById("appSettingsShowLifecycleLog").checked,showResponseViewer:document.getElementById("appSettingsShowResponseViewer").checked,showFileViewerButton:document.getElementById("appSettingsShowFileViewerButton").checked,showAttachmentsButton:document.getElementById("appSettingsShowAttachmentsButton").checked,showMonitor:document.getElementById("appSettingsShowMonitor").checked,showProjectInsights:document.getElementById("appSettingsShowProjectInsights").checked,showFileBrowser:document.getElementById("appSettingsShowFileBrowser").checked,showSubagents:document.getElementById("appSettingsShowSubagents").checked,showUltracodeAgents:document.getElementById("appSettingsShowUltracodeAgents").checked,approvalsInboxEnabled:document.getElementById("appSettingsApprovalsInbox").checked,readMyMindEnabled:document.getElementById("appSettingsReadMyMind").checked,ultracodeFloatingWindows:document.getElementById("appSettingsUltracodeFloatingWindows").checked,showMultiMonitorButton:document.getElementById("appSettingsShowMultiMonitorButton").checked,showPlanUsageLimits:document.getElementById("appSettingsShowPlanUsageLimits").checked,showRedrawButton:document.getElementById("appSettingsShowRedrawButton").checked,mobileOverviewEnabled:document.getElementById("appSettingsMobileOverview").checked,showSessionButton:document.getElementById("appSettingsShowSessionButton").checked,showAwayDigestButton:document.getElementById("appSettingsShowAwayDigestButton").checked,showCronButton:document.getElementById("appSettingsShowCronButton").checked,gestureControlEnabled:document.getElementById("appSettingsGestureControl").checked,subagentTrackingEnabled:document.getElementById("appSettingsSubagentTracking").checked,subagentActiveTabOnly:document.getElementById("appSettingsSubagentActiveTabOnly").checked,imageWatcherEnabled:document.getElementById("appSettingsImageWatcherEnabled").checked,tunnelEnabled:document.getElementById("appSettingsTunnelEnabled").checked,localEchoEnabled:document.getElementById("appSettingsLocalEcho").checked,terminalWheelLocalScrollback:document.getElementById("appSettingsTerminalWheelLocal").checked,cjkInputEnabled:document.getElementById("appSettingsCjkInput").checked,webglRendererEnabled:document.getElementById("appSettingsWebglRenderer").checked,extendedKeyboardBar:document.getElementById("appSettingsExtendedKeyboardBar").checked,tabTwoRows:document.getElementById("appSettingsTabTwoRows").checked,showTabDetachButton:document.getElementById("appSettingsShowTabDetachButton").checked,skin:document.getElementById("appSettingsSkin").value,claudeMode:document.getElementById("appSettingsClaudeMode").value,allowedTools:document.getElementById("appSettingsAllowedTools").value.trim(),codexDangerouslyBypassApprovals:document.getElementById("appSettingsCodexDangerouslyBypassApprovals").checked,codexAnimationsEnabled:document.getElementById("appSettingsCodexAnimations").checked,agentTeamsEnabled:document.getElementById("appSettingsAgentTeams").checked,agentSkillEnabled:document.getElementById("appSettingsAgentSkill").checked,claudeModel:document.getElementById("appSettingsClaudeModel").value,opusContext1mEnabled:document.getElementById("appSettingsOpusContext1m").checked,remoteAutoReconnect:document.getElementById("appSettingsRemoteAutoReconnect").checked,thinkingEffort:document.getElementById("appSettingsThinkingEffort").value,nice:{enabled:document.getElementById("appSettingsNiceEnabled").checked,niceValue:parseInt(document.getElementById("appSettingsNiceValue").value)||10}};if(e.showTokenCount!==void 0&&(s.showTokenCount=e.showTokenCount),e.showCost!==void 0&&(s.showCost=e.showCost),e.shortcutOverrides!==void 0&&(s.shortcutOverrides=e.shortcutOverrides),this.saveAppSettingsToStorage(s),this._updateLocalEchoState(),!n&&s.webglRendererEnabled)try{localStorage.removeItem("codeman-webgl-disabled")}catch{}const o={apiKey:document.getElementById("voiceDeepgramKey").value.trim(),language:document.getElementById("voiceLanguage").value,keyterms:document.getElementById("voiceKeyterms").value.trim(),insertMode:document.getElementById("voiceInsertMode").value};VoiceInput._saveDeepgramConfig(o);const i={enabled:document.getElementById("appSettingsNotifEnabled").checked,browserNotifications:document.getElementById("appSettingsNotifBrowser").checked,audioAlerts:document.getElementById("appSettingsNotifAudio").checked,stuckThresholdMs:(parseInt(document.getElementById("appSettingsNotifStuckMins").value)||10)*6e4,muteCritical:!document.getElementById("appSettingsNotifCritical").checked,muteWarning:!document.getElementById("appSettingsNotifWarning").checked,muteInfo:!document.getElementById("appSettingsNotifInfo").checked,eventTypes:{permission_prompt:{enabled:document.getElementById("eventPermissionEnabled").checked,browser:document.getElementById("eventPermissionBrowser").checked,push:document.getElementById("eventPermissionPush").checked,audio:document.getElementById("eventPermissionAudio").checked},elicitation_dialog:{enabled:document.getElementById("eventQuestionEnabled").checked,browser:document.getElementById("eventQuestionBrowser").checked,push:document.getElementById("eventQuestionPush").checked,audio:document.getElementById("eventQuestionAudio").checked},idle_prompt:{enabled:document.getElementById("eventIdleEnabled").checked,browser:document.getElementById("eventIdleBrowser").checked,push:document.getElementById("eventIdlePush").checked,audio:document.getElementById("eventIdleAudio").checked},stop:{enabled:document.getElementById("eventStopEnabled").checked,browser:document.getElementById("eventStopBrowser").checked,push:document.getElementById("eventStopPush").checked,audio:document.getElementById("eventStopAudio").checked},session_error:{enabled:!0,browser:this.notificationManager?.preferences?.eventTypes?.session_error?.browser??!0,push:this.notificationManager?.preferences?.eventTypes?.session_error?.push??!1,audio:!1},respawn_cycle:{enabled:document.getElementById("eventRespawnEnabled").checked,browser:document.getElementById("eventRespawnBrowser").checked,push:document.getElementById("eventRespawnPush").checked,audio:document.getElementById("eventRespawnAudio").checked},token_milestone:{enabled:!0,browser:!1,push:!1,audio:!1},ralph_complete:{enabled:document.getElementById("eventRalphEnabled").checked,browser:document.getElementById("eventRalphBrowser").checked,push:document.getElementById("eventRalphPush").checked,audio:document.getElementById("eventRalphAudio").checked},subagent_spawn:{enabled:document.getElementById("eventSubagentEnabled").checked,browser:document.getElementById("eventSubagentBrowser").checked,push:document.getElementById("eventSubagentPush").checked,audio:document.getElementById("eventSubagentAudio").checked},subagent_complete:{enabled:document.getElementById("eventSubagentEnabled").checked,browser:document.getElementById("eventSubagentBrowser").checked,push:document.getElementById("eventSubagentPush").checked,audio:document.getElementById("eventSubagentAudio").checked}},_version:5};this.notificationManager&&(this.notificationManager.preferences=i,this.notificationManager.savePreferences()),this._syncPushPreferences(),this.applyHeaderVisibilitySettings(),this.applySkin(),this.applyLocalization(),this.applyTabWrapSettings(),this._updateTokensImmediate(),this.applyMonitorVisibility(),this.renderApprovals?.(),this.renderProjectInsightsPanel(),this.updateSubagentWindowVisibility(),this._updateCjkInputState(),this.activeSessionId||this.showWelcome(),KeyboardAccessoryBar.setMode(s.extendedKeyboardBar?"extended":"simple");const{localEchoEnabled:a,cjkInputEnabled:l,extendedKeyboardBar:c,skin:d,language:r,showPlanUsageLimits:u,showAttachmentsButton:g,showFileViewerButton:p,webglRendererEnabled:w,terminalWheelLocalScrollback:y,showSessionButton:S,showAwayDigestButton:h,showCronButton:b,showTabDetachButton:E,mobileOverviewEnabled:B,...v}=s;try{const f=await this._apiPut("/api/settings",{...v,...s.showPlanUsageLimits?{statusLineTelemetry:!0}:{},notificationPreferences:i,voiceSettings:o});if(s.tunnelEnabled&&await this._handleTunnelEnableRefusal(f)){s.tunnelEnabled=!1,this.saveAppSettingsToStorage(s);const m=document.getElementById("appSettingsTunnelEnabled");m&&(m.checked=!1),this.closeAppSettings();return}await this.saveModelConfigFromSettings(),this.showToast("Settings saved","success"),s.tunnelEnabled&&this.showToast("Tunnel starting \u2014 QR code will appear when ready...","info")}catch{this.showToast("Settings saved locally","warning")}this.closeAppSettings(),s.gestureControlEnabled!==t&&(this.showToast(s.gestureControlEnabled?"Enabling gesture control \u2014 reloading\u2026":"Disabling gesture control \u2014 reloading\u2026","info"),setTimeout(()=>location.reload(),400))},async loadModelConfigForSettings(){try{const t=await(await fetch("/api/execution/model-config")).json();if(t.success&&t.data){const n=t.data,s=document.getElementById("appSettingsDefaultModel");s&&(s.value=n.defaultModel||"");const o=document.getElementById("appSettingsShowModelRecommendations");o&&(o.checked=n.showRecommendations??!0);const i=n.agentTypeOverrides||{},a=document.getElementById("appSettingsModelExplore"),l=document.getElementById("appSettingsModelImplement"),c=document.getElementById("appSettingsModelTest"),d=document.getElementById("appSettingsModelReview");a&&(a.value=i.explore||""),l&&(l.value=i.implement||""),c&&(c.value=i.test||""),d&&(d.value=i.review||"")}}catch(e){console.warn("Failed to load model config:",e)}},async saveModelConfigFromSettings(){const e=document.getElementById("appSettingsDefaultModel"),t=document.getElementById("appSettingsShowModelRecommendations"),n=document.getElementById("appSettingsModelExplore"),s=document.getElementById("appSettingsModelImplement"),o=document.getElementById("appSettingsModelTest"),i=document.getElementById("appSettingsModelReview"),a={};n?.value&&(a.explore=n.value),s?.value&&(a.implement=s.value),o?.value&&(a.test=o.value),i?.value&&(a.review=i.value);const l={defaultModel:e?.value||"",showRecommendations:t?.checked??!0,agentTypeOverrides:a};try{await fetch("/api/execution/model-config",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)})}catch(c){console.warn("Failed to save model config:",c)}},isRalphTrackerEnabledByDefault(){return this.loadAppSettingsFromStorage().ralphTrackerEnabled??!1},getSettingsStorageKey(){return MobileDetection.isHandheldDevice?.()??MobileDetection.getDeviceType()==="mobile"?"codeman-app-settings-mobile":"codeman-app-settings"},getDefaultSettings(){return MobileDetection.isHandheldDevice?.()??MobileDetection.getDeviceType()==="mobile"?{showFontControls:!1,showSystemStats:!1,showTokenCount:!1,showCost:!1,showMonitor:!1,showProjectInsights:!1,showFileBrowser:!1,showSubagents:!1,showUltracodeAgents:!1,ultracodeFloatingWindows:!1,showMultiMonitorButton:!1,showPlanUsageLimits:!1,showAttachmentsButton:!1,showFileViewerButton:!1,showRedrawButton:!1,showSessionButton:!1,showAwayDigestButton:!1,showCronButton:!1,mobileOverviewEnabled:!0,remoteAutoReconnect:!0,gestureControlEnabled:!1,subagentTrackingEnabled:!0,subagentActiveTabOnly:!0,imageWatcherEnabled:!1,ralphTrackerEnabled:!1,tabTwoRows:!1,cjkInputEnabled:!1,terminalWheelLocalScrollback:!1,webglRendererEnabled:!1,skin:"daylight-blue"}:{}},loadAppSettingsFromStorage(){if(this._cachedAppSettings)return this._cachedAppSettings;try{const e=this.getSettingsStorageKey(),t=localStorage.getItem(e);if(t)return this._cachedAppSettings=JSON.parse(t),this._cachedAppSettings}catch(e){console.error("Failed to load app settings:",e)}return this._cachedAppSettings=this.getDefaultSettings(),this._cachedAppSettings},saveAppSettingsToStorage(e){this._cachedAppSettings=e;try{const t=this.getSettingsStorageKey();localStorage.setItem(t,JSON.stringify(e))}catch(t){console.error("Failed to save app settings:",t)}},applySkin(){const e=this.loadAppSettingsFromStorage(),t=this.getDefaultSettings(),n=e.skin??t.skin??"daylight-blue";document.documentElement.setAttribute("data-skin",n),window.__codemanSkin=n;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)},planUsageChipEnabled(e=null){return(e??this.loadAppSettingsFromStorage()).showPlanUsageLimits??this.getDefaultSettings().showPlanUsageLimits??!0},applyHeaderVisibilitySettings(){const e=this.loadAppSettingsFromStorage(),t=this.getDefaultSettings(),n=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"),c=document.getElementById("headerSystemStats"),d=document.getElementById("headerTokens");l&&(l.style.display=o?"":"none"),c&&(c.style.display=i?"":"none"),d&&(d.style.display=a?"":"none");const r=e.showLifecycleLog??t.showLifecycleLog??!1,u=document.querySelector(".btn-lifecycle-log");u&&(u.style.display=r?"":"none");const g=e.showResponseViewer??t.showResponseViewer??!1,p=document.querySelector(".btn-response-viewer-header");p&&p.classList.toggle("btn-response-viewer-header--hidden",!g);const w=e.showAttachmentsButton??t.showAttachmentsButton??!1,y=document.getElementById("attachmentsHistoryBtn");y&&y.classList.toggle("btn-attachments-history--hidden",!w);const S=e.showFileViewerButton??t.showFileViewerButton??!0,h=document.querySelector(".btn-file-viewer");h&&h.classList.toggle("btn-file-viewer--hidden",!S);const b=e.showMultiMonitorButton??t.showMultiMonitorButton??!1,E=document.querySelector(".btn-multimonitor");E&&E.classList.toggle("btn-multimonitor--hidden",!b);const B=e.showUltracodeAgents??t.showUltracodeAgents??!1,v=document.querySelector(".btn-ultracode-agents");v&&v.classList.toggle("btn-ultracode-agents--hidden",!B);const f=document.querySelector(".btn-readmymind");f&&f.classList.toggle("btn-readmymind--hidden",e.readMyMindEnabled!==!0),typeof KeyboardAccessoryBar<"u"&&KeyboardAccessoryBar.syncReadMyMind?.();const m=this.planUsageChipEnabled(e),I=document.getElementById("planUsageChip");I&&I.classList.toggle("header-plan-usage--hidden",!m);const A=e.showRedrawButton??t.showRedrawButton??!1,T=document.querySelector(".btn-redraw-terminal");T&&T.classList.toggle("btn-redraw-terminal--hidden",!A);const M=e.showSessionButton??t.showSessionButton??!1,k=document.querySelector(".btn-session-manager");k&&k.classList.toggle("btn-session-manager--hidden",!M);const x=e.showAwayDigestButton??t.showAwayDigestButton??!1,_=document.querySelector(".btn-away-digest");_&&_.classList.toggle("btn-away-digest--hidden",!x);const R=e.showCronButton??t.showCronButton??!1,C=document.querySelector(".btn-cron");C&&C.classList.toggle("btn-cron--hidden",!R);const L=document.querySelector(".btn-notifications");if(L&&(L.style.display="none"),!(this.notificationManager?.preferences?.enabled??!0)){const P=document.getElementById("notifDrawer");P&&P.classList.remove("open")}},applyTabWrapSettings(){const e=this.loadAppSettingsFromStorage(),t=this.getDefaultSettings(),s=MobileDetection.getDeviceType()==="desktop"?e.tabTwoRows??t.tabTwoRows??!1:!1,o=this._tallTabsEnabled;this._tallTabsEnabled=s;const i=document.getElementById("sessionTabs");i&&(i.classList.toggle("tabs-two-rows",s),i.classList.toggle("tabs-show-folder",s)),o!==void 0&&o!==s&&this._fullRenderSessionTabs()},applyMonitorVisibility(){const e=this.loadAppSettingsFromStorage(),t=this.getDefaultSettings(),n=e.showMonitor??t.showMonitor??!1,s=e.showSubagents??t.showSubagents??!1,o=e.showFileBrowser??t.showFileBrowser??!1,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,c=document.getElementById("ultracodeAgentsPanel");c&&(l?c.classList.remove("hidden"):(c.classList.remove("open"),c.classList.add("hidden"))),e.ultracodeFloatingWindows??t.ultracodeFloatingWindows??!1?typeof this.syncAllUltracodeFloatingWindows=="function"&&this.syncAllUltracodeFloatingWindows():typeof this.removeAllUltracodeWindows=="function"&&this.removeAllUltracodeWindows();const r=document.getElementById("fileBrowserPanel");if(r)if(o&&this.activeSessionId){if(r.classList.add("visible"),this.loadFileBrowser(this.activeSessionId),!this.fileBrowserDragListeners){const u=r.querySelector(".file-browser-header");if(u){const g=()=>{if(!r.style.left){const p=r.getBoundingClientRect();r.style.left=`${p.left}px`,r.style.top=`${p.top}px`,r.style.right="auto"}};u.addEventListener("mousedown",g),u.addEventListener("touchstart",g,{passive:!0}),this.fileBrowserDragListeners=this.makeWindowDraggable(r,u),this.fileBrowserDragListeners._onFirstDrag=g}}}else r.classList.remove("visible")},closeMonitor(){const e=document.getElementById("monitorPanel");e&&(e.classList.remove("open"),e.style.display="none");const t=this.loadAppSettingsFromStorage();t.showMonitor=!1,this.saveAppSettingsToStorage(t)},closeSubagentsPanel(){const e=document.getElementById("subagentsPanel");e&&(e.classList.remove("open"),e.classList.add("hidden")),this.subagentPanelVisible=!1;const t=this.loadAppSettingsFromStorage();t.showSubagents=!1,this.saveAppSettingsToStorage(t)},async clearAllSubagents(){const e=this.subagents.size;if(e===0){this.showToast("No subagents to clear","info");return}if(confirm(`Clear all ${e} tracked subagent(s)? This removes them from the UI but does not affect running processes.`))try{const n=await(await fetch("/api/subagents",{method:"DELETE"})).json();n.success?(this.subagents.clear(),this.subagentActivity.clear(),this.subagentToolResults.clear(),this.cleanupAllFloatingWindows(),this.renderSubagentPanel(),this.renderMonitorSubagents(),this.updateSubagentBadge(),this.showToast(`Cleared ${n.data.cleared} subagent(s)`,"success")):this.showToast("Failed to clear subagents: "+n.error,"error")}catch{this.showToast("Failed to clear subagents","error")}},toggleSubagentsPanel(){const e=document.getElementById("subagentsPanel"),t=document.getElementById("subagentsToggleBtn");if(e){if(e.classList.contains("hidden")){e.classList.remove("hidden");const n=this.loadAppSettingsFromStorage();n.showSubagents=!0,this.saveAppSettingsToStorage(n)}e.classList.toggle("open"),this.subagentPanelVisible=e.classList.contains("open"),t&&(t.innerHTML=this.subagentPanelVisible?"&#x25BC;":"&#x25B2;"),this.subagentPanelVisible&&this.renderSubagentPanel()}},async loadAppSettingsFromServer(e=null){try{if((MobileDetection.isHandheldDevice?.()??MobileDetection.getDeviceType()==="mobile")&&!localStorage.getItem("codeman:planUsagePerDeviceMigrated")){const t=this.loadAppSettingsFromStorage();t&&t.showPlanUsageLimits&&(t.showPlanUsageLimits=!1,this.saveAppSettingsToStorage(t)),localStorage.setItem("codeman:planUsagePerDeviceMigrated","1")}}catch{}try{const t=e?await e:await fetch("/api/settings").then(n=>n.ok?n.json():null).then(n=>n?.success===!0?n.data:n);if(t){const{notificationPreferences:n,voiceSettings:s,respawnPresets:o,runMode:i,...a}=t,l=new Set(["showFontControls","showSystemStats","showTokenCount","showCost","showLifecycleLog","showResponseViewer","showRedrawButton","showMonitor","showProjectInsights","showFileBrowser","showSubagents","subagentActiveTabOnly","tabTwoRows","localEchoEnabled","cjkInputEnabled","extendedKeyboardBar","skin","showPlanUsageLimits","showAttachmentsButton","showFileViewerButton","webglRendererEnabled","language","terminalWheelLocalScrollback","showSessionButton","showAwayDigestButton","showCronButton","showTabDetachButton","mobileOverviewEnabled"]);delete a.showPlanUsageLimits;const c=this.loadAppSettingsFromStorage(),d={...c};for(const[r,u]of Object.entries(a))l.has(r)&&r in c||(d[r]=u);if(this.saveAppSettingsToStorage(d),n&&this.notificationManager&&(localStorage.getItem(this.notificationManager.getStorageKey())||(this.notificationManager.preferences=this.notificationManager.normalizePreferences(n),this.notificationManager.savePreferences())),s){const r=localStorage.getItem("codeman-voice-settings");(!r||!JSON.parse(r).apiKey)&&VoiceInput._saveDeepgramConfig(s)}if(o&&Array.isArray(o))this._serverRespawnPresets=o,localStorage.setItem("codeman-respawn-presets",JSON.stringify(o));else{const r=localStorage.getItem("codeman-respawn-presets");if(r){const u=JSON.parse(r);u.length>0&&(this._serverRespawnPresets=u,this._apiPut("/api/settings",{respawnPresets:u}).catch(()=>{}))}}if(i){this.runMode=i;try{localStorage.setItem("codeman_runMode",i)}catch{}this._applyRunMode()}return d}}catch(t){console.error("Failed to load settings from server:",t)}return this.loadAppSettingsFromStorage()},async loadSubagentWindowStates(){let e=null;try{const t=await fetch("/api/subagent-window-states");if(t.ok){const n=await t.json();e=n?.success===!0?n.data:n,localStorage.setItem("codeman-subagent-window-states",JSON.stringify(e))}}catch(t){console.error("Failed to load subagent window states from server:",t)}if(!e)try{const t=localStorage.getItem("codeman-subagent-window-states");t&&(e=JSON.parse(t))}catch(t){console.error("Failed to load subagent window states from localStorage:",t)}return e||{minimized:{},open:[]}},async saveSubagentParentMap(){const e=Object.fromEntries(this.subagentParentMap);try{localStorage.setItem("codeman-subagent-parents",JSON.stringify(e))}catch(t){console.error("Failed to save subagent parents to localStorage:",t)}try{await fetch("/api/subagent-parents",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}catch(t){console.error("Failed to save subagent parents to server:",t)}},async loadSubagentParentMap(){let e=null;try{const t=await fetch("/api/subagent-parents");if(t.ok){const n=await t.json();e=n?.success===!0?n.data:n,localStorage.setItem("codeman-subagent-parents",JSON.stringify(e))}}catch(t){console.error("Failed to load subagent parents from server:",t)}if(!e)try{const t=localStorage.getItem("codeman-subagent-parents");t&&(e=JSON.parse(t))}catch(t){console.error("Failed to load subagent parents from localStorage:",t)}if(e&&typeof e=="object")for(const[t,n]of Object.entries(e))this.sessions.has(n)&&this.subagents.has(t)&&this.subagentParentMap.set(t,n)},getAgentParentSessionId(e){return this.subagentParentMap.get(e)||null},setAgentParentSessionId(e,t){if(!e||!t||this.subagentParentMap.has(e))return;this.subagentParentMap.set(e,t),this.saveSubagentParentMap();const n=this.subagents.get(e);if(n){n.parentSessionId=t;const s=this.sessions.get(t);s&&(n.parentSessionName=this.getSessionName(s)),this.subagents.set(e,n)}},showHelp(){const e=document.getElementById("helpModal");e.classList.add("active"),this.activeFocusTrap=new FocusTrap(e),this.activeFocusTrap.activate()},closeHelp(){document.getElementById("helpModal").classList.remove("active"),this.activeFocusTrap&&(this.activeFocusTrap.deactivate(),this.activeFocusTrap=null)},renderShortcutSettingsList(){const e=document.getElementById("appSettingsShortcutsList");if(!e)return;const t=this.getShortcutRegistry?this.getShortcutRegistry():typeof DEFAULT_SHORTCUTS<"u"?DEFAULT_SHORTCUTS:[],n=this.readShortcutOverridesFromSettings();e.innerHTML=t.map(s=>{const o=s.displayBindings?s.displayBindings.join(" / "):(s.bindings||[]).map(c=>[...c.modifiers||[],c.key||c.code||""].join("+")).join(" / "),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>
62
62
  <button type="button" class="shortcut-reset-btn" data-shortcut-action="reset" title="Reset to default"${a?"":" disabled"}>Reset</button>
63
63
  <input class="shortcut-enabled-checkbox" type="checkbox" ${s.disabled?"":"checked"} data-shortcut-action="toggle" title="Enable/disable">`:"";return`<div class="shortcut-setting-row${i?"":" shortcut-setting-row--fixed"}" data-shortcut-id="${escapeHtml(s.id)}">
64
64
  <label class="shortcut-setting-label">${escapeHtml(s.label)}</label>