aicodeman 0.4.1 → 0.4.2

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 (79) hide show
  1. package/dist/web/public/{api-client.eb389d1b.js → api-client.3adebdc2.js} +1 -1
  2. package/dist/web/public/api-client.3adebdc2.js.br +0 -0
  3. package/dist/web/public/api-client.3adebdc2.js.gz +0 -0
  4. package/dist/web/public/app.9dab4ee2.js +26 -0
  5. package/dist/web/public/app.9dab4ee2.js.br +0 -0
  6. package/dist/web/public/app.9dab4ee2.js.gz +0 -0
  7. package/dist/web/public/{constants.7555acc0.js → constants.cd61abbc.js} +4 -2
  8. package/dist/web/public/constants.cd61abbc.js.br +0 -0
  9. package/dist/web/public/constants.cd61abbc.js.gz +0 -0
  10. package/dist/web/public/index.html +17 -11
  11. package/dist/web/public/index.html.br +0 -0
  12. package/dist/web/public/index.html.gz +0 -0
  13. package/dist/web/public/input-cjk.92544c51.js.gz +0 -0
  14. package/dist/web/public/{keyboard-accessory.30cd57bd.js → keyboard-accessory.9fb81db6.js} +1 -1
  15. package/dist/web/public/keyboard-accessory.9fb81db6.js.br +0 -0
  16. package/dist/web/public/keyboard-accessory.9fb81db6.js.gz +0 -0
  17. package/dist/web/public/{mobile-handlers.91ad48b8.js → mobile-handlers.d4830fd3.js} +1 -1
  18. package/dist/web/public/mobile-handlers.d4830fd3.js.br +0 -0
  19. package/dist/web/public/mobile-handlers.d4830fd3.js.gz +0 -0
  20. package/dist/web/public/mobile.42fde818.css.gz +0 -0
  21. package/dist/web/public/{notification-manager.2e817554.js → notification-manager.2d5ea8ec.js} +1 -1
  22. package/dist/web/public/notification-manager.2d5ea8ec.js.br +0 -0
  23. package/dist/web/public/notification-manager.2d5ea8ec.js.gz +0 -0
  24. package/dist/web/public/panels-ui.d7f6be08.js +240 -0
  25. package/dist/web/public/panels-ui.d7f6be08.js.br +0 -0
  26. package/dist/web/public/panels-ui.d7f6be08.js.gz +0 -0
  27. package/dist/web/public/ralph-panel.7b014f16.js +69 -0
  28. package/dist/web/public/ralph-panel.7b014f16.js.br +0 -0
  29. package/dist/web/public/ralph-panel.7b014f16.js.gz +0 -0
  30. package/dist/web/public/{ralph-wizard.44a8d04a.js → ralph-wizard.f31ab90e.js} +1 -1
  31. package/dist/web/public/ralph-wizard.f31ab90e.js.br +0 -0
  32. package/dist/web/public/ralph-wizard.f31ab90e.js.gz +0 -0
  33. package/dist/web/public/respawn-ui.372c6ea7.js +47 -0
  34. package/dist/web/public/respawn-ui.372c6ea7.js.br +0 -0
  35. package/dist/web/public/respawn-ui.372c6ea7.js.gz +0 -0
  36. package/dist/web/public/session-ui.0a07c3b7.js +16 -0
  37. package/dist/web/public/session-ui.0a07c3b7.js.br +0 -0
  38. package/dist/web/public/session-ui.0a07c3b7.js.gz +0 -0
  39. package/dist/web/public/settings-ui.94c57184.js +55 -0
  40. package/dist/web/public/settings-ui.94c57184.js.br +0 -0
  41. package/dist/web/public/settings-ui.94c57184.js.gz +0 -0
  42. package/dist/web/public/styles.b8ec2f5a.css.gz +0 -0
  43. package/dist/web/public/{subagent-windows.eb8470b0.js → subagent-windows.a366a4ad.js} +2 -2
  44. package/dist/web/public/subagent-windows.a366a4ad.js.br +0 -0
  45. package/dist/web/public/subagent-windows.a366a4ad.js.gz +0 -0
  46. package/dist/web/public/sw.js.gz +0 -0
  47. package/dist/web/public/terminal-ui.e4565c7b.js +3 -0
  48. package/dist/web/public/terminal-ui.e4565c7b.js.br +0 -0
  49. package/dist/web/public/terminal-ui.e4565c7b.js.gz +0 -0
  50. package/dist/web/public/upload.html.gz +0 -0
  51. package/dist/web/public/vendor/xterm-addon-fit.min.js.gz +0 -0
  52. package/dist/web/public/vendor/xterm-addon-unicode11.min.js.gz +0 -0
  53. package/dist/web/public/vendor/xterm-addon-webgl.min.js.gz +0 -0
  54. package/dist/web/public/vendor/xterm-zerolag-input.137ad9f0.js.gz +0 -0
  55. package/dist/web/public/vendor/xterm.css.gz +0 -0
  56. package/dist/web/public/vendor/xterm.min.js.gz +0 -0
  57. package/dist/web/public/{voice-input.4c22ccd8.js → voice-input.085e9e73.js} +1 -1
  58. package/dist/web/public/voice-input.085e9e73.js.br +0 -0
  59. package/dist/web/public/voice-input.085e9e73.js.gz +0 -0
  60. package/package.json +1 -1
  61. package/dist/web/public/api-client.eb389d1b.js.br +0 -0
  62. package/dist/web/public/api-client.eb389d1b.js.gz +0 -0
  63. package/dist/web/public/app.f3a26c70.js +0 -450
  64. package/dist/web/public/app.f3a26c70.js.br +0 -0
  65. package/dist/web/public/app.f3a26c70.js.gz +0 -0
  66. package/dist/web/public/constants.7555acc0.js.br +0 -0
  67. package/dist/web/public/constants.7555acc0.js.gz +0 -0
  68. package/dist/web/public/keyboard-accessory.30cd57bd.js.br +0 -0
  69. package/dist/web/public/keyboard-accessory.30cd57bd.js.gz +0 -0
  70. package/dist/web/public/mobile-handlers.91ad48b8.js.br +0 -0
  71. package/dist/web/public/mobile-handlers.91ad48b8.js.gz +0 -0
  72. package/dist/web/public/notification-manager.2e817554.js.br +0 -0
  73. package/dist/web/public/notification-manager.2e817554.js.gz +0 -0
  74. package/dist/web/public/ralph-wizard.44a8d04a.js.br +0 -0
  75. package/dist/web/public/ralph-wizard.44a8d04a.js.gz +0 -0
  76. package/dist/web/public/subagent-windows.eb8470b0.js.br +0 -0
  77. package/dist/web/public/subagent-windows.eb8470b0.js.gz +0 -0
  78. package/dist/web/public/voice-input.4c22ccd8.js.br +0 -0
  79. package/dist/web/public/voice-input.4c22ccd8.js.gz +0 -0
@@ -0,0 +1,47 @@
1
+ "use strict";Object.assign(CodemanApp.prototype,{_onRespawnStarted(e){this.respawnStatus[e.sessionId]=e.status,e.sessionId===this.activeSessionId&&this.showRespawnBanner()},_onRespawnStopped(e){delete this.respawnStatus[e.sessionId],e.sessionId===this.activeSessionId&&this.hideRespawnBanner()},_onRespawnStateChanged(e){this.respawnStatus[e.sessionId]&&(this.respawnStatus[e.sessionId].state=e.state),e.sessionId===this.activeSessionId&&this.updateRespawnBanner(e.state)},_onRespawnCycleStarted(e){this.respawnStatus[e.sessionId]&&(this.respawnStatus[e.sessionId].cycleCount=e.cycleNumber),e.sessionId===this.activeSessionId&&(document.getElementById("respawnCycleCount").textContent=e.cycleNumber)},_onRespawnBlocked(e){const t=this.sessions.get(e.sessionId),n={circuit_breaker_open:"Circuit Breaker Open",exit_signal:"Exit Signal Detected",status_blocked:"Claude Reported BLOCKED"}[e.reason]||"Respawn Blocked";if(this.notificationManager?.notify({urgency:"critical",category:"respawn-blocked",sessionId:e.sessionId,sessionName:t?.name||this.getShortId(e.sessionId),title:n,message:e.details}),e.sessionId===this.activeSessionId){const i=document.getElementById("respawnStateLabel");i&&(i.textContent=n,i.classList.add("respawn-blocked"))}},_onRespawnAutoAcceptSent(e){const t=this.sessions.get(e.sessionId);this.notificationManager?.notify({urgency:"info",category:"auto-accept",sessionId:e.sessionId,sessionName:t?.name||this.getShortId(e.sessionId),title:"Plan Accepted",message:`Accepted plan mode for ${t?.name||"session"}`})},_onRespawnDetectionUpdate(e){this.respawnStatus[e.sessionId]&&(this.respawnStatus[e.sessionId].detection=e.detection),e.sessionId===this.activeSessionId&&this.updateDetectionDisplay(e.detection)},_onRespawnTimerStarted(e){if(e.endAt&&(this.respawnTimers[e.sessionId]={endAt:e.endAt,startedAt:e.startedAt,durationMinutes:e.durationMinutes},e.sessionId===this.activeSessionId&&this.showRespawnTimer()),e.timer){const{sessionId:t,timer:s}=e;this.respawnCountdownTimers[t]||(this.respawnCountdownTimers[t]={}),this.respawnCountdownTimers[t][s.name]={endsAt:s.endsAt,totalMs:s.durationMs,reason:s.reason},t===this.activeSessionId&&(this.updateCountdownTimerDisplay(),this.startCountdownInterval())}},_onRespawnTimerCancelled(e){const{sessionId:t,timerName:s}=e;this.respawnCountdownTimers[t]&&delete this.respawnCountdownTimers[t][s],t===this.activeSessionId&&this.updateCountdownTimerDisplay()},_onRespawnTimerCompleted(e){const{sessionId:t,timerName:s}=e;this.respawnCountdownTimers[t]&&delete this.respawnCountdownTimers[t][s],t===this.activeSessionId&&this.updateCountdownTimerDisplay()},_onRespawnError(e){const t=this.sessions.get(e.sessionId);this.notificationManager?.notify({urgency:"critical",category:"session-error",sessionId:e.sessionId,sessionName:t?.name||e.sessionId,title:"Respawn Error",message:e.error||e.message||"Respawn encountered an error"})},_onRespawnActionLog(e){const{sessionId:t,action:s}=e;this.addActionLogEntry(t,s),t===this.activeSessionId&&(this.updateCountdownTimerDisplay(),this.updateActionLogDisplay())},showRespawnBanner(){this.$("respawnBanner").style.display="flex",this.activeSessionId&&this.respawnTimers[this.activeSessionId]&&this.showRespawnTimer();const e=this.sessions.get(this.activeSessionId);e&&e.tokens&&this.updateRespawnTokens(e.tokens)},hideRespawnBanner(){this.$("respawnBanner").style.display="none",this.hideRespawnTimer()},getStateLabel(e){return{stopped:"Stopped",watching:"Watching",confirming_idle:"Confirming idle",ai_checking:"AI checking",sending_update:"Sending prompt",waiting_update:"Running prompt",sending_clear:"Clearing context",waiting_clear:"Clearing...",sending_init:"Initializing",waiting_init:"Initializing...",monitoring_init:"Waiting for work",sending_kickstart:"Kickstarting",waiting_kickstart:"Kickstarting..."}[e]||e.replace(/_/g," ")},updateRespawnBanner(e){const t=this.$("respawnState");t.textContent=this.getStateLabel(e),t.classList.remove("respawn-blocked")},updateDetectionDisplay(e){if(!e)return;const t=this.$("detectionStatus"),s=this.$("detectionWaiting"),n=this.$("detectionConfidence"),i=document.getElementById("detectionAiCheck"),a=document.getElementById("detectionHook");if(a)if(e.stopHookReceived||e.idlePromptReceived){const r=e.idlePromptReceived?"idle":"stop";a.textContent=`\u{1F3AF} ${r} hook`,a.className="detection-hook hook-active",a.style.display=""}else a.style.display="none";e.statusText&&e.statusText!=="Watching..."?(t.textContent=e.statusText,t.style.display=""):t.style.display="none",s.style.display="none";const c=e.confidenceLevel||0;if(c>0?(n.textContent=`${c}%`,n.style.display="",n.className="detection-confidence",e.stopHookReceived||e.idlePromptReceived?n.classList.add("hook-confirmed"):c>=60?n.classList.add("high"):c>=30&&n.classList.add("medium")):n.style.display="none",i&&e.aiCheck){const r=e.aiCheck;let o="",d="detection-ai-check";if(r.status==="checking")o="\u{1F50D} AI checking...",d+=" ai-checking";else if(r.status==="cooldown"&&r.cooldownEndsAt){const m=Math.ceil((r.cooldownEndsAt-Date.now())/1e3);m>0&&(r.lastVerdict==="WORKING"?(o=`\u23F3 Working, retry ${m}s`,d+=" ai-working"):(o=`\u2713 Idle, wait ${m}s`,d+=" ai-idle"))}else if(r.status==="disabled")o="\u26A0 AI disabled",d+=" ai-disabled";else if(r.lastVerdict&&r.lastCheckTime){const m=Math.round((Date.now()-r.lastCheckTime)/1e3);m<120&&(o=r.lastVerdict==="IDLE"?`\u2713 Idle (${m}s)`:`\u23F3 Working (${m}s)`,d+=r.lastVerdict==="IDLE"?" ai-idle":" ai-working")}i.textContent=o,i.className=d,i.style.display=o?"":"none"}else i&&(i.style.display="none");const l=this.$("respawnStatusRow2");if(l){const r=a&&a.style.display!=="none"||i&&i.style.display!=="none"||t&&t.style.display!=="none"||this.respawnCountdownTimers[this.activeSessionId]&&Object.keys(this.respawnCountdownTimers[this.activeSessionId]).length>0;l.style.display=r?"":"none"}},showRespawnTimer(){const e=this.$("respawnTimer");e.style.display="",this.updateRespawnTimer(),this.respawnTimerInterval&&clearInterval(this.respawnTimerInterval),this.respawnTimerInterval=setInterval(()=>this.updateRespawnTimer(),1e3)},hideRespawnTimer(){this.$("respawnTimer").style.display="none",this.respawnTimerInterval&&(clearInterval(this.respawnTimerInterval),this.respawnTimerInterval=null)},updateRespawnTimer(){if(!this.activeSessionId||!this.respawnTimers[this.activeSessionId]){this.hideRespawnTimer();return}const e=this.respawnTimers[this.activeSessionId];if(!e.endAt||isNaN(e.endAt)){this.hideRespawnTimer();return}const t=Date.now(),s=Math.max(0,e.endAt-t);if(s<=0){this.$("respawnTimer").textContent="Time up",delete this.respawnTimers[this.activeSessionId],this.hideRespawnTimer();return}this.$("respawnTimer").textContent=this.formatTime(s)},updateRespawnTokens(e){const t=e&&typeof e=="object",s=t?e.total:e;if(s===this._lastRespawnTokenTotal)return;this._lastRespawnTokenTotal=s;const n=this.$("respawnTokens"),i=t?e.input||0:Math.round(s*.6),a=t?e.output||0:Math.round(s*.4);if(s>0){n.style.display="";const c=this.formatTokens(s);if(this.loadAppSettingsFromStorage().showCost??!1){const o=this.estimateCost(i,a);n.textContent=`${c} tokens \xB7 $${o.toFixed(2)}`}else n.textContent=`${c} tokens`}else n.style.display="none";this.updateCliInfoDisplay()},updateCliInfoDisplay(){const e=this.$("cliInfoBar");if(!e)return;const t=this.sessions.get(this.activeSessionId);if(!t){e.style.display="none";return}let s=[];if(t.tokens){const n=typeof t.tokens=="object"?t.tokens.total:t.tokens;n>0&&s.push(`${this.formatTokens(n)} tokens`)}if(t.cliModel){let n=t.cliModel;n.includes("opus")?n="Opus":n.includes("sonnet")?n="Sonnet":n.includes("haiku")&&(n="Haiku"),s.push(n)}if(t.cliVersion){let n=`v${t.cliVersion}`;t.cliLatestVersion&&t.cliLatestVersion!==t.cliVersion&&(n+=" \u2191"),s.push(n)}s.length>0?(e.textContent=s.join(" \xB7 "),e.style.display=""):e.style.display="none"},addActionLogEntry(e,t){if(!["command","hook"].includes(t.type)){if(t.type==="ai-check"){if(t.detail.includes("Spawning"))return}else if(t.type==="plan-check"){if(t.detail.includes("Spawning"))return}else if(t.type!=="transcript")return}this.respawnActionLogs[e]||(this.respawnActionLogs[e]=[]),this.respawnActionLogs[e].unshift(t),this.respawnActionLogs[e].length>30&&this.respawnActionLogs[e].pop()},startCountdownInterval(){this.timerCountdownInterval||(this.timerCountdownInterval=setInterval(()=>{this.activeSessionId&&this.respawnCountdownTimers[this.activeSessionId]&&this.updateCountdownTimerDisplay()},100))},stopCountdownInterval(){this.timerCountdownInterval&&(clearInterval(this.timerCountdownInterval),this.timerCountdownInterval=null)},updateCountdownTimerDisplay(){const e=this.$("respawnCountdownTimers"),t=this.$("respawnStatusRow2");if(!e)return;const s=this.respawnCountdownTimers[this.activeSessionId];if(!(s&&Object.keys(s).length>0)){if(e.innerHTML="",t){const c=document.getElementById("detectionHook"),l=document.getElementById("detectionAiCheck"),r=this.$("detectionStatus"),o=c&&c.style.display!=="none"||l&&l.style.display!=="none"||r&&r.style.display!=="none";t.style.display=o?"":"none"}return}t&&(t.style.display="");const i=Date.now();let a="";for(const[c,l]of Object.entries(s)){const r=Math.max(0,l.endsAt-i),o=(r/1e3).toFixed(1),d=Math.max(0,Math.min(100,r/l.totalMs*100)),m=c.replace(/-/g," ").replace(/^\w/,u=>u.toUpperCase());a+=`<div class="respawn-countdown-timer" title="${escapeHtml(l.reason||"")}">
2
+ <span class="timer-name">${escapeHtml(m)}</span>
3
+ <span class="timer-value">${o}s</span>
4
+ <div class="respawn-timer-bar">
5
+ <div class="respawn-timer-progress" style="width: ${d}%"></div>
6
+ </div>
7
+ </div>`}e.innerHTML=a},updateActionLogDisplay(){const e=this.$("respawnActionLog");if(!e)return;const t=this.respawnActionLogs[this.activeSessionId];if(!t||t.length===0){e.innerHTML="";return}let s="";for(const n of t.slice(0,5)){const i=new Date(n.timestamp).toLocaleTimeString("en-US",{hour12:!1,hour:"2-digit",minute:"2-digit",second:"2-digit"}),c=n.type==="command"?" action-command":"";s+=`<div class="respawn-action-entry${c}">
8
+ <span class="action-time">${i}</span>
9
+ <span class="action-type">[${n.type}]</span>
10
+ <span class="action-detail">${escapeHtml(n.detail)}</span>
11
+ </div>`}e.innerHTML=s},clearCountdownTimers(e){delete this.respawnCountdownTimers[e],delete this.respawnActionLogs[e],e===this.activeSessionId&&(this.updateCountdownTimerDisplay(),this.updateActionLogDisplay())},async stopRespawn(){if(this.activeSessionId)try{await this._apiPost(`/api/sessions/${this.activeSessionId}/respawn/stop`,{}),delete this.respawnTimers[this.activeSessionId],this.clearCountdownTimers(this.activeSessionId)}catch{this.showToast("Failed to stop respawn","error")}},loadRespawnPresets(){const e=this._serverRespawnPresets;if(e)return[...BUILTIN_RESPAWN_PRESETS,...e];const t=localStorage.getItem("codeman-respawn-presets"),s=t?JSON.parse(t):[];return[...BUILTIN_RESPAWN_PRESETS,...s]},saveRespawnPresets(e){const t=e.filter(s=>!s.builtIn);this._serverRespawnPresets=t,localStorage.setItem("codeman-respawn-presets",JSON.stringify(t)),this._apiPut("/api/settings",{respawnPresets:t}).catch(()=>{})},renderPresetDropdown(){const e=this.loadRespawnPresets(),t=document.getElementById("builtinPresetsGroup"),s=document.getElementById("customPresetsGroup");!t||!s||(t.innerHTML="",s.innerHTML="",e.forEach(n=>{const i=document.createElement("option");i.value=n.id,i.textContent=n.name,n.builtIn?t.appendChild(i):s.appendChild(i)}))},updatePresetDescription(){const e=document.getElementById("respawnPresetSelect"),t=document.getElementById("presetDescriptionHint");if(!e||!t)return;const s=e.value;if(!s){t.textContent="";return}const i=this.loadRespawnPresets().find(a=>a.id===s);t.textContent=i?.description||""},loadRespawnPreset(){const e=document.getElementById("respawnPresetSelect"),t=e?.value;if(!t){this.showToast("Please select a preset first","warning");return}const n=this.loadRespawnPresets().find(i=>i.id===t);n&&(document.getElementById("modalRespawnPrompt").value=n.config.updatePrompt||"",document.getElementById("modalRespawnSendClear").checked=n.config.sendClear??!1,document.getElementById("modalRespawnSendInit").checked=n.config.sendInit??!1,document.getElementById("modalRespawnKickstart").value=n.config.kickstartPrompt||"",document.getElementById("modalRespawnAutoAccept").checked=n.config.autoAcceptPrompts??!0,n.durationMinutes&&this.selectDurationPreset(String(n.durationMinutes)),e.value="",document.getElementById("presetDescriptionHint").textContent="",this.showToast(`Loaded preset: ${n.name}`,"info"))},saveCurrentAsPreset(){document.getElementById("savePresetModal").classList.add("active"),document.getElementById("presetNameInput").value="",document.getElementById("presetDescriptionInput").value="",document.getElementById("presetNameInput").focus()},closeSavePresetModal(){document.getElementById("savePresetModal").classList.remove("active")},confirmSavePreset(){const e=document.getElementById("presetNameInput").value.trim();if(!e){this.showToast("Please enter a preset name","error");return}const t=document.getElementById("modalRespawnPrompt").value,s=document.getElementById("modalRespawnSendClear").checked,n=document.getElementById("modalRespawnSendInit").checked,i=document.getElementById("modalRespawnKickstart").value.trim()||void 0,a=this.getSelectedDuration(),c={id:"custom-"+Date.now(),name:e,description:document.getElementById("presetDescriptionInput").value.trim()||void 0,config:{idleTimeoutMs:5e3,updatePrompt:t,interStepDelayMs:3e3,sendClear:s,sendInit:n,kickstartPrompt:i},durationMinutes:a||void 0,builtIn:!1,createdAt:Date.now()},l=this.loadRespawnPresets();l.push(c),this.saveRespawnPresets(l),this.renderPresetDropdown(),this.closeSavePresetModal(),this.showToast(`Saved preset: ${e}`,"success")},deletePreset(e){const t=this.loadRespawnPresets(),s=t.find(i=>i.id===e);if(!s||s.builtIn){this.showToast("Cannot delete built-in presets","warning");return}const n=t.filter(i=>i.id!==e);this.saveRespawnPresets(n),this.renderPresetDropdown(),this.showToast(`Deleted preset: ${s.name}`,"success")},getModalRespawnConfig(){const e=document.getElementById("modalRespawnPrompt").value,t=document.getElementById("modalRespawnSendClear").checked,s=document.getElementById("modalRespawnSendInit").checked,n=document.getElementById("modalRespawnKickstart").value.trim()||void 0,i=document.getElementById("modalRespawnAutoAccept").checked,a=this.getSelectedDuration(),c=document.getElementById("modalAutoCompactEnabled").checked,l=parseInt(document.getElementById("modalAutoCompactThreshold").value)||11e4,r=document.getElementById("modalAutoCompactPrompt").value.trim()||void 0,o=document.getElementById("modalAutoClearEnabled").checked,d=parseInt(document.getElementById("modalAutoClearThreshold").value)||14e4;return{respawnConfig:{enabled:!0,updatePrompt:e,sendClear:t,sendInit:s,kickstartPrompt:n,autoAcceptPrompts:i},durationMinutes:a,autoCompactEnabled:c,autoCompactThreshold:l,autoCompactPrompt:r,autoClearEnabled:o,autoClearThreshold:d}},async enableRespawnFromModal(){if(!this.editingSessionId){this.showToast("No session selected","warning");return}const{respawnConfig:e,durationMinutes:t,autoCompactEnabled:s,autoCompactThreshold:n,autoCompactPrompt:i,autoClearEnabled:a,autoClearThreshold:c}=this.getModalRespawnConfig();try{const r=await(await fetch(`/api/sessions/${this.editingSessionId}/respawn/enable`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({config:e,durationMinutes:t})})).json();if(r.error)throw new Error(r.error);s&&await fetch(`/api/sessions/${this.editingSessionId}/auto-compact`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({enabled:!0,threshold:n,prompt:i})}),a&&await fetch(`/api/sessions/${this.editingSessionId}/auto-clear`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({enabled:!0,threshold:c})});const o=document.getElementById("sessionRespawnStatus");o.classList.add("active"),o.querySelector(".respawn-status-text").textContent="WATCHING",document.getElementById("modalEnableRespawnBtn").style.display="none",document.getElementById("modalStopRespawnBtn").style.display="",this.showToast("Respawn enabled","success")}catch(l){this.showToast("Failed to enable respawn: "+l.message,"error")}},async stopRespawnFromModal(){if(this.editingSessionId)try{await fetch(`/api/sessions/${this.editingSessionId}/respawn/stop`,{method:"POST"}),delete this.respawnTimers[this.editingSessionId];const e=document.getElementById("sessionRespawnStatus");e.classList.remove("active"),e.querySelector(".respawn-status-text").textContent="Not active",document.getElementById("modalEnableRespawnBtn").style.display="",document.getElementById("modalStopRespawnBtn").style.display="none",this.showToast("Respawn stopped","success")}catch{this.showToast("Failed to stop respawn","error")}},closeSessionOptions(){this.editingSessionId=null,this.stopRunSummaryAutoRefresh(),document.getElementById("sessionOptionsModal").classList.remove("active"),this.activeFocusTrap&&(this.activeFocusTrap.deactivate(),this.activeFocusTrap=null)},setupColorPicker(){const e=document.getElementById("sessionColorPicker");e&&e.addEventListener("click",t=>{const s=t.target.closest(".color-swatch");if(!s||!this.editingSessionId)return;const n=s.dataset.color;this.setSessionColor(this.editingSessionId,n)})},async setSessionColor(e,t){try{if((await fetch(`/api/sessions/${e}/color`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({color:t})})).ok){const n=this.sessions.get(e);n&&(n.color=t,this.renderSessionTabs());const i=document.getElementById("sessionColorPicker");i&&i.querySelectorAll(".color-swatch").forEach(a=>{a.classList.toggle("selected",a.dataset.color===t)})}else this.showToast("Failed to set session color","error")}catch{this.showToast("Failed to set session color","error")}},async openRunSummary(e){this.openSessionOptions(e),this.switchOptionsTab("summary"),this.runSummarySessionId=e,this.runSummaryFilter="all",document.querySelectorAll(".run-summary-filters .filter-btn").forEach(t=>{t.classList.toggle("active",t.dataset.filter==="all")}),await this.loadRunSummary(e)},closeRunSummary(){this.runSummarySessionId=null,this.stopRunSummaryAutoRefresh(),this.closeSessionOptions()},async refreshRunSummary(){const e=this.runSummarySessionId||this.editingSessionId;e&&await this.loadRunSummary(e)},toggleRunSummaryAutoRefresh(){document.getElementById("runSummaryAutoRefresh").checked?this.startRunSummaryAutoRefresh():this.stopRunSummaryAutoRefresh()},startRunSummaryAutoRefresh(){this.runSummaryAutoRefreshTimer||(this.runSummaryAutoRefreshTimer=setInterval(()=>{this.runSummarySessionId&&this.loadRunSummary(this.runSummarySessionId)},5e3))},stopRunSummaryAutoRefresh(){this.runSummaryAutoRefreshTimer&&(clearInterval(this.runSummaryAutoRefreshTimer),this.runSummaryAutoRefreshTimer=null);const e=document.getElementById("runSummaryAutoRefresh");e&&(e.checked=!1)},exportRunSummary(e){if(!this.runSummaryData){this.showToast("No summary data to export","error");return}const{stats:t,events:s,sessionName:n,startedAt:i,lastUpdatedAt:a}=this.runSummaryData,c=new Date().toISOString().slice(0,19).replace(/:/g,"-"),l=`run-summary-${n||"session"}-${c}`;if(e==="json"){const r=JSON.stringify(this.runSummaryData,null,2);this.downloadFile(`${l}.json`,r,"application/json")}else if(e==="md"){const r=a-i;let o=`# Run Summary: ${n||"Session"}
12
+
13
+ `;if(o+=`**Duration**: ${this.formatDuration(r)}
14
+ `,o+=`**Started**: ${new Date(i).toLocaleString()}
15
+ `,o+=`**Last Update**: ${new Date(a).toLocaleString()}
16
+
17
+ `,o+=`## Statistics
18
+
19
+ `,o+=`| Metric | Value |
20
+ `,o+=`|--------|-------|
21
+ `,o+=`| Respawn Cycles | ${t.totalRespawnCycles} |
22
+ `,o+=`| Peak Tokens | ${this.formatTokens(t.peakTokens)} |
23
+ `,o+=`| Active Time | ${this.formatDuration(t.totalTimeActiveMs)} |
24
+ `,o+=`| Idle Time | ${this.formatDuration(t.totalTimeIdleMs)} |
25
+ `,o+=`| Errors | ${t.errorCount} |
26
+ `,o+=`| Warnings | ${t.warningCount} |
27
+ `,o+=`| AI Checks | ${t.aiCheckCount} |
28
+ `,o+=`| State Transitions | ${t.stateTransitions} |
29
+
30
+ `,o+=`## Event Timeline
31
+
32
+ `,s.length===0)o+=`No events recorded.
33
+ `;else{o+=`| Time | Type | Severity | Title | Details |
34
+ `,o+=`|------|------|----------|-------|----------|
35
+ `;for(const d of s){const m=new Date(d.timestamp).toLocaleTimeString("en-US",{hour12:!1}),u=d.details?d.details.replace(/\|/g,"\\|"):"-";o+=`| ${m} | ${d.type} | ${d.severity} | ${d.title} | ${u} |
36
+ `}}this.downloadFile(`${l}.md`,o,"text/markdown")}this.showToast(`Exported as ${e.toUpperCase()}`,"success")},downloadFile(e,t,s){const n=new Blob([t],{type:s}),i=URL.createObjectURL(n),a=document.createElement("a");a.href=i,a.download=e,document.body.appendChild(a),a.click(),document.body.removeChild(a),URL.revokeObjectURL(i)},async loadRunSummary(e){const t=document.getElementById("runSummaryTimeline");t.innerHTML='<p class="empty-message">Loading summary...</p>';try{const n=await(await fetch(`/api/sessions/${e}/run-summary`)).json();if(!n.success){t.innerHTML=`<p class="empty-message">Failed to load summary: ${escapeHtml(n.error)}</p>`;return}this.runSummaryData=n.summary,this.renderRunSummary()}catch(s){console.error("Failed to load run summary:",s),t.innerHTML='<p class="empty-message">Failed to load summary</p>'}},renderRunSummary(){if(!this.runSummaryData)return;const{stats:e,events:t,sessionName:s,startedAt:n,lastUpdatedAt:i}=this.runSummaryData,a=i-n;document.getElementById("runSummarySessionInfo").textContent=`${s||"Session"} - ${this.formatDuration(a)} total`;const c=this.filterRunSummaryEvents(t);this.renderRunSummaryTimeline(c)},filterRunSummaryEvents(e){return this.runSummaryFilter==="all"?e:e.filter(t=>{switch(this.runSummaryFilter){case"errors":return t.severity==="error";case"warnings":return t.severity==="warning"||t.severity==="error";case"respawn":return t.type.startsWith("respawn_")||t.type==="state_stuck";case"idle":return t.type==="idle_detected"||t.type==="working_detected";default:return!0}})},filterRunSummary(e){this.runSummaryFilter=e,document.querySelectorAll(".run-summary-filters .filter-btn").forEach(t=>{t.classList.toggle("active",t.dataset.filter===e)}),this.renderRunSummary()},renderRunSummaryTimeline(e){const t=document.getElementById("runSummaryTimeline");if(!e||e.length===0){t.innerHTML='<p class="empty-message">No events recorded yet</p>';return}const n=[...e].reverse().map(i=>{const a=new Date(i.timestamp).toLocaleTimeString("en-US",{hour12:!1}),c=`event-${i.severity}`,l=this.getEventIcon(i.type,i.severity);return`
37
+ <div class="timeline-event ${c}">
38
+ <div class="event-icon">${l}</div>
39
+ <div class="event-content">
40
+ <div class="event-header">
41
+ <span class="event-title">${escapeHtml(i.title)}</span>
42
+ <span class="event-time">${a}</span>
43
+ </div>
44
+ ${i.details?`<div class="event-details">${escapeHtml(i.details)}</div>`:""}
45
+ </div>
46
+ </div>
47
+ `}).join("");t.innerHTML=n},getEventIcon(e,t){if(t==="error")return"&#x274C;";if(t==="warning")return"&#x26A0;";if(t==="success")return"&#x2714;";switch(e){case"session_started":return"&#x1F680;";case"session_stopped":return"&#x1F6D1;";case"respawn_cycle_started":return"&#x1F504;";case"respawn_cycle_completed":return"&#x2705;";case"respawn_state_change":return"&#x27A1;";case"token_milestone":return"&#x1F4B0;";case"idle_detected":return"&#x1F4A4;";case"working_detected":return"&#x1F4BB;";case"ai_check_result":return"&#x1F916;";case"hook_event":return"&#x1F514;";default:return"&#x2022;"}},formatDuration(e){if(!e||e<0)return"0s";const t=Math.floor(e/1e3),s=Math.floor(t/60),n=Math.floor(s/60);return n>0?`${n}h ${s%60}m`:s>0?`${s}m ${t%60}s`:`${t}s`},saveSessionOptions(){this.closeSessionOptions()}});
@@ -0,0 +1,16 @@
1
+ "use strict";Object.assign(CodemanApp.prototype,{async loadQuickStartCases(e=null,t=null){try{let s=null;try{const c=t?await t:await fetch("/api/settings").then(i=>i.ok?i.json():null);c&&(s=c.lastUsedCase||null)}catch{}const n=await(await fetch("/api/cases")).json();this.cases=n,console.log("[loadQuickStartCases] Loaded cases:",n.map(c=>c.name),"lastUsedCase:",s);const o=document.getElementById("quickStartCase");let l="";const r=n.some(c=>c.name==="testcase"),u=MobileDetection.getDeviceType()==="mobile"?8:20;if(n.forEach(c=>{const i=c.name.length>u?c.name.substring(0,u)+"\u2026":c.name;l+=`<option value="${escapeHtml(c.name)}">${escapeHtml(i)}</option>`}),r||(l='<option value="testcase">testcase</option>'+l),o.innerHTML=l,console.log("[loadQuickStartCases] Set options:",o.innerHTML.substring(0,200)),e)o.value=e,this.updateDirDisplayForCase(e),this.updateMobileCaseLabel(e);else if(s&&n.some(c=>c.name===s))o.value=s,this.updateDirDisplayForCase(s),this.updateMobileCaseLabel(s);else if(n.length>0){const c=n.find(i=>i.name==="testcase")||n[0];o.value=c.name,this.updateDirDisplayForCase(c.name),this.updateMobileCaseLabel(c.name)}else o.value="testcase",document.getElementById("dirDisplay").textContent="~/codeman-cases/testcase",this.updateMobileCaseLabel("testcase");o.dataset.listenerAdded||(o.addEventListener("change",()=>{this.updateDirDisplayForCase(o.value),this.saveLastUsedCase(o.value),this.updateMobileCaseLabel(o.value)}),o.dataset.listenerAdded="true")}catch(s){console.error("Failed to load cases:",s)}},async updateDirDisplayForCase(e){try{const s=await(await fetch(`/api/cases/${e}`)).json();s.path&&(document.getElementById("dirDisplay").textContent=s.path,document.getElementById("dirInput").value=s.path)}catch{document.getElementById("dirDisplay").textContent=e}},async saveLastUsedCase(e){try{const t=await fetch("/api/settings"),s=t.ok?await t.json():{};s.lastUsedCase=e,await fetch("/api/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)})}catch(t){console.error("Failed to save last used case:",t)}},async quickStart(){return this.run()},async run(){return(this._runMode||"claude")==="opencode"?this.runOpenCode():this.runClaude()},get runMode(){return this._runMode||"claude"},setRunMode(e){this._runMode=e;try{localStorage.setItem("codeman_runMode",e)}catch{}this._applyRunMode(),this._apiPut("/api/settings",{runMode:e}).catch(()=>{}),document.getElementById("runModeMenu")?.classList.remove("active")},toggleRunModeMenu(e){e?.stopPropagation();const t=document.getElementById("runModeMenu");if(t&&(t.classList.toggle("active"),t.querySelectorAll(".run-mode-option").forEach(s=>{s.classList.toggle("selected",s.dataset.mode===this.runMode)}),t.classList.contains("active"))){this._loadRunModeHistory();const s=a=>{t.contains(a.target)||(t.classList.remove("active"),document.removeEventListener("click",s))};setTimeout(()=>document.addEventListener("click",s),0)}},async _loadRunModeHistory(){const e=document.getElementById("runModeHistory");if(e){e.innerHTML='<div class="run-mode-hist-empty">Loading...</div>';try{const t=await this._fetchHistorySessions(10);if(t.length===0){e.innerHTML='<div class="run-mode-hist-empty">No history</div>';return}e.replaceChildren();for(const s of t){const a=new Date(s.lastModified),n=a.toLocaleDateString("en",{month:"short",day:"numeric"})+" "+a.toLocaleTimeString("en",{hour:"2-digit",minute:"2-digit",hour12:!1}),o=s.workingDir.replace(/^\/home\/[^/]+\//,"~/"),l=document.createElement("button");l.className="run-mode-option",l.title=s.workingDir,l.dataset.sessionId=s.sessionId,l.dataset.workingDir=s.workingDir;const r=document.createElement("span");r.className="hist-dir",r.textContent=o;const d=document.createElement("span");d.className="hist-meta",d.textContent=n,l.append(r,d),l.addEventListener("click",u=>{u.stopPropagation(),this.resumeHistorySession(s.sessionId,s.workingDir)}),e.appendChild(l)}}catch{e.innerHTML='<div class="run-mode-hist-empty">Failed to load</div>'}}},_applyRunMode(){const e=this.runMode,t=document.getElementById("runBtn"),s=t?.nextElementSibling,a=document.getElementById("runBtnLabel");t&&(t.className=`btn-toolbar btn-run mode-${e}`),s&&(s.className=`btn-toolbar btn-run-gear mode-${e}`),a&&(a.textContent=e==="opencode"?"Run OC":"Run")},_initRunMode(){try{this._runMode=localStorage.getItem("codeman_runMode")||"claude"}catch{this._runMode="claude"}this._applyRunMode()},incrementTabCount(){const e=document.getElementById("tabCount"),t=parseInt(e.value)||1;e.value=Math.min(20,t+1)},decrementTabCount(){const e=document.getElementById("tabCount"),t=parseInt(e.value)||1;e.value=Math.max(1,t-1)},incrementShellCount(){const e=document.getElementById("shellCount"),t=parseInt(e.value)||1;e.value=Math.min(20,t+1)},decrementShellCount(){const e=document.getElementById("shellCount"),t=parseInt(e.value)||1;e.value=Math.max(1,t-1)},async runClaude(){const e=document.getElementById("quickStartCase").value||"testcase",t=Math.min(20,Math.max(1,parseInt(document.getElementById("tabCount").value)||1));this.terminal.clear(),this.terminal.writeln(`\x1B[1;32m Starting ${t} Claude session(s) in ${e}...\x1B[0m`),this.terminal.writeln("");try{let a=await(await fetch(`/api/cases/${e}`)).json();if(!a.path){const g=await(await fetch("/api/cases",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:e,description:""})})).json();if(!g.success)throw new Error(g.error||"Failed to create case");a=g.case}const n=a.path;if(!n)throw new Error("Case path not found");let o=null,l=1;for(const[,m]of this.sessions){const g=m.name&&m.name.match(/^w(\d+)-(.+)$/);if(g&&g[2]===e){const f=parseInt(g[1]);f>=l&&(l=f+1)}}const r=this.isRalphTrackerEnabledByDefault(),d=[];for(let m=0;m<t;m++)d.push(`w${l+m}-${e}`);const u=this.getCaseSettings(e),c=this.loadAppSettingsFromStorage(),i={};(u.agentTeams||c.agentTeamsEnabled)&&(i.CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS="1");const p=Object.keys(i).length>0;this.terminal.writeln(`\x1B[90m Creating ${t} session(s)...\x1B[0m`);const h=d.map(m=>fetch("/api/sessions",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({workingDir:n,name:m,...p?{envOverrides:i}:{}})}).then(g=>g.json())),C=await Promise.all(h),y=[];for(const m of C){if(!m.success)throw new Error(m.error);y.push(m.session.id)}o=y[0],await Promise.all(y.map(m=>fetch(`/api/sessions/${m}/ralph-config`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({enabled:r,disableAutoEnable:!r})}))),this.terminal.writeln(`\x1B[90m Starting ${t} session(s) in parallel...\x1B[0m`),await Promise.all(y.map(m=>fetch(`/api/sessions/${m}/interactive`,{method:"POST"}))),this.terminal.writeln(`\x1B[90m All ${t} sessions ready\x1B[0m`),o&&(await this.selectSession(o),this.loadQuickStartCases()),this.terminal.focus()}catch(s){this.terminal.writeln(`\x1B[1;31m Error: ${s.message}\x1B[0m`)}},stopClaude(){if(!this.activeSessionId)return;const e=document.querySelector(".btn-toolbar.btn-stop");e&&(this._stopConfirmTimer?(clearTimeout(this._stopConfirmTimer),this._stopConfirmTimer=null,e.innerHTML=e.dataset.origHtml,delete e.dataset.origHtml,e.classList.remove("confirming"),fetch(`/api/sessions/${this.activeSessionId}/input`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({input:""})})):(e.dataset.origHtml=e.innerHTML,e.textContent="Tap again",e.classList.add("confirming"),this._stopConfirmTimer=setTimeout(()=>{this._stopConfirmTimer=null,e.dataset.origHtml&&(e.innerHTML=e.dataset.origHtml,delete e.dataset.origHtml),e.classList.remove("confirming")},2e3)))},async runShell(){const e=document.getElementById("quickStartCase").value||"testcase",t=Math.min(20,Math.max(1,parseInt(document.getElementById("shellCount").value)||1));this.terminal.clear(),this.terminal.writeln(`\x1B[1;33m Starting ${t} Shell session(s) in ${e}...\x1B[0m`),this.terminal.writeln("");try{const n=(await(await fetch(`/api/cases/${e}`)).json()).path;if(!n)throw new Error("Case path not found");let o=1;for(const[,i]of this.sessions){const p=i.name&&i.name.match(/^s(\d+)-(.+)$/);if(p&&p[2]===e){const h=parseInt(p[1]);h>=o&&(o=h+1)}}const l=[];for(let i=0;i<t;i++)l.push(`s${o+i}-${e}`);const r=l.map(i=>fetch("/api/sessions",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({workingDir:n,mode:"shell",name:i})}).then(p=>p.json())),d=await Promise.all(r),u=[];for(const i of d){if(!i.success)throw new Error(i.error);u.push(i.session.id)}await Promise.all(u.map(i=>fetch(`/api/sessions/${i}/shell`,{method:"POST"})));const c=this.getTerminalDimensions();c&&await Promise.all(u.map(i=>fetch(`/api/sessions/${i}/resize`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)}))),u.length>0&&(this.activeSessionId=u[0],await this.selectSession(u[0])),this.terminal.focus()}catch(s){this.terminal.writeln(`\x1B[1;31m Error: ${s.message}\x1B[0m`)}},async runOpenCode(){const e=document.getElementById("quickStartCase").value||"testcase";this.terminal.clear(),this.terminal.writeln(`\x1B[1;32m Starting OpenCode session in ${e}...\x1B[0m`),this.terminal.writeln("");try{if(!(await(await fetch("/api/opencode/status")).json()).available){this.terminal.writeln("\x1B[1;31m OpenCode CLI not found.\x1B[0m"),this.terminal.writeln("\x1B[90m Install with: curl -fsSL https://opencode.ai/install | bash\x1B[0m");return}const n=await(await fetch("/api/quick-start",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({caseName:e,mode:"opencode",openCodeConfig:{autoAllowTools:!0}})})).json();if(!n.success)throw new Error(n.error||"Failed to start OpenCode");n.sessionId&&await this.selectSession(n.sessionId),this.terminal.focus()}catch(t){this.terminal.writeln(`\x1B[1;31m Error: ${t.message}\x1B[0m`)}},openSessionOptions(e){const t=this.sessions.get(e);if(!t)return;this.editingSessionId=e,this.switchOptionsTab(t.mode==="opencode"?"summary":"respawn");const s=document.getElementById("sessionRespawnStatus"),a=document.getElementById("modalEnableRespawnBtn"),n=document.getElementById("modalStopRespawnBtn");this.respawnStatus[e]?(s.classList.add("active"),s.querySelector(".respawn-status-text").textContent=this.respawnStatus[e].state||"Active",a.style.display="none",n.style.display=""):(s.classList.remove("active"),s.querySelector(".respawn-status-text").textContent="Not active",a.style.display="",n.style.display="none");const o=document.getElementById("sessionRespawnSection");t.mode==="claude"&&t.pid?o.style.display="":o.style.display="none";const l=t.mode==="opencode";document.querySelectorAll("[data-claude-only]").forEach(h=>{h.style.display=l?"none":""}),this.selectDurationPreset(""),this.loadSavedRespawnConfig(e),document.getElementById("modalAutoCompactEnabled").checked=t.autoCompactEnabled??!1,document.getElementById("modalAutoCompactThreshold").value=t.autoCompactThreshold??11e4,document.getElementById("modalAutoCompactPrompt").value=t.autoCompactPrompt??"",document.getElementById("modalAutoClearEnabled").checked=t.autoClearEnabled??!1,document.getElementById("modalAutoClearThreshold").value=t.autoClearThreshold??14e4,document.getElementById("modalImageWatcherEnabled").checked=t.imageWatcherEnabled??!0,document.getElementById("modalFlickerFilterEnabled").checked=t.flickerFilterEnabled??!1,document.getElementById("modalSessionName").value=t.name||"";const d=t.color||"default";document.getElementById("sessionColorPicker")?.querySelectorAll(".color-swatch").forEach(h=>{h.classList.toggle("selected",h.dataset.color===d)}),this.renderPresetDropdown(),document.getElementById("respawnPresetSelect").value="",document.getElementById("presetDescriptionHint").textContent="";const c=document.querySelector('#sessionOptionsModal .modal-tab-btn[data-tab="ralph"]'),i=document.querySelector('#sessionOptionsModal .modal-tab-btn[data-tab="respawn"]');if(l?(c&&(c.style.display="none"),i&&(i.style.display="none"),this.switchOptionsTab("context")):(c&&(c.style.display=""),i&&(i.style.display="")),!l){const h=this.ralphStates.get(e);this.populateRalphForm({enabled:h?.loop?.enabled??t.ralphLoop?.enabled??!1,completionPhrase:h?.loop?.completionPhrase||t.ralphLoop?.completionPhrase||"",maxIterations:h?.loop?.maxIterations||t.ralphLoop?.maxIterations||0})}const p=document.getElementById("sessionOptionsModal");p.classList.add("active"),this.activeFocusTrap=new FocusTrap(p),this.activeFocusTrap.activate()},async saveSessionName(){if(!this.editingSessionId)return;const e=document.getElementById("modalSessionName").value.trim();try{await this._apiPut(`/api/sessions/${this.editingSessionId}/name`,{name:e})}catch(t){this.showToast("Failed to save session name: "+t.message,"error")}},async autoSaveAutoCompact(){if(this.editingSessionId)try{await this._apiPost(`/api/sessions/${this.editingSessionId}/auto-compact`,{enabled:document.getElementById("modalAutoCompactEnabled").checked,threshold:parseInt(document.getElementById("modalAutoCompactThreshold").value)||11e4,prompt:document.getElementById("modalAutoCompactPrompt").value.trim()||void 0})}catch{}},async autoSaveAutoClear(){if(this.editingSessionId)try{await this._apiPost(`/api/sessions/${this.editingSessionId}/auto-clear`,{enabled:document.getElementById("modalAutoClearEnabled").checked,threshold:parseInt(document.getElementById("modalAutoClearThreshold").value)||14e4})}catch{}},async toggleSessionImageWatcher(){if(!this.editingSessionId)return;const e=document.getElementById("modalImageWatcherEnabled").checked;try{await this._apiPost(`/api/sessions/${this.editingSessionId}/image-watcher`,{enabled:e});const t=this.sessions.get(this.editingSessionId);t&&(t.imageWatcherEnabled=e),this.showToast(`Image watcher ${e?"enabled":"disabled"}`,"success")}catch{this.showToast("Failed to toggle image watcher","error")}},async toggleFlickerFilter(){if(!this.editingSessionId)return;const e=document.getElementById("modalFlickerFilterEnabled").checked;try{await this._apiPost(`/api/sessions/${this.editingSessionId}/flicker-filter`,{enabled:e});const t=this.sessions.get(this.editingSessionId);t&&(t.flickerFilterEnabled=e),this.showToast(`Flicker filter ${e?"enabled":"disabled"}`,"success")}catch{this.showToast("Failed to toggle flicker filter","error")}},async autoSaveRespawnConfig(){if(!this.editingSessionId)return;const e={updatePrompt:document.getElementById("modalRespawnPrompt").value,sendClear:document.getElementById("modalRespawnSendClear").checked,sendInit:document.getElementById("modalRespawnSendInit").checked,kickstartPrompt:document.getElementById("modalRespawnKickstart").value.trim()||void 0,autoAcceptPrompts:document.getElementById("modalRespawnAutoAccept").checked};try{await this._apiPut(`/api/sessions/${this.editingSessionId}/respawn/config`,e)}catch{}},async loadSavedRespawnConfig(e){try{const s=await(await fetch(`/api/sessions/${e}/respawn/config`)).json();if(s.success&&s.config){const a=s.config;document.getElementById("modalRespawnPrompt").value=a.updatePrompt||"update all the docs and CLAUDE.md",document.getElementById("modalRespawnSendClear").checked=a.sendClear??!0,document.getElementById("modalRespawnSendInit").checked=a.sendInit??!0,document.getElementById("modalRespawnKickstart").value=a.kickstartPrompt||"",document.getElementById("modalRespawnAutoAccept").checked=a.autoAcceptPrompts??!0,a.durationMinutes&&(document.querySelector(`.duration-preset-btn[data-minutes="${a.durationMinutes}"]`)?this.selectDurationPreset(String(a.durationMinutes)):(this.selectDurationPreset("custom"),document.getElementById("modalRespawnDuration").value=a.durationMinutes))}}catch{}},selectDurationPreset(e){document.querySelectorAll(".duration-preset-btn").forEach(n=>n.classList.remove("active"));const t=document.querySelector(`.duration-preset-btn[data-minutes="${e}"]`);t&&t.classList.add("active");const s=document.querySelector(".duration-custom-input"),a=document.getElementById("modalRespawnDuration");e==="custom"?(s.classList.add("visible"),a.focus()):(s.classList.remove("visible"),a.value="")},getSelectedDuration(){const e=document.querySelector(".duration-custom-input"),t=document.getElementById("modalRespawnDuration");if(e.classList.contains("visible"))return t.value?parseInt(t.value):null;{const a=document.querySelector(".duration-preset-btn.active")?.dataset.minutes;return a?parseInt(a):null}},switchOptionsTab(e){document.querySelectorAll("#sessionOptionsModal .modal-tab-btn").forEach(t=>{t.classList.toggle("active",t.dataset.tab===e)}),document.getElementById("respawn-tab").classList.toggle("hidden",e!=="respawn"),document.getElementById("context-tab").classList.toggle("hidden",e!=="context"),document.getElementById("ralph-tab").classList.toggle("hidden",e!=="ralph"),document.getElementById("summary-tab").classList.toggle("hidden",e!=="summary"),e==="summary"&&this.editingSessionId&&this.loadRunSummary(this.editingSessionId)},getRalphConfig(){return{enabled:document.getElementById("modalRalphEnabled").checked,completionPhrase:document.getElementById("modalRalphPhrase").value.trim(),maxIterations:parseInt(document.getElementById("modalRalphMaxIterations").value)||0,maxTodos:parseInt(document.getElementById("modalRalphMaxTodos").value)||50,todoExpirationMinutes:parseInt(document.getElementById("modalRalphTodoExpiration").value)||60}},populateRalphForm(e){document.getElementById("modalRalphEnabled").checked=e?.enabled??!1,document.getElementById("modalRalphPhrase").value=e?.completionPhrase||"",document.getElementById("modalRalphMaxIterations").value=e?.maxIterations||0,document.getElementById("modalRalphMaxTodos").value=e?.maxTodos||50,document.getElementById("modalRalphTodoExpiration").value=e?.todoExpirationMinutes||60},async saveRalphConfig(){if(!this.editingSessionId){this.showToast("No session selected","warning");return}const e=this.getRalphConfig();e.enabled&&this.ralphClosedSessions.delete(this.editingSessionId);try{const s=await(await fetch(`/api/sessions/${this.editingSessionId}/ralph-config`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})).json();if(s.error)throw new Error(s.error);this.showToast("Ralph config saved","success")}catch(t){this.showToast("Failed to save Ralph config: "+t.message,"error")}},startInlineRename(e){const t=this.sessions.get(e);if(!t)return;const s=document.querySelector(`.tab-name[data-session-id="${e}"]`);if(!s)return;const a=this.getSessionName(t),n=document.createElement("input");n.type="text",n.value=t.name||"",n.placeholder=a,n.className="tab-rename-input",n.style.cssText="width: 80px; font-size: 0.75rem; padding: 2px 4px; background: var(--bg-input); border: 1px solid var(--accent); border-radius: 3px; color: var(--text); outline: none;";const o=s.textContent;s.textContent="",s.appendChild(n),n.focus(),n.select();const l=async()=>{const r=n.value.trim();if(s.textContent=r||o,r&&r!==t.name)try{await fetch(`/api/sessions/${e}/name`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:r})})}catch{s.textContent=o,this.showToast("Failed to rename","error")}};n.addEventListener("blur",l),n.addEventListener("keydown",r=>{r.key==="Enter"?(r.preventDefault(),n.blur()):r.key==="Escape"&&(n.value="",n.blur())})},toggleCaseSettings(){const e=document.getElementById("caseSettingsPopover");if(e.classList.contains("hidden")){const t=document.getElementById("quickStartCase").value||"testcase",s=this.getCaseSettings(t);document.getElementById("caseAgentTeams").checked=s.agentTeams,e.classList.remove("hidden");const a=n=>{!e.contains(n.target)&&!n.target.classList.contains("btn-case-settings")&&(e.classList.add("hidden"),document.removeEventListener("click",a))};setTimeout(()=>document.addEventListener("click",a),0)}else e.classList.add("hidden")},getCaseSettings(e){try{const t=localStorage.getItem("caseSettings_"+e);if(t)return JSON.parse(t)}catch{}return{agentTeams:!1}},saveCaseSettings(e,t){localStorage.setItem("caseSettings_"+e,JSON.stringify(t))},onCaseSettingChanged(){const e=document.getElementById("quickStartCase").value||"testcase",t=this.getCaseSettings(e);t.agentTeams=document.getElementById("caseAgentTeams").checked,this.saveCaseSettings(e,t);const s=document.getElementById("caseAgentTeamsMobile");s&&(s.checked=t.agentTeams)},toggleCaseSettingsMobile(){const e=document.getElementById("caseSettingsPopoverMobile");if(e.classList.contains("hidden")){const t=document.getElementById("quickStartCase").value||"testcase",s=this.getCaseSettings(t);document.getElementById("caseAgentTeamsMobile").checked=s.agentTeams,e.classList.remove("hidden");const a=n=>{!e.contains(n.target)&&!n.target.classList.contains("btn-case-settings-mobile")&&(e.classList.add("hidden"),document.removeEventListener("click",a))};setTimeout(()=>document.addEventListener("click",a),0)}else e.classList.add("hidden")},onCaseSettingChangedMobile(){const e=document.getElementById("quickStartCase").value||"testcase",t=this.getCaseSettings(e);t.agentTeams=document.getElementById("caseAgentTeamsMobile").checked,this.saveCaseSettings(e,t);const s=document.getElementById("caseAgentTeams");s&&(s.checked=t.agentTeams)},showCreateCaseModal(){document.getElementById("newCaseName").value="",document.getElementById("newCaseDescription").value="",document.getElementById("linkCaseName").value="",document.getElementById("linkCasePath").value="",this.caseModalTab="case-create",this.switchCaseModalTab("case-create");const e=document.getElementById("createCaseModal");e.querySelectorAll(".modal-tabs .modal-tab-btn").forEach(t=>{t.onclick=()=>this.switchCaseModalTab(t.dataset.tab)}),e.querySelectorAll('input[type="text"]').forEach(t=>{t._mobileScrollWired||(t._mobileScrollWired=!0,t.addEventListener("focus",()=>{window.innerWidth<=430&&setTimeout(()=>t.scrollIntoView({behavior:"smooth",block:"center"}),300)}))}),e.classList.add("active"),document.getElementById("newCaseName").focus()},switchCaseModalTab(e){this.caseModalTab=e;const t=document.getElementById("createCaseModal");t.querySelectorAll(".modal-tabs .modal-tab-btn").forEach(a=>{a.classList.toggle("active",a.dataset.tab===e)}),t.querySelectorAll(".modal-tab-content").forEach(a=>{a.classList.toggle("hidden",a.id!==e)});const s=document.getElementById("caseModalSubmit");s.textContent=e==="case-create"?"Create":"Link",e==="case-create"?document.getElementById("newCaseName").focus():document.getElementById("linkCaseName").focus()},closeCreateCaseModal(){document.getElementById("createCaseModal").classList.remove("active")},async submitCaseModal(){const e=document.getElementById("caseModalSubmit"),t=e.textContent;e.classList.add("loading"),e.textContent=this.caseModalTab==="case-create"?"Creating...":"Linking...";try{this.caseModalTab==="case-create"?await this.createCase():await this.linkCase()}finally{e.classList.remove("loading"),e.textContent=t}},async createCase(){const e=document.getElementById("newCaseName").value.trim(),t=document.getElementById("newCaseDescription").value.trim();if(!e){this.showToast("Please enter a case name","error");return}if(!/^[a-zA-Z0-9_-]+$/.test(e)){this.showToast("Invalid name. Use only letters, numbers, hyphens, underscores.","error");return}try{const a=await(await fetch("/api/cases",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:e,description:t})})).json();a.success?(this.closeCreateCaseModal(),this.showToast(`Case "${e}" created`,"success"),await this.loadQuickStartCases(e),await this.saveLastUsedCase(e)):this.showToast(a.error||"Failed to create case","error")}catch(s){console.error("Failed to create case:",s),this.showToast("Failed to create case: "+s.message,"error")}},async linkCase(){const e=document.getElementById("linkCaseName").value.trim(),t=document.getElementById("linkCasePath").value.trim();if(!e){this.showToast("Please enter a case name","error");return}if(!/^[a-zA-Z0-9_-]+$/.test(e)){this.showToast("Invalid name. Use only letters, numbers, hyphens, underscores.","error");return}if(!t){this.showToast("Please enter a folder path","error");return}try{const a=await(await fetch("/api/cases/link",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:e,path:t})})).json();a.success?(this.closeCreateCaseModal(),this.showToast(`Case "${e}" linked to ${t}`,"success"),await this.loadQuickStartCases(e),await this.saveLastUsedCase(e)):this.showToast(a.error||"Failed to link case","error")}catch(s){console.error("Failed to link case:",s),this.showToast("Failed to link case: "+s.message,"error")}},showMobileCasePicker(){const e=document.getElementById("mobileCasePickerModal"),t=document.getElementById("mobileCaseList"),a=document.getElementById("quickStartCase").value;let n="";const o=this.cases||[],r=o.some(d=>d.name==="testcase")?o:[{name:"testcase"},...o];for(const d of r){const u=d.name===a;n+=`
2
+ <button class="mobile-case-item ${u?"selected":""}"
3
+ onclick="app.selectMobileCase('${escapeHtml(d.name)}')">
4
+ <span class="mobile-case-item-icon">
5
+ <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
6
+ <path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"/>
7
+ </svg>
8
+ </span>
9
+ <span class="mobile-case-item-name">${escapeHtml(d.name)}</span>
10
+ <span class="mobile-case-item-check">
11
+ <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5">
12
+ <polyline points="20 6 9 17 4 12"/>
13
+ </svg>
14
+ </span>
15
+ </button>
16
+ `}t.innerHTML=n,e.classList.add("active")},closeMobileCasePicker(){document.getElementById("mobileCasePickerModal").classList.remove("active")},selectMobileCase(e){const t=document.getElementById("quickStartCase");t.value=e,this.updateMobileCaseLabel(e),this.updateDirDisplayForCase(e),this.saveLastUsedCase(e),this.closeMobileCasePicker(),this.showToast(`Selected: ${e}`,"success")},updateMobileCaseLabel(e){const t=document.getElementById("mobileCaseName");t&&(t.textContent=e)},showCreateCaseFromMobile(){this.closeMobileCasePicker(),this.showCreateCaseModal();const e=document.getElementById("createCaseModal");e.classList.add("from-mobile"),setTimeout(()=>e.classList.remove("from-mobile"),300)}});
@@ -0,0 +1,55 @@
1
+ "use strict";Object.assign(CodemanApp.prototype,{_onHookIdlePrompt(e){const t=this.sessions.get(e.sessionId);e.sessionId&&this.setPendingHook(e.sessionId,"idle_prompt"),this.notificationManager?.notify({urgency:"warning",category:"hook-idle",sessionId:e.sessionId,sessionName:t?.name||e.sessionId,title:"Waiting for Input",message:e.message||"Claude is idle and waiting for a prompt"})},_onHookPermissionPrompt(e){const t=this.sessions.get(e.sessionId);e.sessionId&&this.setPendingHook(e.sessionId,"permission_prompt");const n=e.tool?`${e.tool}${e.command?": "+e.command:e.file?": "+e.file:""}`:"";this.notificationManager?.notify({urgency:"critical",category:"hook-permission",sessionId:e.sessionId,sessionName:t?.name||e.sessionId,title:"Permission Required",message:n||"Claude needs tool approval to continue"})},_onHookElicitationDialog(e){const t=this.sessions.get(e.sessionId);e.sessionId&&this.setPendingHook(e.sessionId,"elicitation_dialog"),this.notificationManager?.notify({urgency:"critical",category:"hook-elicitation",sessionId:e.sessionId,sessionName:t?.name||e.sessionId,title:"Question Asked",message:e.question||"Claude is asking a question and waiting for your answer"})},_onHookStop(e){const t=this.sessions.get(e.sessionId);e.sessionId&&this.clearPendingHooks(e.sessionId),this.notificationManager?.notify({urgency:"info",category:"hook-stop",sessionId:e.sessionId,sessionName:t?.name||e.sessionId,title:"Response Complete",message:e.reason||"Claude has finished responding"})},_onHookTeammateIdle(e){const t=this.sessions.get(e.sessionId);this.notificationManager?.notify({urgency:"warning",category:"hook-teammate-idle",sessionId:e.sessionId,sessionName:t?.name||e.sessionId,title:"Teammate Idle",message:`A teammate is idle in ${t?.name||e.sessionId}`})},_onHookTaskCompleted(e){const t=this.sessions.get(e.sessionId);this.notificationManager?.notify({urgency:"info",category:"hook-task-completed",sessionId:e.sessionId,sessionName:t?.name||e.sessionId,title:"Task Completed",message:`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}=t.data;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?.success)throw new Error("Failed to get VAPID key");const t=urlBase64ToUint8Array(e.data.publicKey),n=await this._swRegistration.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:t}),s=n.toJSON(),i=await this._apiJson("/api/push/subscribe",{method:"POST",body:{endpoint:s.endpoint,keys:s.keys,userAgent:navigator.userAgent,pushPreferences:this._buildPushPreferences()}});if(!i?.success)throw new Error("Failed to register subscription");this._pushSubscription=n,this._pushSubscriptionId=i.data.id,localStorage.setItem("codeman-push-subscription-id",i.data.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 i=document.getElementById(s);e[n]=i?i.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("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("appSettingsShowTokenCount").checked=e.showTokenCount??t.showTokenCount??!0,document.getElementById("appSettingsShowCost").checked=e.showCost??t.showCost??!1,document.getElementById("appSettingsShowLifecycleLog").checked=e.showLifecycleLog??t.showLifecycleLog??!0,document.getElementById("appSettingsShowMonitor").checked=e.showMonitor??t.showMonitor??!0,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("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("appSettingsTabTwoRows").checked=e.tabTwoRows??t.tabTwoRows??!1;const n=document.getElementById("appSettingsClaudeMode"),s=document.getElementById("allowedToolsRow");n.value=e.claudeMode||"dangerously-skip-permissions",document.getElementById("appSettingsAllowedTools").value=e.allowedTools||"",s.style.display=n.value==="allowedTools"?"":"none",n.onchange=()=>{s.style.display=n.value==="allowedTools"?"":"none"},document.getElementById("appSettingsAgentTeams").checked=e.agentTeamsEnabled??!1;const i=e.nice||{};document.getElementById("appSettingsNiceEnabled").checked=i.enabled??!1,document.getElementById("appSettingsNiceValue").value=i.niceValue??10,this.loadModelConfigForSettings();const o=this.notificationManager?.preferences||{};document.getElementById("appSettingsNotifEnabled").checked=o.enabled??!0,document.getElementById("appSettingsNotifBrowser").checked=o.browserNotifications??!1,document.getElementById("appSettingsNotifAudio").checked=o.audioAlerts??!1,document.getElementById("appSettingsNotifStuckMins").value=Math.round((o.stuckThresholdMs||6e5)/6e4),document.getElementById("appSettingsNotifCritical").checked=!o.muteCritical,document.getElementById("appSettingsNotifWarning").checked=!o.muteWarning,document.getElementById("appSettingsNotifInfo").checked=!o.muteInfo,document.getElementById("appSettingsPushEnabled").checked=!!this._pushSubscription,this._updatePushUI(!!this._pushSubscription);const l=o.eventTypes||{},a=l.permission_prompt||{};document.getElementById("eventPermissionEnabled").checked=a.enabled??!0,document.getElementById("eventPermissionBrowser").checked=a.browser??!0,document.getElementById("eventPermissionPush").checked=a.push??!1,document.getElementById("eventPermissionAudio").checked=a.audio??!0;const c=l.elicitation_dialog||{};document.getElementById("eventQuestionEnabled").checked=c.enabled??!0,document.getElementById("eventQuestionBrowser").checked=c.browser??!0,document.getElementById("eventQuestionPush").checked=c.push??!1,document.getElementById("eventQuestionAudio").checked=c.audio??!0;const d=l.idle_prompt||{};document.getElementById("eventIdleEnabled").checked=d.enabled??!0,document.getElementById("eventIdleBrowser").checked=d.browser??!0,document.getElementById("eventIdlePush").checked=d.push??!1,document.getElementById("eventIdleAudio").checked=d.audio??!1;const r=l.stop||{};document.getElementById("eventStopEnabled").checked=r.enabled??!0,document.getElementById("eventStopBrowser").checked=r.browser??!1,document.getElementById("eventStopPush").checked=r.push??!1,document.getElementById("eventStopAudio").checked=r.audio??!1;const u=l.respawn_cycle||{};document.getElementById("eventRespawnEnabled").checked=u.enabled??!0,document.getElementById("eventRespawnBrowser").checked=u.browser??!1,document.getElementById("eventRespawnPush").checked=u.push??!1,document.getElementById("eventRespawnAudio").checked=u.audio??!1;const g=l.ralph_complete||{};document.getElementById("eventRalphEnabled").checked=g.enabled??!0,document.getElementById("eventRalphBrowser").checked=g.browser??!0,document.getElementById("eventRalphPush").checked=g.push??!1,document.getElementById("eventRalphAudio").checked=g.audio??!0;const m=l.subagent_spawn||{};document.getElementById("eventSubagentEnabled").checked=m.enabled??!1,document.getElementById("eventSubagentBrowser").checked=m.browser??!1,document.getElementById("eventSubagentPush").checked=m.push??!1,document.getElementById("eventSubagentAudio").checked=m.audio??!1;const h=document.getElementById("notifPermissionStatus");if(h&&typeof Notification<"u"){const p=Notification.permission;h.textContent=p==="granted"?"\u2713":p==="denied"?"\u2717":"?",h.classList.remove("granted","denied"),p==="granted"?h.classList.add("granted"):p==="denied"&&h.classList.add("denied")}const y=VoiceInput._getDeepgramConfig();document.getElementById("voiceDeepgramKey").value=y.apiKey||"",document.getElementById("voiceLanguage").value=y.language||"en-US",document.getElementById("voiceKeyterms").value=y.keyterms||"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=y.insertMode||"direct";const v=document.getElementById("voiceDeepgramKey");v.type="password",document.getElementById("voiceKeyToggleBtn").textContent="Show";const b=VoiceInput.getActiveProviderName(),w=document.getElementById("voiceProviderStatus");w.textContent=b,w.className="voice-provider-status"+(b.startsWith("Deepgram")?" active":""),this.switchSettingsTab("settings-display");const f=document.getElementById("appSettingsModal");f.querySelectorAll(".modal-tabs .modal-tab-btn").forEach(p=>{p.onclick=()=>this.switchSettingsTab(p.dataset.tab)}),f.classList.add("active"),this.activeFocusTrap=new FocusTrap(f),this.activeFocusTrap.activate()},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)})},closeAppSettings(){document.getElementById("appSettingsModal").classList.remove("active"),this.activeFocusTrap&&(this.activeFocusTrap.deactivate(),this.activeFocusTrap=null)},async loadTunnelStatus(){try{const t=await(await fetch("/api/tunnel/status")).json(),n=t.running&&t.url;this._tunnelUrl=n?t.url:null,this._updateTunnelUrlDisplay(this._tunnelUrl),this._updateWelcomeTunnelBtn(!!n,this._tunnelUrl),this._updateTunnelIndicator(!!n)}catch{this._tunnelUrl=null,this._updateTunnelUrlDisplay(null),this._updateWelcomeTunnelBtn(!1),this._updateTunnelIndicator(!1)}},_updateTunnelUrlDisplay(e){const t=document.getElementById("tunnelUrlRow"),n=document.getElementById("tunnelUrlDisplay");if(!t||!n)return;e?(t.style.display="",n.textContent=e,n.onclick=()=>{navigator.clipboard.writeText(e).then(()=>{this.showToast("Tunnel URL copied","success")})}):(t.style.display="none",n.textContent="",n.onclick=null);const s=document.getElementById("tunnelUploadUrlRow"),i=document.getElementById("tunnelUploadUrlDisplay");if(!(!s||!i))if(e){const o=e+"/upload.html";s.style.display="",i.textContent=o,i.onclick=()=>{navigator.clipboard.writeText(o).then(()=>{this.showToast("Upload URL copied","success")})}}else s.style.display="none",i.textContent="",i.onclick=null},showTunnelQR(){this.closeTunnelQR();const e=document.createElement("div");e.id="tunnelQrOverlay",e.style.cssText="position:fixed;inset:0;background:rgba(0,0,0,0.7);z-index:5000;display:flex;align-items:center;justify-content:center;cursor:pointer",e.onclick=n=>{n.target===e&&this.closeTunnelQR()};const t=document.createElement("div");t.style.cssText="background:var(--bg-card);border:1px solid var(--border);border-radius:12px;padding:24px;text-align:center;max-width:340px;width:90vw;box-shadow:var(--shadow-lg);cursor:default",t.innerHTML=`
2
+ <div style="font-size:14px;font-weight:600;color:var(--text-primary);margin-bottom:16px">Scan to connect</div>
3
+ <div id="tunnelQrContainer" style="background:#fff;border-radius:8px;padding:16px;display:inline-block">
4
+ <div style="color:#666;font-size:12px">Loading...</div>
5
+ </div>
6
+ <div id="tunnelQrUrl" style="margin-top:12px;font-family:monospace;font-size:11px;color:var(--text-muted);word-break:break-all;cursor:pointer" title="Click to copy"></div>
7
+ <button onclick="app.closeTunnelQR()" style="margin-top:16px;padding:6px 20px;background:var(--bg-elevated);border:1px solid var(--border);border-radius:6px;color:var(--text-primary);cursor:pointer;font-size:13px">Close</button>
8
+ `,e.appendChild(t),document.body.appendChild(e),fetch("/api/tunnel/qr").then(n=>{if(!n.ok)throw new Error("Tunnel not running");return n.json()}).then(n=>{const s=document.getElementById("tunnelQrContainer");if(s&&n.svg&&(s.innerHTML=n.svg),n.authEnabled){const i=document.createElement("div");i.id="tunnelQrBadge",i.style.cssText="margin-top:8px;font-size:11px;color:var(--text-muted)",i.textContent="Single-use auth \xB7 expires in 60s";const o=document.createElement("button");o.textContent="Regenerate QR",o.style.cssText="margin-top:8px;padding:4px 12px;background:var(--bg-elevated);border:1px solid var(--border);border-radius:4px;color:var(--text-secondary);cursor:pointer;font-size:11px",o.onclick=()=>{fetch("/api/tunnel/qr/regenerate",{method:"POST"}).then(()=>this.showToast("QR code regenerated","success")).catch(()=>this.showToast("Failed to regenerate QR","error"))};const l=s.parentElement;l&&(l.appendChild(i),l.appendChild(o)),this._resetQrCountdown()}}).catch(()=>{const n=document.getElementById("tunnelQrContainer");n&&(n.innerHTML='<div style="color:#c00;font-size:12px;padding:20px">Tunnel not active</div>')}),fetch("/api/tunnel/status").then(n=>n.json()).then(n=>{const s=document.getElementById("tunnelQrUrl");s&&n.url&&(s.textContent=n.url,s.onclick=()=>{navigator.clipboard.writeText(n.url).then(()=>{this.showToast("Tunnel URL copied","success")})})}).catch(()=>{}),this._tunnelQrEscHandler=n=>{n.key==="Escape"&&this.closeTunnelQR()},document.addEventListener("keydown",this._tunnelQrEscHandler)},closeTunnelQR(){const e=document.getElementById("tunnelQrOverlay");e&&e.remove(),this._tunnelQrEscHandler&&(document.removeEventListener("keydown",this._tunnelQrEscHandler),this._tunnelQrEscHandler=null),this._clearQrCountdown()},_refreshTunnelQrFromApi(){fetch("/api/tunnel/qr").then(e=>e.ok?e.json():null).then(e=>{if(!e?.svg)return;const t=document.getElementById("tunnelQrContainer");t&&(t.innerHTML=e.svg);const n=document.getElementById("welcomeQrInner");n&&(n.innerHTML=e.svg)}).catch(()=>{})},_resetQrCountdown(){this._clearQrCountdown(),this._qrCountdownSec=60,this._updateQrCountdownText(),this._qrCountdownTimer=setInterval(()=>{if(this._qrCountdownSec--,this._qrCountdownSec<=0){this._clearQrCountdown();return}this._updateQrCountdownText()},1e3)},_updateQrCountdownText(){const e=document.getElementById("tunnelQrBadge");e&&(e.textContent=`Single-use auth \xB7 expires in ${this._qrCountdownSec}s`)},_clearQrCountdown(){this._qrCountdownTimer&&(clearInterval(this._qrCountdownTimer),this._qrCountdownTimer=null)},async toggleTunnelFromWelcome(){const e=document.getElementById("welcomeTunnelBtn");if(!e)return;const t=e.classList.contains("active");e.disabled=!0;try{const n=!t;await fetch("/api/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({tunnelEnabled:n})}),n?(this._showTunnelConnecting(),this._pollTunnelStatus()):(this._dismissTunnelConnecting(),this.showToast("Tunnel stopped","info"),this._updateWelcomeTunnelBtn(!1),e.disabled=!1)}catch{this._dismissTunnelConnecting(),this.showToast("Failed to toggle tunnel","error"),e.disabled=!1}},_showTunnelConnecting(){const e=document.getElementById("tunnelConnectingToast");e&&e.remove();const t=document.getElementById("welcomeTunnelBtn");t&&(t.classList.add("connecting"),t.innerHTML=`
9
+ <span class="tunnel-spinner"></span>
10
+ Connecting...`);const n=document.createElement("div");n.className="toast toast-info show",n.id="tunnelConnectingToast",n.innerHTML='<span class="tunnel-spinner"></span> Cloudflare Tunnel connecting...',n.style.pointerEvents="auto",this._toastContainer||(this._toastContainer=document.querySelector(".toast-container"),this._toastContainer||(this._toastContainer=document.createElement("div"),this._toastContainer.className="toast-container",document.body.appendChild(this._toastContainer))),this._toastContainer.appendChild(n)},_dismissTunnelConnecting(){clearTimeout(this._tunnelPollTimer),this._tunnelPollTimer=null;const e=document.getElementById("tunnelConnectingToast");e&&(e.classList.remove("show"),setTimeout(()=>e.remove(),200));const t=document.getElementById("welcomeTunnelBtn");t&&t.classList.remove("connecting")},_pollTunnelStatus(e=0){e>15||(this._tunnelPollTimer=setTimeout(async()=>{try{const n=await(await fetch("/api/tunnel/status")).json();if(n.running&&n.url){this._dismissTunnelConnecting(),this._updateTunnelUrlDisplay(n.url),document.getElementById("welcomeOverlay")?.classList.contains("visible")?(this._updateWelcomeTunnelBtn(!0,n.url,!0),this.showToast("Tunnel active","success")):(this._updateWelcomeTunnelBtn(!0,n.url),this.showToast(`Tunnel active: ${n.url}`,"success"),this.showTunnelQR());return}}catch{}this._pollTunnelStatus(e+1)},2e3))},_updateWelcomeTunnelBtn(e,t,n=!1){const s=document.getElementById("welcomeTunnelBtn");s&&(s.disabled=!1,e?(s.classList.remove("connecting"),s.classList.add("active"),s.innerHTML=`
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
+ Tunnel Active`):(s.classList.remove("active","connecting"),s.innerHTML=`
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 i=document.getElementById("welcomeQr"),o=document.getElementById("welcomeQrInner"),l=document.getElementById("welcomeQrUrl");!i||!o||(e?(i.classList.add("visible"),n&&(i.classList.add("expanded"),clearTimeout(this._welcomeQrShrinkTimer),this._welcomeQrShrinkTimer=setTimeout(()=>{i.classList.remove("expanded")},8e3)),t&&(l.textContent=t,l.title="Click QR to enlarge"),fetch("/api/tunnel/qr").then(a=>{if(!a.ok)throw new Error;return a.json()}).then(a=>{a.svg&&(o.innerHTML=a.svg)}).catch(()=>{o.innerHTML='<div style="color:#999;font-size:11px;padding:20px">QR unavailable</div>'})):(clearTimeout(this._welcomeQrShrinkTimer),i.classList.remove("visible","expanded"),o.innerHTML="",l&&(l.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
+ <div class="tunnel-panel-header">
16
+ <h3>
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>
18
+ Cloudflare Tunnel
19
+ <span class="tunnel-panel-status" id="tunnelPanelStatus">Loading...</span>
20
+ </h3>
21
+ </div>
22
+ <div class="tunnel-panel-body" id="tunnelPanelBody">
23
+ <div style="font-size:12px;color:var(--text-muted);padding:8px 0">Loading...</div>
24
+ </div>
25
+ `,document.body.appendChild(e),this._tunnelPanelClickHandler=t=>{!e.contains(t.target)&&t.target.id!=="tunnelIndicator"&&!t.target.closest(".tunnel-indicator")&&this.closeTunnelPanel()},setTimeout(()=>document.addEventListener("click",this._tunnelPanelClickHandler),0),this._tunnelPanelEscHandler=t=>{t.key==="Escape"&&this.closeTunnelPanel()},document.addEventListener("keydown",this._tunnelPanelEscHandler);try{const n=await(await fetch("/api/tunnel/info")).json();this._renderTunnelPanel(n)}catch{const t=document.getElementById("tunnelPanelBody");t&&(t.innerHTML='<div style="font-size:12px;color:var(--red);padding:8px 0">Failed to load tunnel info</div>')}},_renderTunnelPanel(e){const t=document.getElementById("tunnelPanelStatus"),n=document.getElementById("tunnelPanelBody");if(!t||!n)return;t.textContent=e.running?"Connected":"Offline",t.className="tunnel-panel-status"+(e.running?"":" offline");let s="";if(e.url&&(s+=`
26
+ <div class="tunnel-panel-section">
27
+ <div class="tunnel-panel-label">URL</div>
28
+ <div class="tunnel-panel-url" id="tunnelPanelUrl" title="Click to copy">${escapeHtml(e.url)}</div>
29
+ </div>`),s+=`
30
+ <div class="tunnel-panel-section">
31
+ <div class="tunnel-panel-label">Connections</div>
32
+ <div class="tunnel-panel-stat">
33
+ <span>Remote Clients</span>
34
+ <span class="tunnel-panel-stat-value">${e.sseClients}</span>
35
+ </div>`,e.authEnabled&&(s+=`
36
+ <div class="tunnel-panel-stat">
37
+ <span>Auth Sessions</span>
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 o of e.authSessions){const l=o.ua||"Unknown",a=l.match(/Chrome|Firefox|Safari|Edge|Mobile/)?.[0]||"Browser",c=this._formatTimeAgo(o.createdAt);s+=`
40
+ <div class="tunnel-panel-session">
41
+ <span class="tunnel-panel-session-dot"></span>
42
+ <span class="tunnel-panel-session-info" title="${escapeHtml(l)}">${escapeHtml(a)} &middot; ${escapeHtml(o.ip)} &middot; ${c}</span>
43
+ <span class="tunnel-panel-session-method">${o.method}</span>
44
+ </div>`}s+="</div>"}s+='<div class="tunnel-panel-actions">',e.running?s+=`
45
+ <button class="tunnel-panel-btn btn-qr" onclick="app.showTunnelQR();app.closeTunnelPanel()">QR Code</button>
46
+ <button class="tunnel-panel-btn btn-stop" onclick="app._tunnelPanelToggle(false)">Stop Tunnel</button>`:s+='<button class="tunnel-panel-btn btn-start" onclick="app._tunnelPanelToggle(true)">Start Tunnel</button>',s+="</div>",e.authEnabled&&e.authSessions.length>0&&(s+=`
47
+ <div style="padding-top:8px">
48
+ <button class="tunnel-panel-btn btn-revoke" style="width:100%" onclick="app._tunnelPanelRevokeAll()">Revoke All Sessions</button>
49
+ </div>`),n.innerHTML=s;const i=document.getElementById("tunnelPanelUrl");i&&(i.onclick=()=>{navigator.clipboard.writeText(e.url).then(()=>this.showToast("Tunnel URL copied","success"))})},_formatTimeAgo(e){const t=Date.now()-e,n=Math.floor(t/6e4);if(n<1)return"just now";if(n<60)return`${n}m ago`;const s=Math.floor(n/60);return s<24?`${s}h ago`:`${Math.floor(s/24)}d ago`},async _tunnelPanelToggle(e){try{if(await fetch("/api/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({tunnelEnabled:e})}),e){this._updateTunnelIndicator(!1);const t=document.getElementById("tunnelIndicator");t&&(t.style.display="flex",t.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();this._renderTunnelPanel(t)}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,i,o,l;t.addEventListener("mousedown",a=>{if(a.target.tagName==="SELECT"||a.target.tagName==="INPUT"||a.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=a.clientX,i=a.clientY,o=c.left,l=c.top,a.preventDefault()}),document.addEventListener("mousemove",a=>{n&&(e.style.left=o+a.clientX-s+"px",e.style.top=l+a.clientY-i+"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 i=await(await fetch(`/api/session-lifecycle?${n}`)).json(),o=document.getElementById("lifecycleTableBody"),l=document.getElementById("lifecycleEmpty");if(!i.entries||i.entries.length===0){o.innerHTML="",l.style.display="";return}l.style.display="none";const a={created:"#4ade80",started:"#4ade80",recovered:"#4ade80",exit:"#fbbf24",mux_died:"#f87171",deleted:"#f87171",stale_cleaned:"#f87171",server_started:"#666",server_stopped:"#666"};o.innerHTML=i.entries.map(c=>{const d=new Date(c.ts).toLocaleString(),r=a[c.event]||"#888",u=c.name||(c.sessionId==="*"?"\u2014":this.getShortId(c.sessionId)),g=[];return c.exitCode!==void 0&&c.exitCode!==null&&g.push(`code=${c.exitCode}`),c.mode&&g.push(c.mode),`<tr style="border-bottom:1px solid #1a1a2e">
50
+ <td style="padding:3px 8px;color:#888;white-space:nowrap">${d}</td>
51
+ <td style="padding:3px 8px;color:${r};font-weight:600">${c.event}</td>
52
+ <td style="padding:3px 8px;color:#e0e0e0" title="${c.sessionId}">${u}</td>
53
+ <td style="padding:3px 8px;color:#aaa">${c.reason||""}</td>
54
+ <td style="padding:3px 8px;color:#666">${g.join(", ")}</td>
55
+ </tr>`}).join("")}catch(s){console.error("Failed to load lifecycle log:",s)}},async saveAppSettings(){const e={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,showTokenCount:document.getElementById("appSettingsShowTokenCount").checked,showCost:document.getElementById("appSettingsShowCost").checked,showLifecycleLog:document.getElementById("appSettingsShowLifecycleLog").checked,showMonitor:document.getElementById("appSettingsShowMonitor").checked,showProjectInsights:document.getElementById("appSettingsShowProjectInsights").checked,showFileBrowser:document.getElementById("appSettingsShowFileBrowser").checked,showSubagents:document.getElementById("appSettingsShowSubagents").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,tabTwoRows:document.getElementById("appSettingsTabTwoRows").checked,claudeMode:document.getElementById("appSettingsClaudeMode").value,allowedTools:document.getElementById("appSettingsAllowedTools").value.trim(),agentTeamsEnabled:document.getElementById("appSettingsAgentTeams").checked,nice:{enabled:document.getElementById("appSettingsNiceEnabled").checked,niceValue:parseInt(document.getElementById("appSettingsNiceValue").value)||10}};this.saveAppSettingsToStorage(e),this._updateLocalEchoState();const t={apiKey:document.getElementById("voiceDeepgramKey").value.trim(),language:document.getElementById("voiceLanguage").value,keyterms:document.getElementById("voiceKeyterms").value.trim(),insertMode:document.getElementById("voiceInsertMode").value};VoiceInput._saveDeepgramConfig(t);const n={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:4};this.notificationManager&&(this.notificationManager.preferences=n,this.notificationManager.savePreferences()),this._syncPushPreferences(),this.applyHeaderVisibilitySettings(),this.applyTabWrapSettings(),this._updateTokensImmediate(),this.applyMonitorVisibility(),this.renderProjectInsightsPanel(),this.updateSubagentWindowVisibility();const{localEchoEnabled:s,...i}=e;try{await this._apiPut("/api/settings",{...i,notificationPreferences:n,voiceSettings:t}),await this.saveModelConfigFromSettings(),this.showToast("Settings saved","success"),e.tunnelEnabled&&this.showToast("Tunnel starting \u2014 QR code will appear when ready...","info")}catch{this.showToast("Settings saved locally","warning")}this.closeAppSettings()},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||"opus");const i=document.getElementById("appSettingsShowModelRecommendations");i&&(i.checked=n.showRecommendations??!0);const o=n.agentTypeOverrides||{},l=document.getElementById("appSettingsModelExplore"),a=document.getElementById("appSettingsModelImplement"),c=document.getElementById("appSettingsModelTest"),d=document.getElementById("appSettingsModelReview");l&&(l.value=o.explore||""),a&&(a.value=o.implement||""),c&&(c.value=o.test||""),d&&(d.value=o.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"),i=document.getElementById("appSettingsModelTest"),o=document.getElementById("appSettingsModelReview"),l={};n?.value&&(l.explore=n.value),s?.value&&(l.implement=s.value),i?.value&&(l.test=i.value),o?.value&&(l.review=o.value);const a={defaultModel:e?.value||"opus",showRecommendations:t?.checked??!0,agentTypeOverrides:l};try{await fetch("/api/execution/model-config",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)})}catch(c){console.warn("Failed to save model config:",c)}},isRalphTrackerEnabledByDefault(){return this.loadAppSettingsFromStorage().ralphTrackerEnabled??!1},getSettingsStorageKey(){return MobileDetection.getDeviceType()==="mobile"?"codeman-app-settings-mobile":"codeman-app-settings"},getDefaultSettings(){return MobileDetection.getDeviceType()==="mobile"?{showFontControls:!1,showSystemStats:!1,showTokenCount:!1,showCost:!1,showMonitor:!1,showProjectInsights:!1,showFileBrowser:!1,showSubagents:!1,subagentTrackingEnabled:!0,subagentActiveTabOnly:!0,imageWatcherEnabled:!1,ralphTrackerEnabled:!1,tabTwoRows:!1}:{}},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)}},applyHeaderVisibilitySettings(){const e=this.loadAppSettingsFromStorage(),t=this.getDefaultSettings(),n=e.showFontControls??t.showFontControls??!1,s=e.showSystemStats??t.showSystemStats??!0,i=e.showTokenCount??t.showTokenCount??!0,o=document.querySelector(".header-font-controls"),l=document.getElementById("headerSystemStats"),a=document.getElementById("headerTokens");o&&(o.style.display=n?"":"none"),l&&(l.style.display=s?"":"none"),a&&(a.style.display=i?"":"none");const c=e.showLifecycleLog??t.showLifecycleLog??!0,d=document.querySelector(".btn-lifecycle-log");d&&(d.style.display=c?"":"none");const r=this.notificationManager?.preferences?.enabled??!0,u=document.querySelector(".btn-notifications");if(u&&(u.style.display=r?"":"none"),!r){const g=document.getElementById("notifDrawer");g&&g.classList.remove("open")}},applyTabWrapSettings(){const e=this.loadAppSettingsFromStorage(),t=this.getDefaultSettings(),s=MobileDetection.getDeviceType()==="desktop"?e.tabTwoRows??t.tabTwoRows??!1:!1,i=this._tallTabsEnabled;this._tallTabsEnabled=s;const o=document.getElementById("sessionTabs");o&&(o.classList.toggle("tabs-two-rows",s),o.classList.toggle("tabs-show-folder",s)),i!==void 0&&i!==s&&this._fullRenderSessionTabs()},applyMonitorVisibility(){const e=this.loadAppSettingsFromStorage(),t=this.getDefaultSettings(),n=e.showMonitor??t.showMonitor??!0,s=e.showSubagents??t.showSubagents??!1,i=e.showFileBrowser??t.showFileBrowser??!1,o=document.getElementById("monitorPanel");o&&(o.style.display=n?"":"none",n?o.classList.add("open"):o.classList.remove("open"));const l=document.getElementById("subagentsPanel");l&&(s?l.classList.remove("hidden"):l.classList.add("hidden"));const a=document.getElementById("fileBrowserPanel");if(a)if(i&&this.activeSessionId){if(a.classList.add("visible"),this.loadFileBrowser(this.activeSessionId),!this.fileBrowserDragListeners){const c=a.querySelector(".file-browser-header");if(c){const d=()=>{if(!a.style.left){const r=a.getBoundingClientRect();a.style.left=`${r.left}px`,a.style.top=`${r.top}px`,a.style.right="auto"}};c.addEventListener("mousedown",d),c.addEventListener("touchstart",d,{passive:!0}),this.fileBrowserDragListeners=this.makeWindowDraggable(a,c),this.fileBrowserDragListeners._onFirstDrag=d}}}else a.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{const t=e?await e:await fetch("/api/settings").then(n=>n.ok?n.json():null);if(t){const{notificationPreferences:n,voiceSettings:s,respawnPresets:i,runMode:o,...l}=t,a=new Set(["showFontControls","showSystemStats","showTokenCount","showCost","showMonitor","showProjectInsights","showFileBrowser","showSubagents","subagentActiveTabOnly","tabTwoRows","localEchoEnabled"]),c=this.loadAppSettingsFromStorage(),d={...c};for(const[r,u]of Object.entries(l))a.has(r)&&r in c||(d[r]=u);if(this.saveAppSettingsToStorage(d),n&&this.notificationManager&&(localStorage.getItem(this.notificationManager.getStorageKey())||(this.notificationManager.preferences=n,this.notificationManager.savePreferences())),s){const r=localStorage.getItem("codeman-voice-settings");(!r||!JSON.parse(r).apiKey)&&VoiceInput._saveDeepgramConfig(s)}if(i&&Array.isArray(i))this._serverRespawnPresets=i,localStorage.setItem("codeman-respawn-presets",JSON.stringify(i));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(o){this.runMode=o;try{localStorage.setItem("codeman_runMode",o)}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");t.ok&&(e=await t.json(),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");t.ok&&(e=await t.json(),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)},closeAllPanels(){this.closeSessionOptions(),this.closeAppSettings(),this.cancelCloseSession(),this.closeTokenStats(),document.getElementById("monitorPanel").classList.remove("open");const e=document.getElementById("subagentsPanel");e&&e.classList.remove("open"),this.subagentPanelVisible=!1}});
@@ -15,7 +15,7 @@
15
15
  * @mixin Extends CodemanApp.prototype via Object.assign
16
16
  * @dependency app.js (CodemanApp class, this.subagents, this.subagentWindows, this.minimizedSubagents)
17
17
  * @dependency constants.js (escapeHtml)
18
- * @loadorder 9 of 9 — loaded last, after api-client.js
18
+ * @loadorder 15 of 15 — loaded last, after api-client.js
19
19
  */
20
20
 
21
21
  // Codeman — Subagent window management for CodemanApp
@@ -991,7 +991,7 @@ Object.assign(CodemanApp.prototype, {
991
991
  }
992
992
 
993
993
  // Clean up wizard drag listeners (leak fix: document-level handlers)
994
- this.cleanupWizardDragging();
994
+ if (typeof this.cleanupWizardDragging === 'function') this.cleanupWizardDragging();
995
995
 
996
996
  // Deactivate focus trap if wizard was open (leak fix: keydown listener)
997
997
  if (this.activeFocusTrap) {
Binary file
@@ -0,0 +1,3 @@
1
+ "use strict";Object.assign(CodemanApp.prototype,{initTerminal(){const e=parseInt(localStorage.getItem("codeman-scrollback"))||DEFAULT_SCROLLBACK;if(this.terminal=new Terminal({theme:{background:"#0d0d0d",foreground:"#e0e0e0",cursor:"#e0e0e0",cursorAccent:"#0d0d0d",selection:"rgba(255, 255, 255, 0.3)",black:"#0d0d0d",red:"#ff6b6b",green:"#51cf66",yellow:"#ffd43b",blue:"#339af0",magenta:"#cc5de8",cyan:"#22b8cf",white:"#e0e0e0",brightBlack:"#495057",brightRed:"#ff8787",brightGreen:"#69db7c",brightYellow:"#ffe066",brightBlue:"#5c7cfa",brightMagenta:"#da77f2",brightCyan:"#66d9e8",brightWhite:"#ffffff"},fontFamily:'"Fira Code", "Cascadia Code", "JetBrains Mono", "SF Mono", Monaco, monospace',fontSize:MobileDetection.getDeviceType()==="mobile"?10:14,lineHeight:1.2,cursorBlink:!1,cursorStyle:"block",scrollback:e,allowTransparency:!0,allowProposedApi:!0}),this.fitAddon=new FitAddon.FitAddon,this.terminal.loadAddon(this.fitAddon),typeof Unicode11Addon<"u")try{const t=new Unicode11Addon.Unicode11Addon;this.terminal.loadAddon(t),this.terminal.unicode.activeVersion="11"}catch{}const i=document.getElementById("terminalContainer");if(this.terminal.open(i),this.terminal.attachCustomKeyEventHandler(t=>!(t.isComposing||t.keyCode===229)),this._webglAddon=null,!(MobileDetection.getDeviceType()!=="desktop")&&!new URLSearchParams(location.search).has("nowebgl"))if(typeof WebglAddon<"u")this._initWebGL();else{const t=document.createElement("script");t.src="vendor/xterm-addon-webgl.min.js",t.onload=()=>this._initWebGL(),t.onerror=()=>console.warn("[CRASH-DIAG] Failed to load WebGL addon \u2014 using canvas renderer"),document.head.appendChild(t)}if(this._localEchoOverlay=new LocalEchoOverlay(this.terminal),this._cjkInput=null,typeof CjkInput<"u"&&(this._cjkInput=CjkInput.init({send:t=>{this.activeSessionId&&this._sendInputAsync(this.activeSessionId,t)}})),MobileDetection.getDeviceType()==="mobile"&&document.body.classList.contains("safari-browser")?requestAnimationFrame(()=>{this.fitAddon.fit(),requestAnimationFrame(()=>this.fitAddon.fit())}):this.fitAddon.fit(),this.registerFilePathLinkProvider(),i.addEventListener("wheel",t=>{t.preventDefault();const c=Math.round(t.deltaY/25)||(t.deltaY>0?1:-1);this.terminal.scrollLines(c)},{passive:!1}),!(MobileDetection.isTouchDevice()&&window.innerWidth<1024)){let t=0,c=0,l=0,h=0,f=null,m=!1;const p=i.querySelector(".xterm-viewport"),g=_=>{if(!p)return;const y=h?(_-h)/16.67:1;h=_,m?(c!==0&&(p.scrollTop+=c,c=0),f=requestAnimationFrame(g)):Math.abs(l)>.1?(p.scrollTop+=l*y,l*=.94,f=requestAnimationFrame(g)):(f=null,l=0)};i.addEventListener("touchstart",_=>{_.touches.length===1&&(t=_.touches[0].clientY,c=0,l=0,m=!0,h=0,f||(f=requestAnimationFrame(g)))},{passive:!0}),i.addEventListener("touchmove",_=>{if(_.touches.length===1&&m){const y=_.touches[0].clientY,b=t-y;c+=b,l=b*1.2,t=y}},{passive:!0}),i.addEventListener("touchend",()=>{m=!1},{passive:!0}),i.addEventListener("touchcancel",()=>{m=!1,l=0},{passive:!0})}this.showWelcome(),this._resizeTimeout=null,this._lastResizeDims=null;const d=40,r=10,a=()=>{this._resizeTimeout&&clearTimeout(this._resizeTimeout),this._resizeTimeout=setTimeout(()=>{this._resizeTimeout=null,this.fitAddon&&this.fitAddon.fit(),this.flickerFilterBuffer&&(this.flickerFilterTimeout&&(clearTimeout(this.flickerFilterTimeout),this.flickerFilterTimeout=null),this.flushFlickerBuffer());const t=this.activeSessionId?this.sessions.get(this.activeSessionId):null;t&&t.mode!=="shell"&&!t._ended&&this.terminal&&this.isTerminalAtBottom()&&this.terminal.write("\x1B[3J\x1B[H\x1B[2J");const c=typeof KeyboardHandler<"u"&&KeyboardHandler.keyboardVisible;if(this.activeSessionId&&!c){const l=this.fitAddon.proposeDimensions(),h=l?Math.max(l.cols,d):d,f=l?Math.max(l.rows,r):r;(!this._lastResizeDims||h!==this._lastResizeDims.cols||f!==this._lastResizeDims.rows)&&(this._lastResizeDims={cols:h,rows:f},fetch(`/api/sessions/${this.activeSessionId}/resize`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cols:h,rows:f})}).catch(()=>{}))}this.updateConnectionLines(),this._localEchoOverlay?.hasPending&&this._localEchoOverlay.rerender()},300)};window.addEventListener("resize",a),this.terminalResizeObserver&&this.terminalResizeObserver.disconnect(),this.terminalResizeObserver=new ResizeObserver(a),this.terminalResizeObserver.observe(i),this._pendingInput="",this._inputFlushTimeout=null,this._lastKeystrokeTime=0;const s=()=>{if(this._inputFlushTimeout=null,this._pendingInput&&this.activeSessionId){const t=this._pendingInput,c=this.activeSessionId;this._pendingInput="",this._sendInputAsync(c,t)}};this.terminal.onData(t=>{if(!(window.cjkActive||document.activeElement?.id==="cjkInput")&&this.activeSessionId){if(/^\x1b\[[\?>=]?[\d;]*[cnR]$/.test(t))return;if(this._localEchoEnabled){if(t==="\x7F"){if(this._localEchoOverlay?.removeChar()==="flushed"){const{count:h,text:f}=this._localEchoOverlay.getFlushed();this._flushedOffsets?.has(this.activeSessionId)&&(h===0?(this._flushedOffsets.delete(this.activeSessionId),this._flushedTexts?.delete(this.activeSessionId)):(this._flushedOffsets.set(this.activeSessionId,h),this._flushedTexts?.set(this.activeSessionId,f))),this._pendingInput+=t,s()}return}if(/^[\r\n]+$/.test(t)){const l=this._localEchoOverlay?.pendingText||"";this._localEchoOverlay?.clear(),this._localEchoOverlay?.suppressBufferDetection(),this._flushedOffsets?.delete(this.activeSessionId),this._flushedTexts?.delete(this.activeSessionId),this._inputFlushTimeout&&(clearTimeout(this._inputFlushTimeout),this._inputFlushTimeout=null),l&&(this._pendingInput+=l,s()),setTimeout(()=>{this._pendingInput+="\r",s()},80);return}if(t.length>1&&t.charCodeAt(0)>=32){this._localEchoOverlay?.appendText(t);return}if(t.charCodeAt(0)<32){if(t.length>1&&t.charCodeAt(0)===27){this._pendingInput+=t,s();return}if(this._restoringFlushedState){this._pendingInput+=t,s();return}if(t===" "){const h=this._localEchoOverlay?.pendingText||"";this._localEchoOverlay?.clear(),this._flushedOffsets?.delete(this.activeSessionId),this._flushedTexts?.delete(this.activeSessionId),h&&(this._pendingInput+=h),this._pendingInput+=t,this._inputFlushTimeout&&(clearTimeout(this._inputFlushTimeout),this._inputFlushTimeout=null);let f="";try{const p=this._localEchoOverlay?.findPrompt?.();if(p){const g=this.terminal.buffer.active,_=g.getLine(g.viewportY+p.row);_&&(f=_.translateToString(!0).slice(p.col+2).trimEnd())}}catch{}this._tabCompletionBaseText=f,s(),this._tabCompletionSessionId=this.activeSessionId,this._tabCompletionRetries=0,this._tabCompletionFallback&&clearTimeout(this._tabCompletionFallback);const m=this;this._tabCompletionFallback=setTimeout(()=>{if(m._tabCompletionFallback=null,!m._tabCompletionSessionId||m._tabCompletionSessionId!==m.activeSessionId)return;const p=m._localEchoOverlay;!p||p.pendingText||m.terminal.write("",()=>{if(!m._tabCompletionSessionId)return;p.resetBufferDetection();const g=p.detectBufferText();g&&g!==m._tabCompletionBaseText&&(m._tabCompletionSessionId=null,m._tabCompletionRetries=0,m._tabCompletionBaseText=null,p.rerender())})},300);return}const l=this._localEchoOverlay?.pendingText||"";this._localEchoOverlay?.clear(),this._localEchoOverlay?.suppressBufferDetection(),this._flushedOffsets?.delete(this.activeSessionId),this._flushedTexts?.delete(this.activeSessionId),l&&(this._pendingInput+=l),this._pendingInput+=t,this._inputFlushTimeout&&(clearTimeout(this._inputFlushTimeout),this._inputFlushTimeout=null),s();return}if(t.length===1&&t.charCodeAt(0)>=32){this._localEchoOverlay?.addChar(t);return}}if(this._pendingInput+=t,t.charCodeAt(0)<32||t.length>1){this._inputFlushTimeout&&(clearTimeout(this._inputFlushTimeout),this._inputFlushTimeout=null),s();return}const c=performance.now();c-this._lastKeystrokeTime>50?(this._inputFlushTimeout&&(clearTimeout(this._inputFlushTimeout),this._inputFlushTimeout=null),this._lastKeystrokeTime=c,s()):(this._lastKeystrokeTime=c,this._inputFlushTimeout||(this._inputFlushTimeout=setTimeout(s,0)))}})},registerFilePathLinkProvider(){const e=this;let i=-1;this.terminal.registerLinkProvider({provideLinks(o,n){o!==i&&(i=o,console.debug("[LinkProvider] Checking line:",o));const d=e.terminal.buffer.active.getLine(o);if(!d){n(void 0);return}const r=d.translateToString(!0);if(!r||!r.includes("/")){n(void 0);return}const a=[],s=/(tail|cat|head|less|grep|watch|vim|nano)\s+(?:[^\s\/]*\s+)*(\/[^\s"'<>|;&\n\x00-\x1f]+)/g,t=/(\/(?:home|tmp|var|etc|opt)[^\s"'<>|;&\n\x00-\x1f]*\.(?:log|txt|json|md|yaml|yml|csv|xml|sh|py|ts|js))\b/g,c=/Bash\([^)]*?(\/(?:home|tmp|var|etc|opt)[^\s"'<>|;&\)\n\x00-\x1f]+)/g,l=(f,m)=>{const p=r.indexOf(f,m);p!==-1&&(a.some(g=>g.range.start.x===p+1)||a.push({text:f,range:{start:{x:p+1,y:o},end:{x:p+f.length+1,y:o}},decorations:{pointerCursor:!0,underline:!0},activate(g,_){e.openLogViewerWindow(_,e.activeSessionId)}}))};let h;for(s.lastIndex=0;(h=s.exec(r))!==null;)l(h[2],h.index);for(t.lastIndex=0;(h=t.exec(r))!==null;)l(h[1],h.index);for(c.lastIndex=0;(h=c.exec(r))!==null;)l(h[1],h.index);a.length>0&&console.debug("[LinkProvider] Found links:",a.map(f=>f.text)),n(a.length>0?a:void 0)}}),console.log("[LinkProvider] File path link provider registered")},showWelcome(){const e=document.getElementById("welcomeOverlay");e&&(e.classList.add("visible"),this.loadTunnelStatus(),this.loadHistorySessions())},hideWelcome(){const e=document.getElementById("welcomeOverlay");e&&e.classList.remove("visible");const i=document.getElementById("welcomeQr");i&&(clearTimeout(this._welcomeQrShrinkTimer),i.classList.remove("expanded"))},async _fetchHistorySessions(e=12){const n=(await(await fetch("/api/history/sessions")).json()).sessions||[];if(n.length===0)return[];const u=new Map;for(const r of n)u.has(r.workingDir)||u.set(r.workingDir,[]),u.get(r.workingDir).push(r);const d=[];for(const[,r]of u)d.push(...r.slice(0,2));return d.sort((r,a)=>new Date(a.lastModified)-new Date(r.lastModified)),d.slice(0,e)},async loadHistorySessions(){const e=document.getElementById("historySessions"),i=document.getElementById("historyList");if(!(!e||!i))try{const o=await this._fetchHistorySessions(12);if(o.length===0){e.style.display="none";return}i.replaceChildren();for(const n of o){const u=n.sizeBytes<1024?`${n.sizeBytes}B`:n.sizeBytes<1048576?`${(n.sizeBytes/1024).toFixed(0)}K`:`${(n.sizeBytes/1048576).toFixed(1)}M`,d=new Date(n.lastModified),r=d.toLocaleDateString("en",{month:"short",day:"numeric"})+" "+d.toLocaleTimeString("en",{hour:"2-digit",minute:"2-digit",hour12:!1}),a=n.workingDir.replace(/^\/home\/[^/]+\//,"~/"),s=document.createElement("div");s.className="history-item",s.title=n.workingDir,s.addEventListener("click",()=>this.resumeHistorySession(n.sessionId,n.workingDir));const t=document.createElement("span");t.className="history-item-dir",t.textContent=a;const c=document.createElement("span");c.className="history-item-meta",c.textContent=r;const l=document.createElement("span");l.className="history-item-size",l.textContent=u,s.append(t,c,l),i.appendChild(s)}e.style.display=""}catch(o){console.error("[loadHistorySessions]",o),e.style.display="none"}},async resumeHistorySession(e,i){document.getElementById("runModeMenu")?.classList.remove("active");try{this.terminal.clear(),this.terminal.writeln(`\x1B[1;32m Resuming conversation ${e.slice(0,8)}...\x1B[0m`);const o=i.split("/").pop()||"session";let n=1;for(const[,s]of this.sessions){const t=s.name&&s.name.match(/^w(\d+)-/);if(t){const c=parseInt(t[1]);c>=n&&(n=c+1)}}const u=`w${n}-${o}`,r=await(await fetch("/api/sessions",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({workingDir:i,name:u,resumeSessionId:e})})).json();if(!r.success)throw new Error(r.error);const a=r.session.id;await fetch(`/api/sessions/${a}/interactive`,{method:"POST"}),this.terminal.writeln(`\x1B[90m Session ${u} ready\x1B[0m`),await this.selectSession(a),this.terminal.focus()}catch(o){this.terminal.writeln(`\x1B[1;31m Error: ${o.message}\x1B[0m`)}},isTerminalAtBottom(){if(!this.terminal)return!0;const e=this.terminal.buffer.active;return e.viewportY>=e.baseY-2},batchTerminalWrite(e){if(this._isLoadingBuffer){this._loadBufferQueue&&this._loadBufferQueue.push(e);return}if(this.writeFrameScheduled||(this._wasAtBottomBeforeWrite=this.isTerminalAtBottom()),(this.activeSessionId?this.sessions.get(this.activeSessionId):null)?.flickerFilterEnabled??!1){if(e.includes("\x1B[2J")||e.includes("\x1B[H\x1B[J")||e.includes("\x1B[H")&&e.includes("\x1B[?25l")){this.flickerFilterActive=!0,this.flickerFilterBuffer+=e,this.flickerFilterTimeout&&clearTimeout(this.flickerFilterTimeout),this.flickerFilterTimeout=setTimeout(()=>{this.flickerFilterTimeout=null,this.flushFlickerBuffer()},SYNC_WAIT_TIMEOUT_MS);return}if(this.flickerFilterActive){this.flickerFilterBuffer+=e;return}}this.pendingWrites.push(e),this.writeFrameScheduled||(this.writeFrameScheduled=!0,requestAnimationFrame(()=>{this.flushPendingWrites(),this.writeFrameScheduled=!1}))},flushFlickerBuffer(){this.flickerFilterBuffer&&(this.pendingWrites.push(this.flickerFilterBuffer),this.flickerFilterBuffer="",this.flickerFilterActive=!1,this.writeFrameScheduled||(this.writeFrameScheduled=!0,requestAnimationFrame(()=>{this.flushPendingWrites(),this.writeFrameScheduled=!1})))},_updateLocalEchoState(){const e=this.loadAppSettingsFromStorage(),i=this.activeSessionId?this.sessions.get(this.activeSessionId):null,n=!!((e.localEchoEnabled??MobileDetection.isTouchDevice())&&i);this._localEchoEnabled&&!n&&this._localEchoOverlay?.clear(),this._localEchoEnabled=n,this._localEchoOverlay&&i&&(i.mode==="opencode"?this._localEchoOverlay.setPrompt({type:"custom",offset:3,find:u=>{try{const d=u.buffer.active,r=d.cursorY,a=d.getLine(d.viewportY+r);if(!a)return null;const t=a.translateToString(!0).indexOf("\u2503");return t>=0?{row:r,col:t}:null}catch{return null}}}):i.mode==="shell"?(this._localEchoOverlay.clear(),this._localEchoEnabled=!1):this._localEchoOverlay.setPrompt({type:"character",char:"\u276F",offset:2}))},flushPendingWrites(){if(this.pendingWrites.length===0||!this.terminal)return;const e=performance.now(),i=this.pendingWrites.join("");this.pendingWrites=[];const o=i.length;o>16384&&_crashDiag.log(`FLUSH: ${(o/1024).toFixed(0)}KB`);const n=65536;let u=!1;o<=n?this.terminal.write(i):(this.terminal.write(i.slice(0,n)),this.pendingWrites.push(i.slice(n)),u=!0,this.writeFrameScheduled||(this.writeFrameScheduled=!0,requestAnimationFrame(()=>{this.flushPendingWrites(),this.writeFrameScheduled=!1})));const d=u?n:o,r=performance.now()-e;if((r>100||u)&&console.warn(`[CRASH-DIAG] flushPendingWrites: ${r.toFixed(0)}ms, ${(d/1024).toFixed(0)}KB written${u?", rest deferred":""} (total ${(o/1024).toFixed(0)}KB)`),this._wasAtBottomBeforeWrite&&this.terminal.scrollToBottom(),this._localEchoOverlay?.hasPending&&this._localEchoOverlay.rerender(),this._tabCompletionSessionId&&this._tabCompletionSessionId===this.activeSessionId&&this._localEchoOverlay&&!this._localEchoOverlay.pendingText){const a=this._localEchoOverlay,s=this;this.terminal.write("",()=>{if(!s._tabCompletionSessionId)return;a.resetBufferDetection();const t=a.detectBufferText();t?t===s._tabCompletionBaseText?(a.undoDetection(),s._tabCompletionRetries=(s._tabCompletionRetries||0)+1,s._tabCompletionRetries>60&&(s._tabCompletionSessionId=null,s._tabCompletionRetries=0)):(s._tabCompletionSessionId=null,s._tabCompletionRetries=0,s._tabCompletionBaseText=null,s._tabCompletionFallback&&(clearTimeout(s._tabCompletionFallback),s._tabCompletionFallback=null),a.rerender()):(s._tabCompletionRetries=(s._tabCompletionRetries||0)+1,s._tabCompletionRetries>60&&(s._tabCompletionSessionId=null,s._tabCompletionRetries=0))})}},chunkedTerminalWrite(e,i=TERMINAL_CHUNK_SIZE){return new Promise(o=>{if(!e||e.length===0){this._finishBufferLoad(),o();return}this._isLoadingBuffer=!0,this._loadBufferQueue=[];const n=e.replace(DEC_SYNC_STRIP_RE,""),u=()=>{this._finishBufferLoad(),o()};if(n.length<=i){this.terminal.write(n),u();return}let d=0;const r=performance.now();let a=0;const s=()=>{if(d>=n.length){const h=performance.now()-r;console.log(`[CRASH-DIAG] chunkedTerminalWrite complete: ${n.length} bytes in ${a} chunks, ${h.toFixed(0)}ms total`),requestAnimationFrame(u);return}const t=performance.now(),c=n.slice(d,d+i);this.terminal.write(c);const l=performance.now()-t;a++,l>50&&console.warn(`[CRASH-DIAG] chunk #${a} write took ${l.toFixed(0)}ms (${c.length} bytes at offset ${d})`),d+=i,requestAnimationFrame(s)};requestAnimationFrame(s)})},_finishBufferLoad(){const e=this._loadBufferQueue;if(this._isLoadingBuffer=!1,this._loadBufferQueue=null,e&&e.length>0)for(const i of e)this.batchTerminalWrite(i)},clearTerminal(){this.terminal.clear()},async restoreTerminalSize(){if(!this.activeSessionId){this.showToast("No active session","warning");return}const e=this.getTerminalDimensions();if(!e){this.showToast("Could not determine terminal size","error");return}try{await this.sendResize(this.activeSessionId),await fetch(`/api/sessions/${this.activeSessionId}/input`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({input:"\f"})}),this.showToast(`Terminal restored to ${e.cols}x${e.rows}`,"success")}catch(i){console.error("Failed to restore terminal size:",i),this.showToast("Failed to restore terminal size","error")}},sendPendingCtrlL(e){!this.pendingCtrlL||!this.pendingCtrlL.has(e)||(this.pendingCtrlL.delete(e),e===this.activeSessionId&&this.sendResize(e).then(()=>{fetch(`/api/sessions/${e}/input`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({input:"\f"})})}))},async copyTerminal(){try{const e=this.terminal.buffer.active;let i="";for(let o=0;o<e.length;o++){const n=e.getLine(o);n&&(i+=n.translateToString(!0)+`
2
+ `)}await navigator.clipboard.writeText(i.replace(/\n+$/,`
3
+ `)),this.showToast("Copied to clipboard","success")}catch{this.showToast("Failed to copy","error")}},increaseFontSize(){const e=this.terminal.options.fontSize||14;this.setFontSize(Math.min(e+2,24))},decreaseFontSize(){const e=this.terminal.options.fontSize||14;this.setFontSize(Math.max(e-2,10))},setFontSize(e){this.terminal.options.fontSize=e,document.getElementById("fontSizeDisplay").textContent=e,this.fitAddon.fit(),localStorage.setItem("codeman-font-size",e),this._localEchoOverlay?.refreshFont()},loadFontSize(){const e=localStorage.getItem("codeman-font-size");if(e){const i=parseInt(e,10);i>=10&&i<=24&&(this.terminal.options.fontSize=i,document.getElementById("fontSizeDisplay").textContent=i)}},getTerminalDimensions(){const o=this.fitAddon?.proposeDimensions();return o?{cols:Math.max(o.cols,40),rows:Math.max(o.rows,10)}:null},async sendResize(e){const i=this.getTerminalDimensions();if(i){if(this._wsReady&&this._wsSessionId===e)try{this._ws.send(JSON.stringify({t:"z",c:i.cols,r:i.rows}));return}catch{}await fetch(`/api/sessions/${e}/resize`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)})}},async sendInput(e){this.activeSessionId&&await fetch(`/api/sessions/${this.activeSessionId}/input`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({input:e,useMux:!0})})},toggleDirInput(){const e=document.querySelector("#dirDisplay").parentElement,i=document.getElementById("dirInput");i.classList.contains("hidden")&&(i.classList.remove("hidden"),e.style.display="none",i.focus())},hideDirInput(){const e=document.querySelector("#dirDisplay").parentElement,i=document.getElementById("dirInput");setTimeout(()=>{i.classList.add("hidden"),e.style.display="";const o=i.value.trim();document.getElementById("dirDisplay").textContent=o||"No directory"},100)}});
Binary file
Binary file
@@ -19,7 +19,7 @@
19
19
  *
20
20
  * @dependency mobile-handlers.js (MobileDetection for device checks)
21
21
  * @dependency app.js (uses global `app` for sendInput, showToast, terminal focus)
22
- * @loadorder 3 of 9 — loaded after mobile-handlers.js, before notification-manager.js
22
+ * @loadorder 3 of 15 — loaded after mobile-handlers.js, before notification-manager.js
23
23
  */
24
24
 
25
25
  // Codeman — Voice input with Deepgram Nova-3 and Web Speech API fallback
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "aicodeman",
3
- "version": "0.4.1",
3
+ "version": "0.4.2",
4
4
  "description": "The missing control plane for AI coding agents - run 20 autonomous agents with real-time monitoring and session persistence",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",