aicodeman 0.2.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +403 -0
- package/dist/ai-checker-base.d.ts +175 -0
- package/dist/ai-checker-base.d.ts.map +1 -0
- package/dist/ai-checker-base.js +424 -0
- package/dist/ai-checker-base.js.map +1 -0
- package/dist/ai-idle-checker.d.ts +53 -0
- package/dist/ai-idle-checker.d.ts.map +1 -0
- package/dist/ai-idle-checker.js +141 -0
- package/dist/ai-idle-checker.js.map +1 -0
- package/dist/ai-plan-checker.d.ts +52 -0
- package/dist/ai-plan-checker.d.ts.map +1 -0
- package/dist/ai-plan-checker.js +103 -0
- package/dist/ai-plan-checker.js.map +1 -0
- package/dist/bash-tool-parser.d.ts +191 -0
- package/dist/bash-tool-parser.d.ts.map +1 -0
- package/dist/bash-tool-parser.js +598 -0
- package/dist/bash-tool-parser.js.map +1 -0
- package/dist/cli.d.ts +12 -0
- package/dist/cli.d.ts.map +1 -0
- package/dist/cli.js +460 -0
- package/dist/cli.js.map +1 -0
- package/dist/config/buffer-limits.d.ts +59 -0
- package/dist/config/buffer-limits.d.ts.map +1 -0
- package/dist/config/buffer-limits.js +74 -0
- package/dist/config/buffer-limits.js.map +1 -0
- package/dist/config/map-limits.d.ts +40 -0
- package/dist/config/map-limits.d.ts.map +1 -0
- package/dist/config/map-limits.js +52 -0
- package/dist/config/map-limits.js.map +1 -0
- package/dist/file-stream-manager.d.ts +148 -0
- package/dist/file-stream-manager.d.ts.map +1 -0
- package/dist/file-stream-manager.js +351 -0
- package/dist/file-stream-manager.js.map +1 -0
- package/dist/hooks-config.d.ts +31 -0
- package/dist/hooks-config.d.ts.map +1 -0
- package/dist/hooks-config.js +115 -0
- package/dist/hooks-config.js.map +1 -0
- package/dist/image-watcher.d.ts +86 -0
- package/dist/image-watcher.d.ts.map +1 -0
- package/dist/image-watcher.js +275 -0
- package/dist/image-watcher.js.map +1 -0
- package/dist/index.d.ts +11 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +54 -0
- package/dist/index.js.map +1 -0
- package/dist/mux-factory.d.ts +13 -0
- package/dist/mux-factory.d.ts.map +1 -0
- package/dist/mux-factory.js +19 -0
- package/dist/mux-factory.js.map +1 -0
- package/dist/mux-interface.d.ts +145 -0
- package/dist/mux-interface.d.ts.map +1 -0
- package/dist/mux-interface.js +9 -0
- package/dist/mux-interface.js.map +1 -0
- package/dist/plan-orchestrator.d.ts +123 -0
- package/dist/plan-orchestrator.d.ts.map +1 -0
- package/dist/plan-orchestrator.js +500 -0
- package/dist/plan-orchestrator.js.map +1 -0
- package/dist/prompts/index.d.ts +9 -0
- package/dist/prompts/index.d.ts.map +1 -0
- package/dist/prompts/index.js +9 -0
- package/dist/prompts/index.js.map +1 -0
- package/dist/prompts/planner.d.ts +14 -0
- package/dist/prompts/planner.d.ts.map +1 -0
- package/dist/prompts/planner.js +83 -0
- package/dist/prompts/planner.js.map +1 -0
- package/dist/prompts/research-agent.d.ts +10 -0
- package/dist/prompts/research-agent.d.ts.map +1 -0
- package/dist/prompts/research-agent.js +143 -0
- package/dist/prompts/research-agent.js.map +1 -0
- package/dist/push-store.d.ts +41 -0
- package/dist/push-store.d.ts.map +1 -0
- package/dist/push-store.js +168 -0
- package/dist/push-store.js.map +1 -0
- package/dist/ralph-config.d.ts +67 -0
- package/dist/ralph-config.d.ts.map +1 -0
- package/dist/ralph-config.js +134 -0
- package/dist/ralph-config.js.map +1 -0
- package/dist/ralph-loop.d.ts +124 -0
- package/dist/ralph-loop.d.ts.map +1 -0
- package/dist/ralph-loop.js +418 -0
- package/dist/ralph-loop.js.map +1 -0
- package/dist/ralph-tracker.d.ts +1081 -0
- package/dist/ralph-tracker.d.ts.map +1 -0
- package/dist/ralph-tracker.js +3343 -0
- package/dist/ralph-tracker.js.map +1 -0
- package/dist/respawn-controller.d.ts +1182 -0
- package/dist/respawn-controller.d.ts.map +1 -0
- package/dist/respawn-controller.js +2754 -0
- package/dist/respawn-controller.js.map +1 -0
- package/dist/run-summary.d.ts +123 -0
- package/dist/run-summary.d.ts.map +1 -0
- package/dist/run-summary.js +325 -0
- package/dist/run-summary.js.map +1 -0
- package/dist/session-lifecycle-log.d.ts +36 -0
- package/dist/session-lifecycle-log.d.ts.map +1 -0
- package/dist/session-lifecycle-log.js +101 -0
- package/dist/session-lifecycle-log.js.map +1 -0
- package/dist/session-manager.d.ts +97 -0
- package/dist/session-manager.d.ts.map +1 -0
- package/dist/session-manager.js +224 -0
- package/dist/session-manager.js.map +1 -0
- package/dist/session.d.ts +686 -0
- package/dist/session.d.ts.map +1 -0
- package/dist/session.js +2025 -0
- package/dist/session.js.map +1 -0
- package/dist/state-store.d.ts +189 -0
- package/dist/state-store.d.ts.map +1 -0
- package/dist/state-store.js +730 -0
- package/dist/state-store.js.map +1 -0
- package/dist/subagent-watcher.d.ts +345 -0
- package/dist/subagent-watcher.d.ts.map +1 -0
- package/dist/subagent-watcher.js +1469 -0
- package/dist/subagent-watcher.js.map +1 -0
- package/dist/task-queue.d.ts +108 -0
- package/dist/task-queue.d.ts.map +1 -0
- package/dist/task-queue.js +235 -0
- package/dist/task-queue.js.map +1 -0
- package/dist/task-tracker.d.ts +306 -0
- package/dist/task-tracker.d.ts.map +1 -0
- package/dist/task-tracker.js +488 -0
- package/dist/task-tracker.js.map +1 -0
- package/dist/task.d.ts +73 -0
- package/dist/task.d.ts.map +1 -0
- package/dist/task.js +177 -0
- package/dist/task.js.map +1 -0
- package/dist/team-watcher.d.ts +53 -0
- package/dist/team-watcher.d.ts.map +1 -0
- package/dist/team-watcher.js +313 -0
- package/dist/team-watcher.js.map +1 -0
- package/dist/templates/case-template.md +461 -0
- package/dist/templates/claude-md.d.ts +26 -0
- package/dist/templates/claude-md.d.ts.map +1 -0
- package/dist/templates/claude-md.js +74 -0
- package/dist/templates/claude-md.js.map +1 -0
- package/dist/tmux-manager.d.ts +181 -0
- package/dist/tmux-manager.d.ts.map +1 -0
- package/dist/tmux-manager.js +1405 -0
- package/dist/tmux-manager.js.map +1 -0
- package/dist/transcript-watcher.d.ts +110 -0
- package/dist/transcript-watcher.d.ts.map +1 -0
- package/dist/transcript-watcher.js +338 -0
- package/dist/transcript-watcher.js.map +1 -0
- package/dist/tunnel-manager.d.ts +54 -0
- package/dist/tunnel-manager.d.ts.map +1 -0
- package/dist/tunnel-manager.js +251 -0
- package/dist/tunnel-manager.js.map +1 -0
- package/dist/types.d.ts +1139 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +215 -0
- package/dist/types.js.map +1 -0
- package/dist/utils/buffer-accumulator.d.ts +111 -0
- package/dist/utils/buffer-accumulator.d.ts.map +1 -0
- package/dist/utils/buffer-accumulator.js +172 -0
- package/dist/utils/buffer-accumulator.js.map +1 -0
- package/dist/utils/claude-cli-resolver.d.ts +26 -0
- package/dist/utils/claude-cli-resolver.d.ts.map +1 -0
- package/dist/utils/claude-cli-resolver.js +78 -0
- package/dist/utils/claude-cli-resolver.js.map +1 -0
- package/dist/utils/cleanup-manager.d.ts +165 -0
- package/dist/utils/cleanup-manager.d.ts.map +1 -0
- package/dist/utils/cleanup-manager.js +274 -0
- package/dist/utils/cleanup-manager.js.map +1 -0
- package/dist/utils/index.d.ts +19 -0
- package/dist/utils/index.d.ts.map +1 -0
- package/dist/utils/index.js +19 -0
- package/dist/utils/index.js.map +1 -0
- package/dist/utils/lru-map.d.ts +140 -0
- package/dist/utils/lru-map.d.ts.map +1 -0
- package/dist/utils/lru-map.js +234 -0
- package/dist/utils/lru-map.js.map +1 -0
- package/dist/utils/nice-wrapper.d.ts +13 -0
- package/dist/utils/nice-wrapper.d.ts.map +1 -0
- package/dist/utils/nice-wrapper.js +17 -0
- package/dist/utils/nice-wrapper.js.map +1 -0
- package/dist/utils/opencode-cli-resolver.d.ts +21 -0
- package/dist/utils/opencode-cli-resolver.d.ts.map +1 -0
- package/dist/utils/opencode-cli-resolver.js +67 -0
- package/dist/utils/opencode-cli-resolver.js.map +1 -0
- package/dist/utils/regex-patterns.d.ts +64 -0
- package/dist/utils/regex-patterns.d.ts.map +1 -0
- package/dist/utils/regex-patterns.js +74 -0
- package/dist/utils/regex-patterns.js.map +1 -0
- package/dist/utils/stale-expiration-map.d.ts +159 -0
- package/dist/utils/stale-expiration-map.d.ts.map +1 -0
- package/dist/utils/stale-expiration-map.js +277 -0
- package/dist/utils/stale-expiration-map.js.map +1 -0
- package/dist/utils/string-similarity.d.ts +108 -0
- package/dist/utils/string-similarity.d.ts.map +1 -0
- package/dist/utils/string-similarity.js +189 -0
- package/dist/utils/string-similarity.js.map +1 -0
- package/dist/utils/token-validation.d.ts +39 -0
- package/dist/utils/token-validation.d.ts.map +1 -0
- package/dist/utils/token-validation.js +59 -0
- package/dist/utils/token-validation.js.map +1 -0
- package/dist/utils/type-safety.d.ts +33 -0
- package/dist/utils/type-safety.d.ts.map +1 -0
- package/dist/utils/type-safety.js +35 -0
- package/dist/utils/type-safety.js.map +1 -0
- package/dist/web/public/app.js +491 -0
- package/dist/web/public/app.js.br +0 -0
- package/dist/web/public/app.js.gz +0 -0
- package/dist/web/public/index.html +1675 -0
- package/dist/web/public/index.html.br +0 -0
- package/dist/web/public/index.html.gz +0 -0
- package/dist/web/public/manifest.json +8 -0
- package/dist/web/public/mobile.css +1 -0
- package/dist/web/public/mobile.css.br +0 -0
- package/dist/web/public/mobile.css.gz +0 -0
- package/dist/web/public/ralph-wizard.js +1037 -0
- package/dist/web/public/ralph-wizard.js.br +0 -0
- package/dist/web/public/ralph-wizard.js.gz +0 -0
- package/dist/web/public/styles.css +1 -0
- package/dist/web/public/styles.css.br +0 -0
- package/dist/web/public/styles.css.gz +0 -0
- package/dist/web/public/sw.js +67 -0
- package/dist/web/public/sw.js.br +0 -0
- package/dist/web/public/sw.js.gz +0 -0
- package/dist/web/public/upload.html +155 -0
- package/dist/web/public/upload.html.br +0 -0
- package/dist/web/public/upload.html.gz +0 -0
- package/dist/web/public/vendor/xterm-addon-fit.min.js +1 -0
- package/dist/web/public/vendor/xterm-addon-fit.min.js.br +0 -0
- package/dist/web/public/vendor/xterm-addon-fit.min.js.gz +0 -0
- package/dist/web/public/vendor/xterm-addon-unicode11.min.js +1 -0
- package/dist/web/public/vendor/xterm-addon-unicode11.min.js.br +0 -0
- package/dist/web/public/vendor/xterm-addon-unicode11.min.js.gz +0 -0
- package/dist/web/public/vendor/xterm-addon-webgl.min.js +2 -0
- package/dist/web/public/vendor/xterm-addon-webgl.min.js.br +0 -0
- package/dist/web/public/vendor/xterm-addon-webgl.min.js.gz +0 -0
- package/dist/web/public/vendor/xterm.css +209 -0
- package/dist/web/public/vendor/xterm.css.br +0 -0
- package/dist/web/public/vendor/xterm.css.gz +0 -0
- package/dist/web/public/vendor/xterm.min.js +9 -0
- package/dist/web/public/vendor/xterm.min.js.br +0 -0
- package/dist/web/public/vendor/xterm.min.js.gz +0 -0
- package/dist/web/schemas.d.ts +479 -0
- package/dist/web/schemas.d.ts.map +1 -0
- package/dist/web/schemas.js +448 -0
- package/dist/web/schemas.js.map +1 -0
- package/dist/web/server.d.ts +207 -0
- package/dist/web/server.d.ts.map +1 -0
- package/dist/web/server.js +5784 -0
- package/dist/web/server.js.map +1 -0
- package/package.json +110 -0
- package/scripts/postinstall.js +390 -0
|
@@ -0,0 +1,491 @@
|
|
|
1
|
+
"use strict";function urlBase64ToUint8Array(d){const e="=".repeat((4-d.length%4)%4),t=(d+e).replace(/-/g,"+").replace(/_/g,"/"),s=atob(t),n=new Uint8Array(s.length);for(let i=0;i<s.length;++i)n[i]=s.charCodeAt(i);return n}const DEFAULT_SCROLLBACK=5e3,STUCK_THRESHOLD_DEFAULT_MS=6e5,GROUPING_TIMEOUT_MS=5e3,NOTIFICATION_LIST_CAP=100,TITLE_FLASH_INTERVAL_MS=1500,BROWSER_NOTIF_RATE_LIMIT_MS=3e3,AUTO_CLOSE_NOTIFICATION_MS=8e3,THROTTLE_DELAY_MS=100,TERMINAL_CHUNK_SIZE=128*1024,TERMINAL_TAIL_SIZE=256*1024,SYNC_WAIT_TIMEOUT_MS=50,STATS_POLLING_INTERVAL_MS=2e3,ZINDEX_SUBAGENT_BASE=1e3,ZINDEX_PLAN_SUBAGENT_BASE=1100,ZINDEX_LOG_VIEWER_BASE=2e3,ZINDEX_IMAGE_POPUP_BASE=3e3,WINDOW_INITIAL_TOP_PX=120,WINDOW_CASCADE_OFFSET_PX=30,WINDOW_MIN_WIDTH_PX=200,WINDOW_MIN_HEIGHT_PX=200,WINDOW_DEFAULT_WIDTH_PX=300,_hasScheduler=typeof globalThis.scheduler?.postTask=="function";function scheduleBackground(d){_hasScheduler?scheduler.postTask(d,{priority:"background"}):requestAnimationFrame(d)}const DEC_SYNC_START="\x1B[?2026h",DEC_SYNC_END="\x1B[?2026l",DEC_SYNC_STRIP_RE=/\x1b\[\?2026[hl]/g,BUILTIN_RESPAWN_PRESETS=[{id:"solo-work",name:"Solo",description:"Claude working alone \u2014 fast respawn cycles with context reset",config:{idleTimeoutMs:3e3,updatePrompt:"summarize your progress so far before the context reset.",interStepDelayMs:2e3,sendClear:!0,sendInit:!0,kickstartPrompt:"continue working. Pick up where you left off based on the context above.",autoAcceptPrompts:!0},durationMinutes:60,builtIn:!0,createdAt:0},{id:"subagent-workflow",name:"Subagents",description:"Lead session with Task tool subagents \u2014 longer idle tolerance",config:{idleTimeoutMs:45e3,updatePrompt:"check on your running subagents and summarize their results before the context reset. If all subagents have finished, note what was completed and what remains.",interStepDelayMs:3e3,sendClear:!0,sendInit:!0,kickstartPrompt:"check on your running subagents and continue coordinating their work. If all subagents have finished, summarize their results and proceed with the next step.",autoAcceptPrompts:!0},durationMinutes:240,builtIn:!0,createdAt:0},{id:"team-lead",name:"Team",description:"Leading an agent team via TeamCreate \u2014 tolerates long silences",config:{idleTimeoutMs:9e4,updatePrompt:"review the task list and teammate progress. Summarize the current state before the context reset.",interStepDelayMs:5e3,sendClear:!0,sendInit:!0,kickstartPrompt:"check on your teammates by reviewing the task list and any messages in your inbox. Assign new tasks if teammates are idle, or continue coordinating the team effort.",autoAcceptPrompts:!0},durationMinutes:480,builtIn:!0,createdAt:0},{id:"ralph-todo",name:"Ralph/Todo",description:"Ralph Loop task list \u2014 works through todos with progress tracking",config:{idleTimeoutMs:8e3,updatePrompt:"update CLAUDE.md with discoveries and progress notes, mark completed tasks in @fix_plan.md, write a brief summary so the next cycle can continue seamlessly.",interStepDelayMs:3e3,sendClear:!0,sendInit:!0,kickstartPrompt:"read @fix_plan.md for task status, continue on the next uncompleted task. When ALL tasks are complete, output <promise>COMPLETE</promise>.",autoAcceptPrompts:!0},durationMinutes:480,builtIn:!0,createdAt:0},{id:"overnight-autonomous",name:"Overnight",description:"Unattended overnight runs with full context reset between cycles",config:{idleTimeoutMs:1e4,updatePrompt:"summarize what you accomplished so far and write key progress notes to CLAUDE.md so the next cycle can pick up where you left off.",interStepDelayMs:3e3,sendClear:!0,sendInit:!0,kickstartPrompt:"continue working on the task. Pick up where you left off based on the context above.",autoAcceptPrompts:!0},durationMinutes:480,builtIn:!0,createdAt:0}],MobileDetection={isTouchDevice(){return"ontouchstart"in window||navigator.maxTouchPoints>0||window.matchMedia&&window.matchMedia("(pointer: coarse)").matches},isIOS(){return/iPad|iPhone|iPod/.test(navigator.userAgent)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1},isSafari(){return/^((?!chrome|android).)*safari/i.test(navigator.userAgent)},isSmallScreen(){return window.innerWidth<430},isMediumScreen(){return window.innerWidth>=430&&window.innerWidth<768},getDeviceType(){const d=window.innerWidth;return d<430?"mobile":d<768?"tablet":"desktop"},updateBodyClass(){const d=document.body,e=this.getDeviceType(),t=this.isTouchDevice();d.classList.remove("device-mobile","device-tablet","device-desktop","touch-device","ios-device","safari-browser"),d.classList.add(`device-${e}`),t&&d.classList.add("touch-device"),this.isIOS()&&d.classList.add("ios-device"),this.isSafari()&&d.classList.add("safari-browser")},init(){this.updateBodyClass();let d;this._resizeHandler=()=>{clearTimeout(d),d=setTimeout(()=>this.updateBodyClass(),100)},window.addEventListener("resize",this._resizeHandler),this.isIOS()&&(this._gestureStartHandler=e=>e.preventDefault(),this._gestureChangeHandler=e=>e.preventDefault(),document.addEventListener("gesturestart",this._gestureStartHandler),document.addEventListener("gesturechange",this._gestureChangeHandler))},cleanup(){this._resizeHandler&&(window.removeEventListener("resize",this._resizeHandler),this._resizeHandler=null),this._gestureStartHandler&&(document.removeEventListener("gesturestart",this._gestureStartHandler),document.removeEventListener("gesturechange",this._gestureChangeHandler),this._gestureStartHandler=null,this._gestureChangeHandler=null)}};function getEventCoords(d){return d.touches&&d.touches.length>0?{clientX:d.touches[0].clientX,clientY:d.touches[0].clientY}:d.changedTouches&&d.changedTouches.length>0?{clientX:d.changedTouches[0].clientX,clientY:d.changedTouches[0].clientY}:{clientX:d.clientX,clientY:d.clientY}}const KeyboardHandler={lastViewportHeight:0,keyboardVisible:!1,initialViewportHeight:0,init(){MobileDetection.isTouchDevice()&&(this.initialViewportHeight=window.visualViewport?.height||window.innerHeight,this.lastViewportHeight=this.initialViewportHeight,this._focusinHandler=d=>{const e=d.target;this.isInputElement(e)&&setTimeout(()=>{this.scrollInputIntoView(e)},400)},document.addEventListener("focusin",this._focusinHandler),window.visualViewport&&(this._viewportResizeHandler=()=>{this.handleViewportResize()},this._viewportScrollHandler=()=>{this.updateLayoutForKeyboard()},window.visualViewport.addEventListener("resize",this._viewportResizeHandler),window.visualViewport.addEventListener("scroll",this._viewportScrollHandler)))},cleanup(){this._focusinHandler&&(document.removeEventListener("focusin",this._focusinHandler),this._focusinHandler=null),this._viewportResizeHandler&&window.visualViewport&&(window.visualViewport.removeEventListener("resize",this._viewportResizeHandler),this._viewportResizeHandler=null),this._viewportScrollHandler&&window.visualViewport&&(window.visualViewport.removeEventListener("scroll",this._viewportScrollHandler),this._viewportScrollHandler=null)},handleViewportResize(){const d=window.visualViewport?.height||window.innerHeight,e=this.initialViewportHeight-d;e>150&&!this.keyboardVisible?(this.keyboardVisible=!0,document.body.classList.add("keyboard-visible"),this.onKeyboardShow()):e<100&&this.keyboardVisible&&(this.keyboardVisible=!1,document.body.classList.remove("keyboard-visible"),this.onKeyboardHide()),this.keyboardVisible||(this.initialViewportHeight=d),this.updateLayoutForKeyboard(),this.lastViewportHeight=d},updateLayoutForKeyboard(){if(!window.visualViewport)return;if(!MobileDetection.isSmallScreen()&&!MobileDetection.isMediumScreen()){this.resetLayout();return}const d=document.querySelector(".toolbar"),e=document.querySelector(".keyboard-accessory-bar"),t=document.querySelector(".main");if(this.keyboardVisible){const s=window.innerHeight,n=window.visualViewport.offsetTop+window.visualViewport.height,i=s-n;if(i<=0){this.keyboardVisible=!1,document.body.classList.remove("keyboard-visible"),this.onKeyboardHide();return}d&&(d.style.transform=`translateY(${-i}px)`),e&&(e.style.transform=`translateY(${-i}px)`),t&&(t.style.paddingBottom=`${i+94}px`)}else this.resetLayout()},resetLayout(){const d=document.querySelector(".toolbar"),e=document.querySelector(".keyboard-accessory-bar"),t=document.querySelector(".main");d&&(d.style.transform=""),e&&(e.style.transform=""),t&&(t.style.paddingBottom="")},onKeyboardShow(){typeof KeyboardAccessoryBar<"u"&&KeyboardAccessoryBar.show(),setTimeout(()=>{if(typeof app<"u"&&app.terminal){if(app.fitAddon)try{app.fitAddon.fit()}catch{}app.terminal.scrollToBottom(),this._sendTerminalResize()}},150),typeof app<"u"&&app.relayoutMobileSubagentWindows()},onKeyboardHide(){typeof KeyboardAccessoryBar<"u"&&KeyboardAccessoryBar.hide(),this.resetLayout(),setTimeout(()=>{if(typeof app<"u"&&app.fitAddon){try{app.fitAddon.fit()}catch{}app.terminal&&app.terminal.scrollToBottom(),this._sendTerminalResize()}},100),typeof app<"u"&&app.relayoutMobileSubagentWindows()},_sendTerminalResize(){if(!(typeof app>"u"||!app.activeSessionId||!app.fitAddon))try{const d=app.fitAddon.proposeDimensions();if(d){const e=Math.max(d.cols,40),t=Math.max(d.rows,10);app._lastResizeDims={cols:e,rows:t},fetch(`/api/sessions/${app.activeSessionId}/resize`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cols:e,rows:t})}).catch(()=>{})}}catch{}},isInputElement(d){if(!d||d.closest(".xterm")||d.closest(".terminal-container"))return!1;const e=d.tagName?.toLowerCase();if(e==="input"){const t=d.type?.toLowerCase();if(t==="checkbox"||t==="radio"||t==="range"||t==="file")return!1}return e==="input"||e==="textarea"||d.isContentEditable},scrollInputIntoView(d){if(document.activeElement!==d)return;const t=d.closest(".modal.active")?.querySelector(".modal-body");if(t){const s=d.getBoundingClientRect(),n=t.getBoundingClientRect();if(s.top>n.top+n.height*.4){const i=s.top-n.top-100;t.scrollBy({top:i,behavior:"smooth"})}}else d.scrollIntoView({block:"center",behavior:"smooth"})}},SwipeHandler={startX:0,startY:0,startTime:0,minSwipeDistance:80,maxSwipeTime:300,maxVerticalDrift:100,init(){if(!MobileDetection.isTouchDevice())return;const d=document.querySelector(".main");d&&(d.addEventListener("touchstart",e=>this.onTouchStart(e),{passive:!0}),d.addEventListener("touchend",e=>this.onTouchEnd(e),{passive:!0}))},onTouchStart(d){!d.touches||d.touches.length!==1||(this.startX=d.touches[0].clientX,this.startY=d.touches[0].clientY,this.startTime=Date.now())},onTouchEnd(d){if(!d.changedTouches||d.changedTouches.length!==1)return;const e=d.changedTouches[0].clientX,t=d.changedTouches[0].clientY,s=Date.now()-this.startTime,n=e-this.startX,i=Math.abs(t-this.startY);s>this.maxSwipeTime||i>this.maxVerticalDrift||Math.abs(n)<this.minSwipeDistance||(n>0?typeof app<"u"&&app.prevSession():typeof app<"u"&&app.nextSession())}},DeepgramProvider={_ws:null,_mediaRecorder:null,_stream:null,_silenceTimeout:null,_keepAliveInterval:null,_onResult:null,_onError:null,_onEnd:null,async start(d){this._onResult=d.onResult,this._onError=d.onError,this._onEnd=d.onEnd;try{this._stream=await navigator.mediaDevices.getUserMedia({audio:{noiseSuppression:!0,echoCancellation:!0,autoGainControl:!0}})}catch(i){const o=i.name==="NotAllowedError"?"Microphone access denied. Check browser settings.":"Microphone error: "+i.message;this._onError?.(o),this._cleanup();return}d.onStream?.(this._stream);const e=["audio/webm;codecs=opus","audio/webm","audio/mp4"];this._selectedMime=null;for(const i of e)if(typeof MediaRecorder<"u"&&MediaRecorder.isTypeSupported(i)){this._selectedMime=i;break}const t=new URLSearchParams({model:"nova-3",smart_format:"false",punctuate:"false",interim_results:"true",utterance_end_ms:"1500",vad_events:"true"});if(d.language&&d.language!=="multi"?t.set("language",d.language):d.language==="multi"&&t.set("detect_language","true"),d.keyterms?.length)for(const i of d.keyterms){const o=i.trim();o&&t.append("keyterm",o+":2")}const s=(d.apiKey||"").trim();if(!s){this._onError?.("No Deepgram API key configured. Add one in Settings > Voice."),this._cleanup();return}const n=`wss://api.deepgram.com/v1/listen?${t}`;try{this._ws=new WebSocket(n,["token",s])}catch(i){this._onError?.("Failed to connect to Deepgram: "+i.message),this._cleanup();return}this._ws.onopen=()=>{this._keepAliveInterval=setInterval(()=>{if(this._ws?.readyState===WebSocket.OPEN)try{this._ws.send(JSON.stringify({type:"KeepAlive"}))}catch{}},8e3),this._startRecording()},this._ws.onmessage=i=>{try{const o=JSON.parse(i.data);if(o.type==="Results"&&o.channel?.alternatives?.[0]){const a=o.channel.alternatives[0].transcript||"";if(a){const r=o.is_final===!0;this._onResult?.(a,r),this._resetSilenceTimeout()}}}catch{}},this._ws.onerror=()=>{},this._ws.onclose=i=>{clearInterval(this._keepAliveInterval),this._keepAliveInterval=null,i.code===1008?this._onError?.("Authentication failed. Check your Deepgram API key in Settings > Voice."):i.code===1006?this._onError?.("Deepgram connection failed (1006). Check your API key is valid and has credits in Settings > Voice."):i.code!==1e3&&this._onError?.("Deepgram connection closed: "+(i.reason||`code ${i.code}`)),this._stopRecording(),this._onEnd?.()}},_startRecording(){if(!this._stream||!this._ws||this._ws.readyState!==WebSocket.OPEN)return;const d=this._selectedMime?{mimeType:this._selectedMime}:{};try{this._mediaRecorder=new MediaRecorder(this._stream,d)}catch(e){this._onError?.("MediaRecorder failed: "+e.message),this._cleanup();return}this._mediaRecorder.ondataavailable=e=>{e.data.size>0&&this._ws?.readyState===WebSocket.OPEN&&this._ws.send(e.data)},this._mediaRecorder.start(250),this._resetSilenceTimeout()},_stopRecording(){if(this._mediaRecorder&&this._mediaRecorder.state!=="inactive")try{this._mediaRecorder.stop()}catch{}this._stream&&this._stream.getTracks().forEach(d=>d.stop())},_resetSilenceTimeout(){clearTimeout(this._silenceTimeout),this._silenceTimeout=setTimeout(()=>{this.stop()},3e3)},stop(){if(clearTimeout(this._silenceTimeout),this._silenceTimeout=null,clearInterval(this._keepAliveInterval),this._keepAliveInterval=null,this._stopRecording(),this._ws){if(this._ws.onclose=null,this._ws.onmessage=null,this._ws.onerror=null,this._ws.readyState===WebSocket.OPEN)try{this._ws.close(1e3)}catch{}this._ws=null}const d=this._onEnd;this._onResult=null,this._onError=null,this._onEnd=null,d?.()},_cleanup(){this.stop(),this._mediaRecorder=null,this._stream=null,this._selectedMime=null}},VoiceInput={recognition:null,isRecording:!1,supported:!1,silenceTimeout:null,previewEl:null,_lastTranscript:"",_stabilityTimer:null,_accumulatedFinal:"",_activeProvider:null,_recordingStartedAt:0,_retryCount:0,_hasReceivedResult:!1,_durationInterval:null,_analyser:null,_analyserSource:null,_audioContext:null,_levelAnimFrame:null,init(){this._initRecognition(),this._showButtons()},_getDeepgramConfig(){try{return JSON.parse(localStorage.getItem("codeman-voice-settings")||"{}")}catch{return{}}},_saveDeepgramConfig(d){localStorage.setItem("codeman-voice-settings",JSON.stringify(d))},_shouldUseDeepgram(){const d=this._getDeepgramConfig();return!!(d.apiKey&&d.apiKey.trim())},getActiveProviderName(){return this._shouldUseDeepgram()?"Deepgram Nova-3":this.supported?"Web Speech API":"None"},_initRecognition(){const d=window.SpeechRecognition||window.webkitSpeechRecognition;this.supported=!!d,this.supported&&(this.recognition=new d,this.recognition.continuous=!0,this.recognition.interimResults=!0,this.recognition.lang="en-US",this.recognition.maxAlternatives=1,this.recognition.onresult=e=>this._onWebSpeechResult(e),this.recognition.onerror=e=>this._onWebSpeechError(e),this.recognition.onend=()=>this._onWebSpeechEnd())},toggle(){this.isRecording?this.stop():this.start()},start(){if(!this.isRecording){if(!app.activeSessionId){app.showToast("No active session","warning");return}this._retryCount=0,this._shouldUseDeepgram()?this._startDeepgram():this._startWebSpeech()}},_startDeepgram(){const d=this._getDeepgramConfig();this.isRecording=!0,this._activeProvider="deepgram",this._accumulatedFinal="",this._lastTranscript="",this._hasReceivedResult=!1,this._recordingStartedAt=Date.now(),this._updateButtons("recording"),this._showPreview("Listening...","deepgram"),this._startDurationTimer();const e=(d.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").split(",").map(t=>t.trim()).filter(Boolean);DeepgramProvider.start({apiKey:d.apiKey,language:d.language||"en-US",keyterms:e,onStream:t=>{this._startLevelMeter(t)},onResult:(t,s)=>{if(this.isRecording)if(this._hasReceivedResult=!0,s)this._accumulatedFinal+=t,this._hidePreview(),this._insertText(this._accumulatedFinal),this.stop();else{const n=this._accumulatedFinal+t;this._showPreview(n,"deepgram")}},onError:t=>{const s=this.isRecording;this.stop(),s&&app.showToast(t,"error")},onEnd:()=>{this.isRecording&&(this._accumulatedFinal&&this._insertText(this._accumulatedFinal),this.stop())}}),navigator.vibrate&&navigator.vibrate(50)},_startWebSpeech(){if(this.recognition||this._initRecognition(),!this.supported){this._shouldUseDeepgram()?app.showToast("Voice input not supported in this browser","warning"):app.showToast("Voice input not available. Configure Deepgram in Settings > Voice.","warning");return}this.isRecording=!0,this._activeProvider="webspeech",this._accumulatedFinal="",this._lastTranscript="",this._hasReceivedResult=!1,this._recordingStartedAt=Date.now(),this._updateButtons("recording"),this._showPreview("Listening..."),this._startDurationTimer();try{this.recognition.start()}catch(d){if(d.name!=="InvalidStateError"){this.stop(),app.showToast("Voice input failed to start: "+d.message,"error");return}}this._resetSilenceTimeout(),navigator.mediaDevices?.getUserMedia({audio:!0}).then(d=>{this.isRecording&&this._activeProvider==="webspeech"?(this._webSpeechStream=d,this._startLevelMeter(d)):d.getTracks().forEach(e=>e.stop())}).catch(()=>{}),navigator.vibrate&&navigator.vibrate(50)},stop(){if(this.isRecording){if(this.isRecording=!1,clearTimeout(this.silenceTimeout),clearTimeout(this._stabilityTimer),this.silenceTimeout=null,this._stabilityTimer=null,this._retryCount=0,this._stopDurationTimer(),this._stopLevelMeter(),this._updateButtons("idle"),this._hidePreview(),this._activeProvider==="deepgram")DeepgramProvider.stop();else if(this._activeProvider==="webspeech"){try{this.recognition?.stop()}catch{}this._webSpeechStream&&(this._webSpeechStream.getTracks().forEach(d=>d.stop()),this._webSpeechStream=null)}this._activeProvider=null,navigator.vibrate&&navigator.vibrate([30,50,30])}},_onWebSpeechResult(d){if(!this.isRecording)return;this._hasReceivedResult=!0,this._resetSilenceTimeout();let e="",t="";for(let s=d.resultIndex;s<d.results.length;s++){const n=d.results[s][0].transcript;d.results[s].isFinal?t+=n:e+=n}if(t)this._accumulatedFinal+=t,this._hidePreview(),this._insertText(this._accumulatedFinal),this.stop();else if(e){const s=this._accumulatedFinal+e;this._showPreview(s),this._iosStabilityCheck(e)}},_onWebSpeechError(d){if(this._retryCount>0&&(d.error==="aborted"||d.error==="no-speech"))return;const e=this.isRecording;if(this.stop(),!!e)switch(d.error){case"not-allowed":app.showToast("Microphone access denied. Check browser settings.","error");break;case"no-speech":break;case"network":app.showToast("Voice input requires internet connection.","error");break;case"aborted":break;default:app.showToast("Voice input error: "+d.error,"error")}},_onWebSpeechEnd(){if(!this.isRecording)return;if(Date.now()-this._recordingStartedAt<500&&!this._hasReceivedResult&&this._retryCount<2){this._retryCount++;try{this.recognition.start()}catch{this._accumulatedFinal&&this._insertText(this._accumulatedFinal),this.stop()}return}this._accumulatedFinal&&this._insertText(this._accumulatedFinal),this.stop()},_insertText(d){if(!app.activeSessionId||!d.trim())return;const e=d.trim();if((this._getDeepgramConfig().insertMode||"direct")==="compose"){const s=document.querySelector(".voice-compose-overlay .paste-textarea");s?(s.value=e,s.focus(),s.selectionStart=s.selectionEnd=e.length):this._showComposeOverlay(e)}else app._localEchoEnabled&&app._localEchoOverlay?app._localEchoOverlay.appendText(e):app.sendInput(e).catch(()=>{}),this._showVoiceSendBtn(),setTimeout(()=>{app.terminal&&app.terminal.focus()},150)},_showVoiceSendBtn(){const d=document.querySelector(".btn-settings-mobile")||document.querySelector(".btn-settings");!d||d.classList.contains("voice-send-active")||(this._hideVoiceSendBtn(),this._voiceSendGear=d,this._voiceSendOriginalHTML=d.innerHTML,this._voiceSendOriginalOnclick=d.getAttribute("onclick"),d.innerHTML='<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="9 18 15 12 9 6"/></svg>',d.classList.add("voice-send-active"),d.removeAttribute("onclick"),d.title="Send (Enter)",this._voiceSendHandler=()=>{if(app.activeSessionId){if(app._localEchoEnabled&&app._localEchoOverlay){const e=app._localEchoOverlay.pendingText||"";app._localEchoOverlay.clear(),app._localEchoOverlay.suppressBufferDetection(),e&&app.sendInput(e).catch(()=>{}),setTimeout(()=>app.sendInput("\r").catch(()=>{}),80)}else app.sendInput("\r").catch(()=>{});d.classList.add("voice-send-blink"),setTimeout(()=>this._hideVoiceSendBtn(),400)}},d.addEventListener("click",this._voiceSendHandler))},_hideVoiceSendBtn(){const d=this._voiceSendGear;d&&(d.removeEventListener("click",this._voiceSendHandler),d.classList.remove("voice-send-active","voice-send-blink"),d.innerHTML=this._voiceSendOriginalHTML||"",this._voiceSendOriginalOnclick&&d.setAttribute("onclick",this._voiceSendOriginalOnclick),d.title="App Settings",this._voiceSendGear=null,this._voiceSendHandler=null,this._voiceSendOriginalHTML=null,this._voiceSendOriginalOnclick=null)},_showComposeOverlay(d){document.querySelector(".voice-compose-overlay")?.remove();const e=document.createElement("div");e.className="voice-compose-overlay paste-overlay",e.innerHTML=`
|
|
2
|
+
<div class="paste-dialog">
|
|
3
|
+
<textarea class="paste-textarea">${d.replace(/</g,"<")}</textarea>
|
|
4
|
+
<div class="paste-actions">
|
|
5
|
+
<button class="paste-cancel">Cancel</button>
|
|
6
|
+
<button class="paste-new"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z"/><path d="M19 10v2a7 7 0 0 1-14 0v-2"/><line x1="12" y1="19" x2="12" y2="23"/><line x1="8" y1="23" x2="16" y2="23"/></svg> New</button>
|
|
7
|
+
<button class="paste-send">Send</button>
|
|
8
|
+
</div>
|
|
9
|
+
</div>
|
|
10
|
+
`;const t=e.querySelector("textarea"),s=()=>{const o=t.value.trim();e.remove(),o&&app.sendInput(o+"\r").catch(()=>{})},n=()=>e.remove(),i=()=>{t.value="",t.blur(),this.start()};e.querySelector(".paste-cancel").addEventListener("click",n),e.querySelector(".paste-new").addEventListener("click",i),e.querySelector(".paste-send").addEventListener("click",s),e.addEventListener("click",o=>{o.target===e&&n()}),document.body.appendChild(e),t.focus(),t.selectionStart=t.selectionEnd=t.value.length},_resetSilenceTimeout(){clearTimeout(this.silenceTimeout),this.silenceTimeout=setTimeout(()=>{this.isRecording&&(this._accumulatedFinal&&this._insertText(this._accumulatedFinal),this.stop())},3e3)},_iosStabilityCheck(d){d!==this._lastTranscript&&(this._lastTranscript=d,clearTimeout(this._stabilityTimer),this._stabilityTimer=setTimeout(()=>{if(this.isRecording){const e=this._accumulatedFinal+d;this._hidePreview(),this._insertText(e),this.stop()}},750))},_startDurationTimer(){this._stopDurationTimer(),this._durationInterval=setInterval(()=>{if(!this.isRecording||!this.previewEl)return;const d=Math.floor((Date.now()-this._recordingStartedAt)/1e3),e=Math.floor(d/60),t=d%60,s=e>0?`${e}:${String(t).padStart(2,"0")}`:`0:${String(t).padStart(2,"0")}`,n=this.previewEl.querySelector(".voice-timer");n&&(n.textContent=s)},1e3)},_stopDurationTimer(){this._durationInterval&&(clearInterval(this._durationInterval),this._durationInterval=null)},_startLevelMeter(d){this._stopLevelMeter();try{this._audioContext=new(window.AudioContext||window.webkitAudioContext),this._analyserSource=this._audioContext.createMediaStreamSource(d),this._analyser=this._audioContext.createAnalyser(),this._analyser.fftSize=256,this._analyserSource.connect(this._analyser),this._drawLevelMeter()}catch{}},_stopLevelMeter(){if(this._levelAnimFrame&&(cancelAnimationFrame(this._levelAnimFrame),this._levelAnimFrame=null),this._analyserSource){try{this._analyserSource.disconnect()}catch{}this._analyserSource=null}if(this._audioContext){try{this._audioContext.close()}catch{}this._audioContext=null}this._analyser=null},_drawLevelMeter(){if(!this._analyser||!this.isRecording)return;const d=new Uint8Array(this._analyser.frequencyBinCount);this._analyser.getByteFrequencyData(d);let e=0;for(let n=0;n<d.length;n++)e+=d[n]*d[n];const t=Math.sqrt(e/d.length)/255,s=this.previewEl?.querySelector(".voice-level-bars");if(s){const n=s.children;for(let i=0;i<n.length;i++){const o=(i+1)/n.length;n[i].classList.toggle("active",t>=o*.7)}}this._levelAnimFrame=requestAnimationFrame(()=>this._drawLevelMeter())},_showPreview(d,e){if(this.previewEl||(this.previewEl=document.createElement("div"),this.previewEl.className="voice-preview",this.previewEl.setAttribute("aria-live","polite"),document.body.appendChild(this.previewEl)),this.previewEl.querySelector(".voice-recording-indicator"))this._previewTextNode&&(this._previewTextNode.textContent=d||"Listening...");else{this.previewEl.textContent="";const t=document.createElement("span");t.className="voice-recording-indicator",t.innerHTML='<span class="voice-rec-dot"></span>';const s=document.createElement("span");s.className="voice-level-bars";for(let i=0;i<5;i++){const o=document.createElement("span");o.className="voice-level-bar",s.appendChild(o)}t.appendChild(s);const n=document.createElement("span");if(n.className="voice-timer",n.textContent="0:00",t.appendChild(n),this.previewEl.appendChild(t),e==="deepgram"){const i=document.createElement("span");i.className="voice-preview-badge",i.textContent="DG",this.previewEl.appendChild(i),this.previewEl.appendChild(document.createTextNode(" "))}this._previewTextNode=document.createTextNode(d||"Listening..."),this.previewEl.appendChild(this._previewTextNode)}this.previewEl.style.display=""},_hidePreview(){this.previewEl&&(this.previewEl.style.display="none",this.previewEl.textContent="")},_updateButtons(d){const e=d==="recording",t=document.getElementById("voiceInputBtn");t&&(t.classList.toggle("recording",e),t.setAttribute("aria-pressed",String(e)),t.setAttribute("aria-label",e?"Stop voice input":"Start voice input"),t.title=e?"Stop voice input (Ctrl+Shift+V)":"Voice input (Ctrl+Shift+V)");const s=document.getElementById("voiceInputBtnMobile");s&&(s.classList.toggle("recording",e),s.setAttribute("aria-pressed",String(e)),s.setAttribute("aria-label",e?"Stop voice input":"Start voice input"))},_showButtons(){const d=document.getElementById("voiceInputBtn");d&&(d.style.display="");const e=document.getElementById("voiceInputBtnMobile");e&&(e.style.display="")},cleanup(){this.isRecording&&this.stop(),this._hideVoiceSendBtn(),DeepgramProvider._cleanup(),this.recognition=null,this._activeProvider=null,this._stopDurationTimer(),this._stopLevelMeter(),this._webSpeechStream&&(this._webSpeechStream.getTracks().forEach(d=>d.stop()),this._webSpeechStream=null),this.previewEl&&(this.previewEl.remove(),this.previewEl=null),clearTimeout(this.silenceTimeout),clearTimeout(this._stabilityTimer),this.silenceTimeout=null,this._stabilityTimer=null,this._accumulatedFinal="",this._lastTranscript="",this._retryCount=0,this._hasReceivedResult=!1}},KeyboardAccessoryBar={element:null,init(){if(!MobileDetection.isTouchDevice())return;this.element=document.createElement("div"),this.element.className="keyboard-accessory-bar",this.element.innerHTML=`
|
|
11
|
+
<button class="accessory-btn accessory-btn-arrow" data-action="scroll-up" title="Arrow up">
|
|
12
|
+
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5">
|
|
13
|
+
<path d="M5 15l7-7 7 7"/>
|
|
14
|
+
</svg>
|
|
15
|
+
</button>
|
|
16
|
+
<button class="accessory-btn accessory-btn-arrow" data-action="scroll-down" title="Arrow down">
|
|
17
|
+
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5">
|
|
18
|
+
<path d="M19 9l-7 7-7-7"/>
|
|
19
|
+
</svg>
|
|
20
|
+
</button>
|
|
21
|
+
<button class="accessory-btn" data-action="init" title="/init">/init</button>
|
|
22
|
+
<button class="accessory-btn" data-action="clear" title="/clear">/clear</button>
|
|
23
|
+
<button class="accessory-btn" data-action="compact" title="/compact">/compact</button>
|
|
24
|
+
<button class="accessory-btn" data-action="paste" title="Paste from clipboard">
|
|
25
|
+
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
26
|
+
<path d="M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2"/>
|
|
27
|
+
<rect x="8" y="2" width="8" height="4" rx="1" ry="1"/>
|
|
28
|
+
</svg>
|
|
29
|
+
</button>
|
|
30
|
+
<button class="accessory-btn accessory-btn-dismiss" data-action="dismiss" title="Dismiss keyboard">
|
|
31
|
+
<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3">
|
|
32
|
+
<path d="M19 9l-7 7-7-7"/>
|
|
33
|
+
</svg>
|
|
34
|
+
</button>
|
|
35
|
+
`,this.element.addEventListener("click",e=>{const t=e.target.closest(".accessory-btn");if(!t)return;e.preventDefault(),e.stopPropagation();const s=t.dataset.action;this.handleAction(s,t),(s==="scroll-up"||s==="scroll-down"||(s==="clear"||s==="compact")&&this._confirmAction)&&typeof app<"u"&&app.terminal&&app.terminal.focus()});const d=document.querySelector(".toolbar");d&&d.parentNode&&d.parentNode.insertBefore(this.element,d)},_confirmTimer:null,_confirmAction:null,handleAction(d,e){if(!(typeof app>"u"||!app.activeSessionId))switch(d){case"scroll-up":this.sendKey("\x1B[A");break;case"scroll-down":this.sendKey("\x1B[B");break;case"init":this.sendCommand("/init");break;case"clear":case"compact":{const t=d==="clear"?"/clear":"/compact";this._confirmAction===d&&this._confirmTimer?(this.clearConfirm(),this.sendCommand(t)):this.setConfirm(d,e);break}case"paste":this.pasteFromClipboard();break;case"dismiss":document.activeElement?.blur();break}},setConfirm(d,e){this.clearConfirm(),this._confirmAction=d,e&&(e.classList.add("confirming"),e.dataset.origHtml=e.innerHTML,e.textContent="Tap again"),this._confirmTimer=setTimeout(()=>this.clearConfirm(),2e3)},clearConfirm(){if(this._confirmTimer&&(clearTimeout(this._confirmTimer),this._confirmTimer=null),this._confirmAction&&this.element){const d=this.element.querySelector(`[data-action="${this._confirmAction}"]`);d&&d.dataset.origHtml&&(d.innerHTML=d.dataset.origHtml,delete d.dataset.origHtml),d&&d.classList.remove("confirming")}this._confirmAction=null},sendCommand(d){app.activeSessionId&&(app.sendInput(d),setTimeout(()=>app.sendInput("\r"),120))},sendKey(d){app.activeSessionId&&fetch(`/api/sessions/${app.activeSessionId}/input`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({input:d})}).catch(()=>{})},pasteFromClipboard(){if(typeof app>"u"||!app.activeSessionId)return;const d=document.createElement("div");d.className="paste-overlay",d.innerHTML=`
|
|
36
|
+
<div class="paste-dialog">
|
|
37
|
+
<textarea class="paste-textarea" placeholder="Long-press here and tap Paste"></textarea>
|
|
38
|
+
<div class="paste-actions">
|
|
39
|
+
<button class="paste-cancel">Cancel</button>
|
|
40
|
+
<button class="paste-send">Send</button>
|
|
41
|
+
</div>
|
|
42
|
+
</div>
|
|
43
|
+
`;const e=d.querySelector(".paste-textarea"),t=()=>{const s=e.value;d.remove(),s&&app.sendInput(s)};d.querySelector(".paste-cancel").addEventListener("click",()=>d.remove()),d.querySelector(".paste-send").addEventListener("click",t),d.addEventListener("click",s=>{s.target===d&&d.remove()}),document.body.appendChild(d),e.focus()},show(){this.element&&this.element.classList.add("visible")},hide(){this.element&&this.element.classList.remove("visible")}};class FocusTrap{constructor(e){this.element=e,this.previouslyFocused=null,this.boundHandleKeydown=this.handleKeydown.bind(this)}activate(){this.previouslyFocused=document.activeElement,this.element.addEventListener("keydown",this.boundHandleKeydown),requestAnimationFrame(()=>{const e=this.getFocusableElements();e.length&&e[0].focus()})}deactivate(){this.element.removeEventListener("keydown",this.boundHandleKeydown),this.previouslyFocused&&typeof this.previouslyFocused.focus=="function"&&this.previouslyFocused.focus()}getFocusableElements(){const e=['button:not([disabled]):not([tabindex="-1"])','input:not([disabled]):not([tabindex="-1"])','select:not([disabled]):not([tabindex="-1"])','textarea:not([disabled]):not([tabindex="-1"])','a[href]:not([tabindex="-1"])','[tabindex]:not([tabindex="-1"]):not([disabled])'].join(", ");return[...this.element.querySelectorAll(e)].filter(t=>t.offsetParent!==null)}handleKeydown(e){if(e.key!=="Tab")return;const t=this.getFocusableElements();if(t.length===0)return;const s=t[0],n=t[t.length-1];e.shiftKey&&document.activeElement===s?(e.preventDefault(),n.focus()):!e.shiftKey&&document.activeElement===n&&(e.preventDefault(),s.focus())}}function _zl_getCellDimensions(d){const e=d;if(e.dimensions?.css?.cell)return{width:e.dimensions.css.cell.width,height:e.dimensions.css.cell.height};try{const t=e._core?._renderService?.dimensions;if(t?.css?.cell)return{width:t.css.cell.width,height:t.css.cell.height}}catch{}return null}function _zl_findPrompt(d,e){try{const t=d.buffer.active,s=t.viewportY;switch(e.type){case"character":{for(let n=d.rows-1;n>=0;n--){const i=t.getLine(s+n);if(!i)continue;const l=i.translateToString(!0).lastIndexOf(e.char);if(l>=0)return{row:n,col:l}}return null}case"regex":{const n=e.pattern,i=n.global?new RegExp(n.source,n.flags.replace("g","")):n;for(let o=d.rows-1;o>=0;o--){const l=t.getLine(s+o);if(!l)continue;const r=l.translateToString(!0).match(i);if(r)return{row:o,col:r.index??0}}return null}case"custom":return e.find(d);default:return null}}catch{return null}}function _zl_readTextAfterPrompt(d,e,t){try{const s=d.buffer.active,n=s.viewportY+e.row,i=s.getLine(n);return i?i.translateToString(!0).slice(e.col+t).trimEnd():""}catch{return""}}function _zl_charCellWidth(d,e){try{if(e?.unicode?.getStringCellWidth)return e.unicode.getStringCellWidth(d)}catch{}const t=d.codePointAt(0);return t>=4352&&(t<=4447||t>=11904&&t<=12350||t>=12352&&t<=13247||t>=13312&&t<=19903||t>=19968&&t<=42191||t>=43360&&t<=43388||t>=44032&&t<=55203||t>=63744&&t<=64255||t>=65072&&t<=65135||t>=65281&&t<=65376||t>=65504&&t<=65510||t>=126976&&t<=130047||t>=131072&&t<=196607||t>=196608&&t<=262143)?2:1}function _zl_stringCellWidth(d,e){let t=0;for(const s of d)t+=_zl_charCellWidth(s,e);return t}function _zl_renderOverlay(d,e){const{lines:t,startCol:s,totalCols:n,cellW:i,cellH:o,promptRow:l,font:a,showCursor:r,cursorColor:c,terminal:h}=e;d.style.left="0px",d.style.top=l*o+"px",d.innerHTML="";const u=n*i;for(let m=0;m<t.length;m++){const p=m===0?s*i:0,g=m===0?u-p:u,y=m*o,f=_zl_makeLine(t[m],p,y,g,o,i,a,h);d.appendChild(f)}if(r){const m=t[t.length-1],g=(t.length===1?s:0)+_zl_stringCellWidth(m,h);if(g<n){const y=document.createElement("span");y.style.cssText="position:absolute;display:inline-block",y.style.left=g*i+"px",y.style.top=(t.length-1)*o+"px",y.style.width=i+"px",y.style.height=o+"px",y.style.backgroundColor=c,d.appendChild(y)}}d.style.display=""}function _zl_makeLine(d,e,t,s,n,i,o,l){const a=document.createElement("div");a.style.cssText="position:absolute;pointer-events:none",a.style.backgroundColor=o.backgroundColor,a.style.left=e+"px",a.style.top=t+"px",a.style.width=s+"px",a.style.height=n+1+"px",a.style.lineHeight=n+"px";let r=0;for(const c of d){const h=_zl_charCellWidth(c,l),u=document.createElement("span");u.style.cssText="position:absolute;display:inline-block;text-align:center;pointer-events:none;font-feature-settings:'liga' 0,'calt' 0",u.style.left=r*i+"px",u.style.width=h*i+"px",u.style.fontFamily=o.fontFamily,u.style.fontSize=o.fontSize,u.style.fontWeight=o.fontWeight,u.style.color=o.color,u.style.height=n+"px",u.style.lineHeight=n+"px",o.letterSpacing&&(u.style.letterSpacing=o.letterSpacing),u.textContent=c,a.appendChild(u),r+=h}return a}const _ZL_DEFAULT_PROMPT={type:"character",char:">",offset:2},_ZL_DEFAULT_BG="#0d0d0d",_ZL_DEFAULT_FG="#eeeeee",_ZL_DEFAULT_CURSOR="#e0e0e0";class ZerolagInputAddon{constructor(e){this._terminal=null,this._overlay=null,this._pendingText="",this._flushedOffset=0,this._flushedText="",this._bufferDetectDone=!1,this._lastRenderKey="",this._lastPromptPos=null,this._font={fontFamily:"monospace",fontSize:"14px",fontWeight:"normal",color:_ZL_DEFAULT_FG,backgroundColor:_ZL_DEFAULT_BG,letterSpacing:""},this._scrollTimer=null,this._scrollHandler=null,this._scrollViewport=null,this._options={prompt:e?.prompt??_ZL_DEFAULT_PROMPT,zIndex:e?.zIndex??7,showCursor:e?.showCursor??!0,scrollDebounceMs:e?.scrollDebounceMs??50,backgroundColor:e?.backgroundColor,foregroundColor:e?.foregroundColor,cursorColor:e?.cursorColor}}activate(e){this._terminal=e,this._overlay=document.createElement("div"),this._overlay.style.cssText=`position:absolute;z-index:${this._options.zIndex};pointer-events:none;display:none`;const t=e.element?.querySelector(".xterm-screen");t&&t.appendChild(this._overlay),this._cacheFont(),this._scrollHandler=()=>{try{const n=this._terminal.buffer.active;n.viewportY!==n.baseY?(this._overlay.style.display="none",this._scrollTimer&&(clearTimeout(this._scrollTimer),this._scrollTimer=null)):(this._pendingText||this._flushedOffset>0)&&(this._scrollTimer&&clearTimeout(this._scrollTimer),this._scrollTimer=setTimeout(()=>{this._scrollTimer=null,this._lastRenderKey="",this._render()},this._options.scrollDebounceMs))}catch{}};const s=e.element?.querySelector(".xterm-viewport");s&&(s.addEventListener("scroll",this._scrollHandler,{passive:!0}),this._scrollViewport=s)}dispose(){this.clear(),this._scrollTimer&&(clearTimeout(this._scrollTimer),this._scrollTimer=null),this._scrollViewport&&this._scrollHandler&&this._scrollViewport.removeEventListener("scroll",this._scrollHandler),this._overlay?.remove(),this._overlay=null,this._scrollViewport=null,this._scrollHandler=null,this._terminal=null}addChar(e){!this._pendingText&&!this._flushedOffset&&this._detectBufferText(),this._pendingText+=e,this._render()}appendText(e){e&&(!this._pendingText&&!this._flushedOffset&&this._detectBufferText(),this._pendingText+=e,this._render())}removeChar(){return this._pendingText.length>0?(this._pendingText=this._pendingText.slice(0,-1),this._pendingText.length>0||this._flushedOffset>0?this._render():this._hide(),"pending"):this._flushedOffset>0?(this._flushedOffset--,this._flushedText=this._flushedText.slice(0,-1),this._flushedOffset>0?this._render():this._hide(),"flushed"):(this._detectBufferText(),this._flushedOffset>0?(this._flushedOffset--,this._flushedText=this._flushedText.slice(0,-1),this._flushedOffset>0?this._render():this._hide(),"flushed"):!1)}clear(){this._pendingText="",this._flushedOffset=0,this._flushedText="",this._bufferDetectDone=!1,this._lastRenderKey="",this._lastPromptPos=null,this._hide()}setFlushed(e,t,s=!0){this._flushedOffset=e,this._flushedText=t,s&&this._render()}getFlushed(){return{count:this._flushedOffset,text:this._flushedText}}clearFlushed(){this._flushedOffset=0,this._flushedText="",this._pendingText?this._render():this._hide()}rerender(){(this._pendingText||this._flushedOffset>0)&&(this._lastRenderKey="",this._render())}refreshFont(){this._cacheFont(),this._lastRenderKey="",(this._pendingText||this._flushedOffset>0)&&this._render()}detectBufferText(){return this._detectBufferText()}resetBufferDetection(){this._bufferDetectDone=!1}undoDetection(){this._flushedOffset=0,this._flushedText="",this._bufferDetectDone=!1}suppressBufferDetection(){this._bufferDetectDone=!0}setPrompt(e){this._options.prompt=e,this._lastPromptPos=null}findPrompt(){return this._terminal?_zl_findPrompt(this._terminal,this._options.prompt??_ZL_DEFAULT_PROMPT):null}readPromptText(){if(!this._terminal)return null;const e=this.findPrompt();if(!e)return null;const t=(this._options.prompt??_ZL_DEFAULT_PROMPT).offset??2;return _zl_readTextAfterPrompt(this._terminal,e,t)||null}get pendingText(){return this._pendingText}get hasPending(){return this._pendingText.length>0||this._flushedOffset>0}get state(){return{pendingText:this._pendingText,flushedLength:this._flushedOffset,flushedText:this._flushedText,visible:this._overlay!==null&&this._overlay.style.display!=="none",promptPosition:this._lastPromptPos?{...this._lastPromptPos}:null}}_detectBufferText(){if(this._bufferDetectDone||!this._terminal)return null;this._bufferDetectDone=!0;try{const e=this.findPrompt();if(!e)return null;const t=(this._options.prompt??_ZL_DEFAULT_PROMPT).offset??2,s=_zl_readTextAfterPrompt(this._terminal,e,t);if(s.length>0)return this._flushedOffset=s.length,this._flushedText=s,this._lastPromptPos=e,s}catch{}return null}_cacheFont(){if(!this._terminal)return;const e=this._terminal;this._font.fontFamily=e.options.fontFamily||"monospace";const t=e.options.fontSize||14;this._font.fontSize=t+"px",this._font.fontWeight=String(e.options.fontWeight||"normal"),this._font.backgroundColor=this._options.backgroundColor??e.options.theme?.background??_ZL_DEFAULT_BG,this._font.color=this._options.foregroundColor??e.options.theme?.foreground??_ZL_DEFAULT_FG,this._font.letterSpacing="";const s=e.element?.querySelector(".xterm-rows");if(s){const i=getComputedStyle(s);this._font.letterSpacing=i.letterSpacing,!this._options.foregroundColor&&i.color&&(this._font.color=i.color)}const n=_zl_getCellDimensions(e);if(n&&n.width>0){const i=document.createElement("span");i.style.cssText=`position:absolute;visibility:hidden;white-space:pre;font-family:${this._font.fontFamily};font-size:${t}px;font-weight:${this._font.fontWeight};font-feature-settings:'liga' 0,'calt' 0`,this._font.letterSpacing&&(i.style.letterSpacing=this._font.letterSpacing),i.textContent="W",document.body.appendChild(i);const o=i.getBoundingClientRect().width;if(document.body.removeChild(i),o>0&&Math.abs(o-n.width)>.1){const l=t*(n.width/o);this._font.fontSize=l+"px"}}}_hide(){this._overlay&&(this._lastRenderKey="",this._lastPromptPos=null,this._overlay.innerHTML="",this._overlay.style.display="none")}_render(){if(!(!this._terminal||!this._overlay)){if(!this._pendingText&&!(this._flushedOffset>0)){this._overlay.style.display="none";return}try{const e=this._terminal.buffer.active;if(e.viewportY!==e.baseY){this._overlay.style.display="none";return}const t=this.findPrompt();if(t)this._lastPromptPos&&this._flushedOffset>0?this._lastPromptPos={row:t.row,col:this._lastPromptPos.col}:this._lastPromptPos=t;else if(!this._lastPromptPos){this._overlay.style.display="none";return}const s=this._lastPromptPos,n=_zl_getCellDimensions(this._terminal);if(!n){this._overlay.style.display="none";return}const{width:i,height:o}=n,l=this._terminal.cols,a=(this._options.prompt??_ZL_DEFAULT_PROMPT).offset??2,r=s.col+a;let c=this._pendingText;if(this._flushedOffset>0)if(this._flushedText&&this._flushedText.length===this._flushedOffset)c=this._flushedText+this._pendingText;else{const f=e.viewportY+s.row,w=e.getLine(f);w&&(c=w.translateToString(!0).slice(r,r+this._flushedOffset)+this._pendingText)}const h=`${c}:${r}:${s.row}:${s.col}:${l}:${this._flushedOffset}`;if(h===this._lastRenderKey&&this._overlay.style.display!=="none")return;this._lastRenderKey=h;const u=Math.max(1,l-r),m=[],p=[...c];let g=0;{let f="",w=0;for(;g<p.length;){const v=_zl_charCellWidth(p[g],this._terminal);if(w+v>u)break;f+=p[g],w+=v,g++}m.push(f)}for(;g<p.length;){let f="",w=0;for(;g<p.length;){const v=_zl_charCellWidth(p[g],this._terminal);if(w+v>l)break;f+=p[g],w+=v,g++}m.push(f)}const y=this._options.cursorColor??this._terminal.options.theme?.cursor??_ZL_DEFAULT_CURSOR;_zl_renderOverlay(this._overlay,{lines:m,startCol:r,totalCols:l,cellW:i,cellH:o,promptRow:s.row,font:this._font,showCursor:this._options.showCursor,cursorColor:y,terminal:this._terminal})}catch{this._overlay&&(this._overlay.innerHTML="",this._overlay.style.display="none")}}}}const LocalEchoOverlay=class extends ZerolagInputAddon{constructor(d){super({prompt:{type:"character",char:"\u276F",offset:2}}),this.activate(d)}};function extractSyncSegments(d){const e=[];let t=d;for(;t.length>0;){const s=t.indexOf(DEC_SYNC_START);if(s===-1){t.length>0&&e.push(t);break}s>0&&e.push(t.slice(0,s));const n=t.slice(s+DEC_SYNC_START.length),i=n.indexOf(DEC_SYNC_END);if(i===-1){e.push(t.slice(s));break}const o=n.slice(0,i);o.length>0&&e.push(o),t=n.slice(i+DEC_SYNC_END.length)}return e}class NotificationManager{constructor(e){this.app=e,this.notifications=[],this.unreadCount=0,this.isTabVisible=!document.hidden,this.isDrawerOpen=!1,this.originalTitle=document.title,this.titleFlashInterval=null,this.titleFlashState=!1,this.lastBrowserNotifTime=0,this.audioCtx=null,this.renderScheduled=!1,this.groupingMap=new Map,this.preferences=this.loadPreferences(),document.addEventListener("visibilitychange",()=>{this.isTabVisible=!document.hidden,this.isTabVisible&&this.onTabVisible()}),window.addEventListener("pageshow",t=>{t.persisted&&(this.isTabVisible=!0,this.onTabVisible())})}loadPreferences(){const e={permission_prompt:{enabled:!0,browser:!0,audio:!0,push:!1},elicitation_dialog:{enabled:!0,browser:!0,audio:!0,push:!1},idle_prompt:{enabled:!0,browser:!0,audio:!1,push:!1},stop:{enabled:!0,browser:!1,audio:!1,push:!1},session_error:{enabled:!0,browser:!0,audio:!1,push:!1},respawn_cycle:{enabled:!0,browser:!1,audio:!1,push:!1},token_milestone:{enabled:!0,browser:!1,audio:!1,push:!1},ralph_complete:{enabled:!0,browser:!0,audio:!0,push:!1},subagent_spawn:{enabled:!1,browser:!1,audio:!1,push:!1},subagent_complete:{enabled:!1,browser:!1,audio:!1,push:!1}},t=MobileDetection.getDeviceType()==="mobile",s={enabled:!t,browserNotifications:!t,audioAlerts:!1,stuckThresholdMs:STUCK_THRESHOLD_DEFAULT_MS,muteCritical:!1,muteWarning:!1,muteInfo:!1,eventTypes:e,_version:4};try{const n=this.getStorageKey(),i=localStorage.getItem(n);if(i){const o=JSON.parse(i);if((!o._version||o._version<2)&&(o.browserNotifications=!0,o._version=2),o._version<3&&(o.eventTypes=e,o._version=3,localStorage.setItem(n,JSON.stringify(o))),o._version<4){if(o.eventTypes)for(const l of Object.keys(o.eventTypes))o.eventTypes[l]&&o.eventTypes[l].push===void 0&&(o.eventTypes[l].push=!1);o._version=4,localStorage.setItem(n,JSON.stringify(o))}return{...s,...o,eventTypes:{...e,...o.eventTypes}}}}catch{}return s}getStorageKey(){return MobileDetection.getDeviceType()==="mobile"?"codeman-notification-prefs-mobile":"codeman-notification-prefs"}savePreferences(){localStorage.setItem(this.getStorageKey(),JSON.stringify(this.preferences))}notify({urgency:e,category:t,sessionId:s,sessionName:n,title:i,message:o}){if(!this.preferences.enabled)return;const a={"hook-permission":"permission_prompt","hook-elicitation":"elicitation_dialog","hook-idle":"idle_prompt","hook-stop":"stop","session-error":"session_error","session-crash":"session_error","session-stuck":"idle_prompt","respawn-blocked":"respawn_cycle","auto-accept":"respawn_cycle","auto-clear":"respawn_cycle","ralph-complete":"ralph_complete","circuit-breaker":"respawn_cycle","exit-gate":"ralph_complete","subagent-spawn":"subagent_spawn","subagent-complete":"subagent_complete","hook-teammate-idle":"idle_prompt","hook-task-completed":"stop"}[t]||t,r=this.preferences.eventTypes?.[a];let c=!1,h=!1;if(r){if(!r.enabled)return;c=r.browser&&this.preferences.browserNotifications,h=r.audio&&this.preferences.audioAlerts}else{if(e==="critical"&&this.preferences.muteCritical||e==="warning"&&this.preferences.muteWarning||e==="info"&&this.preferences.muteInfo)return;c=this.preferences.browserNotifications&&(e==="critical"||e==="warning"||!this.isTabVisible),h=e==="critical"&&this.preferences.audioAlerts}const u=`${t}:${s||"global"}`,m=this.groupingMap.get(u);if(m){m.notification.count=(m.notification.count||1)+1,m.notification.message=o,m.notification.timestamp=Date.now(),clearTimeout(m.timeout),m.timeout=setTimeout(()=>this.groupingMap.delete(u),GROUPING_TIMEOUT_MS),this.scheduleRender();return}const p={id:Date.now()+"-"+Math.random().toString(36).slice(2,7),urgency:e,category:t,sessionId:s,sessionName:n,title:i,message:o,timestamp:Date.now(),read:!1,count:1};this.notifications.unshift(p),this.notifications.length>100&&this.notifications.pop();const g=setTimeout(()=>this.groupingMap.delete(u),GROUPING_TIMEOUT_MS);this.groupingMap.set(u,{notification:p,timeout:g}),this.unreadCount++,this.updateBadge(),this.scheduleRender(),this.isTabVisible||this.updateTabTitle(),c&&this.sendBrowserNotif(i,o,t,s),h&&this.playAudioAlert()}scheduleRender(){this.renderScheduled||(this.renderScheduled=!0,requestAnimationFrame(()=>{this.renderScheduled=!1,this.renderDrawer()}))}renderDrawer(){const e=document.getElementById("notifList"),t=document.getElementById("notifEmpty");if(!(!e||!t)){if(this.notifications.length===0){e.style.display="none",t.style.display="flex";return}e.style.display="block",t.style.display="none",e.innerHTML=this.notifications.map(s=>{const n=`notif-item-${s.urgency}`,i=s.read?"":" unread",o=s.count>1?`<span class="notif-item-count">×${s.count}</span>`:"",l=s.sessionName?`<span class="notif-item-session">${this.escapeHtml(s.sessionName)}</span>`:"";return`<div class="notif-item ${n}${i}" data-notif-id="${s.id}" data-session-id="${s.sessionId||""}" onclick="app.notificationManager.clickNotification('${this.escapeHtml(s.id)}')">
|
|
44
|
+
<div class="notif-item-header">
|
|
45
|
+
<span class="notif-item-title">${this.escapeHtml(s.title)}${o}</span>
|
|
46
|
+
<span class="notif-item-time">${this.relativeTime(s.timestamp)}</span>
|
|
47
|
+
</div>
|
|
48
|
+
<div class="notif-item-message">${this.escapeHtml(s.message)}</div>
|
|
49
|
+
${l}
|
|
50
|
+
</div>`}).join("")}}updateTabTitle(){this.unreadCount>0&&!this.isTabVisible&&(this.titleFlashInterval||(this.titleFlashInterval=setInterval(()=>{this.titleFlashState=!this.titleFlashState,document.title=this.titleFlashState?`\u26A0\uFE0F (${this.unreadCount}) Codeman`:this.originalTitle},TITLE_FLASH_INTERVAL_MS),document.title=`\u26A0\uFE0F (${this.unreadCount}) Codeman`))}stopTitleFlash(){this.titleFlashInterval&&(clearInterval(this.titleFlashInterval),this.titleFlashInterval=null,this.titleFlashState=!1,document.title=this.originalTitle)}sendBrowserNotif(e,t,s,n){if(!this.preferences.browserNotifications||typeof Notification>"u")return;if(Notification.permission==="default"){Notification.requestPermission().then(l=>{l==="granted"&&this.sendBrowserNotif(e,t,s,n)});return}if(Notification.permission!=="granted")return;const i=Date.now();if(i-this.lastBrowserNotifTime<3e3)return;this.lastBrowserNotifTime=i;const o=new Notification(`Codeman: ${e}`,{body:t,tag:s,icon:"/favicon.ico",silent:!0});o.onclick=()=>{window.focus(),n&&this.app.sessions.has(n)&&this.app.selectSession(n),o.close()},setTimeout(()=>o.close(),8e3)}async requestPermission(){if(typeof Notification>"u"){this.app.showToast("Browser notifications not supported","warning");return}const e=await Notification.requestPermission(),t=document.getElementById("notifPermissionStatus");t&&(t.textContent=`Status: ${e}`),e==="granted"?(this.preferences.browserNotifications=!0,this.savePreferences(),this.app.showToast("Notifications enabled","success")):this.app.showToast(`Permission ${e}`,"warning")}playAudioAlert(){try{this.audioCtx||(this.audioCtx=new(window.AudioContext||window.webkitAudioContext)),this.audioCtx.state==="suspended"&&this.audioCtx.resume();const e=this.audioCtx,t=e.createOscillator(),s=e.createGain();t.connect(s),s.connect(e.destination),t.type="sine",t.frequency.setValueAtTime(660,e.currentTime),s.gain.setValueAtTime(.15,e.currentTime),s.gain.exponentialRampToValueAtTime(.01,e.currentTime+.15),t.start(e.currentTime),t.stop(e.currentTime+.15)}catch{}}toggleDrawer(){const e=document.getElementById("notifDrawer");e&&(this.isDrawerOpen=!this.isDrawerOpen,e.classList.toggle("open",this.isDrawerOpen),this.isDrawerOpen&&this.renderDrawer())}clickNotification(e){const t=this.notifications.find(s=>s.id===e);t&&(t.read||(t.read=!0,this.unreadCount=Math.max(0,this.unreadCount-1),this.updateBadge()),t.sessionId&&this.app.sessions.has(t.sessionId)&&(this.app.selectSession(t.sessionId),this.toggleDrawer()),this.scheduleRender())}markAllRead(){this.notifications.forEach(e=>{e.read=!0}),this.unreadCount=0,this.updateBadge(),this.stopTitleFlash(),this.scheduleRender()}clearAll(){this.notifications=[],this.unreadCount=0,this.updateBadge(),this.stopTitleFlash(),this.scheduleRender()}updateBadge(){const e=document.getElementById("notifBadge");e&&(this.unreadCount>0?(e.style.display="flex",e.textContent=this.unreadCount>99?"99+":String(this.unreadCount)):e.style.display="none")}onTabVisible(){this.stopTitleFlash(),this.isDrawerOpen&&this.markAllRead(),this.app?.fitAddon&&this.app?.activeSessionId&&(this.app.fitAddon.fit(),this.app.sendResize(this.app.activeSessionId))}relativeTime(e){const t=Math.floor((Date.now()-e)/1e3);return t<60?"now":t<3600?`${Math.floor(t/60)}m ago`:t<86400?`${Math.floor(t/3600)}h ago`:`${Math.floor(t/86400)}d ago`}escapeHtml(e){return e?e.replace(/[&<>"']/g,t=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[t]):""}}class CodemanApp{constructor(){this.sessions=new Map,this.sessionOrder=[],this.draggedTabId=null,this.cases=[],this.currentRun=null,this.totalTokens=0,this.globalStats=null,this.eventSource=null,this.terminal=null,this.fitAddon=null,this.activeSessionId=null,this._initGeneration=0,this._initFallbackTimer=null,this._selectGeneration=0,this.respawnStatus={},this.respawnTimers={},this.respawnCountdownTimers={},this.respawnActionLogs={},this.timerCountdownInterval=null,this.terminalBuffers=new Map,this.editingSessionId=null,this.pendingCloseSessionId=null,this.muxSessions=[],this.ralphStates=new Map,this.subagents=new Map,this.subagentActivity=new Map,this.subagentToolResults=new Map,this.activeSubagentId=null,this.subagentPanelVisible=!1,this.subagentWindows=new Map,this.subagentWindowZIndex=ZINDEX_SUBAGENT_BASE,this.minimizedSubagents=new Map,this._subagentHideTimeout=null,this.subagentParentMap=new Map,this.teams=new Map,this.teamTasks=new Map,this.teammateMap=new Map,this.teammatePanesByName=new Map,this.teammateTerminals=new Map,this.terminalBufferCache=new Map,this.ralphStatePanelCollapsed=!0,this.ralphClosedSessions=new Set,this.planSubagents=new Map,this.planSubagentWindowZIndex=ZINDEX_PLAN_SUBAGENT_BASE,this.planGenerationStopped=!1,this.planAgentsMinimized=!1,this.wizardDragState=null,this.wizardDragListeners=null,this.wizardPosition=null,this.projectInsights=new Map,this.logViewerWindows=new Map,this.logViewerWindowZIndex=ZINDEX_LOG_VIEWER_BASE,this.projectInsightsPanelVisible=!1,this.currentSessionWorkingDir=null,this.imagePopups=new Map,this.imagePopupZIndex=ZINDEX_IMAGE_POPUP_BASE,this.tabAlerts=new Map,this.pendingHooks=new Map,this.pendingWrites=[],this.writeFrameScheduled=!1,this._wasAtBottomBeforeWrite=!0,this.syncWaitTimeout=null,this._isLoadingBuffer=!1,this._loadBufferQueue=null,this.flickerFilterBuffer="",this.flickerFilterActive=!1,this.flickerFilterTimeout=null,this.renderSessionTabsTimeout=null,this.renderRalphStatePanelTimeout=null,this.renderTaskPanelTimeout=null,this.renderMuxSessionsTimeout=null,this.systemStatsInterval=null,this.sseReconnectTimeout=null,this._sseListenerCleanup=null,this.reconnectAttempts=0,this.maxReconnectAttempts=10,this.isOnline=navigator.onLine,this._inputQueue=new Map,this._inputQueueMaxBytes=64*1024,this._connectionStatus="connected",this._inputSendChain=Promise.resolve(),this._localEchoOverlay=null,this._localEchoEnabled=!1,this._restoringFlushedState=!1,this.activeFocusTrap=null,this.notificationManager=new NotificationManager(this),this.idleTimers=new Map,this._elemCache={},this.init()}$(e){return this._elemCache[e]||(this._elemCache[e]=document.getElementById(e)),this._elemCache[e]}formatTokens(e){if(e>=1e6){const t=e/1e6;return t>=10?`${t.toFixed(1)}m`:`${t.toFixed(2)}m`}else if(e>=1e3){const t=e/1e3;return t>=100?`${t.toFixed(0)}k`:`${t.toFixed(1)}k`}return String(e)}estimateCost(e,t){const s=e/1e6*15,n=t/1e6*75;return s+n}setPendingHook(e,t){this.pendingHooks.has(e)||this.pendingHooks.set(e,new Set),this.pendingHooks.get(e).add(t),this.updateTabAlertFromHooks(e)}clearPendingHooks(e,t=null){const s=this.pendingHooks.get(e);s&&(t?s.delete(t):s.clear(),s.size===0&&this.pendingHooks.delete(e),this.updateTabAlertFromHooks(e))}updateTabAlertFromHooks(e){const t=this.pendingHooks.get(e);!t||t.size===0?this.tabAlerts.delete(e):t.has("permission_prompt")||t.has("elicitation_dialog")?this.tabAlerts.set(e,"action"):t.has("idle_prompt")&&this.tabAlerts.set(e,"idle"),this.renderSessionTabs()}init(){MobileDetection.init(),KeyboardHandler.init(),SwipeHandler.init(),VoiceInput.init(),KeyboardAccessoryBar.init(),this.applyHeaderVisibilitySettings(),this.applyTabWrapSettings(),this.applyMonitorVisibility(),document.documentElement.classList.remove("mobile-init"),requestAnimationFrame(()=>{this.initTerminal(),this.loadFontSize(),this.connectSSE(),this._initFallbackTimer=setTimeout(()=>{this._initGeneration===0&&this.loadState()},3e3)}),this.registerServiceWorker();const e=fetch("/api/settings").then(t=>t.ok?t.json():null).catch(()=>null);if(this.loadQuickStartCases(null,e),this._initRunMode(),this.setupEventListeners(),MobileDetection.isTouchDevice()){const t=s=>{s&&s.addEventListener("touchstart",n=>{if(!KeyboardHandler.keyboardVisible)return;const i=n.target.closest("button");i&&(n.preventDefault(),i.click(),typeof app<"u"&&app.terminal&&app.terminal.focus())},{passive:!1})};t(document.querySelector(".toolbar")),t(document.querySelector(".welcome-overlay"))}this.setupOnlineDetection(),this.loadAppSettingsFromServer(e).then(()=>{this.applyHeaderVisibilitySettings(),this.applyTabWrapSettings(),this.applyMonitorVisibility()}),document.body.classList.add("app-loaded")}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 r=new Unicode11Addon.Unicode11Addon;this.terminal.loadAddon(r),this.terminal.unicode.activeVersion="11"}catch{}const t=document.getElementById("terminalContainer");if(this.terminal.open(t),typeof WebglAddon<"u")try{const r=new WebglAddon.WebglAddon;r.onContextLoss(()=>{r.dispose()}),this.terminal.loadAddon(r)}catch{}if(this._localEchoOverlay=new LocalEchoOverlay(this.terminal),MobileDetection.getDeviceType()==="mobile"&&document.body.classList.contains("safari-browser")?requestAnimationFrame(()=>{this.fitAddon.fit(),requestAnimationFrame(()=>this.fitAddon.fit())}):this.fitAddon.fit(),this.registerFilePathLinkProvider(),t.addEventListener("wheel",r=>{r.preventDefault();const c=Math.round(r.deltaY/25)||(r.deltaY>0?1:-1);this.terminal.scrollLines(c)},{passive:!1}),!(MobileDetection.isTouchDevice()&&window.innerWidth<1024)){let r=0,c=0,h=0,u=0,m=null,p=!1;const g=t.querySelector(".xterm-viewport"),y=f=>{if(!g)return;const w=u?(f-u)/16.67:1;u=f,p?(c!==0&&(g.scrollTop+=c,c=0),m=requestAnimationFrame(y)):Math.abs(h)>.1?(g.scrollTop+=h*w,h*=.94,m=requestAnimationFrame(y)):(m=null,h=0)};t.addEventListener("touchstart",f=>{f.touches.length===1&&(r=f.touches[0].clientY,c=0,h=0,p=!0,u=0,m||(m=requestAnimationFrame(y)))},{passive:!0}),t.addEventListener("touchmove",f=>{if(f.touches.length===1&&p){const w=f.touches[0].clientY,v=r-w;c+=v,h=v*1.2,r=w}},{passive:!0}),t.addEventListener("touchend",()=>{p=!1},{passive:!0}),t.addEventListener("touchcancel",()=>{p=!1,h=0},{passive:!0})}this.showWelcome(),this._resizeTimeout=null,this._lastResizeDims=null;const i=40,o=10,l=()=>{this._resizeTimeout||(this._resizeTimeout=setTimeout(()=>{if(this._resizeTimeout=null,this.fitAddon){this.fitAddon.fit();const r=typeof KeyboardHandler<"u"&&KeyboardHandler.keyboardVisible;if(this.activeSessionId&&!r){const c=this.fitAddon.proposeDimensions(),h=c?Math.max(c.cols,i):i,u=c?Math.max(c.rows,o):o;(!this._lastResizeDims||h!==this._lastResizeDims.cols||u!==this._lastResizeDims.rows)&&(this._lastResizeDims={cols:h,rows:u},fetch(`/api/sessions/${this.activeSessionId}/resize`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cols:h,rows:u})}).catch(()=>{}))}}this.updateConnectionLines(),this._localEchoOverlay?.hasPending&&this._localEchoOverlay.rerender()},100))};window.addEventListener("resize",l),this.terminalResizeObserver&&this.terminalResizeObserver.disconnect(),this.terminalResizeObserver=new ResizeObserver(l),this.terminalResizeObserver.observe(t),this._pendingInput="",this._inputFlushTimeout=null,this._lastKeystrokeTime=0;const a=()=>{if(this._inputFlushTimeout=null,this._pendingInput&&this.activeSessionId){const r=this._pendingInput,c=this.activeSessionId;this._pendingInput="",this._sendInputAsync(c,r)}};this.terminal.onData(r=>{if(this.activeSessionId){if(/^\x1b\[[\?>=]?[\d;]*[cnR]$/.test(r))return;if(this._localEchoEnabled){if(r==="\x7F"){if(this._localEchoOverlay?.removeChar()==="flushed"){const{count:u,text:m}=this._localEchoOverlay.getFlushed();this._flushedOffsets?.has(this.activeSessionId)&&(u===0?(this._flushedOffsets.delete(this.activeSessionId),this._flushedTexts?.delete(this.activeSessionId)):(this._flushedOffsets.set(this.activeSessionId,u),this._flushedTexts?.set(this.activeSessionId,m))),this._pendingInput+=r,a()}return}if(/^[\r\n]+$/.test(r)){const h=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),h&&(this._pendingInput+=h,a()),setTimeout(()=>{this._pendingInput+="\r",a()},80);return}if(r.length>1&&r.charCodeAt(0)>=32){this._localEchoOverlay?.appendText(r);return}if(r.charCodeAt(0)<32){if(r.length>1&&r.charCodeAt(0)===27){this._pendingInput+=r,a();return}if(this._restoringFlushedState){this._pendingInput+=r,a();return}if(r===" "){const u=this._localEchoOverlay?.pendingText||"";this._localEchoOverlay?.clear(),this._flushedOffsets?.delete(this.activeSessionId),this._flushedTexts?.delete(this.activeSessionId),u&&(this._pendingInput+=u),this._pendingInput+=r,this._inputFlushTimeout&&(clearTimeout(this._inputFlushTimeout),this._inputFlushTimeout=null);let m="";try{const g=this._localEchoOverlay?.findPrompt?.();if(g){const y=this.terminal.buffer.active,f=y.getLine(y.viewportY+g.row);f&&(m=f.translateToString(!0).slice(g.col+2).trimEnd())}}catch{}this._tabCompletionBaseText=m,a(),this._tabCompletionSessionId=this.activeSessionId,this._tabCompletionRetries=0,this._tabCompletionFallback&&clearTimeout(this._tabCompletionFallback);const p=this;this._tabCompletionFallback=setTimeout(()=>{if(p._tabCompletionFallback=null,!p._tabCompletionSessionId||p._tabCompletionSessionId!==p.activeSessionId)return;const g=p._localEchoOverlay;!g||g.pendingText||p.terminal.write("",()=>{if(!p._tabCompletionSessionId)return;g.resetBufferDetection();const y=g.detectBufferText();y&&y!==p._tabCompletionBaseText&&(p._tabCompletionSessionId=null,p._tabCompletionRetries=0,p._tabCompletionBaseText=null,g.rerender())})},300);return}const h=this._localEchoOverlay?.pendingText||"";this._localEchoOverlay?.clear(),this._localEchoOverlay?.suppressBufferDetection(),this._flushedOffsets?.delete(this.activeSessionId),this._flushedTexts?.delete(this.activeSessionId),h&&(this._pendingInput+=h),this._pendingInput+=r,this._inputFlushTimeout&&(clearTimeout(this._inputFlushTimeout),this._inputFlushTimeout=null),a();return}if(r.length===1&&r.charCodeAt(0)>=32){this._localEchoOverlay?.addChar(r);return}}if(this._pendingInput+=r,r.charCodeAt(0)<32||r.length>1){this._inputFlushTimeout&&(clearTimeout(this._inputFlushTimeout),this._inputFlushTimeout=null),a();return}const c=performance.now();c-this._lastKeystrokeTime>50?(this._inputFlushTimeout&&(clearTimeout(this._inputFlushTimeout),this._inputFlushTimeout=null),this._lastKeystrokeTime=c,a()):(this._lastKeystrokeTime=c,this._inputFlushTimeout||(this._inputFlushTimeout=setTimeout(a,0)))}})}registerFilePathLinkProvider(){const e=this;let t=-1;this.terminal.registerLinkProvider({provideLinks(s,n){s!==t&&(t=s);const o=e.terminal.buffer.active.getLine(s);if(!o){n(void 0);return}const l=o.translateToString(!0);if(!l||!l.includes("/")){n(void 0);return}const a=[],r=/(tail|cat|head|less|grep|watch|vim|nano)\s+(?:[^\s\/]*\s+)*(\/[^\s"'<>|;&\n\x00-\x1f]+)/g,c=/(\/(?:home|tmp|var|etc|opt)[^\s"'<>|;&\n\x00-\x1f]*\.(?:log|txt|json|md|yaml|yml|csv|xml|sh|py|ts|js))\b/g,h=/Bash\([^)]*?(\/(?:home|tmp|var|etc|opt)[^\s"'<>|;&\)\n\x00-\x1f]+)/g,u=(p,g)=>{const y=l.indexOf(p,g);y!==-1&&(a.some(f=>f.range.start.x===y+1)||a.push({text:p,range:{start:{x:y+1,y:s},end:{x:y+p.length+1,y:s}},decorations:{pointerCursor:!0,underline:!0},activate(f,w){e.openLogViewerWindow(w,e.activeSessionId)}}))};let m;for(r.lastIndex=0;(m=r.exec(l))!==null;)u(m[2],m.index);for(c.lastIndex=0;(m=c.exec(l))!==null;)u(m[1],m.index);for(h.lastIndex=0;(m=h.exec(l))!==null;)u(m[1],m.index);a.length>0,n(a.length>0?a:void 0)}})}showWelcome(){const e=document.getElementById("welcomeOverlay");e&&(e.classList.add("visible"),this.loadTunnelStatus())}hideWelcome(){const e=document.getElementById("welcomeOverlay");e&&e.classList.remove("visible");const t=document.getElementById("welcomeQr");t&&(clearTimeout(this._welcomeQrShrinkTimer),t.classList.remove("expanded"))}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}this.writeFrameScheduled||(this._wasAtBottomBeforeWrite=this.isTerminalAtBottom());const s=(this.activeSessionId?this.sessions.get(this.activeSessionId):null)?.flickerFilterEnabled??!1;if(/\x1b\[\d{1,2}A/.test(e)||this.flickerFilterActive&&!s){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(s){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(()=>{if(this.pendingWrites.length>0&&this.terminal){const i=this.pendingWrites.join(""),o=i.includes(DEC_SYNC_START),l=i.includes(DEC_SYNC_END);if(o&&!l){this.syncWaitTimeout||(this.syncWaitTimeout=setTimeout(()=>{this.syncWaitTimeout=null,this.flushPendingWrites()},50)),this.writeFrameScheduled=!1;return}this.syncWaitTimeout&&(clearTimeout(this.syncWaitTimeout),this.syncWaitTimeout=null),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(),t=this.activeSessionId?this.sessions.get(this.activeSessionId):null,n=!!((e.localEchoEnabled??MobileDetection.isTouchDevice())&&t);this._localEchoEnabled&&!n&&this._localEchoOverlay?.clear(),this._localEchoEnabled=n,this._localEchoOverlay&&t&&(t.mode==="opencode"?this._localEchoOverlay.setPrompt({type:"custom",offset:3,find:i=>{try{const o=i.buffer.active,l=o.cursorY,a=o.getLine(o.viewportY+l);if(!a)return null;const c=a.translateToString(!0).indexOf("\u2503");return c>=0?{row:l,col:c}:null}catch{return null}}}):this._localEchoOverlay.setPrompt({type:"character",char:"\u276F",offset:2}))}flushPendingWrites(){if(this.pendingWrites.length===0||!this.terminal)return;const e=extractSyncSegments(this.pendingWrites.join(""));this.pendingWrites=[];for(const t of e)if(t){const s=t.startsWith(DEC_SYNC_START)?t.slice(DEC_SYNC_START.length):t;s&&this.terminal.write(s)}if(this._wasAtBottomBeforeWrite&&this.terminal.scrollToBottom(),this._localEchoOverlay?.hasPending&&this._localEchoOverlay.rerender(),this._tabCompletionSessionId&&this._tabCompletionSessionId===this.activeSessionId&&this._localEchoOverlay&&!this._localEchoOverlay.pendingText){const t=this._localEchoOverlay,s=this;this.terminal.write("",()=>{if(!s._tabCompletionSessionId)return;t.resetBufferDetection();const n=t.detectBufferText();n?n===s._tabCompletionBaseText?(t.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),t.rerender()):(s._tabCompletionRetries=(s._tabCompletionRetries||0)+1,s._tabCompletionRetries>60&&(s._tabCompletionSessionId=null,s._tabCompletionRetries=0))})}}chunkedTerminalWrite(e,t=TERMINAL_CHUNK_SIZE){return new Promise(s=>{if(!e||e.length===0){this._finishBufferLoad(),s();return}this._isLoadingBuffer=!0,this._loadBufferQueue=[];const n=e.replace(DEC_SYNC_STRIP_RE,""),i=()=>{this._finishBufferLoad(),s()};if(n.length<=t){this.terminal.write(n),i();return}let o=0;const l=()=>{if(o>=n.length){requestAnimationFrame(i);return}const a=n.slice(o,o+t);this.terminal.write(a),o+=t,requestAnimationFrame(l)};requestAnimationFrame(l)})}_finishBufferLoad(){const e=this._loadBufferQueue;if(this._isLoadingBuffer=!1,this._loadBufferQueue=null,e&&e.length>0)for(const t of e)this.batchTerminalWrite(t)}setupEventListeners(){document.addEventListener("keydown",t=>{t.key==="Escape"&&(this.closeAllPanels(),this.closeHelp()),(t.ctrlKey||t.metaKey)&&(t.key==="?"||t.key==="/")&&(t.preventDefault(),this.showHelp()),(t.ctrlKey||t.metaKey)&&t.key==="Enter"&&(t.preventDefault(),this.quickStart()),(t.ctrlKey||t.metaKey)&&t.key==="w"&&(t.preventDefault(),this.killActiveSession()),(t.ctrlKey||t.metaKey)&&t.key==="Tab"&&(t.preventDefault(),this.nextSession()),(t.ctrlKey||t.metaKey)&&t.key==="k"&&(t.preventDefault(),this.killAllSessions()),(t.ctrlKey||t.metaKey)&&t.key==="l"&&(t.preventDefault(),this.clearTerminal()),(t.ctrlKey||t.metaKey)&&t.shiftKey&&t.key==="R"&&(t.preventDefault(),this.restoreTerminalSize()),(t.ctrlKey||t.metaKey)&&(t.key==="="||t.key==="+")&&(t.preventDefault(),this.increaseFontSize()),(t.ctrlKey||t.metaKey)&&t.key==="-"&&(t.preventDefault(),this.decreaseFontSize()),(t.ctrlKey||t.metaKey)&&t.shiftKey&&t.key==="V"&&(t.preventDefault(),VoiceInput.toggle())},!0);const e=this.$("headerTokens");e&&!e._statsHandlerAttached&&(e.classList.add("clickable"),e._statsHandlerAttached=!0,e.addEventListener("click",()=>this.openTokenStats())),this.setupColorPicker()}connectSSE(){if(!navigator.onLine){this.setConnectionStatus("offline");return}this.sseReconnectTimeout&&(clearTimeout(this.sseReconnectTimeout),this.sseReconnectTimeout=null),this._sseListenerCleanup&&(this._sseListenerCleanup(),this._sseListenerCleanup=null),this.eventSource&&(this.eventSource.close(),this.eventSource=null),this.reconnectAttempts===0?this.setConnectionStatus("connecting"):this.setConnectionStatus("reconnecting"),this.eventSource=new EventSource("/api/events");const e=[],t=(s,n)=>{this.eventSource.addEventListener(s,n),e.push({event:s,handler:n})};this._sseListenerCleanup=()=>{for(const{event:s,handler:n}of e)this.eventSource&&this.eventSource.removeEventListener(s,n);e.length=0},this.eventSource.onopen=()=>{this.reconnectAttempts=0,this.setConnectionStatus("connected")},this.eventSource.onerror=()=>{this.reconnectAttempts++,this.reconnectAttempts>=this.maxReconnectAttempts?this.setConnectionStatus("disconnected"):this.setConnectionStatus("reconnecting"),this.eventSource&&(this.eventSource.close(),this.eventSource=null),this.sseReconnectTimeout&&clearTimeout(this.sseReconnectTimeout);const s=this.reconnectAttempts<=1?200:Math.min(500*Math.pow(2,this.reconnectAttempts-2),3e4);this.sseReconnectTimeout=setTimeout(()=>this.connectSSE(),s)},t("init",s=>{try{this.handleInit(JSON.parse(s.data))}catch{}}),t("session:created",s=>{const n=JSON.parse(s.data);this.sessions.set(n.id,n),this.sessionOrder.includes(n.id)||(this.sessionOrder.push(n.id),this.saveSessionOrder()),this.renderSessionTabs(),this.updateCost(),this.sessions.size===1&&this.startSystemStatsPolling()}),t("session:updated",s=>{const n=JSON.parse(s.data),i=n.session||n,o=this.sessions.get(i.id),l=i.claudeSessionId&&(!o||!o.claudeSessionId);this.sessions.set(i.id,i),this.renderSessionTabs(),this.updateCost(),i.id===this.activeSessionId&&i.tokens&&this.updateRespawnTokens(i.tokens),this.updateSubagentParentNames(i.id),l&&(this.recheckOrphanSubagents(),requestAnimationFrame(()=>{this.updateConnectionLines()}))}),t("session:deleted",s=>{const n=JSON.parse(s.data);if(this._cleanupSessionData(n.id),this.activeSessionId===n.id){this.activeSessionId=null;try{localStorage.removeItem("codeman-active-session")}catch{}this.terminal.clear(),this.showWelcome()}this.renderSessionTabs(),this.renderRalphStatePanel(),this.renderProjectInsightsPanel(),this.sessions.size===0&&this.stopSystemStatsPolling()}),t("session:terminal",s=>{const n=JSON.parse(s.data);n.id===this.activeSessionId&&this.batchTerminalWrite(n.data)}),t("session:needsRefresh",async()=>{if(!(!this.activeSessionId||!this.terminal))try{const i=await(await fetch(`/api/sessions/${this.activeSessionId}/terminal?tail=262144`)).json();i.terminalBuffer&&(this.terminal.clear(),this.terminal.reset(),await this.chunkedTerminalWrite(i.terminalBuffer),this.terminal.scrollToBottom(),this._localEchoOverlay?.rerender(),this.activeSessionId&&this.sendResize(this.activeSessionId))}catch{}}),t("session:clearTerminal",async s=>{const n=JSON.parse(s.data);if(n.id===this.activeSessionId)try{const o=await(await fetch(`/api/sessions/${n.id}/terminal`)).json();if(this.terminal.clear(),this.terminal.reset(),o.terminalBuffer){const l=o.terminalBuffer.replace(DEC_SYNC_STRIP_RE,"");await this.chunkedTerminalWrite(l)}this.sendResize(n.id),this._localEchoOverlay?.rerender()}catch{}}),t("session:completion",s=>{const n=JSON.parse(s.data);this.totalCost+=n.cost||0,this.updateCost(),n.id===this.activeSessionId&&(this.terminal.writeln(""),this.terminal.writeln(`\x1B[1;32m Done (Cost: $${(n.cost||0).toFixed(4)})\x1B[0m`))}),t("session:error",s=>{const n=JSON.parse(s.data);n.id===this.activeSessionId&&this.terminal.writeln(`\x1B[1;31m Error: ${n.error}\x1B[0m`);const i=this.sessions.get(n.id);this.notificationManager?.notify({urgency:"critical",category:"session-error",sessionId:n.id,sessionName:i?.name||n.id?.slice(0,8),title:"Session Error",message:n.error||"Unknown error"})}),t("session:exit",s=>{const n=JSON.parse(s.data),i=this.sessions.get(n.id);i&&(i.status="stopped",this.renderSessionTabs(),n.id===this.activeSessionId&&this._updateLocalEchoState()),n.code&&n.code!==0&&this.notificationManager?.notify({urgency:"critical",category:"session-crash",sessionId:n.id,sessionName:i?.name||n.id?.slice(0,8),title:"Session Crashed",message:`Exited with code ${n.code}`})}),t("session:idle",s=>{const n=JSON.parse(s.data),i=this.sessions.get(n.id);if(i&&(i.status="idle",this.renderSessionTabs(),this.sendPendingCtrlL(n.id),n.id===this.activeSessionId&&this._updateLocalEchoState()),!this.respawnStatus[n.id]?.enabled){const o=this.notificationManager?.preferences?.stuckThresholdMs||6e5;clearTimeout(this.idleTimers.get(n.id)),this.idleTimers.set(n.id,setTimeout(()=>{const l=this.sessions.get(n.id);this.notificationManager?.notify({urgency:"warning",category:"session-stuck",sessionId:n.id,sessionName:l?.name||n.id?.slice(0,8),title:"Session Idle",message:`Idle for ${Math.round(o/6e4)}+ minutes`}),this.idleTimers.delete(n.id)},o))}}),t("session:working",s=>{const n=JSON.parse(s.data),i=this.sessions.get(n.id);i&&(i.status="busy",this.pendingHooks.has(n.id)||this.tabAlerts.delete(n.id),this.renderSessionTabs(),this.sendPendingCtrlL(n.id),n.id===this.activeSessionId&&this._updateLocalEchoState());const o=this.idleTimers.get(n.id);o&&(clearTimeout(o),this.idleTimers.delete(n.id))}),t("scheduled:created",s=>{this.currentRun=JSON.parse(s.data),this.showTimer()}),t("scheduled:updated",s=>{this.currentRun=JSON.parse(s.data),this.updateTimer()}),t("scheduled:completed",s=>{this.currentRun=JSON.parse(s.data),this.hideTimer(),this.showToast("Scheduled run completed!","success")}),t("scheduled:stopped",s=>{this.currentRun=null,this.hideTimer()}),t("respawn:started",s=>{const n=JSON.parse(s.data);this.respawnStatus[n.sessionId]=n.status,n.sessionId===this.activeSessionId&&this.showRespawnBanner()}),t("respawn:stopped",s=>{const n=JSON.parse(s.data);delete this.respawnStatus[n.sessionId],n.sessionId===this.activeSessionId&&this.hideRespawnBanner()}),t("respawn:stateChanged",s=>{const n=JSON.parse(s.data);this.respawnStatus[n.sessionId]&&(this.respawnStatus[n.sessionId].state=n.state),n.sessionId===this.activeSessionId&&this.updateRespawnBanner(n.state)}),t("respawn:cycleStarted",s=>{const n=JSON.parse(s.data);this.respawnStatus[n.sessionId]&&(this.respawnStatus[n.sessionId].cycleCount=n.cycleNumber),n.sessionId===this.activeSessionId&&(document.getElementById("respawnCycleCount").textContent=n.cycleNumber)}),t("respawn:blocked",s=>{const n=JSON.parse(s.data),i=this.sessions.get(n.sessionId),l={circuit_breaker_open:"Circuit Breaker Open",exit_signal:"Exit Signal Detected",status_blocked:"Claude Reported BLOCKED"}[n.reason]||"Respawn Blocked";if(this.notificationManager?.notify({urgency:"critical",category:"respawn-blocked",sessionId:n.sessionId,sessionName:i?.name||n.sessionId?.slice(0,8),title:l,message:n.details}),n.sessionId===this.activeSessionId){const a=document.getElementById("respawnStateLabel");a&&(a.textContent=l,a.classList.add("respawn-blocked"))}}),t("respawn:stepSent",s=>{}),t("respawn:autoAcceptSent",s=>{const n=JSON.parse(s.data),i=this.sessions.get(n.sessionId);this.notificationManager?.notify({urgency:"info",category:"auto-accept",sessionId:n.sessionId,sessionName:i?.name||n.sessionId?.slice(0,8),title:"Plan Accepted",message:`Accepted plan mode for ${i?.name||"session"}`})}),t("respawn:detectionUpdate",s=>{const n=JSON.parse(s.data);this.respawnStatus[n.sessionId]&&(this.respawnStatus[n.sessionId].detection=n.detection),n.sessionId===this.activeSessionId&&this.updateDetectionDisplay(n.detection)}),t("respawn:aiCheckStarted",s=>{}),t("respawn:aiCheckCompleted",s=>{}),t("respawn:aiCheckFailed",s=>{}),t("respawn:aiCheckCooldown",s=>{}),t("respawn:timerStarted",s=>{const n=JSON.parse(s.data);this.respawnTimers[n.sessionId]={endAt:n.endAt,startedAt:n.startedAt,durationMinutes:n.durationMinutes},n.sessionId===this.activeSessionId&&this.showRespawnTimer()}),t("respawn:timerStarted",s=>{const n=JSON.parse(s.data);if(n.timer){const{sessionId:i,timer:o}=n;this.respawnCountdownTimers[i]||(this.respawnCountdownTimers[i]={}),this.respawnCountdownTimers[i][o.name]={endsAt:o.endsAt,totalMs:o.durationMs,reason:o.reason},i===this.activeSessionId&&(this.updateCountdownTimerDisplay(),this.startCountdownInterval())}}),t("respawn:timerCancelled",s=>{const n=JSON.parse(s.data),{sessionId:i,timerName:o}=n;this.respawnCountdownTimers[i]&&delete this.respawnCountdownTimers[i][o],i===this.activeSessionId&&this.updateCountdownTimerDisplay()}),t("respawn:timerCompleted",s=>{const n=JSON.parse(s.data),{sessionId:i,timerName:o}=n;this.respawnCountdownTimers[i]&&delete this.respawnCountdownTimers[i][o],i===this.activeSessionId&&this.updateCountdownTimerDisplay()}),t("respawn:error",s=>{const n=JSON.parse(s.data),i=this.sessions.get(n.sessionId);this.notificationManager?.notify({urgency:"critical",category:"session-error",sessionId:n.sessionId,sessionName:i?.name||n.sessionId,title:"Respawn Error",message:n.error||n.message||"Respawn encountered an error"})}),t("respawn:actionLog",s=>{const n=JSON.parse(s.data),{sessionId:i,action:o}=n;this.addActionLogEntry(i,o),i===this.activeSessionId&&(this.updateCountdownTimerDisplay(),this.updateActionLogDisplay())}),t("session:autoClear",s=>{const n=JSON.parse(s.data);n.sessionId===this.activeSessionId&&(this.showToast(`Auto-cleared at ${n.tokens.toLocaleString()} tokens`,"info"),this.updateRespawnTokens(0));const i=this.sessions.get(n.sessionId);this.notificationManager?.notify({urgency:"info",category:"auto-clear",sessionId:n.sessionId,sessionName:i?.name||n.sessionId?.slice(0,8),title:"Auto-Cleared",message:`Context reset at ${(n.tokens||0).toLocaleString()} tokens`})}),t("session:cliInfo",s=>{const n=JSON.parse(s.data),i=this.sessions.get(n.sessionId);i&&(n.version&&(i.cliVersion=n.version),n.model&&(i.cliModel=n.model),n.accountType&&(i.cliAccountType=n.accountType),n.latestVersion&&(i.cliLatestVersion=n.latestVersion)),n.sessionId===this.activeSessionId&&this.updateCliInfoDisplay()}),t("task:created",s=>{const n=JSON.parse(s.data);this.renderSessionTabs(),n.sessionId===this.activeSessionId&&this.renderTaskPanel()}),t("task:completed",s=>{const n=JSON.parse(s.data);this.renderSessionTabs(),n.sessionId===this.activeSessionId&&this.renderTaskPanel()}),t("task:failed",s=>{const n=JSON.parse(s.data);this.renderSessionTabs(),n.sessionId===this.activeSessionId&&this.renderTaskPanel()}),t("task:updated",s=>{JSON.parse(s.data).sessionId===this.activeSessionId&&this.renderTaskPanel()}),t("mux:created",s=>{const n=JSON.parse(s.data);this.muxSessions.push(n),this.renderMuxSessions()}),t("mux:killed",s=>{const n=JSON.parse(s.data);this.muxSessions=this.muxSessions.filter(i=>i.sessionId!==n.sessionId),this.renderMuxSessions()}),t("mux:died",s=>{const n=JSON.parse(s.data);this.muxSessions=this.muxSessions.filter(i=>i.sessionId!==n.sessionId),this.renderMuxSessions(),this.showToast("Mux session died: "+n.sessionId.slice(0,8),"warning")}),t("mux:statsUpdated",s=>{this.muxSessions=JSON.parse(s.data),document.getElementById("monitorPanel").classList.contains("open")&&this.renderMuxSessions()}),t("session:ralphLoopUpdate",s=>{const n=JSON.parse(s.data);this.ralphClosedSessions.has(n.sessionId)||this.updateRalphState(n.sessionId,{loop:n.state})}),t("session:ralphTodoUpdate",s=>{const n=JSON.parse(s.data);this.ralphClosedSessions.has(n.sessionId)||this.updateRalphState(n.sessionId,{todos:n.todos})}),t("session:ralphCompletionDetected",s=>{const n=JSON.parse(s.data);if(this.ralphClosedSessions.has(n.sessionId))return;const i=`${n.sessionId}:${n.phrase}`;if(this._shownCompletions?.has(i))return;this._shownCompletions||(this._shownCompletions=new Set),this._shownCompletions.add(i),setTimeout(()=>this._shownCompletions?.delete(i),3e4);const o=this.ralphStates.get(n.sessionId)||{};o.loop&&(o.loop.active=!1,this.updateRalphState(n.sessionId,o));const l=this.sessions.get(n.sessionId);this.notificationManager?.notify({urgency:"warning",category:"ralph-complete",sessionId:n.sessionId,sessionName:l?.name||n.sessionId?.slice(0,8),title:"Loop Complete",message:`Completion: ${n.phrase||"unknown"}`})}),t("session:ralphStatusUpdate",s=>{const n=JSON.parse(s.data);this.ralphClosedSessions.has(n.sessionId)||this.updateRalphState(n.sessionId,{statusBlock:n.block})}),t("session:circuitBreakerUpdate",s=>{const n=JSON.parse(s.data);if(!this.ralphClosedSessions.has(n.sessionId)&&(this.updateRalphState(n.sessionId,{circuitBreaker:n.status}),n.status.state==="OPEN")){const i=this.sessions.get(n.sessionId);this.notificationManager?.notify({urgency:"critical",category:"circuit-breaker",sessionId:n.sessionId,sessionName:i?.name||n.sessionId?.slice(0,8),title:"Circuit Breaker Open",message:n.status.reason||"Loop stuck - no progress detected"})}}),t("session:exitGateMet",s=>{const n=JSON.parse(s.data),i=this.sessions.get(n.sessionId);this.notificationManager?.notify({urgency:"warning",category:"exit-gate",sessionId:n.sessionId,sessionName:i?.name||n.sessionId?.slice(0,8),title:"Exit Gate Met",message:`Loop ready to exit (indicators: ${n.completionIndicators})`})}),t("session:bashToolStart",s=>{const n=JSON.parse(s.data);this.handleBashToolStart(n.sessionId,n.tool)}),t("session:bashToolEnd",s=>{const n=JSON.parse(s.data);this.handleBashToolEnd(n.sessionId,n.tool)}),t("session:bashToolsUpdate",s=>{const n=JSON.parse(s.data);this.handleBashToolsUpdate(n.sessionId,n.tools)}),t("hook:idle_prompt",s=>{const n=JSON.parse(s.data),i=this.sessions.get(n.sessionId);n.sessionId&&this.setPendingHook(n.sessionId,"idle_prompt"),this.notificationManager?.notify({urgency:"warning",category:"hook-idle",sessionId:n.sessionId,sessionName:i?.name||n.sessionId,title:"Waiting for Input",message:n.message||"Claude is idle and waiting for a prompt"})}),t("hook:permission_prompt",s=>{const n=JSON.parse(s.data),i=this.sessions.get(n.sessionId);n.sessionId&&this.setPendingHook(n.sessionId,"permission_prompt");const o=n.tool?`${n.tool}${n.command?": "+n.command:n.file?": "+n.file:""}`:"";this.notificationManager?.notify({urgency:"critical",category:"hook-permission",sessionId:n.sessionId,sessionName:i?.name||n.sessionId,title:"Permission Required",message:o||"Claude needs tool approval to continue"})}),t("hook:elicitation_dialog",s=>{const n=JSON.parse(s.data),i=this.sessions.get(n.sessionId);n.sessionId&&this.setPendingHook(n.sessionId,"elicitation_dialog"),this.notificationManager?.notify({urgency:"critical",category:"hook-elicitation",sessionId:n.sessionId,sessionName:i?.name||n.sessionId,title:"Question Asked",message:n.question||"Claude is asking a question and waiting for your answer"})}),t("hook:stop",s=>{const n=JSON.parse(s.data),i=this.sessions.get(n.sessionId);n.sessionId&&this.clearPendingHooks(n.sessionId),this.notificationManager?.notify({urgency:"info",category:"hook-stop",sessionId:n.sessionId,sessionName:i?.name||n.sessionId,title:"Response Complete",message:n.reason||"Claude has finished responding"})}),t("hook:teammate_idle",s=>{const n=JSON.parse(s.data),i=this.sessions.get(n.sessionId);this.notificationManager?.notify({urgency:"warning",category:"hook-teammate-idle",sessionId:n.sessionId,sessionName:i?.name||n.sessionId,title:"Teammate Idle",message:`A teammate is idle in ${i?.name||n.sessionId}`})}),t("hook:task_completed",s=>{const n=JSON.parse(s.data),i=this.sessions.get(n.sessionId);this.notificationManager?.notify({urgency:"info",category:"hook-task-completed",sessionId:n.sessionId,sessionName:i?.name||n.sessionId,title:"Task Completed",message:`A team task completed in ${i?.name||n.sessionId}`})}),t("subagent:discovered",s=>{const n=JSON.parse(s.data);if(this.subagents.set(n.agentId,n),this.subagentActivity.set(n.agentId,[]),this.subagentToolResults.delete(n.agentId),this.subagentWindows.has(n.agentId)&&this.forceCloseSubagentWindow(n.agentId),this.renderSubagentPanel(),this.findParentSessionForSubagent(n.agentId),n.status==="active"){const l=this.subagents.get(n.agentId);l?.sessionId&&Array.from(this.sessions.values()).some(r=>r.claudeSessionId===l.sessionId)&&this.openSubagentWindow(n.agentId)}requestAnimationFrame(()=>{this.updateConnectionLines()});const i=this.subagentParentMap.get(n.agentId),o=i?this.sessions.get(i):null;this.notificationManager?.notify({urgency:"info",category:"subagent-spawn",sessionId:i||n.sessionId,sessionName:o?.name||i||n.sessionId,title:"Subagent Spawned",message:n.description||"New background agent started"})}),t("subagent:updated",s=>{const n=JSON.parse(s.data),i=this.subagents.get(n.agentId);i?(Object.assign(i,n),this.subagents.set(n.agentId,i)):this.subagents.set(n.agentId,n),this.renderSubagentPanel(),this.subagentWindows.has(n.agentId)&&(this.renderSubagentWindowContent(n.agentId),this.updateSubagentWindowHeader(n.agentId))}),t("subagent:tool_call",s=>{const n=JSON.parse(s.data),i=this.subagentActivity.get(n.agentId)||[];i.push({type:"tool",...n}),i.length>50&&i.shift(),this.subagentActivity.set(n.agentId,i),this.activeSubagentId===n.agentId&&this.renderSubagentDetail(),this.renderSubagentPanel(),this.subagentWindows.has(n.agentId)&&this.renderSubagentWindowContent(n.agentId)}),t("subagent:progress",s=>{const n=JSON.parse(s.data),i=this.subagentActivity.get(n.agentId)||[];i.push({type:"progress",...n}),i.length>50&&i.shift(),this.subagentActivity.set(n.agentId,i),this.activeSubagentId===n.agentId&&this.renderSubagentDetail(),this.subagentWindows.has(n.agentId)&&this.renderSubagentWindowContent(n.agentId)}),t("subagent:message",s=>{const n=JSON.parse(s.data),i=this.subagentActivity.get(n.agentId)||[];i.push({type:"message",...n}),i.length>50&&i.shift(),this.subagentActivity.set(n.agentId,i),this.activeSubagentId===n.agentId&&this.renderSubagentDetail(),this.subagentWindows.has(n.agentId)&&this.renderSubagentWindowContent(n.agentId)}),t("subagent:tool_result",s=>{const n=JSON.parse(s.data);this.subagentToolResults.has(n.agentId)||this.subagentToolResults.set(n.agentId,new Map);const i=this.subagentToolResults.get(n.agentId);if(i.set(n.toolUseId,n),i.size>50){const l=i.keys().next().value;i.delete(l)}const o=this.subagentActivity.get(n.agentId)||[];o.push({type:"tool_result",...n}),o.length>50&&o.shift(),this.subagentActivity.set(n.agentId,o),this.activeSubagentId===n.agentId&&this.renderSubagentDetail(),this.subagentWindows.has(n.agentId)&&this.renderSubagentWindowContent(n.agentId)}),t("subagent:completed",async s=>{const n=JSON.parse(s.data),i=this.subagents.get(n.agentId);if(i&&(i.status="completed",this.subagents.set(n.agentId,i)),this.renderSubagentPanel(),this.updateSubagentWindows(),this.subagentWindows.has(n.agentId)){const a=this.subagentWindows.get(n.agentId);a&&!a.minimized&&(await this.closeSubagentWindow(n.agentId),this.saveSubagentWindowStates())}const o=this.subagentParentMap.get(n.agentId),l=o?this.sessions.get(o):null;this.notificationManager?.notify({urgency:"info",category:"subagent-complete",sessionId:o||i?.sessionId||n.sessionId,sessionName:l?.name||o||n.sessionId,title:"Subagent Completed",message:i?.description||n.description||"Background agent finished"}),setTimeout(()=>{this.subagents.get(n.agentId)?.status==="completed"&&(this.subagentActivity.delete(n.agentId),this.subagentToolResults.delete(n.agentId))},300*1e3),setTimeout(()=>{this.subagents.get(n.agentId)?.status==="completed"&&!this.subagentWindows.has(n.agentId)&&(this.subagents.delete(n.agentId),this.subagentParentMap.delete(n.agentId))},1800*1e3)}),t("image:detected",s=>{const n=JSON.parse(s.data);this.openImagePopup(n)}),t("tunnel:started",s=>{const n=JSON.parse(s.data);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())}),t("tunnel:stopped",()=>{this._dismissTunnelConnecting(),this._updateTunnelUrlDisplay(null),this._updateWelcomeTunnelBtn(!1),this.closeTunnelQR()}),t("tunnel:progress",s=>{const n=JSON.parse(s.data),i=document.getElementById("tunnelConnectingToast");i&&(i.innerHTML=`<span class="tunnel-spinner"></span> ${n.message}`);const o=document.getElementById("welcomeTunnelBtn");o?.classList.contains("connecting")&&(o.innerHTML=`<span class="tunnel-spinner"></span> ${n.message}`)}),t("tunnel:error",s=>{const n=JSON.parse(s.data);this._dismissTunnelConnecting(),this.showToast(`Tunnel error: ${n.message}`,"error");const i=document.getElementById("welcomeTunnelBtn");i&&(i.disabled=!1,i.classList.remove("connecting"))}),t("plan:subagent",s=>{const n=JSON.parse(s.data);this.handlePlanSubagentEvent(n)}),t("plan:progress",s=>{const n=JSON.parse(s.data);this._planProgressHandler&&this._planProgressHandler({type:"plan:progress",data:n});const i=document.getElementById("planLoadingTitle"),o=document.getElementById("planLoadingHint");if(i&&n.phase){const l={"parallel-analysis":"Running parallel analysis...",subagent:n.detail||"Subagent working...",synthesis:"Synthesizing results...",verification:"Running verification..."};i.textContent=l[n.phase]||n.phase}o&&n.detail&&(o.textContent=n.detail)}),t("plan:started",s=>{const n=JSON.parse(s.data);this.activePlanOrchestratorId=n.orchestratorId,this.planGenerationStopped=!1,this.renderMonitorPlanAgents()}),t("plan:cancelled",s=>{const n=JSON.parse(s.data);this.activePlanOrchestratorId===n.orchestratorId&&(this.activePlanOrchestratorId=null),this.renderMonitorPlanAgents()}),t("plan:completed",s=>{const n=JSON.parse(s.data);this.activePlanOrchestratorId===n.orchestratorId&&(this.activePlanOrchestratorId=null),this.renderMonitorPlanAgents()})}setConnectionStatus(e){this._connectionStatus=e,this._updateConnectionIndicator(),e==="connected"&&this._inputQueue.size>0&&this._drainInputQueues()}_sendInputAsync(e,t){if(!this.isOnline||this._connectionStatus==="disconnected"){this._enqueueInput(e,t);return}this._inputSendChain=this._inputSendChain.then(()=>{fetch(`/api/sessions/${e}/input`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({input:t}),keepalive:t.length<65536}).then(n=>{n.ok?this.clearPendingHooks(e):this._enqueueInput(e,t)}).catch(()=>{this._enqueueInput(e,t)})})}_enqueueInput(e,t){let n=(this._inputQueue.get(e)||"")+t;n.length>this._inputQueueMaxBytes&&(n=n.slice(n.length-this._inputQueueMaxBytes)),this._inputQueue.set(e,n),this._updateConnectionIndicator()}async _drainInputQueues(){if(this._inputQueue.size===0)return;const e=new Map(this._inputQueue);this._inputQueue.clear(),this._updateConnectionIndicator();for(const[t,s]of e)try{(await fetch(`/api/sessions/${t}/input`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({input:s})})).ok||this._enqueueInput(t,s)}catch{this._enqueueInput(t,s)}this._updateConnectionIndicator()}_updateConnectionIndicator(){const e=this.$("connectionIndicator"),t=this.$("connectionDot"),s=this.$("connectionText");if(!e||!t||!s)return;let n=0;for(const a of this._inputQueue.values())n+=a.length;const i=this._connectionStatus,o=n>0;if((i==="connected"||i==="connecting")&&!o){e.style.display="none";return}e.style.display="flex",t.className="connection-dot";const l=a=>a<1024?`${a}B`:`${(a/1024).toFixed(1)}KB`;i==="connected"&&o?(t.classList.add("draining"),s.textContent=`Sending ${l(n)}...`):i==="reconnecting"?(t.classList.add("reconnecting"),s.textContent=o?`Reconnecting (${l(n)} queued)`:"Reconnecting..."):(t.classList.add("offline"),s.textContent=o?`Offline (${l(n)} queued)`:"Offline")}setupOnlineDetection(){window.addEventListener("online",()=>{this.isOnline=!0,this.reconnectAttempts=0,this.connectSSE()}),window.addEventListener("offline",()=>{this.isOnline=!1,this.setConnectionStatus("offline")})}handleInit(e){this._initFallbackTimer&&(clearTimeout(this._initFallbackTimer),this._initFallbackTimer=null);const t=++this._initGeneration;if(e.version){const i=this.$("versionDisplay"),o=this.$("headerVersion");i&&(i.textContent=`v${e.version}`,i.title=`Codeman v${e.version}`),o&&(o.textContent=`v${e.version}`,o.title=`Codeman v${e.version}`)}VoiceInput.cleanup(),this.sessions.clear(),this.ralphStates.clear(),this.terminalBuffers.clear(),this.terminalBufferCache.clear(),this.projectInsights.clear(),this.teams.clear(),this.teamTasks.clear();for(const i of this.idleTimers.values())clearTimeout(i);if(this.idleTimers.clear(),this.flickerFilterTimeout&&(clearTimeout(this.flickerFilterTimeout),this.flickerFilterTimeout=null),this.flickerFilterBuffer="",this.flickerFilterActive=!1,this.syncWaitTimeout&&(clearTimeout(this.syncWaitTimeout),this.syncWaitTimeout=null),this.pendingWrites=[],this.writeFrameScheduled=!1,this._isLoadingBuffer=!1,this._loadBufferQueue=null,this._localEchoOverlay?.rerender(),this.pendingHooks.clear(),this._parentNameCache&&this._parentNameCache.clear(),this.subagentActivity.clear(),this.subagentToolResults.clear(),MobileDetection.cleanup(),KeyboardHandler.cleanup(),MobileDetection.init(),KeyboardHandler.init(),this.tabAlerts.clear(),this._shownCompletions&&this._shownCompletions.clear(),this.notificationManager?.titleFlashInterval&&(clearInterval(this.notificationManager.titleFlashInterval),this.notificationManager.titleFlashInterval=null),this.notificationManager?.groupingMap){for(const{timeout:i}of this.notificationManager.groupingMap.values())clearTimeout(i);this.notificationManager.groupingMap.clear()}this.terminalResizeObserver&&(this.terminalResizeObserver.disconnect(),this.terminalResizeObserver=null),this.planLoadingTimer&&(clearInterval(this.planLoadingTimer),this.planLoadingTimer=null),this.timerCountdownInterval&&(clearInterval(this.timerCountdownInterval),this.timerCountdownInterval=null),this.runSummaryAutoRefreshTimer&&(clearInterval(this.runSummaryAutoRefreshTimer),this.runSummaryAutoRefreshTimer=null),e.sessions.forEach(i=>{this.sessions.set(i.id,i),(i.ralphLoop||i.ralphTodos)&&!this.ralphClosedSessions.has(i.id)&&this.ralphStates.set(i.id,{loop:i.ralphLoop||null,todos:i.ralphTodos||[]})}),this.syncSessionOrder(),e.respawnStatus?this.respawnStatus=e.respawnStatus:this.respawnStatus={},this.respawnTimers={},this.respawnCountdownTimers={},this.respawnActionLogs={},e.globalStats&&(this.globalStats=e.globalStats),this.totalCost=e.sessions.reduce((i,o)=>i+(o.totalCost||0),0),this.totalCost+=e.scheduledRuns.reduce((i,o)=>i+(o.totalCost||0),0);const s=e.scheduledRuns.find(i=>i.status==="running");if(s&&(this.currentRun=s,this.showTimer()),this.updateCost(),this.renderSessionTabs(),this.sessions.size>0?this.startSystemStatsPolling():this.stopSystemStatsPolling(),this.cleanupAllFloatingWindows(),e.subagents&&(this.subagents.clear(),this.subagentActivity.clear(),this.subagentToolResults.clear(),e.subagents.forEach(i=>{this.subagents.set(i.agentId,i)}),this.renderSubagentPanel(),this.subagentParentMap.clear(),this.loadSubagentParentMap().then(()=>{for(const[i,o]of this.subagentParentMap){const l=this.subagents.get(i);if(l&&this.sessions.has(o)){l.parentSessionId=o;const a=this.sessions.get(o);a&&(l.parentSessionName=this.getSessionName(a)),this.subagents.set(i,l)}}for(const[i]of this.subagents)this.subagentParentMap.has(i)||this.findParentSessionForSubagent(i);this.restoreSubagentWindowStates()})),t!==this._initGeneration)return;const n=this.activeSessionId;if(this.activeSessionId=null,this.sessionOrder.length>0){let i=n;if(!i||!this.sessions.has(i))try{i=localStorage.getItem("codeman-active-session")}catch{}i&&this.sessions.has(i)?this.selectSession(i):this.selectSession(this.sessionOrder[0])}}async loadState(){try{const t=await(await fetch("/api/status")).json();this.handleInit(t)}catch{}}renderSessionTabs(){this.renderSessionTabsTimeout&&clearTimeout(this.renderSessionTabsTimeout),this.renderSessionTabsTimeout=setTimeout(()=>{this._renderSessionTabsImmediate()},100)}_updateActiveTabImmediate(e){const t=this.$("sessionTabs");if(!t)return;const s=t.querySelectorAll(".session-tab[data-id]");for(const n of s)n.dataset.id===e?n.classList.add("active"):n.classList.remove("active")}_renderSessionTabsImmediate(){const e=this.$("sessionTabs"),t=e.querySelectorAll(".session-tab[data-id]"),s=new Set([...t].map(o=>o.dataset.id)),n=new Set(this.sessions.keys());if(s.size===n.size&&[...s].every(o=>n.has(o)))for(const[o,l]of this.sessions){const a=e.querySelector(`.session-tab[data-id="${o}"]`);if(!a)continue;const r=o===this.activeSessionId,c=l.status||"idle",h=this.getSessionName(l),u=l.taskStats||{running:0,total:0},m=u.running>0;r&&!a.classList.contains("active")?a.classList.add("active"):!r&&a.classList.contains("active")&&a.classList.remove("active");const p=this.tabAlerts.get(o),g=p==="action",y=p==="idle",f=a.classList.contains("tab-alert-action"),w=a.classList.contains("tab-alert-idle");g&&!f?(a.classList.add("tab-alert-action"),a.classList.remove("tab-alert-idle")):y&&!w?(a.classList.add("tab-alert-idle"),a.classList.remove("tab-alert-action")):!p&&(f||w)&&a.classList.remove("tab-alert-action","tab-alert-idle");const v=a.querySelector(".tab-status");v&&!v.classList.contains(c)&&(v.className=`tab-status ${c}`);const S=a.querySelector(".tab-name");S&&S.textContent!==h&&(S.textContent=h);const b=a.querySelector(".tab-badge");if(m)if(b)b.textContent!==String(u.running)&&(b.textContent=u.running);else{this._fullRenderSessionTabs();return}else if(b){this._fullRenderSessionTabs();return}const T=a.querySelector(".tab-subagent-badge"),C=this.minimizedSubagents.get(o)?.size||0,B=T?parseInt(T.querySelector(".subagent-count")?.textContent||"0"):0;if(C!==B){this._fullRenderSessionTabs();return}}else this._fullRenderSessionTabs()}_fullRenderSessionTabs(){const e=this.$("sessionTabs");document.querySelectorAll("body > .subagent-dropdown").forEach(n=>n.remove()),this.cancelHideSubagentDropdown();const t=[];let s=this.sessionOrder;MobileDetection.getDeviceType()==="mobile"&&this.activeSessionId&&(s=[this.activeSessionId,...this.sessionOrder.filter(n=>n!==this.activeSessionId)]);for(const n of s){const i=this.sessions.get(n);if(!i)continue;const o=n===this.activeSessionId,l=i.status||"idle",a=this.getSessionName(i),r=i.mode||"claude",c=i.color||"default",h=i.taskStats||{running:0,total:0},u=h.running>0,m=this.tabAlerts.get(n),p=m==="action"?" tab-alert-action":m==="idle"?" tab-alert-idle":"",g=this.minimizedSubagents.get(n),f=(g?.size||0)>0?this.renderSubagentTabBadge(n,g):"",w=i.workingDir&&i.workingDir.split("/").pop()||"",S=(this._tallTabsEnabled??!1)&&i.name&&w&&w!==a;t.push(`<div class="session-tab ${o?"active":""}${p}" data-id="${n}" data-color="${c}" onclick="app.selectSession('${this.escapeHtml(n)}')" oncontextmenu="event.preventDefault(); app.startInlineRename('${this.escapeHtml(n)}')" tabindex="0" role="tab" aria-selected="${o?"true":"false"}" aria-label="${this.escapeHtml(a)} session" ${i.workingDir?`title="${this.escapeHtml(i.workingDir)}"`:""}>
|
|
51
|
+
<span class="tab-status ${l}" aria-hidden="true"></span>
|
|
52
|
+
<span class="tab-info">
|
|
53
|
+
<span class="tab-name-row">
|
|
54
|
+
${r==="shell"?'<span class="tab-mode shell" aria-hidden="true">sh</span>':r==="opencode"?'<span class="tab-mode opencode" aria-hidden="true">oc</span>':""}
|
|
55
|
+
<span class="tab-name" data-session-id="${n}">${this.escapeHtml(a)}</span>
|
|
56
|
+
</span>
|
|
57
|
+
${S?`<span class="tab-folder">\u{1F4C1} ${this.escapeHtml(w)}</span>`:""}
|
|
58
|
+
</span>
|
|
59
|
+
${u?`<span class="tab-badge" onclick="event.stopPropagation(); app.toggleTaskPanel()" aria-label="${h.running} running tasks">${h.running}</span>`:""}
|
|
60
|
+
${f}
|
|
61
|
+
<span class="tab-gear" onclick="event.stopPropagation(); app.openSessionOptions('${this.escapeHtml(n)}')" title="Session options" aria-label="Session options" tabindex="0">⚙</span>
|
|
62
|
+
<span class="tab-close" onclick="event.stopPropagation(); app.requestCloseSession('${this.escapeHtml(n)}')" title="Close session" aria-label="Close session" tabindex="0">×</span>
|
|
63
|
+
</div>`)}e.innerHTML=t.join(""),this.setupTabDragHandlers(),this.setupTabKeyboardNavigation(e),this.updateConnectionLines()}setupTabKeyboardNavigation(e){this._tabKeydownHandler&&e.removeEventListener("keydown",this._tabKeydownHandler),this._tabKeydownHandler=t=>{if(!["ArrowLeft","ArrowRight","Home","End","Enter"," "].includes(t.key))return;const s=[...e.querySelectorAll(".session-tab")],n=s.indexOf(document.activeElement);if((t.key==="Enter"||t.key===" ")&&n>=0){t.preventDefault();const o=s[n].dataset.id;this.selectSession(o);return}if(n<0)return;let i;switch(t.key){case"ArrowLeft":i=n>0?n-1:s.length-1;break;case"ArrowRight":i=n<s.length-1?n+1:0;break;case"Home":i=0;break;case"End":i=s.length-1;break;default:return}t.preventDefault(),s[i]?.focus()},e.addEventListener("keydown",this._tabKeydownHandler)}renderSubagentTabBadge(e,t){if(!t||t.size===0)return"";const s=[];for(const o of t){const l=this.subagents.get(o),a=l?.description||o.substring(0,12),r=a.length>25?a.substring(0,25)+"\u2026":a,c=l?.status||"idle";s.push(`
|
|
64
|
+
<div class="subagent-dropdown-item" onclick="event.stopPropagation(); app.restoreMinimizedSubagent('${this.escapeHtml(o)}', '${this.escapeHtml(e)}')" title="Click to restore">
|
|
65
|
+
<span class="subagent-dropdown-status ${c}"></span>
|
|
66
|
+
<span class="subagent-dropdown-name">${this.escapeHtml(r)}</span>
|
|
67
|
+
<span class="subagent-dropdown-close" onclick="event.stopPropagation(); app.permanentlyCloseMinimizedSubagent('${this.escapeHtml(o)}', '${this.escapeHtml(e)}')" title="Dismiss">×</span>
|
|
68
|
+
</div>
|
|
69
|
+
`)}const n=t.size;return`
|
|
70
|
+
<span class="tab-subagent-badge"
|
|
71
|
+
onmouseenter="app.showSubagentDropdown(this)"
|
|
72
|
+
onmouseleave="app.scheduleHideSubagentDropdown(this)"
|
|
73
|
+
onclick="event.stopPropagation(); app.pinSubagentDropdown(this);">
|
|
74
|
+
<span class="subagent-label">${n===1?"AGENT":`AGENTS (${n})`}</span>
|
|
75
|
+
<div class="subagent-dropdown" onmouseenter="app.cancelHideSubagentDropdown()" onmouseleave="app.scheduleHideSubagentDropdown(this.parentElement)">
|
|
76
|
+
${s.join("")}
|
|
77
|
+
</div>
|
|
78
|
+
</span>
|
|
79
|
+
`}syncSessionOrder(){const e=new Set(this.sessions.keys()),s=this.loadSessionOrder().filter(o=>e.has(o)),n=new Set(s),i=[...e].filter(o=>!n.has(o));this.sessionOrder=[...s,...i]}loadSessionOrder(){try{const e=localStorage.getItem("codeman-session-order");return e?JSON.parse(e):[]}catch{return[]}}saveSessionOrder(){try{localStorage.setItem("codeman-session-order",JSON.stringify(this.sessionOrder))}catch{}}setupTabDragHandlers(){const e=this.$("sessionTabs");e.querySelectorAll(".session-tab[data-id]").forEach(s=>{s.setAttribute("draggable","true"),s.addEventListener("dragstart",n=>{this.draggedTabId=s.dataset.id,s.classList.add("dragging"),n.dataTransfer.effectAllowed="move",n.dataTransfer.setData("text/plain",s.dataset.id)}),s.addEventListener("dragend",()=>{s.classList.remove("dragging"),this.draggedTabId=null,e.querySelectorAll(".session-tab").forEach(n=>{n.classList.remove("drag-over-left","drag-over-right")})}),s.addEventListener("dragover",n=>{if(n.preventDefault(),!this.draggedTabId||this.draggedTabId===s.dataset.id)return;n.dataTransfer.dropEffect="move";const i=s.getBoundingClientRect(),o=i.left+i.width/2,l=n.clientX<o;s.classList.toggle("drag-over-left",l),s.classList.toggle("drag-over-right",!l)}),s.addEventListener("dragleave",()=>{s.classList.remove("drag-over-left","drag-over-right")}),s.addEventListener("drop",n=>{if(n.preventDefault(),s.classList.remove("drag-over-left","drag-over-right"),!this.draggedTabId||this.draggedTabId===s.dataset.id)return;const i=s.dataset.id,o=this.draggedTabId,l=s.getBoundingClientRect(),a=l.left+l.width/2,r=n.clientX<a,c=this.sessionOrder.indexOf(o);let h=this.sessionOrder.indexOf(i);c===-1||h===-1||(this.sessionOrder.splice(c,1),h=this.sessionOrder.indexOf(i),h!==-1&&(r?this.sessionOrder.splice(h,0,o):this.sessionOrder.splice(h+1,0,o),this.saveSessionOrder(),this._fullRenderSessionTabs()))})})}restoreMinimizedSubagent(e,t){const s=this.minimizedSubagents.get(t);s&&(s.delete(e),s.size===0&&this.minimizedSubagents.delete(t)),this.restoreSubagentWindow(e),this.renderSessionTabs(),this.saveSubagentWindowStates()}showSubagentDropdown(e){this.cancelHideSubagentDropdown();const t=e.querySelector(".subagent-dropdown");if(!t||t.classList.contains("open"))return;document.querySelectorAll(".subagent-dropdown.open").forEach(n=>{n.classList.remove("open","pinned"),n.parentElement===document.body&&n._originalParent&&n._originalParent.appendChild(n)}),t._originalParent=e,document.body.appendChild(t);const s=e.getBoundingClientRect();t.style.top=`${s.bottom+2}px`,t.style.left=`${s.left+s.width/2}px`,t.style.transform="translateX(-50%)",t.classList.add("open")}scheduleHideSubagentDropdown(e){this._subagentHideTimeout=setTimeout(()=>{const t=e?.querySelector?.(".subagent-dropdown")||document.querySelector(".subagent-dropdown.open");t&&!t.classList.contains("pinned")&&(t.classList.remove("open"),t._originalParent&&t._originalParent.appendChild(t))},150)}cancelHideSubagentDropdown(){this._subagentHideTimeout&&(clearTimeout(this._subagentHideTimeout),this._subagentHideTimeout=null)}pinSubagentDropdown(e){const t=document.querySelector(".subagent-dropdown.open");if(!t){this.showSubagentDropdown(e);const s=document.querySelector(".subagent-dropdown.open");if(s){s.classList.add("pinned");const n=i=>{!e.contains(i.target)&&!s.contains(i.target)&&(s.classList.remove("open","pinned"),s._originalParent&&s._originalParent.appendChild(s),document.removeEventListener("click",n))};setTimeout(()=>document.addEventListener("click",n),0)}return}if(t.classList.toggle("pinned"),t.classList.contains("pinned")){const s=n=>{!e.contains(n.target)&&!t.contains(n.target)&&(t.classList.remove("open","pinned"),t._originalParent&&t._originalParent.appendChild(t),document.removeEventListener("click",s))};setTimeout(()=>document.addEventListener("click",s),0)}}permanentlyCloseMinimizedSubagent(e,t){const s=this.minimizedSubagents.get(t);s&&(s.delete(e),s.size===0&&this.minimizedSubagents.delete(t)),this.forceCloseSubagentWindow(e),this.renderSessionTabs(),this.updateConnectionLines(),this.saveSubagentWindowStates()}getSessionName(e){return e.name?e.name:e.workingDir?e.workingDir.split("/").pop()||e.workingDir:e.id.slice(0,8)}async selectSession(e){if(this.activeSessionId===e)return;const t=++this._selectGeneration;if(t!==this._selectGeneration)return;this.flickerFilterTimeout&&(clearTimeout(this.flickerFilterTimeout),this.flickerFilterTimeout=null),this.flickerFilterBuffer="",this.flickerFilterActive=!1,this._tabCompletionSessionId=null,this._tabCompletionRetries=0,this._tabCompletionBaseText=null,this._tabCompletionFallback&&(clearTimeout(this._tabCompletionFallback),this._tabCompletionFallback=null),this.syncWaitTimeout&&(clearTimeout(this.syncWaitTimeout),this.syncWaitTimeout=null),this.pendingWrites=[],this.writeFrameScheduled=!1,this._isLoadingBuffer=!1,this._loadBufferQueue=null;try{const i=this.terminal?._core?._compositionHelper;if(i?._isComposing){i._isComposing=!1;const o=this.terminal?.element?.querySelector(".xterm-helper-textarea");o&&o.dispatchEvent(new CompositionEvent("compositionend",{data:""}))}}catch{}if(this.activeSessionId){const i=this._localEchoOverlay?.pendingText||"",o=this._localEchoOverlay?.getFlushed()?.count||0,l=this._localEchoOverlay?.getFlushed()?.text||"";i&&this._sendInputAsync(this.activeSessionId,i);const a=o+i.length;a>0&&(this._flushedOffsets||(this._flushedOffsets=new Map),this._flushedTexts||(this._flushedTexts=new Map),this._flushedOffsets.set(this.activeSessionId,a),this._flushedTexts.set(this.activeSessionId,l+i))}this._localEchoOverlay?.clear(),this._localEchoOverlay&&!this._flushedOffsets?.has(e)&&this._localEchoOverlay.suppressBufferDetection(),this.activeSessionId=e;try{localStorage.setItem("codeman-active-session",e)}catch{}this.hideWelcome(),this.clearPendingHooks(e,"idle_prompt"),this._updateActiveTabImmediate(e),this.renderSessionTabs(),this._updateLocalEchoState(),this._flushedOffsets?.has(e)&&this._localEchoOverlay&&this._localEchoOverlay.setFlushed(this._flushedOffsets.get(e),this._flushedTexts?.get(e)||"",!1);const s=document.querySelector(`.session-tab.active[data-id="${e}"]`);s&&(s.classList.add("tab-glow"),s.addEventListener("animationend",()=>s.classList.remove("tab-glow"),{once:!0}));const n=this.sessions.get(e);if(this.currentSessionWorkingDir=n?.workingDir||null,n&&n.pid===null&&n.status==="idle")try{await fetch(`/api/sessions/${e}/interactive`,{method:"POST"}),n.status="busy"}catch{}this._restoringFlushedState=!0;try{const i=this.terminalBufferCache.get(e);i&&(this.terminal.clear(),this.terminal.reset(),this.terminal.write(i),this.terminal.scrollToBottom());const o=256*1024,l=await fetch(`/api/sessions/${e}/terminal?tail=${o}`);if(t!==this._selectGeneration){this._restoringFlushedState=!1;return}const a=await l.json();if(a.terminalBuffer){if(a.terminalBuffer!==i){if(this.terminal.clear(),this.terminal.reset(),a.truncated&&this.terminal.write(`\x1B[90m... (earlier output truncated for performance) ...\x1B[0m\r
|
|
80
|
+
\r
|
|
81
|
+
`),await this.chunkedTerminalWrite(a.terminalBuffer),t!==this._selectGeneration){this._restoringFlushedState=!1;return}this.terminal.scrollToBottom()}if(this.terminalBufferCache.set(e,a.terminalBuffer),this.terminalBufferCache.size>20){const h=this.terminalBufferCache.keys().next().value;this.terminalBufferCache.delete(h)}}else i||(this.terminal.clear(),this.terminal.reset());if(this._restoringFlushedState=!1,this._flushedOffsets?.has(e)&&this._localEchoOverlay){this._localEchoOverlay.setFlushed(this._flushedOffsets.get(e),this._flushedTexts?.get(e)||"",!1);const c=this._localEchoOverlay;this.terminal.write("",()=>{c.hasPending&&c.rerender()})}this.sendResize(e),(typeof requestIdleCallback=="function"?requestIdleCallback:c=>setTimeout(c,16))(()=>{if(t!==this._selectGeneration)return;this.respawnStatus[e]?(this.showRespawnBanner(),this.updateRespawnBanner(this.respawnStatus[e].state),document.getElementById("respawnCycleCount").textContent=this.respawnStatus[e].cycleCount||0,this.updateCountdownTimerDisplay(),this.updateActionLogDisplay(),Object.keys(this.respawnCountdownTimers[e]||{}).length>0&&this.startCountdownInterval()):(this.hideRespawnBanner(),this.stopCountdownInterval());const c=document.getElementById("taskPanel");c&&c.classList.contains("open")&&this.renderTaskPanel();const h=this.sessions.get(e);if(h&&(h.ralphLoop||h.ralphTodos)&&this.updateRalphState(e,{loop:h.ralphLoop,todos:h.ralphTodos}),this.renderRalphStatePanel(),this.updateCliInfoDisplay(),this.renderProjectInsightsPanel(),this.updateSubagentWindowVisibility(),this.loadAppSettingsFromStorage().showFileBrowser){const m=this.$("fileBrowserPanel");m&&(m.classList.add("visible"),this.loadFileBrowser(e))}}),this.terminal.focus(),this.terminal.scrollToBottom()}catch{this._restoringFlushedState=!1}}_cleanupSessionData(e){this.sessions.delete(e);const t=this.sessionOrder.indexOf(e);t!==-1&&(this.sessionOrder.splice(t,1),this.saveSessionOrder()),this.terminalBuffers.delete(e),this.terminalBufferCache.delete(e),this._flushedOffsets?.delete(e),this._flushedTexts?.delete(e),this._inputQueue.delete(e),this.ralphStates.delete(e),this.ralphClosedSessions.delete(e),this.projectInsights.delete(e),this.pendingHooks.delete(e),this.tabAlerts.delete(e),this.clearCountdownTimers(e),this.closeSessionLogViewerWindows(e),this.closeSessionImagePopups(e),this.closeSessionSubagentWindows(e,!0);const s=this.idleTimers.get(e);s&&(clearTimeout(s),this.idleTimers.delete(e)),delete this.respawnStatus[e],delete this.respawnTimers[e],delete this.respawnCountdownTimers[e],delete this.respawnActionLogs[e]}async closeSession(e,t=!0){try{if(await fetch(`/api/sessions/${e}?killMux=${t}`,{method:"DELETE"}),this._cleanupSessionData(e),this.activeSessionId===e){this.activeSessionId=null;try{localStorage.removeItem("codeman-active-session")}catch{}if(this.sessionOrder.length>0&&this.sessions.size>0){const s=this.sessionOrder[0];this.selectSession(s)}else this.terminal.clear(),this.showWelcome(),this.renderRalphStatePanel()}this.renderSessionTabs(),t?this.showToast("Session closed and tmux killed","success"):this.showToast("Tab hidden, tmux still running","info")}catch{this.showToast("Failed to close session","error")}}requestCloseSession(e){const t=this.sessions.get(e);if(!t)return;this.pendingCloseSessionId=e;const s=this.getSessionName(t),n=document.getElementById("closeConfirmSessionName");n.textContent=s;const i=document.getElementById("closeConfirmKillTitle");i&&(i.textContent=t.mode==="opencode"?"Kill Tmux & OpenCode":"Kill Tmux & Claude Code"),document.getElementById("closeConfirmModal").classList.add("active")}cancelCloseSession(){this.pendingCloseSessionId=null,document.getElementById("closeConfirmModal").classList.remove("active")}async confirmCloseSession(e=!0){const t=this.pendingCloseSessionId;this.cancelCloseSession(),t&&await this.closeSession(t,e)}nextSession(){if(this.sessionOrder.length<=1)return;const t=(this.sessionOrder.indexOf(this.activeSessionId)+1)%this.sessionOrder.length;this.selectSession(this.sessionOrder[t])}prevSession(){if(this.sessionOrder.length<=1)return;const t=(this.sessionOrder.indexOf(this.activeSessionId)-1+this.sessionOrder.length)%this.sessionOrder.length;this.selectSession(this.sessionOrder[t])}goHome(){this.activeSessionId=null;try{localStorage.removeItem("codeman-active-session")}catch{}this.terminal.clear(),this.showWelcome(),this.renderSessionTabs(),this.renderRalphStatePanel()}ralphWizardStep=1;ralphWizardConfig={taskDescription:"",completionPhrase:"COMPLETE",maxIterations:10,caseName:"testcase",enableRespawn:!1,generatedPlan:null,planGenerated:!1,skipPlanGeneration:!1,planDetailLevel:"detailed",existingPlan:null,useExistingPlan:!1};planLoadingTimer=null;planLoadingStartTime=null;async loadQuickStartCases(e=null,t=null){try{let s=null;try{const h=t?await t:await fetch("/api/settings").then(u=>u.ok?u.json():null);h&&(s=h.lastUsedCase||null)}catch{}const i=await(await fetch("/api/cases")).json();this.cases=i;const o=document.getElementById("quickStartCase");let l="";const a=i.some(h=>h.name==="testcase"),c=MobileDetection.getDeviceType()==="mobile"?8:20;if(i.forEach(h=>{const u=h.name.length>c?h.name.substring(0,c)+"\u2026":h.name;l+=`<option value="${this.escapeHtml(h.name)}">${this.escapeHtml(u)}</option>`}),a||(l='<option value="testcase">testcase</option>'+l),o.innerHTML=l,e)o.value=e,this.updateDirDisplayForCase(e),this.updateMobileCaseLabel(e);else if(s&&i.some(h=>h.name===s))o.value=s,this.updateDirDisplayForCase(s),this.updateMobileCaseLabel(s);else if(i.length>0){const h=i.find(u=>u.name==="testcase")||i[0];o.value=h.name,this.updateDirDisplayForCase(h.name),this.updateMobileCaseLabel(h.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{}}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{}}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(),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"))){const s=n=>{t.contains(n.target)||(t.classList.remove("active"),document.removeEventListener("click",s))};setTimeout(()=>document.addEventListener("click",s),0)}}_applyRunMode(){const e=this.runMode,t=document.getElementById("runBtn"),s=t?.nextElementSibling,n=document.getElementById("runBtnLabel");t&&(t.className=`btn-toolbar btn-run mode-${e}`),s&&(s.className=`btn-toolbar btn-run-gear mode-${e}`),n&&(n.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 n=await(await fetch(`/api/cases/${e}`)).json();if(!n.path){const w=await(await fetch("/api/cases",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:e,description:""})})).json();if(!w.success)throw new Error(w.error||"Failed to create case");n=w.case}const i=n.path;if(!i)throw new Error("Case path not found");let o=null,l=1;for(const[,f]of this.sessions){const w=f.name&&f.name.match(/^w(\d+)-(.+)$/);if(w&&w[2]===e){const v=parseInt(w[1]);v>=l&&(l=v+1)}}const a=this.isRalphTrackerEnabledByDefault(),r=[];for(let f=0;f<t;f++)r.push(`w${l+f}-${e}`);const c=this.getCaseSettings(e),h=this.loadAppSettingsFromStorage(),u={};(c.agentTeams||h.agentTeamsEnabled)&&(u.CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS="1");const m=Object.keys(u).length>0;this.terminal.writeln(`\x1B[90m Creating ${t} session(s)...\x1B[0m`);const p=r.map(f=>fetch("/api/sessions",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({workingDir:i,name:f,...m?{envOverrides:u}:{}})}).then(w=>w.json())),g=await Promise.all(p),y=[];for(const f of g){if(!f.success)throw new Error(f.error);y.push(f.session.id)}o=y[0],await Promise.all(y.map(f=>fetch(`/api/sessions/${f}/ralph-config`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({enabled:a,disableAutoEnable:!a})}))),this.terminal.writeln(`\x1B[90m Starting ${t} session(s) in parallel...\x1B[0m`),await Promise.all(y.map(f=>fetch(`/api/sessions/${f}/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 i=(await(await fetch(`/api/cases/${e}`)).json()).path;if(!i)throw new Error("Case path not found");let o=1;for(const[,u]of this.sessions){const m=u.name&&u.name.match(/^s(\d+)-(.+)$/);if(m&&m[2]===e){const p=parseInt(m[1]);p>=o&&(o=p+1)}}const l=[];for(let u=0;u<t;u++)l.push(`s${o+u}-${e}`);const a=l.map(u=>fetch("/api/sessions",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({workingDir:i,mode:"shell",name:u})}).then(m=>m.json())),r=await Promise.all(a),c=[];for(const u of r){if(!u.success)throw new Error(u.error);c.push(u.session.id)}await Promise.all(c.map(u=>fetch(`/api/sessions/${u}/shell`,{method:"POST"})));const h=this.getTerminalDimensions();h&&await Promise.all(c.map(u=>fetch(`/api/sessions/${u}/resize`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(h)}))),c.length>0&&(this.activeSessionId=c[0],await this.selectSession(c[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 i=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(!i.success)throw new Error(i.error||"Failed to start OpenCode");i.sessionId&&await this.selectSession(i.sessionId),this.terminal.focus()}catch(t){this.terminal.writeln(`\x1B[1;31m Error: ${t.message}\x1B[0m`)}}toggleDirInput(){const e=document.querySelector("#dirDisplay").parentElement,t=document.getElementById("dirInput");t.classList.contains("hidden")&&(t.classList.remove("hidden"),e.style.display="none",t.focus())}hideDirInput(){const e=document.querySelector("#dirDisplay").parentElement,t=document.getElementById("dirInput");setTimeout(()=>{t.classList.add("hidden"),e.style.display="";const s=t.value.trim();document.getElementById("dirDisplay").textContent=s||"No directory"},100)}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"),o=document.getElementById("detectionHook");if(o)if(e.stopHookReceived||e.idlePromptReceived){const r=e.idlePromptReceived?"idle":"stop";o.textContent=`\u{1F3AF} ${r} hook`,o.className="detection-hook hook-active",o.style.display=""}else o.style.display="none";e.statusText&&e.statusText!=="Watching..."?(t.textContent=e.statusText,t.style.display=""):t.style.display="none",s.style.display="none";const l=e.confidenceLevel||0;if(l>0?(n.textContent=`${l}%`,n.style.display="",n.className="detection-confidence",e.stopHookReceived||e.idlePromptReceived?n.classList.add("hook-confirmed"):l>=60?n.classList.add("high"):l>=30&&n.classList.add("medium")):n.style.display="none",i&&e.aiCheck){const r=e.aiCheck;let c="",h="detection-ai-check";if(r.status==="checking")c="\u{1F50D} AI checking...",h+=" ai-checking";else if(r.status==="cooldown"&&r.cooldownEndsAt){const u=Math.ceil((r.cooldownEndsAt-Date.now())/1e3);u>0&&(r.lastVerdict==="WORKING"?(c=`\u23F3 Working, retry ${u}s`,h+=" ai-working"):(c=`\u2713 Idle, wait ${u}s`,h+=" ai-idle"))}else if(r.status==="disabled")c="\u26A0 AI disabled",h+=" ai-disabled";else if(r.lastVerdict&&r.lastCheckTime){const u=Math.round((Date.now()-r.lastCheckTime)/1e3);u<120&&(c=r.lastVerdict==="IDLE"?`\u2713 Idle (${u}s)`:`\u23F3 Working (${u}s)`,h+=r.lastVerdict==="IDLE"?" ai-idle":" ai-working")}i.textContent=c,i.className=h,i.style.display=c?"":"none"}else i&&(i.style.display="none");const a=this.$("respawnStatusRow2");if(a){const r=o&&o.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;a.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),o=t?e.output||0:Math.round(s*.4);if(s>0){n.style.display="";const l=this.formatTokens(s);if(this.loadAppSettingsFromStorage().showCost??!1){const c=this.estimateCost(i,o);n.textContent=`${l} tokens \xB7 $${c.toFixed(2)}`}else n.textContent=`${l} 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 l=document.getElementById("detectionHook"),a=document.getElementById("detectionAiCheck"),r=this.$("detectionStatus"),c=l&&l.style.display!=="none"||a&&a.style.display!=="none"||r&&r.style.display!=="none";t.style.display=c?"":"none"}return}t&&(t.style.display="");const i=Date.now();let o="";for(const[l,a]of Object.entries(s)){const r=Math.max(0,a.endsAt-i),c=(r/1e3).toFixed(1),h=Math.max(0,Math.min(100,r/a.totalMs*100)),u=l.replace(/-/g," ").replace(/^\w/,m=>m.toUpperCase());o+=`<div class="respawn-countdown-timer" title="${this.escapeHtml(a.reason||"")}">
|
|
82
|
+
<span class="timer-name">${this.escapeHtml(u)}</span>
|
|
83
|
+
<span class="timer-value">${c}s</span>
|
|
84
|
+
<div class="respawn-timer-bar">
|
|
85
|
+
<div class="respawn-timer-progress" style="width: ${h}%"></div>
|
|
86
|
+
</div>
|
|
87
|
+
</div>`}e.innerHTML=o}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"}),l=n.type==="command"?" action-command":"";s+=`<div class="respawn-action-entry${l}">
|
|
88
|
+
<span class="action-time">${i}</span>
|
|
89
|
+
<span class="action-type">[${n.type}]</span>
|
|
90
|
+
<span class="action-detail">${this.escapeHtml(n.detail)}</span>
|
|
91
|
+
</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 fetch(`/api/sessions/${this.activeSessionId}/respawn/stop`,{method:"POST"}),delete this.respawnTimers[this.activeSessionId],this.clearCountdownTimers(this.activeSessionId)}catch{this.showToast("Failed to stop respawn","error")}}async killActiveSession(){if(!this.activeSessionId){this.showToast("No active session","warning");return}await this.closeSession(this.activeSessionId)}async killAllSessions(){if(this.sessions.size!==0&&confirm(`Kill all ${this.sessions.size} session(s)?`))try{await fetch("/api/sessions",{method:"DELETE"}),this.sessions.clear(),this.terminalBuffers.clear(),this.terminalBufferCache.clear(),this.activeSessionId=null;try{localStorage.removeItem("codeman-active-session")}catch{}this.respawnStatus={},this.respawnCountdownTimers={},this.respawnActionLogs={},this.stopCountdownInterval(),this.hideRespawnBanner(),this.renderSessionTabs(),this.terminal.clear(),this.showWelcome(),this.showToast("All sessions killed","success")}catch{this.showToast("Failed to kill sessions","error")}}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{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 t="";for(let s=0;s<e.length;s++){const n=e.getLine(s);n&&(t+=n.translateToString(!0)+`
|
|
92
|
+
`)}await navigator.clipboard.writeText(t.replace(/\n+$/,`
|
|
93
|
+
`)),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 t=parseInt(e,10);t>=10&&t<=24&&(this.terminal.options.fontSize=t,document.getElementById("fontSizeDisplay").textContent=t)}}getTerminalDimensions(){const s=this.fitAddon?.proposeDimensions();return s?{cols:Math.max(s.cols,40),rows:Math.max(s.rows,10)}:null}async sendResize(e){const t=this.getTerminalDimensions();t&&await fetch(`/api/sessions/${e}/resize`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}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})})}showTimer(){document.getElementById("timerBanner").style.display="flex",this.updateTimer(),this.timerInterval=setInterval(()=>this.updateTimer(),1e3)}hideTimer(){document.getElementById("timerBanner").style.display="none",this.timerInterval&&(clearInterval(this.timerInterval),this.timerInterval=null)}updateTimer(){if(!this.currentRun||this.currentRun.status!=="running")return;const e=Date.now(),t=Math.max(0,this.currentRun.endAt-e),s=this.currentRun.endAt-this.currentRun.startedAt,n=e-this.currentRun.startedAt,i=Math.min(100,n/s*100);document.getElementById("timerValue").textContent=this.formatTime(t),document.getElementById("timerProgress").style.width=`${i}%`,document.getElementById("timerMeta").textContent=`${this.currentRun.completedTasks} tasks | $${this.currentRun.totalCost.toFixed(2)}`}async stopCurrentRun(){if(this.currentRun)try{await fetch(`/api/scheduled/${this.currentRun.id}`,{method:"DELETE"})}catch{this.showToast("Failed to stop run","error")}}formatTime(e){const t=Math.floor(e/1e3),s=Math.floor(t/3600),n=Math.floor(t%3600/60),i=t%60;return`${s.toString().padStart(2,"0")}:${n.toString().padStart(2,"0")}:${i.toString().padStart(2,"0")}`}updateCost(){this.updateTokens()}updateTokens(){this._updateTokensTimeout&&clearTimeout(this._updateTokensTimeout),this._updateTokensTimeout=setTimeout(()=>{this._updateTokensTimeout=null,this._updateTokensImmediate()},200)}_updateTokensImmediate(){let e=0,t=0;this.globalStats?(e=this.globalStats.totalInputTokens||0,t=this.globalStats.totalOutputTokens||0):this.sessions.forEach(l=>{l.tokens&&(e+=l.tokens.input||0,t+=l.tokens.output||0)});const s=e+t;this.totalTokens=s;const n=this.formatTokens(s),i=this.estimateCost(e,t),o=this.$("headerTokens");if(o){const a=this.loadAppSettingsFromStorage().showCost??!1;o.textContent=s>0?a?`${n} tokens \xB7 $${i.toFixed(2)}`:`${n} tokens`:"0 tokens",o.title=this.globalStats?`Lifetime: ${this.globalStats.totalSessionsCreated} sessions created${a?`
|
|
94
|
+
Estimated cost based on Claude Opus pricing`:""}`:`Token usage across active sessions${a?`
|
|
95
|
+
Estimated cost based on Claude Opus pricing`:""}`}}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"),n=document.getElementById("modalEnableRespawnBtn"),i=document.getElementById("modalStopRespawnBtn");this.respawnStatus[e]?(s.classList.add("active"),s.querySelector(".respawn-status-text").textContent=this.respawnStatus[e].state||"Active",n.style.display="none",i.style.display=""):(s.classList.remove("active"),s.querySelector(".respawn-status-text").textContent="Not active",n.style.display="",i.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(p=>{p.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 r=t.color||"default";document.getElementById("sessionColorPicker")?.querySelectorAll(".color-swatch").forEach(p=>{p.classList.toggle("selected",p.dataset.color===r)}),this.renderPresetDropdown(),document.getElementById("respawnPresetSelect").value="",document.getElementById("presetDescriptionHint").textContent="";const h=document.querySelector('#sessionOptionsModal .modal-tab-btn[data-tab="ralph"]'),u=document.querySelector('#sessionOptionsModal .modal-tab-btn[data-tab="respawn"]');if(l?(h&&(h.style.display="none"),u&&(u.style.display="none"),this.switchOptionsTab("context")):(h&&(h.style.display=""),u&&(u.style.display="")),!l){const p=this.ralphStates.get(e);this.populateRalphForm({enabled:p?.loop?.enabled??t.ralphLoop?.enabled??!1,completionPhrase:p?.loop?.completionPhrase||t.ralphLoop?.completionPhrase||"",maxIterations:p?.loop?.maxIterations||t.ralphLoop?.maxIterations||0})}const m=document.getElementById("sessionOptionsModal");m.classList.add("active"),this.activeFocusTrap=new FocusTrap(m),this.activeFocusTrap.activate()}async saveSessionName(){if(!this.editingSessionId)return;const e=document.getElementById("modalSessionName").value.trim();try{await fetch(`/api/sessions/${this.editingSessionId}/name`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:e})})}catch(t){this.showToast("Failed to save session name: "+t.message,"error")}}async autoSaveAutoCompact(){if(this.editingSessionId)try{await fetch(`/api/sessions/${this.editingSessionId}/auto-compact`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({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 fetch(`/api/sessions/${this.editingSessionId}/auto-clear`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({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 fetch(`/api/sessions/${this.editingSessionId}/image-watcher`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({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 fetch(`/api/sessions/${this.editingSessionId}/flicker-filter`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({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 fetch(`/api/sessions/${this.editingSessionId}/respawn/config`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}catch{}}async loadSavedRespawnConfig(e){try{const s=await(await fetch(`/api/sessions/${e}/respawn/config`)).json();if(s.success&&s.config){const n=s.config;document.getElementById("modalRespawnPrompt").value=n.updatePrompt||"update all the docs and CLAUDE.md",document.getElementById("modalRespawnSendClear").checked=n.sendClear??!0,document.getElementById("modalRespawnSendInit").checked=n.sendInit??!0,document.getElementById("modalRespawnKickstart").value=n.kickstartPrompt||"",document.getElementById("modalRespawnAutoAccept").checked=n.autoAcceptPrompts??!0,n.durationMinutes&&(document.querySelector(`.duration-preset-btn[data-minutes="${n.durationMinutes}"]`)?this.selectDurationPreset(String(n.durationMinutes)):(this.selectDurationPreset("custom"),document.getElementById("modalRespawnDuration").value=n.durationMinutes))}}catch{}}selectDurationPreset(e){document.querySelectorAll(".duration-preset-btn").forEach(i=>i.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"),n=document.getElementById("modalRespawnDuration");e==="custom"?(s.classList.add("visible"),n.focus()):(s.classList.remove("visible"),n.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 n=document.querySelector(".duration-preset-btn.active")?.dataset.minutes;return n?parseInt(n):null}}loadRespawnPresets(){const e=localStorage.getItem("codeman-respawn-presets"),t=e?JSON.parse(e):[];return[...BUILTIN_RESPAWN_PRESETS,...t]}saveRespawnPresets(e){const t=e.filter(s=>!s.builtIn);localStorage.setItem("codeman-respawn-presets",JSON.stringify(t))}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(o=>o.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,o=this.getSelectedDuration(),l={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:o||void 0,builtIn:!1,createdAt:Date.now()},a=this.loadRespawnPresets();a.push(l),this.saveRespawnPresets(a),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,o=this.getSelectedDuration(),l=document.getElementById("modalAutoCompactEnabled").checked,a=parseInt(document.getElementById("modalAutoCompactThreshold").value)||11e4,r=document.getElementById("modalAutoCompactPrompt").value.trim()||void 0,c=document.getElementById("modalAutoClearEnabled").checked,h=parseInt(document.getElementById("modalAutoClearThreshold").value)||14e4;return{respawnConfig:{enabled:!0,updatePrompt:e,sendClear:t,sendInit:s,kickstartPrompt:n,autoAcceptPrompts:i},durationMinutes:o,autoCompactEnabled:l,autoCompactThreshold:a,autoCompactPrompt:r,autoClearEnabled:c,autoClearThreshold:h}}async enableRespawnFromModal(){if(!this.editingSessionId){this.showToast("No session selected","warning");return}const{respawnConfig:e,durationMinutes:t,autoCompactEnabled:s,autoCompactThreshold:n,autoCompactPrompt:i,autoClearEnabled:o,autoClearThreshold:l}=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})}),o&&await fetch(`/api/sessions/${this.editingSessionId}/auto-clear`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({enabled:!0,threshold:l})});const c=document.getElementById("sessionRespawnStatus");c.classList.add("active"),c.querySelector(".respawn-status-text").textContent="WATCHING",document.getElementById("modalEnableRespawnBtn").style.display="none",document.getElementById("modalStopRespawnBtn").style.display="",this.showToast("Respawn enabled","success")}catch(a){this.showToast("Failed to enable respawn: "+a.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(o=>{o.classList.toggle("selected",o.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:o}=this.runSummaryData,l=new Date().toISOString().slice(0,19).replace(/:/g,"-"),a=`run-summary-${n||"session"}-${l}`;if(e==="json"){const r=JSON.stringify(this.runSummaryData,null,2);this.downloadFile(`${a}.json`,r,"application/json")}else if(e==="md"){const r=o-i;let c=`# Run Summary: ${n||"Session"}
|
|
96
|
+
|
|
97
|
+
`;if(c+=`**Duration**: ${this.formatDuration(r)}
|
|
98
|
+
`,c+=`**Started**: ${new Date(i).toLocaleString()}
|
|
99
|
+
`,c+=`**Last Update**: ${new Date(o).toLocaleString()}
|
|
100
|
+
|
|
101
|
+
`,c+=`## Statistics
|
|
102
|
+
|
|
103
|
+
`,c+=`| Metric | Value |
|
|
104
|
+
`,c+=`|--------|-------|
|
|
105
|
+
`,c+=`| Respawn Cycles | ${t.totalRespawnCycles} |
|
|
106
|
+
`,c+=`| Peak Tokens | ${this.formatTokens(t.peakTokens)} |
|
|
107
|
+
`,c+=`| Active Time | ${this.formatDuration(t.totalTimeActiveMs)} |
|
|
108
|
+
`,c+=`| Idle Time | ${this.formatDuration(t.totalTimeIdleMs)} |
|
|
109
|
+
`,c+=`| Errors | ${t.errorCount} |
|
|
110
|
+
`,c+=`| Warnings | ${t.warningCount} |
|
|
111
|
+
`,c+=`| AI Checks | ${t.aiCheckCount} |
|
|
112
|
+
`,c+=`| State Transitions | ${t.stateTransitions} |
|
|
113
|
+
|
|
114
|
+
`,c+=`## Event Timeline
|
|
115
|
+
|
|
116
|
+
`,s.length===0)c+=`No events recorded.
|
|
117
|
+
`;else{c+=`| Time | Type | Severity | Title | Details |
|
|
118
|
+
`,c+=`|------|------|----------|-------|----------|
|
|
119
|
+
`;for(const h of s){const u=new Date(h.timestamp).toLocaleTimeString("en-US",{hour12:!1}),m=h.details?h.details.replace(/\|/g,"\\|"):"-";c+=`| ${u} | ${h.type} | ${h.severity} | ${h.title} | ${m} |
|
|
120
|
+
`}}this.downloadFile(`${a}.md`,c,"text/markdown")}this.showToast(`Exported as ${e.toUpperCase()}`,"success")}downloadFile(e,t,s){const n=new Blob([t],{type:s}),i=URL.createObjectURL(n),o=document.createElement("a");o.href=i,o.download=e,document.body.appendChild(o),o.click(),document.body.removeChild(o),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: ${this.escapeHtml(n.error)}</p>`;return}this.runSummaryData=n.summary,this.renderRunSummary()}catch{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,o=i-n;document.getElementById("runSummarySessionInfo").textContent=`${s||"Session"} - ${this.formatDuration(o)} total`;const l=this.filterRunSummaryEvents(t);this.renderRunSummaryTimeline(l)}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 o=new Date(i.timestamp).toLocaleTimeString("en-US",{hour12:!1}),l=`event-${i.severity}`,a=this.getEventIcon(i.type,i.severity);return`
|
|
121
|
+
<div class="timeline-event ${l}">
|
|
122
|
+
<div class="event-icon">${a}</div>
|
|
123
|
+
<div class="event-content">
|
|
124
|
+
<div class="event-header">
|
|
125
|
+
<span class="event-title">${this.escapeHtml(i.title)}</span>
|
|
126
|
+
<span class="event-time">${o}</span>
|
|
127
|
+
</div>
|
|
128
|
+
${i.details?`<div class="event-details">${this.escapeHtml(i.details)}</div>`:""}
|
|
129
|
+
</div>
|
|
130
|
+
</div>
|
|
131
|
+
`}).join("");t.innerHTML=n}getEventIcon(e,t){if(t==="error")return"❌";if(t==="warning")return"⚠";if(t==="success")return"✔";switch(e){case"session_started":return"🚀";case"session_stopped":return"🛑";case"respawn_cycle_started":return"🔄";case"respawn_cycle_completed":return"✅";case"respawn_state_change":return"➡";case"token_milestone":return"💰";case"idle_detected":return"💤";case"working_detected":return"💻";case"ai_check_result":return"🤖";case"hook_event":return"🔔";default:return"•"}}formatTokens(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}k`:String(e||0)}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()}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 n=this.getSessionName(t),i=document.createElement("input");i.type="text",i.value=t.name||"",i.placeholder=n,i.className="tab-rename-input",i.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(i),i.focus(),i.select();const l=async()=>{const a=i.value.trim();if(s.textContent=a||o,a&&a!==t.name)try{await fetch(`/api/sessions/${e}/name`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:a})})}catch{s.textContent=o,this.showToast("Failed to rename","error")}};i.addEventListener("blur",l),i.addEventListener("keydown",a=>{a.key==="Enter"?(a.preventDefault(),i.blur()):a.key==="Escape"&&(i.value="",i.blur())})}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:s}=t.data;s&&this.sessions.has(s)&&this.selectSession(s),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 t=await(await fetch("/api/push/vapid-key")).json();if(!t.success)throw new Error("Failed to get VAPID key");const s=urlBase64ToUint8Array(t.data.publicKey),n=await this._swRegistration.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:s}),i=n.toJSON(),l=await(await fetch("/api/push/subscribe",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({endpoint:i.endpoint,keys:i.keys,userAgent:navigator.userAgent,pushPreferences:this._buildPushPreferences()})})).json();if(!l.success)throw new Error("Failed to register subscription");this._pushSubscription=n,this._pushSubscriptionId=l.data.id,localStorage.setItem("codeman-push-subscription-id",l.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[s,n]of Object.entries(t)){const i=document.getElementById(n);e[s]=i?i.checked:!0}return e["session:error"]=!0,e}_updatePushUI(e){const t=document.getElementById("pushSubscribeBtn"),s=document.getElementById("pushSubscriptionStatus");t&&(t.textContent=e?"Unsubscribe":"Subscribe"),s&&(s.textContent=e?"active":"off",s.classList.remove("granted","denied"),e&&s.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??!0,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 s=document.getElementById("appSettingsClaudeMode"),n=document.getElementById("allowedToolsRow");s.value=e.claudeMode||"dangerously-skip-permissions",document.getElementById("appSettingsAllowedTools").value=e.allowedTools||"",n.style.display=s.value==="allowedTools"?"":"none",s.onchange=()=>{n.style.display=s.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 r=l.elicitation_dialog||{};document.getElementById("eventQuestionEnabled").checked=r.enabled??!0,document.getElementById("eventQuestionBrowser").checked=r.browser??!0,document.getElementById("eventQuestionPush").checked=r.push??!1,document.getElementById("eventQuestionAudio").checked=r.audio??!0;const c=l.idle_prompt||{};document.getElementById("eventIdleEnabled").checked=c.enabled??!0,document.getElementById("eventIdleBrowser").checked=c.browser??!0,document.getElementById("eventIdlePush").checked=c.push??!1,document.getElementById("eventIdleAudio").checked=c.audio??!1;const h=l.stop||{};document.getElementById("eventStopEnabled").checked=h.enabled??!0,document.getElementById("eventStopBrowser").checked=h.browser??!1,document.getElementById("eventStopPush").checked=h.push??!1,document.getElementById("eventStopAudio").checked=h.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 m=l.ralph_complete||{};document.getElementById("eventRalphEnabled").checked=m.enabled??!0,document.getElementById("eventRalphBrowser").checked=m.browser??!0,document.getElementById("eventRalphPush").checked=m.push??!1,document.getElementById("eventRalphAudio").checked=m.audio??!0;const p=l.subagent_spawn||{};document.getElementById("eventSubagentEnabled").checked=p.enabled??!1,document.getElementById("eventSubagentBrowser").checked=p.browser??!1,document.getElementById("eventSubagentPush").checked=p.push??!1,document.getElementById("eventSubagentAudio").checked=p.audio??!1;const g=document.getElementById("notifPermissionStatus");if(g&&typeof Notification<"u"){const b=Notification.permission;g.textContent=b==="granted"?"\u2713":b==="denied"?"\u2717":"?",g.classList.remove("granted","denied"),b==="granted"?g.classList.add("granted"):b==="denied"&&g.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 f=document.getElementById("voiceDeepgramKey");f.type="password",document.getElementById("voiceKeyToggleBtn").textContent="Show";const w=VoiceInput.getActiveProviderName(),v=document.getElementById("voiceProviderStatus");v.textContent=w,v.className="voice-provider-status"+(w.startsWith("Deepgram")?" active":""),this.switchSettingsTab("settings-display");const S=document.getElementById("appSettingsModal");S.querySelectorAll(".modal-tabs .modal-tab-btn").forEach(b=>{b.onclick=()=>this.switchSettingsTab(b.dataset.tab)}),S.classList.add("active"),this.activeFocusTrap=new FocusTrap(S),this.activeFocusTrap.activate()}switchSettingsTab(e){const t=document.getElementById("appSettingsModal");t.querySelectorAll(".modal-tabs .modal-tab-btn").forEach(s=>{s.classList.toggle("active",s.dataset.tab===e)}),t.querySelectorAll(".modal-tab-content").forEach(s=>{s.classList.toggle("hidden",s.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(),s=t.running&&t.url;this._updateTunnelUrlDisplay(s?t.url:null),this._updateWelcomeTunnelBtn(!!s,s?t.url:null)}catch{this._updateTunnelUrlDisplay(null),this._updateWelcomeTunnelBtn(!1)}}_updateTunnelUrlDisplay(e){const t=document.getElementById("tunnelUrlRow"),s=document.getElementById("tunnelUrlDisplay");!t||!s||(e?(t.style.display="",s.textContent=e,s.onclick=()=>{navigator.clipboard.writeText(e).then(()=>{this.showToast("Tunnel URL copied","success")})}):(t.style.display="none",s.textContent="",s.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=s=>{s.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=`
|
|
132
|
+
<div style="font-size:14px;font-weight:600;color:var(--text-primary);margin-bottom:16px">Scan to connect</div>
|
|
133
|
+
<div id="tunnelQrContainer" style="background:#fff;border-radius:8px;padding:16px;display:inline-block">
|
|
134
|
+
<div style="color:#666;font-size:12px">Loading...</div>
|
|
135
|
+
</div>
|
|
136
|
+
<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>
|
|
137
|
+
<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>
|
|
138
|
+
`,e.appendChild(t),document.body.appendChild(e),fetch("/api/tunnel/qr").then(s=>{if(!s.ok)throw new Error("Tunnel not running");return s.json()}).then(s=>{const n=document.getElementById("tunnelQrContainer");n&&s.svg&&(n.innerHTML=s.svg)}).catch(()=>{const s=document.getElementById("tunnelQrContainer");s&&(s.innerHTML='<div style="color:#c00;font-size:12px;padding:20px">Tunnel not active</div>')}),fetch("/api/tunnel/status").then(s=>s.json()).then(s=>{const n=document.getElementById("tunnelQrUrl");n&&s.url&&(n.textContent=s.url,n.onclick=()=>{navigator.clipboard.writeText(s.url).then(()=>{this.showToast("Tunnel URL copied","success")})})}).catch(()=>{}),this._tunnelQrEscHandler=s=>{s.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)}async toggleTunnelFromWelcome(){const e=document.getElementById("welcomeTunnelBtn");if(!e)return;const t=e.classList.contains("active");e.disabled=!0;try{const s=!t;await fetch("/api/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({tunnelEnabled:s})}),s?(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=`
|
|
139
|
+
<span class="tunnel-spinner"></span>
|
|
140
|
+
Connecting...`);const s=document.createElement("div");s.className="toast toast-info show",s.id="tunnelConnectingToast",s.innerHTML='<span class="tunnel-spinner"></span> Cloudflare Tunnel connecting...',s.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(s)}_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 s=await(await fetch("/api/tunnel/status")).json();if(s.running&&s.url){this._dismissTunnelConnecting(),this._updateTunnelUrlDisplay(s.url),document.getElementById("welcomeOverlay")?.classList.contains("visible")?(this._updateWelcomeTunnelBtn(!0,s.url,!0),this.showToast("Tunnel active","success")):(this._updateWelcomeTunnelBtn(!0,s.url),this.showToast(`Tunnel active: ${s.url}`,"success"),this.showTunnelQR());return}}catch{}this._pollTunnelStatus(e+1)},2e3))}_updateWelcomeTunnelBtn(e,t,s=!1){const n=document.getElementById("welcomeTunnelBtn");n&&(n.disabled=!1,e?(n.classList.remove("connecting"),n.classList.add("active"),n.innerHTML=`
|
|
141
|
+
<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>
|
|
142
|
+
Tunnel Active`):(n.classList.remove("active","connecting"),n.innerHTML=`
|
|
143
|
+
<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>
|
|
144
|
+
Cloudflare Tunnel`));const i=document.getElementById("welcomeQr"),o=document.getElementById("welcomeQrInner"),l=document.getElementById("welcomeQrUrl");!i||!o||(e?(i.classList.add("visible"),s&&(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"))}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 s=!1,n,i,o,l;t.addEventListener("mousedown",a=>{if(a.target.tagName==="SELECT"||a.target.tagName==="INPUT"||a.target.tagName==="BUTTON")return;s=!0;const r=e.getBoundingClientRect();e.style.transform="none",e.style.left=r.left+"px",e.style.top=r.top+"px",n=a.clientX,i=a.clientY,o=r.left,l=r.top,a.preventDefault()}),document.addEventListener("mousemove",a=>{s&&(e.style.left=o+a.clientX-n+"px",e.style.top=l+a.clientY-i+"px")}),document.addEventListener("mouseup",()=>{s=!1})}async loadLifecycleLog(){const e=document.getElementById("lifecycleFilterEvent").value,t=document.getElementById("lifecycleFilterSession").value.trim(),s=new URLSearchParams;e&&s.set("event",e),t&&s.set("sessionId",t),s.set("limit","300");try{const i=await(await fetch(`/api/session-lifecycle?${s}`)).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(r=>{const c=new Date(r.ts).toLocaleString(),h=a[r.event]||"#888",u=r.name||(r.sessionId==="*"?"\u2014":r.sessionId.slice(0,8)),m=[];return r.exitCode!==void 0&&r.exitCode!==null&&m.push(`code=${r.exitCode}`),r.mode&&m.push(r.mode),`<tr style="border-bottom:1px solid #1a1a2e">
|
|
145
|
+
<td style="padding:3px 8px;color:#888;white-space:nowrap">${c}</td>
|
|
146
|
+
<td style="padding:3px 8px;color:${h};font-weight:600">${r.event}</td>
|
|
147
|
+
<td style="padding:3px 8px;color:#e0e0e0" title="${r.sessionId}">${u}</td>
|
|
148
|
+
<td style="padding:3px 8px;color:#aaa">${r.reason||""}</td>
|
|
149
|
+
<td style="padding:3px 8px;color:#666">${m.join(", ")}</td>
|
|
150
|
+
</tr>`}).join("")}catch{}}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 s={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=s,this.notificationManager.savePreferences()),this._syncPushPreferences(),this.applyHeaderVisibilitySettings(),this.applyTabWrapSettings(),this._updateTokensImmediate(),this.applyMonitorVisibility(),this.renderProjectInsightsPanel(),this.updateSubagentWindowVisibility();const{localEchoEnabled:n,...i}=e;try{await fetch("/api/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({...i,notificationPreferences:s,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 s=t.data,n=document.getElementById("appSettingsDefaultModel");n&&(n.value=s.defaultModel||"opus");const i=document.getElementById("appSettingsShowModelRecommendations");i&&(i.checked=s.showRecommendations??!0);const o=s.agentTypeOverrides||{},l=document.getElementById("appSettingsModelExplore"),a=document.getElementById("appSettingsModelImplement"),r=document.getElementById("appSettingsModelTest"),c=document.getElementById("appSettingsModelReview");l&&(l.value=o.explore||""),a&&(a.value=o.implement||""),r&&(r.value=o.test||""),c&&(c.value=o.review||"")}}catch{}}async saveModelConfigFromSettings(){const e=document.getElementById("appSettingsDefaultModel"),t=document.getElementById("appSettingsShowModelRecommendations"),s=document.getElementById("appSettingsModelExplore"),n=document.getElementById("appSettingsModelImplement"),i=document.getElementById("appSettingsModelTest"),o=document.getElementById("appSettingsModelReview"),l={};s?.value&&(l.explore=s.value),n?.value&&(l.implement=n.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{}}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{}return this._cachedAppSettings=this.getDefaultSettings(),this._cachedAppSettings}saveAppSettingsToStorage(e){this._cachedAppSettings=e;try{const t=this.getSettingsStorageKey();localStorage.setItem(t,JSON.stringify(e))}catch{}}applyHeaderVisibilitySettings(){const e=this.loadAppSettingsFromStorage(),t=this.getDefaultSettings(),s=e.showFontControls??t.showFontControls??!1,n=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=s?"":"none"),l&&(l.style.display=n?"":"none"),a&&(a.style.display=i?"":"none");const r=e.showLifecycleLog??t.showLifecycleLog??!0,c=document.querySelector(".btn-lifecycle-log");c&&(c.style.display=r?"":"none");const h=this.notificationManager?.preferences?.enabled??!0,u=document.querySelector(".btn-notifications");if(u&&(u.style.display=h?"":"none"),!h){const m=document.getElementById("notifDrawer");m&&m.classList.remove("open")}}applyTabWrapSettings(){const e=this.loadAppSettingsFromStorage(),t=this.getDefaultSettings(),n=MobileDetection.getDeviceType()==="desktop"?e.tabTwoRows??t.tabTwoRows??!1:!1,i=this._tallTabsEnabled;this._tallTabsEnabled=n;const o=document.getElementById("sessionTabs");o&&(o.classList.toggle("tabs-two-rows",n),o.classList.toggle("tabs-show-folder",n)),i!==void 0&&i!==n&&this._fullRenderSessionTabs()}applyMonitorVisibility(){const e=this.loadAppSettingsFromStorage(),t=this.getDefaultSettings(),s=e.showMonitor??t.showMonitor??!0,n=e.showSubagents??t.showSubagents??!0,i=e.showFileBrowser??t.showFileBrowser??!1,o=document.getElementById("monitorPanel");o&&(o.style.display=s?"":"none",s?o.classList.add("open"):o.classList.remove("open"));const l=document.getElementById("subagentsPanel");l&&(n?l.classList.remove("hidden"):l.classList.add("hidden"));const a=document.getElementById("fileBrowserPanel");a&&(i&&this.activeSessionId?(a.classList.add("visible"),this.loadFileBrowser(this.activeSessionId)):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 s=await(await fetch("/api/subagents",{method:"DELETE"})).json();s.success?(this.subagents.clear(),this.subagentActivity.clear(),this.subagentToolResults.clear(),this.cleanupAllFloatingWindows(),this.renderSubagentPanel(),this.renderMonitorSubagents(),this.updateSubagentBadge(),this.showToast(`Cleared ${s.data.cleared} subagent(s)`,"success")):this.showToast("Failed to clear subagents: "+s.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 s=this.loadAppSettingsFromStorage();s.showSubagents=!0,this.saveAppSettingsToStorage(s)}e.classList.toggle("open"),this.subagentPanelVisible=e.classList.contains("open"),t&&(t.innerHTML=this.subagentPanelVisible?"▼":"▲"),this.subagentPanelVisible&&this.renderSubagentPanel()}}async loadAppSettingsFromServer(e=null){try{const t=e?await e:await fetch("/api/settings").then(s=>s.ok?s.json():null);if(t){const{notificationPreferences:s,voiceSettings:n,...i}=t,o=new Set(["showFontControls","showSystemStats","showTokenCount","showCost","showMonitor","showProjectInsights","showFileBrowser","showSubagents","subagentActiveTabOnly","tabTwoRows","localEchoEnabled"]),l=this.loadAppSettingsFromStorage(),a={...l};for(const[r,c]of Object.entries(i))o.has(r)&&r in l||(a[r]=c);if(this.saveAppSettingsToStorage(a),s&&this.notificationManager&&(localStorage.getItem(this.notificationManager.getStorageKey())||(this.notificationManager.preferences=s,this.notificationManager.savePreferences())),n){const r=localStorage.getItem("codeman-voice-settings");(!r||!JSON.parse(r).apiKey)&&VoiceInput._saveDeepgramConfig(n)}return a}}catch{}return this.loadAppSettingsFromStorage()}async saveSubagentWindowStates(){const e={};for(const[n,i]of this.minimizedSubagents)e[n]=Array.from(i);const t=[];for(const[n,i]of this.subagentWindows)i.minimized||t.push({agentId:n,position:i.position||null});const s={minimized:e,open:t};localStorage.setItem("codeman-subagent-window-states",JSON.stringify(s));try{await fetch("/api/subagent-window-states",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)})}catch{}}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{}if(!e)try{const t=localStorage.getItem("codeman-subagent-window-states");t&&(e=JSON.parse(t))}catch{}return e||{minimized:{},open:[]}}async restoreSubagentWindowStates(){const e=await this.loadSubagentWindowStates(),t=Date.now()-600*1e3;for(const[i,o]of Object.entries(e.minimized||{}))if(Array.isArray(o)&&o.length>0)for(const l of o){const a=this.subagents.get(l);if(!a)continue;const r=a.startedAt||0;if(a.status==="completed"||r<t)continue;const c=this.subagentParentMap.get(l),h=c||(this.sessions.has(i)?i:null);h&&(!c&&this.sessions.has(i)&&this.setAgentParentSessionId(l,i),this.minimizedSubagents.has(h)||this.minimizedSubagents.set(h,new Set),this.minimizedSubagents.get(h).add(l))}const s=Date.now(),n=600*1e3;for(const{agentId:i,position:o}of e.open||[]){const l=this.subagents.get(i),a=l?.startedAt?s-l.startedAt:1/0;if(l&&l.status!=="completed"&&a<n&&(this.openSubagentWindow(i),o)){const r=this.subagentWindows.get(i);if(r&&r.element){let c=parseInt(o.left,10)||50,h=parseInt(o.top,10)||120;const u=window.innerWidth,m=window.innerHeight,p=420,g=350;c=Math.max(10,Math.min(c,u-p-10)),h=Math.max(10,Math.min(h,m-g-10)),r.element.style.left=`${c}px`,r.element.style.top=`${h}px`,r.position={left:`${c}px`,top:`${h}px`}}}}this.renderSessionTabs(),this.saveSubagentWindowStates(),requestAnimationFrame(()=>{this.updateConnectionLines()})}async saveSubagentParentMap(){const e=Object.fromEntries(this.subagentParentMap);try{localStorage.setItem("codeman-subagent-parents",JSON.stringify(e))}catch{}try{await fetch("/api/subagent-parents",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}catch{}}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{}if(!e)try{const t=localStorage.getItem("codeman-subagent-parents");t&&(e=JSON.parse(t))}catch{}if(e&&typeof e=="object")for(const[t,s]of Object.entries(e))this.sessions.has(s)&&this.subagents.has(t)&&this.subagentParentMap.set(t,s)}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 s=this.subagents.get(e);if(s){s.parentSessionId=t;const n=this.sessions.get(t);n&&(s.parentSessionName=this.getSessionName(n)),this.subagents.set(e,s)}}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}async openTokenStats(){try{const t=await(await fetch("/api/token-stats")).json();t.success?(this.renderTokenStats(t),document.getElementById("tokenStatsModal").classList.add("active")):this.showToast("Failed to load token stats","error")}catch{this.showToast("Failed to load token stats","error")}}renderTokenStats(e){const{daily:t,totals:s}=e,n=new Date().toISOString().split("T")[0],i=t.find(b=>b.date===n)||{inputTokens:0,outputTokens:0,estimatedCost:0},o=new Date;o.setDate(o.getDate()-7);const l=t.filter(b=>new Date(b.date)>=o),a=l.reduce((b,T)=>b+T.inputTokens,0),r=l.reduce((b,T)=>b+T.outputTokens,0),c=this.estimateCost(a,r),h=s.totalInputTokens,u=s.totalOutputTokens,m=this.estimateCost(h,u),p=document.getElementById("statsSummary");p.innerHTML=`
|
|
151
|
+
<div class="stat-card">
|
|
152
|
+
<span class="stat-card-label">Today</span>
|
|
153
|
+
<span class="stat-card-value">${this.formatTokens(i.inputTokens+i.outputTokens)}</span>
|
|
154
|
+
<span class="stat-card-cost">~$${i.estimatedCost.toFixed(2)}</span>
|
|
155
|
+
</div>
|
|
156
|
+
<div class="stat-card">
|
|
157
|
+
<span class="stat-card-label">7 Days</span>
|
|
158
|
+
<span class="stat-card-value">${this.formatTokens(a+r)}</span>
|
|
159
|
+
<span class="stat-card-cost">~$${c.toFixed(2)}</span>
|
|
160
|
+
</div>
|
|
161
|
+
<div class="stat-card">
|
|
162
|
+
<span class="stat-card-label">Lifetime</span>
|
|
163
|
+
<span class="stat-card-value">${this.formatTokens(h+u)}</span>
|
|
164
|
+
<span class="stat-card-cost">~$${m.toFixed(2)}</span>
|
|
165
|
+
</div>
|
|
166
|
+
`;const g=document.getElementById("statsChart"),y=document.getElementById("statsChartDays"),f=[];for(let b=6;b>=0;b--){const T=new Date;T.setDate(T.getDate()-b);const _=T.toISOString().split("T")[0],C=t.find(B=>B.date===_);f.push({date:_,dayName:T.toLocaleDateString("en-US",{weekday:"short"}),tokens:C?C.inputTokens+C.outputTokens:0,cost:C?C.estimatedCost:0})}const w=Math.max(...f.map(b=>b.tokens),1);g.innerHTML=f.map(b=>{const T=Math.max(b.tokens/w*100,3),_=`${b.dayName}: ${this.formatTokens(b.tokens)} (~$${b.cost.toFixed(2)})`;return`<div class="bar" style="height: ${T}%" data-tooltip="${_}"></div>`}).join(""),y.innerHTML=f.map(b=>`<span>${b.dayName}</span>`).join("");const v=document.getElementById("statsTable"),S=t.slice(0,14);S.length===0?v.innerHTML='<div class="stats-no-data">No usage data recorded yet</div>':v.innerHTML=`
|
|
167
|
+
<div class="stats-table-header">
|
|
168
|
+
<span>Date</span>
|
|
169
|
+
<span>Input</span>
|
|
170
|
+
<span>Output</span>
|
|
171
|
+
<span>Cost</span>
|
|
172
|
+
</div>
|
|
173
|
+
${S.map(b=>`
|
|
174
|
+
<div class="stats-table-row">
|
|
175
|
+
<span class="cell cell-date">${new Date(b.date+"T00:00:00").toLocaleDateString("en-US",{month:"short",day:"numeric"})}</span>
|
|
176
|
+
<span class="cell">${this.formatTokens(b.inputTokens)}</span>
|
|
177
|
+
<span class="cell">${this.formatTokens(b.outputTokens)}</span>
|
|
178
|
+
<span class="cell cell-cost">$${b.estimatedCost.toFixed(2)}</span>
|
|
179
|
+
</div>
|
|
180
|
+
`).join("")}
|
|
181
|
+
`}closeTokenStats(){const e=document.getElementById("tokenStatsModal");e&&e.classList.remove("active")}async toggleMonitorPanel(){const e=document.getElementById("monitorPanel"),t=document.getElementById("monitorToggleBtn");e.classList.toggle("open"),e.classList.contains("open")?(await this.loadMuxSessions(),await fetch("/api/mux-sessions/stats/start",{method:"POST"}),this.renderTaskPanel(),t&&(t.innerHTML="▼")):(await fetch("/api/mux-sessions/stats/stop",{method:"POST"}),t&&(t.innerHTML="▲"))}toggleTaskPanel(){this.toggleMonitorPanel()}toggleMonitorDetach(){const e=document.getElementById("monitorPanel"),t=document.getElementById("monitorDetachBtn");e.classList.contains("detached")?(e.classList.remove("detached"),e.style.top="",e.style.left="",e.style.width="",e.style.height="",t&&(t.innerHTML="⧉",t.title="Detach panel")):(e.classList.add("detached"),e.classList.add("open"),t&&(t.innerHTML="⊞",t.title="Attach panel"),this.setupMonitorDrag())}setupMonitorDrag(){const e=document.getElementById("monitorPanel"),t=document.getElementById("monitorPanelHeader");if(!e||!t)return;let s=!1,n,i,o,l;const a=h=>{if(h.target.closest("button")||!e.classList.contains("detached"))return;s=!0;const u=getEventCoords(h);n=u.clientX,i=u.clientY;const m=e.getBoundingClientRect();o=m.left,l=m.top,document.addEventListener("mousemove",r),document.addEventListener("mouseup",c),document.addEventListener("touchmove",r,{passive:!1}),document.addEventListener("touchend",c),h.preventDefault()},r=h=>{if(!s)return;const u=getEventCoords(h),m=u.clientX-n,p=u.clientY-i;let g=o+m,y=l+p;const f=e.getBoundingClientRect();g=Math.max(0,Math.min(window.innerWidth-f.width,g)),y=Math.max(0,Math.min(window.innerHeight-f.height,y)),e.style.left=g+"px",e.style.top=y+"px"},c=()=>{s=!1,document.removeEventListener("mousemove",r),document.removeEventListener("mouseup",c),document.removeEventListener("touchmove",r),document.removeEventListener("touchend",c)};t.removeEventListener("mousedown",t._dragHandler),t.removeEventListener("touchstart",t._touchDragHandler),t._dragHandler=a,t._touchDragHandler=a,t.addEventListener("mousedown",a),t.addEventListener("touchstart",a,{passive:!1})}toggleSubagentsDetach(){const e=document.getElementById("subagentsPanel"),t=document.getElementById("subagentsDetachBtn");e.classList.contains("detached")?(e.classList.remove("detached"),e.style.top="",e.style.left="",e.style.width="",e.style.height="",t&&(t.innerHTML="⧉",t.title="Detach panel")):(e.classList.add("detached"),e.classList.add("open"),t&&(t.innerHTML="⊞",t.title="Attach panel"),this.setupSubagentsDrag())}setupSubagentsDrag(){const e=document.getElementById("subagentsPanel"),t=document.getElementById("subagentsPanelHeader");if(!e||!t)return;let s=!1,n,i,o,l;const a=h=>{if(h.target.closest("button")||!e.classList.contains("detached"))return;s=!0;const u=getEventCoords(h);n=u.clientX,i=u.clientY;const m=e.getBoundingClientRect();o=m.left,l=m.top,document.addEventListener("mousemove",r),document.addEventListener("mouseup",c),document.addEventListener("touchmove",r,{passive:!1}),document.addEventListener("touchend",c),h.preventDefault()},r=h=>{if(!s)return;const u=getEventCoords(h),m=u.clientX-n,p=u.clientY-i;let g=o+m,y=l+p;const f=e.getBoundingClientRect();g=Math.max(0,Math.min(window.innerWidth-f.width,g)),y=Math.max(0,Math.min(window.innerHeight-f.height,y)),e.style.left=g+"px",e.style.top=y+"px"},c=()=>{s=!1,document.removeEventListener("mousemove",r),document.removeEventListener("mouseup",c),document.removeEventListener("touchmove",r),document.removeEventListener("touchend",c)};t.removeEventListener("mousedown",t._dragHandler),t.removeEventListener("touchstart",t._touchDragHandler),t._dragHandler=a,t._touchDragHandler=a,t.addEventListener("mousedown",a),t.addEventListener("touchstart",a,{passive:!1})}renderTaskPanel(){this.renderTaskPanelTimeout&&clearTimeout(this.renderTaskPanelTimeout),this.renderTaskPanelTimeout=setTimeout(()=>{this._renderTaskPanelImmediate()},100)}_renderTaskPanelImmediate(){const e=this.sessions.get(this.activeSessionId),t=document.getElementById("backgroundTasksBody"),s=document.getElementById("taskPanelStats"),n=document.getElementById("backgroundTasksSection");if(!e||!e.taskTree||e.taskTree.length===0){n&&(n.style.display="none"),t.innerHTML="",s.textContent="0 tasks";return}n&&(n.style.display="");const i=e.taskStats||{running:0,completed:0,failed:0,total:0};s.textContent=`${i.running} running, ${i.completed} done`;const o=(r,c)=>{const h=r.status==="running"?"":r.status==="completed"?"✓":"✗",u=r.endTime?`${((r.endTime-r.startTime)/1e3).toFixed(1)}s`:`${((Date.now()-r.startTime)/1e3).toFixed(0)}s...`;let m="";if(r.children&&r.children.length>0){m='<div class="task-children">';for(const p of r.children){const g=c.find(y=>y.id===p);g&&(m+=`<div class="task-node">${o(g,c)}</div>`)}m+="</div>"}return`
|
|
182
|
+
<div class="task-item">
|
|
183
|
+
<span class="task-status-icon ${r.status}">${h}</span>
|
|
184
|
+
<div class="task-info">
|
|
185
|
+
<div class="task-description">${this.escapeHtml(r.description)}</div>
|
|
186
|
+
<div class="task-meta">
|
|
187
|
+
<span class="task-type">${r.subagentType}</span>
|
|
188
|
+
<span>${u}</span>
|
|
189
|
+
</div>
|
|
190
|
+
</div>
|
|
191
|
+
</div>
|
|
192
|
+
${m}
|
|
193
|
+
`},l=this.flattenTaskTree(e.taskTree);let a='<div class="task-tree">';for(const r of e.taskTree)a+=`<div class="task-node">${o(r,l)}</div>`;a+="</div>",t.innerHTML=a}flattenTaskTree(e,t=[]){for(const s of e)t.push(s);return t}updateRalphState(e,t){const n={...this.ralphStates.get(e)||{loop:null,todos:[]},...t};this.ralphStates.set(e,n),e===this.activeSessionId&&this.renderRalphStatePanel()}toggleRalphStatePanel(){const e=this.terminal?.element?.querySelector(".xterm-viewport"),t=e?.scrollTop;this.ralphStatePanelCollapsed=!this.ralphStatePanelCollapsed,this.renderRalphStatePanel(),requestAnimationFrame(()=>{e&&t!==void 0&&(e.scrollTop=t),this.terminal&&this.fitAddon&&this.fitAddon.fit()})}async closeRalphTracker(){this.activeSessionId&&(this.ralphClosedSessions.add(this.activeSessionId),await fetch(`/api/sessions/${this.activeSessionId}/ralph-config`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({enabled:!1})}),this.ralphStates.delete(this.activeSessionId),this.renderRalphStatePanel())}toggleRalphMenu(){const e=document.getElementById("ralphDropdown");e&&e.classList.toggle("show")}closeRalphMenu(){const e=document.getElementById("ralphDropdown");e&&e.classList.remove("show")}async resetCircuitBreaker(){if(this.activeSessionId)try{(await(await fetch(`/api/sessions/${this.activeSessionId}/ralph-circuit-breaker/reset`,{method:"POST"})).json()).success&&this.notificationManager?.notify({urgency:"info",category:"circuit-breaker",title:"Reset",message:"Circuit breaker reset to CLOSED"})}catch{}}async showFixPlan(){if(this.activeSessionId)try{const t=await(await fetch(`/api/sessions/${this.activeSessionId}/fix-plan`)).json();if(!t.success){this.notificationManager?.notify({urgency:"error",category:"fix-plan",title:"Error",message:t.error||"Failed to generate fix plan"});return}this.showFixPlanModal(t.data.content,t.data.todoCount)}catch{}}showFixPlanModal(e,t){let s=document.getElementById("fixPlanModal");s||(s=document.createElement("div"),s.id="fixPlanModal",s.className="modal",s.innerHTML=`
|
|
194
|
+
<div class="modal-content fix-plan-modal">
|
|
195
|
+
<div class="modal-header">
|
|
196
|
+
<h3>@fix_plan.md</h3>
|
|
197
|
+
<button class="btn-close" onclick="app.closeFixPlanModal()">×</button>
|
|
198
|
+
</div>
|
|
199
|
+
<div class="modal-body">
|
|
200
|
+
<textarea id="fixPlanContent" class="fix-plan-textarea" readonly></textarea>
|
|
201
|
+
</div>
|
|
202
|
+
<div class="modal-footer">
|
|
203
|
+
<span class="fix-plan-stats" id="fixPlanStats"></span>
|
|
204
|
+
<button class="btn btn-secondary" onclick="app.copyFixPlan()">Copy</button>
|
|
205
|
+
<button class="btn btn-primary" onclick="app.writeFixPlanToFile()">Write to File</button>
|
|
206
|
+
<button class="btn btn-secondary" onclick="app.closeFixPlanModal()">Close</button>
|
|
207
|
+
</div>
|
|
208
|
+
</div>
|
|
209
|
+
`,document.body.appendChild(s)),document.getElementById("fixPlanContent").value=e,document.getElementById("fixPlanStats").textContent=`${t} tasks`,s.classList.add("show")}closeFixPlanModal(){const e=document.getElementById("fixPlanModal");e&&e.classList.remove("show")}async copyFixPlan(){const e=document.getElementById("fixPlanContent")?.value;e&&(await navigator.clipboard.writeText(e),this.notificationManager?.notify({urgency:"info",category:"fix-plan",title:"Copied",message:"Fix plan copied to clipboard"}))}async writeFixPlanToFile(){if(this.activeSessionId)try{const t=await(await fetch(`/api/sessions/${this.activeSessionId}/fix-plan/write`,{method:"POST"})).json();t.success?(this.notificationManager?.notify({urgency:"info",category:"fix-plan",title:"Written",message:`@fix_plan.md written to ${t.data.filePath}`}),this.closeFixPlanModal()):this.notificationManager?.notify({urgency:"error",category:"fix-plan",title:"Error",message:t.error||"Failed to write file"})}catch{}}async importFixPlanFromFile(){if(this.activeSessionId)try{const t=await(await fetch(`/api/sessions/${this.activeSessionId}/fix-plan/read`,{method:"POST"})).json();t.success?(this.notificationManager?.notify({urgency:"info",category:"fix-plan",title:"Imported",message:`Imported ${t.data.importedCount} tasks from @fix_plan.md`}),this.updateRalphState(this.activeSessionId,{todos:t.data.todos})):this.notificationManager?.notify({urgency:"warning",category:"fix-plan",title:"Not Found",message:t.error||"@fix_plan.md not found"})}catch{}}toggleRalphDetach(){const e=this.$("ralphStatePanel"),t=this.$("ralphDetachBtn");e&&(e.classList.contains("detached")?(e.classList.remove("detached"),e.style.top="",e.style.left="",e.style.width="",e.style.height="",t&&(t.innerHTML="⧉",t.title="Detach panel")):(e.classList.add("detached"),this.ralphStatePanelCollapsed=!1,e.classList.remove("collapsed"),t&&(t.innerHTML="⊞",t.title="Attach panel"),this.setupRalphDrag()),this.renderRalphStatePanel())}setupRalphDrag(){const e=this.$("ralphStatePanel"),t=this.$("ralphSummary");if(!e||!t)return;let s=!1,n,i,o,l;const a=h=>{if(h.target.closest("button")||h.target.closest(".ralph-toggle")||!e.classList.contains("detached"))return;s=!0,n=h.clientX,i=h.clientY;const u=e.getBoundingClientRect();o=u.left,l=u.top,document.addEventListener("mousemove",r),document.addEventListener("mouseup",c),h.preventDefault()},r=h=>{if(!s)return;const u=h.clientX-n,m=h.clientY-i;let p=o+u,g=l+m;const y=e.getBoundingClientRect();p=Math.max(0,Math.min(window.innerWidth-y.width,p)),g=Math.max(0,Math.min(window.innerHeight-y.height,g)),e.style.left=p+"px",e.style.top=g+"px"},c=()=>{s=!1,document.removeEventListener("mousemove",r),document.removeEventListener("mouseup",c)};t.removeEventListener("mousedown",t._ralphDragHandler),t._ralphDragHandler=a,t.addEventListener("mousedown",a)}renderRalphStatePanel(){this.renderRalphStatePanelTimeout&&clearTimeout(this.renderRalphStatePanelTimeout),this.renderRalphStatePanelTimeout=setTimeout(()=>{this._renderRalphStatePanelImmediate()},50)}_renderRalphStatePanelImmediate(){const e=this.$("ralphStatePanel"),t=this.$("ralphToggle");if(!e)return;if(this.ralphClosedSessions.has(this.activeSessionId)){e.style.display="none";return}const s=this.ralphStates.get(this.activeSessionId),n=s?.loop?.enabled===!0,i=s?.loop?.active||s?.loop?.completionPhrase,o=s?.todos?.length>0,l=s?.circuitBreaker&&s.circuitBreaker.state!=="CLOSED",a=s?.statusBlock!==void 0;if(!n&&!i&&!o&&!l&&!a){e.style.display="none";return}e.style.display="";const r=s?.todos||[],c=r.filter(m=>m.status==="completed").length,h=r.length,u=h>0?Math.round(c/h*100):0;this.updateRalphRing(u),this.updateRalphStatus(s?.loop,c,h),this.updateRalphStats(s?.loop,c,h),this.updateCircuitBreakerBadge(s?.circuitBreaker),this.ralphStatePanelCollapsed?(e.classList.add("collapsed"),t&&(t.innerHTML="▼")):(e.classList.remove("collapsed"),t&&(t.innerHTML="▲"),this.updateRalphExpandedView(s))}updateRalphRing(e){const t=Math.max(0,Math.min(100,Number(e)||0)),s=this.$("ralphRingMiniProgress"),n=this.$("ralphRingMiniText");if(s){const l=100-t;s.style.strokeDashoffset=l}n&&(n.textContent=`${t}%`);const i=this.$("ralphRingProgress"),o=this.$("ralphRingPercent");if(i){const l=264-264*t/100;i.style.strokeDashoffset=l}o&&(o.textContent=`${t}%`)}updateRalphStatus(e,t=0,s=0){const n=this.$("ralphStatusBadge"),i=n?.querySelector(".ralph-status-text");!n||!i||(n.classList.remove("active","completed","tracking"),e?.active?(n.classList.add("active"),i.textContent="Running"):s>0&&t===s?(n.classList.add("completed"),i.textContent="Complete"):e?.enabled||s>0?(n.classList.add("tracking"),i.textContent="Tracking"):i.textContent="Idle")}updateCircuitBreakerBadge(e){let t=this.$("ralphCircuitBreakerBadge");if(!t){const s=this.$("ralphSummary");if(!s)return;if(t=s.querySelector(".ralph-circuit-breaker"),!t){t=document.createElement("div"),t.id="ralphCircuitBreakerBadge",t.className="ralph-circuit-breaker";const n=this.$("ralphStatusBadge");n&&n.nextSibling?n.parentNode.insertBefore(t,n.nextSibling):s.appendChild(t)}}if(!e||e.state==="CLOSED"){t.style.display="none";return}t.style.display="",t.classList.remove("half-open","open"),e.state==="HALF_OPEN"?(t.classList.add("half-open"),t.innerHTML='<span class="cb-icon">\u26A0</span><span class="cb-text">Warning</span>',t.title=e.reason||"Circuit breaker warning"):e.state==="OPEN"&&(t.classList.add("open"),t.innerHTML='<span class="cb-icon">\u{1F6D1}</span><span class="cb-text">Stuck</span>',t.title=e.reason||"Loop appears stuck"),t.onclick=()=>this.resetCircuitBreaker()}async resetCircuitBreaker(){if(this.activeSessionId)try{(await fetch(`/api/sessions/${this.activeSessionId}/ralph-circuit-breaker/reset`,{method:"POST"})).ok}catch{}}updateRalphStats(e,t,s){const n=this.$("ralphStatTime");if(n)if(e?.elapsedHours!==null&&e?.elapsedHours!==void 0)n.textContent=this.formatRalphTime(e.elapsedHours);else if(e?.startedAt){const l=(Date.now()-e.startedAt)/36e5;n.textContent=this.formatRalphTime(l)}else n.textContent="0m";const i=this.$("ralphStatCycles");i&&(e?.maxIterations?i.textContent=`${e.cycleCount||0}/${e.maxIterations}`:i.textContent=String(e?.cycleCount||0));const o=this.$("ralphStatTasks");o&&(o.textContent=`${t}/${s}`)}formatRalphTime(e){if(e<.0167)return"0m";if(e<1)return`${Math.round(e*60)}m`;const t=Math.floor(e),s=Math.round((e-t)*60);return s===0?`${t}h`:`${t}h ${s}m`}updateRalphExpandedView(e){const t=this.$("ralphPhrase");t&&(t.textContent=e?.loop?.completionPhrase||"--");const s=this.$("ralphElapsed");if(s)if(e?.loop?.elapsedHours!==null&&e?.loop?.elapsedHours!==void 0)s.textContent=this.formatRalphTime(e.loop.elapsedHours);else if(e?.loop?.startedAt){const a=(Date.now()-e.loop.startedAt)/36e5;s.textContent=this.formatRalphTime(a)}else s.textContent="0m";const n=this.$("ralphIterations");n&&(e?.loop?.maxIterations?n.textContent=`${e.loop.cycleCount||0} / ${e.loop.maxIterations}`:n.textContent=String(e?.loop?.cycleCount||0));const i=e?.todos||[],o=i.filter(a=>a.status==="completed").length,l=this.$("ralphTasksCount");l&&(l.textContent=`${o}/${i.length}`),e?.loop?.planVersion?this.updatePlanVersionDisplay(e.loop.planVersion,e.loop.planHistoryLength||1):this.updatePlanVersionDisplay(null,0),this.renderRalphTasks(i),this.renderRalphStatusBlock(e?.statusBlock)}renderRalphStatusBlock(e){let t=this.$("ralphStatusBlockDisplay");const s=this.$("ralphExpandedContent");if(!e){t&&t.remove();return}if(!t&&s&&(t=document.createElement("div"),t.id="ralphStatusBlockDisplay",t.className="ralph-status-block",s.insertBefore(t,s.firstChild)),!t)return;const n=e.status==="IN_PROGRESS"?"in-progress":e.status==="COMPLETE"?"complete":e.status==="BLOCKED"?"blocked":"",i=e.testsStatus==="PASSING"?"\u2705":e.testsStatus==="FAILING"?"\u274C":"\u23F8",o=e.workType==="IMPLEMENTATION"?"\u{1F527}":e.workType==="TESTING"?"\u{1F9EA}":e.workType==="DOCUMENTATION"?"\u{1F4DD}":e.workType==="REFACTORING"?"\u267B\uFE0F":"\u{1F4CB}";let l=`
|
|
210
|
+
<div class="ralph-status-block-header">
|
|
211
|
+
<span>RALPH_STATUS</span>
|
|
212
|
+
<span class="ralph-status-block-status ${n}">${this.escapeHtml(e.status)}</span>
|
|
213
|
+
${e.exitSignal?'<span style="color: #4caf50;">\u{1F6AA} EXIT</span>':""}
|
|
214
|
+
</div>
|
|
215
|
+
<div class="ralph-status-block-stats">
|
|
216
|
+
<span>${o} ${this.escapeHtml(e.workType)}</span>
|
|
217
|
+
<span>\u{1F4C1} ${e.filesModified} files</span>
|
|
218
|
+
<span>\u2713 ${this.escapeHtml(String(e.tasksCompletedThisLoop))} tasks</span>
|
|
219
|
+
<span>${i} Tests: ${this.escapeHtml(e.testsStatus)}</span>
|
|
220
|
+
</div>
|
|
221
|
+
`;e.recommendation&&(l+=`<div class="ralph-status-block-recommendation">${this.escapeHtml(e.recommendation)}</div>`),t.innerHTML=l}renderRalphTasks(e){const t=this.$("ralphTasksGrid");if(!t)return;if(e.length===0){(t.children.length!==1||!t.querySelector(".ralph-state-empty"))&&(t.innerHTML='<div class="ralph-state-empty">No tasks detected</div>');return}const s={P0:0,P1:1,P2:2,null:3},n={in_progress:0,pending:1,completed:2},i=[...e].sort((l,a)=>{const r=s[l.priority]??3,c=s[a.priority]??3;return r!==c?r-c:(n[l.status]||1)-(n[a.status]||1)}),o=document.createDocumentFragment();i.forEach((l,a)=>{const r=this.createRalphTaskCard(l,a);o.appendChild(r)}),t.innerHTML="",t.appendChild(o)}createRalphTaskCard(e,t){const s=document.createElement("div"),n=`task-${e.status.replace("_","-")}`,i=e.priority?`task-priority-${e.priority.toLowerCase()}`:"";s.className=`ralph-task-card ${n} ${i}`.trim(),s.dataset.taskId=e.id||t;const o=document.createElement("span");if(o.className="ralph-task-icon",o.textContent=this.getRalphTaskIcon(e.status),s.appendChild(o),e.priority){const r=document.createElement("span");r.className=`ralph-task-priority priority-${e.priority.toLowerCase()}`,r.textContent=e.priority,s.appendChild(r)}const l=document.createElement("span");if(l.className="ralph-task-content",l.textContent=e.content,s.appendChild(l),e.attempts&&e.attempts>0){const r=document.createElement("span");r.className="ralph-task-attempts",e.lastError&&(r.classList.add("has-errors"),r.title=`Last error: ${e.lastError}`),r.textContent=`#${e.attempts}`,s.appendChild(r)}if(e.verificationCriteria){const r=document.createElement("span");r.className="ralph-task-verify-badge",r.title=`Verify: ${e.verificationCriteria}`,r.textContent="\u2713",s.appendChild(r)}if(e.dependencies&&e.dependencies.length>0){const r=document.createElement("span");r.className="ralph-task-deps-indicator",r.title=`Depends on: ${e.dependencies.join(", ")}`,r.textContent=`\u2197${e.dependencies.length}`,s.appendChild(r)}const a=document.createElement("div");if(a.className="ralph-task-actions",e.status!=="completed"){const r=document.createElement("button");r.className="ralph-task-action-btn",r.textContent="\u2713",r.title="Mark complete",r.onclick=c=>{c.stopPropagation(),this.updateRalphTaskStatus(e.id,"completed")},a.appendChild(r)}if(e.status==="completed"){const r=document.createElement("button");r.className="ralph-task-action-btn",r.textContent="\u21BA",r.title="Reopen",r.onclick=c=>{c.stopPropagation(),this.updateRalphTaskStatus(e.id,"pending")},a.appendChild(r)}if(e.lastError){const r=document.createElement("button");r.className="ralph-task-action-btn",r.textContent="\u21BB",r.title="Retry (clear error)",r.onclick=c=>{c.stopPropagation(),this.retryRalphTask(e.id)},a.appendChild(r)}return s.appendChild(a),s}async updateRalphTaskStatus(e,t){if(this.activeSessionId)try{const s=await fetch(`/api/sessions/${this.activeSessionId}/plan/task/${e}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({status:t})});if(!s.ok){const n=await s.json();throw new Error(n.error||"Failed to update task")}this.showToast(`Task ${t==="completed"?"completed":"reopened"}`,"success")}catch(s){this.showToast("Failed to update task: "+s.message,"error")}}async retryRalphTask(e){if(this.activeSessionId)try{const t=await fetch(`/api/sessions/${this.activeSessionId}/plan/task/${e}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({attempts:0,lastError:null,status:"pending"})});if(!t.ok){const s=await t.json();throw new Error(s.error||"Failed to retry task")}this.showToast("Task reset for retry","success")}catch(t){this.showToast("Failed to retry task: "+t.message,"error")}}getRalphTaskIcon(e){switch(e){case"completed":return"\u2713";case"in_progress":return"\u25D0";default:return"\u25CB"}}getTodoIcon(e){return this.getRalphTaskIcon(e)}updatePlanVersionDisplay(e,t){const s=this.$("ralphVersionRow"),n=this.$("ralphPlanVersion"),i=this.$("ralphRollbackBtn");s&&(e&&e>0?(s.style.display="",n&&(n.textContent=`v${e}`),i&&(i.style.display=t>1?"":"none")):s.style.display="none")}async showPlanHistory(){if(this.activeSessionId)try{const t=await(await fetch(`/api/sessions/${this.activeSessionId}/plan/history`)).json();if(t.error){this.showToast("Failed to load plan history: "+t.error,"error");return}const s=t.history||[];if(s.length===0){this.showToast("No plan history available","info");return}this.showPlanHistoryModal(s,t.currentVersion)}catch(e){this.showToast("Failed to load plan history: "+e.message,"error")}}showPlanHistoryModal(e,t){const s=document.getElementById("planHistoryModal");s&&s.remove();const n=document.createElement("div");n.id="planHistoryModal",n.className="modal active",n.innerHTML=`
|
|
222
|
+
<div class="modal-backdrop" onclick="app.closePlanHistoryModal()"></div>
|
|
223
|
+
<div class="modal-content modal-sm">
|
|
224
|
+
<div class="modal-header">
|
|
225
|
+
<h3>Plan Version History</h3>
|
|
226
|
+
<button class="modal-close" onclick="app.closePlanHistoryModal()">×</button>
|
|
227
|
+
</div>
|
|
228
|
+
<div class="modal-body">
|
|
229
|
+
<p style="font-size: 0.8rem; color: var(--text-muted); margin-bottom: 0.75rem;">
|
|
230
|
+
Current version: <strong>v${t}</strong>
|
|
231
|
+
</p>
|
|
232
|
+
<div class="plan-history-list">
|
|
233
|
+
${e.map(i=>`
|
|
234
|
+
<div class="plan-history-item ${i.version===t?"current":""}"
|
|
235
|
+
onclick="app.rollbackToPlanVersion(${i.version})">
|
|
236
|
+
<div>
|
|
237
|
+
<span class="plan-history-version">v${i.version}</span>
|
|
238
|
+
<span class="plan-history-tasks">${i.taskCount||0} tasks</span>
|
|
239
|
+
</div>
|
|
240
|
+
<span class="plan-history-time">${this.formatRelativeTime(i.timestamp)}</span>
|
|
241
|
+
</div>
|
|
242
|
+
`).join("")}
|
|
243
|
+
</div>
|
|
244
|
+
</div>
|
|
245
|
+
<div class="modal-footer">
|
|
246
|
+
<button class="btn-toolbar" onclick="app.closePlanHistoryModal()">Close</button>
|
|
247
|
+
</div>
|
|
248
|
+
</div>
|
|
249
|
+
`,document.body.appendChild(n)}closePlanHistoryModal(){const e=document.getElementById("planHistoryModal");e&&e.remove()}async rollbackToPlanVersion(e){if(this.activeSessionId&&confirm(`Rollback to plan version ${e}? Current changes will be preserved in history.`))try{const s=await(await fetch(`/api/sessions/${this.activeSessionId}/plan/rollback/${e}`,{method:"POST"})).json();if(s.error){this.showToast("Failed to rollback: "+s.error,"error");return}this.showToast(`Rolled back to plan v${e}`,"success"),this.closePlanHistoryModal(),this.renderRalphStatePanel()}catch(t){this.showToast("Failed to rollback: "+t.message,"error")}}formatRelativeTime(e){if(!e)return"";const s=Date.now()-e,n=Math.floor(s/6e4),i=Math.floor(s/36e5),o=Math.floor(s/864e5);return n<1?"just now":n<60?`${n}m ago`:i<24?`${i}h ago`:`${o}d ago`}toggleSubagentPanel(){this.toggleSubagentsPanel()}updateSubagentBadge(){const e=this.$("subagentCountBadge"),t=Array.from(this.subagents.values()).filter(s=>s.status==="active"||s.status==="idle").length;e&&(e.textContent=t>0?t:"")}renderSubagentPanel(){this._subagentPanelRenderTimeout&&clearTimeout(this._subagentPanelRenderTimeout),this._subagentPanelRenderTimeout=setTimeout(()=>{scheduleBackground(()=>this._renderSubagentPanelImmediate())},150)}_renderSubagentPanelImmediate(){const e=this.$("subagentList");if(!e||(this.updateSubagentBadge(),this.renderMonitorSubagents(),!this.subagentPanelVisible))return;if(this.subagents.size===0){e.innerHTML='<div class="subagent-empty">No background agents detected</div>';return}const t=[],s=Array.from(this.subagents.values()).sort((n,i)=>n.status==="active"&&i.status!=="active"?-1:i.status==="active"&&n.status!=="active"?1:(i.lastActivityAt||0)-(n.lastActivityAt||0));for(const n of s){const i=this.activeSubagentId===n.agentId,o=n.status==="active"?"active":n.status==="idle"?"idle":"completed",l=this.subagentActivity.get(n.agentId)||[],a=l[l.length-1],r=a?.type==="tool"?a.tool:null,c=this.subagentWindows.has(n.agentId),h=n.status==="active"||n.status==="idle",u=n.modelShort?`<span class="subagent-model-badge ${this.escapeHtml(n.modelShort)}">${this.escapeHtml(n.modelShort)}</span>`:"",m=this.getTeammateInfo(n),p=m?m.name:n.description||n.agentId.substring(0,7),g=this.getTeammateBadgeHtml(n),y=m?`<span class="subagent-icon teammate-dot teammate-color-${m.color}">\u25CF</span>`:'<span class="subagent-icon">\u{1F916}</span>';t.push(`
|
|
250
|
+
<div class="subagent-item ${o} ${i?"selected":""}${m?" is-teammate":""}"
|
|
251
|
+
onclick="app.selectSubagent('${this.escapeHtml(n.agentId)}')"
|
|
252
|
+
ondblclick="app.openSubagentWindow('${this.escapeHtml(n.agentId)}')"
|
|
253
|
+
title="Double-click to open tracking window">
|
|
254
|
+
<div class="subagent-header">
|
|
255
|
+
${y}
|
|
256
|
+
<span class="subagent-id" title="${this.escapeHtml(n.description||n.agentId)}">${this.escapeHtml(p.length>40?p.substring(0,40)+"...":p)}</span>
|
|
257
|
+
${g}
|
|
258
|
+
${u}
|
|
259
|
+
<span class="subagent-status ${o}">${n.status}</span>
|
|
260
|
+
${h?`<button class="subagent-kill-btn" onclick="event.stopPropagation(); app.killSubagent('${this.escapeHtml(n.agentId)}')" title="Kill agent">✕</button>`:""}
|
|
261
|
+
<button class="subagent-window-btn" onclick="event.stopPropagation(); app.${c?"closeSubagentWindow":"openSubagentWindow"}('${this.escapeHtml(n.agentId)}')" title="${c?"Close window":"Open in window"}">
|
|
262
|
+
${c?"\u2715":"\u29C9"}
|
|
263
|
+
</button>
|
|
264
|
+
</div>
|
|
265
|
+
<div class="subagent-meta">
|
|
266
|
+
<span class="subagent-tools">${n.toolCallCount} tools</span>
|
|
267
|
+
${r?`<span class="subagent-last-tool">${this.getToolIcon(r)} ${r}</span>`:""}
|
|
268
|
+
</div>
|
|
269
|
+
</div>
|
|
270
|
+
`)}e.innerHTML=t.join("")}selectSubagent(e){this.activeSubagentId=e,this.renderSubagentPanel(),this.renderSubagentDetail()}renderSubagentDetail(){const e=this.$("subagentDetail");if(!e)return;if(!this.activeSubagentId){e.innerHTML='<div class="subagent-empty">Select an agent to view details</div>';return}const t=this.subagents.get(this.activeSubagentId),s=this.subagentActivity.get(this.activeSubagentId)||[];if(!t){e.innerHTML='<div class="subagent-empty">Agent not found</div>';return}const n=s.slice(-30).map(a=>{const r=new Date(a.timestamp).toLocaleTimeString("en-US",{hour12:!1});if(a.type==="tool"){const c=this.getToolDetailExpanded(a.tool,a.input,a.fullInput,a.toolUseId);return`<div class="subagent-activity tool" data-tool-use-id="${a.toolUseId||""}">
|
|
271
|
+
<span class="time">${r}</span>
|
|
272
|
+
<span class="icon">${this.getToolIcon(a.tool)}</span>
|
|
273
|
+
<span class="name">${a.tool}</span>
|
|
274
|
+
<span class="detail">${c.primary}</span>
|
|
275
|
+
${c.hasMore?`<button class="tool-expand-btn" onclick="app.toggleToolParams('${this.escapeHtml(a.toolUseId)}')">\u25B6</button>`:""}
|
|
276
|
+
${c.hasMore?`<div class="tool-params-expanded" id="tool-params-${a.toolUseId}" style="display:none;"><pre>${this.escapeHtml(JSON.stringify(a.fullInput||a.input,null,2))}</pre></div>`:""}
|
|
277
|
+
</div>`}else if(a.type==="tool_result"){const c=a.isError?"\u274C":"\u{1F4C4}",h=a.isError?"error":"",u=a.contentLength>500?` (${this.formatBytes(a.contentLength)})`:"",m=a.preview.length>80?a.preview.substring(0,80)+"...":a.preview;return`<div class="subagent-activity tool-result ${h}">
|
|
278
|
+
<span class="time">${r}</span>
|
|
279
|
+
<span class="icon">${c}</span>
|
|
280
|
+
<span class="name">${a.tool||"result"}</span>
|
|
281
|
+
<span class="detail">${this.escapeHtml(m)}${u}</span>
|
|
282
|
+
</div>`}else if(a.type==="progress"){const c=a.hookEvent||a.hookName,h=c?"\u{1FA9D}":a.progressType==="query_update"?"\u27F3":"\u2713",u=c?" hook":"",m=c?a.hookName||a.hookEvent:a.query||a.progressType;return`<div class="subagent-activity progress${u}">
|
|
283
|
+
<span class="time">${r}</span>
|
|
284
|
+
<span class="icon">${h}</span>
|
|
285
|
+
<span class="detail">${m}</span>
|
|
286
|
+
</div>`}else if(a.type==="message"){const c=a.text.length>100?a.text.substring(0,100)+"...":a.text;return`<div class="subagent-activity message">
|
|
287
|
+
<span class="time">${r}</span>
|
|
288
|
+
<span class="icon">\u{1F4AC}</span>
|
|
289
|
+
<span class="detail">${this.escapeHtml(c)}</span>
|
|
290
|
+
</div>`}return""}).join(""),i=t.description||`Agent ${t.agentId}`,o=t.modelShort?`<span class="subagent-model-badge ${this.escapeHtml(t.modelShort)}">${this.escapeHtml(t.modelShort)}</span>`:"",l=t.totalInputTokens||t.totalOutputTokens?`<span>Tokens: ${this.formatTokenCount(t.totalInputTokens||0)}\u2193 ${this.formatTokenCount(t.totalOutputTokens||0)}\u2191</span>`:"";e.innerHTML=`
|
|
291
|
+
<div class="subagent-detail-header">
|
|
292
|
+
<span class="subagent-id" title="${this.escapeHtml(t.description||t.agentId)}">${this.escapeHtml(i.length>60?i.substring(0,60)+"...":i)}</span>
|
|
293
|
+
${o}
|
|
294
|
+
<span class="subagent-status ${t.status}">${t.status}</span>
|
|
295
|
+
<button class="subagent-transcript-btn" onclick="app.viewSubagentTranscript('${this.escapeHtml(t.agentId)}')">
|
|
296
|
+
View Full Transcript
|
|
297
|
+
</button>
|
|
298
|
+
</div>
|
|
299
|
+
<div class="subagent-detail-stats">
|
|
300
|
+
<span>Tools: ${t.toolCallCount}</span>
|
|
301
|
+
<span>Entries: ${t.entryCount}</span>
|
|
302
|
+
<span>Size: ${(t.fileSize/1024).toFixed(1)}KB</span>
|
|
303
|
+
${l}
|
|
304
|
+
</div>
|
|
305
|
+
<div class="subagent-activity-log">
|
|
306
|
+
${n||'<div class="subagent-empty">No activity yet</div>'}
|
|
307
|
+
</div>
|
|
308
|
+
`}toggleToolParams(e){const t=document.getElementById(`tool-params-${e}`);if(!t)return;const s=t.previousElementSibling;t.style.display==="none"?(t.style.display="block",s&&(s.textContent="\u25BC")):(t.style.display="none",s&&(s.textContent="\u25B6"))}formatTokenCount(e){return e>=1e6?(e/1e6).toFixed(1)+"M":e>=1e3?(e/1e3).toFixed(1)+"k":e.toString()}formatBytes(e){return e>=1024*1024?(e/(1024*1024)).toFixed(1)+"MB":e>=1024?(e/1024).toFixed(1)+"KB":e+"B"}getToolIcon(e){return{WebSearch:"\u{1F50D}",WebFetch:"\u{1F310}",Read:"\u{1F4D6}",Write:"\u{1F4DD}",Edit:"\u270F\uFE0F",Bash:"\u{1F4BB}",Glob:"\u{1F4C1}",Grep:"\u{1F50E}",Task:"\u{1F916}"}[e]||"\u{1F527}"}getToolDetail(e,t){if(!t)return"";if(e==="WebSearch"&&t.query)return`"${t.query}"`;if(e==="WebFetch"&&t.url)return t.url;if(e==="Read"&&t.file_path||(e==="Write"||e==="Edit")&&t.file_path)return t.file_path;if(e==="Bash"&&t.command){const s=t.command;return s.length>40?s.substring(0,40)+"...":s}return e==="Glob"&&t.pattern||e==="Grep"&&t.pattern?t.pattern:""}getToolDetailExpanded(e,t,s,n){const i=this.getToolDetail(e,t),o=["query","url","file_path","command","pattern"],r=Object.keys(s||t||{}).filter(c=>!o.includes(c)).length>0||s&&JSON.stringify(s).length>100;return{primary:i,hasMore:r,fullInput:s||t}}async killSubagent(e){try{const s=await(await fetch(`/api/subagents/${e}`,{method:"DELETE"})).json();if(s.success){const n=this.subagents.get(e);n&&(n.status="completed",this.subagents.set(e,n)),this.renderSubagentPanel(),this.renderSubagentDetail(),this.updateSubagentWindows(),this.showToast(`Subagent ${e.substring(0,7)} killed`,"success")}else this.showToast(s.error||"Failed to kill subagent","error")}catch(t){this.showToast("Failed to kill subagent: "+t.message,"error")}}async viewSubagentTranscript(e){try{const s=await(await fetch(`/api/subagents/${e}/transcript?format=formatted`)).json();if(!s.success){alert("Failed to load transcript");return}const n=s.data.formatted.join(`
|
|
309
|
+
`);window.open("","_blank","width=800,height=600").document.write(`
|
|
310
|
+
<html>
|
|
311
|
+
<head>
|
|
312
|
+
<title>Subagent ${this.escapeHtml(e)} Transcript</title>
|
|
313
|
+
<style>
|
|
314
|
+
body { background: #1a1a2e; color: #eee; font-family: monospace; padding: 20px; }
|
|
315
|
+
pre { white-space: pre-wrap; word-wrap: break-word; }
|
|
316
|
+
</style>
|
|
317
|
+
</head>
|
|
318
|
+
<body>
|
|
319
|
+
<h2>Subagent ${this.escapeHtml(e)} Transcript (${s.data.entryCount} entries)</h2>
|
|
320
|
+
<pre>${this.escapeHtml(n)}</pre>
|
|
321
|
+
</body>
|
|
322
|
+
</html>
|
|
323
|
+
`)}catch(t){alert("Failed to load transcript: "+t.message)}}findParentSessionForSubagent(e){if(this.subagentParentMap.has(e)){const s=this.subagentParentMap.get(e);if(this.sessions.has(s)){const n=this.subagents.get(e);if(n&&!n.parentSessionId){n.parentSessionId=s;const i=this.sessions.get(s);i&&(n.parentSessionName=this.getSessionName(i)),this.subagents.set(e,n),this.updateSubagentWindowParent(e)}return}this.subagentParentMap.delete(e)}const t=this.subagents.get(e);if(t){if(t.sessionId){for(const[s,n]of this.sessions)if(n.claudeSessionId===t.sessionId){this.setAgentParentSessionId(e,s),this.updateSubagentWindowParent(e),this.updateSubagentWindowVisibility(),this.updateConnectionLines();return}}if(this.activeSessionId&&this.sessions.has(this.activeSessionId)){this.setAgentParentSessionId(e,this.activeSessionId),this.updateSubagentWindowParent(e),this.updateSubagentWindowVisibility(),this.updateConnectionLines();return}if(this.sessions.size>0){const s=this.sessions.keys().next().value;this.setAgentParentSessionId(e,s),this.updateSubagentWindowParent(e),this.updateSubagentWindowVisibility(),this.updateConnectionLines()}}}recheckOrphanSubagents(){let e=!1;for(const[t,s]of this.subagents)if(!this.subagentParentMap.has(t))this.findParentSessionForSubagent(t),this.subagentParentMap.has(t)&&(e=!0);else if(s.sessionId){const n=this.subagentParentMap.get(t),i=this.sessions.get(n);if(i&&i.claudeSessionId!==s.sessionId){for(const[o,l]of this.sessions)if(l.claudeSessionId===s.sessionId){this.subagentParentMap.set(t,o),s.parentSessionId=o,s.parentSessionName=this.getSessionName(l),this.subagents.set(t,s),this.updateSubagentWindowParent(t),e=!0;break}}}e&&(this.saveSubagentParentMap(),this.updateConnectionLines())}updateSubagentParentNames(e){const t=this.sessions.get(e);if(!t)return;const s=this.getSessionName(t);if(this._parentNameCache?.get(e)!==s){this._parentNameCache||(this._parentNameCache=new Map),this._parentNameCache.set(e,s);for(const[i,o]of this.subagentParentMap)if(o===e){const l=this.subagents.get(i);if(l){l.parentSessionName=s,this.subagents.set(i,l);const a=this.subagentWindows.get(i);if(a){const r=a.element.querySelector(".subagent-window-parent .parent-name");r&&(r.textContent=s)}}}}}updateSubagentWindowParent(e){const t=this.subagentWindows.get(e);if(!t)return;const s=this.subagentParentMap.get(e);if(!s)return;const n=this.sessions.get(s),i=n?this.getSessionName(n):"Unknown",o=t.element,l=o.querySelector(".subagent-window-parent");if(l){l.dataset.parentSession=s;const r=l.querySelector(".parent-name");r&&(r.textContent=i,r.onclick=()=>this.selectSession(s));return}const a=o.querySelector(".subagent-window-header");if(a){const r=document.createElement("div");r.className="subagent-window-parent",r.dataset.parentSession=s,r.innerHTML=`
|
|
324
|
+
<span class="parent-label">from</span>
|
|
325
|
+
<span class="parent-name" onclick="app.selectSession('${this.escapeHtml(s)}')">${this.escapeHtml(i)}</span>
|
|
326
|
+
`,a.insertAdjacentElement("afterend",r)}}updateConnectionLines(){this._connectionLinesScheduled||(this._connectionLinesScheduled=!0,scheduleBackground(()=>{this._connectionLinesScheduled=!1,this._updateConnectionLinesImmediate()}))}_updateConnectionLinesImmediate(){const e=document.getElementById("connectionLines");if(!e)return;e.innerHTML="";const t=document.getElementById("ralphWizardModal"),s=t?.classList.contains("active"),n=s?t.querySelector(".modal-content"):null,i=[];for(const[l,a]of this.subagentWindows){if(a.minimized||a.hidden)continue;const r=a.element;r&&i.push({agentId:l,windowInfo:a,win:r})}const o=Array.from(this.planSubagents.entries()).filter(([,l])=>l.element).map(([l,a])=>({id:l,...a}));for(const{agentId:l,win:a}of i){const r=a.getBoundingClientRect();if(s&&n&&o.length>0){let c=null,h=1/0;for(const u of o){const m=u.element.getBoundingClientRect(),p=m.left+m.width/2,g=m.top+m.height/2,y=r.left+r.width/2,f=r.top+r.height/2,w=Math.hypot(p-y,g-f);w<h&&(h=w,c=u)}if(c){const u=c.element.getBoundingClientRect();let m,p,g,y;const f=u.left+u.width/2;r.left+r.width/2<f?(m=u.left,p=u.top+u.height/2,g=r.right,y=r.top+r.height/2):(m=u.right,p=u.top+u.height/2,g=r.left,y=r.top+r.height/2);const v=(m+g)/2,S=`M ${m} ${p} C ${v} ${p}, ${v} ${y}, ${g} ${y}`,b=document.createElementNS("http://www.w3.org/2000/svg","path");b.setAttribute("d",S),b.setAttribute("class","connection-line plan-to-subagent-line"),b.setAttribute("data-agent-id",l),b.setAttribute("data-plan-agent-id",c.id),e.appendChild(b)}}else if(s&&n){const c=n.getBoundingClientRect(),h=r.left+r.width/2,u=c.left+c.width/2;let m,p,g,y;h<u?(m=c.left,p=c.top+c.height/2,g=r.right,y=r.top+r.height/2):(m=c.right,p=c.top+c.height/2,g=r.left,y=r.top+r.height/2);const f=(m+g)/2,w=`M ${m} ${p} C ${f} ${p}, ${f} ${y}, ${g} ${y}`,v=document.createElementNS("http://www.w3.org/2000/svg","path");v.setAttribute("d",w),v.setAttribute("class","connection-line wizard-connection"),v.setAttribute("data-agent-id",l),e.appendChild(v)}else{const c=this.subagentParentMap.get(l);if(!c)continue;const h=document.querySelector(`.session-tab[data-id="${c}"]`);if(!h)continue;const u=h.getBoundingClientRect(),m=u.left+u.width/2,p=u.bottom,g=r.left+r.width/2,y=r.top,f=(p+y)/2,w=`M ${m} ${p} C ${m} ${f}, ${g} ${f}, ${g} ${y}`,v=document.createElementNS("http://www.w3.org/2000/svg","path");v.setAttribute("d",w),v.setAttribute("class","connection-line"),v.setAttribute("data-agent-id",l),v.setAttribute("data-parent-tab",c),e.appendChild(v)}}if(s&&n&&this.planSubagents.size>0&&!this.planAgentsMinimized){const l=n.getBoundingClientRect();for(const[a,r]of this.planSubagents){const c=r.element;if(!c)continue;const h=c.getBoundingClientRect(),u=h.left+h.width/2,m=l.left+l.width/2;let p,g,y,f;u<m?(p=l.left,g=l.top+l.height/3+(this.planSubagents.size>3?0:50),y=h.right,f=h.top+h.height/2):(p=l.right,g=l.top+l.height/3+(this.planSubagents.size>3?0:50),y=h.left,f=h.top+h.height/2);const w=(p+y)/2,v=`M ${p} ${g} C ${w} ${g}, ${w} ${f}, ${y} ${f}`,S=document.createElementNS("http://www.w3.org/2000/svg","path");S.setAttribute("d",v),S.setAttribute("class","connection-line wizard-connection plan-subagent-line"),S.setAttribute("data-plan-agent-id",a),e.appendChild(S)}}}updateSubagentWindowVisibility(){const t=this.loadAppSettingsFromStorage().subagentActiveTabOnly??!0;for(const[s,n]of this.subagentWindows){const i=this.subagentParentMap.get(s),o=this.subagents.get(s),l=i||o?.parentSessionId;let a;t?a=!!!l||l===this.activeSessionId:a=!0,a?(n.minimized||(n.element.style.display="flex"),n.hidden=!1):(n.element.style.display="none",n.hidden=!0)}this.updateConnectionLines(),this.relayoutMobileSubagentWindows()}openSubagentWindow(e){if(this.subagentWindows.has(e)){const I=this.subagentWindows.get(e),x=this.subagents.get(e),k=this.loadAppSettingsFromStorage().subagentActiveTabOnly??!0;if(I.hidden&&x?.parentSessionId&&k){this.selectSession(x.parentSessionId);return}I.hidden&&!k&&(I.element.style.display="flex",I.hidden=!1),I.element.style.zIndex=++this.subagentWindowZIndex,I.minimized&&this.restoreSubagentWindow(e);return}const t=this.subagents.get(e);if(!t||t.sessionId&&!Array.from(this.sessions.values()).some(x=>x.claudeSessionId===t.sessionId))return;const s=this.subagentWindows.size,n=MobileDetection.getDeviceType()==="mobile",i=110,o=4,l=n?window.innerWidth:420,a=n?i:350,r=20,c=window.innerWidth,h=window.innerHeight;let u=0,m=0;if(n){let I=0;for(const[,E]of this.subagentWindows)!E.minimized&&!E.hidden&&I++;if(u=4,typeof KeyboardHandler<"u"&&KeyboardHandler.keyboardVisible){const k=40+I*(i+o);m=h-k-i}else m=(document.querySelector(".header")?.offsetHeight||36)+8+I*(i+o)}else{const x=document.getElementById("ralphWizardModal")?.classList.contains("active");let E,k,L;if(x){const A=c/2,F=A-720/2,M=A+720/2,z=F-20,R=c-M-20;s%2===0&&R>=l?(E=M+20,L=Math.floor(R/(l+r))||1):z>=l?(E=Math.max(10,F-l-20),L=1):(E=M+20,L=1),k=80}else E=50,k=120,L=Math.floor((c-E-50)/(l+r))||1;const H=Math.floor((h-k-50)/(a+r))||1,N=s%L,W=Math.floor(s/L)%H;u=E+N*(l+r),m=k+W*(a+r),u=Math.max(10,Math.min(u,c-l-10)),m=Math.max(10,Math.min(m,h-a-10))}const p=this.subagentParentMap.get(e)||t.parentSessionId;let g=null;if(p){const I=this.sessions.get(p);I&&(g=this.getSessionName(I),t.parentSessionId||(t.parentSessionId=p,t.parentSessionName=g,this.subagents.set(e,t)))}const y=p?document.querySelector(`.session-tab[data-id="${p}"]`):null,f=document.createElement("div");f.className="subagent-window",f.id=`subagent-window-${e}`,f.style.zIndex=++this.subagentWindowZIndex;const w=p&&g?`<div class="subagent-window-parent" data-parent-session="${p}">
|
|
327
|
+
<span class="parent-label">from</span>
|
|
328
|
+
<span class="parent-name" onclick="app.selectSession('${this.escapeHtml(p)}')">${this.escapeHtml(g)}</span>
|
|
329
|
+
</div>`:"",v=this.getTeammateInfo(t),S=v?v.name:t.description||e.substring(0,7),b=n?30:50,T=S.length>b?S.substring(0,b)+"...":S,_=t.modelShort?`<span class="subagent-model-badge ${t.modelShort}">${t.modelShort}</span>`:"";if(f.innerHTML=`
|
|
330
|
+
<div class="subagent-window-header">
|
|
331
|
+
<div class="subagent-window-title" title="${this.escapeHtml(t.description||e)}">
|
|
332
|
+
<span class="icon">\u{1F916}</span>
|
|
333
|
+
<span class="id">${this.escapeHtml(T)}</span>
|
|
334
|
+
${_}
|
|
335
|
+
<span class="status ${t.status}">${t.status}</span>
|
|
336
|
+
</div>
|
|
337
|
+
<div class="subagent-window-actions">
|
|
338
|
+
<button onclick="app.closeSubagentWindow('${this.escapeHtml(e)}')" title="Minimize to tab">\u2500</button>
|
|
339
|
+
</div>
|
|
340
|
+
</div>
|
|
341
|
+
${w}
|
|
342
|
+
<div class="subagent-window-body" id="subagent-window-body-${e}">
|
|
343
|
+
<div class="subagent-empty">Loading activity...</div>
|
|
344
|
+
</div>
|
|
345
|
+
`,n)f.style.top=`${m}px`,f.style.bottom="auto";else if(y){const I=y.getBoundingClientRect();f.style.left=`${I.left}px`,f.style.top=`${I.bottom}px`,f.style.transform="scale(0.3)",f.style.opacity="0",f.classList.add("spawning")}else f.style.left=`${u}px`,f.style.top=`${m}px`;document.body.appendChild(f);const C=this.makeWindowDraggable(f,f.querySelector(".subagent-window-header")),O=this.loadAppSettingsFromStorage().subagentActiveTabOnly??!0;let P=!1;if(O){const I=this.subagentParentMap.get(e),x=I||t.parentSessionId,E=I||t.parentSessionId;P=!(!x||E===this.activeSessionId)}this.subagentWindows.set(e,{element:f,minimized:!1,hidden:P,dragListeners:C}),P&&(f.style.display="none");const $=v?this.teammatePanesByName.get(v.name):null;$?this.initTeammateTerminal(e,$,f):this.renderSubagentWindowContent(e),f.addEventListener("mousedown",()=>{f.style.zIndex=++this.subagentWindowZIndex});const D=new ResizeObserver(()=>{this.updateConnectionLines()});D.observe(f),this.subagentWindows.get(e).resizeObserver=D,y&&!n?requestAnimationFrame(()=>{f.style.transition="all 0.4s cubic-bezier(0.34, 1.56, 0.64, 1)",f.style.left=`${u}px`,f.style.top=`${m}px`,f.style.transform="scale(1)",f.style.opacity="1",setTimeout(()=>{f.style.transition="",f.classList.remove("spawning"),this.updateConnectionLines()},400)}):this.updateConnectionLines(),this.saveSubagentWindowStates()}closeSubagentWindow(e){const t=this.subagentWindows.get(e);if(!t)return;const s=this.subagents.get(e),n=this.subagentParentMap.get(e);let i=n||s?.parentSessionId||this.activeSessionId;!n&&i&&this.sessions.has(i)&&this.setAgentParentSessionId(e,i),t.element.style.display="none",t.minimized=!0,i&&(this.minimizedSubagents.has(i)||this.minimizedSubagents.set(i,new Set),this.minimizedSubagents.get(i).add(e),this.renderSessionTabs()),this.saveSubagentWindowStates(),this.updateConnectionLines(),this.relayoutMobileSubagentWindows()}relayoutMobileSubagentWindows(){if(MobileDetection.getDeviceType()!=="mobile")return;const e=110,t=4,s=typeof KeyboardHandler<"u"&&KeyboardHandler.keyboardVisible;let n=0;for(const[,i]of this.subagentWindows){if(i.minimized||i.hidden)continue;const o=i.element;if(o.style.left="4px",s){const l=40+n*(e+t);o.style.bottom=`${l}px`,o.style.top="auto"}else{const a=(document.querySelector(".header")?.offsetHeight||36)+8+n*(e+t);o.style.top=`${a}px`,o.style.bottom="auto"}n++}}closeSessionSubagentWindows(e,t=!1){const s=[];for(const[n,i]of this.subagentWindows){const o=this.subagents.get(n),l=this.subagentParentMap.get(n);(o?.parentSessionId===e||l===e)&&s.push(n)}for(const n of s)this.forceCloseSubagentWindow(n),t&&(this.subagents.delete(n),this.subagentActivity.delete(n),this.subagentToolResults.delete(n),this.subagentParentMap.delete(n));this.minimizedSubagents.delete(e),this.renderSessionTabs()}forceCloseSubagentWindow(e){const t=this.subagentWindows.get(e);t&&(t.resizeObserver&&t.resizeObserver.disconnect(),t.dragListeners&&(document.removeEventListener("mousemove",t.dragListeners.move),document.removeEventListener("mouseup",t.dragListeners.up),t.dragListeners.touchMove&&(document.removeEventListener("touchmove",t.dragListeners.touchMove),document.removeEventListener("touchend",t.dragListeners.up),document.removeEventListener("touchcancel",t.dragListeners.up))),t.element.remove(),this.subagentWindows.delete(e));const s=this.teammateTerminals.get(e);if(s){if(s.resizeObserver&&s.resizeObserver.disconnect(),s.terminal)try{s.terminal.dispose()}catch{}this.teammateTerminals.delete(e)}}cleanupAllFloatingWindows(){for(const[e,t]of this.subagentWindows)t.resizeObserver&&t.resizeObserver.disconnect(),t.dragListeners&&(document.removeEventListener("mousemove",t.dragListeners.move),document.removeEventListener("mouseup",t.dragListeners.up),t.dragListeners.touchMove&&(document.removeEventListener("touchmove",t.dragListeners.touchMove),document.removeEventListener("touchend",t.dragListeners.up),document.removeEventListener("touchcancel",t.dragListeners.up))),t.element.remove();this.subagentWindows.clear();for(const[,e]of this.teammateTerminals)if(e.resizeObserver&&e.resizeObserver.disconnect(),e.terminal)try{e.terminal.dispose()}catch{}this.teammateTerminals.clear(),this.teammatePanesByName.clear();for(const[e,t]of this.logViewerWindows)t.eventSource&&t.eventSource.close(),t.dragListeners&&(document.removeEventListener("mousemove",t.dragListeners.move),document.removeEventListener("mouseup",t.dragListeners.up),t.dragListeners.touchMove&&(document.removeEventListener("touchmove",t.dragListeners.touchMove),document.removeEventListener("touchend",t.dragListeners.up),document.removeEventListener("touchcancel",t.dragListeners.up))),t.element.remove();if(this.logViewerWindows.clear(),this.planSubagents){for(const[e,t]of this.planSubagents)t.dragListeners&&(document.removeEventListener("mousemove",t.dragListeners.move),document.removeEventListener("mouseup",t.dragListeners.up)),t.element&&t.element.remove();this.planSubagents.clear()}for(const[e,t]of this.imagePopups)t.dragListeners&&(document.removeEventListener("mousemove",t.dragListeners.move),document.removeEventListener("mouseup",t.dragListeners.up),t.dragListeners.touchMove&&(document.removeEventListener("touchmove",t.dragListeners.touchMove),document.removeEventListener("touchend",t.dragListeners.up),document.removeEventListener("touchcancel",t.dragListeners.up))),t.element.remove();this.imagePopups.clear(),this.activePlanOrchestratorId=null,this._planProgressHandler=null,this.planGenerationStopped=!0,this.planGenerationAbortController&&(this.planGenerationAbortController.abort(),this.planGenerationAbortController=null),this.wizardMinimizedTimer&&(clearInterval(this.wizardMinimizedTimer),this.wizardMinimizedTimer=null),this.cleanupWizardDragging(),this.activeFocusTrap&&(this.activeFocusTrap.deactivate(),this.activeFocusTrap=null),this.teamTasksDragListeners&&(document.removeEventListener("mousemove",this.teamTasksDragListeners.move),document.removeEventListener("mouseup",this.teamTasksDragListeners.up),this.teamTasksDragListeners.touchMove&&(document.removeEventListener("touchmove",this.teamTasksDragListeners.touchMove),document.removeEventListener("touchend",this.teamTasksDragListeners.up),document.removeEventListener("touchcancel",this.teamTasksDragListeners.up)),this.teamTasksDragListeners=null),this.minimizedSubagents.clear(),this.renderMonitorPlanAgents(),this.updateConnectionLines()}minimizeSubagentWindow(e){const t=this.subagentWindows.get(e);t&&(t.element.style.display="none",t.minimized=!0,this.updateConnectionLines())}restoreSubagentWindow(e){const t=this.subagentWindows.get(e),s=this.subagents.get(e);if(!t&&s){this.openSubagentWindow(e);return}if(t){const i=this.loadAppSettingsFromStorage().subagentActiveTabOnly??!0,l=this.subagentParentMap.get(e)||s?.parentSessionId;let a=!0;i&&(a=!l||l===this.activeSessionId),a&&(t.element.style.display="flex",t.element.style.zIndex=++this.subagentWindowZIndex,t.hidden=!1),t.minimized=!1,this.updateConnectionLines(),this.relayoutMobileSubagentWindows()}}makeWindowDraggable(e,t){let s=!1,n,i,o,l,a=!1;const r=(g,y)=>{s=!0,n=g,i=y,o=parseInt(e.style.left)||e.getBoundingClientRect().left,l=parseInt(e.style.top)||e.getBoundingClientRect().top,e.style.bottom="auto"},c=(g,y)=>{if(!s)return;const f=g-n,w=y-i,v=e.offsetWidth||420,S=e.offsetHeight||350,b=window.innerWidth-v-4,T=window.innerHeight-S-4,_=Math.max(4,Math.min(o+f,b)),C=Math.max(4,Math.min(l+w,T));e.style.left=`${_}px`,e.style.top=`${C}px`,a||(a=!0,requestAnimationFrame(()=>{this.updateConnectionLines(),a=!1}))},h=()=>{s&&(s=!1,this.saveSubagentWindowStates())};t.addEventListener("mousedown",g=>{g.target.tagName!=="BUTTON"&&(r(g.clientX,g.clientY),g.preventDefault())}),t.addEventListener("touchstart",g=>{if(g.target.tagName==="BUTTON")return;const y=g.touches[0];r(y.clientX,y.clientY)},{passive:!0});const u=g=>{c(g.clientX,g.clientY)},m=g=>{if(!s)return;g.preventDefault();const y=g.touches[0];c(y.clientX,y.clientY)},p=()=>{h()};return document.addEventListener("mousemove",u),document.addEventListener("mouseup",p),document.addEventListener("touchmove",m,{passive:!1}),document.addEventListener("touchend",p),document.addEventListener("touchcancel",p),{move:u,up:p,touchMove:m}}renderSubagentWindowContent(e){if(this.teammateTerminals.has(e))return;const t=document.getElementById(`subagent-window-body-${e}`);if(!t)return;const s=this.subagentActivity.get(e)||[];if(s.length===0){t.innerHTML='<div class="subagent-empty">No activity yet</div>';return}const n=t.dataset.renderedCount?parseInt(t.dataset.renderedCount,10):0,i=100,o=s.slice(-i);if(n===0||n>o.length||t.children.length===0||t.children.length===1&&t.querySelector(".subagent-empty")){const l=o.map(a=>this._renderActivityItem(a)).join("");t.innerHTML=l,t.dataset.renderedCount=String(o.length)}else{const l=o.slice(n);if(l.length>0){const a=l.map(r=>this._renderActivityItem(r)).join("");for(t.insertAdjacentHTML("beforeend",a),t.dataset.renderedCount=String(o.length);t.children.length>i;)t.removeChild(t.firstChild)}}t.scrollTop=t.scrollHeight}_renderActivityItem(e){const t=new Date(e.timestamp).toLocaleTimeString("en-US",{hour12:!1});if(e.type==="tool")return`<div class="activity-line">
|
|
346
|
+
<span class="time">${t}</span>
|
|
347
|
+
<span class="tool-icon">${this.getToolIcon(e.tool)}</span>
|
|
348
|
+
<span class="tool-name">${e.tool}</span>
|
|
349
|
+
<span class="tool-detail">${this.escapeHtml(this.getToolDetail(e.tool,e.input))}</span>
|
|
350
|
+
</div>`;if(e.type==="tool_result"){const s=e.isError?"\u274C":"\u{1F4C4}",n=e.isError?" error":"",i=e.contentLength>500?` (${this.formatBytes(e.contentLength)})`:"",o=e.preview.length>60?e.preview.substring(0,60)+"...":e.preview;return`<div class="activity-line result-line${n}">
|
|
351
|
+
<span class="time">${t}</span>
|
|
352
|
+
<span class="tool-icon">${s}</span>
|
|
353
|
+
<span class="tool-name">${e.tool||"\u2192"}</span>
|
|
354
|
+
<span class="tool-detail">${this.escapeHtml(o)}${i}</span>
|
|
355
|
+
</div>`}else if(e.type==="progress"){const s=e.hookEvent||e.hookName,n=s?"\u{1FA9D}":e.progressType==="query_update"?"\u27F3":"\u2713",i=s?e.hookName||e.hookEvent:e.query||e.progressType;return`<div class="activity-line progress-line${s?" hook-line":""}">
|
|
356
|
+
<span class="time">${t}</span>
|
|
357
|
+
<span class="tool-icon">${n}</span>
|
|
358
|
+
<span class="tool-detail">${this.escapeHtml(i)}</span>
|
|
359
|
+
</div>`}else if(e.type==="message"){const s=e.text.length>150?e.text.substring(0,150)+"...":e.text;return`<div class="message-line">
|
|
360
|
+
<span class="time">${t}</span> \u{1F4AC} ${this.escapeHtml(s)}
|
|
361
|
+
</div>`}return""}updateSubagentWindows(){for(const e of this.subagentWindows.keys())this.renderSubagentWindowContent(e),this.updateSubagentWindowHeader(e)}updateSubagentWindowHeader(e){const t=this.subagents.get(e);if(!t)return;const s=document.getElementById(`subagent-window-${e}`);if(!s)return;const n=s.querySelector(".subagent-window-title .id");if(n){const c=this.getTeammateInfo(t),h=c?c.name:t.description||e.substring(0,7),u=h.length>50?h.substring(0,50)+"...":h;n.textContent=u}let i=s.querySelector(".teammate-badge");const o=this.getTeammateInfo(t);if(o&&!i){const c=s.querySelector(".subagent-window-title");if(c){const h=document.createElement("span");h.className=`teammate-badge teammate-color-${o.color}`,h.title=`Team: ${o.teamName}`,h.textContent=`@${o.name}`;const u=c.querySelector(".status");u&&u.insertAdjacentElement("beforebegin",h)}}const l=s.querySelector(".subagent-window-title");l&&(l.title=t.description||e);let a=s.querySelector(".subagent-window-title .subagent-model-badge");if(t.modelShort){if(!a){a=document.createElement("span"),a.className=`subagent-model-badge ${t.modelShort}`;const c=s.querySelector(".subagent-window-title .status");c&&c.insertAdjacentElement("beforebegin",a)}a.className=`subagent-model-badge ${t.modelShort}`,a.textContent=t.modelShort}const r=s.querySelector(".subagent-window-title .status");r&&(r.className=`status ${t.status}`,r.textContent=t.status)}openAllActiveSubagentWindows(){for(const[e,t]of this.subagents)t.status==="active"&&!this.subagentWindows.has(e)&&this.openSubagentWindow(e)}initTeammateTerminal(e,t,s){const n=s.querySelector(".subagent-window-body");if(!n)return;n.innerHTML="",n.classList.add("teammate-terminal-body"),s.classList.add("has-terminal");const i=t.sessionId,o=[];this.teammateTerminals.set(e,{terminal:null,fitAddon:null,paneTarget:t.paneTarget,sessionId:i,resizeObserver:null,pendingData:o}),requestAnimationFrame(()=>{if(!document.contains(n)){this.teammateTerminals.delete(e);return}const l=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:12,lineHeight:1.2,cursorBlink:!0,cursorStyle:"block",scrollback:5e3,allowTransparency:!0,allowProposedApi:!0}),a=new FitAddon.FitAddon;if(l.loadAddon(a),typeof Unicode11Addon<"u")try{const h=new Unicode11Addon.Unicode11Addon;l.loadAddon(h),l.unicode.activeVersion="11"}catch{}try{l.open(n)}catch{this.teammateTerminals.delete(e);return}setTimeout(()=>{try{a.fit()}catch{}fetch(`/api/sessions/${i}/teammate-pane-buffer/${encodeURIComponent(t.paneTarget)}`).then(h=>h.json()).then(h=>{if(h.success&&h.data?.buffer)try{l.write(h.data.buffer)}catch{}}).catch(h=>{});for(const h of o)try{l.write(h)}catch{}o.length=0},100),l.onData(h=>{fetch(`/api/sessions/${i}/teammate-pane-input`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({paneTarget:t.paneTarget,input:h})}).catch(u=>{})});const r=new ResizeObserver(()=>{requestAnimationFrame(()=>{try{a.fit()}catch{}})});r.observe(n);const c=this.teammateTerminals.get(e);c&&(c.terminal=l,c.fitAddon=a,c.resizeObserver=r)})}openTeammateTerminalWindow(e){if(!this.sessions.has(e.sessionId))return;const t=`pane-${e.paneTarget}`;if(this.subagentWindows.has(t)){const C=this.subagentWindows.get(t);C.hidden&&(C.element.style.display="flex",C.hidden=!1),C.element.style.zIndex=++this.subagentWindowZIndex,C.minimized&&this.restoreSubagentWindow(t);return}const s=this.subagentWindows.size,n=550,i=400,o=20,l=window.innerWidth,a=window.innerHeight,r=50,c=120,h=Math.floor((l-r-50)/(n+o))||1,u=Math.floor((a-c-50)/(i+o))||1,m=s%h,p=Math.floor(s/h)%u;let g=r+m*(n+o),y=c+p*(i+o);g=Math.max(10,Math.min(g,l-n-10)),y=Math.max(10,Math.min(y,a-i-10));const f=e.color||"blue",w=document.createElement("div");w.className="subagent-window has-terminal",w.id=`subagent-window-${t}`,w.style.zIndex=++this.subagentWindowZIndex,w.style.left=`${g}px`,w.style.top=`${y}px`,w.style.width=`${n}px`,w.style.height=`${i}px`,w.innerHTML=`
|
|
362
|
+
<div class="subagent-window-header">
|
|
363
|
+
<div class="subagent-window-title" title="Teammate terminal: ${this.escapeHtml(e.teammateName)} (pane ${e.paneTarget})">
|
|
364
|
+
<span class="icon" style="color: var(--team-color-${f}, #339af0)">\u2B24</span>
|
|
365
|
+
<span class="id">${this.escapeHtml(e.teammateName)}</span>
|
|
366
|
+
<span class="status running">terminal</span>
|
|
367
|
+
</div>
|
|
368
|
+
<div class="subagent-window-actions">
|
|
369
|
+
<button onclick="app.closeSubagentWindow('${this.escapeHtml(t)}')" title="Minimize to tab">\u2500</button>
|
|
370
|
+
</div>
|
|
371
|
+
</div>
|
|
372
|
+
<div class="subagent-window-body teammate-terminal-body" id="subagent-window-body-${t}">
|
|
373
|
+
</div>
|
|
374
|
+
`,document.body.appendChild(w);const v=this.makeWindowDraggable(w,w.querySelector(".subagent-window-header"));typeof this.makeWindowResizable=="function"&&this.makeWindowResizable(w);const T=(this.loadAppSettingsFromStorage().subagentActiveTabOnly??!0)&&e.sessionId!==this.activeSessionId;this.subagentWindows.set(t,{element:w,minimized:!1,hidden:T,dragListeners:v,description:`Teammate: ${e.teammateName}`}),this.subagentParentMap.set(t,e.sessionId),T&&(w.style.display="none"),w.addEventListener("mousedown",()=>{w.style.zIndex=++this.subagentWindowZIndex});const _=new ResizeObserver(()=>{this.updateConnectionLines()});_.observe(w),this.subagentWindows.get(t).resizeObserver=_,this.initTeammateTerminal(t,e,w),requestAnimationFrame(()=>{w.style.transition="transform 0.3s ease, opacity 0.3s ease",w.style.transform="scale(1)",w.style.opacity="1"})}rebuildTeammateMap(){this.teammateMap.clear();for(const[e,t]of this.teams)for(const s of t.members)s.agentType!=="team-lead"&&this.teammateMap.set(s.name,{name:s.name,color:s.color||"blue",teamName:e,agentId:s.agentId})}getTeammateInfo(e){if(!e?.description)return null;const t=e.description.match(/<teammate-message\s+teammate_id="?([^">\s]+)/);if(!t)return null;const n=t[1].split("@")[0];return this.teammateMap.get(n)||{name:n,color:"blue",teamName:"unknown"}}getTeammateBadgeHtml(e){const t=this.getTeammateInfo(e);return t?`<span class="teammate-badge teammate-color-${t.color}" title="Team: ${this.escapeHtml(t.teamName)}">@${this.escapeHtml(t.name)}</span>`:""}renderTeamTasksPanel(){const e=document.getElementById("teamTasksPanel");if(!e)return;let t=null,s=null;if(this.activeSessionId){for(const[p,g]of this.teams)if(g.leadSessionId===this.activeSessionId){t=g,s=p;break}}if(!t){e.style.display="none";return}const n=e.style.display==="none";if(e.style.display="flex",n&&!this.teamTasksDragListeners){e.style.left=`${Math.max(10,window.innerWidth-360-20)}px`,e.style.top=`${Math.max(10,window.innerHeight-300-70)}px`;const y=e.querySelector(".team-tasks-header");y&&(this.teamTasksDragListeners=this.makeWindowDraggable(e,y))}const i=this.teamTasks.get(s)||[],o=i.filter(p=>p.status==="completed").length,l=i.length,a=l>0?Math.round(o/l*100):0,r=e.querySelector(".team-tasks-header-text");if(r){const p=t.members.filter(g=>g.agentType!=="team-lead").length;r.textContent=`Team Tasks (${p} teammates)`}const c=e.querySelector(".team-tasks-progress-fill");c&&(c.style.width=`${a}%`);const h=e.querySelector(".team-tasks-progress-text");h&&(h.textContent=`${o}/${l}`);const u=e.querySelector(".team-tasks-list");if(!u)return;if(i.length===0){u.innerHTML='<div class="team-task-empty">No tasks yet</div>';return}const m=i.map(p=>{const g=p.status==="completed"?"\u2713":p.status==="in_progress"?"\u25C9":"\u25CB",y=p.status.replace("_","-"),f=p.owner?`<span class="team-task-owner teammate-color-${this.getTeammateColor(p.owner)}">${this.escapeHtml(p.owner)}</span>`:"";return`<div class="team-task-item ${y}">
|
|
375
|
+
<span class="team-task-status">${g}</span>
|
|
376
|
+
<span class="team-task-subject">${this.escapeHtml(p.subject)}</span>
|
|
377
|
+
${f}
|
|
378
|
+
</div>`}).join("");u.innerHTML=m}hideTeamTasksPanel(){const e=document.getElementById("teamTasksPanel");e&&(e.style.display="none"),this.teamTasksDragListeners&&(document.removeEventListener("mousemove",this.teamTasksDragListeners.move),document.removeEventListener("mouseup",this.teamTasksDragListeners.up),this.teamTasksDragListeners.touchMove&&(document.removeEventListener("touchmove",this.teamTasksDragListeners.touchMove),document.removeEventListener("touchend",this.teamTasksDragListeners.up),document.removeEventListener("touchcancel",this.teamTasksDragListeners.up)),this.teamTasksDragListeners=null)}getTeammateColor(e){return this.teammateMap.get(e)?.color||"blue"}normalizeFilePath(e,t){if(!e)return"";let s=e.trim();const n="/home/"+(window.USER||"user");s.startsWith("~/")?s=n+s.slice(1):s==="~"&&(s=n),!s.startsWith("/")&&t&&(s=t+"/"+s);const i=s.split("/"),o=[];for(const l of i)l===""||l==="."||(l===".."?o.length>1&&o.pop():o.push(l));return"/"+o.join("/")}getFilename(e){const t=e.split("/");return t[t.length-1]||""}isShallowRootPath(e){return e.startsWith("/")?e.split("/").filter(s=>s!=="").length===1:!1}isPathInWorkingDir(e,t){if(!t)return!1;const s=this.normalizeFilePath(e,t);return s.startsWith(t+"/")||s===t}pathsAreEquivalent(e,t,s){const n=this.normalizeFilePath(e,s),i=this.normalizeFilePath(t,s);if(n===i)return!0;const o=this.getFilename(n),l=this.getFilename(i);if(o!==l)return!1;const a=this.isShallowRootPath(e),r=this.isShallowRootPath(t),c=this.isPathInWorkingDir(n,s),h=this.isPathInWorkingDir(i,s);return!!(a&&h||r&&c)}pickBetterPath(e,t,s){if(s){const o=this.isPathInWorkingDir(e,s),l=this.isPathInWorkingDir(t,s);if(o&&!l)return e;if(l&&!o)return t}const n=e.startsWith("/"),i=t.startsWith("/");return n&&!i?e:i&&!n?t:e.length!==t.length?e.length>t.length?e:t:!e.includes("~")&&t.includes("~")?e:!t.includes("~")&&e.includes("~")?t:e}deduplicateProjectInsightPaths(e,t){const s=[];for(const o of e)for(const l of o.filePaths)s.push({rawPath:l,toolId:o.id});if(s.length<=1){const o=new Map;for(const l of s)o.set(this.normalizeFilePath(l.rawPath,t),l);return o}s.sort((o,l)=>{const a=this.isPathInWorkingDir(o.rawPath,t),r=this.isPathInWorkingDir(l.rawPath,t);return a&&!r?-1:r&&!a?1:l.rawPath.length-o.rawPath.length});const n=new Map,i=new Set;for(const{rawPath:o,toolId:l}of s){const a=this.normalizeFilePath(o,t);let r=!1;for(const[,c]of n)if(this.pathsAreEquivalent(o,c.rawPath,t)){r=!0;break}!r&&!i.has(a)&&(n.set(a,{rawPath:o,toolId:l}),i.add(a))}return n}handleBashToolStart(e,t){let s=this.projectInsights.get(e)||[];s=s.filter(n=>n.id!==t.id),s.push(t),this.projectInsights.set(e,s),this.renderProjectInsightsPanel()}handleBashToolEnd(e,t){const n=(this.projectInsights.get(e)||[]).find(i=>i.id===t.id);n&&(n.status="completed"),this.renderProjectInsightsPanel(),setTimeout(()=>{const i=this.projectInsights.get(e)||[];this.projectInsights.set(e,i.filter(o=>o.id!==t.id)),this.renderProjectInsightsPanel()},2e3)}handleBashToolsUpdate(e,t){this.projectInsights.set(e,t),this.renderProjectInsightsPanel()}renderProjectInsightsPanel(){const e=this.$("projectInsightsPanel"),t=this.$("projectInsightsList");if(!e||!t)return;if(!(this.loadAppSettingsFromStorage().showProjectInsights??!1)){e.classList.remove("visible"),this.projectInsightsPanelVisible=!1;return}const o=(this.projectInsights.get(this.activeSessionId)||[]).filter(u=>u.status==="running");if(o.length===0){e.classList.remove("visible"),this.projectInsightsPanelVisible=!1;return}e.classList.add("visible"),this.projectInsightsPanelVisible=!0;const a=this.sessions.get(this.activeSessionId)?.workingDir||this.currentSessionWorkingDir,r=this.deduplicateProjectInsightPaths(o,a),c=new Set(Array.from(r.values()).map(u=>u.rawPath)),h=[];for(const u of o){const m=u.filePaths.filter(g=>c.has(g));if(m.length===0)continue;const p=u.command.length>50?u.command.substring(0,50)+"...":u.command;h.push(`
|
|
379
|
+
<div class="project-insight-item" data-tool-id="${u.id}">
|
|
380
|
+
<div class="project-insight-command">
|
|
381
|
+
<span class="icon">\u{1F4BB}</span>
|
|
382
|
+
<span class="cmd" title="${this.escapeHtml(u.command)}">${this.escapeHtml(p)}</span>
|
|
383
|
+
<span class="project-insight-status ${u.status}">${u.status}</span>
|
|
384
|
+
${u.timeout?`<span class="project-insight-timeout">${this.escapeHtml(u.timeout)}</span>`:""}
|
|
385
|
+
</div>
|
|
386
|
+
<div class="project-insight-paths">
|
|
387
|
+
`);for(const g of m){const y=g.split("/").pop();h.push(`
|
|
388
|
+
<span class="project-insight-filepath"
|
|
389
|
+
onclick="app.openLogViewerWindow('${this.escapeHtml(g)}', '${this.escapeHtml(u.sessionId)}')"
|
|
390
|
+
title="${this.escapeHtml(g)}">${this.escapeHtml(y)}</span>
|
|
391
|
+
`)}h.push(`
|
|
392
|
+
</div>
|
|
393
|
+
</div>
|
|
394
|
+
`)}t.innerHTML=h.join("")}closeProjectInsightsPanel(){const e=this.$("projectInsightsPanel");e&&(e.classList.remove("visible"),this.projectInsightsPanelVisible=!1)}fileBrowserData=null;fileBrowserExpandedDirs=new Set;fileBrowserFilter="";fileBrowserAllExpanded=!1;filePreviewContent="";async loadFileBrowser(e){if(!e)return;const t=this.$("fileBrowserTree"),s=this.$("fileBrowserStatus");if(t){t.innerHTML='<div class="file-browser-loading">Loading files...</div>';try{const n=await fetch(`/api/sessions/${e}/files?depth=5&showHidden=false`);if(!n.ok)throw new Error("Failed to load files");const i=await n.json();if(!i.success)throw new Error(i.error||"Failed to load files");if(this.fileBrowserData=i.data,this.renderFileBrowserTree(),s){const{totalFiles:o,totalDirectories:l,truncated:a}=i.data;s.textContent=`${o} files, ${l} dirs${a?" (truncated)":""}`}}catch(n){t.innerHTML=`<div class="file-browser-empty">Failed to load files: ${this.escapeHtml(n.message)}</div>`}}}renderFileBrowserTree(){const e=this.$("fileBrowserTree");if(!e||!this.fileBrowserData)return;const{tree:t}=this.fileBrowserData;if(!t||t.length===0){e.innerHTML='<div class="file-browser-empty">No files found</div>';return}const s=[],n=this.fileBrowserFilter.toLowerCase(),i=(o,l)=>{const a=o.type==="directory",r=this.fileBrowserExpandedDirs.has(o.path),c=!n||o.name.toLowerCase().includes(n);let h=!1;a&&n&&o.children&&(h=this.hasMatchingChild(o,n));const m=!(c||h)&&n?" hidden-by-filter":"",p=a?r?"\u{1F4C2}":"\u{1F4C1}":this.getFileIcon(o.extension),g=a?`<span class="file-tree-expand${r?" expanded":""}">\u25B6</span>`:'<span class="file-tree-expand"></span>',y=!a&&o.size!==void 0?`<span class="file-tree-size">${this.formatFileSize(o.size)}</span>`:"",f=a?"file-tree-name directory":"file-tree-name";if(s.push(`
|
|
395
|
+
<div class="file-tree-item${m}" data-path="${this.escapeHtml(o.path)}" data-type="${o.type}" data-depth="${l}">
|
|
396
|
+
${g}
|
|
397
|
+
<span class="file-tree-icon">${p}</span>
|
|
398
|
+
<span class="${f}">${this.escapeHtml(o.name)}</span>
|
|
399
|
+
${y}
|
|
400
|
+
</div>
|
|
401
|
+
`),a&&r&&o.children)for(const w of o.children)i(w,l+1)};for(const o of t)i(o,0);e.innerHTML=s.join(""),e.querySelectorAll(".file-tree-item").forEach(o=>{o.addEventListener("click",()=>{const l=o.dataset.path;o.dataset.type==="directory"?this.toggleFileBrowserFolder(l):this.openFilePreview(l)})})}hasMatchingChild(e,t){if(!e.children)return!1;for(const s of e.children)if(s.name.toLowerCase().includes(t)||s.type==="directory"&&this.hasMatchingChild(s,t))return!0;return!1}toggleFileBrowserFolder(e){this.fileBrowserExpandedDirs.has(e)?this.fileBrowserExpandedDirs.delete(e):this.fileBrowserExpandedDirs.add(e),this.renderFileBrowserTree()}filterFileBrowser(e){this.fileBrowserFilter=e,e&&this.expandAllDirectories(this.fileBrowserData?.tree||[]),this.renderFileBrowserTree()}expandAllDirectories(e){for(const t of e)t.type==="directory"&&(this.fileBrowserExpandedDirs.add(t.path),t.children&&this.expandAllDirectories(t.children))}collapseAllDirectories(){this.fileBrowserExpandedDirs.clear()}toggleFileBrowserExpand(){this.fileBrowserAllExpanded=!this.fileBrowserAllExpanded;const e=this.$("fileBrowserExpandBtn");this.fileBrowserAllExpanded?(this.expandAllDirectories(this.fileBrowserData?.tree||[]),e&&(e.innerHTML="\u229F")):(this.collapseAllDirectories(),e&&(e.innerHTML="\u229E")),this.renderFileBrowserTree()}refreshFileBrowser(){if(this.activeSessionId){this.fileBrowserExpandedDirs.clear(),this.fileBrowserFilter="",this.fileBrowserAllExpanded=!1;const e=this.$("fileBrowserSearch");e&&(e.value=""),this.loadFileBrowser(this.activeSessionId)}}closeFileBrowserPanel(){const e=this.$("fileBrowserPanel");e&&e.classList.remove("visible");const t=this.loadAppSettingsFromStorage();t.showFileBrowser=!1,this.saveAppSettingsToStorage(t)}async openFilePreview(e){if(!this.activeSessionId||!e)return;const t=this.$("filePreviewOverlay"),s=this.$("filePreviewTitle"),n=this.$("filePreviewBody"),i=this.$("filePreviewFooter");if(!(!t||!n)){t.classList.add("visible"),s.textContent=e,n.innerHTML='<div class="binary-message">Loading...</div>',i.textContent="";try{const o=await fetch(`/api/sessions/${this.activeSessionId}/file-content?path=${encodeURIComponent(e)}&lines=500`);if(!o.ok)throw new Error("Failed to load file");const l=await o.json();if(!l.success)throw new Error(l.error||"Failed to load file");const a=l.data;if(a.type==="image")n.innerHTML=`<img src="${a.url}" alt="${this.escapeHtml(e)}">`,i.textContent=`${this.formatFileSize(a.size)} \u2022 ${a.extension}`;else if(a.type==="video")n.innerHTML=`<video src="${a.url}" controls autoplay></video>`,i.textContent=`${this.formatFileSize(a.size)} \u2022 ${a.extension}`;else if(a.type==="binary")n.innerHTML=`<div class="binary-message">Binary file (${this.formatFileSize(a.size)})<br>Cannot preview</div>`,i.textContent=a.extension||"binary";else{this.filePreviewContent=a.content,n.innerHTML=`<pre><code>${this.escapeHtml(a.content)}</code></pre>`;const r=a.truncated?` (showing 500/${a.totalLines} lines)`:"";i.textContent=`${a.totalLines} lines \u2022 ${this.formatFileSize(a.size)}${r}`}}catch(o){n.innerHTML=`<div class="binary-message">Error: ${this.escapeHtml(o.message)}</div>`}}}closeFilePreview(){const e=this.$("filePreviewOverlay");e&&e.classList.remove("visible"),this.filePreviewContent=""}copyFilePreviewContent(){this.filePreviewContent&&navigator.clipboard.writeText(this.filePreviewContent).then(()=>{this.showToast("Copied to clipboard","success")}).catch(()=>{this.showToast("Failed to copy","error")})}getFileIcon(e){return e&&{ts:"\u{1F4D8}",tsx:"\u{1F4D8}",js:"\u{1F4D2}",jsx:"\u{1F4D2}",mjs:"\u{1F4D2}",cjs:"\u{1F4D2}",py:"\u{1F40D}",pyx:"\u{1F40D}",pyw:"\u{1F40D}",rs:"\u{1F980}",go:"\u{1F439}",c:"\u2699\uFE0F",cpp:"\u2699\uFE0F",h:"\u2699\uFE0F",hpp:"\u2699\uFE0F",html:"\u{1F310}",htm:"\u{1F310}",css:"\u{1F3A8}",scss:"\u{1F3A8}",sass:"\u{1F3A8}",less:"\u{1F3A8}",json:"\u{1F4CB}",yaml:"\u{1F4CB}",yml:"\u{1F4CB}",xml:"\u{1F4CB}",toml:"\u{1F4CB}",csv:"\u{1F4CB}",md:"\u{1F4DD}",markdown:"\u{1F4DD}",txt:"\u{1F4DD}",rst:"\u{1F4DD}",png:"\u{1F5BC}\uFE0F",jpg:"\u{1F5BC}\uFE0F",jpeg:"\u{1F5BC}\uFE0F",gif:"\u{1F5BC}\uFE0F",svg:"\u{1F5BC}\uFE0F",webp:"\u{1F5BC}\uFE0F",ico:"\u{1F5BC}\uFE0F",bmp:"\u{1F5BC}\uFE0F",mp4:"\u{1F3AC}",webm:"\u{1F3AC}",mov:"\u{1F3AC}",mp3:"\u{1F3B5}",wav:"\u{1F3B5}",ogg:"\u{1F3B5}",sh:"\u{1F4BB}",bash:"\u{1F4BB}",zsh:"\u{1F4BB}",env:"\u{1F510}",gitignore:"\u{1F6AB}",dockerfile:"\u{1F433}",lock:"\u{1F512}"}[e.toLowerCase()]||"\u{1F4C4}"}formatFileSize(e){return e==null?"":e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:e<1024*1024*1024?`${(e/(1024*1024)).toFixed(1)} MB`:`${(e/(1024*1024*1024)).toFixed(1)} GB`}openLogViewerWindow(e,t){if(t=t||this.activeSessionId,!t)return;const s=`${t}-${e.replace(/[^a-zA-Z0-9]/g,"_")}`;if(this.logViewerWindows.has(s)){const h=this.logViewerWindows.get(s);h.element.style.zIndex=++this.logViewerWindowZIndex;return}const n=this.logViewerWindows.size,i=100+n%5*30,o=100+n%5*30,l=e.split("/").pop(),a=document.createElement("div");a.className="log-viewer-window",a.id=`log-viewer-window-${s}`,a.style.left=`${i}px`,a.style.top=`${o}px`,a.style.zIndex=++this.logViewerWindowZIndex,a.innerHTML=`
|
|
402
|
+
<div class="log-viewer-window-header">
|
|
403
|
+
<div class="log-viewer-window-title" title="${this.escapeHtml(e)}">
|
|
404
|
+
<span class="icon">\u{1F4C4}</span>
|
|
405
|
+
<span class="filename">${this.escapeHtml(l)}</span>
|
|
406
|
+
<span class="status streaming">streaming</span>
|
|
407
|
+
</div>
|
|
408
|
+
<div class="log-viewer-window-actions">
|
|
409
|
+
<button onclick="app.closeLogViewerWindow('${this.escapeHtml(s)}')" title="Close">\xD7</button>
|
|
410
|
+
</div>
|
|
411
|
+
</div>
|
|
412
|
+
<div class="log-viewer-window-body" id="log-viewer-body-${s}">
|
|
413
|
+
<div class="log-info">Connecting to ${this.escapeHtml(e)}...</div>
|
|
414
|
+
</div>
|
|
415
|
+
`,document.body.appendChild(a);const r=this.makeWindowDraggable(a,a.querySelector(".log-viewer-window-header")),c=new EventSource(`/api/sessions/${t}/tail-file?path=${encodeURIComponent(e)}&lines=50`);c.onmessage=h=>{const u=JSON.parse(h.data),m=document.getElementById(`log-viewer-body-${s}`);if(m)switch(u.type){case"connected":m.innerHTML="";break;case"data":const p=m.scrollTop+m.clientHeight>=m.scrollHeight-10,g=this.escapeHtml(u.content);m.innerHTML+=g,p&&(m.scrollTop=m.scrollHeight),m.innerHTML.length>5e5&&(m.innerHTML=m.innerHTML.slice(-4e5));break;case"end":this.updateLogViewerStatus(s,"disconnected","ended");break;case"error":m.innerHTML+=`<div class="log-error">${this.escapeHtml(u.error)}</div>`,this.updateLogViewerStatus(s,"error","error");break}},c.onerror=()=>{this.updateLogViewerStatus(s,"disconnected","connection error")},this.logViewerWindows.set(s,{element:a,eventSource:c,filePath:e,sessionId:t,dragListeners:r})}updateLogViewerStatus(e,t,s){const n=document.querySelector(`#log-viewer-window-${e} .status`);n&&(n.className=`status ${t}`,n.textContent=s)}closeLogViewerWindow(e){const t=this.logViewerWindows.get(e);t&&(t.eventSource&&t.eventSource.close(),t.dragListeners&&(document.removeEventListener("mousemove",t.dragListeners.move),document.removeEventListener("mouseup",t.dragListeners.up)),t.element.remove(),this.logViewerWindows.delete(e))}closeSessionLogViewerWindows(e){const t=[];for(const[s,n]of this.logViewerWindows)n.sessionId===e&&t.push(s);for(const s of t)this.closeLogViewerWindow(s)}openImagePopup(e){const{sessionId:t,filePath:s,relativePath:n,fileName:i,timestamp:o,size:l}=e,a=`${t}-${o}`;if(this.imagePopups.has(a)){const b=this.imagePopups.get(a);b.element.style.zIndex=++this.imagePopupZIndex;return}if(this.imagePopups.size>=20){const b=this.imagePopups.keys().next().value;b&&this.closeImagePopup(b)}const c=this.imagePopups.size,h=(window.innerWidth-600)/2,u=(window.innerHeight-500)/2,m=h+c%5*30,p=u+c%5*30,y=this.sessions.get(t)?.name||t.substring(0,8),f=(l/1024).toFixed(1),w=`/api/sessions/${t}/file-raw?path=${encodeURIComponent(n||i)}`,v=document.createElement("div");v.className="image-popup-window",v.id=`image-popup-${a}`,v.style.left=`${m}px`,v.style.top=`${p}px`,v.style.zIndex=++this.imagePopupZIndex,v.innerHTML=`
|
|
416
|
+
<div class="image-popup-header">
|
|
417
|
+
<div class="image-popup-title" title="${this.escapeHtml(s)}">
|
|
418
|
+
<span class="icon">\u{1F5BC}\uFE0F</span>
|
|
419
|
+
<span class="filename">${this.escapeHtml(i)}</span>
|
|
420
|
+
<span class="session-badge">${this.escapeHtml(y)}</span>
|
|
421
|
+
<span class="size-badge">${f} KB</span>
|
|
422
|
+
</div>
|
|
423
|
+
<div class="image-popup-actions">
|
|
424
|
+
<button onclick="app.openImageInNewTab('${this.escapeHtml(w)}')" title="Open in new tab">\u2197</button>
|
|
425
|
+
<button onclick="app.closeImagePopup('${this.escapeHtml(a)}')" title="Close">\xD7</button>
|
|
426
|
+
</div>
|
|
427
|
+
</div>
|
|
428
|
+
<div class="image-popup-body">
|
|
429
|
+
<img src="${w}" alt="${this.escapeHtml(i)}"
|
|
430
|
+
onerror="this.parentElement.innerHTML='<div class=\\'image-error\\'>Failed to load image</div>'"
|
|
431
|
+
onclick="app.openImageInNewTab('${this.escapeHtml(w)}')" />
|
|
432
|
+
</div>
|
|
433
|
+
`,document.body.appendChild(v);const S=this.makeWindowDraggable(v,v.querySelector(".image-popup-header"));v.addEventListener("mousedown",()=>{v.style.zIndex=++this.imagePopupZIndex}),this.imagePopups.set(a,{element:v,sessionId:t,filePath:s,dragListeners:S})}closeImagePopup(e){const t=this.imagePopups.get(e);t&&(t.dragListeners&&(document.removeEventListener("mousemove",t.dragListeners.move),document.removeEventListener("mouseup",t.dragListeners.up),t.dragListeners.touchMove&&(document.removeEventListener("touchmove",t.dragListeners.touchMove),document.removeEventListener("touchend",t.dragListeners.up),document.removeEventListener("touchcancel",t.dragListeners.up))),t.element.remove(),this.imagePopups.delete(e))}openImageInNewTab(e){window.open(e,"_blank")}closeSessionImagePopups(e){const t=[];for(const[s,n]of this.imagePopups)n.sessionId===e&&t.push(s);for(const s of t)this.closeImagePopup(s)}async loadMuxSessions(){try{const t=await(await fetch("/api/mux-sessions")).json();this.muxSessions=t.sessions||[],this.renderMuxSessions()}catch{}}killAllSessions(){const e=this.muxSessions?.length||0;if(e===0){alert("No sessions to kill");return}document.getElementById("killAllCount").textContent=e;const t=document.getElementById("killAllModal");t.classList.add("active"),this.activeFocusTrap=new FocusTrap(t),this.activeFocusTrap.activate()}closeKillAllModal(){document.getElementById("killAllModal").classList.remove("active"),this.activeFocusTrap&&(this.activeFocusTrap.deactivate(),this.activeFocusTrap=null)}async confirmKillAll(e){this.closeKillAllModal();try{if(e){if((await(await fetch("/api/sessions",{method:"DELETE"})).json()).success){this.sessions.clear(),this.muxSessions=[],this.activeSessionId=null;try{localStorage.removeItem("codeman-active-session")}catch{}this.renderSessionTabs(),this.renderMuxSessions(),this.terminal.clear(),this.terminal.reset(),this.toast("All sessions and tmux killed","success")}}else{this.sessions.clear(),this.activeSessionId=null;try{localStorage.removeItem("codeman-active-session")}catch{}this.renderSessionTabs(),this.terminal.clear(),this.terminal.reset(),this.toast("All tabs removed, tmux still running","info")}}catch(t){this.toast("Failed to kill sessions: "+t.message,"error")}}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 n=i=>{!e.contains(i.target)&&!i.target.classList.contains("btn-case-settings")&&(e.classList.add("hidden"),document.removeEventListener("click",n))};setTimeout(()=>document.addEventListener("click",n),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 n=i=>{!e.contains(i.target)&&!i.target.classList.contains("btn-case-settings-mobile")&&(e.classList.add("hidden"),document.removeEventListener("click",n))};setTimeout(()=>document.addEventListener("click",n),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(n=>{n.classList.toggle("active",n.dataset.tab===e)}),t.querySelectorAll(".modal-tab-content").forEach(n=>{n.classList.toggle("hidden",n.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 n=await(await fetch("/api/cases",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:e,description:t})})).json();n.success?(this.closeCreateCaseModal(),this.showToast(`Case "${e}" created`,"success"),await this.loadQuickStartCases(e),await this.saveLastUsedCase(e)):this.showToast(n.error||"Failed to create case","error")}catch(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 n=await(await fetch("/api/cases/link",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:e,path:t})})).json();n.success?(this.closeCreateCaseModal(),this.showToast(`Case "${e}" linked to ${t}`,"success"),await this.loadQuickStartCases(e),await this.saveLastUsedCase(e)):this.showToast(n.error||"Failed to link case","error")}catch(s){this.showToast("Failed to link case: "+s.message,"error")}}showMobileCasePicker(){const e=document.getElementById("mobileCasePickerModal"),t=document.getElementById("mobileCaseList"),n=document.getElementById("quickStartCase").value;let i="";const o=this.cases||[],a=o.some(r=>r.name==="testcase")?o:[{name:"testcase"},...o];for(const r of a){const c=r.name===n;i+=`
|
|
434
|
+
<button class="mobile-case-item ${c?"selected":""}"
|
|
435
|
+
onclick="app.selectMobileCase('${this.escapeHtml(r.name)}')">
|
|
436
|
+
<span class="mobile-case-item-icon">
|
|
437
|
+
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
438
|
+
<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"/>
|
|
439
|
+
</svg>
|
|
440
|
+
</span>
|
|
441
|
+
<span class="mobile-case-item-name">${this.escapeHtml(r.name)}</span>
|
|
442
|
+
<span class="mobile-case-item-check">
|
|
443
|
+
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5">
|
|
444
|
+
<polyline points="20 6 9 17 4 12"/>
|
|
445
|
+
</svg>
|
|
446
|
+
</span>
|
|
447
|
+
</button>
|
|
448
|
+
`}t.innerHTML=i,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)}renderMuxSessions(){this.renderMuxSessionsTimeout&&clearTimeout(this.renderMuxSessionsTimeout),this.renderMuxSessionsTimeout=setTimeout(()=>{this._renderMuxSessionsImmediate()},100)}_renderMuxSessionsImmediate(){const e=document.getElementById("muxSessionsBody");if(!this.muxSessions||this.muxSessions.length===0){e.innerHTML='<div class="monitor-empty">No mux sessions</div>';return}let t="";for(const s of this.muxSessions){const n=s.stats||{memoryMB:0,cpuPercent:0,childCount:0},i=this.sessions.get(s.sessionId),o=i?i.status:"unknown",l=i?i.isWorking:!1;let a,r;o==="idle"&&!l?(a="IDLE",r="status-idle"):o==="busy"||l?(a="WORKING",r="status-working"):o==="stopped"?(a="STOPPED",r="status-stopped"):(a=o.toUpperCase(),r="");const c=i&&i.tokens?i.tokens:null,h=i?i.totalCost:0,u=i&&i.cliModel||"",m=u.includes("opus")?"opus":u.includes("sonnet")?"sonnet":u.includes("haiku")?"haiku":"",p=i?i.ralphTodoStats:null;let g="";if(p&&p.total>0){const v=Math.round(p.completed/p.total*100);g=`<span class="process-stat todo-progress">${p.completed}/${p.total} (${v}%)</span>`}let y="";c&&c.total>0&&(y=`<span class="process-stat tokens">${(c.total/1e3).toFixed(1)}k tok</span>`);let f="";h>0&&(f=`<span class="process-stat cost">$${h.toFixed(2)}</span>`);let w="";m&&(w=`<span class="monitor-model-badge ${m}">${m}</span>`),t+=`
|
|
449
|
+
<div class="process-item">
|
|
450
|
+
<span class="monitor-status-badge ${r}">${a}</span>
|
|
451
|
+
<div class="process-info">
|
|
452
|
+
<div class="process-name">${w} ${this.escapeHtml(s.name||s.muxName)}</div>
|
|
453
|
+
<div class="process-meta">
|
|
454
|
+
${y}
|
|
455
|
+
${f}
|
|
456
|
+
${g}
|
|
457
|
+
<span class="process-stat memory">${n.memoryMB}MB</span>
|
|
458
|
+
<span class="process-stat cpu">${n.cpuPercent}%</span>
|
|
459
|
+
</div>
|
|
460
|
+
</div>
|
|
461
|
+
<div class="process-actions">
|
|
462
|
+
<button class="btn-toolbar btn-sm btn-danger" onclick="app.killMuxSession('${this.escapeHtml(s.sessionId)}')" title="Kill session">Kill</button>
|
|
463
|
+
</div>
|
|
464
|
+
</div>
|
|
465
|
+
`}e.innerHTML=t}renderMonitorSubagents(){const e=document.getElementById("monitorSubagentsBody"),t=document.getElementById("monitorSubagentStats");if(!e)return;const s=Array.from(this.subagents.values()),n=s.filter(o=>o.status==="active"||o.status==="idle").length;if(t&&(t.textContent=`${s.length} tracked`+(n>0?`, ${n} active`:"")),s.length===0){e.innerHTML='<div class="monitor-empty">No background agents</div>';return}let i="";for(const o of s){const l=o.status==="active"?"active":o.status==="idle"?"idle":"completed",a=o.modelShort?`<span class="model-badge ${o.modelShort}">${o.modelShort}</span>`:"",r=o.description?this.escapeHtml(o.description.substring(0,40)):o.agentId;i+=`
|
|
466
|
+
<div class="process-item">
|
|
467
|
+
<span class="process-mode ${l}">${o.status}</span>
|
|
468
|
+
<div class="process-info">
|
|
469
|
+
<div class="process-name">${a} ${r}</div>
|
|
470
|
+
<div class="process-meta">
|
|
471
|
+
<span>ID: ${o.agentId}</span>
|
|
472
|
+
<span>${o.toolCallCount||0} tools</span>
|
|
473
|
+
</div>
|
|
474
|
+
</div>
|
|
475
|
+
<div class="process-actions">
|
|
476
|
+
${o.status!=="completed"?`<button class="btn-toolbar btn-sm btn-danger" onclick="app.killSubagent('${this.escapeHtml(o.agentId)}')" title="Kill agent">Kill</button>`:""}
|
|
477
|
+
</div>
|
|
478
|
+
</div>
|
|
479
|
+
`}e.innerHTML=i}async killMuxSession(e){if(confirm("Kill this mux session?")){try{await this.closeSession(e,!0)}catch{try{await fetch(`/api/mux-sessions/${e}`,{method:"DELETE"})}catch{}this.showToast("Tmux session killed","success")}this.muxSessions=this.muxSessions.filter(t=>t.sessionId!==e),this.renderMuxSessions()}}async reconcileMuxSessions(){try{const t=await(await fetch("/api/mux-sessions/reconcile",{method:"POST"})).json();t.dead&&t.dead.length>0?(this.showToast(`Found ${t.dead.length} dead mux session(s)`,"warning"),await this.loadMuxSessions()):this.showToast("All mux sessions are alive","success")}catch{this.showToast("Failed to reconcile mux sessions","error")}}renderMonitorPlanAgents(){const e=document.getElementById("monitorPlanAgentsSection"),t=document.getElementById("monitorPlanAgentsBody"),s=document.getElementById("monitorPlanAgentStats");if(!e||!t)return;const n=Array.from(this.planSubagents?.values()||[]),i=!!this.activePlanOrchestratorId;if(n.length===0&&!i){e.style.display="none";return}e.style.display="";const o=n.filter(r=>r.status==="running").length,l=n.filter(r=>r.status==="completed"||r.status==="failed").length;if(s&&(i?s.textContent=`${o} running, ${l} done`:s.textContent=`${n.length} total`),n.length===0){t.innerHTML=`<div class="monitor-empty">${i?"Plan generation starting...":"No plan agents"}</div>`;return}let a="";for(const r of n){const c=r.status==="running"?"active":r.status==="completed"?"completed":"error",h=r.agentType||r.agentId,u=r.model?'<span class="model-badge opus">opus</span>':"",m=r.detail?this.escapeHtml(r.detail.substring(0,50)):"",p=r.durationMs?`${(r.durationMs/1e3).toFixed(1)}s`:"",g=r.itemCount?`${r.itemCount} items`:"";a+=`
|
|
480
|
+
<div class="process-item">
|
|
481
|
+
<span class="process-mode ${c}">${r.status||"pending"}</span>
|
|
482
|
+
<div class="process-info">
|
|
483
|
+
<div class="process-name">${u} ${this.escapeHtml(h)}</div>
|
|
484
|
+
<div class="process-meta">
|
|
485
|
+
${m?`<span>${m}</span>`:""}
|
|
486
|
+
${g?`<span>${g}</span>`:""}
|
|
487
|
+
${p?`<span>${p}</span>`:""}
|
|
488
|
+
</div>
|
|
489
|
+
</div>
|
|
490
|
+
</div>
|
|
491
|
+
`}t.innerHTML=a}async cancelPlanFromMonitor(){if(!this.activePlanOrchestratorId&&this.planSubagents?.size===0){this.showToast("No active plan generation","info");return}if(!confirm("Cancel plan generation and close all plan agent windows?"))return;await this.cancelPlanGeneration(),document.getElementById("ralphWizardModal")?.classList.contains("active")&&this.closeRalphWizard(),this.renderMonitorPlanAgents(),this.showToast("Plan generation cancelled","success")}_toastContainer=null;toggleNotifications(){this.notificationManager?.toggleDrawer()}toast(e,t="info"){return this.showToast(e,t)}showToast(e,t="info"){const s=document.createElement("div");s.className=`toast toast-${t}`,s.textContent=e,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(s),requestAnimationFrame(()=>s.classList.add("show")),setTimeout(()=>{s.classList.remove("show"),setTimeout(()=>s.remove(),200)},3e3)}startSystemStatsPolling(){this.stopSystemStatsPolling(),this.fetchSystemStats(),this.systemStatsInterval=setInterval(()=>{this.fetchSystemStats()},2e3)}stopSystemStatsPolling(){this.systemStatsInterval&&(clearInterval(this.systemStatsInterval),this.systemStatsInterval=null)}async fetchSystemStats(){const e=document.getElementById("headerSystemStats");if(!(!e||e.style.display==="none"))try{const s=await(await fetch("/api/system/stats")).json();this.updateSystemStatsDisplay(s)}catch{}}updateSystemStatsDisplay(e){const t=this.$("statCpu"),s=this.$("statCpuBar"),n=this.$("statMem"),i=this.$("statMemBar");if(t&&s&&(t.textContent=`${e.cpu}%`,s.style.width=`${Math.min(100,e.cpu)}%`,s.classList.remove("medium","high"),t.classList.remove("high"),e.cpu>80?(s.classList.add("high"),t.classList.add("high")):e.cpu>50&&s.classList.add("medium")),n&&i){const o=(e.memory.usedMB/1024).toFixed(1);n.textContent=`${o}G`,i.style.width=`${Math.min(100,e.memory.percent)}%`,i.classList.remove("medium","high"),n.classList.remove("high"),e.memory.percent>80?(i.classList.add("high"),n.classList.add("high")):e.memory.percent>50&&i.classList.add("medium")}}static _htmlEscapeMap={"&":"&","<":"<",">":">",'"':""","'":"'"};static _htmlEscapePattern=/[&<>"']/g;escapeHtml(e){return e?e.replace(CodemanApp._htmlEscapePattern,t=>CodemanApp._htmlEscapeMap[t]):""}}try{for(let d=0;d<localStorage.length;d++){const e=localStorage.key(d);if(e&&(e.startsWith("claudeman-")||e.startsWith("claudeman_"))){const t=e.replace(/^claudeman[-_]/,s=>"codeman"+s.charAt(s.length-1));localStorage.getItem(t)===null&&localStorage.setItem(t,localStorage.getItem(e))}}}catch{}const app=new CodemanApp;window.app=app,window.MobileDetection=MobileDetection;
|