tmux-weblink 2.2.48 → 2.2.50

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.
@@ -1,46 +1,46 @@
1
- var Gn=/\x1b\](?:10|11|110|111|104)(?:;[^\x07\x1b]*)?\x1b?(?:\\|\x07)/g;function ht(e){return e.replace(/\x1b\[\?1049[hl]/g,"")}function Se(e){return e.replace(Gn,"")}var Ue;function ei(){return Ue||(document.querySelector("link[data-tmux-web-xterm-css]")?Ue=Promise.resolve():(Ue=new Promise(e=>{let t=document.createElement("link");t.rel="stylesheet",t.href="/assets/xterm.css",t.setAttribute("data-tmux-web-xterm-css",""),t.addEventListener("load",()=>e(),{once:!0}),t.addEventListener("error",()=>e(),{once:!0}),document.head.appendChild(t)}),Ue))}var ti=class Tn{terminal;fitAddon;container;webglActive=!1;repaintTimer=0;webglAddon=null;constructor(t,n,i){this.container=t,this.terminal=n,this.fitAddon=i,this.terminal.loadAddon(this.fitAddon),this.terminal.open(t),this.enableWebglRenderer(),document.addEventListener("visibilitychange",()=>{document.hidden||this.refreshPaintedRows()})}enableWebglRenderer(){if(ii()==="webgl"){try{if(!document.createElement("canvas").getContext("webgl2",{failIfMajorPerformanceCaveat:!0}))return}catch{return}import("./addon-webgl-B45EJ6AW.js").then(({WebglAddon:t})=>{let n=new t;n.onContextLoss(()=>{this.webglActive=!1,this.webglAddon=null;try{n.dispose()}catch{}this.fit()});try{this.terminal.loadAddon(n)}catch{return}this.webglAddon=n,this.webglActive=!0,this.fit()}).catch(()=>{})}}refreshPaintedRows(){if(this.webglActive){try{this.webglAddon?.clearTextureAtlas?.()}catch{}try{this.terminal.refresh(0,Math.max(0,this.terminal.rows-1))}catch{}}}static async create(t,n,i){let[{Terminal:a},{FitAddon:r}]=await Promise.all([import("./xterm-BXEES47M.js"),import("./addon-fit-D5N335P2.js"),ei()]),s="'JetBrains Mono', 'SF Mono', 'Menlo', monospace",l=new a({fontSize:ni(14,s),fontFamily:s,cursorBlink:!0,cursorStyle:"bar",scrollback:n,convertEol:!1,smoothScrollDuration:120,theme:i});return new Tn(t,l,new r)}get cols(){return this.terminal.cols}get rows(){return this.terminal.rows}write(t){return new Promise(n=>this.terminal.write(t,n))}reset(){this.terminal.reset()}scrollToBottom(){this.terminal.scrollToBottom()}scrollToLine(t,n=!1){this.terminal.scrollToLine(Math.max(0,t),n),this.scheduleRepaintCheck()}scrollLines(t){this.terminal.scrollLines(t),this.scheduleRepaintCheck()}scheduleRepaintCheck(){this.webglActive&&(this.repaintTimer&&clearTimeout(this.repaintTimer),this.repaintTimer=setTimeout(()=>{this.repaintTimer=0,this.refreshPaintedRows()},150))}isNearScrollbackTop(){return this.terminal.buffer.active.viewportY<=1}viewportY(){return this.terminal.buffer.active.viewportY}baseY(){return this.terminal.buffer.active.baseY}cellHeight(){let t=this.terminal.element?.querySelector(".xterm-screen")?.getBoundingClientRect().height??0,n=this.terminal.rows;return t>0&&n>0?t/n:16}fit(){let t=ai(this.container);if(t.width<=0||t.height<=0)return!1;let n=this.terminal.cols,i=this.terminal.rows,a=this.paintedCellWidth();a<=0&&(this.fitAddon.fit(),a=this.paintedCellWidth());let r=this.fitAddon.proposeDimensions?.();if(!r)return this.fitAddon.fit(),!0;let s=this.overlayScrollbarWidth(),l=s>0?s+2:0,p=a>0?Math.max(10,Math.min(r.cols,Math.floor((t.width-l)/a))):r.cols,u=r.rows;return(p!==this.terminal.cols||u!==this.terminal.rows)&&this.terminal.resize(p,u),this.webglActive&&(n!==this.terminal.cols||i!==this.terminal.rows)&&this.refreshPaintedRows(),!0}paintedCellWidth(){let t=this.terminal.element?.querySelector(".xterm-screen")?.getBoundingClientRect().width??0,n=this.terminal.cols;return t>0&&n>0?t/n:0}overlayScrollbarWidth(){let t=this.terminal.element?.querySelector(".vertical.scrollbar");if(!t)return 0;let n=t.getBoundingClientRect();return!(n.width>0)||!(n.height>0)?0:Math.round(n.width)}focus(){this.terminal.focus()}pasteText(t){this.terminal.paste(t)}input(t){this.terminal.input(t,!1)}onData(t){this.terminal.onData(t),this.terminal.onBinary(t)}onResize(t){this.terminal.onResize(t)}onScroll(t){this.terminal.onScroll(t)}attachCustomKeyEventHandler(t){this.terminal.attachCustomKeyEventHandler(t)}isFocused(){let t=document.activeElement;return t?t===this.container||t===this.terminal.textarea||this.container.contains(t)||!!t.closest?.(".xterm"):!1}getScreenText(){return this.getRowsText(0,this.terminal.rows-1)}getRowsText(t,n){let i=this.terminal.buffer.active,[a,r]=t<=n?[t,n]:[n,t],s=i.viewportY,l=[];for(let p=a;p<=r;p++){let u=i.getLine(s+p);l.push(u?u.translateToString(!0):"")}return l.join(`
2
- `)}selectRows(t,n){let i=this.terminal.buffer.active,[a,r]=t<=n?[t,n]:[n,t];this.terminal.selectLines(i.viewportY+a,i.viewportY+r)}selectCells(t,n,i,a){let r=this.terminal.buffer.active,s=Math.min(n,a),l=Math.max(n,a);if(s===l){let p=Math.min(t,i),u=Math.max(t,i);this.terminal.select(p,r.viewportY+s,u-p+1)}else this.terminal.selectLines(r.viewportY+s,r.viewportY+l)}getCellsText(t,n,i,a){let r=this.terminal.buffer.active,s=Math.min(n,a),l=Math.max(n,a),p=n<a?t:n>a?i:Math.min(t,i),u=n<a?i:n>a?t:Math.max(t,i),v=r.viewportY,b=[];for(let D=s;D<=l;D++){let x=r.getLine(v+D);if(!x){b.push("");continue}let w=D===s?p:0,g=D===l?u:this.terminal.cols-1,A="";for(let W=w;W<=g;W++){let O=x.getCell(W);O&&(A+=O.getChars())}b.push(A.replace(/\s+$/,""))}return b.join(`
3
- `)}getSelection(){return this.terminal.getSelection()}clearSelection(){this.terminal.clearSelection()}hasSelectionSupport(){return!0}};function ni(e,t){try{let n=document.createElement("canvas").getContext("2d");if(!n)return e;let i=100;n.font=`${i}px ${t}`;let a=n.measureText("M").width/i;if(!Number.isFinite(a)||a<=0)return e;let r=window.devicePixelRatio||1,s=e,l=Number.POSITIVE_INFINITY;for(let p=4;p<=40;p++){let u=p/(a*r);if(u<e-1.5||u>e+1.5)continue;let v=Math.abs(u-e);v<l&&(l=v,s=u)}return Math.round(s*100)/100}catch{return e}}function ii(){try{let e=new URLSearchParams(window.location.search).get("renderer");return e==="dom"||e==="webgl"?e:null}catch{return null}}function ai(e){let t=e.getBoundingClientRect(),n=window.visualViewport;return n?{width:Math.min(t.width,n.width),height:Math.max(0,Math.min(t.height,n.height-Math.max(0,t.top)))}:t}function si(e,t,n){return e.innerHTML="",e.classList.add("terminal-pending"),(async()=>{let i=await ti.create(e,n.scrollback,n.theme),a,r=0,s,l=null,p=0,u=0,v=.2,b=10,D=.95,x=.04,w=null,g=null;function A(o){w||(w=document.createElement("div"),w.style.cssText=["position:absolute","left:0","width:40%","padding:10px 0","text-align:center","font:600 14px/1.4 system-ui, -apple-system, sans-serif","color:rgba(255,255,255,0.95)","background:rgba(20,30,50,0.55)","border:1px solid rgba(255,255,255,0.25)","border-radius:10px","pointer-events:none","opacity:0","transition:opacity 0.15s ease","z-index:6"].join(";"),e.appendChild(w)),w.textContent=o?"\u2191 \u4E0A\u7FFB\u4E00\u9875 (PgUp)":"\u2193 \u4E0B\u7FFB\u4E00\u9875 (PgDn)",w.style.top=o?"10%":"auto",w.style.bottom=o?"auto":"10%",w.style.opacity="1",g&&clearTimeout(g),g=setTimeout(()=>{w&&(w.style.opacity="0")},900)}function W(){g&&clearTimeout(g),w&&(w.style.opacity="0")}function O(){p&&(cancelAnimationFrame(p),p=0),u=0}function _(o){if(O(),Math.abs(o)<v)return;u=Math.max(-b,Math.min(b,o));let d=()=>{if(B){p=0;return}let f=i.cellHeight(),E=f>0?Math.round(u*16/f):u>0?1:-1;E===0&&(E=u>0?1:-1);let I=i.viewportY()-E,ee=i.baseY(),oe=Math.max(0,Math.min(I,ee));if(i.scrollToLine(oe,!0),u*=D,oe!==I){p=0;return}if(Math.abs(u)<x){p=0;return}p=requestAnimationFrame(d)};p=requestAnimationFrame(d)}let Z=0,y="connecting",S=0,G=!1,h=[],z="",B=!1,le=1e3,$=location.protocol==="https:"?"wss:":"ws:",$t=n.wsBase||"/ws",Mn=$+"//"+location.host+$t+"/"+encodeURIComponent(t),Dn=($t.replace(/^\/ws/,"")||"")+"/api/session/"+encodeURIComponent(t)+"/upload",An=/^((?!chrome|android|crios|fxios|edgios).)*safari/i.test(navigator.userAgent);function Fn(){return h.join("")+z}async function $n(o,d=0){let f=o?i.viewportY():0,E=Se(Fn());if(i.reset(),!E){o||i.scrollToBottom();return}await i.write(E),o?i.scrollToLine(d+f):i.scrollToBottom()}function re(o){a?.readyState===WebSocket.OPEN&&a.send(JSON.stringify(o))}function Pn(o){let d;try{d=JSON.parse(o)}catch{y==="live"&&(z+=o,i.write(Se(o)));return}if(d.type==="auth.required"){let f=localStorage.getItem("tmux-web-token");f?re({type:"auth.token",token:f}):location.href="/login?returnTo="+encodeURIComponent(location.pathname+location.search);return}if(d.type==="attach_failed"&&typeof d.message=="string"){je=!0,y="dead",i.reset(),i.write(`\r
4
- \x1B[31m`+Se(d.message)+`\x1B[0m\r
5
- `).then(()=>{He();try{a?.close()}catch{}});return}if(d.type==="auth.ok"){d.token&&localStorage.setItem("tmux-web-token",d.token),le=1e3,de(),re({type:"resize",cols:i.cols,rows:i.rows}),U();return}if(d.type==="auth.failed"){if(d.permanentLock||d.retryAfterMs&&d.retryAfterMs>6e4){localStorage.removeItem("tmux-web-token"),location.href="/login?error="+encodeURIComponent(d.message);return}return}if(d.type==="snapshot"&&typeof d.data=="string"){let f=ht(Se(d.data));h=[f],z="",S=typeof d.lines=="number"?d.lines:n.terminal.initialLines,y="live",i.reset(),de(),re({type:"resize",cols:i.cols,rows:i.rows}),i.write(f).then(()=>i.scrollToBottom());return}if(d.type==="window_changed"&&typeof d.activeIndex=="number"){let f=new URL(location.href);f.searchParams.get("window")!==String(d.activeIndex)&&(f.searchParams.set("window",String(d.activeIndex)),history.replaceState(history.state,"",f)),window.dispatchEvent(new CustomEvent("tmux:windows",{detail:d.windows}));return}if(d.type==="history"&&typeof d.data=="string"){d.lines>0&&d.data?(h.unshift(ht(d.data)),S+=d.lines,$n(!0,d.lines).finally(()=>{G=!1})):G=!1;return}if(d.type==="data"&&typeof d.data=="string"){let f=ht(Se(d.data));if(y==="connecting"){y="live",z=f,i.write(f);return}y==="live"&&(z+=f,i.write(f))}}let je=!1;function Pt(){if(je)return;let o=Mn,d=localStorage.getItem("tmux-web-token");d&&(o+=(o.includes("?")?"&":"?")+"token="+encodeURIComponent(d)),o+=(o.includes("?")?"&":"?")+"cols="+i.cols+"&rows="+i.rows,a=new WebSocket(o),a.onopen=()=>{y="connecting",S=0,G=!1,h=[],z="",i.reset(),le=1e3},a.onmessage=f=>{typeof f.data=="string"&&Pn(f.data)},a.onclose=()=>{B||(y="connecting",!je&&setTimeout(()=>{le=Math.min(le*2,1e4),!B&&!je&&Pt()},le))},a.onerror=()=>a?.close()}function he(o){re({type:"input",data:o})}function de(){return i.fit()}function He(){e.classList.remove("terminal-pending")}function U(){r&&cancelAnimationFrame(r),s&&clearTimeout(s),de(),r=requestAnimationFrame(()=>{r=0,de()&&He()}),s=setTimeout(()=>{de()&&He()},120)}function Nn(){U(),setTimeout(U,50),setTimeout(U,150),setTimeout(U,300)}function Nt(o){return typeof o=="string"&&o.startsWith("image/")}function Ot(o){return o?.files?.length?o.files[0]??null:null}function On(o){if(!o?.items)return null;for(let d=0;d<o.items.length;d++){let f=o.items[d];if(f?.kind==="file"&&Nt(f.type))return f.getAsFile()}return null}async function jn(o){let d=new FormData,f=o instanceof File&&o.name?o.name:"upload";d.append("file",o,f);let E=localStorage.getItem("tmux-web-token"),I={};E&&(I.Authorization="Bearer "+E);let ee=await fetch(Dn,{method:"POST",body:d,headers:I});if(!ee.ok){let Wt="upload failed";try{let Jt=await ee.json();Jt.error&&(Wt=Jt.error)}catch{}throw new Error(Wt)}let oe=await ee.json();if(!oe.path)throw new Error("no path in response");return oe.path}async function pt(o){try{let d=await jn(o);he(d)}catch{}}i.onData(o=>he(o)),i.onResize(({cols:o,rows:d})=>re({type:"resize",cols:o,rows:d})),i.onScroll(()=>{y!=="live"||G||!i.isNearScrollbackTop()||(G=!0,re({type:"load_history",before:S}))});let we=!1,Ee=!1,P=null,j=null,ke=document.createElement("div");ke.className="terminal-copy-banner",ke.innerHTML='<strong>Copy mode</strong><span class="hint">drag to copy \xB7 Esc exits</span>',ke.hidden=!0,e.appendChild(ke);let ne=document.createElement("div");ne.className="terminal-copy-banner terminal-copy-toast",ne.textContent="Copied",ne.hidden=!0,e.appendChild(ne);function jt(o,d){let f=e.querySelector(".xterm-screen, canvas"),E=(f&&f.getBoundingClientRect().width>0?f:e).getBoundingClientRect(),I=E.height>0&&i.rows>0?E.height/i.rows:18,ee=E.width>0&&i.cols>0?E.width/i.cols:9;return{row:Math.max(0,Math.min(i.rows-1,Math.floor((d-E.top)/I))),col:Math.max(0,Math.min(i.cols-1,Math.floor((o-E.left)/ee)))}}async function Re(o){if(!o)return;try{if(navigator.clipboard?.writeText){await navigator.clipboard.writeText(o);return}}catch{}let d=document.createElement("textarea");d.value=o,d.style.position="fixed",d.style.opacity="0",d.style.pointerEvents="none",document.body.appendChild(d),d.focus(),d.select();try{document.execCommand("copy")}catch{}d.remove()}let Ce;function _e(){ne.hidden=!1,Ce&&clearTimeout(Ce),Ce=setTimeout(()=>{ne.hidden=!0},1e3)}function ve(o){we=o,ke.hidden=!o,e.classList.toggle("terminal-copy-mode-active",o),o&&i.focus()}function Ht(){ve(!we)}function Hn(o){B||o.button!==0||Ee||(we||o.shiftKey)&&(o.preventDefault(),o.stopPropagation(),Ee=!0,P=jt(o.clientX,o.clientY),j=P,i.selectCells(P.col,P.row,j.col,j.row),document.addEventListener("mousemove",mt,!0),document.addEventListener("mouseup",ft,!0))}function mt(o){B||!Ee||!P||(o.preventDefault(),o.stopPropagation(),j=jt(o.clientX,o.clientY),i.selectCells(P.col,P.row,j.col,j.row))}function ft(o){if(B||!Ee||!P||!j)return;o.preventDefault(),o.stopPropagation(),document.removeEventListener("mousemove",mt,!0),document.removeEventListener("mouseup",ft,!0),Ee=!1;let d=i.getCellsText(P.col,P.row,j.col,j.row);P=null,j=null,i.clearSelection(),ve(!1),d&&(ne.textContent="\u5DF2\u590D\u5236",Re(d).then(_e)),i.focus()}e.addEventListener("mousedown",Hn,!0),document.addEventListener("keydown",Rn,!0);function Rn(o){if(!(B||!i.isFocused()||o.defaultPrevented||o.isComposing)){if(we){if(o.key==="Escape"){o.preventDefault(),o.stopPropagation(),P=null,j=null,i.clearSelection(),ve(!1);return}if(o.key==="Enter"||(o.ctrlKey||o.metaKey)&&o.code==="KeyC"){o.preventDefault(),o.stopPropagation(),Re(i.getScreenText()).then(_e),ve(!1);return}}if(o.altKey&&o.code==="KeyC"&&!o.ctrlKey&&!o.metaKey){if(o.preventDefault(),o.stopPropagation(),P&&j){let d=i.getCellsText(P.col,P.row,j.col,j.row);P=null,j=null,i.clearSelection(),ve(!1),d&&(ne.textContent="Copied",Re(d).then(_e))}else{let d=i.getSelection();d?(i.clearSelection(),ne.textContent="Copied",Re(d).then(_e)):Ht()}return}if((o.ctrlKey||o.metaKey)&&o.code==="KeyV"){o.preventDefault(),o.stopPropagation(),(async()=>{try{if(navigator.clipboard?.read){let d=await navigator.clipboard.read();for(let f of d)for(let E of f.types)if(Nt(E)){let I=await f.getType(E);await pt(I);return}}}catch{}try{let d=await navigator.clipboard?.readText();d&&i.pasteText(Rt(d))}catch{}})();return}}}let ze=0;function Rt(o){return o.split(`\r
1
+ var ni=/\x1b\](?:10|11|110|111|104)(?:;[^\x07\x1b]*)?\x1b?(?:\\|\x07)/g;function gt(e){return e.replace(/\x1b\[\?1049[hl]/g,"")}function Me(e){return e.replace(ni,"")}var qe;function ii(){return qe||(document.querySelector("link[data-tmux-web-xterm-css]")?qe=Promise.resolve():(qe=new Promise(e=>{let t=document.createElement("link");t.rel="stylesheet",t.href="/assets/xterm.css",t.setAttribute("data-tmux-web-xterm-css",""),t.addEventListener("load",()=>e(),{once:!0}),t.addEventListener("error",()=>e(),{once:!0}),document.head.appendChild(t)}),qe))}var ai=class Hn{terminal;fitAddon;container;webglActive=!1;repaintTimer=0;webglAddon=null;constructor(t,n,i){this.container=t,this.terminal=n,this.fitAddon=i,this.terminal.loadAddon(this.fitAddon),this.terminal.open(t),this.enableWebglRenderer(),document.addEventListener("visibilitychange",()=>{document.hidden||this.refreshPaintedRows()})}enableWebglRenderer(){if(si()==="webgl"){try{if(!document.createElement("canvas").getContext("webgl2",{failIfMajorPerformanceCaveat:!0}))return}catch{return}import("./addon-webgl-B45EJ6AW.js").then(({WebglAddon:t})=>{let n=new t;n.onContextLoss(()=>{this.webglActive=!1,this.webglAddon=null;try{n.dispose()}catch{}this.fit()});try{this.terminal.loadAddon(n)}catch{return}this.webglAddon=n,this.webglActive=!0,this.fit()}).catch(()=>{})}}refreshPaintedRows(){if(this.webglActive){try{this.webglAddon?.clearTextureAtlas?.()}catch{}try{this.terminal.refresh(0,Math.max(0,this.terminal.rows-1))}catch{}}}static async create(t,n,i){let[{Terminal:a},{FitAddon:r}]=await Promise.all([import("./xterm-BXEES47M.js"),import("./addon-fit-D5N335P2.js"),ii()]),o="'JetBrains Mono', 'SF Mono', 'Menlo', monospace",l=new a({fontSize:oi(14,o),fontFamily:o,cursorBlink:!0,cursorStyle:"bar",scrollback:n,convertEol:!1,smoothScrollDuration:120,theme:i});return new Hn(t,l,new r)}get cols(){return this.terminal.cols}get rows(){return this.terminal.rows}write(t){return new Promise(n=>this.terminal.write(t,n))}reset(){this.terminal.reset()}scrollToBottom(){this.terminal.scrollToBottom()}scrollToLine(t,n=!1){this.terminal.scrollToLine(Math.max(0,t),n),this.scheduleRepaintCheck()}scrollLines(t){this.terminal.scrollLines(t),this.scheduleRepaintCheck()}scheduleRepaintCheck(){this.webglActive&&(this.repaintTimer&&clearTimeout(this.repaintTimer),this.repaintTimer=setTimeout(()=>{this.repaintTimer=0,this.refreshPaintedRows()},150))}isNearScrollbackTop(){return this.terminal.buffer.active.viewportY<=1}viewportY(){return this.terminal.buffer.active.viewportY}baseY(){return this.terminal.buffer.active.baseY}cellHeight(){let t=this.terminal.element?.querySelector(".xterm-screen")?.getBoundingClientRect().height??0,n=this.terminal.rows;return t>0&&n>0?t/n:16}fit(){let t=li(this.container);if(t.width<=0||t.height<=0)return!1;let n=this.terminal.cols,i=this.terminal.rows,a=this.paintedCellWidth();a<=0&&(this.fitAddon.fit(),a=this.paintedCellWidth());let r=this.fitAddon.proposeDimensions?.();if(!r)return this.fitAddon.fit(),!0;let o=this.overlayScrollbarWidth(),l=o>0?o+2:0,u=a>0?Math.max(10,Math.min(r.cols,Math.floor((t.width-l)/a))):r.cols,p=r.rows;return(u!==this.terminal.cols||p!==this.terminal.rows)&&this.terminal.resize(u,p),this.webglActive&&(n!==this.terminal.cols||i!==this.terminal.rows)&&this.refreshPaintedRows(),!0}paintedCellWidth(){let t=this.terminal.element?.querySelector(".xterm-screen")?.getBoundingClientRect().width??0,n=this.terminal.cols;return t>0&&n>0?t/n:0}overlayScrollbarWidth(){let t=this.terminal.element?.querySelector(".vertical.scrollbar");if(!t)return 0;let n=t.getBoundingClientRect();return!(n.width>0)||!(n.height>0)?0:Math.round(n.width)}focus(){this.terminal.focus()}pasteText(t){this.terminal.paste(t)}input(t){this.terminal.input(t,!1)}onData(t){this.terminal.onData(t),this.terminal.onBinary(t)}onResize(t){this.terminal.onResize(t)}onScroll(t){this.terminal.onScroll(t)}attachCustomKeyEventHandler(t){this.terminal.attachCustomKeyEventHandler(t)}isFocused(){let t=document.activeElement;return t?t===this.container||t===this.terminal.textarea||this.container.contains(t)||!!t.closest?.(".xterm"):!1}getScreenText(){return this.getRowsText(0,this.terminal.rows-1)}getRowsText(t,n){let i=this.terminal.buffer.active,[a,r]=t<=n?[t,n]:[n,t],o=i.viewportY,l=[];for(let u=a;u<=r;u++){let p=i.getLine(o+u);l.push(p?p.translateToString(!0):"")}return l.join(`
2
+ `)}selectRows(t,n){let i=this.terminal.buffer.active,[a,r]=t<=n?[t,n]:[n,t];this.terminal.selectLines(i.viewportY+a,i.viewportY+r)}selectCells(t,n,i,a){let r=this.terminal.buffer.active,o=Math.min(n,a),l=Math.max(n,a);if(o===l){let u=Math.min(t,i),p=Math.max(t,i);this.terminal.select(u,r.viewportY+o,p-u+1)}else this.terminal.selectLines(r.viewportY+o,r.viewportY+l)}getCellsText(t,n,i,a){let r=this.terminal.buffer.active,o=Math.min(n,a),l=Math.max(n,a),u=n<a?t:n>a?i:Math.min(t,i),p=n<a?i:n>a?t:Math.max(t,i),f=r.viewportY,y=[];for(let H=o;H<=l;H++){let L=r.getLine(f+H);if(!L){y.push("");continue}let w=H===o?u:0,g=H===l?p:this.terminal.cols-1,M="";for(let W=w;W<=g;W++){let P=L.getCell(W);P&&(M+=P.getChars())}y.push(M.replace(/\s+$/,""))}return y.join(`
3
+ `)}getSelection(){return this.terminal.getSelection()}clearSelection(){this.terminal.clearSelection()}hasSelectionSupport(){return!0}};function oi(e,t){try{let n=document.createElement("canvas").getContext("2d");if(!n)return e;let i=100;n.font=`${i}px ${t}`;let a=n.measureText("M").width/i;if(!Number.isFinite(a)||a<=0)return e;let r=window.devicePixelRatio||1,o=e,l=Number.POSITIVE_INFINITY;for(let u=4;u<=40;u++){let p=u/(a*r);if(p<e-1.5||p>e+1.5)continue;let f=Math.abs(p-e);f<l&&(l=f,o=p)}return Math.round(o*100)/100}catch{return e}}function si(){try{let e=new URLSearchParams(window.location.search).get("renderer");return e==="dom"||e==="webgl"?e:null}catch{return null}}function li(e){let t=e.getBoundingClientRect(),n=window.visualViewport;return n?{width:Math.min(t.width,n.width),height:Math.max(0,Math.min(t.height,n.height-Math.max(0,t.top)))}:t}function ri(e,t,n){return e.innerHTML="",e.classList.add("terminal-pending"),(async()=>{let i=await ai.create(e,n.scrollback,n.theme),a,r=0,o,l=null,u=0,p=0,f=.2,y=10,H=.95,L=.04,w=null,g=null;function M(s){w||(w=document.createElement("div"),w.style.cssText=["position:absolute","left:0","width:40%","padding:10px 0","text-align:center","font:600 14px/1.4 system-ui, -apple-system, sans-serif","color:rgba(255,255,255,0.95)","background:rgba(20,30,50,0.55)","border:1px solid rgba(255,255,255,0.25)","border-radius:10px","pointer-events:none","opacity:0","transition:opacity 0.15s ease","z-index:6"].join(";"),e.appendChild(w)),w.textContent=s?"\u2191 \u4E0A\u7FFB\u4E00\u9875 (PgUp)":"\u2193 \u4E0B\u7FFB\u4E00\u9875 (PgDn)",w.style.top=s?"10%":"auto",w.style.bottom=s?"auto":"10%",w.style.opacity="1",g&&clearTimeout(g),g=setTimeout(()=>{w&&(w.style.opacity="0")},900)}function W(){g&&clearTimeout(g),w&&(w.style.opacity="0")}function P(){u&&(cancelAnimationFrame(u),u=0),p=0}function j(s){if(P(),Math.abs(s)<f)return;p=Math.max(-y,Math.min(y,s));let d=()=>{if(B){u=0;return}let h=i.cellHeight(),E=h>0?Math.round(p*16/h):p>0?1:-1;E===0&&(E=p>0?1:-1);let I=i.viewportY()-E,ee=i.baseY(),se=Math.max(0,Math.min(I,ee));if(i.scrollToLine(se,!0),p*=H,se!==I){u=0;return}if(Math.abs(p)<L){u=0;return}u=requestAnimationFrame(d)};u=requestAnimationFrame(d)}let R=0,b="connecting",x=0,G=!1,v=[],_="",B=!1,le=1e3,A=location.protocol==="https:"?"wss:":"ws:",$t=n.wsBase||"/ws",Dn=A+"//"+location.host+$t+"/"+encodeURIComponent(t),An=($t.replace(/^\/ws/,"")||"")+"/api/session/"+encodeURIComponent(t)+"/upload",Fn=/^((?!chrome|android|crios|fxios|edgios).)*safari/i.test(navigator.userAgent);function $n(){return v.join("")+_}async function Pn(s,d=0){let h=s?i.viewportY():0,E=Me($n());if(i.reset(),!E){s||i.scrollToBottom();return}await i.write(E),s?i.scrollToLine(d+h):i.scrollToBottom()}function re(s){a?.readyState===WebSocket.OPEN&&a.send(JSON.stringify(s))}function Nn(s){let d;try{d=JSON.parse(s)}catch{b==="live"&&(_+=s,i.write(Me(s)));return}if(d.type==="auth.required"){let h=localStorage.getItem("tmux-web-token");h?re({type:"auth.token",token:h}):location.href="/login?returnTo="+encodeURIComponent(location.pathname+location.search);return}if(d.type==="attach_failed"&&typeof d.message=="string"){je=!0,b="dead",i.reset(),i.write(`\r
4
+ \x1B[31m`+Me(d.message)+`\x1B[0m\r
5
+ `).then(()=>{Re();try{a?.close()}catch{}});return}if(d.type==="auth.ok"){d.token&&localStorage.setItem("tmux-web-token",d.token),le=1e3,de(),re({type:"resize",cols:i.cols,rows:i.rows}),U();return}if(d.type==="auth.failed"){if(d.permanentLock||d.retryAfterMs&&d.retryAfterMs>6e4){localStorage.removeItem("tmux-web-token"),location.href="/login?error="+encodeURIComponent(d.message);return}return}if(d.type==="snapshot"&&typeof d.data=="string"){let h=gt(Me(d.data));v=[h],_="",x=typeof d.lines=="number"?d.lines:n.terminal.initialLines,b="live",i.reset(),de(),re({type:"resize",cols:i.cols,rows:i.rows}),i.write(h).then(()=>i.scrollToBottom());return}if(d.type==="window_changed"&&typeof d.activeIndex=="number"){let h=new URL(location.href);h.searchParams.get("window")!==String(d.activeIndex)&&(h.searchParams.set("window",String(d.activeIndex)),history.replaceState(history.state,"",h)),window.dispatchEvent(new CustomEvent("tmux:windows",{detail:d.windows}));return}if(d.type==="history"&&typeof d.data=="string"){d.lines>0&&d.data?(v.unshift(gt(d.data)),x+=d.lines,Pn(!0,d.lines).finally(()=>{G=!1})):G=!1;return}if(d.type==="data"&&typeof d.data=="string"){let h=gt(Me(d.data));if(b==="connecting"){b="live",_=h,i.write(h);return}b==="live"&&(_+=h,i.write(h))}}let je=!1;function Pt(){if(je)return;let s=Dn,d=localStorage.getItem("tmux-web-token");d&&(s+=(s.includes("?")?"&":"?")+"token="+encodeURIComponent(d)),s+=(s.includes("?")?"&":"?")+"cols="+i.cols+"&rows="+i.rows,a=new WebSocket(s),a.onopen=()=>{b="connecting",x=0,G=!1,v=[],_="",i.reset(),le=1e3},a.onmessage=h=>{typeof h.data=="string"&&Nn(h.data)},a.onclose=()=>{B||(b="connecting",!je&&setTimeout(()=>{le=Math.min(le*2,1e4),!B&&!je&&Pt()},le))},a.onerror=()=>a?.close()}function fe(s){re({type:"input",data:s})}function de(){return i.fit()}function Re(){e.classList.remove("terminal-pending")}function U(){r&&cancelAnimationFrame(r),o&&clearTimeout(o),de(),r=requestAnimationFrame(()=>{r=0,de()&&Re()}),o=setTimeout(()=>{de()&&Re()},120)}function Vn(){U(),setTimeout(U,50),setTimeout(U,150),setTimeout(U,300)}function Nt(s){return typeof s=="string"&&s.startsWith("image/")}function Vt(s){return s?.files?.length?s.files[0]??null:null}function On(s){if(!s?.items)return null;for(let d=0;d<s.items.length;d++){let h=s.items[d];if(h?.kind==="file"&&Nt(h.type))return h.getAsFile()}return null}async function jn(s){let d=new FormData,h=s instanceof File&&s.name?s.name:"upload";d.append("file",s,h);let E=localStorage.getItem("tmux-web-token"),I={};E&&(I.Authorization="Bearer "+E);let ee=await fetch(An,{method:"POST",body:d,headers:I});if(!ee.ok){let qt="upload failed";try{let Jt=await ee.json();Jt.error&&(qt=Jt.error)}catch{}throw new Error(qt)}let se=await ee.json();if(!se.path)throw new Error("no path in response");return se.path}async function ht(s){try{let d=await jn(s);fe(d)}catch{}}i.onData(s=>fe(s)),i.onResize(({cols:s,rows:d})=>re({type:"resize",cols:s,rows:d})),i.onScroll(()=>{b!=="live"||G||!i.isNearScrollbackTop()||(G=!0,re({type:"load_history",before:x}))});let ke=!1,Ce=!1,F=null,N=null,Le=document.createElement("div");Le.className="terminal-copy-banner",Le.innerHTML='<strong>Copy mode</strong><span class="hint">drag to copy \xB7 Esc exits</span>',Le.hidden=!0,e.appendChild(Le);let ne=document.createElement("div");ne.className="terminal-copy-banner terminal-copy-toast",ne.textContent="Copied",ne.hidden=!0,e.appendChild(ne);function Ot(s,d){let h=e.querySelector(".xterm-screen, canvas"),E=(h&&h.getBoundingClientRect().width>0?h:e).getBoundingClientRect(),I=E.height>0&&i.rows>0?E.height/i.rows:18,ee=E.width>0&&i.cols>0?E.width/i.cols:9;return{row:Math.max(0,Math.min(i.rows-1,Math.floor((d-E.top)/I))),col:Math.max(0,Math.min(i.cols-1,Math.floor((s-E.left)/ee)))}}async function _e(s){if(!s)return;try{if(navigator.clipboard?.writeText){await navigator.clipboard.writeText(s);return}}catch{}let d=document.createElement("textarea");d.value=s,d.style.position="fixed",d.style.opacity="0",d.style.pointerEvents="none",document.body.appendChild(d),d.focus(),d.select();try{document.execCommand("copy")}catch{}d.remove()}let xe;function Ue(){ne.hidden=!1,xe&&clearTimeout(xe),xe=setTimeout(()=>{ne.hidden=!0},1e3)}function ge(s){ke=s,Le.hidden=!s,e.classList.toggle("terminal-copy-mode-active",s),s&&i.focus()}function jt(){ge(!ke)}function Rn(s){B||s.button!==0||Ce||(ke||s.shiftKey)&&(s.preventDefault(),s.stopPropagation(),Ce=!0,F=Ot(s.clientX,s.clientY),N=F,i.selectCells(F.col,F.row,N.col,N.row),document.addEventListener("mousemove",vt,!0),document.addEventListener("mouseup",ft,!0))}function vt(s){B||!Ce||!F||(s.preventDefault(),s.stopPropagation(),N=Ot(s.clientX,s.clientY),i.selectCells(F.col,F.row,N.col,N.row))}function ft(s){if(B||!Ce||!F||!N)return;s.preventDefault(),s.stopPropagation(),document.removeEventListener("mousemove",vt,!0),document.removeEventListener("mouseup",ft,!0),Ce=!1;let d=i.getCellsText(F.col,F.row,N.col,N.row);F=null,N=null,i.clearSelection(),ge(!1),d&&(ne.textContent="\u5DF2\u590D\u5236",_e(d).then(Ue)),i.focus()}e.addEventListener("mousedown",Rn,!0),document.addEventListener("keydown",_n,!0);function _n(s){if(!(B||!i.isFocused()||s.defaultPrevented||s.isComposing)){if(ke){if(s.key==="Escape"){s.preventDefault(),s.stopPropagation(),F=null,N=null,i.clearSelection(),ge(!1);return}if(s.key==="Enter"||(s.ctrlKey||s.metaKey)&&s.code==="KeyC"){s.preventDefault(),s.stopPropagation(),_e(i.getScreenText()).then(Ue),ge(!1);return}}if(s.altKey&&s.code==="KeyC"&&!s.ctrlKey&&!s.metaKey){if(s.preventDefault(),s.stopPropagation(),F&&N){let d=i.getCellsText(F.col,F.row,N.col,N.row);F=null,N=null,i.clearSelection(),ge(!1),d&&(ne.textContent="Copied",_e(d).then(Ue))}else{let d=i.getSelection();d?(i.clearSelection(),ne.textContent="Copied",_e(d).then(Ue)):jt()}return}if((s.ctrlKey||s.metaKey)&&s.code==="KeyV"){s.preventDefault(),s.stopPropagation(),(async()=>{try{if(navigator.clipboard?.read){let d=await navigator.clipboard.read();for(let h of d)for(let E of h.types)if(Nt(E)){let I=await h.getType(E);await ht(I);return}}}catch{}try{let d=await navigator.clipboard?.readText();d&&i.pasteText(Rt(d))}catch{}})();return}}}let We=0;function Rt(s){return s.split(`\r
6
6
  `).join(`
7
7
  `).split(`
8
- `).join("\r")}async function _n(o){let d=On(o.clipboardData);if(d){o.preventDefault(),o.stopPropagation();let I=Date.now();if(I-ze<50)return;ze=I,await pt(d);return}let f=o.clipboardData?.getData("text/plain");if(!f)return;o.preventDefault(),o.stopPropagation();let E=Date.now();E-ze<50||(ze=E,i.pasteText(Rt(f)))}let xe=0;function zn(o){o.preventDefault(),xe++,Ot(o.dataTransfer)&&e.classList.add("terminal-drag-over")}function Un(o){o.preventDefault(),o.dataTransfer&&(o.dataTransfer.dropEffect="copy")}function Wn(o){o.preventDefault(),xe--,xe<=0&&(xe=0,e.classList.remove("terminal-drag-over"))}async function Jn(o){o.preventDefault(),xe=0,e.classList.remove("terminal-drag-over");let d=Ot(o.dataTransfer);d&&await pt(d)}function _t(o){!An||o.key!=="Escape"||we||o.defaultPrevented||o.repeat||o.metaKey||o.ctrlKey||o.altKey||i.isFocused()&&(o.preventDefault(),o.stopPropagation(),he("\x1B"))}e.addEventListener("paste",_n),e.addEventListener("dragenter",zn),e.addEventListener("dragover",Un),e.addEventListener("dragleave",Wn),e.addEventListener("drop",Jn),document.addEventListener("keydown",_t,!0);function qn(o){if(o.touches.length!==1){l=null;return}let d=o.touches[0];if(!d)return;O();let f=e.getBoundingClientRect(),E=d.clientX-f.left<f.width*.4?"tui":"history",I=d.clientY-f.top<f.height*.5;l={startX:d.clientX,startY:d.clientY,lastX:d.clientX,lastY:d.clientY,lastT:performance.now(),velocity:0,scrolling:!1,zone:E,tuiUp:I,sent:!1},o.stopPropagation()}function Yn(o){if(!l||o.touches.length!==1)return;let d=o.touches[0];if(!d)return;let f=d.clientY-l.startY,E=d.clientX-l.startX;if(!l.scrolling){if(Math.abs(f)<8||Math.abs(f)<Math.abs(E))return;l.scrolling=!0,Z=Date.now()+500}o.preventDefault(),o.stopPropagation();let I=performance.now(),ee=d.clientY-l.lastY;if(l.zone==="tui"){l.sent||(l.sent=!0,he(l.tuiUp?"\x1B[5~":"\x1B[6~"),A(l.tuiUp)),l.lastX=d.clientX,l.lastY=d.clientY,l.lastT=I;return}let oe=I-l.lastT;oe>0&&(l.velocity=ee/oe),Qn(-ee),l.lastX=d.clientX,l.lastY=d.clientY,l.lastT=I}function Vn(o){if(!l)return;let d=l.scrolling,f=l.zone,E=l.tuiUp,I=l.velocity;if(l=null,o.stopPropagation(),f==="tui"){d||(he(E?"\x1B[5~":"\x1B[6~"),A(E),Z=Date.now()+500,o.preventDefault());return}if(!d){i.focus();return}Z=Date.now()+500,o.preventDefault(),I&&_(I)}function Kn(o){l=null,O(),o.stopPropagation()}function Xn(o){o.pointerType==="touch"&&Date.now()<Z&&(o.preventDefault(),o.stopPropagation())}function Qn(o){let d=i.cellHeight(),f=d>0?Math.round(o/d):o>0?1:-1;f===0&&(f=o>0?1:-1),i.scrollLines(f)}e.addEventListener("touchstart",qn,{passive:!0,capture:!0}),e.addEventListener("touchmove",Yn,{passive:!1,capture:!0}),e.addEventListener("touchend",Vn,{passive:!1,capture:!0}),e.addEventListener("touchcancel",Kn,{passive:!0,capture:!0}),e.addEventListener("pointerup",Xn,!0);function zt(){U()}window.addEventListener("resize",zt),window.visualViewport?.addEventListener("resize",U),window.visualViewport?.addEventListener("scroll",U);let Ut=new ResizeObserver(()=>U());Ut.observe(e),document.fonts?.ready.then(()=>{U(),setTimeout(U,50),setTimeout(U,200)}),e.addEventListener("focusin",Nn,!0);async function Zn(){if(document.fonts?.ready)try{await Promise.race([document.fonts.ready,new Promise(o=>setTimeout(o,1e3))])}catch{}}return requestAnimationFrame(()=>{de()&&He(),(async()=>(await Zn(),de()&&re({type:"resize",cols:i.cols,rows:i.rows}),Pt(),U()))()}),{destroy(){if(B=!0,O(),ve(!1),Ce&&clearTimeout(Ce),document.removeEventListener("mousemove",mt,!0),document.removeEventListener("mouseup",ft,!0),a){try{a.close(1e3,"session switch")}catch{}a=void 0}e.innerHTML="",e.classList.remove("terminal-pending"),window.removeEventListener("resize",zt),Ut.disconnect(),document.removeEventListener("keydown",_t,!0)},focus(){i.focus()},sendInput(o){he(o)},toggleCopyMode(){Ht()}}})()}var m={catalog:null,templates:[],bots:[],approvals:[],activeId:null,items:new Map,ws:null,pollTimer:0,renderQueued:!1};function vt(){try{return localStorage.getItem("tmux-web-token")||""}catch{return""}}async function T(e,t){let n=await fetch(e,{...t,headers:{"content-type":"application/json",Authorization:`Bearer ${vt()}`,...t?.headers||{}}}),i=await n.text(),a=i?JSON.parse(i):null;if(!n.ok)throw new Error(a&&a.error||`HTTP ${n.status}`);return a}function c(e,t,n){let i=document.createElement(e);return t&&(i.className=t),n!==void 0&&(i.textContent=n),i}function oi(e){return e==="running"?"var(--panel-success)":e==="waiting_approval"||e==="waiting_input"?"#e0a23c":e==="failed"?"var(--panel-danger, #e5534b)":e==="completed"?"var(--panel-accent)":"var(--panel-muted)"}function We(){let e=m.approvals.length,t=document.getElementById("bots-inbox-badge");t&&(t.style.display=e?"inline-block":"none",t.textContent=String(e));let n=document.getElementById("bv-inbox-count");n&&(n.textContent=e?`(${e})`:""),window.__botsSnapshot=m.bots,window.__refreshSidebar?.()}function li(){let e=document.getElementById("set-bot-templates"),t=document.getElementById("set-bot-new"),n=document.getElementById("set-bot-inbox"),i=()=>{document.getElementById("settings-popover")?.classList.remove("open"),document.getElementById("settings-backdrop")?.classList.remove("open")};e?.addEventListener("click",()=>{i(),Le()}),t?.addEventListener("click",()=>{i(),bi()}),n?.addEventListener("click",()=>{i(),Ct()})}function ri(){let e=c("div","bots-view");e.id="bots-view",e.hidden=!0;let t=c("div","bots-view-head"),n=c("div","bv-title"),i=c("span","bots-dot");i.id="bv-dot";let a=c("span","bv-title-text");a.id="bv-title";let r=c("span","bv-status");r.id="bv-status",n.append(i,a,r);let s=c("div","bv-actions"),l=c("div","bv-mode"),p=c("button","bv-mode-btn");p.id="bv-mode-btn",p.type="button",p.title="\u5BA1\u6279\u6A21\u5F0F\uFF08\u70B9\u5F00\u770B\u8BF4\u660E\uFF09";let u=c("div","bv-mode-menu");u.id="bv-mode-menu",u.hidden=!0;for(let[y,S,G]of[["supervised","\u9ED8\u8BA4","\u53EA\u8BFB\u5DE5\u5177\uFF08read/grep/find/ls\uFF09\u76F4\u63A5\u653E\u884C\uFF1Bbash\u3001edit\u3001write\u3001\u6269\u5C55/MCP \u5DE5\u5177\u4F1A\u95EE\u4F60"],["parent-supervised","\u76D1\u7BA1","\u5176\u4F59\u5DE5\u5177\u4EA4\u7ED9\u4E0A\u7EA7 bot \u51B3\u5B9A\uFF08\u5E26\u7406\u7531\uFF09\uFF1B\u4F60\u4ECD\u7136\u80FD\u770B\u5230\u5E76\u56DE\u7B54\uFF0C\u5148\u7B54\u5148\u5F97\uFF1B\u6CA1\u6709\u4E0A\u7EA7\u65F6\u56DE\u843D\u5230\u9ED8\u8BA4"],["full-access","\u5168\u653E\u884C","\u6240\u6709\u5DE5\u5177\u76F4\u63A5\u6267\u884C\uFF0C\u4E0D\u518D\u8BE2\u95EE\u3002\u6CE8\u610F\u8FD9\u4E0D\u662F\u6C99\u7BB1"]]){let h=c("button");h.dataset.mode=y,h.innerHTML=`<b>${S}</b><span>${G}</span>`,h.onclick=()=>{u.hidden=!0,di(y)},u.appendChild(h)}p.onclick=y=>{y.stopPropagation(),u.hidden=!u.hidden},l.append(p,u),document.addEventListener("click",y=>{l.contains(y.target)||(u.hidden=!0)});let v=c("button","btn","Allow all");v.id="bv-allow-all",v.title="Approve every pending request for this bot",v.onclick=()=>{if(!m.activeId)return;let y=m.approvals.filter(S=>S.botId===m.activeId);Promise.all(y.map(S=>T(`/api/bots/${S.botId}/approve`,{method:"POST",body:JSON.stringify({requestId:S.id,allow:!0})}))).finally(()=>void Y(!0))};let b=c("button","btn","Needs you "),D=c("span");D.id="bv-inbox-count",b.appendChild(D),b.onclick=()=>void Ct();let x=c("button","btn","Resume");x.onclick=()=>void Yt(y=>T(`/api/bots/${y}/resume`,{method:"POST"}).then(()=>Y(!0)));let w=c("button","btn danger","Stop");w.onclick=()=>void Yt(y=>T(`/api/bots/${y}/stop`,{method:"POST"}).then(()=>Y(!0)));let g=c("button","btn","Delete");g.onclick=()=>{m.activeId&&confirm("Delete this bot and its session?")&&T(`/api/bots/${m.activeId}`,{method:"DELETE"}).then(()=>{gt(),Y(!0)})};let A=c("button","btn","\u2715");A.onclick=()=>gt(),s.append(l,v,b,x,w,g,A),t.append(n,s);let W=c("div","bots-messages");W.id="bots-messages";let O=c("div","bots-composer"),_=c("textarea");_.id="bots-input",_.rows=1,_.placeholder="Message the bot\u2026 (Enter to send, Shift+Enter for newline)",_.onkeydown=y=>{y.key==="Enter"&&!y.shiftKey&&(y.preventDefault(),qt())};let Z=c("button","btn primary","Send");Z.onclick=()=>void qt(),O.append(_,Z),e.append(t,W,O),document.querySelector(".main-area")?.appendChild(e),document.getElementById("bots-modal")||vi()}async function qt(){let e=document.getElementById("bots-input");if(!e||!m.activeId||!e.value.trim())return;let t=e.value;e.value="";try{await T(`/api/bots/${m.activeId}/input`,{method:"POST",body:JSON.stringify({text:t})})}catch(n){ce({kind:"notice",level:"error",text:n instanceof Error?n.message:String(n)})}}function Yt(e){m.activeId&&e(m.activeId).catch(t=>ce({kind:"notice",level:"error",text:t instanceof Error?t.message:String(t)}))}function gt(){m.activeId=null;let e=document.getElementById("bots-view");e&&(e.hidden=!0);try{m.ws?.close()}catch{}m.ws=null,We();let t=document.getElementById("terminal-container"),n=document.getElementById("main-placeholder"),i=!!document.querySelector(".session-item.active:not(.bot-item)");t&&i?(t.style.display="",n&&(n.style.display="none")):n&&(n.style.display="")}async function Vt(e){m.activeId=e,m.items.set(e,[]);let t=document.getElementById("bots-view");t&&(t.hidden=!1);let n=document.getElementById("main-placeholder");n&&(n.style.display="none");let i=document.getElementById("terminal-container");i&&(i.style.display="none");let a=document.getElementById("file-editor");a&&(a.style.display="none"),We(),wt();try{m.ws?.close()}catch{}let r=location.protocol==="https:"?"wss:":"ws:",s=new WebSocket(`${r}//${location.host}/ws/bots/${encodeURIComponent(e)}?token=${encodeURIComponent(vt())}`);m.ws=s,s.onmessage=l=>{try{Xt(JSON.parse(String(l.data)))}catch{}},s.onclose=()=>{m.activeId===e&&setTimeout(()=>{m.activeId===e&&Y(!0)},1500)},await Y(!0)}function bt(){return m.bots.find(e=>e.id===m.activeId)||null}function yt(){let e=bt();if(!e)return;let t=document.getElementById("bv-title"),n=document.getElementById("bv-status"),i=document.getElementById("bv-dot");t&&(t.textContent=e.title),n&&(n.textContent=`${e.status.replace(/_/g," ")} \xB7 ${e.templateId} \xB7 ${e.projectPath}`);let a=document.getElementById("bv-mode-btn");a&&e.runtimeMode&&(a.textContent=`${Kt[e.runtimeMode]||e.runtimeMode} \u25BE`);for(let l of document.querySelectorAll("#bv-mode-menu button"))l.classList.toggle("active",l.dataset.mode===e.runtimeMode);let r=document.getElementById("bv-allow-all"),s=m.approvals.filter(l=>l.botId===e.id).length;r&&(r.hidden=s===0,r.textContent=`Allow all (${s})`),i&&(i.style.background=oi(e.status))}var Kt={supervised:"\u9ED8\u8BA4","parent-supervised":"\u76D1\u7BA1","full-access":"\u5168\u653E\u884C"};async function di(e){if(m.activeId)try{await T(`/api/bots/${m.activeId}/mode`,{method:"POST",body:JSON.stringify({mode:e})});let t=bt();t&&(t.runtimeMode=e),yt(),ce({kind:"notice",level:"info",text:`\u5BA1\u6279\u6A21\u5F0F\uFF1A${Kt[e]||e}`})}catch(t){ce({kind:"notice",level:"error",text:t instanceof Error?t.message:String(t)})}}function ce(e,t=m.activeId){if(!t)return;let n=m.items.get(t)||[];n.push(e),m.items.set(t,n),t===m.activeId&&ue()}function ue(){m.renderQueued||(m.renderQueued=!0,requestAnimationFrame(()=>{m.renderQueued=!1,wt()}))}function wt(){let e=document.getElementById("bots-messages");if(!e||!m.activeId)return;let t=m.items.get(m.activeId)||[];e.textContent="";let n=null;for(let i of t)if(i.kind==="user"){let a=c("div","bv-msg bv-user");a.textContent=i.text,e.appendChild(a),n=null}else if(i.kind==="assistant"){let a=c("div","bv-msg bv-assistant");if(i.thinking){let s=c("details","bv-thinking");s.appendChild(c("summary",void 0,"thinking")),s.appendChild(c("div",void 0,i.thinking)),a.appendChild(s)}let r=c("div","bv-text");r.textContent=i.text,a.appendChild(r),e.appendChild(a),n=r}else if(i.kind==="tool")e.appendChild(ci(i)),n=null;else if(i.kind==="approval")e.appendChild(ui(i)),n=null;else if(i.kind==="notice"){let a=c("div",`bv-notice bv-notice-${i.level}`,i.text);e.appendChild(a)}n&&(n.scrollTop=n.scrollHeight),e.scrollTop=e.scrollHeight}function ci(e){let t=c("details","bv-tool");t.open=e.phase!=="end"||!!e.isError;let n=c("summary"),i=c("span","bv-tool-name",e.name);if(n.appendChild(i),e.phase!=="end"&&n.appendChild(c("span","bv-tool-phase",e.phase)),e.isError&&n.appendChild(c("span","bv-tool-error","error")),typeof e.durationMs=="number"&&n.appendChild(c("span","bv-tool-meta",`${Math.round(e.durationMs)}ms`)),t.appendChild(n),e.args!==void 0){let a=c("pre","bv-pre");a.textContent=typeof e.args=="string"?e.args:JSON.stringify(e.args,null,2),t.appendChild(a)}if(e.output){let a=c("pre","bv-pre bv-output");a.textContent=e.output,t.appendChild(a)}return t}function ui(e){let t=c("div","bv-approval"),n=e.approval;if(t.appendChild(c("div","bv-approval-title",n.title)),n.message&&t.appendChild(c("pre","bv-pre",n.message)),e.decided)return t.appendChild(c("div","bv-approval-decided",e.decided==="allowed"?"Allowed":"Denied")),t;let i=c("input","bv-reason");i.placeholder="reason (optional)";let a=c("div","bv-approval-actions"),r=c("button","btn primary","Allow"),s=c("button","btn",n.method==="confirm"&&/^Allow (.+?)\?$/.test(n.title)?`Always allow ${/^Allow (.+?)\?$/.exec(n.title)?.[1]}`:"Always allow");s.hidden=n.method!=="confirm";let l=c("button","btn danger","Deny"),p=async(u,v=!1)=>{try{await T(`/api/bots/${n.botId}/approve`,{method:"POST",body:JSON.stringify({requestId:n.id,allow:u,always:v,reason:i.value||void 0})}),e.decided=u?"allowed":"denied",ue(),Y(!0)}catch(b){ce({kind:"notice",level:"error",text:b instanceof Error?b.message:String(b)})}};return r.onclick=()=>void p(!0),s.onclick=()=>void p(!0,!0),l.onclick=()=>void p(!1),a.append(i,r,s,l),t.appendChild(a),t}function Xt(e){let t=String(e.type||""),n=m.activeId;if(!n)return;let i=m.items.get(n)||[];if(t==="snapshot")m.items.set(n,[]);else if(t==="user")ce({kind:"user",text:String(e.text||"")});else if(t==="status"){let a=bt();a&&(a.status=String(e.status||a.status)),yt(),fi()}else if(t==="message"){let a=e.message;if(!a||String(a.role||"")!=="assistant")return;let r=pi(a),s=mi(a),l=i[i.length-1];l&&l.kind==="assistant"?(l.text=r||l.text,l.thinking=s||l.thinking):i.push({kind:"assistant",text:r,thinking:s}),m.items.set(n,i),ue()}else if(t==="delta"){let a=String(e.kind||""),r=String(e.delta||""),s=i[i.length-1];(!s||s.kind!=="assistant")&&(i.push({kind:"assistant",text:"",thinking:""}),s=i[i.length-1]),s.kind==="assistant"&&(a==="text"?s.text+=r:a==="thinking"&&(s.thinking+=r)),m.items.set(n,i),ue()}else if(t==="tool"){let a=String(e.callId||""),r=i.find(l=>l.kind==="tool"&&l.callId===a),s=String(e.phase||"start");r?(r.phase=s,s==="update"&&e.output&&(r.output=String(e.output)),s==="end"&&(e.output&&(r.output=String(e.output)),r.isError=e.isError===!0,typeof e.durationMs=="number"&&(r.durationMs=e.durationMs))):i.push({kind:"tool",callId:a,name:String(e.name||"tool"),args:e.args,output:e.output?String(e.output):void 0,isError:e.isError===!0,durationMs:typeof e.durationMs=="number"?e.durationMs:void 0,phase:s}),m.items.set(n,i),ue()}else if(t==="approval"){let a=e.approval;if(!a)return;let r=i;for(let s=r.length-1;s>=0;s--){let l=r[s];if(l.kind==="approval"&&l.approval.id===a.id){l.approval=a,a.state!=="pending"&&(l.decided=a.state==="allowed"?"allowed":"denied"),m.items.set(n,r),ue();return}}r.push({kind:"approval",approval:a}),m.items.set(n,r),ue()}else t==="notice"&&ce({kind:"notice",level:String(e.level||"info"),text:String(e.text||"")})}function pi(e){let t=e.content;return Array.isArray(t)?t.map(n=>n&&typeof n=="object"&&n.type==="text"?String(n.text||""):"").join(""):String(e.text||"")}function mi(e){let t=e.content;return Array.isArray(t)?t.map(n=>n&&typeof n=="object"&&n.type==="thinking"?String(n.thinking||""):"").join(""):""}async function Y(e=!1){try{let[t,n]=await Promise.all([T("/api/bots"),T("/api/bots/approvals")]);if(m.bots=t,m.approvals=n,We(),yt(),e&&m.activeId){let i=await T(`/api/bots/${m.activeId}/events?limit=300`);hi(i)}}catch{}}async function fi(){try{m.bots=await T("/api/bots"),We()}catch{}}function hi(e){if(m.activeId){m.items.set(m.activeId,[]);for(let t of e)Xt(t);wt()}}function vi(){let e=c("div","bots-modal");e.id="bots-modal",e.hidden=!0;let t=c("div","bots-modal-card"),n=c("div","bots-modal-head"),i=c("span");i.id="bots-modal-title";let a=c("button","btn","\u2715");a.onclick=()=>Je(),n.append(i,a);let r=c("div","bots-modal-body");r.id="bots-modal-body",t.append(n,r),e.appendChild(t),e.onclick=s=>{s.target===e&&Je()},document.body.appendChild(e)}function Et(e){let t=document.getElementById("bots-modal"),n=document.getElementById("bots-modal-title"),i=document.getElementById("bots-modal-body");if(!t||!i)throw new Error("modal missing");return n&&(n.textContent=e),i.textContent="",t.hidden=!1,i}function Je(){let e=document.getElementById("bots-modal");e&&(e.hidden=!0)}async function gi(){return m.catalog||(m.catalog=await T("/api/bots/catalog")),m.catalog}async function Qt(){return m.templates=await T("/api/bots/templates"),m.templates}async function Le(){let e=Et("Bot templates"),[t,n]=await Promise.all([gi(),Qt()]),i=c("div","bv-template-list");for(let p of n){let u=c("div","bv-template-row");u.appendChild(c("span","bv-template-name",p.manifest.name)),u.appendChild(c("span","bv-template-desc",p.manifest.description||""));let v=c("button","btn","Edit");v.onclick=()=>Zt(e,t,p);let b=c("button","btn","Copy");b.title="Duplicate this template",b.onclick=()=>{let w=JSON.parse(JSON.stringify(p.manifest));w.name=`${p.manifest.name} copy`,T("/api/bots/templates",{method:"POST",body:JSON.stringify({manifest:w})}).then(()=>Le()).catch(g=>alert(g instanceof Error?g.message:String(g)))};let D=c("button","btn danger","Delete");D.onclick=()=>{confirm(`Delete template ${p.manifest.name}?`)&&T(`/api/bots/templates/${p.id}`,{method:"DELETE"}).then(()=>Le())};let x=c("span","bv-template-actions");x.append(v,b,D),u.appendChild(x),i.appendChild(u)}n.length===0&&i.appendChild(c("div","bots-empty","No templates yet")),e.appendChild(i);let a=c("div","bv-template-actions"),r=c("button","btn primary","New template");r.onclick=()=>Zt(e,t,null);let s=c("button","btn","Export");s.title="Download templates + library as JSON",s.onclick=()=>{(async()=>{try{let p=await fetch("/api/bots/export",{headers:{Authorization:`Bearer ${vt()}`}});if(!p.ok)throw new Error(`HTTP ${p.status}`);let u=await p.blob(),v=document.createElement("a");v.href=URL.createObjectURL(u),v.download=`tmux-weblink-bots-${new Date().toISOString().slice(0,10)}.json`,v.click(),setTimeout(()=>URL.revokeObjectURL(v.href),2e3)}catch(p){alert(p instanceof Error?p.message:String(p))}})()};let l=c("button","btn","Import");l.title="Restore templates from a JSON bundle",l.onclick=()=>{let p=document.createElement("input");p.type="file",p.accept="application/json,.json",p.onchange=()=>{let u=p.files?.[0];u&&(async()=>{try{let v=JSON.parse(await u.text()),b=await T("/api/bots/import",{method:"POST",body:JSON.stringify(v)});alert(`Imported ${b.templates} templates, ${b.files} library files (${b.skipped} kept)`),await Le()}catch(v){alert(v instanceof Error?v.message:String(v))}})()},p.click()},a.append(r,s,l),e.appendChild(a)}function kt(e,t,n){let i=c("div","bv-field");i.appendChild(c("label","bv-label",e));let a=c("div","bv-check-grid"),r=[];for(let s of t){let l=c("label","bv-check"),p=document.createElement("input");p.type="checkbox",p.checked=n.includes(s.id),l.append(p,c("span",void 0,s.label)),s.hint&&(l.title=s.hint),a.appendChild(l),r.push({id:s.id,input:p})}return i.appendChild(a),{element:i,get:()=>r.filter(s=>s.input.checked).map(s=>s.id)}}function Zt(e,t,n){e.textContent="";let i=n?JSON.parse(JSON.stringify(n.manifest)):{name:"new-bot",description:""},a=c("input","bv-input");a.value=i.name,a.placeholder="Template name";let r=c("input","bv-input");r.value=i.description||"",r.placeholder="One line description";let s=c("textarea","bv-textarea");s.rows=6,s.value=i.system||"",s.placeholder="System prompt for this bot (written to SYSTEM.md)";let l=kt("Skills",t.skills.map(h=>({id:h.id,label:h.name,hint:h.description})),i.skills||[]),p=kt("Extensions (Pi builtins + library)",t.extensions.map(h=>({id:h.id,label:`${h.name}${h.kind==="builtin"?" (builtin)":""}`,hint:h.description})),(i.extensions||[]).map(h=>h.replace(/^.*\//,"").replace(/\.(js|ts)$/,""))),u=kt("Prompt templates",t.prompts.map(h=>({id:h.id,label:h.name})),i.prompts||[]),v=c("select","bv-input");v.appendChild(new Option("none",""));for(let h of t.mcp)v.appendChild(new Option(h.name,h.id));i.mcp&&(v.value=t.mcp.find(h=>JSON.stringify(h.servers)===JSON.stringify(i.mcp?.mcpServers))?.id||"");let b=c("div","bv-field");b.appendChild(c("label","bv-label","Tools (allow list; deny always blocks)"));let D=c("div","bv-check-grid"),x=[];for(let h of t.tools){let z=c("label","bv-check"),B=document.createElement("input");B.type="checkbox",B.checked=(i.tools?.allow||[]).includes(h.name)||!i.tools?.allow?.length&&["read","grep","find","ls","edit","write","bash"].includes(h.name),z.append(B,c("span",void 0,h.name)),D.appendChild(z),x.push({name:h.name,input:B})}b.appendChild(D);let w=c("input","bv-input");w.value=(i.tools?.deny||[]).join(", "),w.placeholder="Always deny (comma separated), e.g. bash, write";let g=c("textarea","bv-textarea");g.rows=2,g.value=(i.packages||[]).join(`
9
- `),g.placeholder="Pi packages, one per line (npm:@scope/pkg@1.2.3, git:..., ./path)";let A=c("select","bv-input");A.appendChild(new Option("default (Pi settings)",""));for(let h of t.models)A.appendChild(new Option(`${h.provider}/${h.model}`,`${h.provider}
10
- ${h.model}`));i.model?.provider&&i.model?.id&&(A.value=`${i.model.provider}
11
- ${i.model.id}`);let W=c("select","bv-input");for(let h of["","off","minimal","low","medium","high","xhigh","max"])W.appendChild(new Option(h||"default",h));i.model?.thinking&&(W.value=i.model.thinking);let O=c("select","bv-input");for(let h of["supervised","auto-accept-edits","full-access"])O.appendChild(new Option(h,h));O.value=i.permissions?.runtimeMode||"supervised";let _=c("select","bv-input");_.appendChild(new Option("ignore project .pi (recommended)","ignore")),_.appendChild(new Option("inherit project .pi (needs trust)","inherit")),_.value=i.projectResources||"ignore";let Z=c("label","bv-check"),y=document.createElement("input");y.type="checkbox",y.checked=!!i.orchestrator,Z.append(y,c("span",void 0,"Super bot: gets orchestration tools (create/stop/status child bots)"));let S=(h,z)=>{let B=c("div","bv-field");return B.appendChild(c("label","bv-label",h)),B.appendChild(z),B};e.append(S("Name",a),S("Description",r),S("System prompt",s),l.element,p.element,u.element,S("MCP preset",v),b,S("Always deny tools",w),S("Packages",g),S("Model",A),S("Thinking level",W),S("Approval mode",O),S("Project resources",_),Z);let G=c("button","btn primary",n?"Save template":"Create template");G.onclick=async()=>{let[h,z]=A.value.split(`
12
- `),B=t.mcp.find($=>$.id===v.value),le={name:a.value.trim()||"bot",description:r.value.trim()||void 0,system:s.value.trim()||void 0,skills:l.get(),extensions:p.get().map($=>($.startsWith("builtin:"),$)),prompts:u.get(),packages:g.value.split(`
13
- `).map($=>$.trim()).filter(Boolean),mcp:B?{mcpServers:B.servers}:void 0,tools:{allow:x.filter($=>$.input.checked).map($=>$.name),deny:w.value.split(",").map($=>$.trim()).filter(Boolean)},model:h?{provider:h,id:z,thinking:W.value||void 0}:void 0,permissions:{runtimeMode:O.value},projectResources:_.value==="inherit"?"inherit":"ignore",orchestrator:y.checked||void 0};try{await T("/api/bots/templates",{method:"POST",body:JSON.stringify({id:n?.id,manifest:le})}),Je(),await Le()}catch($){alert($ instanceof Error?$.message:String($))}},e.appendChild(G)}async function bi(){return Gt("")}async function Gt(e){let t=Et("New bot"),n=await Qt();if(n.length===0){t.appendChild(c("div","bots-empty","Create a template first (\u2699)."));return}let i=c("select","bv-input");for(let u of n)i.appendChild(new Option(u.manifest.name,u.id));let a=c("input","bv-input");a.placeholder="Title (defaults to template name)";let r=c("input","bv-input");r.placeholder="/path/to/project";let s=e||m.bots[0]?.projectPath||"";r.value=s;let l=c("select","bv-input");l.appendChild(new Option("shared \u2014 run in the project folder","shared")),l.appendChild(new Option("worktree \u2014 isolated git worktree","worktree")),t.append(qe("Template",i),qe("Title",a),qe("Project path",r),qe("Workspace",l));let p=c("button","btn primary","Create bot");p.onclick=async()=>{try{let u=await T("/api/bots",{method:"POST",body:JSON.stringify({templateId:i.value,title:a.value.trim()||void 0,projectPath:r.value.trim()||void 0,isolation:l.value})});Je(),await Y(!0),await Vt(u.id)}catch(u){alert(u instanceof Error?u.message:String(u))}},t.appendChild(p)}function qe(e,t){let n=c("div","bv-field");return n.appendChild(c("label","bv-label",e)),n.appendChild(t),n}async function Ct(){let e=Et("Needs you");if(m.approvals=await T("/api/bots/approvals"),m.approvals.length===0){e.appendChild(c("div","bots-empty","Nothing waiting."));return}for(let t of m.approvals){let n=c("div","bv-approval");n.appendChild(c("div","bv-approval-title",`${t.botTitle}: ${t.title}`)),t.message&&n.appendChild(c("pre","bv-pre",t.message));let i=c("input","bv-reason");i.placeholder="reason (optional)";let a=c("div","bv-approval-actions"),r=c("button","btn primary","Allow"),s=c("button","btn danger","Deny"),l=async p=>{await T(`/api/bots/${t.botId}/approve`,{method:"POST",body:JSON.stringify({requestId:t.id,allow:p,reason:i.value||void 0})}),await Y(!0),await Ct()};r.onclick=()=>void l(!0),s.onclick=()=>void l(!1),a.append(i,r,s),n.appendChild(a),e.appendChild(n)}}function yi(){window.__botsInited||(window.__botsInited=!0,ri(),li(),window.__openBot=Vt,document.addEventListener("click",e=>{let t=e.target;t&&(t.closest(".session-item.bot-item")||t.closest(".session-item")&&m.activeId&&setTimeout(()=>gt(),0))},!0),Y(!0),m.pollTimer=window.setInterval(()=>{document.hidden||Y()},6e3),window.addEventListener("beforeunload",()=>window.clearInterval(m.pollTimer)))}var Ie=window.__TMUX_WEB_SHELL__,L=null,M=null,Be=typeof window.__TMUX_WEB_SCOPE__?.agentId=="string"?window.__TMUX_WEB_SCOPE__.agentId:null,H=Be;window.__tmuxWebScopeAgent=Be;var xt="sessions",ie="",Ye="",Ve="",en="";function N(e){return H?"/a/"+encodeURIComponent(H)+e:e}var k=document.getElementById("sidebar-content"),pe=document.getElementById("main-placeholder"),J=document.getElementById("terminal-container"),Te=document.getElementById("file-editor"),wi=document.getElementById("fe-path"),V=document.getElementById("fe-status"),Me=document.getElementById("fe-content"),me=document.getElementById("fe-save"),Ei=document.getElementById("fe-delete"),ki=document.getElementById("fe-back"),tn=document.getElementById("fe-new-name"),Ci=document.getElementById("fe-new-btn"),St=document.getElementById("settings-backdrop"),nn=document.getElementById("settings-popover"),an=document.querySelector(".sidebar"),sn="tmux-web-force-narrow";function Ke(){try{return localStorage.getItem(sn)==="1"}catch{return!1}}function on(){document.documentElement.classList.toggle("force-narrow",Ke()),Ke()&&ln()&&Xe()}function ln(){return Ke()?!0:window.matchMedia("(max-width: 640px)").matches}function Xe(){ln()&&an.classList.add("collapsed")}function rn(){an.classList.remove("collapsed")}document.getElementById("mode-sessions").addEventListener("click",()=>{rn(),dn("sessions")}),document.getElementById("mode-files").addEventListener("click",()=>{rn(),dn("files")});function dn(e){xt=e,document.querySelectorAll(".mode-btn").forEach(n=>n.classList.remove("active"));let t=document.getElementById(e==="sessions"?"mode-sessions":"mode-files");t&&t.classList.add("active"),e==="sessions"?(Lt="",ae()):ji()}var Lt="";async function ae(){if(xt!=="sessions")return;try{let t=await(await fetch("/api/sidebar/sessions")).json(),n=(window.__botsSnapshot||[]).map(a=>[a.id,a.title,a.status,a.projectPath]),i=JSON.stringify({recent:t.recent,agents:t.agents,tombstones:t.tombstones,bots:n});if(i===Lt)return;Lt=i,Ti(t)}catch{k.innerHTML+='<div class="file-tree-empty">Failed to load sessions</div>'}let e=document.getElementById("ns-btn");e&&e.addEventListener("click",()=>{let t=window.__openNewSessionModal;typeof t=="function"?t():document.getElementById("new-session-modal")?.classList.add("open")}),Ft()}var cn="tmux-web-sidebar-group-collapsed";function un(){try{return new Set(JSON.parse(localStorage.getItem(cn)||"[]"))}catch{return new Set}}function xi(e){try{localStorage.setItem(cn,JSON.stringify([...e]))}catch{}}function Si(e,t,n){if(!e)return"\u2026";let i=n&&(e===n||e.startsWith(n+"/"))?"~"+e.slice(n.length):e,a=i.split("/").filter(Boolean);if(a.length===0)return e;for(let r=1;r<=a.length;r++){let s=a.slice(-r).join("/");if(!t.some(l=>!l||l===e?!1:(n&&(l===n||l.startsWith(n+"/"))?"~"+l.slice(n.length):l).split("/").filter(Boolean).slice(-r).join("/")===s))return s}return i}function Li(e){let t=document.createElement("div");t.className="session-item bot-item",t.setAttribute("data-bot-id",e.id),t.title=`Bot \xB7 ${e.projectPath}`;let n=e.status==="running"?"var(--panel-success)":e.status==="waiting_approval"||e.status==="waiting_input"?"#e0a23c":e.status==="failed"?"var(--panel-danger, #e5534b)":"var(--panel-muted)";return t.innerHTML=`<svg class="bot-icon" viewBox="0 0 24 24" fill="currentColor"><path d="M11 2h2v3h2a3 3 0 0 1 3 3v1h1a2 2 0 0 1 2 2v6a2 2 0 0 1-2 2h-1v1a3 3 0 0 1-3 3H9a3 3 0 0 1-3-3v-1H5a2 2 0 0 1-2-2v-6a2 2 0 0 1 2-2h1V8a3 3 0 0 1 3-3h2V2zm-2 6v1h6V8H9zm-2 5a1.5 1.5 0 1 0 0 3 1.5 1.5 0 0 0 0-3zm10 0a1.5 1.5 0 1 0 0 3 1.5 1.5 0 0 0 0-3z"/></svg><span>${C(e.title)}</span><span class="bot-status-dot" style="background:${n}"></span>`,t.addEventListener("click",i=>{i.stopPropagation(),window.__openBot?.(e.id)}),t}function pn(e,t,n,i=!0){let a=new Map;for(let u of e){let v=u.path||"";a.has(v)||a.set(v,[]),a.get(v).push(u)}let r=n?[]:window.__botsSnapshot||[],s=new Map;for(let u of r)a.has(u.projectPath)||a.set(u.projectPath,[]),s.has(u.projectPath)||s.set(u.projectPath,[]),s.get(u.projectPath).push(u);let l=[...a.keys()],p=un();for(let[u,v]of a){let b=Si(u,l,t),D=p.has(u),x=document.createElement("div");if(x.className="session-group-header"+(D?" collapsed":""),x.title=u||"No working directory",x.innerHTML=`<span class="sg-folder">&#128193;</span><span class="sg-label">${C(b)}</span>`,!n&&u){let g=document.createElement("button");g.className="sg-add-bot",g.textContent="+",g.title=`New bot in ${u}`,g.addEventListener("click",A=>{A.stopPropagation(),Bt(u)}),x.appendChild(g)}x.addEventListener("click",()=>{let g=un(),A=x.nextElementSibling;g.has(u)?(g.delete(u),x.classList.remove("collapsed"),A?.classList.remove("collapsed")):(g.add(u),x.classList.add("collapsed"),A?.classList.add("collapsed")),xi(g)});let w=document.createElement("div");w.className="session-group-body"+(D?" collapsed":"");for(let g of v)w.appendChild(n?Ii(g,n,i):Bi(g));for(let g of s.get(u)||[])w.appendChild(Li(g));k.appendChild(x),k.appendChild(w)}}function Ii(e,t,n){let i=document.createElement("div");i.className="session-item"+(e.name===M&&H===t?" active":"")+(n?"":" session-offline"),i.setAttribute("data-session",e.name),i.setAttribute("data-agent",t),i.innerHTML=`<svg viewBox="0 0 24 24" fill="currentColor"><path d="${e.attached?"M19 4H5a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6a2 2 0 0 0-2-2zm0 14H5V6h14v12z":"M4 6h16v2H4V6zm0 5h16v2H4v-2zm0 5h16v2H4v-2z"}"></svg>
8
+ `).join("\r")}async function Un(s){let d=On(s.clipboardData);if(d){s.preventDefault(),s.stopPropagation();let I=Date.now();if(I-We<50)return;We=I,await ht(d);return}let h=s.clipboardData?.getData("text/plain");if(!h)return;s.preventDefault(),s.stopPropagation();let E=Date.now();E-We<50||(We=E,i.pasteText(Rt(h)))}let Se=0;function Wn(s){s.preventDefault(),Se++,Vt(s.dataTransfer)&&e.classList.add("terminal-drag-over")}function qn(s){s.preventDefault(),s.dataTransfer&&(s.dataTransfer.dropEffect="copy")}function Jn(s){s.preventDefault(),Se--,Se<=0&&(Se=0,e.classList.remove("terminal-drag-over"))}async function Yn(s){s.preventDefault(),Se=0,e.classList.remove("terminal-drag-over");let d=Vt(s.dataTransfer);d&&await ht(d)}function _t(s){!Fn||s.key!=="Escape"||ke||s.defaultPrevented||s.repeat||s.metaKey||s.ctrlKey||s.altKey||i.isFocused()&&(s.preventDefault(),s.stopPropagation(),fe("\x1B"))}e.addEventListener("paste",Un),e.addEventListener("dragenter",Wn),e.addEventListener("dragover",qn),e.addEventListener("dragleave",Jn),e.addEventListener("drop",Yn),document.addEventListener("keydown",_t,!0);function Kn(s){if(s.touches.length!==1){l=null;return}let d=s.touches[0];if(!d)return;P();let h=e.getBoundingClientRect(),E=d.clientX-h.left<h.width*.4?"tui":"history",I=d.clientY-h.top<h.height*.5;l={startX:d.clientX,startY:d.clientY,lastX:d.clientX,lastY:d.clientY,lastT:performance.now(),velocity:0,scrolling:!1,zone:E,tuiUp:I,sent:!1},s.stopPropagation()}function Xn(s){if(!l||s.touches.length!==1)return;let d=s.touches[0];if(!d)return;let h=d.clientY-l.startY,E=d.clientX-l.startX;if(!l.scrolling){if(Math.abs(h)<8||Math.abs(h)<Math.abs(E))return;l.scrolling=!0,R=Date.now()+500}s.preventDefault(),s.stopPropagation();let I=performance.now(),ee=d.clientY-l.lastY;if(l.zone==="tui"){l.sent||(l.sent=!0,fe(l.tuiUp?"\x1B[5~":"\x1B[6~"),M(l.tuiUp)),l.lastX=d.clientX,l.lastY=d.clientY,l.lastT=I;return}let se=I-l.lastT;se>0&&(l.velocity=ee/se),ei(-ee),l.lastX=d.clientX,l.lastY=d.clientY,l.lastT=I}function Qn(s){if(!l)return;let d=l.scrolling,h=l.zone,E=l.tuiUp,I=l.velocity;if(l=null,s.stopPropagation(),h==="tui"){d||(fe(E?"\x1B[5~":"\x1B[6~"),M(E),R=Date.now()+500,s.preventDefault());return}if(!d){i.focus();return}R=Date.now()+500,s.preventDefault(),I&&j(I)}function Zn(s){l=null,P(),s.stopPropagation()}function Gn(s){s.pointerType==="touch"&&Date.now()<R&&(s.preventDefault(),s.stopPropagation())}function ei(s){let d=i.cellHeight(),h=d>0?Math.round(s/d):s>0?1:-1;h===0&&(h=s>0?1:-1),i.scrollLines(h)}e.addEventListener("touchstart",Kn,{passive:!0,capture:!0}),e.addEventListener("touchmove",Xn,{passive:!1,capture:!0}),e.addEventListener("touchend",Qn,{passive:!1,capture:!0}),e.addEventListener("touchcancel",Zn,{passive:!0,capture:!0}),e.addEventListener("pointerup",Gn,!0);function Ut(){U()}window.addEventListener("resize",Ut),window.visualViewport?.addEventListener("resize",U),window.visualViewport?.addEventListener("scroll",U);let Wt=new ResizeObserver(()=>U());Wt.observe(e),document.fonts?.ready.then(()=>{U(),setTimeout(U,50),setTimeout(U,200)}),e.addEventListener("focusin",Vn,!0);async function ti(){if(document.fonts?.ready)try{await Promise.race([document.fonts.ready,new Promise(s=>setTimeout(s,1e3))])}catch{}}return requestAnimationFrame(()=>{de()&&Re(),(async()=>(await ti(),de()&&re({type:"resize",cols:i.cols,rows:i.rows}),Pt(),U()))()}),{destroy(){if(B=!0,P(),ge(!1),xe&&clearTimeout(xe),document.removeEventListener("mousemove",vt,!0),document.removeEventListener("mouseup",ft,!0),a){try{a.close(1e3,"session switch")}catch{}a=void 0}e.innerHTML="",e.classList.remove("terminal-pending"),window.removeEventListener("resize",Ut),Wt.disconnect(),document.removeEventListener("keydown",_t,!0)},focus(){i.focus()},sendInput(s){fe(s)},toggleCopyMode(){jt()}}})()}var Yt={menu:"M3 6h18v2H3V6zm0 5h18v2H3v-2zm0 5h18v2H3v-2z",close:"M18.3 5.71a1 1 0 0 0-1.41 0L12 10.59 7.11 5.7a1 1 0 1 0-1.41 1.41L10.59 12l-4.89 4.89a1 1 0 1 0 1.41 1.41L12 13.41l4.89 4.89a1 1 0 1 0 1.41-1.41L13.41 12l4.89-4.89a1 1 0 0 0 0-1.4z",search:"M15.5 14h-.79l-.28-.27A6.47 6.47 0 0 0 16 9.5 6.5 6.5 0 1 0 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z",refresh:"M17.65 6.35A7.96 7.96 0 0 0 12 4a8 8 0 1 0 8 8h-2a6 6 0 1 1-6-6c1.66 0 3.14.69 4.22 1.78L13 11h7V4l-2.35 2.35z",add:"M19 13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z",edit:"M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM5.92 19H5v-.92l9.06-9.06.92.92L5.92 19zm13.66-12.83a1 1 0 0 0 0-1.41l-1.34-1.34a1 1 0 0 0-1.41 0l-1.05 1.05 2.75 2.75 1.05-1.05z",delete:"M15 4V3H9v1H4v2h1.5l.81 13.05A2 2 0 0 0 8.3 21h7.4a2 2 0 0 0 1.99-1.95L18.5 6H20V4h-5zm-5.5 2h5l-.75 12h-3.5L9.5 6z",check:"M9 16.17 4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41L9 16.17z",sessions:"M4 6h16v2H4V6zm0 5h16v2H4v-2zm0 5h16v2H4v-2z",notes:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8l-6-6zm-1 2 5 5h-5V4zM6 20V4h5v7h7v9H6z",schedule:"M19 4h-1V2h-2v2H8V2H6v2H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6a2 2 0 0 0-2-2zm0 16H5V10h14v10zM9 14H7v-2h2v2zm4 0h-2v-2h2v2zm4 0h-2v-2h2v2zm-8 4H7v-2h2v2zm4 0h-2v-2h2v2zm4 0h-2v-2h2v2z",agents:"M12 2a5 5 0 1 0 0 10 5 5 0 0 0 0-10zm0 8a3 3 0 1 1 0-6 3 3 0 0 1 0 6zm-7 13v-2a5 5 0 0 1 5-5h4a5 5 0 0 1 5 5v2h2v-2a7 7 0 0 0-7-7H10a7 7 0 0 0-7 7v2h2z",history:"M13 3a9 9 0 0 0-9 9H1l4 4 4-4H6a7 7 0 1 1 7 7c-1.93 0-3.68-.79-4.94-2.06l-1.42 1.42A8.96 8.96 0 0 0 13 21a9 9 0 0 0 0-18zm-1 5v5l4.25 2.55.75-1.23-3.5-2.08V8H12z","quick-commands":"M13 3 4 14h7l-1 7 9-11h-7l1-7z",windows:"M4 6h16v2H4V6zm0 5h10v2H4v-2zm0 5h16v2H4v-2z",terminal:"M4 17.6 6.4 20l8-8-8-8L4 6.4 11.6 12 4 17.6zM20 18h-8v2h8v-2z",microphone:"M12 14c1.66 0 3-1.34 3-3V5c0-1.66-1.34-3-3-3S9 3.34 9 5v6c0 1.66 1.34 3 3 3zm5-3c0 2.76-2.24 5-5 5s-5-2.24-5-5H5c0 3.53 2.61 6.43 6 6.92V21h2v-3.08c3.39-.49 6-3.39 6-6.92h-2z",keyboard:"M20 5H4c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm-9 3h2v2h-2V8zm0 3h2v2h-2v-2zM8 8h2v2H8V8zm0 3h2v2H8v-2zm-1 2H5v-2h2v2zm0-3H5V8h2v2zm9 7H8v-2h8v2zm0-4h-2v-2h2v2zm0-3h-2V8h2v2zm3 3h-2v-2h2v2zm0-3h-2V8h2v2z",bot:"M11 2h2v3h2a3 3 0 0 1 3 3v1h1a2 2 0 0 1 2 2v6a2 2 0 0 1-2 2h-1v1a3 3 0 0 1-3 3H9a3 3 0 0 1-3-3v-1H5a2 2 0 0 1-2-2v-6a2 2 0 0 1 2-2h1V8a3 3 0 0 1 3-3h2V2zm-2 6v1h6V8H9zm-2 5a1.5 1.5 0 1 0 0 3 1.5 1.5 0 0 0 0-3zm10 0a1.5 1.5 0 1 0 0 3 1.5 1.5 0 0 0 0-3z",layers:"M12 2 2 7l10 5 10-5-10-5zm0 7.5L4.5 5.8 12 2l7.5 3.8L12 9.5zM2 12l10 5 10-5-1.9-.95L12 14.9l-8.1-3.85L2 12zm0 4.5 10 5 10-5-1.9-.95L12 19.4l-8.1-3.85-1.9.95z",inbox:"M19 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V5a2 2 0 0 0-2-2zm0 16H5v-3h3.6a3.5 3.5 0 0 0 6.8 0H19v3zm0-5h-4.7a3.5 3.5 0 0 1-6.6 0H5V5h14v9z","chevron-down":"M7.4 8.6 12 13.2l4.6-4.6L18 10l-6 6-6-6 1.4-1.4z",settings:"M19.14 12.94c.04-.3.06-.61.06-.94 0-.32-.02-.64-.07-.94l2.03-1.58a.49.49 0 0 0 .12-.61l-1.92-3.32a.488.488 0 0 0-.59-.22l-2.39.96c-.5-.38-1.03-.7-1.62-.94l-.36-2.54a.484.484 0 0 0-.48-.41h-3.84c-.24 0-.43.17-.47.41l-.36 2.54c-.59.24-1.13.57-1.62.94l-2.39-.96c-.22-.08-.47 0-.59.22L2.74 8.87c-.12.21-.08.47.12.61l2.03 1.58c-.05.3-.09.63-.09.94s.02.64.07.94l-2.03 1.58a.49.49 0 0 0-.12.61l1.92 3.32c.12.22.37.29.59.22l2.39-.96c.5.38 1.03.7 1.62.94l.36 2.54c.05.24.24.41.48.41h3.84c.24 0 .44-.17.47-.41l.36-2.54c.59-.24 1.13-.56 1.62-.94l2.39.96c.22.08.47 0 .59-.22l1.92-3.32c.12-.22.07-.47-.12-.61l-2.01-1.58zM12 15.6a3.6 3.6 0 1 1 0-7.2 3.6 3.6 0 0 1 0 7.2z",pin:"M16 12V4h1V2H7v2h1v8l-4 4v2h5.2v6h1.6v-6H20v-2l-4-4z","pin-outline":"M16 12V4h1V2H7v2h1v8l-4 4v2h5.2v6h1.6v-6H20v-2l-4-4zm-4.8 7.2V11l2-2V4h1.6v5l2 2v5.2H11.2z",folder:"M10 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2h-8l-2-2z",file:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8l-6-6zm-1 2 5 5h-5V4zM6 20V4h5v7h7v9H6z",worktree:"M6 3a3 3 0 0 0-1 5.83v6.34a3 3 0 1 0 2 0V8.83A3 3 0 0 0 6 3zm0 2a1 1 0 1 1 0 2 1 1 0 0 1 0-2zm0 12a1 1 0 1 1 0 2 1 1 0 0 1 0-2zM18 3a3 3 0 0 0-1 5.83V9a4 4 0 0 1-4 4h-2a3 3 0 1 0 0 2h2a6 6 0 0 0 6-6v-.17A3 3 0 0 0 18 3zm0 2a1 1 0 1 1 0 2 1 1 0 0 1 0-2zM9 13a1 1 0 1 1 0 2 1 1 0 0 1 0-2z",copy:"M16 1H4c-1.1 0-2 .9-2 2v14h2V3h12V1zm3 4H8c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h11c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm0 16H8V7h11v14z",export:"M19 9h-4V3H9v6H5l7 7 7-7zM5 18v2h14v-2H5z",chevronRight:"M9.29 6.71a1 1 0 0 0 0 1.41L13.17 12l-3.88 3.88a1 1 0 1 0 1.41 1.41l4.59-4.59a1 1 0 0 0 0-1.41L10.7 6.7a1 1 0 0 0-1.41.01z",lightning:"M11 21h-1l1-7H7.5c-.58 0-.57-.32-.38-.66.19-.33.51-.89.73-1.27L13 3h1l-1 7h3.5c.49 0 .56.33.47.51l-.07.15c-.22.46-.58 1.18-.78 1.58L11 21z","git-branch":"M13.5 7a2.5 2.5 0 1 1-5 0 2.5 2.5 0 0 1 5 0zm0 10a2.5 2.5 0 1 1-5 0 2.5 2.5 0 0 1 5 0zM11 9.5v5.1a4.03 4.03 0 0 0-3-.1V9.4a4.03 4.03 0 0 0 3 .1z",external:"M14 3h7v7h-2V6l-9.29 9.29-1.41-1.41L17.59 4.5H14V3zm4 16H5V5h7V3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7h-2v7z",play:"M8 5v14l11-7L8 5z",stop:"M6 6h12v12H6V6z",warning:"M1 21h22L12 2 1 21zm12-3h-2v-2h2v2zm0-4h-2v-4h2v4z",info:"M11 7h2v2h-2V7zm0 4h2v6h-2v-6zm1-9C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2z",spinner:"M12 4V1L8 5l4 4V6c3.31 0 6 2.69 6 6 0 1.01-.25 1.97-.7 2.8l1.46 1.46A7.93 7.93 0 0 0 20 12c0-4.42-3.58-8-8-8z",dots:"M6 10c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm12 0c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm-6 0c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2z"};function di(e){return Yt[e]??Yt.menu}function ce(e,t=""){return`<svg viewBox="0 0 24 24" fill="currentColor"${t?" "+t:""}><path d="${di(e)}"/></svg>`}var m={catalog:null,templates:[],bots:[],approvals:[],activeId:null,items:new Map,ws:null,pollTimer:0,renderQueued:!1};function yt(){try{return localStorage.getItem("tmux-web-token")||""}catch{return""}}async function T(e,t){let n=await fetch(e,{...t,headers:{"content-type":"application/json",Authorization:`Bearer ${yt()}`,...t?.headers||{}}}),i=await n.text(),a=i?JSON.parse(i):null;if(!n.ok)throw new Error(a&&a.error||`HTTP ${n.status}`);return a}function c(e,t,n){let i=document.createElement(e);return t&&(i.className=t),n!==void 0&&(i.textContent=n),i}function ci(e){return e==="running"?"var(--panel-success)":e==="waiting_approval"||e==="waiting_input"?"#e0a23c":e==="failed"?"var(--panel-danger, #e5534b)":e==="completed"?"var(--panel-accent)":"var(--panel-muted)"}function ye(){let e=document.getElementById("bots-view");if(!e)return;let t=window.visualViewport,n=window.matchMedia("(max-width: 640px)").matches,i=!document.querySelector(".sidebar")?.classList.contains("collapsed");if(m.activeId&&t&&n&&!i){let a=document.querySelector(".fixed-header"),r=a?Math.round(a.getBoundingClientRect().height):0;e.style.position="fixed",e.style.top=`${Math.round(t.offsetTop)+r}px`,e.style.left=`${Math.round(t.offsetLeft)}px`,e.style.width=`${Math.round(t.width)}px`,e.style.height=`${Math.max(120,Math.round(t.height)-r)}px`,e.style.right="auto",e.style.bottom="auto"}else e.style.position="",e.style.top="",e.style.left="",e.style.width="",e.style.height="",e.style.right="",e.style.bottom=""}window.visualViewport?.addEventListener("resize",ye),window.visualViewport?.addEventListener("scroll",ye),window.addEventListener("resize",ye),document.addEventListener("click",()=>setTimeout(ye,0));function Je(){let e=m.approvals.length,t=document.getElementById("bots-inbox-badge");t&&(t.style.display=e?"inline-block":"none",t.textContent=String(e));let n=document.getElementById("bv-inbox-count");n&&(n.textContent=e?`(${e})`:""),window.__botsSnapshot=m.bots,window.__refreshSidebar?.()}function ui(){let e=document.getElementById("set-bot-templates"),t=document.getElementById("set-bot-new"),n=document.getElementById("set-bot-inbox"),i=()=>{document.getElementById("settings-popover")?.classList.remove("open"),document.getElementById("settings-backdrop")?.classList.remove("open")};e?.addEventListener("click",()=>{i(),Ie()}),t?.addEventListener("click",()=>{i(),ki()}),n?.addEventListener("click",()=>{i(),xt()})}function pi(){let e=c("div","bots-view");e.id="bots-view",e.hidden=!0;let t=c("div","bots-view-head"),n=c("div","bv-title"),i=c("span","bots-dot");i.id="bv-dot";let a=c("span","bv-title-text");a.id="bv-title";let r=c("span","bv-status");r.id="bv-status",n.append(i,a,r);let o=c("div","bv-actions"),l=c("div","bv-mode"),u=c("button","bv-mode-btn");u.id="bv-mode-btn",u.type="button",u.title="\u5BA1\u6279\u6A21\u5F0F\uFF08\u70B9\u5F00\u770B\u8BF4\u660E\uFF09",u.innerHTML=`<span id="bv-mode-label"></span>${ce("chevron-down",'width="12" height="12"')}`;let p=c("div","bv-mode-menu");p.id="bv-mode-menu",p.hidden=!0;for(let[b,x,G]of[["supervised","\u9ED8\u8BA4","\u53EA\u8BFB\u5DE5\u5177\uFF08read/grep/find/ls\uFF09\u76F4\u63A5\u653E\u884C\uFF1Bbash\u3001edit\u3001write\u3001\u6269\u5C55/MCP \u5DE5\u5177\u4F1A\u95EE\u4F60"],["parent-supervised","\u76D1\u7BA1","\u5176\u4F59\u5DE5\u5177\u4EA4\u7ED9\u4E0A\u7EA7 bot \u51B3\u5B9A\uFF08\u5E26\u7406\u7531\uFF09\uFF1B\u4F60\u4ECD\u7136\u80FD\u770B\u5230\u5E76\u56DE\u7B54\uFF0C\u5148\u7B54\u5148\u5F97\uFF1B\u6CA1\u6709\u4E0A\u7EA7\u65F6\u56DE\u843D\u5230\u9ED8\u8BA4"],["full-access","\u5168\u653E\u884C","\u6240\u6709\u5DE5\u5177\u76F4\u63A5\u6267\u884C\uFF0C\u4E0D\u518D\u8BE2\u95EE\u3002\u6CE8\u610F\u8FD9\u4E0D\u662F\u6C99\u7BB1"]]){let v=c("button");v.dataset.mode=b,v.innerHTML=`<b>${x}</b><span>${G}</span>`,v.onclick=()=>{p.hidden=!0,mi(b)},p.appendChild(v)}u.onclick=b=>{b.stopPropagation(),p.hidden=!p.hidden},l.append(u,p),document.addEventListener("click",b=>{l.contains(b.target)||(p.hidden=!0)});let f=c("button","btn","Allow all");f.id="bv-allow-all",f.title="Approve every pending request for this bot",f.onclick=()=>{if(!m.activeId)return;let b=m.approvals.filter(x=>x.botId===m.activeId);Promise.all(b.map(x=>T(`/api/bots/${x.botId}/approve`,{method:"POST",body:JSON.stringify({requestId:x.id,allow:!0})}))).finally(()=>void Y(!0))};let y=c("button","btn","Needs you "),H=c("span");H.id="bv-inbox-count",y.appendChild(H),y.onclick=()=>void xt();let L=c("button","btn","Resume");L.onclick=()=>void Xt(b=>T(`/api/bots/${b}/resume`,{method:"POST"}).then(()=>Y(!0)));let w=c("button","btn danger","Stop");w.onclick=()=>void Xt(b=>T(`/api/bots/${b}/stop`,{method:"POST"}).then(()=>Y(!0)));let g=c("button","btn","Delete");g.onclick=()=>{m.activeId&&confirm("Delete this bot and its session?")&&T(`/api/bots/${m.activeId}`,{method:"DELETE"}).then(()=>{bt(),Y(!0)})};let M=c("button","btn");M.innerHTML=ce("close",'width="14" height="14"'),M.title="Close bot view",M.onclick=()=>bt(),o.append(l,f,y,L,w,g,M),t.append(n,o);let W=c("div","bots-messages");W.id="bots-messages";let P=c("div","bots-composer"),j=c("textarea");j.id="bots-input",j.rows=1,j.placeholder="Message the bot\u2026 (Enter to send, Shift+Enter for newline)",j.onkeydown=b=>{b.key==="Enter"&&!b.shiftKey&&(b.preventDefault(),Kt())};let R=c("button","btn primary");R.title="Send",R.setAttribute("aria-label","Send"),R.innerHTML='<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M12 19V5M5 12l7-7 7 7"/></svg>',R.onclick=()=>void Kt(),P.append(j,R),e.append(t,W,P),document.querySelector(".main-area")?.appendChild(e),document.getElementById("bots-modal")||wi()}async function Kt(){let e=document.getElementById("bots-input");if(!e||!m.activeId||!e.value.trim())return;let t=e.value;e.value="";try{await T(`/api/bots/${m.activeId}/input`,{method:"POST",body:JSON.stringify({text:t})})}catch(n){ue({kind:"notice",level:"error",text:n instanceof Error?n.message:String(n)})}}function Xt(e){m.activeId&&e(m.activeId).catch(t=>ue({kind:"notice",level:"error",text:t instanceof Error?t.message:String(t)}))}function bt(){m.activeId=null,ye();let e=document.getElementById("bots-view");e&&(e.hidden=!0);try{m.ws?.close()}catch{}m.ws=null,Je();let t=document.getElementById("terminal-container"),n=document.getElementById("main-placeholder"),i=!!document.querySelector(".session-item.active:not(.bot-item)");t&&i?(t.style.display="",n&&(n.style.display="none")):n&&(n.style.display="")}async function Qt(e){m.activeId=e,window.__collapseSidebar?.(),ye(),m.items.set(e,[]);let t=document.getElementById("bots-view");t&&(t.hidden=!1);let n=document.getElementById("main-placeholder");n&&(n.style.display="none");let i=document.getElementById("terminal-container");i&&(i.style.display="none");let a=document.getElementById("file-editor");a&&(a.style.display="none"),Je(),kt();try{m.ws?.close()}catch{}let r=location.protocol==="https:"?"wss:":"ws:",o=new WebSocket(`${r}//${location.host}/ws/bots/${encodeURIComponent(e)}?token=${encodeURIComponent(yt())}`);m.ws=o,o.onmessage=l=>{try{Gt(JSON.parse(String(l.data)))}catch{}},o.onclose=()=>{m.activeId===e&&setTimeout(()=>{m.activeId===e&&Y(!0)},1500)},await Y(!0)}function wt(){return m.bots.find(e=>e.id===m.activeId)||null}function Et(){let e=wt();if(!e)return;let t=document.getElementById("bv-title"),n=document.getElementById("bv-status"),i=document.getElementById("bv-dot");t&&(t.textContent=e.title),n&&(n.textContent=`${e.status.replace(/_/g," ")} \xB7 ${e.templateId} \xB7 ${e.projectPath}`);let a=document.getElementById("bv-mode-label");a&&e.runtimeMode&&(a.textContent=Zt[e.runtimeMode]||e.runtimeMode);for(let l of document.querySelectorAll("#bv-mode-menu button"))l.classList.toggle("active",l.dataset.mode===e.runtimeMode);let r=document.getElementById("bv-allow-all"),o=m.approvals.filter(l=>l.botId===e.id).length;r&&(r.hidden=o===0,r.textContent=`Allow all (${o})`),i&&(i.style.background=ci(e.status))}var Zt={supervised:"\u9ED8\u8BA4","parent-supervised":"\u76D1\u7BA1","full-access":"\u5168\u653E\u884C"};async function mi(e){if(m.activeId)try{await T(`/api/bots/${m.activeId}/mode`,{method:"POST",body:JSON.stringify({mode:e})});let t=wt();t&&(t.runtimeMode=e),Et(),ue({kind:"notice",level:"info",text:`\u5BA1\u6279\u6A21\u5F0F\uFF1A${Zt[e]||e}`})}catch(t){ue({kind:"notice",level:"error",text:t instanceof Error?t.message:String(t)})}}function ue(e,t=m.activeId){if(!t)return;let n=m.items.get(t)||[];n.push(e),m.items.set(t,n),t===m.activeId&&pe()}function pe(){m.renderQueued||(m.renderQueued=!0,requestAnimationFrame(()=>{m.renderQueued=!1,kt()}))}function kt(){let e=document.getElementById("bots-messages");if(!e||!m.activeId)return;let t=m.items.get(m.activeId)||[];e.textContent="";let n=null;for(let i of t)if(i.kind==="user"){let a=c("div","bv-msg bv-user");a.textContent=i.text,e.appendChild(a),n=null}else if(i.kind==="assistant"){let a=c("div","bv-msg bv-assistant");if(i.thinking){let o=c("details","bv-thinking");o.appendChild(c("summary",void 0,"thinking")),o.appendChild(c("div",void 0,i.thinking)),a.appendChild(o)}let r=c("div","bv-text");r.textContent=i.text,a.appendChild(r),e.appendChild(a),n=r}else if(i.kind==="tool")e.appendChild(hi(i)),n=null;else if(i.kind==="approval")e.appendChild(vi(i)),n=null;else if(i.kind==="notice"){let a=c("div",`bv-notice bv-notice-${i.level}`,i.text);e.appendChild(a)}n&&(n.scrollTop=n.scrollHeight),e.scrollTop=e.scrollHeight}function hi(e){let t=c("details","bv-tool");t.open=e.phase!=="end"||!!e.isError;let n=c("summary"),i=c("span","bv-tool-name",e.name);if(n.appendChild(i),e.phase!=="end"&&n.appendChild(c("span","bv-tool-phase",e.phase)),e.isError&&n.appendChild(c("span","bv-tool-error","error")),typeof e.durationMs=="number"&&n.appendChild(c("span","bv-tool-meta",`${Math.round(e.durationMs)}ms`)),t.appendChild(n),e.args!==void 0){let a=c("pre","bv-pre");a.textContent=typeof e.args=="string"?e.args:JSON.stringify(e.args,null,2),t.appendChild(a)}if(e.output){let a=c("pre","bv-pre bv-output");a.textContent=e.output,t.appendChild(a)}return t}function vi(e){let t=c("div","bv-approval"),n=e.approval;if(t.appendChild(c("div","bv-approval-title",n.title)),n.message&&t.appendChild(c("pre","bv-pre",n.message)),e.decided)return t.appendChild(c("div","bv-approval-decided",e.decided==="allowed"?"Allowed":"Denied")),t;let i=c("input","bv-reason");i.placeholder="reason (optional)";let a=c("div","bv-approval-actions"),r=c("button","btn primary","Allow"),o=c("button","btn",n.method==="confirm"&&/^Allow (.+?)\?$/.test(n.title)?`Always allow ${/^Allow (.+?)\?$/.exec(n.title)?.[1]}`:"Always allow");o.hidden=n.method!=="confirm";let l=c("button","btn danger","Deny"),u=async(p,f=!1)=>{try{await T(`/api/bots/${n.botId}/approve`,{method:"POST",body:JSON.stringify({requestId:n.id,allow:p,always:f,reason:i.value||void 0})}),e.decided=p?"allowed":"denied",pe(),Y(!0)}catch(y){ue({kind:"notice",level:"error",text:y instanceof Error?y.message:String(y)})}};return r.onclick=()=>void u(!0),o.onclick=()=>void u(!0,!0),l.onclick=()=>void u(!1),a.append(i,r,o,l),t.appendChild(a),t}function Gt(e){let t=String(e.type||""),n=m.activeId;if(!n)return;let i=m.items.get(n)||[];if(t==="snapshot")m.items.set(n,[]);else if(t==="user")ue({kind:"user",text:String(e.text||"")});else if(t==="status"){let a=wt();a&&(a.status=String(e.status||a.status)),Et(),yi()}else if(t==="message"){let a=e.message;if(!a||String(a.role||"")!=="assistant")return;let r=fi(a),o=gi(a),l=i[i.length-1];l&&l.kind==="assistant"?(l.text=r||l.text,l.thinking=o||l.thinking):i.push({kind:"assistant",text:r,thinking:o}),m.items.set(n,i),pe()}else if(t==="delta"){let a=String(e.kind||""),r=String(e.delta||""),o=i[i.length-1];(!o||o.kind!=="assistant")&&(i.push({kind:"assistant",text:"",thinking:""}),o=i[i.length-1]),o.kind==="assistant"&&(a==="text"?o.text+=r:a==="thinking"&&(o.thinking+=r)),m.items.set(n,i),pe()}else if(t==="tool"){let a=String(e.callId||""),r=i.find(l=>l.kind==="tool"&&l.callId===a),o=String(e.phase||"start");r?(r.phase=o,o==="update"&&e.output&&(r.output=String(e.output)),o==="end"&&(e.output&&(r.output=String(e.output)),r.isError=e.isError===!0,typeof e.durationMs=="number"&&(r.durationMs=e.durationMs))):i.push({kind:"tool",callId:a,name:String(e.name||"tool"),args:e.args,output:e.output?String(e.output):void 0,isError:e.isError===!0,durationMs:typeof e.durationMs=="number"?e.durationMs:void 0,phase:o}),m.items.set(n,i),pe()}else if(t==="approval"){let a=e.approval;if(!a)return;let r=i;for(let o=r.length-1;o>=0;o--){let l=r[o];if(l.kind==="approval"&&l.approval.id===a.id){l.approval=a,a.state!=="pending"&&(l.decided=a.state==="allowed"?"allowed":"denied"),m.items.set(n,r),pe();return}}r.push({kind:"approval",approval:a}),m.items.set(n,r),pe()}else t==="notice"&&ue({kind:"notice",level:String(e.level||"info"),text:String(e.text||"")})}function fi(e){let t=e.content;return Array.isArray(t)?t.map(n=>n&&typeof n=="object"&&n.type==="text"?String(n.text||""):"").join(""):String(e.text||"")}function gi(e){let t=e.content;return Array.isArray(t)?t.map(n=>n&&typeof n=="object"&&n.type==="thinking"?String(n.thinking||""):"").join(""):""}async function Y(e=!1){try{let[t,n]=await Promise.all([T("/api/bots"),T("/api/bots/approvals")]);if(m.bots=t,m.approvals=n,Je(),Et(),e&&m.activeId){let i=await T(`/api/bots/${m.activeId}/events?limit=300`);bi(i)}}catch{}}async function yi(){try{m.bots=await T("/api/bots"),Je()}catch{}}function bi(e){if(m.activeId){m.items.set(m.activeId,[]);for(let t of e)Gt(t);kt()}}function wi(){let e=c("div","bots-modal");e.id="bots-modal",e.hidden=!0;let t=c("div","bots-modal-card"),n=c("div","bots-modal-head"),i=c("span");i.id="bots-modal-title";let a=c("button","btn");a.innerHTML=ce("close",'width="14" height="14"'),a.title="Close",a.onclick=()=>Ye(),n.append(i,a);let r=c("div","bots-modal-body");r.id="bots-modal-body",t.append(n,r),e.appendChild(t),e.onclick=o=>{o.target===e&&Ye()},document.body.appendChild(e)}function Ct(e){let t=document.getElementById("bots-modal"),n=document.getElementById("bots-modal-title"),i=document.getElementById("bots-modal-body");if(!t||!i)throw new Error("modal missing");return n&&(n.textContent=e),i.textContent="",t.hidden=!1,i}function Ye(){let e=document.getElementById("bots-modal");e&&(e.hidden=!0)}async function Ei(){return m.catalog||(m.catalog=await T("/api/bots/catalog")),m.catalog}async function en(){return m.templates=await T("/api/bots/templates"),m.templates}async function Ie(){let e=Ct("Bot templates"),[t,n]=await Promise.all([Ei(),en()]),i=c("div","bv-template-list");for(let u of n){let p=c("div","bv-template-row");p.appendChild(c("span","bv-template-name",u.manifest.name)),p.appendChild(c("span","bv-template-desc",u.manifest.description||""));let f=c("button","btn","Edit");f.onclick=()=>tn(e,t,u);let y=c("button","btn","Copy");y.title="Duplicate this template",y.onclick=()=>{let w=JSON.parse(JSON.stringify(u.manifest));w.name=`${u.manifest.name} copy`,T("/api/bots/templates",{method:"POST",body:JSON.stringify({manifest:w})}).then(()=>Ie()).catch(g=>alert(g instanceof Error?g.message:String(g)))};let H=c("button","btn danger","Delete");H.onclick=()=>{confirm(`Delete template ${u.manifest.name}?`)&&T(`/api/bots/templates/${u.id}`,{method:"DELETE"}).then(()=>Ie())};let L=c("span","bv-template-actions");L.append(f,y,H),p.appendChild(L),i.appendChild(p)}n.length===0&&i.appendChild(c("div","bots-empty","No templates yet")),e.appendChild(i);let a=c("div","bv-template-actions"),r=c("button","btn primary","New template");r.onclick=()=>tn(e,t,null);let o=c("button","btn","Export");o.title="Download templates + library as JSON",o.onclick=()=>{(async()=>{try{let u=await fetch("/api/bots/export",{headers:{Authorization:`Bearer ${yt()}`}});if(!u.ok)throw new Error(`HTTP ${u.status}`);let p=await u.blob(),f=document.createElement("a");f.href=URL.createObjectURL(p),f.download=`tmux-weblink-bots-${new Date().toISOString().slice(0,10)}.json`,f.click(),setTimeout(()=>URL.revokeObjectURL(f.href),2e3)}catch(u){alert(u instanceof Error?u.message:String(u))}})()};let l=c("button","btn","Import");l.title="Restore templates from a JSON bundle",l.onclick=()=>{let u=document.createElement("input");u.type="file",u.accept="application/json,.json",u.onchange=()=>{let p=u.files?.[0];p&&(async()=>{try{let f=JSON.parse(await p.text()),y=await T("/api/bots/import",{method:"POST",body:JSON.stringify(f)});alert(`Imported ${y.templates} templates, ${y.files} library files (${y.skipped} kept)`),await Ie()}catch(f){alert(f instanceof Error?f.message:String(f))}})()},u.click()},a.append(r,o,l),e.appendChild(a)}function Lt(e,t,n){let i=c("div","bv-field");i.appendChild(c("label","bv-label",e));let a=c("div","bv-check-grid"),r=[];for(let o of t){let l=c("label","bv-check"),u=document.createElement("input");u.type="checkbox",u.checked=n.includes(o.id),l.append(u,c("span",void 0,o.label)),o.hint&&(l.title=o.hint),a.appendChild(l),r.push({id:o.id,input:u})}return i.appendChild(a),{element:i,get:()=>r.filter(o=>o.input.checked).map(o=>o.id)}}function tn(e,t,n){e.textContent="";let i=n?JSON.parse(JSON.stringify(n.manifest)):{name:"new-bot",description:""},a=c("input","bv-input");a.value=i.name,a.placeholder="Template name";let r=c("input","bv-input");r.value=i.description||"",r.placeholder="One line description";let o=c("textarea","bv-textarea");o.rows=6,o.value=i.system||"",o.placeholder="System prompt for this bot (written to SYSTEM.md)";let l=Lt("Skills",t.skills.map(v=>({id:v.id,label:v.name,hint:v.description})),i.skills||[]),u=Lt("Extensions (Pi builtins + library)",t.extensions.map(v=>({id:v.id,label:`${v.name}${v.kind==="builtin"?" (builtin)":""}`,hint:v.description})),(i.extensions||[]).map(v=>v.replace(/^.*\//,"").replace(/\.(js|ts)$/,""))),p=Lt("Prompt templates",t.prompts.map(v=>({id:v.id,label:v.name})),i.prompts||[]),f=c("select","bv-input");f.appendChild(new Option("none",""));for(let v of t.mcp)f.appendChild(new Option(v.name,v.id));i.mcp&&(f.value=t.mcp.find(v=>JSON.stringify(v.servers)===JSON.stringify(i.mcp?.mcpServers))?.id||"");let y=c("div","bv-field");y.appendChild(c("label","bv-label","Tools (allow list; deny always blocks)"));let H=c("div","bv-check-grid"),L=[];for(let v of t.tools){let _=c("label","bv-check"),B=document.createElement("input");B.type="checkbox",B.checked=(i.tools?.allow||[]).includes(v.name)||!i.tools?.allow?.length&&["read","grep","find","ls","edit","write","bash"].includes(v.name),_.append(B,c("span",void 0,v.name)),H.appendChild(_),L.push({name:v.name,input:B})}y.appendChild(H);let w=c("input","bv-input");w.value=(i.tools?.deny||[]).join(", "),w.placeholder="Always deny (comma separated), e.g. bash, write";let g=c("textarea","bv-textarea");g.rows=2,g.value=(i.packages||[]).join(`
9
+ `),g.placeholder="Pi packages, one per line (npm:@scope/pkg@1.2.3, git:..., ./path)";let M=c("select","bv-input");M.appendChild(new Option("default (Pi settings)",""));for(let v of t.models)M.appendChild(new Option(`${v.provider}/${v.model}`,`${v.provider}
10
+ ${v.model}`));i.model?.provider&&i.model?.id&&(M.value=`${i.model.provider}
11
+ ${i.model.id}`);let W=c("select","bv-input");for(let v of["","off","minimal","low","medium","high","xhigh","max"])W.appendChild(new Option(v||"default",v));i.model?.thinking&&(W.value=i.model.thinking);let P=c("select","bv-input");for(let v of["supervised","auto-accept-edits","full-access"])P.appendChild(new Option(v,v));P.value=i.permissions?.runtimeMode||"supervised";let j=c("select","bv-input");j.appendChild(new Option("ignore project .pi (recommended)","ignore")),j.appendChild(new Option("inherit project .pi (needs trust)","inherit")),j.value=i.projectResources||"ignore";let R=c("label","bv-check"),b=document.createElement("input");b.type="checkbox",b.checked=!!i.orchestrator,R.append(b,c("span",void 0,"Super bot: gets orchestration tools (create/stop/status child bots)"));let x=(v,_)=>{let B=c("div","bv-field");return B.appendChild(c("label","bv-label",v)),B.appendChild(_),B};e.append(x("Name",a),x("Description",r),x("System prompt",o),l.element,u.element,p.element,x("MCP preset",f),y,x("Always deny tools",w),x("Packages",g),x("Model",M),x("Thinking level",W),x("Approval mode",P),x("Project resources",j),R);let G=c("button","btn primary",n?"Save template":"Create template");G.onclick=async()=>{let[v,_]=M.value.split(`
12
+ `),B=t.mcp.find(A=>A.id===f.value),le={name:a.value.trim()||"bot",description:r.value.trim()||void 0,system:o.value.trim()||void 0,skills:l.get(),extensions:u.get().map(A=>(A.startsWith("builtin:"),A)),prompts:p.get(),packages:g.value.split(`
13
+ `).map(A=>A.trim()).filter(Boolean),mcp:B?{mcpServers:B.servers}:void 0,tools:{allow:L.filter(A=>A.input.checked).map(A=>A.name),deny:w.value.split(",").map(A=>A.trim()).filter(Boolean)},model:v?{provider:v,id:_,thinking:W.value||void 0}:void 0,permissions:{runtimeMode:P.value},projectResources:j.value==="inherit"?"inherit":"ignore",orchestrator:b.checked||void 0};try{await T("/api/bots/templates",{method:"POST",body:JSON.stringify({id:n?.id,manifest:le})}),Ye(),await Ie()}catch(A){alert(A instanceof Error?A.message:String(A))}},e.appendChild(G)}async function ki(){return nn("")}async function nn(e){let t=Ct("New bot"),n=await en();if(n.length===0){t.appendChild(c("div","bots-empty","No templates yet \u2014 create one with \u201CNew template\u201D."));return}let i=c("select","bv-input");for(let p of n)i.appendChild(new Option(p.manifest.name,p.id));let a=c("input","bv-input");a.placeholder="Title (defaults to template name)";let r=c("input","bv-input");r.placeholder="/path/to/project";let o=e||m.bots[0]?.projectPath||"";r.value=o;let l=c("select","bv-input");l.appendChild(new Option("shared \u2014 run in the project folder","shared")),l.appendChild(new Option("worktree \u2014 isolated git worktree","worktree")),t.append(Ke("Template",i),Ke("Title",a),Ke("Project path",r),Ke("Workspace",l));let u=c("button","btn primary","Create bot");u.onclick=async()=>{try{let p=await T("/api/bots",{method:"POST",body:JSON.stringify({templateId:i.value,title:a.value.trim()||void 0,projectPath:r.value.trim()||void 0,isolation:l.value})});Ye(),await Y(!0),await Qt(p.id)}catch(p){alert(p instanceof Error?p.message:String(p))}},t.appendChild(u)}function Ke(e,t){let n=c("div","bv-field");return n.appendChild(c("label","bv-label",e)),n.appendChild(t),n}async function xt(){let e=Ct("Needs you");if(m.approvals=await T("/api/bots/approvals"),m.approvals.length===0){e.appendChild(c("div","bots-empty","Nothing waiting."));return}for(let t of m.approvals){let n=c("div","bv-approval");n.appendChild(c("div","bv-approval-title",`${t.botTitle}: ${t.title}`)),t.message&&n.appendChild(c("pre","bv-pre",t.message));let i=c("input","bv-reason");i.placeholder="reason (optional)";let a=c("div","bv-approval-actions"),r=c("button","btn primary","Allow"),o=c("button","btn danger","Deny"),l=async u=>{await T(`/api/bots/${t.botId}/approve`,{method:"POST",body:JSON.stringify({requestId:t.id,allow:u,reason:i.value||void 0})}),await Y(!0),await xt()};r.onclick=()=>void l(!0),o.onclick=()=>void l(!1),a.append(i,r,o),n.appendChild(a),e.appendChild(n)}}function Ci(){window.__botsInited||(window.__botsInited=!0,pi(),ui(),window.__openBot=Qt,document.addEventListener("click",e=>{let t=e.target;t&&(t.closest(".session-item.bot-item")||t.closest(".session-item")&&m.activeId&&setTimeout(()=>bt(),0))},!0),Y(!0),m.pollTimer=window.setInterval(()=>{document.hidden||Y()},6e3),window.addEventListener("beforeunload",()=>window.clearInterval(m.pollTimer)))}var Be=window.__TMUX_WEB_SHELL__,S=null,z=null,Te=typeof window.__TMUX_WEB_SCOPE__?.agentId=="string"?window.__TMUX_WEB_SCOPE__.agentId:null,V=Te;window.__tmuxWebScopeAgent=Te;var St="sessions",ie="",Xe="",Qe="",an="";function $(e){return V?"/a/"+encodeURIComponent(V)+e:e}var k=document.getElementById("sidebar-content"),me=document.getElementById("main-placeholder"),q=document.getElementById("terminal-container"),ze=document.getElementById("file-editor"),Li=document.getElementById("fe-path"),K=document.getElementById("fe-status"),He=document.getElementById("fe-content"),he=document.getElementById("fe-save"),xi=document.getElementById("fe-delete"),Si=document.getElementById("fe-back"),on=document.getElementById("fe-new-name"),Mi=document.getElementById("fe-new-btn"),Mt=document.getElementById("settings-backdrop"),sn=document.getElementById("settings-popover"),ln=document.querySelector(".sidebar"),rn="tmux-web-force-narrow";function Ze(){try{return localStorage.getItem(rn)==="1"}catch{return!1}}function dn(){document.documentElement.classList.toggle("force-narrow",Ze()),Ze()&&cn()&&De()}function cn(){return Ze()?!0:window.matchMedia("(max-width: 640px)").matches}function De(){cn()&&ln.classList.add("collapsed")}function un(){ln.classList.remove("collapsed")}window.__collapseSidebar=De,document.getElementById("mode-sessions").addEventListener("click",()=>{un(),pn("sessions")}),document.getElementById("mode-files").addEventListener("click",()=>{un(),pn("files")});function pn(e){St=e,document.querySelectorAll(".mode-btn").forEach(n=>n.classList.remove("active"));let t=document.getElementById(e==="sessions"?"mode-sessions":"mode-files");t&&t.classList.add("active"),e==="sessions"?(It="",ae()):Ri()}var It="";async function ae(){if(St!=="sessions")return;try{let t=await(await fetch("/api/sidebar/sessions")).json(),n=(window.__botsSnapshot||[]).map(a=>[a.id,a.title,a.status,a.projectPath]),i=JSON.stringify({recent:t.recent,agents:t.agents,tombstones:t.tombstones,bots:n});if(i===It)return;It=i,Di(t)}catch{k.innerHTML+='<div class="file-tree-empty">Failed to load sessions</div>'}let e=document.getElementById("ns-btn");e&&e.addEventListener("click",()=>{let t=window.__openNewSessionModal;typeof t=="function"?t():document.getElementById("new-session-modal")?.classList.add("open")}),Ft()}var mn="tmux-web-sidebar-group-collapsed";function hn(){try{return new Set(JSON.parse(localStorage.getItem(mn)||"[]"))}catch{return new Set}}function Ii(e){try{localStorage.setItem(mn,JSON.stringify([...e]))}catch{}}function Bi(e,t,n){if(!e)return"\u2026";let i=n&&(e===n||e.startsWith(n+"/"))?"~"+e.slice(n.length):e,a=i.split("/").filter(Boolean);if(a.length===0)return e;for(let r=1;r<=a.length;r++){let o=a.slice(-r).join("/");if(!t.some(l=>!l||l===e?!1:(n&&(l===n||l.startsWith(n+"/"))?"~"+l.slice(n.length):l).split("/").filter(Boolean).slice(-r).join("/")===o))return o}return i}function Ti(e){let t=document.createElement("div");t.className="session-item bot-item",t.setAttribute("data-bot-id",e.id),t.title=`Bot \xB7 ${e.projectPath}`;let n=e.status==="running"?"var(--panel-success)":e.status==="waiting_approval"||e.status==="waiting_input"?"#e0a23c":e.status==="failed"?"var(--panel-danger, #e5534b)":"var(--panel-muted)";return t.innerHTML=`${ce("bot",'class="bot-icon"')}<span>${C(e.title)}</span><span class="bot-status-dot" style="background:${n}"></span>`,t.addEventListener("click",i=>{i.stopPropagation(),window.__openBot?.(e.id)}),t}function vn(e,t,n,i=!0){let a=new Map;for(let p of e){let f=p.path||"";a.has(f)||a.set(f,[]),a.get(f).push(p)}let r=n?[]:window.__botsSnapshot||[],o=new Map;for(let p of r)a.has(p.projectPath)||a.set(p.projectPath,[]),o.has(p.projectPath)||o.set(p.projectPath,[]),o.get(p.projectPath).push(p);let l=[...a.keys()],u=hn();for(let[p,f]of a){let y=Bi(p,l,t),H=u.has(p),L=document.createElement("div");if(L.className="session-group-header"+(H?" collapsed":""),L.title=p||"No working directory",L.innerHTML=`<span class="sg-folder">&#128193;</span><span class="sg-label">${C(y)}</span>`,!n&&p){let g=document.createElement("button");g.className="sg-add-bot",g.innerHTML=ce("add",'width="12" height="12"'),g.title=`New bot in ${p}`,g.addEventListener("click",M=>{M.stopPropagation(),Tt(p)}),L.appendChild(g)}L.addEventListener("click",()=>{let g=hn(),M=L.nextElementSibling;g.has(p)?(g.delete(p),L.classList.remove("collapsed"),M?.classList.remove("collapsed")):(g.add(p),L.classList.add("collapsed"),M?.classList.add("collapsed")),Ii(g)});let w=document.createElement("div");w.className="session-group-body"+(H?" collapsed":"");for(let g of f)w.appendChild(n?zi(g,n,i):Hi(g));for(let g of o.get(p)||[])w.appendChild(Ti(g));k.appendChild(L),k.appendChild(w)}}function zi(e,t,n){let i=document.createElement("div");i.className="session-item"+(e.name===z&&V===t?" active":"")+(n?"":" session-offline"),i.setAttribute("data-session",e.name),i.setAttribute("data-agent",t),i.innerHTML=`<svg viewBox="0 0 24 24" fill="currentColor"><path d="${e.attached?"M19 4H5a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6a2 2 0 0 0-2-2zm0 14H5V6h14v12z":"M4 6h16v2H4V6zm0 5h16v2H4v-2zm0 5h16v2H4v-2z"}"></svg>
14
14
  <span>${C(e.name)}</span>${n?"":'<span class="meta">offline</span>'}
15
- <button class="session-edit-btn" data-session="${C(e.name)}" title="Edit session"><svg viewBox="0 0 24 24" fill="currentColor" width="14" height="14"><path d="M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM20.71 7.04a1 1 0 000-1.41l-2.34-2.34a1 1 0 00-1.41 0l-1.83 1.83 3.75 3.75 1.83-1.83z"/></svg></button>`,n&&i.addEventListener("click",r=>{r.target.closest(".session-edit-btn")||De(e.name,t)});let a=i.querySelector(".session-edit-btn");return a&&a.addEventListener("click",r=>{r.stopPropagation(),ot(e.name,a,{agentId:t})}),i}function Bi(e){let t=document.createElement("div");t.className="session-item"+(e.name===M&&!H?" active":""),t.setAttribute("data-session",e.name),t.innerHTML=`<svg viewBox="0 0 24 24" fill="currentColor"><path d="${e.attached?"M19 4H5a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6a2 2 0 0 0-2-2zm0 14H5V6h14v12z":"M4 6h16v2H4V6zm0 5h16v2H4v-2zm0 5h16v2H4v-2z"}"></svg>
15
+ <button class="session-edit-btn" data-session="${C(e.name)}" title="Edit session"><svg viewBox="0 0 24 24" fill="currentColor" width="14" height="14"><path d="M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM20.71 7.04a1 1 0 000-1.41l-2.34-2.34a1 1 0 00-1.41 0l-1.83 1.83 3.75 3.75 1.83-1.83z"/></svg></button>`,n&&i.addEventListener("click",r=>{r.target.closest(".session-edit-btn")||Ae(e.name,t)});let a=i.querySelector(".session-edit-btn");return a&&a.addEventListener("click",r=>{r.stopPropagation(),rt(e.name,a,{agentId:t})}),i}function Hi(e){let t=document.createElement("div");t.className="session-item"+(e.name===z&&!V?" active":""),t.setAttribute("data-session",e.name),t.innerHTML=`<svg viewBox="0 0 24 24" fill="currentColor"><path d="${e.attached?"M19 4H5a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6a2 2 0 0 0-2-2zm0 14H5V6h14v12z":"M4 6h16v2H4V6zm0 5h16v2H4v-2zm0 5h16v2H4v-2z"}"></svg>
16
16
  <span>${C(e.name)}</span>
17
17
  <button class="session-edit-btn" data-session="${C(e.name)}" title="Edit session"><svg viewBox="0 0 24 24" fill="currentColor" width="14" height="14"><path d="M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM20.71 7.04a1 1 0 000-1.41l-2.34-2.34a1 1 0 00-1.41 0l-1.83 1.83 3.75 3.75 1.83-1.83z"/></svg></button>
18
- `,t.addEventListener("click",i=>{i.target.closest(".session-edit-btn")||De(e.name)});let n=t.querySelector(".session-edit-btn");return n&&n.addEventListener("click",i=>{i.stopPropagation(),ot(e.name,n)}),t}function Ti(e){k.innerHTML='<button class="new-session-sidebar-btn" id="ns-btn">+ New Session</button>';let t=e.recent||[],n=document.createElement("div");n.className="sidebar-section-label"+(Be?" clickable":""),n.textContent=Be?"\u2190 \u8FD4\u56DE\u672C\u673A":"\u672C\u673A",Be&&(n.title="Back to hub",n.addEventListener("click",()=>{window.location.href="/"})),k.appendChild(n),pn(t,e.home);let i=e.agents||[];for(let r of i){if(!r.sessions||r.sessions.length===0)continue;let s=r.agentId===H,l=document.createElement("div");l.className="sidebar-section-label machine-label"+(r.online?"":" agent-offline-label")+(!s&&r.online?" clickable":""),l.textContent=r.agentName+(r.online?"":" (offline)"),!s&&r.online&&(l.title="\u6253\u5F00 "+r.agentName,l.addEventListener("click",()=>{window.location.href="/a/"+encodeURIComponent(r.agentId)+"/"})),k.appendChild(l),pn(r.sessions,e.home,r.agentId,r.online)}let a=e.tombstones||[];if(a.length>0){let r=document.createElement("div");r.className="sidebar-section-label tombstone-label",r.textContent="\u5931\u6548\u4F1A\u8BDD",k.appendChild(r);for(let s of a){let l=document.createElement("div");l.className="session-item session-tombstone",l.setAttribute("data-session",s.name),s.agentId&&l.setAttribute("data-agent",s.agentId);let p=s.agentId?s.agentOnline?" (agent)":" (agent \u79BB\u7EBF)":"";l.innerHTML=`<svg viewBox="0 0 24 24" fill="currentColor"><path d="M4 6h16v2H4V6zm0 5h16v2H4v-2zm0 5h16v2H4v-2z"></svg>
19
- <span>${C(s.name)}</span><span class="meta">\u5931\u6548${p}</span>
20
- <button class="session-edit-btn" data-session="${C(s.name)}" title="\u6062\u590D\u4F1A\u8BDD"><svg viewBox="0 0 24 24" fill="currentColor" width="14" height="14"><path d="M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM20.71 7.04a1 1 0 000-1.41l-2.34-2.34a1 1 0 00-1.41 0l-1.83 1.83 3.75 3.75 1.83-1.83z"/></svg></button>`,l.title="\u5931\u6548\u4F1A\u8BDD\uFF1A\u70B9\u51FB\u7BA1\u7406\uFF08\u91CD\u5EFA/\u91CD\u547D\u540D/\u5220\u9664\uFF09",l.addEventListener("click",()=>{ot(s.name,l,{tombstone:!0,agentId:s.agentId})});let u=l.querySelector(".session-edit-btn");u&&u.addEventListener("click",v=>{v.stopPropagation(),ot(s.name,u,{tombstone:!0,agentId:s.agentId})}),k.appendChild(l)}}}function C(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}async function De(e,t){if(M===e&&L&&H===(t||null))return;Te.style.display="none",pe.style.display="none",J.style.display="",J.classList.add("terminal-pending"),Xe(),L&&(at(),L.destroy(),L=null),M=e,H=t||null,window.__tmuxWebScopeAgent=H,window.__tmuxWebCurrentSession=M,ea(e,t);let n=At(e,t);In.set(n,Date.now()+Zi);let i=ye.get(n);if(i&&i.state==="working"){i.state="idle",i.doneUntil=void 0,i.unread=!1;let a=k.querySelector(t?'.session-item[data-agent="'+CSS.escape(t)+'"][data-session="'+CSS.escape(e)+'"]':'.session-item[data-session="'+CSS.escape(e)+'"]:not([data-agent])');a&&ut(a,n,i)}for(let a of k.querySelectorAll(".session-item"))a.classList.toggle("active",a.getAttribute("data-session")===e&&(a.getAttribute("data-agent")||null)===H);try{L=await si(J,e,{terminal:Ie.terminal,scrollback:Ie.scrollback,theme:Ie.theme,wsBase:H?"/ws/a/"+encodeURIComponent(H):Ie.wsBase||"/ws"}),kn()}catch(a){console.error("[shell] terminal init failed:",a);let r=a&&typeof a=="object"&&"message"in a?a.message:String(a);J.textContent="Failed to open terminal for "+e+": "+r,J.classList.remove("terminal-pending")}}var Qe=[],F=null,mn=!1;function Mi(e){if(!F||!F.files.length)return null;let t=F.repoRoot;if(!t||!e.startsWith(t))return null;let n=e.slice(t.length+1);for(let i of F.files)if(i.path===n)return i.status;return null}async function Di(e){mn=!0;try{let t=await fetch(N("/api/git/status?path="+encodeURIComponent(e)));t.ok?F=await t.json():F=null}catch{F=null}finally{mn=!1}}function Ai(){if(!F||!F.branch)return"";let{branch:e,linesAdded:t,linesRemoved:n}=F,i=`<div class="sidebar-git"><div class="git-branch-badge">
18
+ `,t.addEventListener("click",i=>{i.target.closest(".session-edit-btn")||Ae(e.name)});let n=t.querySelector(".session-edit-btn");return n&&n.addEventListener("click",i=>{i.stopPropagation(),rt(e.name,n)}),t}function Di(e){k.innerHTML='<button class="new-session-sidebar-btn" id="ns-btn">+ New Session</button>';let t=e.recent||[],n=document.createElement("div");n.className="sidebar-section-label"+(Te?" clickable":""),n.textContent=Te?"\u2190 \u8FD4\u56DE\u672C\u673A":"\u672C\u673A",Te&&(n.title="Back to hub",n.addEventListener("click",()=>{window.location.href="/"})),k.appendChild(n),vn(t,e.home);let i=e.agents||[];for(let r of i){if(!r.sessions||r.sessions.length===0)continue;let o=r.agentId===V,l=document.createElement("div");l.className="sidebar-section-label machine-label"+(r.online?"":" agent-offline-label")+(!o&&r.online?" clickable":""),l.textContent=r.agentName+(r.online?"":" (offline)"),!o&&r.online&&(l.title="\u6253\u5F00 "+r.agentName,l.addEventListener("click",()=>{window.location.href="/a/"+encodeURIComponent(r.agentId)+"/"})),k.appendChild(l),vn(r.sessions,e.home,r.agentId,r.online)}let a=e.tombstones||[];if(a.length>0){let r=document.createElement("div");r.className="sidebar-section-label tombstone-label",r.textContent="\u5931\u6548\u4F1A\u8BDD",k.appendChild(r);for(let o of a){let l=document.createElement("div");l.className="session-item session-tombstone",l.setAttribute("data-session",o.name),o.agentId&&l.setAttribute("data-agent",o.agentId);let u=o.agentId?o.agentOnline?" (agent)":" (agent \u79BB\u7EBF)":"";l.innerHTML=`<svg viewBox="0 0 24 24" fill="currentColor"><path d="M4 6h16v2H4V6zm0 5h16v2H4v-2zm0 5h16v2H4v-2z"></svg>
19
+ <span>${C(o.name)}</span><span class="meta">\u5931\u6548${u}</span>
20
+ <button class="session-edit-btn" data-session="${C(o.name)}" title="\u6062\u590D\u4F1A\u8BDD"><svg viewBox="0 0 24 24" fill="currentColor" width="14" height="14"><path d="M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM20.71 7.04a1 1 0 000-1.41l-2.34-2.34a1 1 0 00-1.41 0l-1.83 1.83 3.75 3.75 1.83-1.83z"/></svg></button>`,l.title="\u5931\u6548\u4F1A\u8BDD\uFF1A\u70B9\u51FB\u7BA1\u7406\uFF08\u91CD\u5EFA/\u91CD\u547D\u540D/\u5220\u9664\uFF09",l.addEventListener("click",()=>{rt(o.name,l,{tombstone:!0,agentId:o.agentId})});let p=l.querySelector(".session-edit-btn");p&&p.addEventListener("click",f=>{f.stopPropagation(),rt(o.name,p,{tombstone:!0,agentId:o.agentId})}),k.appendChild(l)}}}function C(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}async function Ae(e,t){if(z===e&&S&&V===(t||null))return;ze.style.display="none",me.style.display="none",q.style.display="",q.classList.add("terminal-pending"),De(),S&&(st(),S.destroy(),S=null),z=e,V=t||null,window.__tmuxWebScopeAgent=V,window.__tmuxWebCurrentSession=z,aa(e,t);let n=At(e,t);Tn.set(n,Date.now()+na);let i=Ee.get(n);if(i&&i.state==="working"){i.state="idle",i.doneUntil=void 0,i.unread=!1;let a=k.querySelector(t?'.session-item[data-agent="'+CSS.escape(t)+'"][data-session="'+CSS.escape(e)+'"]':'.session-item[data-session="'+CSS.escape(e)+'"]:not([data-agent])');a&&mt(a,n,i)}for(let a of k.querySelectorAll(".session-item"))a.classList.toggle("active",a.getAttribute("data-session")===e&&(a.getAttribute("data-agent")||null)===V);try{S=await ri(q,e,{terminal:Be.terminal,scrollback:Be.scrollback,theme:Be.theme,wsBase:V?"/ws/a/"+encodeURIComponent(V):Be.wsBase||"/ws"}),xn()}catch(a){console.error("[shell] terminal init failed:",a);let r=a&&typeof a=="object"&&"message"in a?a.message:String(a);q.textContent="Failed to open terminal for "+e+": "+r,q.classList.remove("terminal-pending")}}var Ge=[],D=null,fn=!1;function Ai(e){if(!D||!D.files.length)return null;let t=D.repoRoot;if(!t||!e.startsWith(t))return null;let n=e.slice(t.length+1);for(let i of D.files)if(i.path===n)return i.status;return null}async function Fi(e){fn=!0;try{let t=await fetch($("/api/git/status?path="+encodeURIComponent(e)));t.ok?D=await t.json():D=null}catch{D=null}finally{fn=!1}}function $i(){if(!D||!D.branch)return"";let{branch:e,linesAdded:t,linesRemoved:n}=D,i=`<div class="sidebar-git"><div class="git-branch-badge">
21
21
  <svg viewBox="0 0 16 16" fill="currentColor"><path d="M11.63 1.22a.75.75 0 00-1.06 0L5.99 5.8 4.12 3.93a.75.75 0 10-1.06 1.06L4.93 6.87A3.5 3.5 0 003 10.09v3.16a.75.75 0 001 0v-3.16a2.5 2.5 0 012.5-2.5h.27l-1.06 1.06a.75.75 0 001.06 1.06l2.37-2.38a.75.75 0 000-1.06L7.59 5.27l4.04-4.05a.75.75 0 000-1.06L11.63 1.22zM3.25 13.94a.75.75 0 01-.75-.75v-.69a.75.75 0 011.5 0v.69c0 .414-.336.75-.75.75z"/></svg>
22
- ${C(e)}</div>`;return(t>0||n>0)&&(i+=`<div class="git-diff-stats">+<span class="add">${t}</span> <span class="del">-${n}</span></div>`),i+"</div>"}k.addEventListener("click",e=>{e.target.closest(".sidebar-git")&&ge&&F&&(e.stopPropagation(),bn())});var Ae=document.getElementById("header-git"),fn=document.getElementById("git-diff-view"),hn=document.getElementById("gd-path"),Ze=document.getElementById("gd-status"),Ge=document.getElementById("gd-content"),Fi=document.getElementById("gd-back"),ge=null;function Fe(e){if(!e||!e.branch){Ae.style.display="none",ge=null;return}ge=e.repoRoot;let{branch:t,linesAdded:n,linesRemoved:i}=e,a=`<span class="branch">${C(t)}</span>`;(n>0||i>0)&&(a+=`<span class="sep">\xB7</span>+<span class="diff-add">${n}</span> <span class="diff-del">-${i}</span>`),Ae.innerHTML=a,Ae.style.display="block"}Ae.addEventListener("click",e=>{ge&&F&&(e.stopPropagation(),bn())});var R=document.getElementById("git-popover"),et=document.getElementById("git-popover-backdrop");function It(){let e=Ae.getBoundingClientRect();R.style.top=e.bottom+4+"px",R.style.left=Math.max(8,Math.min(e.left,window.innerWidth-400))+"px"}function vn(){let e=ge,t=document.getElementById("git-popover-browse");t&&t.addEventListener("click",()=>{if(nt(),e){xt="files",document.querySelectorAll(".mode-btn").forEach(i=>i.classList.remove("active"));let n=document.getElementById("mode-files");n&&n.classList.add("active"),se(e)}})}var gn="";function bn(){if(!F)return;let e=F.files||[];if(!e.length)R.innerHTML=`<div class="git-popover-header">No changes \u2014 clean working tree</div>
23
- <div class="git-popover-footer"><button id="git-popover-browse">Browse repository \u2192</button></div>`;else{let t=`<div class="git-popover-header">${e.length} file${e.length>1?"s":""} changed</div>`;for(let n=0;n<e.length;n++){let i=e[n],a=i.additions||0,r=i.deletions||0,s="";switch(i.status){case"M":s='<span class="git-file-status M">M</span>';break;case"A":s='<span class="git-file-status A">A</span>';break;case"D":s='<span class="git-file-status D">D</span>';break;case"?":s='<span class="git-file-status ?">?</span>';break;case"R":s='<span class="git-file-status R">R</span>';break}t+=`<div class="git-popover-item" data-idx="${n}">
24
- ${s}<span class="file-path">${C(i.path)}</span>
22
+ ${C(e)}</div>`;return(t>0||n>0)&&(i+=`<div class="git-diff-stats">+<span class="add">${t}</span> <span class="del">-${n}</span></div>`),i+"</div>"}k.addEventListener("click",e=>{e.target.closest(".sidebar-git")&&be&&D&&(e.stopPropagation(),En())});var Fe=document.getElementById("header-git"),gn=document.getElementById("git-diff-view"),yn=document.getElementById("gd-path"),et=document.getElementById("gd-status"),tt=document.getElementById("gd-content"),Pi=document.getElementById("gd-back"),be=null;function $e(e){if(!e||!e.branch){Fe.style.display="none",be=null;return}be=e.repoRoot;let{branch:t,linesAdded:n,linesRemoved:i}=e,a=`<span class="branch">${C(t)}</span>`;(n>0||i>0)&&(a+=`<span class="sep">\xB7</span>+<span class="diff-add">${n}</span> <span class="diff-del">-${i}</span>`),Fe.innerHTML=a,Fe.style.display="block"}Fe.addEventListener("click",e=>{be&&D&&(e.stopPropagation(),En())});var O=document.getElementById("git-popover"),nt=document.getElementById("git-popover-backdrop");function Bt(){let e=Fe.getBoundingClientRect();O.style.top=e.bottom+4+"px",O.style.left=Math.max(8,Math.min(e.left,window.innerWidth-400))+"px"}function bn(){let e=be,t=document.getElementById("git-popover-browse");t&&t.addEventListener("click",()=>{if(at(),e){St="files",document.querySelectorAll(".mode-btn").forEach(i=>i.classList.remove("active"));let n=document.getElementById("mode-files");n&&n.classList.add("active"),oe(e)}})}var wn="";function En(){if(!D)return;let e=D.files||[];if(!e.length)O.innerHTML=`<div class="git-popover-header">No changes \u2014 clean working tree</div>
23
+ <div class="git-popover-footer"><button id="git-popover-browse">Browse repository \u2192</button></div>`;else{let t=`<div class="git-popover-header">${e.length} file${e.length>1?"s":""} changed</div>`;for(let n=0;n<e.length;n++){let i=e[n],a=i.additions||0,r=i.deletions||0,o="";switch(i.status){case"M":o='<span class="git-file-status M">M</span>';break;case"A":o='<span class="git-file-status A">A</span>';break;case"D":o='<span class="git-file-status D">D</span>';break;case"?":o='<span class="git-file-status ?">?</span>';break;case"R":o='<span class="git-file-status R">R</span>';break}t+=`<div class="git-popover-item" data-idx="${n}">
24
+ ${o}<span class="file-path">${C(i.path)}</span>
25
25
  <span class="file-add">${a>0?"+"+a:""}</span>
26
26
  <span class="file-del">${r>0?"-"+r:""}</span>
27
- </div>`}t+='<div class="git-popover-footer"><button id="git-popover-browse">Browse repository \u2192</button></div>',gn=t,R.innerHTML=t,R.querySelectorAll(".git-popover-item").forEach(n=>{let i=parseInt(n.dataset.idx||"0",10),a=e[i];!a||a.status==="D"||(n.classList.add("clickable"),n.style.cursor="pointer",n.addEventListener("click",()=>wn(a.path)))})}It(),R.classList.add("open"),et.classList.add("open"),vn()}function $i(){return window.innerWidth>=1024}function yn(e,t){let n=(e+(t&&e?`
27
+ </div>`}t+='<div class="git-popover-footer"><button id="git-popover-browse">Browse repository \u2192</button></div>',wn=t,O.innerHTML=t,O.querySelectorAll(".git-popover-item").forEach(n=>{let i=parseInt(n.dataset.idx||"0",10),a=e[i];!a||a.status==="D"||(n.classList.add("clickable"),n.style.cursor="pointer",n.addEventListener("click",()=>Cn(a.path)))})}Bt(),O.classList.add("open"),nt.classList.add("open"),bn()}function Ni(){return window.innerWidth>=1024}function kn(e,t){let n=(e+(t&&e?`
28
28
  `:"")+t).split(`
29
- `),i="",a=0,r=0;for(let s of n){let l=s;if(l.startsWith("@@")){let p=l.match(/@@\s+-(\d+)[^+]*\+(\d+)/);p&&(a=parseInt(p[1],10)-1,r=parseInt(p[2],10)-1),i+=`<div class="diff-line hunk"><span class="ln-body">${C(l)}</span></div>`;continue}if(l.startsWith("diff --git")||l.startsWith("index ")||l.startsWith("--- ")||l.startsWith("+++ ")||l.startsWith("new file")||l.startsWith("deleted file")){l.startsWith("diff --git")&&(i+=`<div class="diff-line header"><span class="ln-body">${C(l)}</span></div>`);continue}if(l.startsWith("+"))r++,i+=`<div class="diff-line add"><span class="ln-no">${r}</span><span class="ln-body">${C(l)}</span></div>`;else if(l.startsWith("-"))a++,i+=`<div class="diff-line del"><span class="ln-no">${a}</span><span class="ln-body">${C(l)}</span></div>`;else if(l.startsWith("\\"))i+=`<div class="diff-line"><span class="ln-body">${C(l)}</span></div>`;else{if(!l&&!a&&!r)continue;a++,r++,i+=`<div class="diff-line"><span class="ln-no">${a}</span><span class="ln-no" style="margin-right:12px">${r}</span><span class="ln-body">${C(l)}</span></div>`}}return{html:i,lineCount:n.length}}var tt=null;async function wn(e){let t=ge;if(t)if(nt(),$i()){J.style.display="none",L&&(at(),L.destroy(),L=null,tt=M,M=null),Fe(null),Te.style.display="none",pe.style.display="none",fn.style.display="flex",hn.textContent=e,Ze.textContent="Loading\u2026",Ge.innerHTML="";try{let n=await fetch(N("/api/git/diff?path="+encodeURIComponent(t)+"&file="+encodeURIComponent(e)));if(!n.ok)throw new Error(await n.text());let i=await n.json();Ni(e,i.diff,i.stagedDiff)}catch(n){let i=n instanceof Error?n.message:String(n);Ze.textContent="Error",Ge.innerHTML=`<div class="diff-empty" style="padding:24px;text-align:center;color:var(--panel-muted)">Error: ${C(i)}</div>`}}else{R.innerHTML=`<div class="git-diff-view"><div class="diff-header">
29
+ `),i="",a=0,r=0;for(let o of n){let l=o;if(l.startsWith("@@")){let u=l.match(/@@\s+-(\d+)[^+]*\+(\d+)/);u&&(a=parseInt(u[1],10)-1,r=parseInt(u[2],10)-1),i+=`<div class="diff-line hunk"><span class="ln-body">${C(l)}</span></div>`;continue}if(l.startsWith("diff --git")||l.startsWith("index ")||l.startsWith("--- ")||l.startsWith("+++ ")||l.startsWith("new file")||l.startsWith("deleted file")){l.startsWith("diff --git")&&(i+=`<div class="diff-line header"><span class="ln-body">${C(l)}</span></div>`);continue}if(l.startsWith("+"))r++,i+=`<div class="diff-line add"><span class="ln-no">${r}</span><span class="ln-body">${C(l)}</span></div>`;else if(l.startsWith("-"))a++,i+=`<div class="diff-line del"><span class="ln-no">${a}</span><span class="ln-body">${C(l)}</span></div>`;else if(l.startsWith("\\"))i+=`<div class="diff-line"><span class="ln-body">${C(l)}</span></div>`;else{if(!l&&!a&&!r)continue;a++,r++,i+=`<div class="diff-line"><span class="ln-no">${a}</span><span class="ln-no" style="margin-right:12px">${r}</span><span class="ln-body">${C(l)}</span></div>`}}return{html:i,lineCount:n.length}}var it=null;async function Cn(e){let t=be;if(t)if(at(),Ni()){q.style.display="none",S&&(st(),S.destroy(),S=null,it=z,z=null),$e(null),ze.style.display="none",me.style.display="none",gn.style.display="flex",yn.textContent=e,et.textContent="Loading\u2026",tt.innerHTML="";try{let n=await fetch($("/api/git/diff?path="+encodeURIComponent(t)+"&file="+encodeURIComponent(e)));if(!n.ok)throw new Error(await n.text());let i=await n.json();Oi(e,i.diff,i.stagedDiff)}catch(n){let i=n instanceof Error?n.message:String(n);et.textContent="Error",tt.innerHTML=`<div class="diff-empty" style="padding:24px;text-align:center;color:var(--panel-muted)">Error: ${C(i)}</div>`}}else{O.innerHTML=`<div class="git-diff-view"><div class="diff-header">
30
30
  <button class="diff-back">\u2190 Back</button>
31
31
  <span class="diff-filename">${C(e)}</span>
32
32
  <span class="diff-loading">Loading\u2026</span>
33
- </div></div>`,It(),R.classList.add("open"),et.classList.add("open");try{let n=await fetch(N("/api/git/diff?path="+encodeURIComponent(t)+"&file="+encodeURIComponent(e)));if(!n.ok)throw new Error(await n.text());let i=await n.json();Pi(e,i.diff,i.stagedDiff)}catch(n){let i=n instanceof Error?n.message:String(n);R.innerHTML=`<div class="git-diff-view"><div class="diff-header">
33
+ </div></div>`,Bt(),O.classList.add("open"),nt.classList.add("open");try{let n=await fetch($("/api/git/diff?path="+encodeURIComponent(t)+"&file="+encodeURIComponent(e)));if(!n.ok)throw new Error(await n.text());let i=await n.json();Vi(e,i.diff,i.stagedDiff)}catch(n){let i=n instanceof Error?n.message:String(n);O.innerHTML=`<div class="git-diff-view"><div class="diff-header">
34
34
  <button class="diff-back">\u2190 Back</button>
35
35
  <span class="diff-filename">${C(e)}</span>
36
- </div><div class="diff-empty">Error loading diff: ${C(i)}</div></div>`}}}function Pi(e,t,n){if(!t&&!n){R.innerHTML=`<div class="git-diff-view"><div class="diff-header">
36
+ </div><div class="diff-empty">Error loading diff: ${C(i)}</div></div>`}}}function Vi(e,t,n){if(!t&&!n){O.innerHTML=`<div class="git-diff-view"><div class="diff-header">
37
37
  <button class="diff-back">\u2190 Back</button>
38
38
  <span class="diff-filename">${C(e)}</span>
39
- </div><div class="diff-empty">No diff content available</div></div>`;return}let{html:i,lineCount:a}=yn(t,n);R.innerHTML=`<div class="git-diff-view"><div class="diff-header">
39
+ </div><div class="diff-empty">No diff content available</div></div>`;return}let{html:i,lineCount:a}=kn(t,n);O.innerHTML=`<div class="git-diff-view"><div class="diff-header">
40
40
  <button class="diff-back">\u2190 Back</button>
41
41
  <span class="diff-filename">${C(e)}</span>
42
42
  <span class="diff-filesize">${a} lines</span>
43
- </div><div class="diff-content">${i}</div></div>`,R.querySelector(".diff-back")?.addEventListener("click",()=>{R.innerHTML=gn,It(),F&&R.querySelectorAll(".git-popover-item").forEach(r=>{let s=parseInt(r.dataset.idx||"0",10),l=F.files[s];!l||l.status==="D"||(r.style.cursor="pointer",r.addEventListener("click",()=>wn(l.path)))}),vn()})}function Ni(e,t,n){if(!t&&!n){Ze.textContent="No diff",Ge.innerHTML='<div class="diff-empty" style="padding:24px;text-align:center;color:var(--panel-muted)">No diff content available</div>';return}let{html:i,lineCount:a}=yn(t,n);hn.textContent=e,Ze.textContent=a+" lines",Ge.innerHTML=i}function Oi(){fn.style.display="none",tt?(J.style.display="",J.classList.add("terminal-pending"),De(tt),tt=null):M?(J.style.display="",J.classList.add("terminal-pending"),kn()):pe.style.display="flex"}Fi.addEventListener("click",Oi);function nt(){R.classList.remove("open"),et.classList.remove("open")}et.addEventListener("click",nt),document.addEventListener("keydown",e=>{e.key==="Escape"&&(nt(),ct())});async function En(e){try{let t=await(await fetch("/api/fs/session-path?session="+encodeURIComponent(e))).json();if(t.path){let n=await fetch("/api/git/status?path="+encodeURIComponent(t.path));if(n.ok){let i=await n.json();F=i,Fe(i);return}}}catch{}F=null,Fe(null)}var it=null;function kn(){at(),M&&(En(M),it=setInterval(()=>{M&&En(M)},3e4))}function at(){it&&(clearInterval(it),it=null)}async function Bt(e){let t=e;if(t.startsWith("~"))try{let n=await(await fetch(N("/api/fs/list?path="+encodeURIComponent(t)))).json();typeof n.path=="string"&&n.path&&(t=n.path)}catch{}t=t.replace(/\/+$/,"")||"/",Gt(t)}function Cn(e,t){let n=document.createElement("button");n.className="file-tree-bot-btn",n.textContent="+",n.title=`Create bot in ${t}`,n.setAttribute("aria-label",`Create bot in ${t}`),n.addEventListener("click",i=>{i.preventDefault(),i.stopPropagation(),Bt(t)}),e.appendChild(n)}function ji(){if(Qe=Ie.fsRoots||[],Qe.length===0){if(M){Hi(M);return}se("");return}k.innerHTML="";for(let e of Qe){let t=document.createElement("div");t.className="file-tree-item",t.innerHTML=`<svg viewBox="0 0 24 24" fill="currentColor" class="file-icon"><path d="M10 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2h-8l-2-2z"/></svg> ${C(e)}`,t.addEventListener("click",()=>se(e)),Cn(t,e),k.appendChild(t)}}async function Hi(e){k.innerHTML='<div class="file-tree-empty">Loading...</div>';try{let t=await(await fetch(N("/api/fs/session-path?session="+encodeURIComponent(e)))).json();t.path?se(t.path):k.innerHTML='<div class="file-tree-info">Could not determine session directory.</div>'}catch{k.innerHTML='<div class="file-tree-error">Failed to get session directory</div>'}}async function se(e){ie=e,k.innerHTML='<div class="file-tree-empty">Loading...</div>';let t=Di(e);try{let n=await(await fetch(N("/api/fs/list?path="+encodeURIComponent(e)))).json(),i=typeof n.path=="string"&&n.path?n.path:e;if(i&&(ie=i),await t,k.innerHTML="",i){let s=document.createElement("div");s.className="file-tree-item file-tree-create-bot",s.innerHTML='<span class="file-tree-bot-plus">+</span> Create bot in this folder',s.title=`Create bot in ${i}`,s.addEventListener("click",()=>void Bt(i)),k.appendChild(s)}Fe(F),k.innerHTML+=Ai();let a=Ri(i||e);if(a&&!Qe.some(s=>i===s)){let s=document.createElement("div");s.className="file-tree-item",s.innerHTML="..",s.addEventListener("click",()=>se(a)),k.appendChild(s)}if(n.dirs)for(let s of n.dirs){let l=s.split("/").pop()||s.split("\\").pop(),p=document.createElement("div");p.className="file-tree-item",p.innerHTML=`<svg viewBox="0 0 24 24" fill="currentColor" class="file-icon"><path d="M10 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2h-8l-2-2z"/></svg> ${C(l)}`,p.addEventListener("click",()=>se(s)),Cn(p,s),k.appendChild(p)}else k.innerHTML="";let r=n.files||[];for(let s of r){let l=s.split("/").pop()||s.split("\\").pop(),p=Mi(s),u="",v="";if(p)switch(p){case"M":u="git-mod",v='<span class="git-file-status M">M</span>';break;case"A":u="git-add",v='<span class="git-file-status A">A</span>';break;case"D":u="git-del",v='<span class="git-file-status D">D</span>';break;case"?":u="git-untracked",v='<span class="git-file-status ?">?</span>';break;case"R":u="git-mod",v='<span class="git-file-status R">R</span>';break}let b=document.createElement("div");b.className="file-tree-item file"+(u?" "+u:""),b.innerHTML=`<span class="file-icon">\u{1F4C4}</span> ${v}${C(l)}`,b.addEventListener("click",()=>_i(s)),k.appendChild(b)}}catch{k.innerHTML='<div class="file-tree-error">Failed to load directory</div>'}}function Ri(e){let t=e.lastIndexOf("/");return t<=0?null:e.substring(0,t)}async function _i(e){Ye=e,J.style.display="none",L&&(at(),L.destroy(),L=null,M=null),Fe(null),Xe(),pe.style.display="none",Te.style.display="flex",wi.textContent=e,V.textContent="Loading...",me.style.display="none";try{let t=await fetch(N("/api/file?path="+encodeURIComponent(e)));if(!t.ok){let i=await t.json();V.textContent=i.error||"Failed to load",Me.value="";return}let n=await t.json();Me.value=n.content,Ve=n.content,en=n.content,V.textContent=n.size+" bytes",me.style.display=""}catch{V.textContent="Failed to load",Me.value=""}}Me.addEventListener("input",()=>{Ve=Me.value}),me.addEventListener("click",async()=>{me.textContent="Saving...",me.disabled=!0;try{let e=await fetch(N("/api/file"),{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:Ye,content:Ve})});if(!e.ok){let t=await e.json();V.textContent=t.error||"Save failed";return}en=Ve,V.textContent="Saved"}catch{V.textContent="Save failed"}finally{me.disabled=!1,me.textContent="Save"}}),Ei.addEventListener("click",async()=>{if(confirm("Delete "+Ye+"?"))try{let e=await fetch(N("/api/file/delete"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:Ye})});if(!e.ok){let t=await e.json();V.textContent=t.error||"Delete failed";return}Te.style.display="none",pe.style.display="flex",ie&&se(ie)}catch{V.textContent="Delete failed"}}),ki.addEventListener("click",()=>{Te.style.display="none",pe.style.display="flex",ie&&se(ie)}),Ci.addEventListener("click",async()=>{let e=tn.value.trim();if(!e)return;let t=ie+"/"+e;try{let n=await fetch(N("/api/file/touch"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:t})});if(!n.ok){let i=await n.json();V.textContent=i.error||"Create failed";return}tn.value="",ie&&se(ie)}catch{V.textContent="Create failed"}});var st=document.getElementById("force-narrow-toggle");st&&(st.checked=Ke(),st.addEventListener("change",()=>{try{localStorage.setItem(sn,st.checked?"1":"0")}catch{}on(),ae()})),on(),document.getElementById("mode-settings").addEventListener("click",()=>{let e=nn.classList.toggle("open");St.classList.toggle("open",e)}),St.addEventListener("click",()=>{nn.classList.remove("open"),St.classList.remove("open")});var q="",K=!1,X,$e=document.createElement("div");$e.className="session-popover-backdrop",document.body.appendChild($e);var Q=document.createElement("div");Q.id="session-popover",Q.className="session-popover",Q.style.display="none",Q.innerHTML=`<div class="sp-field">
43
+ </div><div class="diff-content">${i}</div></div>`,O.querySelector(".diff-back")?.addEventListener("click",()=>{O.innerHTML=wn,Bt(),D&&O.querySelectorAll(".git-popover-item").forEach(r=>{let o=parseInt(r.dataset.idx||"0",10),l=D.files[o];!l||l.status==="D"||(r.style.cursor="pointer",r.addEventListener("click",()=>Cn(l.path)))}),bn()})}function Oi(e,t,n){if(!t&&!n){et.textContent="No diff",tt.innerHTML='<div class="diff-empty" style="padding:24px;text-align:center;color:var(--panel-muted)">No diff content available</div>';return}let{html:i,lineCount:a}=kn(t,n);yn.textContent=e,et.textContent=a+" lines",tt.innerHTML=i}function ji(){gn.style.display="none",it?(q.style.display="",q.classList.add("terminal-pending"),Ae(it),it=null):z?(q.style.display="",q.classList.add("terminal-pending"),xn()):me.style.display="flex"}Pi.addEventListener("click",ji);function at(){O.classList.remove("open"),nt.classList.remove("open")}nt.addEventListener("click",at),document.addEventListener("keydown",e=>{e.key==="Escape"&&(at(),pt())});async function Ln(e){try{let t=await(await fetch("/api/fs/session-path?session="+encodeURIComponent(e))).json();if(t.path){let n=await fetch("/api/git/status?path="+encodeURIComponent(t.path));if(n.ok){let i=await n.json();D=i,$e(i);return}}}catch{}D=null,$e(null)}var ot=null;function xn(){st(),z&&(Ln(z),ot=setInterval(()=>{z&&Ln(z)},3e4))}function st(){ot&&(clearInterval(ot),ot=null)}async function Tt(e){let t=e;if(t.startsWith("~"))try{let n=await(await fetch($("/api/fs/list?path="+encodeURIComponent(t)))).json();typeof n.path=="string"&&n.path&&(t=n.path)}catch{}t=t.replace(/\/+$/,"")||"/",nn(t)}function Sn(e,t){let n=document.createElement("button");n.className="file-tree-bot-btn",n.innerHTML=ce("add",'width="12" height="12"'),n.title=`Create bot in ${t}`,n.setAttribute("aria-label",`Create bot in ${t}`),n.addEventListener("click",i=>{i.preventDefault(),i.stopPropagation(),Tt(t)}),e.appendChild(n)}function Ri(){if(Ge=Be.fsRoots||[],Ge.length===0){if(z){_i(z);return}oe("");return}k.innerHTML="";for(let e of Ge){let t=document.createElement("div");t.className="file-tree-item",t.innerHTML=`<svg viewBox="0 0 24 24" fill="currentColor" class="file-icon"><path d="M10 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2h-8l-2-2z"/></svg> ${C(e)}`,t.addEventListener("click",()=>oe(e)),Sn(t,e),k.appendChild(t)}}async function _i(e){k.innerHTML='<div class="file-tree-empty">Loading...</div>';try{let t=await(await fetch($("/api/fs/session-path?session="+encodeURIComponent(e)))).json();t.path?oe(t.path):k.innerHTML='<div class="file-tree-info">Could not determine session directory.</div>'}catch{k.innerHTML='<div class="file-tree-error">Failed to get session directory</div>'}}async function oe(e){ie=e,k.innerHTML='<div class="file-tree-empty">Loading...</div>';let t=Fi(e);try{let n=await(await fetch($("/api/fs/list?path="+encodeURIComponent(e)))).json(),i=typeof n.path=="string"&&n.path?n.path:e;if(i&&(ie=i),await t,k.innerHTML="",i){let o=document.createElement("div");o.className="file-tree-item file-tree-create-bot",o.innerHTML=`<span class="file-tree-bot-plus">${ce("add",'width="11" height="11"')}</span> Create bot in this folder`,o.title=`Create bot in ${i}`,o.addEventListener("click",()=>void Tt(i)),k.appendChild(o)}$e(D),k.innerHTML+=$i();let a=Ui(i||e);if(a&&!Ge.some(o=>i===o)){let o=document.createElement("div");o.className="file-tree-item",o.innerHTML="..",o.addEventListener("click",()=>oe(a)),k.appendChild(o)}if(n.dirs)for(let o of n.dirs){let l=o.split("/").pop()||o.split("\\").pop(),u=document.createElement("div");u.className="file-tree-item",u.innerHTML=`<svg viewBox="0 0 24 24" fill="currentColor" class="file-icon"><path d="M10 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2h-8l-2-2z"/></svg> ${C(l)}`,u.addEventListener("click",()=>oe(o)),Sn(u,o),k.appendChild(u)}else k.innerHTML="";let r=n.files||[];for(let o of r){let l=o.split("/").pop()||o.split("\\").pop(),u=Ai(o),p="",f="";if(u)switch(u){case"M":p="git-mod",f='<span class="git-file-status M">M</span>';break;case"A":p="git-add",f='<span class="git-file-status A">A</span>';break;case"D":p="git-del",f='<span class="git-file-status D">D</span>';break;case"?":p="git-untracked",f='<span class="git-file-status ?">?</span>';break;case"R":p="git-mod",f='<span class="git-file-status R">R</span>';break}let y=document.createElement("div");y.className="file-tree-item file"+(p?" "+p:""),y.innerHTML=`<span class="file-icon">\u{1F4C4}</span> ${f}${C(l)}`,y.addEventListener("click",()=>Wi(o)),k.appendChild(y)}}catch{k.innerHTML='<div class="file-tree-error">Failed to load directory</div>'}}function Ui(e){let t=e.lastIndexOf("/");return t<=0?null:e.substring(0,t)}async function Wi(e){Xe=e,q.style.display="none",S&&(st(),S.destroy(),S=null,z=null),$e(null),De(),me.style.display="none",ze.style.display="flex",Li.textContent=e,K.textContent="Loading...",he.style.display="none";try{let t=await fetch($("/api/file?path="+encodeURIComponent(e)));if(!t.ok){let i=await t.json();K.textContent=i.error||"Failed to load",He.value="";return}let n=await t.json();He.value=n.content,Qe=n.content,an=n.content,K.textContent=n.size+" bytes",he.style.display=""}catch{K.textContent="Failed to load",He.value=""}}He.addEventListener("input",()=>{Qe=He.value}),he.addEventListener("click",async()=>{he.textContent="Saving...",he.disabled=!0;try{let e=await fetch($("/api/file"),{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:Xe,content:Qe})});if(!e.ok){let t=await e.json();K.textContent=t.error||"Save failed";return}an=Qe,K.textContent="Saved"}catch{K.textContent="Save failed"}finally{he.disabled=!1,he.textContent="Save"}}),xi.addEventListener("click",async()=>{if(confirm("Delete "+Xe+"?"))try{let e=await fetch($("/api/file/delete"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:Xe})});if(!e.ok){let t=await e.json();K.textContent=t.error||"Delete failed";return}ze.style.display="none",me.style.display="flex",ie&&oe(ie)}catch{K.textContent="Delete failed"}}),Si.addEventListener("click",()=>{ze.style.display="none",me.style.display="flex",ie&&oe(ie)}),Mi.addEventListener("click",async()=>{let e=on.value.trim();if(!e)return;let t=ie+"/"+e;try{let n=await fetch($("/api/file/touch"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:t})});if(!n.ok){let i=await n.json();K.textContent=i.error||"Create failed";return}on.value="",ie&&oe(ie)}catch{K.textContent="Create failed"}});var lt=document.getElementById("force-narrow-toggle");lt&&(lt.checked=Ze(),lt.addEventListener("change",()=>{try{localStorage.setItem(rn,lt.checked?"1":"0")}catch{}dn(),ae()})),dn(),document.getElementById("mode-settings").addEventListener("click",()=>{let e=sn.classList.toggle("open");Mt.classList.toggle("open",e)}),Mt.addEventListener("click",()=>{sn.classList.remove("open"),Mt.classList.remove("open")});var J="",X=!1,Q,Pe=document.createElement("div");Pe.className="session-popover-backdrop",document.body.appendChild(Pe);var Z=document.createElement("div");Z.id="session-popover",Z.className="session-popover",Z.style.display="none",Z.innerHTML=`<div class="sp-field">
44
44
  <label>Rename session</label>
45
45
  <input type="text" id="sp-name" />
46
46
  </div>
@@ -50,5 +50,5 @@ ${i.model.id}`);let W=c("select","bv-input");for(let h of["","off","minimal","lo
50
50
  <button class="btn danger sp-delete" id="sp-delete">Delete</button>
51
51
  </div>
52
52
  <hr class="sp-divider" id="sp-divider" />
53
- <button class="btn primary" id="sp-rebuild" style="display:none">\u91CD\u5EFA\u540C\u540D\u540C\u8DEF\u5F84 session</button>`,document.body.appendChild(Q);function zi(e){let t=e.getBoundingClientRect(),n=window.innerHeight,i=Q.offsetHeight||240,a=t.bottom+4;a+i>n-8&&(a=Math.max(8,t.top-i-4)),Q.style.top=a+"px",Q.style.left=Math.max(8,Math.min(t.left,window.innerWidth-240))+"px"}function ot(e,t,n){q=e,K=!!n?.tombstone,X=n?.agentId;let i=document.getElementById("sp-name");i.value=e;let a=Q.querySelector(".sp-field label");a.textContent=K?"\u91CD\u547D\u540D (\u4EC5\u8BB0\u5F55\uFF0C\u4E0D\u91CD\u5EFA)":"Rename session";let r=document.getElementById("sp-rebuild");r.style.display=K?"":"none";let s=document.getElementById("sp-delete");s.textContent=K?"\u5220\u9664\u8BB0\u5F55":"Delete",s.title=K?"\u5220\u9664\u5931\u6548\u8BB0\u5F55\uFF08\u5893\u7891\u6D88\u5931\uFF09":"Delete session";let l=document.getElementById("sp-divider");l&&(l.style.display=K?"":"none");let p=document.getElementById("sp-save");p.textContent=K?"\u91CD\u547D\u540D":"Save",$e.classList.add("open"),Q.style.display="block",zi(t),setTimeout(()=>i.focus(),50)}function fe(){$e.classList.remove("open"),Q.style.display="none"}$e.addEventListener("click",fe),document.getElementById("sp-save").addEventListener("click",async()=>{let e=document.getElementById("sp-name").value.trim();if(!e||e===q){fe();return}try{let t=K?{oldName:q,newName:e,agentId:X}:{oldName:q,newName:e,...X?{agentId:X}:{}};if(!(await fetch(N(K?"/api/sessions/rename-tombstone":"/api/sessions/rename"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})).ok)return;fe(),ae(),!K&&M===q&&(X??null)===H&&De(e,X)}catch{}}),document.getElementById("sp-rebuild").addEventListener("click",async()=>{if(confirm('\u91CD\u5EFA\u4F1A\u8BDD "'+q+'" (\u540C\u540D\u540C\u8DEF\u5F84\uFF0C\u5185\u5BB9\u4E3A\u7A7A)\uFF1F'))try{let e=await fetch(N("/api/sessions/rebuild"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:q,agentId:X})});if(!e.ok){let t=await e.json();alert(t.error||"\u91CD\u5EFA\u5931\u8D25");return}fe(),ae()}catch{}}),document.getElementById("sp-delete").addEventListener("click",async()=>{if(K){if(!confirm('\u5220\u9664\u5931\u6548\u8BB0\u5F55 "'+q+'"\uFF1F'))return;try{if(!(await fetch(N("/api/sessions/dismiss"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:q,agentId:X})})).ok)return;fe(),ae()}catch{}return}if(confirm('Delete session "'+q+'"?'))try{if(!(await fetch(N("/api/sessions/kill"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:q,...X?{agentId:X}:{}})})).ok)return;fe(),M===q&&(X??null)===H&&(L&&(L.destroy(),L=null),M=null,J.style.display="none",pe.style.display="flex"),ae()}catch{}}),document.getElementById("sp-cancel").addEventListener("click",fe);var xn={esc:"\x1B",tab:" ","s-tab":"\x1B[Z",up:"\x1B[A",down:"\x1B[B",left:"\x1B[D",right:"\x1B[C",space:" ",enter:"\r","ctrl-r":"","ctrl-c":"",btw:"/btw ",yes:"yes\r"},lt=document.getElementById("mobile-keys"),Ui=new Set(["up","down","left","right","tab","s-tab","space"]),Wi=400,Ji=80,Pe=0,rt=0,dt=!1;function qi(){Pe&&(clearTimeout(Pe),Pe=0),rt&&(clearInterval(rt),rt=0)}lt.addEventListener("mousedown",e=>{e.target.closest("button[data-key]")&&e.preventDefault()}),lt.addEventListener("pointerdown",e=>{let t=e.target.closest("button[data-key]");if(!t)return;let n=t.dataset.key;Ui.has(n)&&(dt=!1,Pe=setTimeout(()=>{Pe=0,dt=!0,rt=setInterval(()=>{let i=xn[n];i&&L&&L.sendInput(i)},Ji)},Wi))});for(let e of["pointerup","pointercancel","pointerleave"])lt.addEventListener(e,qi);lt.addEventListener("click",e=>{let t=e.target.closest("button[data-key]");if(!t||!L)return;if(dt){dt=!1;return}let n=xn[t.dataset.key];n&&(L.sendInput(n),L.focus())});var te=document.getElementById("mk-input"),Sn=document.getElementById("mk-send");function Ln(){if(!te||!L)return;let e=te.value;e&&(L.sendInput(e+"\r"),te.value="",te.rows=1,L.focus())}if(te&&(te.addEventListener("input",()=>{te.rows=1;let e=te.value.split(`
54
- `).length;te.rows=Math.min(e,4)}),te.addEventListener("keydown",e=>{e.key==="Enter"&&!e.shiftKey&&(e.preventDefault(),Ln())})),Sn&&Sn.addEventListener("click",Ln),window.visualViewport){let e=document.querySelector(".app-layout"),t=()=>{e&&(e.style.height=window.visualViewport.height+"px"),window.scrollTo(0,0),document.documentElement.scrollTop=0,document.body.scrollTop=0};window.visualViewport.addEventListener("resize",t),window.addEventListener("orientationchange",()=>setTimeout(t,100)),document.addEventListener("touchstart",()=>{(window.scrollY>0||document.documentElement.scrollTop>0)&&window.scrollTo(0,0)},{passive:!0})}var Tt=document.getElementById("process-panel"),Ne=document.getElementById("proc-list"),Yi=document.getElementById("proc-close"),Mt=document.getElementById("proc-backdrop"),Vi=document.getElementById("header-ram");function Ki(){Ne.innerHTML='<div class="proc-empty">Loading\u2026</div>',fetch(N("/api/system/processes")).then(e=>e.json()).then(e=>{if(!Array.isArray(e)||!e.length){Ne.innerHTML='<div class="proc-empty">No processes</div>';return}let t="";for(let n of e){let i=n.rss,a=i<1048576?(i/1024).toFixed(0)+"K":(i/1048576).toFixed(1)+"M";t+='<div class="proc-row" data-pid="'+n.pid+'"><span class="proc-mem">'+n.mem+'%</span><span class="proc-rss">'+a+'</span><span class="proc-cmd" title="'+C(n.command)+'">'+C(n.command)+'</span><button class="proc-kill" title="Kill PID '+n.pid+'">&times;</button></div>'}Ne.innerHTML=t;for(let n of Ne.querySelectorAll(".proc-row")){let i=n.querySelector(".proc-kill");i&&i.addEventListener("click",a=>{let r=a.target.closest(".proc-row");!r||!confirm("Kill PID "+r.dataset.pid+"?")||fetch(N("/api/system/kill"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({pid:parseInt(r.dataset.pid,10)})}).then(s=>s.json()).then(s=>{s.ok?r.style.opacity="0.3":alert("Failed: "+(s.error||"unknown"))}).catch(()=>alert("Network error"))})}}).catch(()=>{Ne.innerHTML='<div class="proc-empty">Failed to load</div>'})}function Xi(){Tt.classList.add("open"),Mt.classList.add("open"),Ki()}function ct(){Tt.classList.remove("open"),Mt.classList.remove("open")}Vi.addEventListener("click",e=>{e.stopPropagation(),Tt.classList.contains("open")?ct():Xi()}),Yi.addEventListener("click",ct),Mt.addEventListener("click",ct);var Qi=2e3,Oe=null,Dt=null,be=new Map,ye=new Map,Zi=5e3,In=new Map;function At(e,t){return(t?"a:"+t+":":"l:")+e}function Gi(e,t,n){let i=At(e,t);if(n==="working"){let u=In.get(i);if(u&&Date.now()<u)return}let a=ye.get(i),r=e===M&&(t??null)===H,s=n==="idle"&&a?.state==="working";ye.set(i,{session:e,agentId:t,state:n,doneUntil:s?Date.now()+Qi:void 0,unread:s?!r:!1});let l=t?'.session-item[data-agent="'+CSS.escape(t)+'"][data-session="'+CSS.escape(e)+'"]':'.session-item[data-session="'+CSS.escape(e)+'"]:not([data-agent])',p=k.querySelector(l);p&&ut(p,i,ye.get(i))}function ut(e,t,n){let i=be.get(t);i&&(clearTimeout(i),be.delete(t)),e.classList.remove("working","just-done");let a=n.session===M&&(n.agentId??null)===H;n.state==="working"?e.classList.add("working"):a&&n.doneUntil&&Date.now()<n.doneUntil?(e.classList.add("just-done"),be.set(t,setTimeout(()=>{e.classList.remove("just-done"),be.delete(t)},Math.max(0,n.doneUntil-Date.now())))):!a&&n.unread&&e.classList.add("just-done")}function Ft(){for(let[e,t]of ye){let n=t.agentId?'.session-item[data-agent="'+CSS.escape(t.agentId)+'"][data-session="'+CSS.escape(t.session)+'"]':'.session-item[data-session="'+CSS.escape(t.session)+'"]:not([data-agent])',i=k.querySelector(n);i&&ut(i,e,t)}}function ea(e,t){let n=At(e,t),i=ye.get(n);if(!i)return;let a=be.get(n);a&&(clearTimeout(a),be.delete(n)),i.doneUntil=void 0,i.unread=!1;let r=t?'.session-item[data-agent="'+CSS.escape(t)+'"][data-session="'+CSS.escape(e)+'"]':'.session-item[data-session="'+CSS.escape(e)+'"]:not([data-agent])',s=k.querySelector(r);s&&ut(s,n,i)}function Bn(){if(Oe||Dt)return;let e=localStorage.getItem("tmux-web-token"),t=(location.protocol==="https:"?"wss:":"ws:")+"//"+location.host+"/ws/activity";e&&(t+="?token="+encodeURIComponent(e));try{let n=new WebSocket(t);Oe=n,n.onmessage=i=>{try{let a=JSON.parse(String(i.data));a&&a.type==="session.activity"&&typeof a.session=="string"&&Gi(a.session,a.agentId||void 0,a.state==="working"?"working":"idle")}catch{}},n.onclose=()=>{Oe===n&&(Oe=null,Dt=setTimeout(()=>{Dt=null,Bn()},5e3))},n.onerror=()=>{try{n.close()}catch{}}}catch{Oe=null}}window.__openSession=De,window.__refreshSidebar=ae,ae(),Xe(),Ft(),Bn(),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&Ft()}),setInterval(()=>{document.visibilityState==="visible"&&ae()},1e4),yi();
53
+ <button class="btn primary" id="sp-rebuild" style="display:none">\u91CD\u5EFA\u540C\u540D\u540C\u8DEF\u5F84 session</button>`,document.body.appendChild(Z);function qi(e){let t=e.getBoundingClientRect(),n=window.innerHeight,i=Z.offsetHeight||240,a=t.bottom+4;a+i>n-8&&(a=Math.max(8,t.top-i-4)),Z.style.top=a+"px",Z.style.left=Math.max(8,Math.min(t.left,window.innerWidth-240))+"px"}function rt(e,t,n){J=e,X=!!n?.tombstone,Q=n?.agentId;let i=document.getElementById("sp-name");i.value=e;let a=Z.querySelector(".sp-field label");a.textContent=X?"\u91CD\u547D\u540D (\u4EC5\u8BB0\u5F55\uFF0C\u4E0D\u91CD\u5EFA)":"Rename session";let r=document.getElementById("sp-rebuild");r.style.display=X?"":"none";let o=document.getElementById("sp-delete");o.textContent=X?"\u5220\u9664\u8BB0\u5F55":"Delete",o.title=X?"\u5220\u9664\u5931\u6548\u8BB0\u5F55\uFF08\u5893\u7891\u6D88\u5931\uFF09":"Delete session";let l=document.getElementById("sp-divider");l&&(l.style.display=X?"":"none");let u=document.getElementById("sp-save");u.textContent=X?"\u91CD\u547D\u540D":"Save",Pe.classList.add("open"),Z.style.display="block",qi(t),setTimeout(()=>i.focus(),50)}function ve(){Pe.classList.remove("open"),Z.style.display="none"}Pe.addEventListener("click",ve),document.getElementById("sp-save").addEventListener("click",async()=>{let e=document.getElementById("sp-name").value.trim();if(!e||e===J){ve();return}try{let t=X?{oldName:J,newName:e,agentId:Q}:{oldName:J,newName:e,...Q?{agentId:Q}:{}};if(!(await fetch($(X?"/api/sessions/rename-tombstone":"/api/sessions/rename"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})).ok)return;ve(),ae(),!X&&z===J&&(Q??null)===V&&Ae(e,Q)}catch{}}),document.getElementById("sp-rebuild").addEventListener("click",async()=>{if(confirm('\u91CD\u5EFA\u4F1A\u8BDD "'+J+'" (\u540C\u540D\u540C\u8DEF\u5F84\uFF0C\u5185\u5BB9\u4E3A\u7A7A)\uFF1F'))try{let e=await fetch($("/api/sessions/rebuild"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:J,agentId:Q})});if(!e.ok){let t=await e.json();alert(t.error||"\u91CD\u5EFA\u5931\u8D25");return}ve(),ae()}catch{}}),document.getElementById("sp-delete").addEventListener("click",async()=>{if(X){if(!confirm('\u5220\u9664\u5931\u6548\u8BB0\u5F55 "'+J+'"\uFF1F'))return;try{if(!(await fetch($("/api/sessions/dismiss"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:J,agentId:Q})})).ok)return;ve(),ae()}catch{}return}if(confirm('Delete session "'+J+'"?'))try{if(!(await fetch($("/api/sessions/kill"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:J,...Q?{agentId:Q}:{}})})).ok)return;ve(),z===J&&(Q??null)===V&&(S&&(S.destroy(),S=null),z=null,q.style.display="none",me.style.display="flex"),ae()}catch{}}),document.getElementById("sp-cancel").addEventListener("click",ve);var Mn={esc:"\x1B",tab:" ","s-tab":"\x1B[Z",up:"\x1B[A",down:"\x1B[B",left:"\x1B[D",right:"\x1B[C",space:" ",enter:"\r","ctrl-r":"","ctrl-c":"",btw:"/btw ",yes:"yes\r"},dt=document.getElementById("mobile-keys"),Ji=new Set(["up","down","left","right","tab","s-tab","space"]),Yi=400,Ki=80,Ne=0,ct=0,ut=!1;function Xi(){Ne&&(clearTimeout(Ne),Ne=0),ct&&(clearInterval(ct),ct=0)}dt.addEventListener("mousedown",e=>{e.target.closest("button[data-key]")&&e.preventDefault()}),dt.addEventListener("pointerdown",e=>{let t=e.target.closest("button[data-key]");if(!t)return;let n=t.dataset.key;Ji.has(n)&&(ut=!1,Ne=setTimeout(()=>{Ne=0,ut=!0,ct=setInterval(()=>{let i=Mn[n];i&&S&&S.sendInput(i)},Ki)},Yi))});for(let e of["pointerup","pointercancel","pointerleave"])dt.addEventListener(e,Xi);dt.addEventListener("click",e=>{let t=e.target.closest("button[data-key]");if(!t||!S)return;if(ut){ut=!1;return}let n=Mn[t.dataset.key];n&&(S.sendInput(n),S.focus())});var te=document.getElementById("mk-input"),In=document.getElementById("mk-send");function Bn(){if(!te||!S)return;let e=te.value;e&&(S.sendInput(e+"\r"),te.value="",te.rows=1,S.focus())}if(te&&(te.addEventListener("input",()=>{te.rows=1;let e=te.value.split(`
54
+ `).length;te.rows=Math.min(e,4)}),te.addEventListener("keydown",e=>{e.key==="Enter"&&!e.shiftKey&&(e.preventDefault(),Bn())})),In&&In.addEventListener("click",Bn),window.visualViewport){let e=document.querySelector(".app-layout"),t=()=>{e&&(e.style.height=window.visualViewport.height+"px"),window.scrollTo(0,0),document.documentElement.scrollTop=0,document.body.scrollTop=0};window.visualViewport.addEventListener("resize",t),window.addEventListener("orientationchange",()=>setTimeout(t,100)),document.addEventListener("touchstart",()=>{(window.scrollY>0||document.documentElement.scrollTop>0)&&window.scrollTo(0,0)},{passive:!0})}var zt=document.getElementById("process-panel"),Ve=document.getElementById("proc-list"),Qi=document.getElementById("proc-close"),Ht=document.getElementById("proc-backdrop"),Zi=document.getElementById("header-ram");function Gi(){Ve.innerHTML='<div class="proc-empty">Loading\u2026</div>',fetch($("/api/system/processes")).then(e=>e.json()).then(e=>{if(!Array.isArray(e)||!e.length){Ve.innerHTML='<div class="proc-empty">No processes</div>';return}let t="";for(let n of e){let i=n.rss,a=i<1048576?(i/1024).toFixed(0)+"K":(i/1048576).toFixed(1)+"M";t+='<div class="proc-row" data-pid="'+n.pid+'"><span class="proc-mem">'+n.mem+'%</span><span class="proc-rss">'+a+'</span><span class="proc-cmd" title="'+C(n.command)+'">'+C(n.command)+'</span><button class="proc-kill" title="Kill PID '+n.pid+'">&times;</button></div>'}Ve.innerHTML=t;for(let n of Ve.querySelectorAll(".proc-row")){let i=n.querySelector(".proc-kill");i&&i.addEventListener("click",a=>{let r=a.target.closest(".proc-row");!r||!confirm("Kill PID "+r.dataset.pid+"?")||fetch($("/api/system/kill"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({pid:parseInt(r.dataset.pid,10)})}).then(o=>o.json()).then(o=>{o.ok?r.style.opacity="0.3":alert("Failed: "+(o.error||"unknown"))}).catch(()=>alert("Network error"))})}}).catch(()=>{Ve.innerHTML='<div class="proc-empty">Failed to load</div>'})}function ea(){zt.classList.add("open"),Ht.classList.add("open"),Gi()}function pt(){zt.classList.remove("open"),Ht.classList.remove("open")}Zi.addEventListener("click",e=>{e.stopPropagation(),zt.classList.contains("open")?pt():ea()}),Qi.addEventListener("click",pt),Ht.addEventListener("click",pt);var ta=2e3,Oe=null,Dt=null,we=new Map,Ee=new Map,na=5e3,Tn=new Map;function At(e,t){return(t?"a:"+t+":":"l:")+e}function ia(e,t,n){let i=At(e,t);if(n==="working"){let p=Tn.get(i);if(p&&Date.now()<p)return}let a=Ee.get(i),r=e===z&&(t??null)===V,o=n==="idle"&&a?.state==="working";Ee.set(i,{session:e,agentId:t,state:n,doneUntil:o?Date.now()+ta:void 0,unread:o?!r:!1});let l=t?'.session-item[data-agent="'+CSS.escape(t)+'"][data-session="'+CSS.escape(e)+'"]':'.session-item[data-session="'+CSS.escape(e)+'"]:not([data-agent])',u=k.querySelector(l);u&&mt(u,i,Ee.get(i))}function mt(e,t,n){let i=we.get(t);i&&(clearTimeout(i),we.delete(t)),e.classList.remove("working","just-done");let a=n.session===z&&(n.agentId??null)===V;n.state==="working"?e.classList.add("working"):a&&n.doneUntil&&Date.now()<n.doneUntil?(e.classList.add("just-done"),we.set(t,setTimeout(()=>{e.classList.remove("just-done"),we.delete(t)},Math.max(0,n.doneUntil-Date.now())))):!a&&n.unread&&e.classList.add("just-done")}function Ft(){for(let[e,t]of Ee){let n=t.agentId?'.session-item[data-agent="'+CSS.escape(t.agentId)+'"][data-session="'+CSS.escape(t.session)+'"]':'.session-item[data-session="'+CSS.escape(t.session)+'"]:not([data-agent])',i=k.querySelector(n);i&&mt(i,e,t)}}function aa(e,t){let n=At(e,t),i=Ee.get(n);if(!i)return;let a=we.get(n);a&&(clearTimeout(a),we.delete(n)),i.doneUntil=void 0,i.unread=!1;let r=t?'.session-item[data-agent="'+CSS.escape(t)+'"][data-session="'+CSS.escape(e)+'"]':'.session-item[data-session="'+CSS.escape(e)+'"]:not([data-agent])',o=k.querySelector(r);o&&mt(o,n,i)}function zn(){if(Oe||Dt)return;let e=localStorage.getItem("tmux-web-token"),t=(location.protocol==="https:"?"wss:":"ws:")+"//"+location.host+"/ws/activity";e&&(t+="?token="+encodeURIComponent(e));try{let n=new WebSocket(t);Oe=n,n.onmessage=i=>{try{let a=JSON.parse(String(i.data));a&&a.type==="session.activity"&&typeof a.session=="string"&&ia(a.session,a.agentId||void 0,a.state==="working"?"working":"idle")}catch{}},n.onclose=()=>{Oe===n&&(Oe=null,Dt=setTimeout(()=>{Dt=null,zn()},5e3))},n.onerror=()=>{try{n.close()}catch{}}}catch{Oe=null}}window.__openSession=Ae,window.__refreshSidebar=ae,ae(),De(),Ft(),zn(),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&Ft()}),setInterval(()=>{document.visibilityState==="visible"&&ae()},1e4),Ci();