aicodeman 1.3.2 → 1.3.4
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/dist/session.d.ts.map +1 -1
- package/dist/session.js +21 -1
- package/dist/session.js.map +1 -1
- package/dist/utils/claude-cli-resolver.d.ts +11 -0
- package/dist/utils/claude-cli-resolver.d.ts.map +1 -1
- package/dist/utils/claude-cli-resolver.js +41 -1
- package/dist/utils/claude-cli-resolver.js.map +1 -1
- package/dist/utils/index.d.ts +1 -1
- package/dist/utils/index.d.ts.map +1 -1
- package/dist/utils/index.js +1 -1
- package/dist/utils/index.js.map +1 -1
- package/dist/web/public/api-client.c9b1cddc.js.gz +0 -0
- package/dist/web/public/{app.b0534652.js → app.6890f3d0.js} +1 -1
- package/dist/web/public/app.6890f3d0.js.br +0 -0
- package/dist/web/public/app.6890f3d0.js.gz +0 -0
- package/dist/web/public/constants.5b18ed64.js.gz +0 -0
- package/dist/web/public/cron-ui.js.gz +0 -0
- package/dist/web/public/image-input.ee16ad88.js.gz +0 -0
- package/dist/web/public/index.html +15 -5
- package/dist/web/public/index.html.br +0 -0
- package/dist/web/public/index.html.gz +0 -0
- package/dist/web/public/input-cjk.63794d0b.js.gz +0 -0
- package/dist/web/public/keyboard-accessory.3f91acef.js.gz +0 -0
- package/dist/web/public/mobile-handlers.b5a667ef.js.gz +0 -0
- package/dist/web/public/mobile.0644e3ac.css.gz +0 -0
- package/dist/web/public/notification-manager.ca9dc40d.js.gz +0 -0
- package/dist/web/public/orchestrator-panel.js.gz +0 -0
- package/dist/web/public/panels-ui.ca03853f.js.gz +0 -0
- package/dist/web/public/ralph-panel.6de2d0f8.js.gz +0 -0
- package/dist/web/public/ralph-wizard.13a1831e.js.gz +0 -0
- package/dist/web/public/respawn-ui.2d249da9.js.gz +0 -0
- package/dist/web/public/sanitize-html.bc7078d6.js.gz +0 -0
- package/dist/web/public/session-ui.c9094fe9.js +49 -0
- package/dist/web/public/session-ui.c9094fe9.js.br +0 -0
- package/dist/web/public/session-ui.c9094fe9.js.gz +0 -0
- package/dist/web/public/settings-ui.9538a0c1.js +67 -0
- package/dist/web/public/settings-ui.9538a0c1.js.br +0 -0
- package/dist/web/public/settings-ui.9538a0c1.js.gz +0 -0
- package/dist/web/public/styles.3d78fd0d.css.gz +0 -0
- package/dist/web/public/subagent-windows.69b60c35.js.gz +0 -0
- package/dist/web/public/sw.js.gz +0 -0
- package/dist/web/public/terminal-ui.efda6083.js +3 -0
- package/dist/web/public/terminal-ui.efda6083.js.br +0 -0
- package/dist/web/public/terminal-ui.efda6083.js.gz +0 -0
- package/dist/web/public/ultracode-panel.js.gz +0 -0
- package/dist/web/public/ultracode-windows.js.gz +0 -0
- package/dist/web/public/upload.html.gz +0 -0
- package/dist/web/public/vendor/dompurify.min.js.gz +0 -0
- package/dist/web/public/vendor/marked.min.js.gz +0 -0
- package/dist/web/public/vendor/xterm-addon-fit.min.js.gz +0 -0
- package/dist/web/public/vendor/xterm-addon-serialize.min.js.gz +0 -0
- package/dist/web/public/vendor/xterm-addon-unicode11.min.js.gz +0 -0
- package/dist/web/public/vendor/xterm-addon-webgl.min.js.gz +0 -0
- package/dist/web/public/vendor/xterm-zerolag-input.137ad9f0.js.gz +0 -0
- package/dist/web/public/vendor/xterm.css.gz +0 -0
- package/dist/web/public/vendor/xterm.min.js.gz +0 -0
- package/dist/web/public/voice-input.085e9e73.js.gz +0 -0
- package/package.json +1 -1
- package/dist/web/public/app.b0534652.js.br +0 -0
- package/dist/web/public/app.b0534652.js.gz +0 -0
- package/dist/web/public/session-ui.b51814ef.js +0 -49
- package/dist/web/public/session-ui.b51814ef.js.br +0 -0
- package/dist/web/public/session-ui.b51814ef.js.gz +0 -0
- package/dist/web/public/settings-ui.6c67c125.js +0 -67
- package/dist/web/public/settings-ui.6c67c125.js.br +0 -0
- package/dist/web/public/settings-ui.6c67c125.js.gz +0 -0
- package/dist/web/public/terminal-ui.dbf141fa.js +0 -3
- package/dist/web/public/terminal-ui.dbf141fa.js.br +0 -0
- package/dist/web/public/terminal-ui.dbf141fa.js.gz +0 -0
|
@@ -1,49 +0,0 @@
|
|
|
1
|
-
"use strict";Object.assign(CodemanApp.prototype,{buildEnvOverrides(e,t){const s={};return(e?.agentTeams||t?.agentTeamsEnabled)&&(s.CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS="1"),s},getEffortSetting(e){const t=e?.thinkingEffort;return["low","medium","high","xhigh","max","ultracode"].includes(t)?t:void 0},formatCasePickerLabel(e){return e?.location==="remote"&&e.remote?.hostId?`${e.name} @ ${e.remote.hostId}`:e?.name||""},buildCasePickerOptions(e=[]){const t=[],s=new Set;for(const a of e)!a?.name||s.has(a.name)||(s.add(a.name),t.push(a));return s.has("testcase")||t.push({name:"testcase"}),t.map(a=>{const n=this.formatCasePickerLabel(a),o=[a.name,n,a.path,a.location,a.remote?.hostId,a.remote?.label,a.remote?.path].filter(Boolean).join(" ").toLowerCase();return{name:a.name,label:n,case:a,searchText:o}}).sort((a,n)=>a.label.localeCompare(n.label,void 0,{sensitivity:"base",numeric:!0}))},filterCasePickerOptions(e,t){const s=String(t||"").trim().toLowerCase().split(/\s+/).filter(Boolean);return s.length===0?e:e.filter(a=>s.every(n=>a.searchText.includes(n)))},getCasePickerOptions(){return this.buildCasePickerOptions(this.cases||[])},updateCasePickerInput(e){const t=document.getElementById("quickStartCaseSearch");if(!t)return;const s=this.getCasePickerOptions().find(a=>a.name===e);t.value=s?.label||e||"testcase",t.title=s?.label||t.value},renderQuickStartCaseSelectOptions(e,t){e&&(e.innerHTML=t.map(s=>`<option value="${escapeHtml(s.name)}">${escapeHtml(s.label)}</option>`).join(""))},openCasePicker(e=""){const t=document.getElementById("quickStartCaseSearch"),s=document.getElementById("quickStartCaseList");!t||!s||(this._casePickerOpen=!0,this._casePickerFilter=e,this._casePickerActiveIndex=0,t.setAttribute("aria-expanded","true"),this.renderCasePickerList())},closeCasePicker(){const e=document.getElementById("quickStartCaseSearch"),t=document.getElementById("quickStartCaseList");this._casePickerOpen=!1,this._casePickerFilter="",e?.setAttribute("aria-expanded","false"),e?.removeAttribute("aria-activedescendant"),t?.classList.add("hidden")},renderCasePickerList(){const e=document.getElementById("quickStartCaseSearch"),t=document.getElementById("quickStartCaseList"),s=document.getElementById("quickStartCase");if(!e||!t||!s)return;const a=this.filterCasePickerOptions(this.getCasePickerOptions(),this._casePickerFilter||""),n=s.value||"testcase",o=Math.max(0,a.length-1);if(this._casePickerActiveIndex=Math.min(Math.max(this._casePickerActiveIndex||0,0),o),a.length===0){t.innerHTML='<div class="case-combobox-empty">No cases match</div>',t.classList.remove("hidden"),e.removeAttribute("aria-activedescendant");return}t.innerHTML=a.map((i,r)=>{const c=r===this._casePickerActiveIndex,m=i.name===n;return`
|
|
2
|
-
<button
|
|
3
|
-
type="button"
|
|
4
|
-
id="${`quickStartCaseOption-${r}`}"
|
|
5
|
-
class="case-combobox-option ${c?"active":""} ${m?"selected":""}"
|
|
6
|
-
role="option"
|
|
7
|
-
aria-selected="${m?"true":"false"}"
|
|
8
|
-
data-case="${escapeHtml(i.name)}"
|
|
9
|
-
title="${escapeHtml(i.label)}">
|
|
10
|
-
<span class="case-combobox-check">${m?"\u2713":""}</span>
|
|
11
|
-
<span class="case-combobox-option-label">${escapeHtml(i.label)}</span>
|
|
12
|
-
</button>
|
|
13
|
-
`}).join(""),t.classList.remove("hidden"),e.setAttribute("aria-activedescendant",`quickStartCaseOption-${this._casePickerActiveIndex}`)},selectQuickStartCase(e,{save:t=!0}={}){const s=document.getElementById("quickStartCase");s&&(s.value=e||"testcase",this.updateCasePickerInput(s.value),this.closeCasePicker(),this.updateDirDisplayForCase(s.value),this.updateMobileCaseLabel(s.value),t&&this.saveLastUsedCase(s.value))},setupQuickStartCasePicker(){const e=document.getElementById("quickStartCase"),t=document.getElementById("quickStartCaseSearch"),s=document.getElementById("quickStartCaseList"),a=document.getElementById("quickStartCasePicker");!e||!t||!s||!a||t.dataset.listenerAdded||(t.addEventListener("focus",()=>{t.select?.(),this.openCasePicker("")}),t.addEventListener("click",()=>{t.select?.(),this.openCasePicker("")}),t.addEventListener("input",()=>{this.openCasePicker(t.value)}),t.addEventListener("keydown",n=>{const o=this.filterCasePickerOptions(this.getCasePickerOptions(),this._casePickerFilter||t.value);if(n.key==="ArrowDown")n.preventDefault(),this._casePickerActiveIndex=Math.min((this._casePickerActiveIndex||0)+1,Math.max(0,o.length-1)),this._casePickerOpen?this.renderCasePickerList():this.openCasePicker(t.value);else if(n.key==="ArrowUp")n.preventDefault(),this._casePickerActiveIndex=Math.max((this._casePickerActiveIndex||0)-1,0),this._casePickerOpen?this.renderCasePickerList():this.openCasePicker(t.value);else if(n.key==="Enter"){const i=o[this._casePickerActiveIndex||0];i&&(n.preventDefault(),this.selectQuickStartCase(i.name),this.run?.())}else n.key==="Escape"?(n.preventDefault(),this.updateCasePickerInput(e.value),this.closeCasePicker()):n.key==="Tab"&&(this.updateCasePickerInput(e.value),this.closeCasePicker())}),s.addEventListener("mousedown",n=>n.preventDefault()),s.addEventListener("click",n=>{const o=n.target.closest?.(".case-combobox-option");o?.dataset?.case&&this.selectQuickStartCase(o.dataset.case)}),document.addEventListener&&!this._casePickerDocumentListenerAdded&&(document.addEventListener("pointerdown",n=>{a.contains(n.target)||(this.updateCasePickerInput(e.value),this.closeCasePicker())}),this._casePickerDocumentListenerAdded=!0),t.dataset.listenerAdded="true")},async loadQuickStartCases(e=null,t=null){try{let s=null;try{const r=t?await t:await fetch("/api/settings").then(c=>c.ok?c.json():null).then(c=>c?.data??null);r&&(s=r.lastUsedCase||null)}catch{}const n=(await(await fetch("/api/cases")).json()).data;this.cases=n,console.log("[loadQuickStartCases] Loaded cases:",n.map(r=>r.name),"lastUsedCase:",s);const o=document.getElementById("quickStartCase"),i=this.getCasePickerOptions();if(this.renderQuickStartCaseSelectOptions(o,i),console.log("[loadQuickStartCases] Set options:",o.innerHTML.substring(0,200)),e)o.value=e,this.updateDirDisplayForCase(e),this.updateMobileCaseLabel(e);else if(s&&n.some(r=>r.name===s))o.value=s,this.updateDirDisplayForCase(s),this.updateMobileCaseLabel(s);else if(n.length>0){const r=n.find(c=>c.name==="testcase")||n[0];o.value=r.name,this.updateDirDisplayForCase(r.name),this.updateMobileCaseLabel(r.name)}else o.value="testcase",document.getElementById("dirDisplay").textContent="~/codeman-cases/testcase",this.updateMobileCaseLabel("testcase");this.updateCasePickerInput(o.value),this.renderCasePickerList(),this.closeCasePicker(),o.dataset.listenerAdded||(o.addEventListener("change",()=>{this.updateDirDisplayForCase(o.value),this.saveLastUsedCase(o.value),this.updateMobileCaseLabel(o.value),this.updateCasePickerInput(o.value)}),o.dataset.listenerAdded="true"),this.setupQuickStartCasePicker()}catch(s){console.error("Failed to load cases:",s)}},async updateDirDisplayForCase(e){try{const s=(await(await fetch(`/api/cases/${e}`)).json()).data;s.path&&(document.getElementById("dirDisplay").textContent=s.path,document.getElementById("dirInput").value=s.path)}catch{document.getElementById("dirDisplay").textContent=e}},async saveLastUsedCase(e){try{await fetch("/api/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({lastUsedCase:e})})}catch(t){console.error("Failed to save last used case:",t)}},async quickStart(){return this.run()},async run(){const e=this._runMode||"claude";return e==="opencode"?this.runOpenCode():e==="codex"?this.runCodex():e==="gemini"?this.runGemini():this.runClaude()},setRunMode(e){this._runMode=e;try{localStorage.setItem("codeman_runMode",e)}catch{}this._applyRunMode(),this._apiPut("/api/settings",{runMode:e}).catch(()=>{}),document.getElementById("runModeMenu")?.classList.remove("active")},toggleRunModeMenu(e){e?.stopPropagation();const t=document.getElementById("runModeMenu");if(t&&(t.classList.toggle("active"),t.querySelectorAll(".run-mode-option").forEach(s=>{s.classList.toggle("selected",s.dataset.mode===this.runMode)}),t.classList.contains("active"))){this._loadRunModeHistory();const s=a=>{t.contains(a.target)||(t.classList.remove("active"),document.removeEventListener("click",s))};setTimeout(()=>document.addEventListener("click",s),0)}},async _loadRunModeHistory(){const e=document.getElementById("runModeHistory");if(e){e.innerHTML='<div class="run-mode-hist-empty">Loading...</div>';try{const t=await this._fetchHistorySessions(10);if(t.length===0){e.innerHTML='<div class="run-mode-hist-empty">No history</div>';return}e.replaceChildren();for(const s of t){const a=new Date(s.lastModified),n=a.toLocaleDateString("en",{month:"short",day:"numeric"})+" "+a.toLocaleTimeString("en",{hour:"2-digit",minute:"2-digit",hour12:!1}),o=s.workingDir.replace(/^\/home\/[^/]+\//,"~/"),i=document.createElement("button");i.className="run-mode-option",i.title=s.workingDir,i.dataset.sessionId=s.sessionId,i.dataset.workingDir=s.workingDir;const r=document.createElement("span");r.className="hist-dir",r.textContent=o;const c=document.createElement("span");c.className="hist-meta",c.textContent=n,i.append(r,c),i.addEventListener("click",m=>{m.stopPropagation(),this.resumeHistorySession(s.sessionId,s.workingDir)}),e.appendChild(i)}}catch{e.innerHTML='<div class="run-mode-hist-empty">Failed to load</div>'}}},_applyRunMode(){const e=this.runMode,t=document.getElementById("runBtn"),s=t?.nextElementSibling,a=document.getElementById("runBtnLabel");t&&(t.className=`btn-toolbar btn-run mode-${e}`),s&&(s.className=`btn-toolbar btn-run-gear mode-${e}`),a&&(a.textContent=e==="opencode"?"Run OC":e==="codex"?"Run CX":e==="gemini"?"Run GM":"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(""),this.terminal.focus();try{let a=(await(await fetch(`/api/cases/${e}`)).json())?.data??{};if(!a.path){const f=await(await fetch("/api/cases",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:e,description:""})})).json();if(!f.success)throw new Error(f.error||"Failed to create case");a=f.data.case}const n=a.path;if(!n)throw new Error("Case path not found");if(a.location==="remote"){const u=[];for(let f=0;f<t;f++){const w=await(await fetch("/api/quick-start",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({caseName:e,mode:"claude"})})).json();if(!w.success)throw new Error(w.error||"Failed to start remote Claude session");u.push(w.data.sessionId)}this.terminal.writeln(`\x1B[90m All ${t} remote session(s) ready\x1B[0m`),u[0]&&(await this.selectSession(u[0]),this.loadQuickStartCases()),this.terminal.focus();return}let o=null,i=1;for(const[,u]of this.sessions){const f=u.name&&u.name.match(/^w(\d+)-([a-zA-Z0-9_-]+)/);if(f&&f[2]===e){const v=parseInt(f[1]);v>=i&&(i=v+1)}}const r=this.isRalphTrackerEnabledByDefault(),c=[];for(let u=0;u<t;u++)c.push(`w${i+u}-${e}`);const m=this.getCaseSettings(e),h=this.loadAppSettingsFromStorage(),p=this.buildEnvOverrides(m,h),y=Object.keys(p).length>0,l=this.getEffortSetting(h),d=m.opusContext1m||h.opusContext1mEnabled,C=h.claudeModel||(d?"opus[1m]":"");this.terminal.writeln(`\x1B[90m Creating ${t} session(s)...\x1B[0m`);const g=c.map(u=>fetch("/api/sessions",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({workingDir:n,name:u,...y?{envOverrides:p}:{},...l?{effort:l}:{},...C!==void 0?{modelOverride:C}:{},statusLineTelemetry:h.showPlanUsageLimits===!0})}).then(f=>f.json())),S=await Promise.all(g),b=[];for(const u of S){if(!u.success)throw new Error(u.error);b.push(u.data.session.id)}o=b[0],await Promise.all(b.map(u=>fetch(`/api/sessions/${u}/ralph-config`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({enabled:r,disableAutoEnable:!r})}))),this.terminal.writeln(`\x1B[90m Starting ${t} session(s) in parallel...\x1B[0m`),await Promise.all(b.map(u=>fetch(`/api/sessions/${u}/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{let a=(await(await fetch(`/api/cases/${e}`)).json())?.data??{};if(!a.path){const d=await(await fetch("/api/cases",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:e,description:""})})).json();if(!d.success)throw new Error(d.error||"Failed to create case");a=d.data.case}const n=(this.cases||[]).find(l=>l.name===e),o=a.location==="remote"||n?.location==="remote",i=a.path;if(!i)throw new Error("Case path not found");if(a.location==="remote"){const l=[];for(let d=0;d<t;d++){const g=await(await fetch("/api/quick-start",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({caseName:e,mode:"shell"})})).json();if(!g.success)throw new Error(g.error||"Failed to start remote shell session");l.push(g.data.sessionId)}l[0]&&(this.activeSessionId=l[0],await this.selectSession(l[0])),this.terminal.focus();return}let r=1;for(const[,l]of this.sessions){const d=l.name&&l.name.match(/^s(\d+)-([a-zA-Z0-9_-]+)/);if(d&&d[2]===e){const C=parseInt(d[1]);C>=r&&(r=C+1)}}const c=[];for(let l=0;l<t;l++)c.push(`s${r+l}-${e}`);const m=c.map(l=>fetch("/api/sessions",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...o?{caseName:e}:{workingDir:i},mode:"shell",name:l})}).then(d=>d.json())),h=await Promise.all(m),p=[];for(const l of h){if(!l.success)throw new Error(l.error);p.push(l.data.session.id)}await Promise.all(p.map(l=>fetch(`/api/sessions/${l}/shell`,{method:"POST"})));const y=this.getTerminalDimensions();y&&await Promise.all(p.map(l=>fetch(`/api/sessions/${l}/resize`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(y)}))),p.length>0&&(this.activeSessionId=p[0],await this.selectSession(p[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",t=(this.cases||[]).find(s=>s.name===e)?.location==="remote";this.terminal.clear(),this.terminal.writeln(`\x1B[1;32m Starting OpenCode session in ${e}...\x1B[0m`),this.terminal.writeln(""),this.terminal.focus();try{if(!t&&!(await(await fetch("/api/opencode/status")).json()).data.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 s=this.buildEnvOverrides(this.getCaseSettings(e),this.loadAppSettingsFromStorage()),n=await(await fetch("/api/quick-start",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({caseName:e,mode:"opencode",...t?{}:{openCodeConfig:{autoAllowTools:!0},...Object.keys(s).length>0?{envOverrides:s}:{}}})})).json();if(!n.success)throw new Error(n.error||"Failed to start OpenCode");n.data.sessionId&&await this.selectSession(n.data.sessionId),this.terminal.focus()}catch(s){this.terminal.writeln(`\x1B[1;31m Error: ${s.message}\x1B[0m`)}},async runCodex(){const e=document.getElementById("quickStartCase").value||"testcase",t=(this.cases||[]).find(s=>s.name===e)?.location==="remote";this.terminal.clear(),this.terminal.writeln(`\x1B[1;32m Starting Codex session in ${e}...\x1B[0m`),this.terminal.writeln(""),this.terminal.focus();try{if(!t&&!(await(await fetch("/api/codex/status")).json()).data.available){this.terminal.writeln("\x1B[1;31m Codex CLI not found.\x1B[0m"),this.terminal.writeln("\x1B[90m Install with: npm install -g @openai/codex\x1B[0m");return}const s=this.loadAppSettingsFromStorage(),a=this.buildEnvOverrides(this.getCaseSettings(e),s),o=await(await fetch("/api/quick-start",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({caseName:e,mode:"codex",...t?{}:{codexConfig:{dangerouslyBypassApprovals:s.codexDangerouslyBypassApprovals??!1,renderMode:"hybrid"},...Object.keys(a).length>0?{envOverrides:a}:{}}})})).json();if(!o.success)throw new Error(o.error||"Failed to start Codex");o.data.sessionId&&await this.selectSession(o.data.sessionId),this.terminal.focus()}catch(s){this.terminal.writeln(`\x1B[1;31m Error: ${s.message}\x1B[0m`)}},async runGemini(){const e=document.getElementById("quickStartCase").value||"testcase",t=(this.cases||[]).find(s=>s.name===e)?.location==="remote";this.terminal.clear(),this.terminal.writeln(`\x1B[1;32m Starting Gemini session in ${e}...\x1B[0m`),this.terminal.writeln(""),this.terminal.focus();try{if(!t&&!(await(await fetch("/api/gemini/status")).json()).data.available){this.terminal.writeln("\x1B[1;31m Gemini CLI not found.\x1B[0m"),this.terminal.writeln("\x1B[90m Install with: npm install -g @google/gemini-cli\x1B[0m");return}const s=this.buildEnvOverrides(this.getCaseSettings(e),this.loadAppSettingsFromStorage()),n=await(await fetch("/api/quick-start",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({caseName:e,mode:"gemini",...t?{}:{geminiConfig:{approvalMode:"yolo"},...Object.keys(s).length>0?{envOverrides:s}:{}}})})).json();if(!n.success)throw new Error(n.error||"Failed to start Gemini");n.data.sessionId&&await this.selectSession(n.data.sessionId),this.terminal.focus()}catch(s){this.terminal.writeln(`\x1B[1;31m Error: ${s.message}\x1B[0m`)}},openSessionOptions(e){const t=this.sessions.get(e);if(!t)return;this.editingSessionId=e;const s=t.mode==="opencode"||t.mode==="codex"||t.mode==="gemini";this.switchOptionsTab(s?"summary":"respawn");const a=document.getElementById("sessionRespawnStatus"),n=document.getElementById("modalEnableRespawnBtn"),o=document.getElementById("modalStopRespawnBtn");this.respawnStatus[e]?(a.classList.add("active"),a.querySelector(".respawn-status-text").textContent=this.respawnStatus[e].state||"Active",n.style.display="none",o.style.display=""):(a.classList.remove("active"),a.querySelector(".respawn-status-text").textContent="Not active",n.style.display="",o.style.display="none");const i=document.getElementById("sessionRespawnSection");t.mode==="claude"&&t.pid?i.style.display="":i.style.display="none";const r=t.mode==="opencode"||t.mode==="codex"||t.mode==="gemini";document.querySelectorAll("[data-claude-only]").forEach(g=>{g.style.display=r?"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("modalAutoResumeEnabled").checked=t.autoResumeEnabled??!1,this.updateAutoResumeStatus(e),document.getElementById("modalImageWatcherEnabled").checked=t.imageWatcherEnabled??!0,document.getElementById("modalFlickerFilterEnabled").checked=t.flickerFilterEnabled??!1;const m=parseSessionPrefix(t.name),h=document.getElementById("modalSessionPrefix");m?(h.textContent=m.prefix+": ",h.style.display="",document.getElementById("modalSessionName").value=m.suffix,document.getElementById("modalSessionName").placeholder="Add description..."):(h.style.display="none",h.textContent="",document.getElementById("modalSessionName").value=t.name||"",document.getElementById("modalSessionName").placeholder="Auto (directory name)");const p=t.color||"default";document.getElementById("sessionColorPicker")?.querySelectorAll(".color-swatch").forEach(g=>{g.classList.toggle("selected",g.dataset.color===p)}),this.renderPresetDropdown(),document.getElementById("respawnPresetSelect").value="",document.getElementById("presetDescriptionHint").textContent="";const l=document.querySelector('#sessionOptionsModal .modal-tab-btn[data-tab="ralph"]'),d=document.querySelector('#sessionOptionsModal .modal-tab-btn[data-tab="respawn"]');if(r?(l&&(l.style.display="none"),d&&(d.style.display="none"),this.switchOptionsTab("context")):(l&&(l.style.display=""),d&&(d.style.display="")),!r){const g=this.ralphStates.get(e);this.populateRalphForm({enabled:g?.loop?.enabled??t.ralphLoop?.enabled??!1,completionPhrase:g?.loop?.completionPhrase||t.ralphLoop?.completionPhrase||"",maxIterations:g?.loop?.maxIterations||t.ralphLoop?.maxIterations||0,maxTodos:g?.loop?.maxTodos||t.ralphLoop?.maxTodos,todoExpirationMinutes:g?.loop?.todoExpirationMinutes||t.ralphLoop?.todoExpirationMinutes})}const C=document.getElementById("sessionOptionsModal");C.classList.add("active"),this.activeFocusTrap=new FocusTrap(C),this.activeFocusTrap.activate()},async saveSessionName(){if(!this.editingSessionId)return;const e=this.sessions.get(this.editingSessionId),t=e?parseSessionPrefix(e.name):null,s=document.getElementById("modalSessionName").value.trim();let a;t?a=t.prefix+(s?": "+s:""):a=s;try{await this._apiPut(`/api/sessions/${this.editingSessionId}/name`,{name:a})}catch(n){this.showToast("Failed to save session name: "+n.message,"error")}},async autoSaveAutoCompact(){if(this.editingSessionId)try{await this._apiPost(`/api/sessions/${this.editingSessionId}/auto-compact`,{enabled:document.getElementById("modalAutoCompactEnabled").checked,threshold:parseInt(document.getElementById("modalAutoCompactThreshold").value)||11e4,prompt:document.getElementById("modalAutoCompactPrompt").value.trim()||void 0})}catch{}},async autoSaveAutoClear(){if(this.editingSessionId)try{await this._apiPost(`/api/sessions/${this.editingSessionId}/auto-clear`,{enabled:document.getElementById("modalAutoClearEnabled").checked,threshold:parseInt(document.getElementById("modalAutoClearThreshold").value)||14e4})}catch{}},async autoSaveAutoResume(){if(!this.editingSessionId)return;const e=document.getElementById("modalAutoResumeEnabled").checked;try{await this._apiPost(`/api/sessions/${this.editingSessionId}/auto-resume`,{enabled:e});const t=this.sessions.get(this.editingSessionId);t&&(t.autoResumeEnabled=e,e||(t.autoResumeAt=void 0)),this.updateAutoResumeStatus(this.editingSessionId),this.showToast(`Auto-resume on usage limit ${e?"enabled":"disabled"}`,"success")}catch(t){this.showToast("Failed to toggle auto-resume: "+t.message,"error")}},updateAutoResumeStatus(e){const t=document.getElementById("autoResumeStatus");if(!t||this.editingSessionId!==e)return;const s=this.sessions.get(e);if(s?.autoResumeAt&&s.autoResumeAt>Date.now()){const a=new Date(s.autoResumeAt).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});t.textContent=`Usage limit pause active \u2014 resumes at ${a}`,t.classList.add("active")}else t.textContent="",t.classList.remove("active")},async toggleSessionImageWatcher(){if(!this.editingSessionId)return;const e=document.getElementById("modalImageWatcherEnabled").checked;try{await this._apiPost(`/api/sessions/${this.editingSessionId}/image-watcher`,{enabled:e});const t=this.sessions.get(this.editingSessionId);t&&(t.imageWatcherEnabled=e),this.showToast(`Image watcher ${e?"enabled":"disabled"}`,"success")}catch{this.showToast("Failed to toggle image watcher","error")}},async toggleFlickerFilter(){if(!this.editingSessionId)return;const e=document.getElementById("modalFlickerFilterEnabled").checked;try{await this._apiPost(`/api/sessions/${this.editingSessionId}/flicker-filter`,{enabled:e});const t=this.sessions.get(this.editingSessionId);t&&(t.flickerFilterEnabled=e),this.showToast(`Flicker filter ${e?"enabled":"disabled"}`,"success")}catch{this.showToast("Failed to toggle flicker filter","error")}},async autoSaveRespawnConfig(){if(!this.editingSessionId)return;const e={updatePrompt:document.getElementById("modalRespawnPrompt").value,sendClear:document.getElementById("modalRespawnSendClear").checked,sendInit:document.getElementById("modalRespawnSendInit").checked,kickstartPrompt:document.getElementById("modalRespawnKickstart").value.trim()||void 0,autoAcceptPrompts:document.getElementById("modalRespawnAutoAccept").checked};try{await this._apiPut(`/api/sessions/${this.editingSessionId}/respawn/config`,e)}catch{}},async loadSavedRespawnConfig(e){try{const s=await(await fetch(`/api/sessions/${e}/respawn/config`)).json();if(s.success&&s.data&&s.data.config){const a=s.data.config;document.getElementById("modalRespawnPrompt").value=a.updatePrompt||"update all the docs and CLAUDE.md",document.getElementById("modalRespawnSendClear").checked=a.sendClear??!0,document.getElementById("modalRespawnSendInit").checked=a.sendInit??!0,document.getElementById("modalRespawnKickstart").value=a.kickstartPrompt||"",document.getElementById("modalRespawnAutoAccept").checked=a.autoAcceptPrompts??!0,a.durationMinutes&&(document.querySelector(`.duration-preset-btn[data-minutes="${a.durationMinutes}"]`)?this.selectDurationPreset(String(a.durationMinutes)):(this.selectDurationPreset("custom"),document.getElementById("modalRespawnDuration").value=a.durationMinutes))}}catch{}},selectDurationPreset(e){document.querySelectorAll(".duration-preset-btn").forEach(n=>n.classList.remove("active"));const t=document.querySelector(`.duration-preset-btn[data-minutes="${e}"]`);t&&t.classList.add("active");const s=document.querySelector(".duration-custom-input"),a=document.getElementById("modalRespawnDuration");e==="custom"?(s.classList.add("visible"),a.focus()):(s.classList.remove("visible"),a.value="")},getSelectedDuration(){const e=document.querySelector(".duration-custom-input"),t=document.getElementById("modalRespawnDuration");if(e.classList.contains("visible"))return t.value?parseInt(t.value):null;{const a=document.querySelector(".duration-preset-btn.active")?.dataset.minutes;return a?parseInt(a):null}},switchOptionsTab(e){document.querySelectorAll("#sessionOptionsModal .modal-tab-btn").forEach(t=>{t.classList.toggle("active",t.dataset.tab===e)}),document.getElementById("respawn-tab").classList.toggle("hidden",e!=="respawn"),document.getElementById("context-tab").classList.toggle("hidden",e!=="context"),document.getElementById("ralph-tab").classList.toggle("hidden",e!=="ralph"),document.getElementById("summary-tab").classList.toggle("hidden",e!=="summary"),e==="summary"&&this.editingSessionId&&this.loadRunSummary(this.editingSessionId)},getRalphConfig(){return{enabled:document.getElementById("modalRalphEnabled").checked,completionPhrase:document.getElementById("modalRalphPhrase").value.trim(),maxIterations:parseInt(document.getElementById("modalRalphMaxIterations").value)||0,maxTodos:parseInt(document.getElementById("modalRalphMaxTodos").value)||50,todoExpirationMinutes:parseInt(document.getElementById("modalRalphTodoExpiration").value)||60}},populateRalphForm(e){document.getElementById("modalRalphEnabled").checked=e?.enabled??!1,document.getElementById("modalRalphPhrase").value=e?.completionPhrase||"",document.getElementById("modalRalphMaxIterations").value=e?.maxIterations||0,document.getElementById("modalRalphMaxTodos").value=e?.maxTodos||50,document.getElementById("modalRalphTodoExpiration").value=e?.todoExpirationMinutes||60},async saveRalphConfig(){if(!this.editingSessionId){this.showToast("No session selected","warning");return}const e=this.getRalphConfig();e.enabled&&this.ralphClosedSessions.delete(this.editingSessionId);try{const s=await(await fetch(`/api/sessions/${this.editingSessionId}/ralph-config`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})).json();if(s.error)throw new Error(s.error);this.showToast("Ralph config saved","success")}catch(t){this.showToast("Failed to save Ralph config: "+t.message,"error")}},startInlineRename(e){const t=this.sessions.get(e);if(!t)return;const s=document.querySelector(`.tab-name[data-session-id="${e}"]`);if(!s)return;this._inlineRenameActive=!0;const a=this.getSessionName(t),n=parseSessionPrefix(t.name),o=s.textContent;for(s.textContent="";s.firstChild;)s.removeChild(s.firstChild);if(n){const c=document.createElement("span");c.textContent=n.prefix+": ",c.style.cssText="color: var(--text-muted); font-size: 0.75rem; white-space: nowrap;",s.appendChild(c)}const i=document.createElement("input");i.type="text",i.value=n?n.suffix:t.name||"",i.placeholder=n?"Add description...":a,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;",s.appendChild(i),i.focus(),i.select();const r=async({commit:c})=>{if(!this._inlineRenameActive)return;if(this._inlineRenameActive=!1,this._activeRename=null,!c){this.renderSessionTabs();return}const m=i.value.trim(),h=n?n.prefix+(m?": "+m:""):m;if(s.textContent=h||o,this.sessions.has(e)&&h!==t.name)try{await fetch(`/api/sessions/${e}/name`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:h})})}catch{s.textContent=o,this.showToast("Failed to rename","error")}this.renderSessionTabs()};this._activeRename={sessionId:e,cancel:()=>r({commit:!1})},i.addEventListener("blur",()=>r({commit:!0})),i.addEventListener("keydown",c=>{c.isComposing||c.keyCode===229||(c.key==="Enter"?(c.preventDefault(),i.blur()):c.key==="Escape"&&(i.value="",i.blur()))})},toggleCaseSettings(){const e=document.getElementById("caseSettingsPopover");if(e.classList.contains("hidden")){const t=document.getElementById("quickStartCase").value||"testcase",s=this.getCaseSettings(t);document.getElementById("caseAgentTeams").checked=s.agentTeams,document.getElementById("caseOpusContext1m").checked=s.opusContext1m,e.classList.remove("hidden");const a=n=>{!e.contains(n.target)&&!n.target.classList.contains("btn-case-settings")&&(e.classList.add("hidden"),document.removeEventListener("click",a))};setTimeout(()=>document.addEventListener("click",a),0)}else e.classList.add("hidden")},getCaseSettings(e){try{const t=localStorage.getItem("caseSettings_"+e);if(t)return JSON.parse(t)}catch{}return{agentTeams:!1,opusContext1m:!0}},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,t.opusContext1m=document.getElementById("caseOpusContext1m").checked,this.saveCaseSettings(e,t);const s=document.getElementById("caseAgentTeamsMobile");s&&(s.checked=t.agentTeams);const a=document.getElementById("caseOpusContext1mMobile");a&&(a.checked=t.opusContext1m)},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,document.getElementById("caseOpusContext1mMobile").checked=s.opusContext1m,e.classList.remove("hidden");const a=n=>{!e.contains(n.target)&&!n.target.classList.contains("btn-case-settings-mobile")&&(e.classList.add("hidden"),document.removeEventListener("click",a))};setTimeout(()=>document.addEventListener("click",a),0)}else e.classList.add("hidden")},onCaseSettingChangedMobile(){const e=document.getElementById("quickStartCase").value||"testcase",t=this.getCaseSettings(e);t.agentTeams=document.getElementById("caseAgentTeamsMobile").checked,t.opusContext1m=document.getElementById("caseOpusContext1mMobile").checked,this.saveCaseSettings(e,t);const s=document.getElementById("caseAgentTeams");s&&(s.checked=t.agentTeams);const a=document.getElementById("caseOpusContext1m");a&&(a.checked=t.opusContext1m)},showCreateCaseModal(){document.getElementById("newCaseName").value="",document.getElementById("newCaseDescription").value="",document.getElementById("linkCaseName").value="",document.getElementById("linkCasePath").value="",["remoteCaseName","remoteCasePath","remoteHostId","remoteHostAddress","remoteHostUsername","remoteHostPort","remoteHostCodexCommand","remoteHostIdentityFile","remoteHostSocksProxy","remoteHostJumpHost","remoteHostExtraSshOptions"].forEach(s=>{const a=document.getElementById(s);a&&(a.value="")}),this.caseModalTab="case-create",this.switchCaseModalTab("case-create");const t=document.getElementById("createCaseModal");t.querySelectorAll(".modal-tabs .modal-tab-btn").forEach(s=>{s.onclick=()=>this.switchCaseModalTab(s.dataset.tab)}),t.querySelectorAll('input[type="text"]').forEach(s=>{s._mobileScrollWired||(s._mobileScrollWired=!0,s.addEventListener("focus",()=>{window.innerWidth<=430&&setTimeout(()=>s.scrollIntoView({behavior:"smooth",block:"center"}),300)}))}),t.classList.add("active"),document.getElementById("newCaseName").focus()},switchCaseModalTab(e){this.caseModalTab=e;const t=document.getElementById("createCaseModal");t.querySelectorAll(".modal-tabs .modal-tab-btn").forEach(a=>{a.classList.toggle("active",a.dataset.tab===e)}),t.querySelectorAll(".modal-tab-content").forEach(a=>{a.classList.toggle("hidden",a.id!==e)});const s=document.getElementById("caseModalSubmit");e==="case-manage"?(s.style.display="none",this.renderCaseManageList()):(s.style.display="",s.textContent=e==="case-create"?"Create":e==="case-remote"?"Link Remote":"Link"),e==="case-create"?document.getElementById("newCaseName").focus():e==="case-link"?document.getElementById("linkCaseName").focus():e==="case-remote"&&document.getElementById("remoteCaseName").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():this.caseModalTab==="case-remote"?await this.linkRemoteCase():await this.linkCase()}finally{e.classList.remove("loading"),e.textContent=t}},async createCase(){const e=document.getElementById("newCaseName").value.trim(),t=document.getElementById("newCaseDescription").value.trim();if(!e){this.showToast("Please enter a case name","error");return}if(!/^[a-zA-Z0-9_-]+$/.test(e)){this.showToast("Invalid name. Use only letters, numbers, hyphens, underscores.","error");return}try{const a=await(await fetch("/api/cases",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:e,description:t})})).json();a.success?(this.closeCreateCaseModal(),this.showToast(`Case "${e}" created`,"success"),await this.loadQuickStartCases(e),await this.saveLastUsedCase(e)):this.showToast(a.error||"Failed to create case","error")}catch(s){console.error("Failed to create case:",s),this.showToast("Failed to create case: "+s.message,"error")}},async linkCase(){const e=document.getElementById("linkCaseName").value.trim(),t=document.getElementById("linkCasePath").value.trim();if(!e){this.showToast("Please enter a case name","error");return}if(!/^[a-zA-Z0-9_-]+$/.test(e)){this.showToast("Invalid name. Use only letters, numbers, hyphens, underscores.","error");return}if(!t){this.showToast("Please enter a folder path","error");return}try{const a=await(await fetch("/api/cases/link",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:e,path:t})})).json();a.success?(this.closeCreateCaseModal(),this.showToast(`Case "${e}" linked to ${t}`,"success"),await this.loadQuickStartCases(e),await this.saveLastUsedCase(e)):this.showToast(a.error||"Failed to link case","error")}catch(s){console.error("Failed to link case:",s),this.showToast("Failed to link case: "+s.message,"error")}},async linkRemoteCase(){const e=document.getElementById("remoteCaseName").value.trim(),t=document.getElementById("remoteCasePath").value.trim(),s=document.getElementById("remoteHostId").value.trim(),a=document.getElementById("remoteHostAddress").value.trim(),n=document.getElementById("remoteHostUsername").value.trim(),o=document.getElementById("remoteHostCodexCommand").value.trim(),i=document.getElementById("remoteHostPort").value.trim(),r=document.getElementById("remoteHostIdentityFile").value.trim(),c=document.getElementById("remoteHostSocksProxy").value.trim(),m=document.getElementById("remoteHostJumpHost").value.trim(),h=document.getElementById("remoteHostExtraSshOptions").value.split(`
|
|
14
|
-
`).map(y=>y.trim()).filter(y=>y.length>0);if(!e||!t||!s||!a||!n){this.showToast("Please complete all required remote fields","error");return}if(!/^[a-zA-Z0-9_-]+$/.test(e)||!/^[a-zA-Z0-9_-]+$/.test(s)){this.showToast("Invalid name. Use only letters, numbers, hyphens, underscores.","error");return}if(!t.startsWith("/")){this.showToast("Remote path must be absolute","error");return}let p;if(i&&(p=Number(i),!Number.isInteger(p)||p<1||p>65535)){this.showToast("SSH port must be a number between 1 and 65535","error");return}try{const y={id:s,label:s,host:a,username:n,...p?{port:p}:{},...r?{identityFile:r}:{},...c?{socksProxy:c}:{},...m?{jumpHost:m}:{},...h.length?{extraSshOptions:h}:{},...o?{commands:{codex:o}}:{}},d=await(await fetch("/api/remote-hosts",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(y)})).json();if(!d.success&&d.errorCode!=="ALREADY_EXISTS")throw new Error(d.error||"Failed to save remote host");const g=await(await fetch("/api/cases/remote-link",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:e,hostId:s,remotePath:t})})).json();g.success?(this.closeCreateCaseModal(),this.showToast(`Remote case "${e}" linked`,"success"),await this.loadQuickStartCases(e),await this.saveLastUsedCase(e)):this.showToast(g.error||"Failed to link remote case","error")}catch(y){console.error("Failed to link remote case:",y),this.showToast("Failed to link remote case: "+y.message,"error")}},renderCaseManageList(){const e=document.getElementById("caseManageList"),t=this.cases||[];if(t.length===0){e.innerHTML='<div class="form-hint" style="text-align: center; padding: 2rem 0;">No cases yet</div>';return}let s="";t.forEach((a,n)=>{const o=n===0,i=n===t.length-1,r=a.path?a.path.replace(/^\/Users\/[^/]+/,"~"):"";s+=`
|
|
15
|
-
<div class="case-manage-item" data-case="${escapeHtml(a.name)}">
|
|
16
|
-
<div class="case-manage-info">
|
|
17
|
-
<span class="case-manage-name">${escapeHtml(a.name)}</span>
|
|
18
|
-
<span class="case-manage-path">${escapeHtml(r)}</span>
|
|
19
|
-
</div>
|
|
20
|
-
<div class="case-manage-actions">
|
|
21
|
-
<button class="case-manage-btn" onclick="app.moveCaseUp(${escapeHtml(JSON.stringify(a.name))})"
|
|
22
|
-
title="Move up" ${o?"disabled":""}>▲</button>
|
|
23
|
-
<button class="case-manage-btn" onclick="app.moveCaseDown(${escapeHtml(JSON.stringify(a.name))})"
|
|
24
|
-
title="Move down" ${i?"disabled":""}>▼</button>
|
|
25
|
-
<button class="case-manage-btn case-manage-btn-delete" onclick="app.deleteCase(${escapeHtml(JSON.stringify(a.name))})"
|
|
26
|
-
title="Delete case">✕</button>
|
|
27
|
-
</div>
|
|
28
|
-
</div>
|
|
29
|
-
`}),e.innerHTML=s},async moveCaseUp(e){const t=this.cases||[],s=t.findIndex(n=>n.name===e);if(s<=0)return;const a=[...t];[a[s-1],a[s]]=[a[s],a[s-1]],this.cases=a,this.renderCaseManageList(),await this.saveCaseOrder(a.map(n=>n.name))},async moveCaseDown(e){const t=this.cases||[],s=t.findIndex(n=>n.name===e);if(s<0||s>=t.length-1)return;const a=[...t];[a[s],a[s+1]]=[a[s+1],a[s]],this.cases=a,this.renderCaseManageList(),await this.saveCaseOrder(a.map(n=>n.name))},async deleteCase(e){if(confirm(`Delete case "${e}"? Linked cases will only be unlinked (folder preserved). Created cases will be permanently deleted.`))try{const s=await(await fetch(`/api/cases/${encodeURIComponent(e)}`,{method:"DELETE"})).json();if(s.success){this.showToast(`Case "${e}" ${s.data?.type==="unlinked"?"unlinked":"deleted"}`,"success"),this.cases=(this.cases||[]).filter(o=>o.name!==e),this.renderCaseManageList();const a=document.getElementById("quickStartCase"),n=a.value;n===e&&a.blur?.(),await this.loadQuickStartCases(n===e?null:n),n===e&&await this.saveLastUsedCase(document.getElementById("quickStartCase")?.value||"testcase")}else this.showToast(s.error||"Failed to delete case","error")}catch(t){this.showToast("Failed to delete case: "+t.message,"error")}},async saveCaseOrder(e){try{await fetch("/api/cases/order",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({order:e})});const s=document.getElementById("quickStartCase").value;await this.loadQuickStartCases(s)}catch(t){this.showToast("Failed to save case order: "+t.message,"error")}},showMobileCasePicker(){const e=document.getElementById("mobileCasePickerModal"),t=document.getElementById("mobileCaseList"),a=document.getElementById("quickStartCase").value;let n="";const o=this.getCasePickerOptions();for(const i of o){const r=i.name===a;n+=`
|
|
30
|
-
<button class="mobile-case-item ${r?"selected":""}"
|
|
31
|
-
onclick="app.selectMobileCase(${escapeHtml(JSON.stringify(i.name))})">
|
|
32
|
-
<span class="mobile-case-item-icon">
|
|
33
|
-
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
34
|
-
<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"/>
|
|
35
|
-
</svg>
|
|
36
|
-
</span>
|
|
37
|
-
<span class="mobile-case-item-name">${escapeHtml(i.label)}</span>
|
|
38
|
-
<span class="mobile-case-item-delete" onclick="event.stopPropagation(); app.deleteCaseMobile(${escapeHtml(JSON.stringify(i.name))})" title="Delete">
|
|
39
|
-
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
40
|
-
<line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/>
|
|
41
|
-
</svg>
|
|
42
|
-
</span>
|
|
43
|
-
<span class="mobile-case-item-check">
|
|
44
|
-
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5">
|
|
45
|
-
<polyline points="20 6 9 17 4 12"/>
|
|
46
|
-
</svg>
|
|
47
|
-
</span>
|
|
48
|
-
</button>
|
|
49
|
-
`}t.innerHTML=n,e.classList.add("active")},closeMobileCasePicker(){document.getElementById("mobileCasePickerModal").classList.remove("active")},selectMobileCase(e){const t=document.getElementById("quickStartCase");t.value=e,this.updateMobileCaseLabel(e),this.updateDirDisplayForCase(e),this.saveLastUsedCase(e),this.closeMobileCasePicker(),this.showToast(`Selected: ${e}`,"success")},updateMobileCaseLabel(e){const t=document.getElementById("mobileCaseName");t&&(t.textContent=e)},async deleteCaseMobile(e){if(confirm(`Delete case "${e}"?`))try{const s=await(await fetch(`/api/cases/${encodeURIComponent(e)}`,{method:"DELETE"})).json();s.success?(this.showToast(`Case "${e}" ${s.data?.type==="unlinked"?"unlinked":"deleted"}`,"success"),this.cases=(this.cases||[]).filter(a=>a.name!==e),this.closeMobileCasePicker(),await this.loadQuickStartCases()):this.showToast(s.error||"Failed to delete case","error")}catch(t){this.showToast("Failed to delete case: "+t.message,"error")}},showCreateCaseFromMobile(){this.closeMobileCasePicker(),this.showCreateCaseModal();const e=document.getElementById("createCaseModal");e.classList.add("from-mobile"),setTimeout(()=>e.classList.remove("from-mobile"),300)}}),Object.defineProperty(CodemanApp.prototype,"runMode",{configurable:!0,enumerable:!0,get(){return this._runMode||"claude"},set(e){this._runMode=e==="opencode"||e==="codex"||e==="gemini"||e==="claude"?e:"claude"}});
|
|
Binary file
|
|
Binary file
|
|
@@ -1,67 +0,0 @@
|
|
|
1
|
-
"use strict";Object.assign(CodemanApp.prototype,{_onHookIdlePrompt(e){e.sessionId&&this.setPendingHook(e.sessionId,"idle_prompt"),this._notifySession(e.sessionId,"warning","hook-idle","Waiting for Input",e.message||"Claude is idle and waiting for a prompt")},_onHookPermissionPrompt(e){e.sessionId&&this.setPendingHook(e.sessionId,"permission_prompt");const t=e.tool?`${e.tool}${e.command?": "+e.command:e.file?": "+e.file:""}`:"";this._notifySession(e.sessionId,"critical","hook-permission","Permission Required",t||"Claude needs tool approval to continue")},_onHookElicitationDialog(e){e.sessionId&&this.setPendingHook(e.sessionId,"elicitation_dialog"),this._notifySession(e.sessionId,"critical","hook-elicitation","Question Asked",e.question||"Claude is asking a question and waiting for your answer")},_onHookStop(e){e.sessionId&&this.clearPendingHooks(e.sessionId),this._notifySession(e.sessionId,"info","hook-stop","Response Complete",e.reason||"Claude has finished responding")},_onHookTeammateIdle(e){const t=this.sessions.get(e.sessionId);this._notifySession(e.sessionId,"warning","hook-teammate-idle","Teammate Idle",`A teammate is idle in ${t?.name||e.sessionId}`)},_onHookTaskCompleted(e){const t=this.sessions.get(e.sessionId);this._notifySession(e.sessionId,"info","hook-task-completed","Task Completed",`A team task completed in ${t?.name||e.sessionId}`)},_onTunnelStarted(e){console.log("[Tunnel] Started:",e.url),this._tunnelUrl=e.url,this._dismissTunnelConnecting(),this._updateTunnelUrlDisplay(e.url),this._updateTunnelIndicator(!0),document.getElementById("welcomeOverlay")?.classList.contains("visible")?(this._updateWelcomeTunnelBtn(!0,e.url,!0),this.showToast("Tunnel active","success")):(this._updateWelcomeTunnelBtn(!0,e.url),this.showToast(`Tunnel active: ${e.url}`,"success"),this.showTunnelQR())},_onTunnelStopped(){console.log("[Tunnel] Stopped"),this._tunnelUrl=null,this._dismissTunnelConnecting(),this._updateTunnelUrlDisplay(null),this._updateWelcomeTunnelBtn(!1),this._updateTunnelIndicator(!1),this.closeTunnelPanel(),this.closeTunnelQR()},_onTunnelProgress(e){console.log("[Tunnel] Progress:",e.message);const t=document.getElementById("tunnelConnectingToast");t&&(t.innerHTML=`<span class="tunnel-spinner"></span> ${e.message}`);const n=document.getElementById("welcomeTunnelBtn");n?.classList.contains("connecting")&&(n.innerHTML=`<span class="tunnel-spinner"></span> ${e.message}`)},_onTunnelError(e){console.warn("[Tunnel] Error:",e.message),this._dismissTunnelConnecting(),this.showToast(`Tunnel error: ${e.message}`,"error");const t=document.getElementById("welcomeTunnelBtn");t&&(t.disabled=!1,t.classList.remove("connecting"))},_onTunnelQrRotated(e){if(e.svg){const t=document.getElementById("tunnelQrContainer");t&&(t.innerHTML=e.svg);const n=document.getElementById("welcomeQrInner");n&&(n.innerHTML=e.svg)}else this._refreshTunnelQrFromApi();this._resetQrCountdown()},_onTunnelQrRegenerated(e){if(e.svg){const t=document.getElementById("tunnelQrContainer");t&&(t.innerHTML=e.svg);const n=document.getElementById("welcomeQrInner");n&&(n.innerHTML=e.svg)}else this._refreshTunnelQrFromApi();this._resetQrCountdown()},_onTunnelQrAuthUsed(e){const n=(e.ua||"Unknown device").match(/Chrome|Firefox|Safari|Edge|Mobile/)?.[0]||"Browser";this.showToast(`Device authenticated via QR (${n}, ${e.ip}). Not you?`,"warning",{duration:1e4,action:{label:"Revoke All",onClick:()=>{fetch("/api/auth/revoke",{method:"POST",headers:{"Content-Type":"application/json"},body:"{}"}).then(()=>this.showToast("All sessions revoked","success")).catch(()=>this.showToast("Failed to revoke sessions","error"))}}})},registerServiceWorker(){"serviceWorker"in navigator&&navigator.serviceWorker.register("/sw.js").then(e=>{this._swRegistration=e,navigator.serviceWorker.addEventListener("message",t=>{if(t.data?.type==="notification-click"){const{sessionId:n}=t.data;n&&this.sessions.has(n)&&this.selectSession(n),window.focus()}}),e.pushManager.getSubscription().then(t=>{t&&(this._pushSubscription=t,this._updatePushUI(!0))})}).catch(()=>{})},async subscribeToPush(){if(!this._swRegistration){this.showToast("Service worker not available. HTTPS or localhost required.","error");return}try{const e=await this._apiJson("/api/push/vapid-key");if(!e)throw new Error("Failed to get VAPID key");const t=urlBase64ToUint8Array(e.publicKey),n=await this._swRegistration.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:t}),s=n.toJSON(),o=await this._apiJson("/api/push/subscribe",{method:"POST",body:{endpoint:s.endpoint,keys:s.keys,userAgent:navigator.userAgent,pushPreferences:this._buildPushPreferences()}});if(!o)throw new Error("Failed to register subscription");this._pushSubscription=n,this._pushSubscriptionId=o.id,localStorage.setItem("codeman-push-subscription-id",o.id),this._updatePushUI(!0),this.showToast("Push notifications enabled","success")}catch(e){this.showToast("Push subscription failed: "+(e.message||e),"error")}},async unsubscribeFromPush(){try{this._pushSubscription&&await this._pushSubscription.unsubscribe();const e=this._pushSubscriptionId||localStorage.getItem("codeman-push-subscription-id");e&&await fetch(`/api/push/subscribe/${e}`,{method:"DELETE"}).catch(()=>{}),this._pushSubscription=null,this._pushSubscriptionId=null,localStorage.removeItem("codeman-push-subscription-id"),this._updatePushUI(!1),this.showToast("Push notifications disabled","success")}catch(e){this.showToast("Failed to unsubscribe: "+(e.message||e),"error")}},async togglePushSubscription(){this._pushSubscription?await this.unsubscribeFromPush():await this.subscribeToPush()},async _syncPushPreferences(){const e=this._pushSubscriptionId||localStorage.getItem("codeman-push-subscription-id");if(e)try{await fetch(`/api/push/subscribe/${e}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({pushPreferences:this._buildPushPreferences()})})}catch{}},_buildPushPreferences(){const e={},t={"hook:permission_prompt":"eventPermissionPush","hook:elicitation_dialog":"eventQuestionPush","hook:idle_prompt":"eventIdlePush","hook:stop":"eventStopPush","respawn:blocked":"eventRespawnPush","session:ralphCompletionDetected":"eventRalphPush"};for(const[n,s]of Object.entries(t)){const o=document.getElementById(s);e[n]=o?o.checked:!0}return e["session:error"]=!0,e},_updatePushUI(e){const t=document.getElementById("pushSubscribeBtn"),n=document.getElementById("pushSubscriptionStatus");t&&(t.textContent=e?"Unsubscribe":"Subscribe"),n&&(n.textContent=e?"active":"off",n.classList.remove("granted","denied"),e&&n.classList.add("granted"))},openAppSettings(){const e=this.loadAppSettingsFromStorage();document.getElementById("appSettingsClaudeMdPath").value=e.defaultClaudeMdPath||"",document.getElementById("appSettingsDefaultDir").value=e.defaultWorkingDir||"";const t=this.getDefaultSettings();document.getElementById("appSettingsRalphEnabled").checked=e.ralphTrackerEnabled??t.ralphTrackerEnabled??!1,document.getElementById("appSettingsShowFontControls").checked=e.showFontControls??t.showFontControls??!1,document.getElementById("appSettingsShowSystemStats").checked=e.showSystemStats??t.showSystemStats??!0,document.getElementById("appSettingsShowLifecycleLog").checked=e.showLifecycleLog??t.showLifecycleLog??!0,document.getElementById("appSettingsShowResponseViewer").checked=e.showResponseViewer??t.showResponseViewer??!1,document.getElementById("appSettingsShowAttachmentsButton").checked=e.showAttachmentsButton??t.showAttachmentsButton??!1,document.getElementById("appSettingsSkin").value=e.skin??t.skin??"daylight-blue",document.getElementById("appSettingsWebglRenderer").checked=e.webglRendererEnabled??t.webglRendererEnabled??!0;const n=document.getElementById("appSettingsWebglRendererItem");n&&(n.style.display=MobileDetection.getDeviceType()==="desktop"?"":"none"),document.getElementById("appSettingsShowMonitor").checked=e.showMonitor??t.showMonitor??!1,document.getElementById("appSettingsShowProjectInsights").checked=e.showProjectInsights??t.showProjectInsights??!1,document.getElementById("appSettingsShowFileBrowser").checked=e.showFileBrowser??t.showFileBrowser??!1,document.getElementById("appSettingsShowSubagents").checked=e.showSubagents??t.showSubagents??!1,document.getElementById("appSettingsShowUltracodeAgents").checked=e.showUltracodeAgents??t.showUltracodeAgents??!1,document.getElementById("appSettingsUltracodeFloatingWindows").checked=e.ultracodeFloatingWindows??t.ultracodeFloatingWindows??!1,document.getElementById("appSettingsShowMultiMonitorButton").checked=e.showMultiMonitorButton??t.showMultiMonitorButton??!1,document.getElementById("appSettingsShowPlanUsageLimits").checked=e.showPlanUsageLimits??t.showPlanUsageLimits??!1,document.getElementById("appSettingsShowRedrawButton").checked=e.showRedrawButton??t.showRedrawButton??!1;const s=document.getElementById("appSettingsGestureControlItem");s&&(s.style.display=window.__codemanGestureAvailable?"":"none"),document.getElementById("appSettingsGestureControl").checked=e.gestureControlEnabled??t.gestureControlEnabled??!1,document.getElementById("appSettingsSubagentTracking").checked=e.subagentTrackingEnabled??t.subagentTrackingEnabled??!0,document.getElementById("appSettingsSubagentActiveTabOnly").checked=e.subagentActiveTabOnly??t.subagentActiveTabOnly??!0,document.getElementById("appSettingsImageWatcherEnabled").checked=e.imageWatcherEnabled??t.imageWatcherEnabled??!1,document.getElementById("appSettingsTunnelEnabled").checked=e.tunnelEnabled??!1,this.loadTunnelStatus(),document.getElementById("appSettingsLocalEcho").checked=e.localEchoEnabled??MobileDetection.isTouchDevice(),document.getElementById("appSettingsCjkInput").checked=e.cjkInputEnabled??t.cjkInputEnabled??!1,document.getElementById("appSettingsExtendedKeyboardBar").checked=e.extendedKeyboardBar??!1,document.getElementById("appSettingsTabTwoRows").checked=e.tabTwoRows??t.tabTwoRows??!1;const o=document.getElementById("appSettingsClaudeMode"),a=document.getElementById("allowedToolsRow");o.value=e.claudeMode||"dangerously-skip-permissions",document.getElementById("appSettingsAllowedTools").value=e.allowedTools||"",a.style.display=o.value==="allowedTools"?"":"none",o.onchange=()=>{a.style.display=o.value==="allowedTools"?"":"none"},document.getElementById("appSettingsCodexDangerouslyBypassApprovals").checked=e.codexDangerouslyBypassApprovals??!1,document.getElementById("appSettingsAgentTeams").checked=e.agentTeamsEnabled??!1,document.getElementById("appSettingsClaudeModel").value=e.claudeModel??"",document.getElementById("appSettingsOpusContext1m").checked=e.opusContext1mEnabled??!1,document.getElementById("appSettingsThinkingEffort").value=e.thinkingEffort??"";const i=e.nice||{};document.getElementById("appSettingsNiceEnabled").checked=i.enabled??!1,document.getElementById("appSettingsNiceValue").value=i.niceValue??10,this.loadModelConfigForSettings();const l=this.notificationManager?.preferences||{};document.getElementById("appSettingsNotifEnabled").checked=l.enabled??!0,document.getElementById("appSettingsNotifBrowser").checked=l.browserNotifications??!1,document.getElementById("appSettingsNotifAudio").checked=l.audioAlerts??!1,document.getElementById("appSettingsNotifStuckMins").value=Math.round((l.stuckThresholdMs||6e5)/6e4),document.getElementById("appSettingsNotifCritical").checked=!l.muteCritical,document.getElementById("appSettingsNotifWarning").checked=!l.muteWarning,document.getElementById("appSettingsNotifInfo").checked=!l.muteInfo,document.getElementById("appSettingsPushEnabled").checked=!!this._pushSubscription,this._updatePushUI(!!this._pushSubscription);const r=l.eventTypes||{},d=r.permission_prompt||{};document.getElementById("eventPermissionEnabled").checked=d.enabled??!0,document.getElementById("eventPermissionBrowser").checked=d.browser??!0,document.getElementById("eventPermissionPush").checked=d.push??!1,document.getElementById("eventPermissionAudio").checked=d.audio??!0;const c=r.elicitation_dialog||{};document.getElementById("eventQuestionEnabled").checked=c.enabled??!0,document.getElementById("eventQuestionBrowser").checked=c.browser??!0,document.getElementById("eventQuestionPush").checked=c.push??!1,document.getElementById("eventQuestionAudio").checked=c.audio??!0;const u=r.idle_prompt||{};document.getElementById("eventIdleEnabled").checked=u.enabled??!0,document.getElementById("eventIdleBrowser").checked=u.browser??!0,document.getElementById("eventIdlePush").checked=u.push??!1,document.getElementById("eventIdleAudio").checked=u.audio??!1;const h=r.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 p=r.respawn_cycle||{};document.getElementById("eventRespawnEnabled").checked=p.enabled??!0,document.getElementById("eventRespawnBrowser").checked=p.browser??!1,document.getElementById("eventRespawnPush").checked=p.push??!1,document.getElementById("eventRespawnAudio").checked=p.audio??!1;const g=r.ralph_complete||{};document.getElementById("eventRalphEnabled").checked=g.enabled??!0,document.getElementById("eventRalphBrowser").checked=g.browser??!0,document.getElementById("eventRalphPush").checked=g.push??!1,document.getElementById("eventRalphAudio").checked=g.audio??!0;const f=r.subagent_spawn||{};document.getElementById("eventSubagentEnabled").checked=f.enabled??!1,document.getElementById("eventSubagentBrowser").checked=f.browser??!1,document.getElementById("eventSubagentPush").checked=f.push??!1,document.getElementById("eventSubagentAudio").checked=f.audio??!1;const y=document.getElementById("notifPermissionStatus");if(y&&typeof Notification<"u"){const m=Notification.permission;y.textContent=m==="granted"?"\u2713":m==="denied"?"\u2717":"?",y.classList.remove("granted","denied"),m==="granted"?y.classList.add("granted"):m==="denied"&&y.classList.add("denied")}const w=VoiceInput._getDeepgramConfig();document.getElementById("voiceDeepgramKey").value=w.apiKey||"",document.getElementById("voiceLanguage").value=w.language||"en-US",document.getElementById("voiceKeyterms").value=w.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=w.insertMode||"direct";const v=document.getElementById("voiceDeepgramKey");v.type="password",document.getElementById("voiceKeyToggleBtn").textContent="Show";const E=VoiceInput.getActiveProviderName(),b=document.getElementById("voiceProviderStatus");b.textContent=E,b.className="voice-provider-status"+(E.startsWith("Deepgram")?" active":""),this._initUpdatesSection(),this.switchSettingsTab("settings-display");const S=document.getElementById("appSettingsModal");S.querySelectorAll(".modal-tabs .modal-tab-btn").forEach(m=>{m.onclick=()=>this.switchSettingsTab(m.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(n=>{n.classList.toggle("active",n.dataset.tab===e)}),t.querySelectorAll(".modal-tab-content").forEach(n=>{n.classList.toggle("hidden",n.id!==e)}),e==="settings-shortcuts"&&this.renderShortcutSettingsList?.()},closeAppSettings(){document.getElementById("appSettingsModal").classList.remove("active"),this.activeFocusTrap&&(this.activeFocusTrap.deactivate(),this.activeFocusTrap=null)},_updatePhaseText(e){return{queued:"Queued\u2026",preparing:"Preparing\u2026",stashing:"Stashing local changes\u2026",fetching:"Fetching release\u2026",checkout:"Checking out release\u2026",installing:"Installing dependencies\u2026",building:"Building\u2026",restarting:"Restarting Codeman\u2026"}[e]||e},_initUpdatesSection(){const e=this.$("updateCurrentVersion");e&&(e.textContent=(this.$("versionDisplay")?.textContent||"").trim()||"\u2014");for(const t of["updateResult","updateActionRow","updateNotes","updateProgress"]){const n=this.$(t);n&&(n.style.display="none")}this._updateCheck=null},_setUpdateResult(e){const t=this.$("updateResult");t&&(t.style.display="block",t.innerHTML=e)},_setUpdateProgress(e){const t=this.$("updateProgress");t&&(t.style.display="block",t.innerHTML=e)},async checkForUpdate(){const e=this.$("updateCheckBtn");e&&(e.disabled=!0,e.textContent="Checking\u2026");const t=await this._apiJson("/api/system/update/check");e&&(e.disabled=!1,e.textContent="Check now");const n=this.$("updateActionRow"),s=this.$("updateNotes");if(n&&(n.style.display="none"),s&&(s.style.display="none"),!t){this._setUpdateResult("Could not check for updates. Try again later.");return}this._updateCheck=t;const o=this.$("updateCurrentVersion");if(o&&t.currentVersion&&(o.textContent=`v${t.currentVersion}`),t.installKind&&t.installKind!=="git"){this._setUpdateResult(`This install can't update itself (${escapeHtml(t.installKind)}). Update with <code>npm i -g aicodeman@latest</code>.`);return}if(t.selfUpdateEnabled===!1){this._setUpdateResult("In-app updates are disabled on this server (CODEMAN_DISABLE_SELF_UPDATE=1).");return}if(t.error&&!t.updateAvailable){this._setUpdateResult(escapeHtml(t.error));return}if(t.updateAvailable&&t.latestVersion){this._setUpdateResult(`Update available: <strong>v${escapeHtml(t.latestVersion)}</strong> (current v${escapeHtml(t.currentVersion||"")})`);const a=this.$("updateActionLabel");a&&(a.textContent=`Update to v${t.latestVersion}`),n&&(n.style.display="flex");const i=this.$("updateNowBtn");i&&(i.disabled=!1,i.textContent="Update now"),s&&t.notes&&(s.style.display="block",s.textContent=t.notes)}else this._setUpdateResult(`You're up to date (v${escapeHtml(t.currentVersion||"")}).`)},async startSelfUpdate(){const e=this._updateCheck?.latestVersion?`v${this._updateCheck.latestVersion}`:"the latest release";if(!confirm(`Update Codeman to ${e}? The server will restart and this page will reload.`))return;const t=this.$("updateNowBtn");t&&(t.disabled=!0,t.textContent="Starting\u2026");const n=await this._apiPost("/api/system/update",{});if(!n||!n.ok){let a="Failed to start the update.";try{const i=await n.json();typeof i?.error=="string"&&i.error&&(a=i.error)}catch{}this._setUpdateProgress(`<span style="color:var(--danger,#e5534b)">${escapeHtml(a)}</span>`),t&&(t.disabled=!1,t.textContent="Update now");return}const s=this.$("updateActionRow");s&&(s.style.display="none");const o=this.$("updateNotes");o&&(o.style.display="none"),this._setUpdateProgress("Starting update\u2026"),this._pollUpdateStatus()},_stopUpdatePolling(){this._updatePollTimer&&(clearInterval(this._updatePollTimer),this._updatePollTimer=null)},_pollUpdateStatus(){this._stopUpdatePolling();const e=new Set(["completed","completed-needs-manual-restart","failed","idle"]),t=async()=>{let n=null;try{const s=await fetch("/api/system/update/status");if(s.ok){const o=await s.json();n=o&&o.success===!0?o.data:o}}catch{}if(!n){this._setUpdateProgress("\u21BB Restarting Codeman\u2026");return}if(!e.has(n.phase)){const s=n.message&&n.message.trim()?n.message.trim():this._updatePhaseText(n.phase);let o="";n.startedAt&&(o=` <span style="color:var(--text-secondary)">\xB7 ${Math.max(0,Math.round((Date.now()-n.startedAt)/1e3))}s</span>`),this._setUpdateProgress(`<span class="tunnel-spinner"></span> ${escapeHtml(s)}${o}`);return}if(this._stopUpdatePolling(),n.phase==="completed"){let s=`<span style="color:var(--success,#3fb950)">\u2713 Updated to v${escapeHtml(n.toVersion||"")}. Reloading\u2026</span>`;n.stashRef&&(s+=`<br><span style="color:var(--text-secondary)">Local changes stashed as <code>${escapeHtml(n.stashRef)}</code> \u2014 run <code>git stash pop</code> to restore.</span>`),this._setUpdateProgress(s),setTimeout(()=>location.reload(),2500)}else if(n.phase==="completed-needs-manual-restart")this._setUpdateProgress(`Update staged. Restart Codeman to apply:<br><code>${escapeHtml(n.manualRestartCommand||"restart codeman web")}</code>`);else if(n.phase==="failed"){let s=`<span style="color:var(--danger,#e5534b)">\u2717 ${escapeHtml(n.message||"Update failed")}.</span>`;n.error&&(s+=`<br><span style="color:var(--text-secondary)">${escapeHtml(n.error)}</span>`),s+='<br><span style="color:var(--text-secondary)">The previous version is still running.</span>',n.stashRef&&(s+=`<br><span style="color:var(--text-secondary)">Local changes stashed as <code>${escapeHtml(n.stashRef)}</code>.</span>`),this._setUpdateProgress(s);const o=this.$("updateNowBtn"),a=this.$("updateActionRow");o&&(o.disabled=!1,o.textContent="Try again"),a&&(a.style.display="flex")}};t(),this._updatePollTimer=setInterval(t,1500)},async loadTunnelStatus(){try{const t=await(await fetch("/api/tunnel/status")).json(),n=t?.success===!0?t.data:t,s=n.running&&n.url;this._tunnelUrl=s?n.url:null,this._updateTunnelUrlDisplay(this._tunnelUrl),this._updateWelcomeTunnelBtn(!!s,this._tunnelUrl),this._updateTunnelIndicator(!!s)}catch{this._tunnelUrl=null,this._updateTunnelUrlDisplay(null),this._updateWelcomeTunnelBtn(!1),this._updateTunnelIndicator(!1)}},_updateTunnelUrlRow(e,t,n,s=""){const o=document.getElementById(e),a=document.getElementById(t);if(!(!o||!a))if(n){const i=n+s;o.style.display="",a.textContent=i,a.onclick=()=>{navigator.clipboard.writeText(i).then(()=>{this.showToast(`${s?"Upload":"Tunnel"} URL copied`,"success")})}}else o.style.display="none",a.textContent="",a.onclick=null},_updateTunnelUrlDisplay(e){this._updateTunnelUrlRow("tunnelUrlRow","tunnelUrlDisplay",e),this._updateTunnelUrlRow("tunnelUploadUrlRow","tunnelUploadUrlDisplay",e,"/upload.html")},showTunnelQR(){this.closeTunnelQR();const e=document.createElement("div");e.id="tunnelQrOverlay",e.style.cssText="position:fixed;inset:0;background:rgba(0,0,0,0.7);z-index:5000;display:flex;align-items:center;justify-content:center;cursor:pointer",e.onclick=n=>{n.target===e&&this.closeTunnelQR()};const t=document.createElement("div");t.style.cssText="background:var(--bg-card);border:1px solid var(--border);border-radius:12px;padding:24px;text-align:center;max-width:340px;width:90vw;box-shadow:var(--shadow-lg);cursor:default",t.innerHTML=`
|
|
2
|
-
<div style="font-size:14px;font-weight:600;color:var(--text-primary);margin-bottom:16px">Scan to connect</div>
|
|
3
|
-
<div id="tunnelQrContainer" style="background:#fff;border-radius:8px;padding:16px;display:inline-block">
|
|
4
|
-
<div style="color:#666;font-size:12px">Loading...</div>
|
|
5
|
-
</div>
|
|
6
|
-
<div id="tunnelQrUrl" style="margin-top:12px;font-family:monospace;font-size:11px;color:var(--text-muted);word-break:break-all;cursor:pointer" title="Click to copy"></div>
|
|
7
|
-
<button onclick="app.closeTunnelQR()" style="margin-top:16px;padding:6px 20px;background:var(--bg-elevated);border:1px solid var(--border);border-radius:6px;color:var(--text-primary);cursor:pointer;font-size:13px">Close</button>
|
|
8
|
-
`,e.appendChild(t),document.body.appendChild(e),fetch("/api/tunnel/qr").then(n=>{if(!n.ok)throw new Error("Tunnel not running");return n.json()}).then(n=>{const s=n?.success===!0?n.data:n,o=document.getElementById("tunnelQrContainer");if(o&&s.svg&&(o.innerHTML=s.svg),s.authEnabled){const a=document.createElement("div");a.id="tunnelQrBadge",a.style.cssText="margin-top:8px;font-size:11px;color:var(--text-muted)",a.textContent="Single-use auth \xB7 expires in 60s";const i=document.createElement("button");i.textContent="Regenerate QR",i.style.cssText="margin-top:8px;padding:4px 12px;background:var(--bg-elevated);border:1px solid var(--border);border-radius:4px;color:var(--text-secondary);cursor:pointer;font-size:11px",i.onclick=()=>{fetch("/api/tunnel/qr/regenerate",{method:"POST"}).then(()=>this.showToast("QR code regenerated","success")).catch(()=>this.showToast("Failed to regenerate QR","error"))};const l=o.parentElement;l&&(l.appendChild(a),l.appendChild(i)),this._resetQrCountdown()}}).catch(()=>{const n=document.getElementById("tunnelQrContainer");n&&(n.innerHTML='<div style="color:#c00;font-size:12px;padding:20px">Tunnel not active</div>')}),fetch("/api/tunnel/status").then(n=>n.json()).then(n=>{const s=n?.success===!0?n.data:n,o=document.getElementById("tunnelQrUrl");o&&s.url&&(o.textContent=s.url,o.onclick=()=>{navigator.clipboard.writeText(s.url).then(()=>{this.showToast("Tunnel URL copied","success")})})}).catch(()=>{}),this._tunnelQrEscHandler=n=>{n.key==="Escape"&&this.closeTunnelQR()},document.addEventListener("keydown",this._tunnelQrEscHandler)},closeTunnelQR(){const e=document.getElementById("tunnelQrOverlay");e&&e.remove(),this._tunnelQrEscHandler&&(document.removeEventListener("keydown",this._tunnelQrEscHandler),this._tunnelQrEscHandler=null),this._clearQrCountdown()},_refreshTunnelQrFromApi(){fetch("/api/tunnel/qr").then(e=>e.ok?e.json():null).then(e=>{const t=e?.success===!0?e.data:e;if(!t?.svg)return;const n=document.getElementById("tunnelQrContainer");n&&(n.innerHTML=t.svg);const s=document.getElementById("welcomeQrInner");s&&(s.innerHTML=t.svg)}).catch(()=>{})},_resetQrCountdown(){this._clearQrCountdown(),this._qrCountdownSec=60,this._updateQrCountdownText(),this._qrCountdownTimer=setInterval(()=>{if(this._qrCountdownSec--,this._qrCountdownSec<=0){this._clearQrCountdown();return}this._updateQrCountdownText()},1e3)},_updateQrCountdownText(){const e=document.getElementById("tunnelQrBadge");e&&(e.textContent=`Single-use auth \xB7 expires in ${this._qrCountdownSec}s`)},_clearQrCountdown(){this._qrCountdownTimer&&(clearInterval(this._qrCountdownTimer),this._qrCountdownTimer=null)},async toggleTunnelFromWelcome(){const e=document.getElementById("welcomeTunnelBtn");if(!e)return;const t=e.classList.contains("active");e.disabled=!0;try{const n=!t,s=await fetch("/api/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({tunnelEnabled:n})});if(n&&await this._handleTunnelEnableRefusal(s)){this._dismissTunnelConnecting(),this._updateWelcomeTunnelBtn(!1),e.disabled=!1;return}n?(this._showTunnelConnecting(),this._pollTunnelStatus()):(this._dismissTunnelConnecting(),this.showToast("Tunnel stopped","info"),this._updateWelcomeTunnelBtn(!1),e.disabled=!1)}catch{this._dismissTunnelConnecting(),this.showToast("Failed to toggle tunnel","error"),e.disabled=!1}},_showTunnelConnecting(){const e=document.getElementById("tunnelConnectingToast");e&&e.remove();const t=document.getElementById("welcomeTunnelBtn");t&&(t.classList.add("connecting"),t.innerHTML=`
|
|
9
|
-
<span class="tunnel-spinner"></span>
|
|
10
|
-
Connecting...`);const n=document.createElement("div");n.className="toast toast-info show",n.id="tunnelConnectingToast",n.innerHTML='<span class="tunnel-spinner"></span> Cloudflare Tunnel connecting...',n.style.pointerEvents="auto",this._toastContainer||(this._toastContainer=document.querySelector(".toast-container"),this._toastContainer||(this._toastContainer=document.createElement("div"),this._toastContainer.className="toast-container",document.body.appendChild(this._toastContainer))),this._toastContainer.appendChild(n)},_dismissTunnelConnecting(){clearTimeout(this._tunnelPollTimer),this._tunnelPollTimer=null;const e=document.getElementById("tunnelConnectingToast");e&&(e.classList.remove("show"),setTimeout(()=>e.remove(),200));const t=document.getElementById("welcomeTunnelBtn");t&&t.classList.remove("connecting")},_pollTunnelStatus(e=0){e>15||(this._tunnelPollTimer=setTimeout(async()=>{try{const n=await(await fetch("/api/tunnel/status")).json(),s=n?.success===!0?n.data:n;if(s.running&&s.url){this._dismissTunnelConnecting(),this._updateTunnelUrlDisplay(s.url),document.getElementById("welcomeOverlay")?.classList.contains("visible")?(this._updateWelcomeTunnelBtn(!0,s.url,!0),this.showToast("Tunnel active","success")):(this._updateWelcomeTunnelBtn(!0,s.url),this.showToast(`Tunnel active: ${s.url}`,"success"),this.showTunnelQR());return}}catch{}this._pollTunnelStatus(e+1)},2e3))},_updateWelcomeTunnelBtn(e,t,n=!1){const s=document.getElementById("welcomeTunnelBtn");s&&(s.disabled=!1,e?(s.classList.remove("connecting"),s.classList.add("active"),s.innerHTML=`
|
|
11
|
-
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 2L2 7l10 5 10-5-10-5z"/><path d="M2 17l10 5 10-5"/><path d="M2 12l10 5 10-5"/></svg>
|
|
12
|
-
Tunnel Active`):(s.classList.remove("active","connecting"),s.innerHTML=`
|
|
13
|
-
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 2L2 7l10 5 10-5-10-5z"/><path d="M2 17l10 5 10-5"/><path d="M2 12l10 5 10-5"/></svg>
|
|
14
|
-
Cloudflare Tunnel`));const o=document.getElementById("welcomeQr"),a=document.getElementById("welcomeQrInner"),i=document.getElementById("welcomeQrUrl");!o||!a||(e?(o.classList.add("visible"),n&&(o.classList.add("expanded"),clearTimeout(this._welcomeQrShrinkTimer),this._welcomeQrShrinkTimer=setTimeout(()=>{o.classList.remove("expanded")},8e3)),t&&(i.textContent=t,i.title="Click QR to enlarge"),fetch("/api/tunnel/qr").then(l=>{if(!l.ok)throw new Error;return l.json()}).then(l=>{const r=l?.success===!0?l.data:l;r.svg&&(a.innerHTML=r.svg)}).catch(()=>{a.innerHTML='<div style="color:#999;font-size:11px;padding:20px">QR unavailable</div>'})):(clearTimeout(this._welcomeQrShrinkTimer),o.classList.remove("visible","expanded"),a.innerHTML="",i&&(i.textContent="")))},toggleWelcomeQrSize(){const e=document.getElementById("welcomeQr");e&&(clearTimeout(this._welcomeQrShrinkTimer),e.classList.toggle("expanded"))},_updateTunnelIndicator(e){if(MobileDetection.getDeviceType()==="mobile")return;const t=document.getElementById("tunnelIndicator");t&&(t.style.display=e?"flex":"none",t.classList.remove("connecting"))},toggleTunnelPanel(){if(document.getElementById("tunnelPanel")){this.closeTunnelPanel();return}this._openTunnelPanel()},async _openTunnelPanel(){const e=document.createElement("div");e.className="tunnel-panel",e.id="tunnelPanel",e.innerHTML=`
|
|
15
|
-
<div class="tunnel-panel-header">
|
|
16
|
-
<h3>
|
|
17
|
-
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 2L2 7l10 5 10-5-10-5z"/><path d="M2 17l10 5 10-5"/><path d="M2 12l10 5 10-5"/></svg>
|
|
18
|
-
Cloudflare Tunnel
|
|
19
|
-
<span class="tunnel-panel-status" id="tunnelPanelStatus">Loading...</span>
|
|
20
|
-
</h3>
|
|
21
|
-
</div>
|
|
22
|
-
<div class="tunnel-panel-body" id="tunnelPanelBody">
|
|
23
|
-
<div style="font-size:12px;color:var(--text-muted);padding:8px 0">Loading...</div>
|
|
24
|
-
</div>
|
|
25
|
-
`,document.body.appendChild(e),this._tunnelPanelClickHandler=t=>{!e.contains(t.target)&&t.target.id!=="tunnelIndicator"&&!t.target.closest(".tunnel-indicator")&&this.closeTunnelPanel()},setTimeout(()=>document.addEventListener("click",this._tunnelPanelClickHandler),0),this._tunnelPanelEscHandler=t=>{t.key==="Escape"&&this.closeTunnelPanel()},document.addEventListener("keydown",this._tunnelPanelEscHandler);try{const n=await(await fetch("/api/tunnel/info")).json(),s=n?.success===!0?n.data:n;this._renderTunnelPanel(s)}catch{const t=document.getElementById("tunnelPanelBody");t&&(t.innerHTML='<div style="font-size:12px;color:var(--red);padding:8px 0">Failed to load tunnel info</div>')}},_renderTunnelPanel(e){const t=document.getElementById("tunnelPanelStatus"),n=document.getElementById("tunnelPanelBody");if(!t||!n)return;t.textContent=e.running?"Connected":"Offline",t.className="tunnel-panel-status"+(e.running?"":" offline");let s="";if(e.url&&(s+=`
|
|
26
|
-
<div class="tunnel-panel-section">
|
|
27
|
-
<div class="tunnel-panel-label">URL</div>
|
|
28
|
-
<div class="tunnel-panel-url" id="tunnelPanelUrl" title="Click to copy">${escapeHtml(e.url)}</div>
|
|
29
|
-
</div>`),s+=`
|
|
30
|
-
<div class="tunnel-panel-section">
|
|
31
|
-
<div class="tunnel-panel-label">Connections</div>
|
|
32
|
-
<div class="tunnel-panel-stat">
|
|
33
|
-
<span>Remote Clients</span>
|
|
34
|
-
<span class="tunnel-panel-stat-value">${e.sseClients}</span>
|
|
35
|
-
</div>`,e.authEnabled&&(s+=`
|
|
36
|
-
<div class="tunnel-panel-stat">
|
|
37
|
-
<span>Auth Sessions</span>
|
|
38
|
-
<span class="tunnel-panel-stat-value">${e.authSessions.length}</span>
|
|
39
|
-
</div>`),s+="</div>",e.authEnabled&&e.authSessions.length>0){s+='<div class="tunnel-panel-section"><div class="tunnel-panel-label">Authenticated Devices</div>';for(const a of e.authSessions){const i=a.ua||"Unknown",l=i.match(/Chrome|Firefox|Safari|Edge|Mobile/)?.[0]||"Browser",r=this._formatTimeAgo(a.createdAt);s+=`
|
|
40
|
-
<div class="tunnel-panel-session">
|
|
41
|
-
<span class="tunnel-panel-session-dot"></span>
|
|
42
|
-
<span class="tunnel-panel-session-info" title="${escapeHtml(i)}">${escapeHtml(l)} · ${escapeHtml(a.ip)} · ${r}</span>
|
|
43
|
-
<span class="tunnel-panel-session-method">${a.method}</span>
|
|
44
|
-
</div>`}s+="</div>"}s+='<div class="tunnel-panel-actions">',e.running?s+=`
|
|
45
|
-
<button class="tunnel-panel-btn btn-qr" onclick="app.showTunnelQR();app.closeTunnelPanel()">QR Code</button>
|
|
46
|
-
<button class="tunnel-panel-btn btn-stop" onclick="app._tunnelPanelToggle(false)">Stop Tunnel</button>`:s+='<button class="tunnel-panel-btn btn-start" onclick="app._tunnelPanelToggle(true)">Start Tunnel</button>',s+="</div>",e.authEnabled&&e.authSessions.length>0&&(s+=`
|
|
47
|
-
<div style="padding-top:8px">
|
|
48
|
-
<button class="tunnel-panel-btn btn-revoke" style="width:100%" onclick="app._tunnelPanelRevokeAll()">Revoke All Sessions</button>
|
|
49
|
-
</div>`),n.innerHTML=s;const o=document.getElementById("tunnelPanelUrl");o&&(o.onclick=()=>{navigator.clipboard.writeText(e.url).then(()=>this.showToast("Tunnel URL copied","success"))})},_formatTimeAgo(e){const t=Date.now()-e,n=Math.floor(t/6e4);if(n<1)return"just now";if(n<60)return`${n}m ago`;const s=Math.floor(n/60);return s<24?`${s}h ago`:`${Math.floor(s/24)}d ago`},async _handleTunnelEnableRefusal(e){if(!e||e.ok)return!1;let t="Tunnel refused: set CODEMAN_PASSWORD before exposing Codeman publicly.";try{const n=await e.json();n&&n.error&&(t=n.error)}catch{}if(e.status===403){if(!confirm(`\u26A0\uFE0F SECURITY WARNING \u2014 no password set
|
|
50
|
-
|
|
51
|
-
Enabling the Cloudflare tunnel will publish THIS machine to a public URL with NO login. Anyone who gets the URL has full terminal control \u2014 effectively remote code execution on your computer.
|
|
52
|
-
|
|
53
|
-
Strongly recommended: set CODEMAN_PASSWORD instead.
|
|
54
|
-
|
|
55
|
-
Enable the unauthenticated public tunnel anyway?`))return this._dismissTunnelConnecting?.(),this.showToast("Tunnel not enabled","info"),!0;try{const s=await fetch("/api/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({tunnelEnabled:!0,acknowledgeUnauthTunnel:!0})});if(s.ok)return this.showToast("Public tunnel enabling \u2014 no password set \u26A0\uFE0F","warning"),!1;let o="Failed to enable tunnel.";try{const a=await s.json();a&&a.error&&(o=a.error)}catch{}return this._dismissTunnelConnecting?.(),this.showToast(o,"error"),!0}catch{return this._dismissTunnelConnecting?.(),this.showToast("Failed to enable tunnel","error"),!0}}return this._dismissTunnelConnecting?.(),this.showToast(t,"error"),!0},async _tunnelPanelToggle(e){try{const t=await fetch("/api/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({tunnelEnabled:e})});if(e&&await this._handleTunnelEnableRefusal(t)){this.closeTunnelPanel();return}if(e){this._updateTunnelIndicator(!1);const n=document.getElementById("tunnelIndicator");n&&(n.style.display="flex",n.classList.add("connecting")),this.showToast("Tunnel starting...","info"),this._showTunnelConnecting(),this._pollTunnelStatus()}else this.showToast("Tunnel stopped","info");this.closeTunnelPanel()}catch{this.showToast("Failed to toggle tunnel","error")}},async _tunnelPanelRevokeAll(){try{await fetch("/api/auth/revoke",{method:"POST",headers:{"Content-Type":"application/json"},body:"{}"}),this.showToast("All sessions revoked","success");const t=await(await fetch("/api/tunnel/info")).json(),n=t?.success===!0?t.data:t;this._renderTunnelPanel(n)}catch{this.showToast("Failed to revoke sessions","error")}},closeTunnelPanel(){const e=document.getElementById("tunnelPanel");e&&e.remove(),this._tunnelPanelClickHandler&&(document.removeEventListener("click",this._tunnelPanelClickHandler),this._tunnelPanelClickHandler=null),this._tunnelPanelEscHandler&&(document.removeEventListener("keydown",this._tunnelPanelEscHandler),this._tunnelPanelEscHandler=null)},toggleDeepgramKeyVisibility(){const e=document.getElementById("voiceDeepgramKey"),t=document.getElementById("voiceKeyToggleBtn");e.type==="password"?(e.type="text",t.textContent="Hide"):(e.type="password",t.textContent="Show")},openLifecycleLog(){const e=document.getElementById("lifecycleWindow");e.style.display="block",e._dragInitialized||(e.style.left="50%",e.style.transform="translateX(-50%)",this._initLifecycleDrag(e),e._dragInitialized=!0),this.loadLifecycleLog()},closeLifecycleLog(){document.getElementById("lifecycleWindow").style.display="none"},_initLifecycleDrag(e){const t=document.getElementById("lifecycleWindowHeader");let n=!1,s,o,a,i;t.addEventListener("mousedown",l=>{if(l.target.tagName==="SELECT"||l.target.tagName==="INPUT"||l.target.tagName==="BUTTON")return;n=!0;const r=e.getBoundingClientRect();e.style.transform="none",e.style.left=r.left+"px",e.style.top=r.top+"px",s=l.clientX,o=l.clientY,a=r.left,i=r.top,l.preventDefault()}),document.addEventListener("mousemove",l=>{n&&(e.style.left=a+l.clientX-s+"px",e.style.top=i+l.clientY-o+"px")}),document.addEventListener("mouseup",()=>{n=!1})},async loadLifecycleLog(){const e=document.getElementById("lifecycleFilterEvent").value,t=document.getElementById("lifecycleFilterSession").value.trim(),n=new URLSearchParams;e&&n.set("event",e),t&&n.set("sessionId",t),n.set("limit","300");try{const o=await(await fetch(`/api/session-lifecycle?${n}`)).json(),a=o?.success===!0?o.data:o,i=document.getElementById("lifecycleTableBody"),l=document.getElementById("lifecycleEmpty");if(!a.entries||a.entries.length===0){i.innerHTML="",l.style.display="";return}l.style.display="none";const r={created:"#4ade80",started:"#4ade80",recovered:"#4ade80",exit:"#fbbf24",mux_died:"#f87171",deleted:"#f87171",stale_cleaned:"#f87171",server_started:"#666",server_stopped:"#666"};i.innerHTML=a.entries.map(d=>{const c=new Date(d.ts).toLocaleString(),u=r[d.event]||"#888",h=d.name||(d.sessionId==="*"?"\u2014":this.getShortId(d.sessionId)),p=[];return d.exitCode!==void 0&&d.exitCode!==null&&p.push(`code=${d.exitCode}`),d.mode&&p.push(d.mode),`<tr style="border-bottom:1px solid #1a1a2e">
|
|
56
|
-
<td style="padding:3px 8px;color:#888;white-space:nowrap">${c}</td>
|
|
57
|
-
<td style="padding:3px 8px;color:${u};font-weight:600">${d.event}</td>
|
|
58
|
-
<td style="padding:3px 8px;color:#e0e0e0" title="${d.sessionId}">${h}</td>
|
|
59
|
-
<td style="padding:3px 8px;color:#aaa">${d.reason||""}</td>
|
|
60
|
-
<td style="padding:3px 8px;color:#666">${p.join(", ")}</td>
|
|
61
|
-
</tr>`}).join("")}catch(s){console.error("Failed to load lifecycle log:",s)}},async saveAppSettings(){const e=this.loadAppSettingsFromStorage(),t=(e.gestureControlEnabled??!1)===!0,n=(e.webglRendererEnabled??!0)===!0,s={defaultClaudeMdPath:document.getElementById("appSettingsClaudeMdPath").value.trim(),defaultWorkingDir:document.getElementById("appSettingsDefaultDir").value.trim(),ralphTrackerEnabled:document.getElementById("appSettingsRalphEnabled").checked,showFontControls:document.getElementById("appSettingsShowFontControls").checked,showSystemStats:document.getElementById("appSettingsShowSystemStats").checked,showLifecycleLog:document.getElementById("appSettingsShowLifecycleLog").checked,showResponseViewer:document.getElementById("appSettingsShowResponseViewer").checked,showAttachmentsButton:document.getElementById("appSettingsShowAttachmentsButton").checked,showMonitor:document.getElementById("appSettingsShowMonitor").checked,showProjectInsights:document.getElementById("appSettingsShowProjectInsights").checked,showFileBrowser:document.getElementById("appSettingsShowFileBrowser").checked,showSubagents:document.getElementById("appSettingsShowSubagents").checked,showUltracodeAgents:document.getElementById("appSettingsShowUltracodeAgents").checked,ultracodeFloatingWindows:document.getElementById("appSettingsUltracodeFloatingWindows").checked,showMultiMonitorButton:document.getElementById("appSettingsShowMultiMonitorButton").checked,showPlanUsageLimits:document.getElementById("appSettingsShowPlanUsageLimits").checked,showRedrawButton:document.getElementById("appSettingsShowRedrawButton").checked,gestureControlEnabled:document.getElementById("appSettingsGestureControl").checked,subagentTrackingEnabled:document.getElementById("appSettingsSubagentTracking").checked,subagentActiveTabOnly:document.getElementById("appSettingsSubagentActiveTabOnly").checked,imageWatcherEnabled:document.getElementById("appSettingsImageWatcherEnabled").checked,tunnelEnabled:document.getElementById("appSettingsTunnelEnabled").checked,localEchoEnabled:document.getElementById("appSettingsLocalEcho").checked,cjkInputEnabled:document.getElementById("appSettingsCjkInput").checked,webglRendererEnabled:document.getElementById("appSettingsWebglRenderer").checked,extendedKeyboardBar:document.getElementById("appSettingsExtendedKeyboardBar").checked,tabTwoRows:document.getElementById("appSettingsTabTwoRows").checked,skin:document.getElementById("appSettingsSkin").value,claudeMode:document.getElementById("appSettingsClaudeMode").value,allowedTools:document.getElementById("appSettingsAllowedTools").value.trim(),codexDangerouslyBypassApprovals:document.getElementById("appSettingsCodexDangerouslyBypassApprovals").checked,agentTeamsEnabled:document.getElementById("appSettingsAgentTeams").checked,claudeModel:document.getElementById("appSettingsClaudeModel").value,opusContext1mEnabled:document.getElementById("appSettingsOpusContext1m").checked,thinkingEffort:document.getElementById("appSettingsThinkingEffort").value,nice:{enabled:document.getElementById("appSettingsNiceEnabled").checked,niceValue:parseInt(document.getElementById("appSettingsNiceValue").value)||10}};if(e.showTokenCount!==void 0&&(s.showTokenCount=e.showTokenCount),e.showCost!==void 0&&(s.showCost=e.showCost),e.shortcutOverrides!==void 0&&(s.shortcutOverrides=e.shortcutOverrides),this.saveAppSettingsToStorage(s),this._updateLocalEchoState(),!n&&s.webglRendererEnabled)try{localStorage.removeItem("codeman-webgl-disabled")}catch{}const o={apiKey:document.getElementById("voiceDeepgramKey").value.trim(),language:document.getElementById("voiceLanguage").value,keyterms:document.getElementById("voiceKeyterms").value.trim(),insertMode:document.getElementById("voiceInsertMode").value};VoiceInput._saveDeepgramConfig(o);const a={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=a,this.notificationManager.savePreferences()),this._syncPushPreferences(),this.applyHeaderVisibilitySettings(),this.applySkin(),this.applyTabWrapSettings(),this._updateTokensImmediate(),this.applyMonitorVisibility(),this.renderProjectInsightsPanel(),this.updateSubagentWindowVisibility(),this._updateCjkInputState(),KeyboardAccessoryBar.setMode(s.extendedKeyboardBar?"extended":"simple");const{localEchoEnabled:i,cjkInputEnabled:l,extendedKeyboardBar:r,skin:d,showPlanUsageLimits:c,showAttachmentsButton:u,webglRendererEnabled:h,...p}=s;try{const g=await this._apiPut("/api/settings",{...p,...s.showPlanUsageLimits?{statusLineTelemetry:!0}:{},notificationPreferences:a,voiceSettings:o});if(s.tunnelEnabled&&await this._handleTunnelEnableRefusal(g)){s.tunnelEnabled=!1,this.saveAppSettingsToStorage(s);const f=document.getElementById("appSettingsTunnelEnabled");f&&(f.checked=!1),this.closeAppSettings();return}await this.saveModelConfigFromSettings(),this.showToast("Settings saved","success"),s.tunnelEnabled&&this.showToast("Tunnel starting \u2014 QR code will appear when ready...","info")}catch{this.showToast("Settings saved locally","warning")}this.closeAppSettings(),s.gestureControlEnabled!==t&&(this.showToast(s.gestureControlEnabled?"Enabling gesture control \u2014 reloading\u2026":"Disabling gesture control \u2014 reloading\u2026","info"),setTimeout(()=>location.reload(),400))},async loadModelConfigForSettings(){try{const t=await(await fetch("/api/execution/model-config")).json();if(t.success&&t.data){const n=t.data,s=document.getElementById("appSettingsDefaultModel");s&&(s.value=n.defaultModel||"");const o=document.getElementById("appSettingsShowModelRecommendations");o&&(o.checked=n.showRecommendations??!0);const a=n.agentTypeOverrides||{},i=document.getElementById("appSettingsModelExplore"),l=document.getElementById("appSettingsModelImplement"),r=document.getElementById("appSettingsModelTest"),d=document.getElementById("appSettingsModelReview");i&&(i.value=a.explore||""),l&&(l.value=a.implement||""),r&&(r.value=a.test||""),d&&(d.value=a.review||"")}}catch(e){console.warn("Failed to load model config:",e)}},async saveModelConfigFromSettings(){const e=document.getElementById("appSettingsDefaultModel"),t=document.getElementById("appSettingsShowModelRecommendations"),n=document.getElementById("appSettingsModelExplore"),s=document.getElementById("appSettingsModelImplement"),o=document.getElementById("appSettingsModelTest"),a=document.getElementById("appSettingsModelReview"),i={};n?.value&&(i.explore=n.value),s?.value&&(i.implement=s.value),o?.value&&(i.test=o.value),a?.value&&(i.review=a.value);const l={defaultModel:e?.value||"",showRecommendations:t?.checked??!0,agentTypeOverrides:i};try{await fetch("/api/execution/model-config",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)})}catch(r){console.warn("Failed to save model config:",r)}},isRalphTrackerEnabledByDefault(){return this.loadAppSettingsFromStorage().ralphTrackerEnabled??!1},getSettingsStorageKey(){return MobileDetection.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,showUltracodeAgents:!1,ultracodeFloatingWindows:!1,showMultiMonitorButton:!1,showPlanUsageLimits:!1,showAttachmentsButton:!1,showRedrawButton:!1,gestureControlEnabled:!1,subagentTrackingEnabled:!0,subagentActiveTabOnly:!0,imageWatcherEnabled:!1,ralphTrackerEnabled:!1,tabTwoRows:!1,cjkInputEnabled:!1,webglRendererEnabled:!1,skin:"daylight-blue"}:{}},loadAppSettingsFromStorage(){if(this._cachedAppSettings)return this._cachedAppSettings;try{const e=this.getSettingsStorageKey(),t=localStorage.getItem(e);if(t)return this._cachedAppSettings=JSON.parse(t),this._cachedAppSettings}catch(e){console.error("Failed to load app settings:",e)}return this._cachedAppSettings=this.getDefaultSettings(),this._cachedAppSettings},saveAppSettingsToStorage(e){this._cachedAppSettings=e;try{const t=this.getSettingsStorageKey();localStorage.setItem(t,JSON.stringify(e))}catch(t){console.error("Failed to save app settings:",t)}},applySkin(){const e=this.loadAppSettingsFromStorage(),t=this.getDefaultSettings(),n=e.skin??t.skin??"daylight-blue";document.documentElement.setAttribute("data-skin",n),window.__codemanSkin=n;try{localStorage.setItem("codeman:skin",n)}catch{}typeof this.applyTerminalSkin=="function"&&this.applyTerminalSkin(n)},applyHeaderVisibilitySettings(){const e=this.loadAppSettingsFromStorage(),t=this.getDefaultSettings(),n=MobileDetection.getDeviceType()!=="desktop",s=n?!1:e.showFontControls??t.showFontControls??!1,o=n?!1:e.showSystemStats??t.showSystemStats??!0,a=n?!1:e.showTokenCount??t.showTokenCount??!0,i=document.querySelector(".header-font-controls"),l=document.getElementById("headerSystemStats"),r=document.getElementById("headerTokens");i&&(i.style.display=s?"":"none"),l&&(l.style.display=o?"":"none"),r&&(r.style.display=a?"":"none");const d=e.showLifecycleLog??t.showLifecycleLog??!0,c=document.querySelector(".btn-lifecycle-log");c&&(c.style.display=d?"":"none");const u=e.showResponseViewer??t.showResponseViewer??!1,h=document.querySelector(".btn-response-viewer-header");h&&h.classList.toggle("btn-response-viewer-header--hidden",!u);const p=e.showAttachmentsButton??t.showAttachmentsButton??!1,g=document.getElementById("attachmentsHistoryBtn");g&&g.classList.toggle("btn-attachments-history--hidden",!p);const f=e.showMultiMonitorButton??t.showMultiMonitorButton??!1,y=document.querySelector(".btn-multimonitor");y&&y.classList.toggle("btn-multimonitor--hidden",!f);const w=e.showUltracodeAgents??t.showUltracodeAgents??!1,v=document.querySelector(".btn-ultracode-agents");v&&v.classList.toggle("btn-ultracode-agents--hidden",!w);const E=e.showPlanUsageLimits??t.showPlanUsageLimits??!1,b=document.getElementById("planUsageChip");b&&b.classList.toggle("header-plan-usage--hidden",!E);const S=e.showRedrawButton??t.showRedrawButton??!1,m=document.querySelector(".btn-redraw-terminal");m&&m.classList.toggle("btn-redraw-terminal--hidden",!S);const T=document.querySelector(".btn-notifications");if(T&&(T.style.display="none"),!(this.notificationManager?.preferences?.enabled??!0)){const I=document.getElementById("notifDrawer");I&&I.classList.remove("open")}},applyTabWrapSettings(){const e=this.loadAppSettingsFromStorage(),t=this.getDefaultSettings(),s=MobileDetection.getDeviceType()==="desktop"?e.tabTwoRows??t.tabTwoRows??!1:!1,o=this._tallTabsEnabled;this._tallTabsEnabled=s;const a=document.getElementById("sessionTabs");a&&(a.classList.toggle("tabs-two-rows",s),a.classList.toggle("tabs-show-folder",s)),o!==void 0&&o!==s&&this._fullRenderSessionTabs()},applyMonitorVisibility(){const e=this.loadAppSettingsFromStorage(),t=this.getDefaultSettings(),n=e.showMonitor??t.showMonitor??!1,s=e.showSubagents??t.showSubagents??!1,o=e.showFileBrowser??t.showFileBrowser??!1,a=document.getElementById("monitorPanel");a&&(a.style.display=n?"":"none",n?a.classList.add("open"):a.classList.remove("open"));const i=document.getElementById("subagentsPanel");i&&(s?i.classList.remove("hidden"):i.classList.add("hidden"));const l=e.showUltracodeAgents??t.showUltracodeAgents??!1,r=document.getElementById("ultracodeAgentsPanel");r&&(l?r.classList.remove("hidden"):(r.classList.remove("open"),r.classList.add("hidden"))),e.ultracodeFloatingWindows??t.ultracodeFloatingWindows??!1?typeof this.syncAllUltracodeFloatingWindows=="function"&&this.syncAllUltracodeFloatingWindows():typeof this.removeAllUltracodeWindows=="function"&&this.removeAllUltracodeWindows();const c=document.getElementById("fileBrowserPanel");if(c)if(o&&this.activeSessionId){if(c.classList.add("visible"),this.loadFileBrowser(this.activeSessionId),!this.fileBrowserDragListeners){const u=c.querySelector(".file-browser-header");if(u){const h=()=>{if(!c.style.left){const p=c.getBoundingClientRect();c.style.left=`${p.left}px`,c.style.top=`${p.top}px`,c.style.right="auto"}};u.addEventListener("mousedown",h),u.addEventListener("touchstart",h,{passive:!0}),this.fileBrowserDragListeners=this.makeWindowDraggable(c,u),this.fileBrowserDragListeners._onFirstDrag=h}}}else c.classList.remove("visible")},closeMonitor(){const e=document.getElementById("monitorPanel");e&&(e.classList.remove("open"),e.style.display="none");const t=this.loadAppSettingsFromStorage();t.showMonitor=!1,this.saveAppSettingsToStorage(t)},closeSubagentsPanel(){const e=document.getElementById("subagentsPanel");e&&(e.classList.remove("open"),e.classList.add("hidden")),this.subagentPanelVisible=!1;const t=this.loadAppSettingsFromStorage();t.showSubagents=!1,this.saveAppSettingsToStorage(t)},async clearAllSubagents(){const e=this.subagents.size;if(e===0){this.showToast("No subagents to clear","info");return}if(confirm(`Clear all ${e} tracked subagent(s)? This removes them from the UI but does not affect running processes.`))try{const n=await(await fetch("/api/subagents",{method:"DELETE"})).json();n.success?(this.subagents.clear(),this.subagentActivity.clear(),this.subagentToolResults.clear(),this.cleanupAllFloatingWindows(),this.renderSubagentPanel(),this.renderMonitorSubagents(),this.updateSubagentBadge(),this.showToast(`Cleared ${n.data.cleared} subagent(s)`,"success")):this.showToast("Failed to clear subagents: "+n.error,"error")}catch{this.showToast("Failed to clear subagents","error")}},toggleSubagentsPanel(){const e=document.getElementById("subagentsPanel"),t=document.getElementById("subagentsToggleBtn");if(e){if(e.classList.contains("hidden")){e.classList.remove("hidden");const n=this.loadAppSettingsFromStorage();n.showSubagents=!0,this.saveAppSettingsToStorage(n)}e.classList.toggle("open"),this.subagentPanelVisible=e.classList.contains("open"),t&&(t.innerHTML=this.subagentPanelVisible?"▼":"▲"),this.subagentPanelVisible&&this.renderSubagentPanel()}},async loadAppSettingsFromServer(e=null){try{if(MobileDetection.getDeviceType()==="mobile"&&!localStorage.getItem("codeman:planUsagePerDeviceMigrated")){const t=this.loadAppSettingsFromStorage();t&&t.showPlanUsageLimits&&(t.showPlanUsageLimits=!1,this.saveAppSettingsToStorage(t)),localStorage.setItem("codeman:planUsagePerDeviceMigrated","1")}}catch{}try{const t=e?await e:await fetch("/api/settings").then(n=>n.ok?n.json():null).then(n=>n?.success===!0?n.data:n);if(t){const{notificationPreferences:n,voiceSettings:s,respawnPresets:o,runMode:a,...i}=t,l=new Set(["showFontControls","showSystemStats","showTokenCount","showCost","showLifecycleLog","showResponseViewer","showRedrawButton","showMonitor","showProjectInsights","showFileBrowser","showSubagents","subagentActiveTabOnly","tabTwoRows","localEchoEnabled","cjkInputEnabled","extendedKeyboardBar","skin","showPlanUsageLimits","showAttachmentsButton","webglRendererEnabled"]);delete i.showPlanUsageLimits;const r=this.loadAppSettingsFromStorage(),d={...r};for(const[c,u]of Object.entries(i))l.has(c)&&c in r||(d[c]=u);if(this.saveAppSettingsToStorage(d),n&&this.notificationManager&&(localStorage.getItem(this.notificationManager.getStorageKey())||(this.notificationManager.preferences=n,this.notificationManager.savePreferences())),s){const c=localStorage.getItem("codeman-voice-settings");(!c||!JSON.parse(c).apiKey)&&VoiceInput._saveDeepgramConfig(s)}if(o&&Array.isArray(o))this._serverRespawnPresets=o,localStorage.setItem("codeman-respawn-presets",JSON.stringify(o));else{const c=localStorage.getItem("codeman-respawn-presets");if(c){const u=JSON.parse(c);u.length>0&&(this._serverRespawnPresets=u,this._apiPut("/api/settings",{respawnPresets:u}).catch(()=>{}))}}if(a){this.runMode=a;try{localStorage.setItem("codeman_runMode",a)}catch{}this._applyRunMode()}return d}}catch(t){console.error("Failed to load settings from server:",t)}return this.loadAppSettingsFromStorage()},async loadSubagentWindowStates(){let e=null;try{const t=await fetch("/api/subagent-window-states");if(t.ok){const n=await t.json();e=n?.success===!0?n.data:n,localStorage.setItem("codeman-subagent-window-states",JSON.stringify(e))}}catch(t){console.error("Failed to load subagent window states from server:",t)}if(!e)try{const t=localStorage.getItem("codeman-subagent-window-states");t&&(e=JSON.parse(t))}catch(t){console.error("Failed to load subagent window states from localStorage:",t)}return e||{minimized:{},open:[]}},async saveSubagentParentMap(){const e=Object.fromEntries(this.subagentParentMap);try{localStorage.setItem("codeman-subagent-parents",JSON.stringify(e))}catch(t){console.error("Failed to save subagent parents to localStorage:",t)}try{await fetch("/api/subagent-parents",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}catch(t){console.error("Failed to save subagent parents to server:",t)}},async loadSubagentParentMap(){let e=null;try{const t=await fetch("/api/subagent-parents");if(t.ok){const n=await t.json();e=n?.success===!0?n.data:n,localStorage.setItem("codeman-subagent-parents",JSON.stringify(e))}}catch(t){console.error("Failed to load subagent parents from server:",t)}if(!e)try{const t=localStorage.getItem("codeman-subagent-parents");t&&(e=JSON.parse(t))}catch(t){console.error("Failed to load subagent parents from localStorage:",t)}if(e&&typeof e=="object")for(const[t,n]of Object.entries(e))this.sessions.has(n)&&this.subagents.has(t)&&this.subagentParentMap.set(t,n)},getAgentParentSessionId(e){return this.subagentParentMap.get(e)||null},setAgentParentSessionId(e,t){if(!e||!t||this.subagentParentMap.has(e))return;this.subagentParentMap.set(e,t),this.saveSubagentParentMap();const n=this.subagents.get(e);if(n){n.parentSessionId=t;const s=this.sessions.get(t);s&&(n.parentSessionName=this.getSessionName(s)),this.subagents.set(e,n)}},showHelp(){const e=document.getElementById("helpModal");e.classList.add("active"),this.activeFocusTrap=new FocusTrap(e),this.activeFocusTrap.activate()},closeHelp(){document.getElementById("helpModal").classList.remove("active"),this.activeFocusTrap&&(this.activeFocusTrap.deactivate(),this.activeFocusTrap=null)},renderShortcutSettingsList(){const e=document.getElementById("appSettingsShortcutsList");if(!e)return;const t=this.getShortcutRegistry?this.getShortcutRegistry():typeof DEFAULT_SHORTCUTS<"u"?DEFAULT_SHORTCUTS:[],n=this.readShortcutOverridesFromSettings();e.innerHTML=t.map(s=>{const o=s.displayBindings?s.displayBindings.join(" / "):(s.bindings||[]).map(r=>[...r.modifiers||[],r.key||r.code||""].join("+")).join(" / "),a=!!s.action&&Array.isArray(s.bindings),i=!!n[s.id],l=a?`<button type="button" class="shortcut-capture-btn" data-shortcut-action="capture" title="Capture new binding">Edit</button>
|
|
62
|
-
<button type="button" class="shortcut-reset-btn" data-shortcut-action="reset" title="Reset to default"${i?"":" disabled"}>Reset</button>
|
|
63
|
-
<input class="shortcut-enabled-checkbox" type="checkbox" ${s.disabled?"":"checked"} data-shortcut-action="toggle" title="Enable/disable">`:"";return`<div class="shortcut-setting-row${a?"":" shortcut-setting-row--fixed"}" data-shortcut-id="${escapeHtml(s.id)}">
|
|
64
|
-
<label class="shortcut-setting-label">${escapeHtml(s.label)}</label>
|
|
65
|
-
<input class="shortcut-binding-input" type="text" readonly value="${escapeHtml(o)}" placeholder="(none)" data-id="${escapeHtml(s.id)}">
|
|
66
|
-
${l}
|
|
67
|
-
</div>`}).join(""),this._wireShortcutSettingsList(e)},_wireShortcutSettingsList(e){e.dataset.shortcutListenersAdded||(e.dataset.shortcutListenersAdded="true",e.addEventListener("click",t=>{const n=t.target?.closest?.("[data-shortcut-action]");if(!n)return;const s=n.closest?.("[data-shortcut-id]")?.dataset?.shortcutId;s&&(n.dataset.shortcutAction==="capture"?this.startShortcutCapture(s):n.dataset.shortcutAction==="reset"&&this.resetShortcutOverride(s))}),e.addEventListener("change",t=>{const n=t.target;if(!n?.matches?.('[data-shortcut-action="toggle"]'))return;const s=n.closest?.("[data-shortcut-id]")?.dataset?.shortcutId;s&&this.toggleShortcutEnabled(s,n.checked)}))},readShortcutOverridesFromSettings(){return this.loadAppSettingsFromStorage().shortcutOverrides||{}},startShortcutCapture(e){const t=document.querySelector(`.shortcut-binding-input[data-id="${e}"]`);if(!t)return;t.value="Press keys\u2026",t.focus(),this._capturingShortcutId=e;const n=s=>{s.preventDefault(),s.stopPropagation(),!(s.key==="Control"||s.key==="Shift"||s.key==="Alt"||s.key==="Meta")&&(t.removeEventListener("keydown",n),this.onShortcutCaptureKeydown(s,e))};t.addEventListener("keydown",n)},onShortcutCaptureKeydown(e,t){if(e.preventDefault(),e.stopPropagation(),this._capturingShortcutId=null,e.key==="Escape"){this.renderShortcutSettingsList();return}if(!e.ctrlKey&&!e.metaKey&&!e.altKey){this.renderShortcutSettingsList(),this.showToast?.("Shortcut must include Ctrl, Cmd, or Alt","error");return}const n=[];e.ctrlKey&&n.push("ctrl"),e.metaKey&&n.push("meta"),e.shiftKey&&n.push("shift"),e.altKey&&n.push("alt");const s=this.loadAppSettingsFromStorage(),o={...s.shortcutOverrides||{}};o[t]={...o[t]||{},bindings:[{modifiers:n,key:e.key,code:e.code}]},s.shortcutOverrides=o,this.saveAppSettingsToStorage(s),this.renderShortcutSettingsList()},resetShortcutOverride(e){const t=this.loadAppSettingsFromStorage(),n={...t.shortcutOverrides||{}};delete n[e],t.shortcutOverrides=n,this.saveAppSettingsToStorage(t),this.renderShortcutSettingsList()},toggleShortcutEnabled(e,t){const n=this.loadAppSettingsFromStorage(),s={...n.shortcutOverrides||{}};s[e]={...s[e]||{},disabled:!t},n.shortcutOverrides=s,this.saveAppSettingsToStorage(n),this.renderShortcutSettingsList()},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}});
|
|
Binary file
|
|
Binary file
|
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
"use strict";(function(e){const t=/^\x1b\[[\?>=]?[\d;]*[cnR]$/,s=/^\x1b\][\d;]*[^\x07\x1b]*(?:\x07|\x1b\\)$/;function a(h){return t.test(h)||s.test(h)}function n(h){return a(h)}const l={og:{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"},"daylight-green":{background:"#161b23",foreground:"#dfe6ef",cursor:"#2fd3aa",cursorAccent:"#161b23",selection:"rgba(47,211,170,0.22)",black:"#161b23",red:"#ff8585",green:"#34d8a0",yellow:"#f0c25a",blue:"#5cc6e8",magenta:"#c79af2",cyan:"#2bcbbb",white:"#dfe6ef",brightBlack:"#5b6675",brightRed:"#ffa0a0",brightGreen:"#5fe6b8",brightYellow:"#ffd884",brightBlue:"#82d4ee",brightMagenta:"#d6b3f7",brightCyan:"#5ee0d4",brightWhite:"#f3f6fa"},"daylight-blue":{background:"#161b23",foreground:"#dfe6ef",cursor:"#38b6f0",cursorAccent:"#161b23",selection:"rgba(56,182,240,0.22)",black:"#161b23",red:"#ff8585",green:"#34d8a0",yellow:"#f0c25a",blue:"#5cc6e8",magenta:"#c79af2",cyan:"#2bcbbb",white:"#dfe6ef",brightBlack:"#5b6675",brightRed:"#ffa0a0",brightGreen:"#5fe6b8",brightYellow:"#ffd884",brightBlue:"#82d4ee",brightMagenta:"#d6b3f7",brightCyan:"#5ee0d4",brightWhite:"#f3f6fa"}};function u(){const h=typeof document<"u"&&document.documentElement.dataset.skin||"daylight-blue";return l[h]||l["daylight-blue"]}e.CodemanTerminalInput={isTerminalQueryResponse:a,shouldSuppressTerminalQueryResponse:n,USER_SCROLL_STICKY_SUPPRESS_MS:1500,TOUCH_COMPAT_MOUSE_SUPPRESS_MS:450},e.CODEMAN_XTERM_THEMES=l,e.codemanCurrentXtermTheme=u})(window),Object.assign(CodemanApp.prototype,{initTerminal(){const e=parseInt(localStorage.getItem("codeman-scrollback")),t=Number.isFinite(e)&&e>0?Math.max(e,DEFAULT_SCROLLBACK):DEFAULT_SCROLLBACK;if(this.terminal=new Terminal({theme:{...window.codemanCurrentXtermTheme()},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:t,allowTransparency:!0,allowProposedApi:!0}),this.fitAddon=new FitAddon.FitAddon,this.terminal.loadAddon(this.fitAddon),this._xtermSnapshots=new Map,typeof SerializeAddon<"u")try{this._serializeAddon=new SerializeAddon.SerializeAddon,this.terminal.loadAddon(this._serializeAddon)}catch{this._serializeAddon=null}if(typeof Unicode11Addon<"u")try{const o=new Unicode11Addon.Unicode11Addon;this.terminal.loadAddon(o),this.terminal.unicode.activeVersion="11"}catch{}const s=document.getElementById("terminalContainer");this.terminal.open(s),this._installMobileTapMouseGuard(),this.terminal.attachCustomKeyEventHandler(o=>{if(o.isComposing||o.keyCode===229||o.altKey&&!o.ctrlKey&&!o.shiftKey&&/^(Digit[1-9]|BracketLeft|BracketRight|KeyK)$/.test(o.code||"")||o.type==="keydown"&&this.shouldOpenCommandPaletteFromShortcut?.(o))return!1;if((o.ctrlKey||o.metaKey)&&o.key==="v"&&o.type==="keydown")return this.activeSessionId&&this._handleImagePaste&&this._handleImagePaste(),!1;if(o.key==="Enter"&&(o.shiftKey||o.ctrlKey)&&o.type==="keydown"){if(this.activeSessionId)if(this._localEchoEnabled){const d=this._localEchoOverlay?.pendingText||"";this._localEchoOverlay?.clear(),this._localEchoOverlay?.suppressBufferDetection(),this._flushedOffsets?.delete(this.activeSessionId),this._flushedTexts?.delete(this.activeSessionId),d&&(this._pendingInput+=d,g()),setTimeout(()=>{fetch(`/api/sessions/${this.activeSessionId}/send-key`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({key:o.ctrlKey?"C-Enter":"S-Enter"})})},d?80:0)}else fetch(`/api/sessions/${this.activeSessionId}/send-key`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({key:o.ctrlKey?"C-Enter":"S-Enter"})});return!1}return!0});{const o=s.querySelector(".xterm-helper-textarea");if(o&&MobileDetection.isTouchDevice()){let d=!1,m=0;o.addEventListener("compositionstart",()=>{d=!0}),o.addEventListener("compositionend",()=>{d=!1}),o.addEventListener("keydown",p=>{!p.isComposing&&p.keyCode!==229&&(m=Date.now())}),o.addEventListener("input",p=>{if(d||p.isComposing||p.inputType!=="insertText"||!p.data||Date.now()-m<50)return;const _=p.data,T=this._localEchoOverlay?.pendingText||"";Promise.resolve().then(()=>{if(this._lastTerminalData?.data===_&&performance.now()-this._lastTerminalData.time<100){o.value="";return}const S=this._localEchoOverlay?.pendingText||"";if(this._localEchoEnabled&&S.length>T.length&&S.endsWith(_)){o.value="";return}const E=o.value;!E||E.trim()===""&&_!==" "||(this.terminal._core.coreService.triggerDataEvent(_,!0),o.value="")})})}}this._webglAddon=null;const i=new URLSearchParams(location.search),r=(()=>{try{const o=localStorage.getItem("codeman-webgl-disabled");if(!o)return!1;const{at:d}=JSON.parse(o);return Date.now()-d>WEBGL_FALLBACK.STICKY_EXPIRY_MS?(localStorage.removeItem("codeman-webgl-disabled"),!1):!0}catch{return!1}})(),a=this.loadAppSettingsFromStorage(),n=this.getDefaultSettings(),l=a.webglRendererEnabled??n.webglRendererEnabled,{skip:u,clearSticky:h}=shouldSkipWebGL({deviceType:MobileDetection.getDeviceType(),noWebglParam:i.has("nowebgl"),forceParam:i.get("webgl")==="force",stickyDisabled:r,userPrefEnabled:l});if(h)try{localStorage.removeItem("codeman-webgl-disabled")}catch{}if(u&&r&&console.log("[CRASH-DIAG] WebGL sticky-disabled from prior stalls \u2014 DOM renderer in use. Re-enable: ?webgl=force"),!u)if(typeof WebglAddon<"u")this._initWebGL();else{const o=document.createElement("script");o.src="vendor/xterm-addon-webgl.min.js",o.onload=()=>this._initWebGL(),o.onerror=()=>console.warn("[CRASH-DIAG] Failed to load WebGL addon \u2014 using canvas renderer"),document.head.appendChild(o)}this._localEchoOverlay=new LocalEchoOverlay(this.terminal),MobileDetection.isTouchDevice()&&(this.terminal.onCursorMove(()=>this._syncMobileHelperTextareaToCursor()),this.terminal.onRender(()=>this._syncMobileHelperTextareaToCursor())),this._cjkInput=null,typeof CjkInput<"u"&&(this._cjkInput=CjkInput.init({send:o=>{this._handleCjkInput(o)}}));const c=this.terminal.focus.bind(this.terminal);this.terminal.focus=()=>{const o=document.getElementById("cjkInput");o?.classList.contains("cjk-input-visible")?o.focus():c()},MobileDetection.getDeviceType()==="mobile"&&document.body.classList.contains("safari-browser")?requestAnimationFrame(()=>{this.fitAddon.fit(),requestAnimationFrame(()=>this.fitAddon.fit())}):this.fitAddon.fit(),this.registerFilePathLinkProvider(),s.addEventListener("wheel",o=>{o.preventDefault();const d=Math.round(o.deltaY/25)||(o.deltaY>0?1:-1);if(this._shouldForwardWheelToApp(o)){this._sendSyntheticSgrWheel(o.clientX,o.clientY,d);return}this._noteTerminalUserScroll(d),this.terminal.scrollLines(d)},{passive:!1});{const o=()=>this.terminal._core?._renderService?.dimensions?.css?.cell?.height||13;let d=0,m=0,p=0,_=null,T=!1;const S=C=>{const b=p?(C-p)/16.67:1;if(p=C,!T&&Math.abs(m)>.3){const x=Math.round(m/o());x!==0&&this.terminal.scrollLines(x),m*=.92,_=requestAnimationFrame(S)}else T?_=requestAnimationFrame(S):(_=null,m=0)};let E=0,I=!1,L=0;const A=8;s.addEventListener("touchstart",C=>{C.touches.length===1&&(d=C.touches[0].clientY,L=d,m=0,E=0,T=!0,I=!1,p=0,_&&(cancelAnimationFrame(_),_=null))},{passive:!0}),s.addEventListener("touchmove",C=>{if(C.touches.length===1&&T){const b=C.touches[0].clientY;if(!I&&Math.abs(b-L)>=A&&(I=!0),!I)return;C.preventDefault();const x=d-b;E+=x,m=x*1.2,d=b;const M=o(),k=Math.trunc(E/M);k!==0&&(this._noteTerminalUserScroll(k),this.terminal.scrollLines(k),E-=k*M)}},{passive:!1}),s.addEventListener("touchend",C=>{if(T=!1,!_&&Math.abs(m)>.3&&(_=requestAnimationFrame(S)),!I&&this.terminal){const b=C.changedTouches&&C.changedTouches[0],x=this.terminal.modes?.mouseTrackingMode,M=!!x&&x!=="none";b&&this._suppressTrustedTapMouseEvents(),b&&M?this._dispatchSyntheticTerminalClick(b.clientX,b.clientY):b&&this._sessionUsesServerMouseStrip()&&this._sendSyntheticSgrTap(b.clientX,b.clientY),this._syncMobileHelperTextareaToCursor();const k=document.getElementById("cjkInput");k?.classList.contains("cjk-input-visible")?k.focus():this.terminal.focus()}},{passive:!0}),s.addEventListener("touchcancel",()=>{T=!1,m=0,E=0},{passive:!0})}s.addEventListener("click",o=>this._handleDesktopTerminalClick(o)),this.showWelcome(),this.initImageInput(),this._chunkedWriteGen=0,this._bufferLoadSeq=0,this._bufferLoadOwner=null,this._lastUserScrollUpAt=null,this._resizeTimeout=null,this._lastResizeDims=null;const w=40,v=10,y=()=>{this._resizeTimeout&&clearTimeout(this._resizeTimeout),this._resizeTimeout=setTimeout(()=>{this._resizeTimeout=null,this.fitAddon&&this.fitAddon.fit(),this.flickerFilterBuffer&&(this.flickerFilterTimeout&&(clearTimeout(this.flickerFilterTimeout),this.flickerFilterTimeout=null),this.flushFlickerBuffer());const o=typeof KeyboardHandler<"u"&&KeyboardHandler.keyboardVisible;if(this.activeSessionId&&!o){const d=this.fitAddon.proposeDimensions(),m=d?Math.max(d.cols,w):w,p=d?Math.max(d.rows,v):v;if(!this._lastResizeDims||m!==this._lastResizeDims.cols||p!==this._lastResizeDims.rows){const _=this.activeSessionId?this.sessions.get(this.activeSessionId):null;_&&_.mode!=="shell"&&this.terminal&&this.isTerminalAtBottom()&&this.terminal.write("\x1B[3J\x1B[H\x1B[2J"),this._lastResizeDims={cols:m,rows:p};const T=typeof MobileDetection<"u"&&MobileDetection.getDeviceType?MobileDetection.getDeviceType():"desktop";let S=!1;if(this._wsReady&&this._wsSessionId===this.activeSessionId)try{this._ws.send(JSON.stringify({t:"z",c:m,r:p,v:T})),S=!0}catch{}S||fetch(`/api/sessions/${this.activeSessionId}/resize`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cols:m,rows:p,viewportType:T})}).catch(()=>{})}}this.updateConnectionLines(),this._localEchoOverlay?.hasPending&&this._localEchoOverlay.rerender()},300)};window.addEventListener("resize",y),this.terminalResizeObserver&&this.terminalResizeObserver.disconnect(),this.terminalResizeObserver=new ResizeObserver(y),this.terminalResizeObserver.observe(s),this._pendingInput="",this._inputFlushTimeout=null,this._lastKeystrokeTime=0;const g=()=>{if(this._inputFlushTimeout=null,this._pendingInput&&this.activeSessionId){const o=this._pendingInput,d=this.activeSessionId;this._pendingInput="",this._sendInputAsync(d,o)}};this.terminal.onData(o=>{if(!/^\x1b\[<\d+;\d+;\d+[Mm]$/.test(o)&&(window.cjkActive||document.activeElement?.id==="cjkInput")){const m=document.getElementById("cjkInput");m?.classList.contains("cjk-input-visible")&&document.activeElement===this.terminal.textarea&&!window.CodemanTerminalInput?.shouldSuppressTerminalQueryResponse(o)&&(_crashDiag.log("CJK regain-focus (onData swallowed input)"),m.focus());return}if(this.activeSessionId){if(window.CodemanTerminalInput?.shouldSuppressTerminalQueryResponse(o))return;if(this._lastTerminalData={data:o,time:performance.now()},this._localEchoEnabled){if(o==="\x7F"){if(this._localEchoOverlay?.removeChar()==="flushed"){const{count:_,text:T}=this._localEchoOverlay.getFlushed();this._flushedOffsets?.has(this.activeSessionId)&&(_===0?(this._flushedOffsets.delete(this.activeSessionId),this._flushedTexts?.delete(this.activeSessionId)):(this._flushedOffsets.set(this.activeSessionId,_),this._flushedTexts?.set(this.activeSessionId,T))),this._pendingInput+=o,g()}return}if(/^[\r\n]+$/.test(o)){const p=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),p&&(this._pendingInput+=p,g()),setTimeout(()=>{this._pendingInput+="\r",g()},80);return}if(o.length>1&&o.charCodeAt(0)>=32){this._localEchoOverlay?.appendText(o);return}if(o.charCodeAt(0)<32){if(o.length>1&&o.charCodeAt(0)===27){this._pendingInput+=o,g();return}if(this._restoringFlushedState){this._pendingInput+=o,g();return}if(o===" "){const _=this._localEchoOverlay?.pendingText||"";this._localEchoOverlay?.clear(),this._flushedOffsets?.delete(this.activeSessionId),this._flushedTexts?.delete(this.activeSessionId),_&&(this._pendingInput+=_),this._pendingInput+=o,this._inputFlushTimeout&&(clearTimeout(this._inputFlushTimeout),this._inputFlushTimeout=null);let T="";try{const E=this._localEchoOverlay?.findPrompt?.();if(E){const I=this.terminal.buffer.active,L=I.getLine(I.viewportY+E.row);L&&(T=L.translateToString(!0).slice(E.col+2).trimEnd())}}catch{}this._tabCompletionBaseText=T,g(),this._tabCompletionSessionId=this.activeSessionId,this._tabCompletionRetries=0,this._tabCompletionFallback&&clearTimeout(this._tabCompletionFallback);const S=this;this._tabCompletionFallback=setTimeout(()=>{if(S._tabCompletionFallback=null,!S._tabCompletionSessionId||S._tabCompletionSessionId!==S.activeSessionId)return;const E=S._localEchoOverlay;!E||E.pendingText||S.terminal.write("",()=>{if(!S._tabCompletionSessionId)return;E.resetBufferDetection();const I=E.detectBufferText();I&&I!==S._tabCompletionBaseText&&(S._tabCompletionSessionId=null,S._tabCompletionRetries=0,S._tabCompletionBaseText=null,E.rerender())})},300);return}const p=this._localEchoOverlay?.pendingText||"";this._localEchoOverlay?.clear(),this._localEchoOverlay?.suppressBufferDetection(),this._flushedOffsets?.delete(this.activeSessionId),this._flushedTexts?.delete(this.activeSessionId),p&&(this._pendingInput+=p),this._pendingInput+=o,this._inputFlushTimeout&&(clearTimeout(this._inputFlushTimeout),this._inputFlushTimeout=null),g();return}if(o.length===1&&o.charCodeAt(0)>=32){this._localEchoOverlay?.addChar(o);return}}if(this._pendingInput+=o,o.charCodeAt(0)<32||o.length>1){this._inputFlushTimeout&&(clearTimeout(this._inputFlushTimeout),this._inputFlushTimeout=null),g();return}const m=performance.now();m-this._lastKeystrokeTime>50?(this._inputFlushTimeout&&(clearTimeout(this._inputFlushTimeout),this._inputFlushTimeout=null),this._lastKeystrokeTime=m,g()):(this._lastKeystrokeTime=m,this._inputFlushTimeout||(this._inputFlushTimeout=setTimeout(g,0)))}})},registerFilePathLinkProvider(){const e=this;let t=-1;this.terminal.registerLinkProvider({provideLinks(s,i){s!==t&&(t=s,console.debug("[LinkProvider] Checking line:",s));const a=e.terminal.buffer.active.getLine(s-1);if(!a){i(void 0);return}const n=a.translateToString(!0);if(!n||!n.includes("/")){i(void 0);return}const l=[],u=/https?:\/\/[^\s"'<>|;&)\]\x00-\x1f]+/g,h=(g,o)=>{const d=g.replace(/[.,;:!?)]+$/,""),m=n.indexOf(d,o);m!==-1&&(l.some(p=>p.range.start.x===m+1)||l.push({text:d,range:{start:{x:m+1,y:s},end:{x:m+d.length+1,y:s}},decorations:{pointerCursor:!0,underline:!0},activate(p,_){window.open(_,"_blank","noopener,noreferrer")},hover(){e._linkHovered=!0},leave(){e._linkHovered=!1}}))},c=/\b(tail|cat|head|less|grep|watch|vim|nano)\s+(?:[^\s\/]+\s+){0,4}(\/[^\s"'<>|;&\n\x00-\x1f]+)/g,f=/(\/(?:home|tmp|var|etc|opt)[^\s"'<>|;&\n\x00-\x1f]*\.(?:log|txt|json|md|yaml|yml|csv|xml|sh|py|ts|js))\b/g,w=/Bash\([^)]*?(\/(?:home|tmp|var|etc|opt)[^\s"'<>|;&\)\n\x00-\x1f]+)/g,v=(g,o)=>{const d=n.indexOf(g,o);d!==-1&&(l.some(m=>m.range.start.x===d+1)||l.push({text:g,range:{start:{x:d+1,y:s},end:{x:d+g.length+1,y:s}},decorations:{pointerCursor:!0,underline:!0},activate(m,p){e.openLogViewerWindow(p,e.activeSessionId)},hover(){e._linkHovered=!0},leave(){e._linkHovered=!1}}))};let y;for(u.lastIndex=0;(y=u.exec(n))!==null;)h(y[0],y.index);for(c.lastIndex=0;(y=c.exec(n))!==null;)v(y[2],y.index);for(f.lastIndex=0;(y=f.exec(n))!==null;)v(y[1],y.index);for(w.lastIndex=0;(y=w.exec(n))!==null;)v(y[1],y.index);l.length>0&&console.debug("[LinkProvider] Found links:",l.map(g=>g.text)),i(l.length>0?l:void 0)}}),console.log("[LinkProvider] File path link provider registered")},showWelcome(){const e=document.getElementById("welcomeOverlay");e&&(e.classList.add("visible"),this.loadTunnelStatus(),this.loadHistorySessions(),this.initSearchPanel()),this._updateCjkInputState?.()},hideWelcome(){const e=document.getElementById("welcomeOverlay");e&&e.classList.remove("visible");const t=document.getElementById("welcomeQr");t&&(clearTimeout(this._welcomeQrShrinkTimer),t.classList.remove("expanded")),this._updateCjkInputState?.()},async _fetchHistorySessions(){const s=(await(await fetch("/api/history/sessions")).json()).data?.sessions||[];if(s.length===0)return[];const i=new Map;for(const a of s){const n=a.projectKey||a.workingDir;i.has(n)||i.set(n,[]),i.get(n).push(a)}const r=[];for(const[,a]of i)r.push(...a.slice(0,3));return r.sort((a,n)=>new Date(n.lastModified)-new Date(a.lastModified)),r},async _fetchUnifiedSessions(e=60){const t=await fetch("/api/sessions/unified?limit="+e),s=await t.json().catch(()=>null);if(!t.ok||!s||s.success===!1||!s.data)throw new Error(s?.error||`unified sessions request failed (HTTP ${t.status})`);return s.data.sessions||[]},_resolveCaseLabel(e,t){if(!e)return"";let s=null;for(const i of t||[])if(!(!i||!i.path)){if(e===i.path)return`#${i.name}`;if(e.startsWith(i.path+"/")){const r=i.path.length;(!s||r>s.len)&&(s={name:i.name,suffix:e.slice(r),len:r})}}return s?`#${s.name}${s.suffix}`:e.split("/").pop()||e},_shortenHomePath(e){return(e||"").replace(/^\/home\/[^/]+\//,"~/").replace(/^\/Users\/[^/]+\//,"~/")},_buildHistoryItem(e,t,s){const i=s?.showViewAll!==!1,r=typeof e.sizeBytes=="number",a=r?e.sizeBytes<1024?`${e.sizeBytes}B`:e.sizeBytes<1048576?`${(e.sizeBytes/1024).toFixed(0)}K`:`${(e.sizeBytes/1048576).toFixed(1)}M`:"",n=typeof e.lastActivityAt=="number"?e.lastActivityAt:e.lastModified?Date.parse(e.lastModified):NaN;let l="";if(!Number.isNaN(n)){const b=new Date(n);l=b.toLocaleDateString("en",{month:"short",day:"numeric"})+" "+b.toLocaleTimeString("en",{hour:"2-digit",minute:"2-digit",hour12:!1})}const u=this._shortenHomePath(e.workingDir),h=this._resolveCaseLabel(e.workingDir,t),c=Array.isArray(e.sources)&&e.sources.includes("live"),f=document.createElement("div");f.className="history-item",f.title=e.workingDir||"";const w=document.createElement("div");w.className="history-item-main",w.addEventListener("click",s?.onActivate||(()=>{c&&this.sessions.has(e.sessionId)?this.selectSession(e.sessionId):this.resumeHistorySession(e.claudeSessionId||e.sessionId,e.workingDir||"")}));const v=document.createElement("div");v.className="history-item-text";const y=document.createElement("span");y.className="history-item-title",y.textContent=e.name||e.firstPrompt||u;const g=document.createElement("div");if(g.className="history-item-badges",e.mode){const b=document.createElement("span");b.className="history-item-badge history-item-badge-mode",b.textContent=e.mode,g.appendChild(b)}if(c){const b=document.createElement("span");b.className="history-item-badge history-item-badge-live",b.textContent="LIVE",g.appendChild(b)}const o=document.createElement("span");o.className="history-item-subtitle",h.startsWith("#")&&o.classList.add("is-case"),o.textContent=h,v.append(y),g.childElementCount>0&&v.append(g),v.append(o);const d=document.createElement("span");d.className="history-item-meta",d.textContent=l;const m=document.createElement("button");m.className="history-item-expand",m.type="button",m.setAttribute("aria-haspopup","menu"),m.setAttribute("aria-label","Session actions"),m.setAttribute("aria-expanded","false"),m.textContent="\u22EF",w.append(v,d,m);const p=document.createElement("div");p.className="history-item-detail",p.hidden=!0;const _=document.createElement("div");_.className="history-detail-row";const T=document.createElement("span");T.className="history-detail-label",T.textContent="Prompt";const S=document.createElement("span");S.className="history-detail-value history-detail-prompt",S.textContent=e.firstPrompt||"(no prompt captured)",_.append(T,S);const E=document.createElement("div");E.className="history-detail-row";const I=document.createElement("span");I.className="history-detail-label",I.textContent="Path";const L=document.createElement("span");L.className="history-detail-value history-detail-path",L.textContent=u,E.append(I,L);const A=document.createElement("div");A.className="history-detail-row history-detail-meta";const C=[];if(l&&C.push(l),r&&C.push(a),C.push(e.sessionId.slice(0,8)),A.textContent=C.join(" \xB7 "),p.append(_,E,A),i&&e.projectKey){const b=document.createElement("div");b.className="history-detail-row history-detail-actions";const x=document.createElement("button");x.type="button",x.className="history-view-all-btn",x.textContent="View all in this folder",x.addEventListener("click",M=>{M.stopPropagation(),this.openFolderHistoryModal(e.projectKey,e.workingDir,t)}),b.appendChild(x),p.appendChild(b)}return m.addEventListener("click",b=>{b.stopPropagation(),b.preventDefault(),this._openSessionRowMenu(b.currentTarget,e,t,f,p)}),f.append(w,p),f},_openSessionRowMenu(e,t,s,i,r){if(this._openRowMenuClose)try{this._openRowMenuClose()}catch{}const a=Array.isArray(t.sources)&&t.sources.includes("live")&&this.sessions.has(t.sessionId),n=document.createElement("div");n.className="session-row-menu",n.setAttribute("role","menu");let l=null,u=null,h=null;const c=()=>{document.removeEventListener("mousedown",l,!0),document.removeEventListener("keydown",u,!0),window.removeEventListener("scroll",h,!0),window.removeEventListener("resize",h,!0);try{n.remove()}catch{}this._openRowMenuEl===n&&(this._openRowMenuEl=null,this._openRowMenuClose=null)},f=(d,m,p)=>{const _=document.createElement("button");_.type="button",_.className="session-row-menu-item",_.setAttribute("role","menuitem");const T=document.createElement("span");if(T.className="session-row-menu-label",T.textContent=d,_.appendChild(T),p&&p.sublabel){const S=document.createElement("span");S.className="session-row-menu-sublabel",S.textContent=p.sublabel,_.appendChild(S)}_.addEventListener("click",async S=>{S.stopPropagation(),S.preventDefault(),await m()}),n.appendChild(_)};f(a?"Switch to session":"Resume session",()=>{a?this.selectSession(t.sessionId):this.resumeHistorySession(t.claudeSessionId||t.sessionId,t.workingDir||""),this.closeSessionManager?.(),c()}),a&&f("Open folder",()=>{this.selectSession(t.sessionId),this.loadFileBrowser?.(t.sessionId),this.closeSessionManager?.(),c()}),t.workingDir&&f("Copy path",async()=>{const d=await this._copyText(t.workingDir);this.showToast(d?"Path copied":"Copy failed",d?"success":"error"),c()}),f("Show details",()=>{const d=i.classList.toggle("expanded");r.hidden=!d,e.setAttribute("aria-expanded",d?"true":"false"),c()}),document.body.appendChild(n);const w=e.getBoundingClientRect(),v=n.getBoundingClientRect(),y=4;let g=w.bottom+y;g+v.height>window.innerHeight&&w.top-y-v.height>=0&&(g=w.top-y-v.height);let o=w.right-v.width;o<y&&(o=y),o+v.width>window.innerWidth-y&&(o=Math.max(y,window.innerWidth-y-v.width)),n.style.top=`${Math.max(y,g)}px`,n.style.left=`${o}px`,l=d=>{n.contains(d.target)||e.contains(d.target)||c()},u=d=>{d.key==="Escape"&&(d.stopPropagation(),c())},h=()=>c(),document.addEventListener("mousedown",l,!0),document.addEventListener("keydown",u,!0),window.addEventListener("scroll",h,!0),window.addEventListener("resize",h,!0),this._openRowMenuEl=n,this._openRowMenuClose=c},_HISTORY_INITIAL_COUNT:4,async loadHistorySessions(){const e=document.getElementById("historySessions"),t=document.getElementById("historyList");if(!(!e||!t))try{const s=Array.isArray(this.cases)&&this.cases.length>0?Promise.resolve(this.cases):fetch("/api/cases").then(n=>n.ok?n.json():null).then(n=>n?.data||[]).catch(()=>[]),[i,r]=await Promise.all([this._fetchUnifiedSessions(60),s]);if(i.length===0){e.style.display="none";return}t.replaceChildren();const a=this._HISTORY_INITIAL_COUNT;for(let n=0;n<Math.min(a,i.length);n++)t.appendChild(this._buildHistoryItem(i[n],r));if(i.length>a){const n=document.createElement("button");n.className="history-show-more",n.textContent=`Show ${i.length-a} more`,n.addEventListener("click",()=>{for(let l=a;l<i.length;l++)t.insertBefore(this._buildHistoryItem(i[l],r),n);n.remove()}),t.appendChild(n)}e.style.display=""}catch(s){console.error("[loadHistorySessions]",s),e.style.display="none"}},_FOLDER_HISTORY_PAGE_SIZE:20,openFolderHistoryModal(e,t,s){this._closeFolderHistoryModal();const i=document.createElement("div");i.className="modal active folder-history-modal",i.id="folderHistoryModal";const r=document.createElement("div");r.className="modal-backdrop",r.addEventListener("click",()=>this._closeFolderHistoryModal());const a=document.createElement("div");a.className="modal-content modal-lg";const n=document.createElement("div");n.className="modal-header";const l=document.createElement("h3");l.textContent="Folder History";const u=document.createElement("div");u.className="folder-history-subtitle",u.textContent=this._shortenHomePath(t);const h=document.createElement("button");h.className="modal-close",h.setAttribute("aria-label","Close"),h.innerHTML="×",h.addEventListener("click",()=>this._closeFolderHistoryModal()),n.append(l,h);const c=document.createElement("div");c.className="modal-body";const f=document.createElement("div");f.className="folder-history-list",f.setAttribute("data-loading","true"),f.textContent="Loading...",c.append(u,f),a.append(n,c),i.append(r,a),document.body.appendChild(i),this._folderHistoryState={projectKey:e,workingDir:t,cases:s||[],offset:0,total:null,list:f},this._folderHistoryEscHandler=w=>{w.key==="Escape"&&this._closeFolderHistoryModal()},document.addEventListener("keydown",this._folderHistoryEscHandler),this._loadFolderHistoryPage()},async _loadFolderHistoryPage(){const e=this._folderHistoryState;if(!e)return;const{projectKey:t,cases:s,list:i}=e,r=this._FOLDER_HISTORY_PAGE_SIZE,a=e.offset,n=i.querySelector(".folder-history-more");n&&n.remove(),a===0&&(i.replaceChildren(),i.removeAttribute("data-loading"));try{const l=`/api/history/sessions?projectKey=${encodeURIComponent(t)}&offset=${a}&limit=${r}`,h=await(await fetch(l)).json(),c=h.data?.sessions||[];if(e.total=typeof h.data?.total=="number"?h.data.total:c.length+a,a===0&&c.length===0){const f=document.createElement("div");f.className="folder-history-empty",f.textContent="No conversations found in this folder.",i.appendChild(f);return}for(const f of c)i.appendChild(this._buildHistoryItem(f,s,{showViewAll:!1}));if(e.offset=a+c.length,e.offset<e.total){const f=e.total-e.offset,w=document.createElement("button");w.className="history-show-more folder-history-more",w.textContent=`Show ${Math.min(r,f)} more (${f} remaining)`,w.addEventListener("click",()=>this._loadFolderHistoryPage()),i.appendChild(w)}}catch(l){console.error("[loadFolderHistoryPage]",l);const u=document.createElement("div");u.className="folder-history-empty",u.textContent="Failed to load folder history.",i.appendChild(u)}},_closeFolderHistoryModal(){const e=document.getElementById("folderHistoryModal");e&&e.remove(),this._folderHistoryEscHandler&&(document.removeEventListener("keydown",this._folderHistoryEscHandler),this._folderHistoryEscHandler=null),this._folderHistoryState=null},async resumeHistorySession(e,t){document.getElementById("runModeMenu")?.classList.remove("active"),this._closeFolderHistoryModal();try{this.terminal.clear(),this.terminal.writeln(`\x1B[1;32m Resuming conversation ${e.slice(0,8)}...\x1B[0m`);const s=t.split("/").pop()||"session";let i=1;for(const[,v]of this.sessions){const y=v.name&&v.name.match(/^w(\d+)-/);if(y){const g=parseInt(y[1]);g>=i&&(i=g+1)}}const r=`w${i}-${s}`,n=(this.cases||[]).find(v=>v.path===t)?.name||t.split("/").pop()||"",l=this.loadAppSettingsFromStorage(),u=this.buildEnvOverrides(this.getCaseSettings(n),l),h=this.getEffortSetting(l),f=await(await fetch("/api/sessions",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({workingDir:t,name:r,resumeSessionId:e,...Object.keys(u).length>0?{envOverrides:u}:{},...h?{effort:h}:{}})})).json();if(!f.success)throw new Error(f.error);const w=f.data.session.id;await fetch(`/api/sessions/${w}/interactive`,{method:"POST"}),this.terminal.writeln(`\x1B[90m Session ${r} ready\x1B[0m`),await this.selectSession(w),this.terminal.focus()}catch(s){this.terminal.writeln(`\x1B[1;31m Error: ${s.message}\x1B[0m`)}},isTerminalAtBottom(){if(!this.terminal)return!0;const e=this.terminal.buffer.active;return e.viewportY>=e.baseY-2},_noteTerminalUserScroll(e){e<0?this._lastUserScrollUpAt=performance.now():this.isTerminalAtBottom()&&(this._lastUserScrollUpAt=null)},_hasRecentUserScrollUp(){return typeof this._lastUserScrollUpAt!="number"?!1:performance.now()-this._lastUserScrollUpAt<window.CodemanTerminalInput.USER_SCROLL_STICKY_SUPPRESS_MS},batchTerminalWrite(e){if(this._isLoadingBuffer){this._loadBufferQueue&&this._loadBufferQueue.push(e);return}if(this.writeFrameScheduled||(this._wasAtBottomBeforeWrite=this.isTerminalAtBottom()),(this.activeSessionId?this.sessions.get(this.activeSessionId):null)?.flickerFilterEnabled??!1){if(e.includes("\x1B[2J")||e.includes("\x1B[H\x1B[J")||e.includes("\x1B[H")&&e.includes("\x1B[?25l")){this.flickerFilterActive=!0,this.flickerFilterBuffer+=e,this.flickerFilterTimeout&&clearTimeout(this.flickerFilterTimeout),this.flickerFilterTimeout=setTimeout(()=>{this.flickerFilterTimeout=null,this.flushFlickerBuffer()},SYNC_WAIT_TIMEOUT_MS);return}if(this.flickerFilterActive){this.flickerFilterBuffer+=e;return}}this.pendingWrites.push(e),this.writeFrameScheduled||(this.writeFrameScheduled=!0,this._safeYield(()=>{this.flushPendingWrites(),this.writeFrameScheduled=!1}))},flushFlickerBuffer(){this.flickerFilterBuffer&&(this.pendingWrites.push(this.flickerFilterBuffer),this.flickerFilterBuffer="",this.flickerFilterActive=!1,this.writeFrameScheduled||(this.writeFrameScheduled=!0,this._safeYield(()=>{this.flushPendingWrites(),this.writeFrameScheduled=!1})))},_updateLocalEchoState(){const e=this.loadAppSettingsFromStorage(),t=this.activeSessionId?this.sessions.get(this.activeSessionId):null,i=!!((e.localEchoEnabled??MobileDetection.isTouchDevice())&&t);this._localEchoEnabled&&!i&&this._localEchoOverlay?.clear(),this._localEchoEnabled=i,this._localEchoOverlay&&t&&(t.mode==="opencode"?this._localEchoOverlay.setPrompt({type:"custom",offset:3,find:r=>{try{const a=r.buffer.active,n=a.cursorY,l=a.getLine(a.viewportY+n);if(!l)return null;const h=l.translateToString(!0).indexOf("\u2503");return h>=0?{row:n,col:h}:null}catch{return null}}}):t.mode==="shell"?(this._localEchoOverlay.clear(),this._localEchoEnabled=!1):this._localEchoOverlay.setPrompt({type:"custom",offset:0,find:r=>{try{const a=r.buffer.active;for(let n=r.rows-1;n>=0;n--){const l=a.getLine(a.viewportY+n);if(!l)continue;const h=l.translateToString(!0).lastIndexOf("\u276F");if(h>=0)return{row:n,col:h+2}}return{row:Math.max(0,Math.min(r.rows-1,a.cursorY)),col:Math.max(0,Math.min(r.cols-1,a.cursorX))}}catch{return null}}}))},_handleCjkInput(e){if(!this.activeSessionId){_crashDiag.log(`CJK send DROP no-session len=${e.length}`);return}_crashDiag.log(`CJK send\u2192${this.activeSessionId.slice(0,8)} len=${e.length}`),this._sendInputAsync(this.activeSessionId,e)},flushPendingWrites(){if(this.pendingWrites.length===0||!this.terminal)return;const e=performance.now(),t=this.pendingWrites.join("");this.pendingWrites=[];const s=t.length;s>16384&&_crashDiag.log(`FLUSH: ${(s/1024).toFixed(0)}KB`);const r=(this.activeSessionId&&this.sessions?this.sessions.get(this.activeSessionId):null)?.mode==="codex"?32768:65536;let a=!1;const n=this._hasRecentUserScrollUp()&&this.terminal.buffer?.active?this.terminal.buffer.active.viewportY:null;s<=r?this.terminal.write(t):(this.terminal.write(t.slice(0,r)),this.pendingWrites.push(t.slice(r)),a=!0,this.writeFrameScheduled||(this.writeFrameScheduled=!0,this._safeYield(()=>{this.flushPendingWrites(),this.writeFrameScheduled=!1}))),n!==null&&this.terminal.buffer?.active?.viewportY!==n&&typeof this.terminal.scrollToLine=="function"&&this.terminal.scrollToLine(n);const l=a?r:s,u=performance.now()-e;if((u>100||a)&&console.warn(`[CRASH-DIAG] flushPendingWrites: ${u.toFixed(0)}ms, ${(l/1024).toFixed(0)}KB written${a?", rest deferred":""} (total ${(s/1024).toFixed(0)}KB)`),this._wasAtBottomBeforeWrite&&!this._hasRecentUserScrollUp()&&this.terminal.scrollToBottom(),this._localEchoOverlay?.hasPending&&this._localEchoOverlay.rerender(),this._tabCompletionSessionId&&this._tabCompletionSessionId===this.activeSessionId&&this._localEchoOverlay&&!this._localEchoOverlay.pendingText){const h=this._localEchoOverlay,c=this;this.terminal.write("",()=>{if(!c._tabCompletionSessionId)return;h.resetBufferDetection();const f=h.detectBufferText();f?f===c._tabCompletionBaseText?(h.undoDetection(),c._tabCompletionRetries=(c._tabCompletionRetries||0)+1,c._tabCompletionRetries>60&&(c._tabCompletionSessionId=null,c._tabCompletionRetries=0)):(c._tabCompletionSessionId=null,c._tabCompletionRetries=0,c._tabCompletionBaseText=null,c._tabCompletionFallback&&(clearTimeout(c._tabCompletionFallback),c._tabCompletionFallback=null),h.rerender()):(c._tabCompletionRetries=(c._tabCompletionRetries||0)+1,c._tabCompletionRetries>60&&(c._tabCompletionSessionId=null,c._tabCompletionRetries=0))})}},_safeYield(e){let t=!1;const s=()=>{t||(t=!0,e())};requestAnimationFrame(s),setTimeout(s,50),this._workerYield(s)},_workerYield(e){try{if(this._yieldWorker===void 0){const t="onmessage=()=>setTimeout(()=>postMessage(0),0);",s=new Blob([t],{type:"application/javascript"}),i=URL.createObjectURL(s);this._yieldWorker=new Worker(i),URL.revokeObjectURL(i),this._yieldQueue=[],this._yieldWorker.onmessage=()=>{const r=this._yieldQueue.shift();r&&r()}}if(!this._yieldWorker)return;this._yieldQueue.push(e),this._yieldWorker.postMessage(0)}catch{this._yieldWorker=null}},scrollToLastNonEmptyLine(){if(!this.terminal?.buffer?.active){this.terminal?.scrollToBottom?.();return}const e=this.terminal.buffer.active,t=e.baseY+e.length;let s=-1;for(let i=t-1;i>=0;i--)if(e.getLine(i)?.translateToString(!0).trim()){s=i;break}if(s>=0&&typeof this.terminal.scrollToLine=="function"){let i=Math.max(0,s-this.terminal.rows+2);const r=Math.max(0,s);for(;i<r&&!e.getLine(i)?.translateToString(!0).trim();)i++;this.terminal.scrollToLine(i)}else this.terminal.scrollToBottom()},chunkedTerminalWrite(e,t=TERMINAL_CHUNK_SIZE,s){const i=++this._chunkedWriteGen,r=this._beginBufferLoad(s);return new Promise(a=>{if(!e||e.length===0){this._finishBufferLoad(r),a();return}const n=e.replace(DEC_SYNC_STRIP_RE,""),l=()=>{this._chunkedWriteGen===i&&this._finishBufferLoad(r),a()};if(n.length<=t){this.terminal.write(n,l);return}let u=0;const h=performance.now();let c=0;const f=()=>{if(this._chunkedWriteGen!==i){a();return}if(u>=n.length){const g=performance.now()-h;console.log(`[CRASH-DIAG] chunkedTerminalWrite complete: ${n.length} bytes in ${c} chunks, ${g.toFixed(0)}ms total`),this._safeYield(l);return}const w=performance.now(),v=n.slice(u,u+t);this.terminal.write(v);const y=performance.now()-w;c++,y>50&&console.warn(`[CRASH-DIAG] chunk #${c} write took ${y.toFixed(0)}ms (${v.length} bytes at offset ${u})`),u+=t,this._safeYield(f)};this._safeYield(f)})},_beginBufferLoad(e){this._bufferLoadSeq===void 0&&(this._bufferLoadSeq=0);const t=e===void 0?`buffer-${++this._bufferLoadSeq}`:e;return this._bufferLoadOwner=t,this._isLoadingBuffer=!0,this._loadBufferQueue=[],t},_finishBufferLoad(e,t){if(e!==void 0&&this._bufferLoadOwner!==e)return!1;const s=this._loadBufferQueue;if(this._isLoadingBuffer=!1,this._loadBufferQueue=null,this._bufferLoadOwner=null,t?.flushQueued&&s&&s.length)for(const i of s)this.batchTerminalWrite(i);return!0},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,{force:!0}),this.showToast(`Terminal restored to ${e.cols}x${e.rows}`,"success")}catch(t){console.error("Failed to restore terminal size:",t),this.showToast("Failed to restore terminal size","error")}},sendPendingCtrlL(e){},async copyTerminal(){try{const e=this.terminal.buffer.active;let t="";for(let s=0;s<e.length;s++){const i=e.getLine(s);i&&(t+=i.translateToString(!0)+`
|
|
2
|
-
`)}await navigator.clipboard.writeText(t.replace(/\n+$/,`
|
|
3
|
-
`)),this.showToast("Copied to clipboard","success")}catch{this.showToast("Failed to copy","error")}},_syncMobileHelperTextareaToCursor(){if(!(!MobileDetection.isTouchDevice()||!this.terminal?.element))try{const e=this.terminal.element,t=this.terminal.element.querySelector(".xterm-cursor"),s=this.terminal.element.querySelector(".xterm-screen");if(!(e instanceof HTMLElement)||!(t instanceof HTMLElement)||!(s instanceof HTMLElement))return;const i=t.getBoundingClientRect(),r=s.getBoundingClientRect();if(!i.width&&!i.height)return;const a=Math.max(0,Math.round(i.left-r.left)),n=Math.max(0,Math.round(i.top-r.top));e.style.setProperty("--xterm-helper-left",`${a}px`),e.style.setProperty("--xterm-helper-top",`${n}px`)}catch{}},_dispatchSyntheticTerminalClick(e,t){const s=this.terminal?.element;if(!s||!Number.isFinite(e)||!Number.isFinite(t))return;const i={bubbles:!0,cancelable:!0,view:window,clientX:e,clientY:t,screenX:e,screenY:t,button:0,detail:1};try{s.dispatchEvent(new MouseEvent("mousedown",{...i,buttons:1})),s.dispatchEvent(new MouseEvent("mouseup",{...i,buttons:0}))}catch{}},_sessionUsesServerMouseStrip(){const e=this.sessions?.get(this.activeSessionId)?.mode||"claude";return e==="claude"||e==="codex"||e==="gemini"},_terminalViewportAtBottom(){const e=this.terminal?.buffer?.active;return!e||e.viewportY>=e.baseY},_clientPointToCell(e,t){if(!this.terminal||!Number.isFinite(e)||!Number.isFinite(t))return null;const s=this.terminal.element?.querySelector(".xterm-screen"),i=this.terminal._core?._renderService?.dimensions?.css?.cell;if(!s||!i?.width||!i?.height)return null;const r=s.getBoundingClientRect(),a=Math.max(1,Math.min(this.terminal.cols,Math.floor((e-r.left)/i.width)+1)),n=Math.max(1,Math.min(this.terminal.rows,Math.floor((t-r.top)/i.height)+1));return{col:a,row:n}},_sendSyntheticSgrTap(e,t){if(!this.activeSessionId||!this._terminalViewportAtBottom())return;const s=this._clientPointToCell(e,t);s&&this._sendInputAsync(this.activeSessionId,`\x1B[<0;${s.col};${s.row}M\x1B[<0;${s.col};${s.row}m`)},_cliVersionAtLeast(e,t){if(typeof e!="string")return!1;const s=e.trim().replace(/^v/,"").split(".").map(Number);if(s.length!==3||s.some(r=>!Number.isFinite(r)))return!1;const i=t.split(".").map(Number);for(let r=0;r<3;r++)if(s[r]!==i[r])return s[r]>i[r];return!0},_shouldForwardWheelToApp(e){if(e.shiftKey)return!1;const t=this.terminal?.modes?.mouseTrackingMode;if(t&&t!=="none")return!1;const s=this.sessions?.get(this.activeSessionId),i=s?.mode||"claude";if(i==="claude"){if(!this._cliVersionAtLeast(s?.cliVersion,"2.1.187"))return!1}else if(i!=="codex")return!1;return this._terminalViewportAtBottom()},_sendSyntheticSgrWheel(e,t,s){if(!this.activeSessionId||!s)return;const i=this._clientPointToCell(e,t);if(!i)return;const r=s<0?64:65,a=Math.min(Math.abs(s),5),n=this._wheelSgrQueue||"";n.length>512||(this._wheelSgrQueue=n+`\x1B[<${r};${i.col};${i.row}M`.repeat(a),!this._wheelSgrFlushTimer&&(this._wheelSgrFlushTimer=setTimeout(()=>this._flushWheelSgrQueue(),40)))},_flushWheelSgrQueue(){this._wheelSgrFlushTimer=null;const e=this._wheelSgrQueue;this._wheelSgrQueue="",e&&this.activeSessionId&&this._sendInputAsync(this.activeSessionId,e)},_handleDesktopTerminalClick(e){if(!this.terminal||!e?.isTrusted||e.button!==0||e.detail!==1||e.shiftKey||e.altKey||e.ctrlKey||e.metaKey)return;const t=this.terminal.modes?.mouseTrackingMode;t&&t!=="none"||this._sessionUsesServerMouseStrip()&&(this.terminal.hasSelection?.()||this._linkHovered||performance.now()<=(this._trustedTapMouseSuppressUntil||0)||e.target?.closest?.(".xterm-screen")&&this._sendSyntheticSgrTap(e.clientX,e.clientY))},_installMobileTapMouseGuard(){const e=this.terminal?.element;if(!e||e._codemanTapMouseGuardInstalled||typeof MobileDetection<"u"&&MobileDetection.isTouchDevice&&!MobileDetection.isTouchDevice())return;e._codemanTapMouseGuardInstalled=!0;const t=s=>{const i=this._trustedTapMouseSuppressUntil||0;!s.isTrusted||performance.now()>i||(s.preventDefault(),s.stopImmediatePropagation())};e.addEventListener("mousedown",t,!0),e.addEventListener("mouseup",t,!0)},_suppressTrustedTapMouseEvents(){const e=window.CodemanTerminalInput?.TOUCH_COMPAT_MOUSE_SUPPRESS_MS||450;this._trustedTapMouseSuppressUntil=performance.now()+e},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,t={}){this.fitAddon&&this.fitAddon.fit();const s=this.getTerminalDimensions();if(!s)return!1;const i=this._lastResizeDims,r=!i||i.cols!==s.cols||i.rows!==s.rows;this._lastResizeDims={cols:s.cols,rows:s.rows};const a=typeof MobileDetection<"u"&&MobileDetection.getDeviceType?MobileDetection.getDeviceType():window.innerWidth<430?"mobile":window.innerWidth<768?"tablet":"desktop";if(!t.forceHttp&&this._wsReady&&this._wsSessionId===e)try{const l={t:"z",c:s.cols,r:s.rows,v:a};return t.force&&(l.f=!0),this._ws.send(JSON.stringify(l)),r}catch{}const n={...s,viewportType:a};return t.force&&(n.force=!0),await fetch(`/api/sessions/${e}/resize`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)}),r},async sendInput(e){!this.activeSessionId||!e||this._sendInputAsync(this.activeSessionId,e,{useMux:!0})},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)},applyTerminalSkin(e){const t={...window.CODEMAN_XTERM_THEMES[e]||window.CODEMAN_XTERM_THEMES["daylight-blue"]};if(this.terminal){this.terminal.options.theme=t;try{this.terminal.refresh(0,this.terminal.rows-1)}catch{}}if(this.teammateTerminals){for(const[,s]of this.teammateTerminals)if(s&&s.terminal){s.terminal.options.theme={...t};try{s.terminal.refresh(0,s.terminal.rows-1)}catch{}}}}}),(function(e){const i={session:"Sessions",event:"Events",file:"Files"};function r(a){if(!Number.isFinite(a))return"";const n=new Date(a);return n.toLocaleDateString("en",{month:"short",day:"numeric"})+" "+n.toLocaleTimeString("en",{hour:"2-digit",minute:"2-digit",hour12:!1})}e.CodemanSearch={SEARCH_DEBOUNCE_MS:250,SEARCH_LIMIT:60,SOURCE_LABELS:i,formatSearchTime:r}})(window),Object.assign(CodemanApp.prototype,{initSearchPanel(){const e=document.getElementById("searchInput");if(!e||this._searchPanelWired){this._searchPanelWired&&this._populateSearchCaseFilter();return}this._searchPanelWired=!0,this._searchTypes=new Set(["session","event","file"]),this._searchSecondary={caseLabel:"",status:"",days:""},this._searchDebounceTimer=null,this._searchSeq=0,this._searchLastData=null;const t=document.getElementById("searchClearBtn"),s=document.getElementById("searchResults");e.addEventListener("input",()=>{t&&(t.hidden=e.value.length===0),this._scheduleSearch()}),e.addEventListener("keydown",n=>{n.key==="Escape"&&e.value&&(n.stopPropagation(),this._clearSearch())}),t&&t.addEventListener("click",()=>this._clearSearch()),document.querySelectorAll("#searchFilters .search-filter-chip").forEach(n=>{n.addEventListener("click",()=>{const l=n.dataset.typeFilter;this._searchTypes.has(l)&&this._searchTypes.size===1||(this._searchTypes.has(l)?(this._searchTypes.delete(l),n.classList.remove("active")):(this._searchTypes.add(l),n.classList.add("active")),this._runSearch())})});const i=document.getElementById("searchCaseFilter"),r=document.getElementById("searchStatusFilter"),a=document.getElementById("searchDateFilter");i&&i.addEventListener("change",()=>{this._searchSecondary.caseLabel=i.value,this._renderSearch(this._searchLastData)}),r&&r.addEventListener("change",()=>{this._searchSecondary.status=r.value,this._renderSearch(this._searchLastData)}),a&&a.addEventListener("change",()=>{this._searchSecondary.days=a.value,this._renderSearch(this._searchLastData)}),this._populateSearchCaseFilter(),s&&(s.hidden=!0)},_populateSearchCaseFilter(){const e=document.getElementById("searchCaseFilter");if(!e)return;const t=Array.isArray(this.cases)?this.cases:[],s=Array.from(new Set(t.map(a=>a&&a.name).filter(Boolean))).sort(),i=e.value;e.innerHTML="";const r=document.createElement("option");r.value="",r.textContent="All cases",e.appendChild(r);for(const a of s){const n=document.createElement("option");n.value=a,n.textContent="#"+a,e.appendChild(n)}i&&s.includes(i)&&(e.value=i)},_scheduleSearch(){clearTimeout(this._searchDebounceTimer),this._searchDebounceTimer=setTimeout(()=>this._runSearch(),window.CodemanSearch.SEARCH_DEBOUNCE_MS)},_clearSearch(){const e=document.getElementById("searchInput"),t=document.getElementById("searchClearBtn");e&&(e.value=""),t&&(t.hidden=!0),this._searchLastData=null,this._renderSearch(null)},async _runSearch(){const e=document.getElementById("searchInput");if(!e)return;const t=e.value.trim();if(t.length===0){this._searchLastData=null,this._renderSearch(null);return}const s=Array.from(this._searchTypes),i=new URLSearchParams;i.set("q",t.slice(0,200)),s.length>0&&s.length<3&&i.set("types",s.join(",")),i.set("limit",String(window.CodemanSearch.SEARCH_LIMIT));const r=++this._searchSeq,a=await this._apiJson("/api/search?"+i.toString());r===this._searchSeq&&(a?this._searchLastData=a:this._searchLastData={query:t,groups:[],totalResults:0,truncated:!1,_error:!0},this._renderSearch(this._searchLastData))},_applySecondaryFilters(e){const{caseLabel:t,status:s,days:i}=this._searchSecondary;let r=e;if(t){const a="#"+t;r=r.filter(n=>(n.sessionName||"").includes(a)||n.sessionName===t)}if(s){const a=new Set((this.sessionOrder||[]).concat(Object.keys(this.sessions||{})));r=r.filter(n=>{const l=a.has(n.sessionId);return s==="active"?l:!l})}if(i){const a=Date.now()-Number(i)*24*60*60*1e3;r=r.filter(n=>Number.isFinite(n.timestamp)&&n.timestamp>=a)}return r},_renderSearch(e){const t=document.getElementById("searchResults"),s=document.getElementById("historyTitle"),i=document.getElementById("historyList");if(!t)return;const r=!!e;if(s&&(s.style.display=r?"none":""),i&&(i.style.display=r?"none":""),t.innerHTML="",!e){t.hidden=!0;return}if(t.hidden=!1,e._error){const l=document.createElement("div");l.className="search-empty",l.textContent="Search unavailable \u2014 check the query and try again.",t.appendChild(l);return}const a=(e.groups||[]).map(l=>({type:l.type,results:this._applySecondaryFilters(l.results||[])})).filter(l=>l.results.length>0);if(a.reduce((l,u)=>l+u.results.length,0)===0){const l=document.createElement("div");l.className="search-empty",l.textContent='No results for "'+(e.query||"")+'"',t.appendChild(l);return}for(const l of a){const u=document.createElement("div");u.className="search-group-header";const h=document.createElement("span");h.className="search-group-label",h.textContent=window.CodemanSearch.SOURCE_LABELS[l.type]||l.type;const c=document.createElement("span");c.className="search-group-count",c.textContent=String(l.results.length),u.append(h,c),t.appendChild(u);for(const f of l.results)t.appendChild(this._buildSearchResultCard(f))}if(e.truncated){const l=document.createElement("div");l.className="search-truncated",l.textContent="Showing the top matches \u2014 refine your search to narrow results.",t.appendChild(l)}},_buildSearchResultCard(e){const t=document.createElement("div");t.className="search-result-card",t.dataset.type=e.type,t.tabIndex=0,t.setAttribute("role","button");const s=document.createElement("div");s.className="search-result-top";const i=document.createElement("span");i.className="search-result-badge search-badge-"+e.type,i.textContent=(window.CodemanSearch.SOURCE_LABELS[e.type]||e.type).replace(/s$/,"");const r=document.createElement("span");r.className="search-result-name",r.textContent=e.sessionName||e.sessionId||"(session)";const a=document.createElement("span");a.className="search-result-time",a.textContent=window.CodemanSearch.formatSearchTime(e.timestamp),s.append(i,r,a);const n=document.createElement("div");n.className="search-result-snippet",n.textContent=e.snippet||"",t.append(s,n);const l=()=>this._jumpToSearchResult(e);return t.addEventListener("click",l),t.addEventListener("keydown",u=>{(u.key==="Enter"||u.key===" ")&&(u.preventDefault(),l())}),t},_jumpToSearchResult(e){const t=e&&e.jumpTo;if(t){typeof this.hideWelcome=="function"&&this.hideWelcome();try{t.kind==="run-summary"?this.openRunSummary(t.sessionId):t.kind==="file-preview"?this.openFilePreview(t.relativePath||"",t.sessionId,t.targetId||null):this.selectSession(t.sessionId)}catch(s){console.error("[search] jump failed",s)}}}});
|
|
Binary file
|
|
Binary file
|