tmux-weblink 2.2.44 → 2.2.46

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 ii=/\x1b\](?:10|11|110|111|104)(?:;[^\x07\x1b]*)?\x1b?(?:\\|\x07)/g;function bt(e){return e.replace(/\x1b\[\?1049[hl]/g,"")}function Le(e){return e.replace(ii,"")}var _e;function ai(){return _e||(document.querySelector("link[data-tmux-web-xterm-css]")?_e=Promise.resolve():(_e=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)}),_e))}var si=class An{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(oi()==="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"),ai()]),l="'JetBrains Mono', 'SF Mono', 'Menlo', monospace",s=new a({fontSize:li(14,l),fontFamily:l,cursorBlink:!0,cursorStyle:"bar",scrollback:n,convertEol:!1,smoothScrollDuration:120,theme:i});return new An(t,s,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=ri(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 l=this.overlayScrollbarWidth(),s=l>0?l+2:0,p=a>0?Math.max(10,Math.min(r.cols,Math.floor((t.width-s)/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],l=i.viewportY,s=[];for(let p=a;p<=r;p++){let u=i.getLine(l+p);s.push(u?u.translateToString(!0):"")}return s.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,l=Math.min(n,a),s=Math.max(n,a);if(l===s){let p=Math.min(t,i),u=Math.max(t,i);this.terminal.select(p,r.viewportY+l,u-p+1)}else this.terminal.selectLines(r.viewportY+l,r.viewportY+s)}getCellsText(t,n,i,a){let r=this.terminal.buffer.active,l=Math.min(n,a),s=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),h=r.viewportY,g=[];for(let x=l;x<=s;x++){let B=r.getLine(h+x);if(!B){g.push("");continue}let E=x===l?p:0,I=x===s?u:this.terminal.cols-1,O="";for(let D=E;D<=I;D++){let W=B.getCell(D);W&&(O+=W.getChars())}g.push(O.replace(/\s+$/,""))}return g.join(`
3
- `)}getSelection(){return this.terminal.getSelection()}clearSelection(){this.terminal.clearSelection()}hasSelectionSupport(){return!0}};function li(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,l=e,s=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 h=Math.abs(u-e);h<s&&(s=h,l=u)}return Math.round(l*100)/100}catch{return e}}function oi(){try{let e=new URLSearchParams(window.location.search).get("renderer");return e==="dom"||e==="webgl"?e:null}catch{return null}}function ri(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 di(e,t,n){return e.innerHTML="",e.classList.add("terminal-pending"),(async()=>{let i=await si.create(e,n.scrollback,n.theme),a,r=0,l,s=null,p=0,u=0,h=.2,g=10,x=.95,B=.04,E=null,I=null;function O(o){E||(E=document.createElement("div"),E.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(E)),E.textContent=o?"\u2191 \u4E0A\u7FFB\u4E00\u9875 (PgUp)":"\u2193 \u4E0B\u7FFB\u4E00\u9875 (PgDn)",E.style.top=o?"10%":"auto",E.style.bottom=o?"auto":"10%",E.style.opacity="1",I&&clearTimeout(I),I=setTimeout(()=>{E&&(E.style.opacity="0")},900)}function D(){I&&clearTimeout(I),E&&(E.style.opacity="0")}function W(){p&&(cancelAnimationFrame(p),p=0),u=0}function le(o){if(W(),Math.abs(o)<h)return;u=Math.max(-g,Math.min(g,o));let c=()=>{if(L){p=0;return}let f=i.cellHeight(),b=f>0?Math.round(u*16/f):u>0?1:-1;b===0&&(b=u>0?1:-1);let C=i.viewportY()-b,V=i.baseY(),ae=Math.max(0,Math.min(C,V));if(i.scrollToLine(ae,!0),u*=x,ae!==C){p=0;return}if(Math.abs(u)<B){p=0;return}p=requestAnimationFrame(c)};p=requestAnimationFrame(c)}let oe=0,H="connecting",N=0,ie=!1,v=[],z="",L=!1,re=1e3,M=location.protocol==="https:"?"wss:":"ws:",Nt=n.wsBase||"/ws",Pn=M+"//"+location.host+Nt+"/"+encodeURIComponent(t),Nn=(Nt.replace(/^\/ws/,"")||"")+"/api/session/"+encodeURIComponent(t)+"/upload",Fn=/^((?!chrome|android|crios|fxios|edgios).)*safari/i.test(navigator.userAgent);function Rn(){return v.join("")+z}async function jn(o,c=0){let f=o?i.viewportY():0,b=Le(Rn());if(i.reset(),!b){o||i.scrollToBottom();return}await i.write(b),o?i.scrollToLine(c+f):i.scrollToBottom()}function de(o){a?.readyState===WebSocket.OPEN&&a.send(JSON.stringify(o))}function On(o){let c;try{c=JSON.parse(o)}catch{H==="live"&&(z+=o,i.write(Le(o)));return}if(c.type==="auth.required"){let f=localStorage.getItem("tmux-web-token");f?de({type:"auth.token",token:f}):location.href="/login?returnTo="+encodeURIComponent(location.pathname+location.search);return}if(c.type==="attach_failed"&&typeof c.message=="string"){Oe=!0,H="dead",i.reset(),i.write(`\r
4
- \x1B[31m`+Le(c.message)+`\x1B[0m\r
5
- `).then(()=>{He();try{a?.close()}catch{}});return}if(c.type==="auth.ok"){c.token&&localStorage.setItem("tmux-web-token",c.token),re=1e3,ce(),de({type:"resize",cols:i.cols,rows:i.rows}),U();return}if(c.type==="auth.failed"){if(c.permanentLock||c.retryAfterMs&&c.retryAfterMs>6e4){localStorage.removeItem("tmux-web-token"),location.href="/login?error="+encodeURIComponent(c.message);return}return}if(c.type==="snapshot"&&typeof c.data=="string"){let f=bt(Le(c.data));v=[f],z="",N=typeof c.lines=="number"?c.lines:n.terminal.initialLines,H="live",i.reset(),ce(),de({type:"resize",cols:i.cols,rows:i.rows}),i.write(f).then(()=>i.scrollToBottom());return}if(c.type==="window_changed"&&typeof c.activeIndex=="number"){let f=new URL(location.href);f.searchParams.get("window")!==String(c.activeIndex)&&(f.searchParams.set("window",String(c.activeIndex)),history.replaceState(history.state,"",f)),window.dispatchEvent(new CustomEvent("tmux:windows",{detail:c.windows}));return}if(c.type==="history"&&typeof c.data=="string"){c.lines>0&&c.data?(v.unshift(bt(c.data)),N+=c.lines,jn(!0,c.lines).finally(()=>{ie=!1})):ie=!1;return}if(c.type==="data"&&typeof c.data=="string"){let f=bt(Le(c.data));if(H==="connecting"){H="live",z=f,i.write(f);return}H==="live"&&(z+=f,i.write(f))}}let Oe=!1;function Ft(){if(Oe)return;let o=Pn,c=localStorage.getItem("tmux-web-token");c&&(o+=(o.includes("?")?"&":"?")+"token="+encodeURIComponent(c)),o+=(o.includes("?")?"&":"?")+"cols="+i.cols+"&rows="+i.rows,a=new WebSocket(o),a.onopen=()=>{H="connecting",N=0,ie=!1,v=[],z="",i.reset(),re=1e3},a.onmessage=f=>{typeof f.data=="string"&&On(f.data)},a.onclose=()=>{L||(H="connecting",!Oe&&setTimeout(()=>{re=Math.min(re*2,1e4),!L&&!Oe&&Ft()},re))},a.onerror=()=>a?.close()}function fe(o){de({type:"input",data:o})}function ce(){return i.fit()}function He(){e.classList.remove("terminal-pending")}function U(){r&&cancelAnimationFrame(r),l&&clearTimeout(l),ce(),r=requestAnimationFrame(()=>{r=0,ce()&&He()}),l=setTimeout(()=>{ce()&&He()},120)}function Hn(){U(),setTimeout(U,50),setTimeout(U,150),setTimeout(U,300)}function Rt(o){return typeof o=="string"&&o.startsWith("image/")}function jt(o){return o?.files?.length?o.files[0]??null:null}function zn(o){if(!o?.items)return null;for(let c=0;c<o.items.length;c++){let f=o.items[c];if(f?.kind==="file"&&Rt(f.type))return f.getAsFile()}return null}async function Un(o){let c=new FormData,f=o instanceof File&&o.name?o.name:"upload";c.append("file",o,f);let b=localStorage.getItem("tmux-web-token"),C={};b&&(C.Authorization="Bearer "+b);let V=await fetch(Nn,{method:"POST",body:c,headers:C});if(!V.ok){let qt="upload failed";try{let Yt=await V.json();Yt.error&&(qt=Yt.error)}catch{}throw new Error(qt)}let ae=await V.json();if(!ae.path)throw new Error("no path in response");return ae.path}async function ht(o){try{let c=await Un(o);fe(c)}catch{}}i.onData(o=>fe(o)),i.onResize(({cols:o,rows:c})=>de({type:"resize",cols:o,rows:c})),i.onScroll(()=>{H!=="live"||ie||!i.isNearScrollbackTop()||(ie=!0,de({type:"load_history",before:N}))});let we=!1,Ee=!1,A=null,F=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 G=document.createElement("div");G.className="terminal-copy-banner terminal-copy-toast",G.textContent="Copied",G.hidden=!0,e.appendChild(G);function Ot(o,c){let f=e.querySelector(".xterm-screen, canvas"),b=(f&&f.getBoundingClientRect().width>0?f:e).getBoundingClientRect(),C=b.height>0&&i.rows>0?b.height/i.rows:18,V=b.width>0&&i.cols>0?b.width/i.cols:9;return{row:Math.max(0,Math.min(i.rows-1,Math.floor((c-b.top)/C))),col:Math.max(0,Math.min(i.cols-1,Math.floor((o-b.left)/V)))}}async function ze(o){if(!o)return;try{if(navigator.clipboard?.writeText){await navigator.clipboard.writeText(o);return}}catch{}let c=document.createElement("textarea");c.value=o,c.style.position="fixed",c.style.opacity="0",c.style.pointerEvents="none",document.body.appendChild(c),c.focus(),c.select();try{document.execCommand("copy")}catch{}c.remove()}let Ce;function Ue(){G.hidden=!1,Ce&&clearTimeout(Ce),Ce=setTimeout(()=>{G.hidden=!0},1e3)}function he(o){we=o,ke.hidden=!o,e.classList.toggle("terminal-copy-mode-active",o),o&&i.focus()}function Ht(){he(!we)}function Wn(o){L||o.button!==0||Ee||(we||o.shiftKey)&&(o.preventDefault(),o.stopPropagation(),Ee=!0,A=Ot(o.clientX,o.clientY),F=A,i.selectCells(A.col,A.row,F.col,F.row),document.addEventListener("mousemove",vt,!0),document.addEventListener("mouseup",gt,!0))}function vt(o){L||!Ee||!A||(o.preventDefault(),o.stopPropagation(),F=Ot(o.clientX,o.clientY),i.selectCells(A.col,A.row,F.col,F.row))}function gt(o){if(L||!Ee||!A||!F)return;o.preventDefault(),o.stopPropagation(),document.removeEventListener("mousemove",vt,!0),document.removeEventListener("mouseup",gt,!0),Ee=!1;let c=i.getCellsText(A.col,A.row,F.col,F.row);A=null,F=null,i.clearSelection(),he(!1),c&&(G.textContent="\u5DF2\u590D\u5236",ze(c).then(Ue)),i.focus()}e.addEventListener("mousedown",Wn,!0),document.addEventListener("keydown",_n,!0);function _n(o){if(!(L||!i.isFocused()||o.defaultPrevented||o.isComposing)){if(we){if(o.key==="Escape"){o.preventDefault(),o.stopPropagation(),A=null,F=null,i.clearSelection(),he(!1);return}if(o.key==="Enter"||(o.ctrlKey||o.metaKey)&&o.code==="KeyC"){o.preventDefault(),o.stopPropagation(),ze(i.getScreenText()).then(Ue),he(!1);return}}if(o.altKey&&o.code==="KeyC"&&!o.ctrlKey&&!o.metaKey){if(o.preventDefault(),o.stopPropagation(),A&&F){let c=i.getCellsText(A.col,A.row,F.col,F.row);A=null,F=null,i.clearSelection(),he(!1),c&&(G.textContent="Copied",ze(c).then(Ue))}else{let c=i.getSelection();c?(i.clearSelection(),G.textContent="Copied",ze(c).then(Ue)):Ht()}return}if((o.ctrlKey||o.metaKey)&&o.code==="KeyV"){o.preventDefault(),o.stopPropagation(),(async()=>{try{if(navigator.clipboard?.read){let c=await navigator.clipboard.read();for(let f of c)for(let b of f.types)if(Rt(b)){let C=await f.getType(b);await ht(C);return}}}catch{}try{let c=await navigator.clipboard?.readText();c&&i.pasteText(zt(c))}catch{}})();return}}}let We=0;function zt(o){return o.split(`\r
1
+ var ei=/\x1b\](?:10|11|110|111|104)(?:;[^\x07\x1b]*)?\x1b?(?:\\|\x07)/g;function vt(e){return e.replace(/\x1b\[\?1049[hl]/g,"")}function Se(e){return e.replace(ei,"")}var Ue;function ti(){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 ni=class Mn{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:s},{FitAddon:r}]=await Promise.all([import("./xterm-BXEES47M.js"),import("./addon-fit-D5N335P2.js"),ti()]),a="'JetBrains Mono', 'SF Mono', 'Menlo', monospace",o=new s({fontSize:ii(14,a),fontFamily:a,cursorBlink:!0,cursorStyle:"bar",scrollback:n,convertEol:!1,smoothScrollDuration:120,theme:i});return new Mn(t,o,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,s=this.paintedCellWidth();s<=0&&(this.fitAddon.fit(),s=this.paintedCellWidth());let r=this.fitAddon.proposeDimensions?.();if(!r)return this.fitAddon.fit(),!0;let a=this.overlayScrollbarWidth(),o=a>0?a+2:0,p=s>0?Math.max(10,Math.min(r.cols,Math.floor((t.width-o)/s))):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,[s,r]=t<=n?[t,n]:[n,t],a=i.viewportY,o=[];for(let p=s;p<=r;p++){let u=i.getLine(a+p);o.push(u?u.translateToString(!0):"")}return o.join(`
2
+ `)}selectRows(t,n){let i=this.terminal.buffer.active,[s,r]=t<=n?[t,n]:[n,t];this.terminal.selectLines(i.viewportY+s,i.viewportY+r)}selectCells(t,n,i,s){let r=this.terminal.buffer.active,a=Math.min(n,s),o=Math.max(n,s);if(a===o){let p=Math.min(t,i),u=Math.max(t,i);this.terminal.select(p,r.viewportY+a,u-p+1)}else this.terminal.selectLines(r.viewportY+a,r.viewportY+o)}getCellsText(t,n,i,s){let r=this.terminal.buffer.active,a=Math.min(n,s),o=Math.max(n,s),p=n<s?t:n>s?i:Math.min(t,i),u=n<s?i:n>s?t:Math.max(t,i),h=r.viewportY,b=[];for(let M=a;M<=o;M++){let C=r.getLine(h+M);if(!C){b.push("");continue}let y=M===a?p:0,g=M===o?u:this.terminal.cols-1,A="";for(let F=y;F<=g;F++){let O=C.getCell(F);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 ii(e,t){try{let n=document.createElement("canvas").getContext("2d");if(!n)return e;let i=100;n.font=`${i}px ${t}`;let s=n.measureText("M").width/i;if(!Number.isFinite(s)||s<=0)return e;let r=window.devicePixelRatio||1,a=e,o=Number.POSITIVE_INFINITY;for(let p=4;p<=40;p++){let u=p/(s*r);if(u<e-1.5||u>e+1.5)continue;let h=Math.abs(u-e);h<o&&(o=h,a=u)}return Math.round(a*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 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 oi(e,t,n){return e.innerHTML="",e.classList.add("terminal-pending"),(async()=>{let i=await ni.create(e,n.scrollback,n.theme),s,r=0,a,o=null,p=0,u=0,h=.2,b=10,M=.95,C=.04,y=null,g=null;function A(l){y||(y=document.createElement("div"),y.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(y)),y.textContent=l?"\u2191 \u4E0A\u7FFB\u4E00\u9875 (PgUp)":"\u2193 \u4E0B\u7FFB\u4E00\u9875 (PgDn)",y.style.top=l?"10%":"auto",y.style.bottom=l?"auto":"10%",y.style.opacity="1",g&&clearTimeout(g),g=setTimeout(()=>{y&&(y.style.opacity="0")},900)}function F(){g&&clearTimeout(g),y&&(y.style.opacity="0")}function O(){p&&(cancelAnimationFrame(p),p=0),u=0}function x(l){if(O(),Math.abs(l)<h)return;u=Math.max(-b,Math.min(b,l));let c=()=>{if(I){p=0;return}let f=i.cellHeight(),w=f>0?Math.round(u*16/f):u>0?1:-1;w===0&&(w=u>0?1:-1);let L=i.viewportY()-w,Z=i.baseY(),oe=Math.max(0,Math.min(L,Z));if(i.scrollToLine(oe,!0),u*=M,oe!==L){p=0;return}if(Math.abs(u)<C){p=0;return}p=requestAnimationFrame(c)};p=requestAnimationFrame(c)}let _=0,U="connecting",H=0,ae=!1,v=[],W="",I=!1,le=1e3,$=location.protocol==="https:"?"wss:":"ws:",$t=n.wsBase||"/ws",An=$+"//"+location.host+$t+"/"+encodeURIComponent(t),Dn=($t.replace(/^\/ws/,"")||"")+"/api/session/"+encodeURIComponent(t)+"/upload",$n=/^((?!chrome|android|crios|fxios|edgios).)*safari/i.test(navigator.userAgent);function Pn(){return v.join("")+W}async function Nn(l,c=0){let f=l?i.viewportY():0,w=Se(Pn());if(i.reset(),!w){l||i.scrollToBottom();return}await i.write(w),l?i.scrollToLine(c+f):i.scrollToBottom()}function re(l){s?.readyState===WebSocket.OPEN&&s.send(JSON.stringify(l))}function Fn(l){let c;try{c=JSON.parse(l)}catch{U==="live"&&(W+=l,i.write(Se(l)));return}if(c.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(c.type==="attach_failed"&&typeof c.message=="string"){He=!0,U="dead",i.reset(),i.write(`\r
4
+ \x1B[31m`+Se(c.message)+`\x1B[0m\r
5
+ `).then(()=>{je();try{s?.close()}catch{}});return}if(c.type==="auth.ok"){c.token&&localStorage.setItem("tmux-web-token",c.token),le=1e3,de(),re({type:"resize",cols:i.cols,rows:i.rows}),q();return}if(c.type==="auth.failed"){if(c.permanentLock||c.retryAfterMs&&c.retryAfterMs>6e4){localStorage.removeItem("tmux-web-token"),location.href="/login?error="+encodeURIComponent(c.message);return}return}if(c.type==="snapshot"&&typeof c.data=="string"){let f=vt(Se(c.data));v=[f],W="",H=typeof c.lines=="number"?c.lines:n.terminal.initialLines,U="live",i.reset(),de(),re({type:"resize",cols:i.cols,rows:i.rows}),i.write(f).then(()=>i.scrollToBottom());return}if(c.type==="window_changed"&&typeof c.activeIndex=="number"){let f=new URL(location.href);f.searchParams.get("window")!==String(c.activeIndex)&&(f.searchParams.set("window",String(c.activeIndex)),history.replaceState(history.state,"",f)),window.dispatchEvent(new CustomEvent("tmux:windows",{detail:c.windows}));return}if(c.type==="history"&&typeof c.data=="string"){c.lines>0&&c.data?(v.unshift(vt(c.data)),H+=c.lines,Nn(!0,c.lines).finally(()=>{ae=!1})):ae=!1;return}if(c.type==="data"&&typeof c.data=="string"){let f=vt(Se(c.data));if(U==="connecting"){U="live",W=f,i.write(f);return}U==="live"&&(W+=f,i.write(f))}}let He=!1;function Pt(){if(He)return;let l=An,c=localStorage.getItem("tmux-web-token");c&&(l+=(l.includes("?")?"&":"?")+"token="+encodeURIComponent(c)),l+=(l.includes("?")?"&":"?")+"cols="+i.cols+"&rows="+i.rows,s=new WebSocket(l),s.onopen=()=>{U="connecting",H=0,ae=!1,v=[],W="",i.reset(),le=1e3},s.onmessage=f=>{typeof f.data=="string"&&Fn(f.data)},s.onclose=()=>{I||(U="connecting",!He&&setTimeout(()=>{le=Math.min(le*2,1e4),!I&&!He&&Pt()},le))},s.onerror=()=>s?.close()}function he(l){re({type:"input",data:l})}function de(){return i.fit()}function je(){e.classList.remove("terminal-pending")}function q(){r&&cancelAnimationFrame(r),a&&clearTimeout(a),de(),r=requestAnimationFrame(()=>{r=0,de()&&je()}),a=setTimeout(()=>{de()&&je()},120)}function On(){q(),setTimeout(q,50),setTimeout(q,150),setTimeout(q,300)}function Nt(l){return typeof l=="string"&&l.startsWith("image/")}function Ft(l){return l?.files?.length?l.files[0]??null:null}function Hn(l){if(!l?.items)return null;for(let c=0;c<l.items.length;c++){let f=l.items[c];if(f?.kind==="file"&&Nt(f.type))return f.getAsFile()}return null}async function jn(l){let c=new FormData,f=l instanceof File&&l.name?l.name:"upload";c.append("file",l,f);let w=localStorage.getItem("tmux-web-token"),L={};w&&(L.Authorization="Bearer "+w);let Z=await fetch(Dn,{method:"POST",body:c,headers:L});if(!Z.ok){let Ut="upload failed";try{let Wt=await Z.json();Wt.error&&(Ut=Wt.error)}catch{}throw new Error(Ut)}let oe=await Z.json();if(!oe.path)throw new Error("no path in response");return oe.path}async function mt(l){try{let c=await jn(l);he(c)}catch{}}i.onData(l=>he(l)),i.onResize(({cols:l,rows:c})=>re({type:"resize",cols:l,rows:c})),i.onScroll(()=>{U!=="live"||ae||!i.isNearScrollbackTop()||(ae=!0,re({type:"load_history",before:H}))});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 ee=document.createElement("div");ee.className="terminal-copy-banner terminal-copy-toast",ee.textContent="Copied",ee.hidden=!0,e.appendChild(ee);function Ot(l,c){let f=e.querySelector(".xterm-screen, canvas"),w=(f&&f.getBoundingClientRect().width>0?f:e).getBoundingClientRect(),L=w.height>0&&i.rows>0?w.height/i.rows:18,Z=w.width>0&&i.cols>0?w.width/i.cols:9;return{row:Math.max(0,Math.min(i.rows-1,Math.floor((c-w.top)/L))),col:Math.max(0,Math.min(i.cols-1,Math.floor((l-w.left)/Z)))}}async function Re(l){if(!l)return;try{if(navigator.clipboard?.writeText){await navigator.clipboard.writeText(l);return}}catch{}let c=document.createElement("textarea");c.value=l,c.style.position="fixed",c.style.opacity="0",c.style.pointerEvents="none",document.body.appendChild(c),c.focus(),c.select();try{document.execCommand("copy")}catch{}c.remove()}let Ce;function ze(){ee.hidden=!1,Ce&&clearTimeout(Ce),Ce=setTimeout(()=>{ee.hidden=!0},1e3)}function ve(l){we=l,ke.hidden=!l,e.classList.toggle("terminal-copy-mode-active",l),l&&i.focus()}function Ht(){ve(!we)}function Rn(l){I||l.button!==0||Ee||(we||l.shiftKey)&&(l.preventDefault(),l.stopPropagation(),Ee=!0,P=Ot(l.clientX,l.clientY),j=P,i.selectCells(P.col,P.row,j.col,j.row),document.addEventListener("mousemove",ft,!0),document.addEventListener("mouseup",ht,!0))}function ft(l){I||!Ee||!P||(l.preventDefault(),l.stopPropagation(),j=Ot(l.clientX,l.clientY),i.selectCells(P.col,P.row,j.col,j.row))}function ht(l){if(I||!Ee||!P||!j)return;l.preventDefault(),l.stopPropagation(),document.removeEventListener("mousemove",ft,!0),document.removeEventListener("mouseup",ht,!0),Ee=!1;let c=i.getCellsText(P.col,P.row,j.col,j.row);P=null,j=null,i.clearSelection(),ve(!1),c&&(ee.textContent="\u5DF2\u590D\u5236",Re(c).then(ze)),i.focus()}e.addEventListener("mousedown",Rn,!0),document.addEventListener("keydown",zn,!0);function zn(l){if(!(I||!i.isFocused()||l.defaultPrevented||l.isComposing)){if(we){if(l.key==="Escape"){l.preventDefault(),l.stopPropagation(),P=null,j=null,i.clearSelection(),ve(!1);return}if(l.key==="Enter"||(l.ctrlKey||l.metaKey)&&l.code==="KeyC"){l.preventDefault(),l.stopPropagation(),Re(i.getScreenText()).then(ze),ve(!1);return}}if(l.altKey&&l.code==="KeyC"&&!l.ctrlKey&&!l.metaKey){if(l.preventDefault(),l.stopPropagation(),P&&j){let c=i.getCellsText(P.col,P.row,j.col,j.row);P=null,j=null,i.clearSelection(),ve(!1),c&&(ee.textContent="Copied",Re(c).then(ze))}else{let c=i.getSelection();c?(i.clearSelection(),ee.textContent="Copied",Re(c).then(ze)):Ht()}return}if((l.ctrlKey||l.metaKey)&&l.code==="KeyV"){l.preventDefault(),l.stopPropagation(),(async()=>{try{if(navigator.clipboard?.read){let c=await navigator.clipboard.read();for(let f of c)for(let w of f.types)if(Nt(w)){let L=await f.getType(w);await mt(L);return}}}catch{}try{let c=await navigator.clipboard?.readText();c&&i.pasteText(jt(c))}catch{}})();return}}}let _e=0;function jt(l){return l.split(`\r
6
6
  `).join(`
7
7
  `).split(`
8
- `).join("\r")}async function qn(o){let c=zn(o.clipboardData);if(c){o.preventDefault(),o.stopPropagation();let C=Date.now();if(C-We<50)return;We=C,await ht(c);return}let f=o.clipboardData?.getData("text/plain");if(!f)return;o.preventDefault(),o.stopPropagation();let b=Date.now();b-We<50||(We=b,i.pasteText(zt(f)))}let xe=0;function Yn(o){o.preventDefault(),xe++,jt(o.dataTransfer)&&e.classList.add("terminal-drag-over")}function Jn(o){o.preventDefault(),o.dataTransfer&&(o.dataTransfer.dropEffect="copy")}function Kn(o){o.preventDefault(),xe--,xe<=0&&(xe=0,e.classList.remove("terminal-drag-over"))}async function Vn(o){o.preventDefault(),xe=0,e.classList.remove("terminal-drag-over");let c=jt(o.dataTransfer);c&&await ht(c)}function Ut(o){!Fn||o.key!=="Escape"||we||o.defaultPrevented||o.repeat||o.metaKey||o.ctrlKey||o.altKey||i.isFocused()&&(o.preventDefault(),o.stopPropagation(),fe("\x1B"))}e.addEventListener("paste",qn),e.addEventListener("dragenter",Yn),e.addEventListener("dragover",Jn),e.addEventListener("dragleave",Kn),e.addEventListener("drop",Vn),document.addEventListener("keydown",Ut,!0);function Xn(o){if(o.touches.length!==1){s=null;return}let c=o.touches[0];if(!c)return;W();let f=e.getBoundingClientRect(),b=c.clientX-f.left<f.width*.4?"tui":"history",C=c.clientY-f.top<f.height*.5;s={startX:c.clientX,startY:c.clientY,lastX:c.clientX,lastY:c.clientY,lastT:performance.now(),velocity:0,scrolling:!1,zone:b,tuiUp:C,sent:!1},o.stopPropagation()}function Qn(o){if(!s||o.touches.length!==1)return;let c=o.touches[0];if(!c)return;let f=c.clientY-s.startY,b=c.clientX-s.startX;if(!s.scrolling){if(Math.abs(f)<8||Math.abs(f)<Math.abs(b))return;s.scrolling=!0,oe=Date.now()+500}o.preventDefault(),o.stopPropagation();let C=performance.now(),V=c.clientY-s.lastY;if(s.zone==="tui"){s.sent||(s.sent=!0,fe(s.tuiUp?"\x1B[5~":"\x1B[6~"),O(s.tuiUp)),s.lastX=c.clientX,s.lastY=c.clientY,s.lastT=C;return}let ae=C-s.lastT;ae>0&&(s.velocity=V/ae),ti(-V),s.lastX=c.clientX,s.lastY=c.clientY,s.lastT=C}function Zn(o){if(!s)return;let c=s.scrolling,f=s.zone,b=s.tuiUp,C=s.velocity;if(s=null,o.stopPropagation(),f==="tui"){c||(fe(b?"\x1B[5~":"\x1B[6~"),O(b),oe=Date.now()+500,o.preventDefault());return}if(!c){i.focus();return}oe=Date.now()+500,o.preventDefault(),C&&le(C)}function Gn(o){s=null,W(),o.stopPropagation()}function ei(o){o.pointerType==="touch"&&Date.now()<oe&&(o.preventDefault(),o.stopPropagation())}function ti(o){let c=i.cellHeight(),f=c>0?Math.round(o/c):o>0?1:-1;f===0&&(f=o>0?1:-1),i.scrollLines(f)}e.addEventListener("touchstart",Xn,{passive:!0,capture:!0}),e.addEventListener("touchmove",Qn,{passive:!1,capture:!0}),e.addEventListener("touchend",Zn,{passive:!1,capture:!0}),e.addEventListener("touchcancel",Gn,{passive:!0,capture:!0}),e.addEventListener("pointerup",ei,!0);function Wt(){U()}window.addEventListener("resize",Wt),window.visualViewport?.addEventListener("resize",U),window.visualViewport?.addEventListener("scroll",U);let _t=new ResizeObserver(()=>U());_t.observe(e),document.fonts?.ready.then(()=>{U(),setTimeout(U,50),setTimeout(U,200)}),e.addEventListener("focusin",Hn,!0);async function ni(){if(document.fonts?.ready)try{await Promise.race([document.fonts.ready,new Promise(o=>setTimeout(o,1e3))])}catch{}}return requestAnimationFrame(()=>{ce()&&He(),(async()=>(await ni(),ce()&&de({type:"resize",cols:i.cols,rows:i.rows}),Ft(),U()))()}),{destroy(){if(L=!0,W(),he(!1),Ce&&clearTimeout(Ce),document.removeEventListener("mousemove",vt,!0),document.removeEventListener("mouseup",gt,!0),a){try{a.close(1e3,"session switch")}catch{}a=void 0}e.innerHTML="",e.classList.remove("terminal-pending"),window.removeEventListener("resize",Wt),_t.disconnect(),document.removeEventListener("keydown",Ut,!0)},focus(){i.focus()},sendInput(o){fe(o)},toggleCopyMode(){Ht()}}})()}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 $(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 d(e,t,n){let i=document.createElement(e);return t&&(i.className=t),n!==void 0&&(i.textContent=n),i}function Jt(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 ci(){let e=d("div","bots-section");e.id="bots-section";let t=d("div","bots-head"),n=d("span","bots-title","Bots"),i=d("span","bots-badge");i.hidden=!0,n.appendChild(i);let a=d("span","bots-head-actions"),r=d("button","bots-icon-btn","\u2699");r.title="Bot templates",r.onclick=()=>void Ke();let l=d("button","bots-icon-btn","+");l.title="New bot from template",l.onclick=()=>void wi(),a.append(r,l),t.append(n,a);let s=d("div","bots-list");s.id="bots-list",e.append(t,s);let p=document.querySelector(".sidebar"),u=document.querySelector(".sidebar-footer");return p&&p.insertBefore(e,u||null),{list:s,badge:i}}var Se=null,qe=null;function Ye(){if(!Se)return;Se.textContent="";let e=new Map;for(let i of m.bots){if(i.parentBotId)continue;let a=i.projectPath;e.has(a)||e.set(a,[]),e.get(a).push(i)}e.size===0&&Se.appendChild(d("div","bots-empty","No bots yet"));for(let[i,a]of e){let r=d("div","bots-group"),l=d("div","bots-group-label",i.replace(/^.*\//,"")||i);l.title=i;let s=d("button","bots-icon-btn bots-group-add","+");s.title=`New bot in ${i}`,s.onclick=p=>{p.stopPropagation(),xt(i)},l.appendChild(s),r.appendChild(l);for(let p of a){r.appendChild(Kt(p));for(let u of m.bots.filter(h=>h.parentBotId===p.id)){let h=Kt(u);h.classList.add("bots-row-child"),r.appendChild(h)}}Se.appendChild(r)}let t=m.approvals.length;qe&&(qe.hidden=t===0,qe.textContent=String(t));let n=document.getElementById("bv-inbox-count");n&&(n.textContent=t?`(${t})`:"")}function Kt(e){let t=d("div","bots-row");t.dataset.botId=e.id,e.id===m.activeId&&t.classList.add("active");let n=d("span","bots-dot");n.style.background=Jt(e.status);let i=d("span","bots-name",e.title),a=d("span","bots-meta",e.status.replace(/_/g," "));return t.append(n,i,a),t.onclick=()=>void Qt(e.id),t}function pi(){let e=d("div","bots-view");e.id="bots-view",e.hidden=!0;let t=d("div","bots-view-head"),n=d("div","bv-title"),i=d("span","bots-dot");i.id="bv-dot";let a=d("span","bv-title-text");a.id="bv-title";let r=d("span","bv-status");r.id="bv-status",n.append(i,a,r);let l=d("div","bv-actions"),s=d("button","btn","Needs you "),p=d("span");p.id="bv-inbox-count",s.appendChild(p),s.onclick=()=>void an();let u=d("button","btn","Resume");u.onclick=()=>void Xt(D=>$(`/api/bots/${D}/resume`,{method:"POST"}).then(()=>X(!0)));let h=d("button","btn danger","Stop");h.onclick=()=>void Xt(D=>$(`/api/bots/${D}/stop`,{method:"POST"}).then(()=>X(!0)));let g=d("button","btn","Delete");g.onclick=()=>{m.activeId&&confirm("Delete this bot and its session?")&&$(`/api/bots/${m.activeId}`,{method:"DELETE"}).then(()=>{wt(),X(!0)})};let x=d("button","btn","\u2715");x.onclick=()=>wt(),l.append(s,u,h,g,x),t.append(n,l);let B=d("div","bots-messages");B.id="bots-messages";let E=d("div","bots-composer"),I=d("textarea");I.id="bots-input",I.rows=1,I.placeholder="Message the bot\u2026 (Enter to send, Shift+Enter for newline)",I.onkeydown=D=>{D.key==="Enter"&&!D.shiftKey&&(D.preventDefault(),Vt())};let O=d("button","btn primary","Send");O.onclick=()=>void Vt(),E.append(I,O),e.append(t,B,E),document.querySelector(".main-area")?.appendChild(e),document.getElementById("bots-modal")||bi()}async function Vt(){let e=document.getElementById("bots-input");if(!e||!m.activeId||!e.value.trim())return;let t=e.value;e.value="";try{await $(`/api/bots/${m.activeId}/input`,{method:"POST",body:JSON.stringify({text:t})})}catch(n){Ie({kind:"notice",level:"error",text:n instanceof Error?n.message:String(n)})}}function Xt(e){m.activeId&&e(m.activeId).catch(t=>Ie({kind:"notice",level:"error",text:t instanceof Error?t.message:String(t)}))}function wt(){m.activeId=null;let e=document.getElementById("bots-view");e&&(e.hidden=!0);try{m.ws?.close()}catch{}m.ws=null,Ye();let t=document.getElementById("main-placeholder");t&&(t.style.display="")}async function Qt(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"),Ye(),Et();try{m.ws?.close()}catch{}let r=location.protocol==="https:"?"wss:":"ws:",l=new WebSocket(`${r}//${location.host}/ws/bots/${encodeURIComponent(e)}?token=${encodeURIComponent(yt())}`);m.ws=l,l.onmessage=s=>{try{en(JSON.parse(String(s.data)))}catch{}},l.onclose=()=>{m.activeId===e&&setTimeout(()=>{m.activeId===e&&X(!0)},1500)},await X(!0)}function Zt(){return m.bots.find(e=>e.id===m.activeId)||null}function Gt(){let e=Zt();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}`),i&&(i.style.background=Jt(e.status))}function Ie(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,Et()}))}function Et(){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=d("div","bv-msg bv-user");a.textContent=i.text,e.appendChild(a),n=null}else if(i.kind==="assistant"){let a=d("div","bv-msg bv-assistant");if(i.thinking){let l=d("details","bv-thinking");l.appendChild(d("summary",void 0,"thinking")),l.appendChild(d("div",void 0,i.thinking)),a.appendChild(l)}let r=d("div","bv-text");r.textContent=i.text,a.appendChild(r),e.appendChild(a),n=r}else if(i.kind==="tool")e.appendChild(ui(i)),n=null;else if(i.kind==="approval")e.appendChild(mi(i)),n=null;else if(i.kind==="notice"){let a=d("div",`bv-notice bv-notice-${i.level}`,i.text);e.appendChild(a)}n&&(n.scrollTop=n.scrollHeight),e.scrollTop=e.scrollHeight}function ui(e){let t=d("details","bv-tool");t.open=e.phase!=="end"||!!e.isError;let n=d("summary"),i=d("span","bv-tool-name",e.name);if(n.appendChild(i),e.phase!=="end"&&n.appendChild(d("span","bv-tool-phase",e.phase)),e.isError&&n.appendChild(d("span","bv-tool-error","error")),typeof e.durationMs=="number"&&n.appendChild(d("span","bv-tool-meta",`${Math.round(e.durationMs)}ms`)),t.appendChild(n),e.args!==void 0){let a=d("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=d("pre","bv-pre bv-output");a.textContent=e.output,t.appendChild(a)}return t}function mi(e){let t=d("div","bv-approval"),n=e.approval;if(t.appendChild(d("div","bv-approval-title",n.title)),n.message&&t.appendChild(d("pre","bv-pre",n.message)),e.decided)return t.appendChild(d("div","bv-approval-decided",e.decided==="allowed"?"Allowed":"Denied")),t;let i=d("input","bv-reason");i.placeholder="reason (optional)";let a=d("div","bv-approval-actions"),r=d("button","btn primary","Allow"),l=d("button","btn danger","Deny"),s=async p=>{try{await $(`/api/bots/${n.botId}/approve`,{method:"POST",body:JSON.stringify({requestId:n.id,allow:p,reason:i.value||void 0})}),e.decided=p?"allowed":"denied",pe(),X(!0)}catch(u){Ie({kind:"notice",level:"error",text:u instanceof Error?u.message:String(u)})}};return r.onclick=()=>void s(!0),l.onclick=()=>void s(!1),a.append(i,r,l),t.appendChild(a),t}function en(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")Ie({kind:"user",text:String(e.text||"")});else if(t==="status"){let a=Zt();a&&(a.status=String(e.status||a.status)),Gt(),vi()}else if(t==="message"){let a=e.message;if(!a||String(a.role||"")!=="assistant")return;let r=fi(a),l=hi(a),s=i[i.length-1];s&&s.kind==="assistant"?(s.text=r||s.text,s.thinking=l||s.thinking):i.push({kind:"assistant",text:r,thinking:l}),m.items.set(n,i),pe()}else if(t==="delta"){let a=String(e.kind||""),r=String(e.delta||""),l=i[i.length-1];(!l||l.kind!=="assistant")&&(i.push({kind:"assistant",text:"",thinking:""}),l=i[i.length-1]),l.kind==="assistant"&&(a==="text"?l.text+=r:a==="thinking"&&(l.thinking+=r)),m.items.set(n,i),pe()}else if(t==="tool"){let a=String(e.callId||""),r=i.find(s=>s.kind==="tool"&&s.callId===a),l=String(e.phase||"start");r?(r.phase=l,l==="update"&&e.output&&(r.output=String(e.output)),l==="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:l}),m.items.set(n,i),pe()}else if(t==="approval"){let a=e.approval;if(!a)return;let r=i;for(let l=r.length-1;l>=0;l--){let s=r[l];if(s.kind==="approval"&&s.approval.id===a.id){s.approval=a,a.state!=="pending"&&(s.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"&&Ie({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 hi(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 X(e=!1){try{let[t,n]=await Promise.all([$("/api/bots"),$("/api/bots/approvals")]);if(m.bots=t,m.approvals=n,Ye(),Gt(),e&&m.activeId){let i=await $(`/api/bots/${m.activeId}/events?limit=300`);gi(i)}}catch{}}async function vi(){try{m.bots=await $("/api/bots"),Ye()}catch{}}function gi(e){if(m.activeId){m.items.set(m.activeId,[]);for(let t of e)en(t);Et()}}function bi(){let e=d("div","bots-modal");e.id="bots-modal",e.hidden=!0;let t=d("div","bots-modal-card"),n=d("div","bots-modal-head"),i=d("span");i.id="bots-modal-title";let a=d("button","btn","\u2715");a.onclick=()=>Je(),n.append(i,a);let r=d("div","bots-modal-body");r.id="bots-modal-body",t.append(n,r),e.appendChild(t),e.onclick=l=>{l.target===e&&Je()},document.body.appendChild(e)}function kt(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 yi(){return m.catalog||(m.catalog=await $("/api/bots/catalog")),m.catalog}async function tn(){return m.templates=await $("/api/bots/templates"),m.templates}async function Ke(){let e=kt("Bot templates"),[t,n]=await Promise.all([yi(),tn()]),i=d("div","bv-template-list");for(let p of n){let u=d("div","bv-template-row");u.appendChild(d("span","bv-template-name",p.manifest.name)),u.appendChild(d("span","bv-template-desc",p.manifest.description||""));let h=d("button","btn","Edit");h.onclick=()=>nn(e,t,p);let g=d("button","btn danger","Delete");g.onclick=()=>{confirm(`Delete template ${p.manifest.name}?`)&&$(`/api/bots/templates/${p.id}`,{method:"DELETE"}).then(()=>Ke())};let x=d("span","bv-template-actions");x.append(h,g),u.appendChild(x),i.appendChild(u)}n.length===0&&i.appendChild(d("div","bots-empty","No templates yet")),e.appendChild(i);let a=d("div","bv-template-actions"),r=d("button","btn primary","New template");r.onclick=()=>nn(e,t,null);let l=d("button","btn","Export");l.title="Download templates + library as JSON",l.onclick=()=>{(async()=>{try{let p=await fetch("/api/bots/export",{headers:{Authorization:`Bearer ${yt()}`}});if(!p.ok)throw new Error(`HTTP ${p.status}`);let u=await p.blob(),h=document.createElement("a");h.href=URL.createObjectURL(u),h.download=`tmux-weblink-bots-${new Date().toISOString().slice(0,10)}.json`,h.click(),setTimeout(()=>URL.revokeObjectURL(h.href),2e3)}catch(p){alert(p instanceof Error?p.message:String(p))}})()};let s=d("button","btn","Import");s.title="Restore templates from a JSON bundle",s.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 h=JSON.parse(await u.text()),g=await $("/api/bots/import",{method:"POST",body:JSON.stringify(h)});alert(`Imported ${g.templates} templates, ${g.files} library files (${g.skipped} kept)`),await Ke()}catch(h){alert(h instanceof Error?h.message:String(h))}})()},p.click()},a.append(r,l,s),e.appendChild(a)}function Ct(e,t,n){let i=d("div","bv-field");i.appendChild(d("label","bv-label",e));let a=d("div","bv-check-grid"),r=[];for(let l of t){let s=d("label","bv-check"),p=document.createElement("input");p.type="checkbox",p.checked=n.includes(l.id),s.append(p,d("span",void 0,l.label)),l.hint&&(s.title=l.hint),a.appendChild(s),r.push({id:l.id,input:p})}return i.appendChild(a),{element:i,get:()=>r.filter(l=>l.input.checked).map(l=>l.id)}}function nn(e,t,n){e.textContent="";let i=n?JSON.parse(JSON.stringify(n.manifest)):{name:"new-bot",description:""},a=d("input","bv-input");a.value=i.name,a.placeholder="Template name";let r=d("input","bv-input");r.value=i.description||"",r.placeholder="One line description";let l=d("textarea","bv-textarea");l.rows=6,l.value=i.system||"",l.placeholder="System prompt for this bot (written to SYSTEM.md)";let s=Ct("Skills",t.skills.map(v=>({id:v.id,label:v.name,hint:v.description})),i.skills||[]),p=Ct("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)$/,""))),u=Ct("Prompt templates",t.prompts.map(v=>({id:v.id,label:v.name})),i.prompts||[]),h=d("select","bv-input");h.appendChild(new Option("none",""));for(let v of t.mcp)h.appendChild(new Option(v.name,v.id));i.mcp&&(h.value=t.mcp.find(v=>JSON.stringify(v.servers)===JSON.stringify(i.mcp?.mcpServers))?.id||"");let g=d("div","bv-field");g.appendChild(d("label","bv-label","Tools (allow list; deny always blocks)"));let x=d("div","bv-check-grid"),B=[];for(let v of t.tools){let z=d("label","bv-check"),L=document.createElement("input");L.type="checkbox",L.checked=(i.tools?.allow||[]).includes(v.name)||!i.tools?.allow?.length&&["read","grep","find","ls","edit","write","bash"].includes(v.name),z.append(L,d("span",void 0,v.name)),x.appendChild(z),B.push({name:v.name,input:L})}g.appendChild(x);let E=d("input","bv-input");E.value=(i.tools?.deny||[]).join(", "),E.placeholder="Always deny (comma separated), e.g. bash, write";let I=d("textarea","bv-textarea");I.rows=2,I.value=(i.packages||[]).join(`
9
- `),I.placeholder="Pi packages, one per line (npm:@scope/pkg@1.2.3, git:..., ./path)";let O=d("select","bv-input");O.appendChild(new Option("default (Pi settings)",""));for(let v of t.models)O.appendChild(new Option(`${v.provider}/${v.model}`,`${v.provider}
10
- ${v.model}`));i.model?.provider&&i.model?.id&&(O.value=`${i.model.provider}
11
- ${i.model.id}`);let D=d("select","bv-input");for(let v of["","off","minimal","low","medium","high","xhigh","max"])D.appendChild(new Option(v||"default",v));i.model?.thinking&&(D.value=i.model.thinking);let W=d("select","bv-input");for(let v of["supervised","auto-accept-edits","full-access"])W.appendChild(new Option(v,v));W.value=i.permissions?.runtimeMode||"supervised";let le=d("select","bv-input");le.appendChild(new Option("ignore project .pi (recommended)","ignore")),le.appendChild(new Option("inherit project .pi (needs trust)","inherit")),le.value=i.projectResources||"ignore";let oe=d("label","bv-check"),H=document.createElement("input");H.type="checkbox",H.checked=!!i.orchestrator,oe.append(H,d("span",void 0,"Super bot: gets orchestration tools (create/stop/status child bots)"));let N=(v,z)=>{let L=d("div","bv-field");return L.appendChild(d("label","bv-label",v)),L.appendChild(z),L};e.append(N("Name",a),N("Description",r),N("System prompt",l),s.element,p.element,u.element,N("MCP preset",h),g,N("Always deny tools",E),N("Packages",I),N("Model",O),N("Thinking level",D),N("Approval mode",W),N("Project resources",le),oe);let ie=d("button","btn primary",n?"Save template":"Create template");ie.onclick=async()=>{let[v,z]=O.value.split(`
12
- `),L=t.mcp.find(M=>M.id===h.value),re={name:a.value.trim()||"bot",description:r.value.trim()||void 0,system:l.value.trim()||void 0,skills:s.get(),extensions:p.get().map(M=>(M.startsWith("builtin:"),M)),prompts:u.get(),packages:I.value.split(`
13
- `).map(M=>M.trim()).filter(Boolean),mcp:L?{mcpServers:L.servers}:void 0,tools:{allow:B.filter(M=>M.input.checked).map(M=>M.name),deny:E.value.split(",").map(M=>M.trim()).filter(Boolean)},model:v?{provider:v,id:z,thinking:D.value||void 0}:void 0,permissions:{runtimeMode:W.value},projectResources:le.value==="inherit"?"inherit":"ignore",orchestrator:H.checked||void 0};try{await $("/api/bots/templates",{method:"POST",body:JSON.stringify({id:n?.id,manifest:re})}),Je(),await Ke()}catch(M){alert(M instanceof Error?M.message:String(M))}},e.appendChild(ie)}async function wi(){return xt("")}async function xt(e){let t=kt("New bot"),n=await tn();if(n.length===0){t.appendChild(d("div","bots-empty","Create a template first (\u2699)."));return}let i=d("select","bv-input");for(let u of n)i.appendChild(new Option(u.manifest.name,u.id));let a=d("input","bv-input");a.placeholder="Title (defaults to template name)";let r=d("input","bv-input");r.placeholder="/path/to/project";let l=e||m.bots[0]?.projectPath||"";r.value=l;let s=d("select","bv-input");s.appendChild(new Option("shared \u2014 run in the project folder","shared")),s.appendChild(new Option("worktree \u2014 isolated git worktree","worktree")),t.append(Ve("Template",i),Ve("Title",a),Ve("Project path",r),Ve("Workspace",s));let p=d("button","btn primary","Create bot");p.onclick=async()=>{try{let u=await $("/api/bots",{method:"POST",body:JSON.stringify({templateId:i.value,title:a.value.trim()||void 0,projectPath:r.value.trim()||void 0,isolation:s.value})});Je(),await X(!0),await Qt(u.id)}catch(u){alert(u instanceof Error?u.message:String(u))}},t.appendChild(p)}function Ve(e,t){let n=d("div","bv-field");return n.appendChild(d("label","bv-label",e)),n.appendChild(t),n}async function an(){let e=kt("Needs you");if(m.approvals=await $("/api/bots/approvals"),m.approvals.length===0){e.appendChild(d("div","bots-empty","Nothing waiting."));return}for(let t of m.approvals){let n=d("div","bv-approval");n.appendChild(d("div","bv-approval-title",`${t.botTitle}: ${t.title}`)),t.message&&n.appendChild(d("pre","bv-pre",t.message));let i=d("input","bv-reason");i.placeholder="reason (optional)";let a=d("div","bv-approval-actions"),r=d("button","btn primary","Allow"),l=d("button","btn danger","Deny"),s=async p=>{await $(`/api/bots/${t.botId}/approve`,{method:"POST",body:JSON.stringify({requestId:t.id,allow:p,reason:i.value||void 0})}),await X(!0),await an()};r.onclick=()=>void s(!0),l.onclick=()=>void s(!1),a.append(i,r,l),n.appendChild(a),e.appendChild(n)}}function Ei(){if(document.getElementById("bots-section"))return;let e=ci();Se=e.list,qe=e.badge,pi(),document.addEventListener("click",t=>{let n=t.target;n&&n.closest(".session-item")&&m.activeId&&wt()},!0),X(!0),m.pollTimer=window.setInterval(()=>{document.hidden||X()},6e3),window.addEventListener("beforeunload",()=>window.clearInterval(m.pollTimer))}var Te=window.__TMUX_WEB_SHELL__,k=null,S=null,Be=typeof window.__TMUX_WEB_SCOPE__?.agentId=="string"?window.__TMUX_WEB_SCOPE__.agentId:null,R=Be;window.__tmuxWebScopeAgent=Be;var Lt="sessions",ee="",Xe="",Qe="",sn="";function P(e){return R?"/a/"+encodeURIComponent(R)+e:e}var y=document.getElementById("sidebar-content"),ue=document.getElementById("main-placeholder"),_=document.getElementById("terminal-container"),Me=document.getElementById("file-editor"),ki=document.getElementById("fe-path"),J=document.getElementById("fe-status"),De=document.getElementById("fe-content"),me=document.getElementById("fe-save"),Ci=document.getElementById("fe-delete"),xi=document.getElementById("fe-back"),ln=document.getElementById("fe-new-name"),Li=document.getElementById("fe-new-btn"),St=document.getElementById("settings-backdrop"),on=document.getElementById("settings-popover"),rn=document.querySelector(".sidebar"),dn="tmux-web-force-narrow";function Ze(){try{return localStorage.getItem(dn)==="1"}catch{return!1}}function cn(){document.documentElement.classList.toggle("force-narrow",Ze()),Ze()&&pn()&&Ge()}function pn(){return Ze()?!0:window.matchMedia("(max-width: 640px)").matches}function Ge(){pn()&&rn.classList.add("collapsed")}function un(){rn.classList.remove("collapsed")}document.getElementById("mode-sessions").addEventListener("click",()=>{un(),mn("sessions")}),document.getElementById("mode-files").addEventListener("click",()=>{un(),mn("files")});function mn(e){Lt=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="",te()):Oi()}var It="";async function te(){if(Lt!=="sessions")return;try{let t=await(await fetch("/api/sidebar/sessions")).json(),n=JSON.stringify({recent:t.recent,agents:t.agents,tombstones:t.tombstones});if(n===It)return;It=n,Mi(t)}catch{y.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")}),Pt()}var fn="tmux-web-sidebar-group-collapsed";function hn(){try{return new Set(JSON.parse(localStorage.getItem(fn)||"[]"))}catch{return new Set}}function Si(e){try{localStorage.setItem(fn,JSON.stringify([...e]))}catch{}}function Ii(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 l=a.slice(-r).join("/");if(!t.some(s=>!s||s===e?!1:(n&&(s===n||s.startsWith(n+"/"))?"~"+s.slice(n.length):s).split("/").filter(Boolean).slice(-r).join("/")===l))return l}return i}function vn(e,t,n,i=!0){let a=new Map;for(let s of e){let p=s.path||"";a.has(p)||a.set(p,[]),a.get(p).push(s)}let r=[...a.keys()],l=hn();for(let[s,p]of a){let u=Ii(s,r,t),h=l.has(s),g=document.createElement("div");g.className="session-group-header"+(h?" collapsed":""),g.title=s||"No working directory",g.innerHTML=`<span class="sg-folder">&#128193;</span><span class="sg-label">${w(u)}</span>`,g.addEventListener("click",()=>{let B=hn(),E=g.nextElementSibling;B.has(s)?(B.delete(s),g.classList.remove("collapsed"),E?.classList.remove("collapsed")):(B.add(s),g.classList.add("collapsed"),E?.classList.add("collapsed")),Si(B)});let x=document.createElement("div");x.className="session-group-body"+(h?" collapsed":"");for(let B of p)x.appendChild(n?Ti(B,n,i):Bi(B,s));y.appendChild(g),y.appendChild(x)}}function Ti(e,t,n){let i=document.createElement("div");i.className="session-item"+(e.name===S&&R===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
- <span>${w(e.name)}</span>${n?"":'<span class="meta">offline</span>'}
15
- <button class="session-edit-btn" data-session="${w(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")||$e(e.name,t)});let a=i.querySelector(".session-edit-btn");return a&&a.addEventListener("click",r=>{r.stopPropagation(),dt(e.name,a,{agentId:t})}),i}function Bi(e,t){let n=document.createElement("div");n.className="session-item"+(e.name===S&&!R?" active":""),n.setAttribute("data-session",e.name),n.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
- <span>${w(e.name)}</span>
17
- <button class="session-edit-btn" data-session="${w(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
- `,n.addEventListener("click",a=>{a.target.closest(".session-edit-btn")||$e(e.name)});let i=n.querySelector(".session-edit-btn");return i&&i.addEventListener("click",a=>{a.stopPropagation(),dt(e.name,i,{sessionPath:t})}),n}function Mi(e){y.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="/"})),y.appendChild(n),vn(t,e.home);let i=e.agents||[];for(let r of i){if(!r.sessions||r.sessions.length===0)continue;let l=r.agentId===R,s=document.createElement("div");s.className="sidebar-section-label machine-label"+(r.online?"":" agent-offline-label")+(!l&&r.online?" clickable":""),s.textContent=r.agentName+(r.online?"":" (offline)"),!l&&r.online&&(s.title="\u6253\u5F00 "+r.agentName,s.addEventListener("click",()=>{window.location.href="/a/"+encodeURIComponent(r.agentId)+"/"})),y.appendChild(s),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",y.appendChild(r);for(let l of a){let s=document.createElement("div");s.className="session-item session-tombstone",s.setAttribute("data-session",l.name),l.agentId&&s.setAttribute("data-agent",l.agentId);let p=l.agentId?l.agentOnline?" (agent)":" (agent \u79BB\u7EBF)":"";s.innerHTML=`<svg viewBox="0 0 24 24" fill="currentColor"><path d="M4 6h16v2H4V6zm0 5h16v2H4v-2zm0 5h16v2H4v-2z"></svg>
19
- <span>${w(l.name)}</span><span class="meta">\u5931\u6548${p}</span>
20
- <button class="session-edit-btn" data-session="${w(l.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>`,s.title="\u5931\u6548\u4F1A\u8BDD\uFF1A\u70B9\u51FB\u7BA1\u7406\uFF08\u91CD\u5EFA/\u91CD\u547D\u540D/\u5220\u9664\uFF09",s.addEventListener("click",()=>{dt(l.name,s,{tombstone:!0,agentId:l.agentId})});let u=s.querySelector(".session-edit-btn");u&&u.addEventListener("click",h=>{h.stopPropagation(),dt(l.name,u,{tombstone:!0,agentId:l.agentId})}),y.appendChild(s)}}}function w(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}async function $e(e,t){if(S===e&&k&&R===(t||null))return;Me.style.display="none",ue.style.display="none",_.style.display="",_.classList.add("terminal-pending"),Ge(),k&&(ot(),k.destroy(),k=null),S=e,R=t||null,window.__tmuxWebScopeAgent=R,window.__tmuxWebCurrentSession=S,ta(e,t);let n=At(e,t);Dn.set(n,Date.now()+Gi);let i=ye.get(n);if(i&&i.state==="working"){i.state="idle",i.doneUntil=void 0,i.unread=!1;let a=y.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&&ft(a,n,i)}for(let a of y.querySelectorAll(".session-item"))a.classList.toggle("active",a.getAttribute("data-session")===e&&(a.getAttribute("data-agent")||null)===R);try{k=await di(_,e,{terminal:Te.terminal,scrollback:Te.scrollback,theme:Te.theme,wsBase:R?"/ws/a/"+encodeURIComponent(R):Te.wsBase||"/ws"}),Sn()}catch(a){console.error("[shell] terminal init failed:",a);let r=a&&typeof a=="object"&&"message"in a?a.message:String(a);_.textContent="Failed to open terminal for "+e+": "+r,_.classList.remove("terminal-pending")}}var et=[],T=null,gn=!1;function Di(e){if(!T||!T.files.length)return null;let t=T.repoRoot;if(!t||!e.startsWith(t))return null;let n=e.slice(t.length+1);for(let i of T.files)if(i.path===n)return i.status;return null}async function $i(e){gn=!0;try{let t=await fetch(P("/api/git/status?path="+encodeURIComponent(e)));t.ok?T=await t.json():T=null}catch{T=null}finally{gn=!1}}function Ai(){if(!T||!T.branch)return"";let{branch:e,linesAdded:t,linesRemoved:n}=T,i=`<div class="sidebar-git"><div class="git-branch-badge">
8
+ `).join("\r")}async function _n(l){let c=Hn(l.clipboardData);if(c){l.preventDefault(),l.stopPropagation();let L=Date.now();if(L-_e<50)return;_e=L,await mt(c);return}let f=l.clipboardData?.getData("text/plain");if(!f)return;l.preventDefault(),l.stopPropagation();let w=Date.now();w-_e<50||(_e=w,i.pasteText(jt(f)))}let xe=0;function Un(l){l.preventDefault(),xe++,Ft(l.dataTransfer)&&e.classList.add("terminal-drag-over")}function Wn(l){l.preventDefault(),l.dataTransfer&&(l.dataTransfer.dropEffect="copy")}function qn(l){l.preventDefault(),xe--,xe<=0&&(xe=0,e.classList.remove("terminal-drag-over"))}async function Jn(l){l.preventDefault(),xe=0,e.classList.remove("terminal-drag-over");let c=Ft(l.dataTransfer);c&&await mt(c)}function Rt(l){!$n||l.key!=="Escape"||we||l.defaultPrevented||l.repeat||l.metaKey||l.ctrlKey||l.altKey||i.isFocused()&&(l.preventDefault(),l.stopPropagation(),he("\x1B"))}e.addEventListener("paste",_n),e.addEventListener("dragenter",Un),e.addEventListener("dragover",Wn),e.addEventListener("dragleave",qn),e.addEventListener("drop",Jn),document.addEventListener("keydown",Rt,!0);function Yn(l){if(l.touches.length!==1){o=null;return}let c=l.touches[0];if(!c)return;O();let f=e.getBoundingClientRect(),w=c.clientX-f.left<f.width*.4?"tui":"history",L=c.clientY-f.top<f.height*.5;o={startX:c.clientX,startY:c.clientY,lastX:c.clientX,lastY:c.clientY,lastT:performance.now(),velocity:0,scrolling:!1,zone:w,tuiUp:L,sent:!1},l.stopPropagation()}function Kn(l){if(!o||l.touches.length!==1)return;let c=l.touches[0];if(!c)return;let f=c.clientY-o.startY,w=c.clientX-o.startX;if(!o.scrolling){if(Math.abs(f)<8||Math.abs(f)<Math.abs(w))return;o.scrolling=!0,_=Date.now()+500}l.preventDefault(),l.stopPropagation();let L=performance.now(),Z=c.clientY-o.lastY;if(o.zone==="tui"){o.sent||(o.sent=!0,he(o.tuiUp?"\x1B[5~":"\x1B[6~"),A(o.tuiUp)),o.lastX=c.clientX,o.lastY=c.clientY,o.lastT=L;return}let oe=L-o.lastT;oe>0&&(o.velocity=Z/oe),Zn(-Z),o.lastX=c.clientX,o.lastY=c.clientY,o.lastT=L}function Vn(l){if(!o)return;let c=o.scrolling,f=o.zone,w=o.tuiUp,L=o.velocity;if(o=null,l.stopPropagation(),f==="tui"){c||(he(w?"\x1B[5~":"\x1B[6~"),A(w),_=Date.now()+500,l.preventDefault());return}if(!c){i.focus();return}_=Date.now()+500,l.preventDefault(),L&&x(L)}function Xn(l){o=null,O(),l.stopPropagation()}function Qn(l){l.pointerType==="touch"&&Date.now()<_&&(l.preventDefault(),l.stopPropagation())}function Zn(l){let c=i.cellHeight(),f=c>0?Math.round(l/c):l>0?1:-1;f===0&&(f=l>0?1:-1),i.scrollLines(f)}e.addEventListener("touchstart",Yn,{passive:!0,capture:!0}),e.addEventListener("touchmove",Kn,{passive:!1,capture:!0}),e.addEventListener("touchend",Vn,{passive:!1,capture:!0}),e.addEventListener("touchcancel",Xn,{passive:!0,capture:!0}),e.addEventListener("pointerup",Qn,!0);function zt(){q()}window.addEventListener("resize",zt),window.visualViewport?.addEventListener("resize",q),window.visualViewport?.addEventListener("scroll",q);let _t=new ResizeObserver(()=>q());_t.observe(e),document.fonts?.ready.then(()=>{q(),setTimeout(q,50),setTimeout(q,200)}),e.addEventListener("focusin",On,!0);async function Gn(){if(document.fonts?.ready)try{await Promise.race([document.fonts.ready,new Promise(l=>setTimeout(l,1e3))])}catch{}}return requestAnimationFrame(()=>{de()&&je(),(async()=>(await Gn(),de()&&re({type:"resize",cols:i.cols,rows:i.rows}),Pt(),q()))()}),{destroy(){if(I=!0,O(),ve(!1),Ce&&clearTimeout(Ce),document.removeEventListener("mousemove",ft,!0),document.removeEventListener("mouseup",ht,!0),s){try{s.close(1e3,"session switch")}catch{}s=void 0}e.innerHTML="",e.classList.remove("terminal-pending"),window.removeEventListener("resize",zt),_t.disconnect(),document.removeEventListener("keydown",Rt,!0)},focus(){i.focus()},sendInput(l){he(l)},toggleCopyMode(){Ht()}}})()}var m={catalog:null,templates:[],bots:[],approvals:[],activeId:null,items:new Map,ws:null,pollTimer:0,renderQueued:!1};function gt(){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 ${gt()}`,...t?.headers||{}}}),i=await n.text(),s=i?JSON.parse(i):null;if(!n.ok)throw new Error(s&&s.error||`HTTP ${n.status}`);return s}function d(e,t,n){let i=document.createElement(e);return t&&(i.className=t),n!==void 0&&(i.textContent=n),i}function li(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 ri(){let e=d("div","bots-section");e.id="bots-section";let t=d("div","bots-head"),n=d("span","bots-title","Bots"),i=d("span","bots-badge");i.hidden=!0,n.appendChild(i);let s=d("span","bots-head-actions"),r=d("button","bots-icon-btn","\u2699");r.title="Bot templates",r.onclick=()=>void Le();let a=d("button","bots-icon-btn","+");a.title="New bot from template",a.onclick=()=>void bi(),s.append(r,a),t.append(n,s);let o=d("div","bots-list");o.id="bots-list",e.append(t,o);let p=document.querySelector(".sidebar"),u=document.querySelector(".sidebar-footer");return p&&p.insertBefore(e,u||null),{list:o,badge:i}}var bt=null,We=null;function qe(){bt&&(bt.textContent="");let e=m.approvals.length;We&&(We.hidden=e===0,We.textContent=String(e));let t=document.getElementById("bv-inbox-count");t&&(t.textContent=e?`(${e})`:""),window.__botsSnapshot=m.bots,window.__refreshSidebar?.()}function di(){let e=d("div","bots-view");e.id="bots-view",e.hidden=!0;let t=d("div","bots-view-head"),n=d("div","bv-title"),i=d("span","bots-dot");i.id="bv-dot";let s=d("span","bv-title-text");s.id="bv-title";let r=d("span","bv-status");r.id="bv-status",n.append(i,s,r);let a=d("div","bv-actions"),o=d("select","bv-mode-select");o.id="bv-mode",o.title="Approval mode for this bot";for(let[x,_]of[["supervised","\u9ED8\u8BA4\uFF1A\u53EA\u8BFB\u81EA\u52A8\uFF0C\u5176\u4F59\u95EE\u6211"],["parent-supervised","Super agent \u76D1\u7BA1\uFF1A\u4EA4\u7ED9\u4E0A\u7EA7 bot"],["full-access","Full access\uFF1A\u5168\u90E8\u653E\u884C"]])o.appendChild(new Option(_,x));o.onchange=()=>{m.activeId&&T(`/api/bots/${m.activeId}/mode`,{method:"POST",body:JSON.stringify({mode:o.value})}).then(()=>ce({kind:"notice",level:"info",text:`Approval mode: ${o.value}`})).catch(x=>ce({kind:"notice",level:"error",text:x instanceof Error?x.message:String(x)}))};let p=d("button","btn","Allow all");p.id="bv-allow-all",p.title="Approve every pending request for this bot",p.onclick=()=>{if(!m.activeId)return;let x=m.approvals.filter(_=>_.botId===m.activeId);Promise.all(x.map(_=>T(`/api/bots/${_.botId}/approve`,{method:"POST",body:JSON.stringify({requestId:_.id,allow:!0})}))).finally(()=>void K(!0))};let u=d("button","btn","Needs you "),h=d("span");h.id="bv-inbox-count",u.appendChild(h),u.onclick=()=>void en();let b=d("button","btn","Resume");b.onclick=()=>void Jt(x=>T(`/api/bots/${x}/resume`,{method:"POST"}).then(()=>K(!0)));let M=d("button","btn danger","Stop");M.onclick=()=>void Jt(x=>T(`/api/bots/${x}/stop`,{method:"POST"}).then(()=>K(!0)));let C=d("button","btn","Delete");C.onclick=()=>{m.activeId&&confirm("Delete this bot and its session?")&&T(`/api/bots/${m.activeId}`,{method:"DELETE"}).then(()=>{yt(),K(!0)})};let y=d("button","btn","\u2715");y.onclick=()=>yt(),a.append(o,p,u,b,M,C,y),t.append(n,a);let g=d("div","bots-messages");g.id="bots-messages";let A=d("div","bots-composer"),F=d("textarea");F.id="bots-input",F.rows=1,F.placeholder="Message the bot\u2026 (Enter to send, Shift+Enter for newline)",F.onkeydown=x=>{x.key==="Enter"&&!x.shiftKey&&(x.preventDefault(),qt())};let O=d("button","btn primary","Send");O.onclick=()=>void qt(),A.append(F,O),e.append(t,g,A),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 Jt(e){m.activeId&&e(m.activeId).catch(t=>ce({kind:"notice",level:"error",text:t instanceof Error?t.message:String(t)}))}function yt(){m.activeId=null;let e=document.getElementById("bots-view");e&&(e.hidden=!0);try{m.ws?.close()}catch{}m.ws=null,qe();let t=document.getElementById("main-placeholder");t&&(t.style.display="")}async function Yt(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 s=document.getElementById("file-editor");s&&(s.style.display="none"),qe(),wt();try{m.ws?.close()}catch{}let r=location.protocol==="https:"?"wss:":"ws:",a=new WebSocket(`${r}//${location.host}/ws/bots/${encodeURIComponent(e)}?token=${encodeURIComponent(gt())}`);m.ws=a,a.onmessage=o=>{try{Xt(JSON.parse(String(o.data)))}catch{}},a.onclose=()=>{m.activeId===e&&setTimeout(()=>{m.activeId===e&&K(!0)},1500)},await K(!0)}function Kt(){return m.bots.find(e=>e.id===m.activeId)||null}function Vt(){let e=Kt();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 s=document.getElementById("bv-mode");s&&e.runtimeMode&&(s.value=e.runtimeMode);let r=document.getElementById("bv-allow-all"),a=m.approvals.filter(o=>o.botId===e.id).length;r&&(r.hidden=a===0,r.textContent=`Allow all (${a})`),i&&(i.style.background=li(e.status))}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&&pe()}function pe(){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 s=d("div","bv-msg bv-user");s.textContent=i.text,e.appendChild(s),n=null}else if(i.kind==="assistant"){let s=d("div","bv-msg bv-assistant");if(i.thinking){let a=d("details","bv-thinking");a.appendChild(d("summary",void 0,"thinking")),a.appendChild(d("div",void 0,i.thinking)),s.appendChild(a)}let r=d("div","bv-text");r.textContent=i.text,s.appendChild(r),e.appendChild(s),n=r}else if(i.kind==="tool")e.appendChild(ci(i)),n=null;else if(i.kind==="approval")e.appendChild(pi(i)),n=null;else if(i.kind==="notice"){let s=d("div",`bv-notice bv-notice-${i.level}`,i.text);e.appendChild(s)}n&&(n.scrollTop=n.scrollHeight),e.scrollTop=e.scrollHeight}function ci(e){let t=d("details","bv-tool");t.open=e.phase!=="end"||!!e.isError;let n=d("summary"),i=d("span","bv-tool-name",e.name);if(n.appendChild(i),e.phase!=="end"&&n.appendChild(d("span","bv-tool-phase",e.phase)),e.isError&&n.appendChild(d("span","bv-tool-error","error")),typeof e.durationMs=="number"&&n.appendChild(d("span","bv-tool-meta",`${Math.round(e.durationMs)}ms`)),t.appendChild(n),e.args!==void 0){let s=d("pre","bv-pre");s.textContent=typeof e.args=="string"?e.args:JSON.stringify(e.args,null,2),t.appendChild(s)}if(e.output){let s=d("pre","bv-pre bv-output");s.textContent=e.output,t.appendChild(s)}return t}function pi(e){let t=d("div","bv-approval"),n=e.approval;if(t.appendChild(d("div","bv-approval-title",n.title)),n.message&&t.appendChild(d("pre","bv-pre",n.message)),e.decided)return t.appendChild(d("div","bv-approval-decided",e.decided==="allowed"?"Allowed":"Denied")),t;let i=d("input","bv-reason");i.placeholder="reason (optional)";let s=d("div","bv-approval-actions"),r=d("button","btn primary","Allow"),a=d("button","btn",n.method==="confirm"&&/^Allow (.+?)\?$/.test(n.title)?`Always allow ${/^Allow (.+?)\?$/.exec(n.title)?.[1]}`:"Always allow");a.hidden=n.method!=="confirm";let o=d("button","btn danger","Deny"),p=async(u,h=!1)=>{try{await T(`/api/bots/${n.botId}/approve`,{method:"POST",body:JSON.stringify({requestId:n.id,allow:u,always:h,reason:i.value||void 0})}),e.decided=u?"allowed":"denied",pe(),K(!0)}catch(b){ce({kind:"notice",level:"error",text:b instanceof Error?b.message:String(b)})}};return r.onclick=()=>void p(!0),a.onclick=()=>void p(!0,!0),o.onclick=()=>void p(!1),s.append(i,r,a,o),t.appendChild(s),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 s=Kt();s&&(s.status=String(e.status||s.status)),Vt(),fi()}else if(t==="message"){let s=e.message;if(!s||String(s.role||"")!=="assistant")return;let r=ui(s),a=mi(s),o=i[i.length-1];o&&o.kind==="assistant"?(o.text=r||o.text,o.thinking=a||o.thinking):i.push({kind:"assistant",text:r,thinking:a}),m.items.set(n,i),pe()}else if(t==="delta"){let s=String(e.kind||""),r=String(e.delta||""),a=i[i.length-1];(!a||a.kind!=="assistant")&&(i.push({kind:"assistant",text:"",thinking:""}),a=i[i.length-1]),a.kind==="assistant"&&(s==="text"?a.text+=r:s==="thinking"&&(a.thinking+=r)),m.items.set(n,i),pe()}else if(t==="tool"){let s=String(e.callId||""),r=i.find(o=>o.kind==="tool"&&o.callId===s),a=String(e.phase||"start");r?(r.phase=a,a==="update"&&e.output&&(r.output=String(e.output)),a==="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:s,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:a}),m.items.set(n,i),pe()}else if(t==="approval"){let s=e.approval;if(!s)return;let r=i;for(let a=r.length-1;a>=0;a--){let o=r[a];if(o.kind==="approval"&&o.approval.id===s.id){o.approval=s,s.state!=="pending"&&(o.decided=s.state==="allowed"?"allowed":"denied"),m.items.set(n,r),pe();return}}r.push({kind:"approval",approval:s}),m.items.set(n,r),pe()}else t==="notice"&&ce({kind:"notice",level:String(e.level||"info"),text:String(e.text||"")})}function ui(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 K(e=!1){try{let[t,n]=await Promise.all([T("/api/bots"),T("/api/bots/approvals")]);if(m.bots=t,m.approvals=n,qe(),Vt(),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"),qe()}catch{}}function hi(e){if(m.activeId){m.items.set(m.activeId,[]);for(let t of e)Xt(t);wt()}}function vi(){let e=d("div","bots-modal");e.id="bots-modal",e.hidden=!0;let t=d("div","bots-modal-card"),n=d("div","bots-modal-head"),i=d("span");i.id="bots-modal-title";let s=d("button","btn","\u2715");s.onclick=()=>Je(),n.append(i,s);let r=d("div","bots-modal-body");r.id="bots-modal-body",t.append(n,r),e.appendChild(t),e.onclick=a=>{a.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=d("div","bv-template-list");for(let p of n){let u=d("div","bv-template-row");u.appendChild(d("span","bv-template-name",p.manifest.name)),u.appendChild(d("span","bv-template-desc",p.manifest.description||""));let h=d("button","btn","Edit");h.onclick=()=>Zt(e,t,p);let b=d("button","btn","Copy");b.title="Duplicate this template",b.onclick=()=>{let y=JSON.parse(JSON.stringify(p.manifest));y.name=`${p.manifest.name} copy`,T("/api/bots/templates",{method:"POST",body:JSON.stringify({manifest:y})}).then(()=>Le()).catch(g=>alert(g instanceof Error?g.message:String(g)))};let M=d("button","btn danger","Delete");M.onclick=()=>{confirm(`Delete template ${p.manifest.name}?`)&&T(`/api/bots/templates/${p.id}`,{method:"DELETE"}).then(()=>Le())};let C=d("span","bv-template-actions");C.append(h,b,M),u.appendChild(C),i.appendChild(u)}n.length===0&&i.appendChild(d("div","bots-empty","No templates yet")),e.appendChild(i);let s=d("div","bv-template-actions"),r=d("button","btn primary","New template");r.onclick=()=>Zt(e,t,null);let a=d("button","btn","Export");a.title="Download templates + library as JSON",a.onclick=()=>{(async()=>{try{let p=await fetch("/api/bots/export",{headers:{Authorization:`Bearer ${gt()}`}});if(!p.ok)throw new Error(`HTTP ${p.status}`);let u=await p.blob(),h=document.createElement("a");h.href=URL.createObjectURL(u),h.download=`tmux-weblink-bots-${new Date().toISOString().slice(0,10)}.json`,h.click(),setTimeout(()=>URL.revokeObjectURL(h.href),2e3)}catch(p){alert(p instanceof Error?p.message:String(p))}})()};let o=d("button","btn","Import");o.title="Restore templates from a JSON bundle",o.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 h=JSON.parse(await u.text()),b=await T("/api/bots/import",{method:"POST",body:JSON.stringify(h)});alert(`Imported ${b.templates} templates, ${b.files} library files (${b.skipped} kept)`),await Le()}catch(h){alert(h instanceof Error?h.message:String(h))}})()},p.click()},s.append(r,a,o),e.appendChild(s)}function kt(e,t,n){let i=d("div","bv-field");i.appendChild(d("label","bv-label",e));let s=d("div","bv-check-grid"),r=[];for(let a of t){let o=d("label","bv-check"),p=document.createElement("input");p.type="checkbox",p.checked=n.includes(a.id),o.append(p,d("span",void 0,a.label)),a.hint&&(o.title=a.hint),s.appendChild(o),r.push({id:a.id,input:p})}return i.appendChild(s),{element:i,get:()=>r.filter(a=>a.input.checked).map(a=>a.id)}}function Zt(e,t,n){e.textContent="";let i=n?JSON.parse(JSON.stringify(n.manifest)):{name:"new-bot",description:""},s=d("input","bv-input");s.value=i.name,s.placeholder="Template name";let r=d("input","bv-input");r.value=i.description||"",r.placeholder="One line description";let a=d("textarea","bv-textarea");a.rows=6,a.value=i.system||"",a.placeholder="System prompt for this bot (written to SYSTEM.md)";let o=kt("Skills",t.skills.map(v=>({id:v.id,label:v.name,hint:v.description})),i.skills||[]),p=kt("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)$/,""))),u=kt("Prompt templates",t.prompts.map(v=>({id:v.id,label:v.name})),i.prompts||[]),h=d("select","bv-input");h.appendChild(new Option("none",""));for(let v of t.mcp)h.appendChild(new Option(v.name,v.id));i.mcp&&(h.value=t.mcp.find(v=>JSON.stringify(v.servers)===JSON.stringify(i.mcp?.mcpServers))?.id||"");let b=d("div","bv-field");b.appendChild(d("label","bv-label","Tools (allow list; deny always blocks)"));let M=d("div","bv-check-grid"),C=[];for(let v of t.tools){let W=d("label","bv-check"),I=document.createElement("input");I.type="checkbox",I.checked=(i.tools?.allow||[]).includes(v.name)||!i.tools?.allow?.length&&["read","grep","find","ls","edit","write","bash"].includes(v.name),W.append(I,d("span",void 0,v.name)),M.appendChild(W),C.push({name:v.name,input:I})}b.appendChild(M);let y=d("input","bv-input");y.value=(i.tools?.deny||[]).join(", "),y.placeholder="Always deny (comma separated), e.g. bash, write";let g=d("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=d("select","bv-input");A.appendChild(new Option("default (Pi settings)",""));for(let v of t.models)A.appendChild(new Option(`${v.provider}/${v.model}`,`${v.provider}
10
+ ${v.model}`));i.model?.provider&&i.model?.id&&(A.value=`${i.model.provider}
11
+ ${i.model.id}`);let F=d("select","bv-input");for(let v of["","off","minimal","low","medium","high","xhigh","max"])F.appendChild(new Option(v||"default",v));i.model?.thinking&&(F.value=i.model.thinking);let O=d("select","bv-input");for(let v of["supervised","auto-accept-edits","full-access"])O.appendChild(new Option(v,v));O.value=i.permissions?.runtimeMode||"supervised";let x=d("select","bv-input");x.appendChild(new Option("ignore project .pi (recommended)","ignore")),x.appendChild(new Option("inherit project .pi (needs trust)","inherit")),x.value=i.projectResources||"ignore";let _=d("label","bv-check"),U=document.createElement("input");U.type="checkbox",U.checked=!!i.orchestrator,_.append(U,d("span",void 0,"Super bot: gets orchestration tools (create/stop/status child bots)"));let H=(v,W)=>{let I=d("div","bv-field");return I.appendChild(d("label","bv-label",v)),I.appendChild(W),I};e.append(H("Name",s),H("Description",r),H("System prompt",a),o.element,p.element,u.element,H("MCP preset",h),b,H("Always deny tools",y),H("Packages",g),H("Model",A),H("Thinking level",F),H("Approval mode",O),H("Project resources",x),_);let ae=d("button","btn primary",n?"Save template":"Create template");ae.onclick=async()=>{let[v,W]=A.value.split(`
12
+ `),I=t.mcp.find($=>$.id===h.value),le={name:s.value.trim()||"bot",description:r.value.trim()||void 0,system:a.value.trim()||void 0,skills:o.get(),extensions:p.get().map($=>($.startsWith("builtin:"),$)),prompts:u.get(),packages:g.value.split(`
13
+ `).map($=>$.trim()).filter(Boolean),mcp:I?{mcpServers:I.servers}:void 0,tools:{allow:C.filter($=>$.input.checked).map($=>$.name),deny:y.value.split(",").map($=>$.trim()).filter(Boolean)},model:v?{provider:v,id:W,thinking:F.value||void 0}:void 0,permissions:{runtimeMode:O.value},projectResources:x.value==="inherit"?"inherit":"ignore",orchestrator:U.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(ae)}async function bi(){return Gt("")}async function Gt(e){let t=Et("New bot"),n=await Qt();if(n.length===0){t.appendChild(d("div","bots-empty","Create a template first (\u2699)."));return}let i=d("select","bv-input");for(let u of n)i.appendChild(new Option(u.manifest.name,u.id));let s=d("input","bv-input");s.placeholder="Title (defaults to template name)";let r=d("input","bv-input");r.placeholder="/path/to/project";let a=e||m.bots[0]?.projectPath||"";r.value=a;let o=d("select","bv-input");o.appendChild(new Option("shared \u2014 run in the project folder","shared")),o.appendChild(new Option("worktree \u2014 isolated git worktree","worktree")),t.append(Ye("Template",i),Ye("Title",s),Ye("Project path",r),Ye("Workspace",o));let p=d("button","btn primary","Create bot");p.onclick=async()=>{try{let u=await T("/api/bots",{method:"POST",body:JSON.stringify({templateId:i.value,title:s.value.trim()||void 0,projectPath:r.value.trim()||void 0,isolation:o.value})});Je(),await K(!0),await Yt(u.id)}catch(u){alert(u instanceof Error?u.message:String(u))}},t.appendChild(p)}function Ye(e,t){let n=d("div","bv-field");return n.appendChild(d("label","bv-label",e)),n.appendChild(t),n}async function en(){let e=Et("Needs you");if(m.approvals=await T("/api/bots/approvals"),m.approvals.length===0){e.appendChild(d("div","bots-empty","Nothing waiting."));return}for(let t of m.approvals){let n=d("div","bv-approval");n.appendChild(d("div","bv-approval-title",`${t.botTitle}: ${t.title}`)),t.message&&n.appendChild(d("pre","bv-pre",t.message));let i=d("input","bv-reason");i.placeholder="reason (optional)";let s=d("div","bv-approval-actions"),r=d("button","btn primary","Allow"),a=d("button","btn danger","Deny"),o=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 K(!0),await en()};r.onclick=()=>void o(!0),a.onclick=()=>void o(!1),s.append(i,r,a),n.appendChild(s),e.appendChild(n)}}function yi(){if(document.getElementById("bots-section"))return;let e=ri();bt=e.list,We=e.badge,di(),window.__openBot=Yt,document.addEventListener("click",t=>{let n=t.target;n&&n.closest(".session-item")&&m.activeId&&yt()},!0),K(!0),m.pollTimer=window.setInterval(()=>{document.hidden||K()},6e3),window.addEventListener("beforeunload",()=>window.clearInterval(m.pollTimer))}var Ie=window.__TMUX_WEB_SHELL__,S=null,B=null,Te=typeof window.__TMUX_WEB_SCOPE__?.agentId=="string"?window.__TMUX_WEB_SCOPE__.agentId:null,R=Te;window.__tmuxWebScopeAgent=Te;var Ct="sessions",te="",Ke="",Ve="",tn="";function N(e){return R?"/a/"+encodeURIComponent(R)+e:e}var E=document.getElementById("sidebar-content"),ue=document.getElementById("main-placeholder"),J=document.getElementById("terminal-container"),Be=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"),nn=document.getElementById("fe-new-name"),Ci=document.getElementById("fe-new-btn"),xt=document.getElementById("settings-backdrop"),sn=document.getElementById("settings-popover"),an=document.querySelector(".sidebar"),on="tmux-web-force-narrow";function Xe(){try{return localStorage.getItem(on)==="1"}catch{return!1}}function ln(){document.documentElement.classList.toggle("force-narrow",Xe()),Xe()&&rn()&&Qe()}function rn(){return Xe()?!0:window.matchMedia("(max-width: 640px)").matches}function Qe(){rn()&&an.classList.add("collapsed")}function dn(){an.classList.remove("collapsed")}document.getElementById("mode-sessions").addEventListener("click",()=>{dn(),cn("sessions")}),document.getElementById("mode-files").addEventListener("click",()=>{dn(),cn("files")});function cn(e){Ct=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"?(St="",ne()):Hi()}var St="";async function ne(){if(Ct!=="sessions")return;try{let t=await(await fetch("/api/sidebar/sessions")).json(),n=(window.__botsSnapshot||[]).map(s=>[s.id,s.title,s.status,s.projectPath]),i=JSON.stringify({recent:t.recent,agents:t.agents,tombstones:t.tombstones,bots:n});if(i===St)return;St=i,Bi(t)}catch{E.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")}),Dt()}var pn="tmux-web-sidebar-group-collapsed";function un(){try{return new Set(JSON.parse(localStorage.getItem(pn)||"[]"))}catch{return new Set}}function xi(e){try{localStorage.setItem(pn,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,s=i.split("/").filter(Boolean);if(s.length===0)return e;for(let r=1;r<=s.length;r++){let a=s.slice(-r).join("/");if(!t.some(o=>!o||o===e?!1:(n&&(o===n||o.startsWith(n+"/"))?"~"+o.slice(n.length):o).split("/").filter(Boolean).slice(-r).join("/")===a))return a}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>${k(e.title)}</span><span class="bot-status-dot" style="background:${n}"></span>`,t.addEventListener("click",i=>{i.stopPropagation(),window.__openBot?.(e.id)}),t}function mn(e,t,n,i=!0){let s=new Map;for(let u of e){let h=u.path||"";s.has(h)||s.set(h,[]),s.get(h).push(u)}let r=n?[]:window.__botsSnapshot||[],a=new Map;for(let u of r)s.has(u.projectPath)||s.set(u.projectPath,[]),a.has(u.projectPath)||a.set(u.projectPath,[]),a.get(u.projectPath).push(u);let o=[...s.keys()],p=un();for(let[u,h]of s){let b=Si(u,o,t),M=p.has(u),C=document.createElement("div");if(C.className="session-group-header"+(M?" collapsed":""),C.title=u||"No working directory",C.innerHTML=`<span class="sg-folder">&#128193;</span><span class="sg-label">${k(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(),It(u)}),C.appendChild(g)}C.addEventListener("click",()=>{let g=un(),A=C.nextElementSibling;g.has(u)?(g.delete(u),C.classList.remove("collapsed"),A?.classList.remove("collapsed")):(g.add(u),C.classList.add("collapsed"),A?.classList.add("collapsed")),xi(g)});let y=document.createElement("div");y.className="session-group-body"+(M?" collapsed":"");for(let g of h)y.appendChild(n?Ii(g,n,i):Ti(g));for(let g of a.get(u)||[])y.appendChild(Li(g));E.appendChild(C),E.appendChild(y)}}function Ii(e,t,n){let i=document.createElement("div");i.className="session-item"+(e.name===B&&R===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
+ <span>${k(e.name)}</span>${n?"":'<span class="meta">offline</span>'}
15
+ <button class="session-edit-btn" data-session="${k(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 s=i.querySelector(".session-edit-btn");return s&&s.addEventListener("click",r=>{r.stopPropagation(),lt(e.name,s,{agentId:t})}),i}function Ti(e){let t=document.createElement("div");t.className="session-item"+(e.name===B&&!R?" 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
+ <span>${k(e.name)}</span>
17
+ <button class="session-edit-btn" data-session="${k(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")||Ae(e.name)});let n=t.querySelector(".session-edit-btn");return n&&n.addEventListener("click",i=>{i.stopPropagation(),lt(e.name,n)}),t}function Bi(e){E.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="/"})),E.appendChild(n),mn(t,e.home);let i=e.agents||[];for(let r of i){if(!r.sessions||r.sessions.length===0)continue;let a=r.agentId===R,o=document.createElement("div");o.className="sidebar-section-label machine-label"+(r.online?"":" agent-offline-label")+(!a&&r.online?" clickable":""),o.textContent=r.agentName+(r.online?"":" (offline)"),!a&&r.online&&(o.title="\u6253\u5F00 "+r.agentName,o.addEventListener("click",()=>{window.location.href="/a/"+encodeURIComponent(r.agentId)+"/"})),E.appendChild(o),mn(r.sessions,e.home,r.agentId,r.online)}let s=e.tombstones||[];if(s.length>0){let r=document.createElement("div");r.className="sidebar-section-label tombstone-label",r.textContent="\u5931\u6548\u4F1A\u8BDD",E.appendChild(r);for(let a of s){let o=document.createElement("div");o.className="session-item session-tombstone",o.setAttribute("data-session",a.name),a.agentId&&o.setAttribute("data-agent",a.agentId);let p=a.agentId?a.agentOnline?" (agent)":" (agent \u79BB\u7EBF)":"";o.innerHTML=`<svg viewBox="0 0 24 24" fill="currentColor"><path d="M4 6h16v2H4V6zm0 5h16v2H4v-2zm0 5h16v2H4v-2z"></svg>
19
+ <span>${k(a.name)}</span><span class="meta">\u5931\u6548${p}</span>
20
+ <button class="session-edit-btn" data-session="${k(a.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>`,o.title="\u5931\u6548\u4F1A\u8BDD\uFF1A\u70B9\u51FB\u7BA1\u7406\uFF08\u91CD\u5EFA/\u91CD\u547D\u540D/\u5220\u9664\uFF09",o.addEventListener("click",()=>{lt(a.name,o,{tombstone:!0,agentId:a.agentId})});let u=o.querySelector(".session-edit-btn");u&&u.addEventListener("click",h=>{h.stopPropagation(),lt(a.name,u,{tombstone:!0,agentId:a.agentId})}),E.appendChild(o)}}}function k(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}async function Ae(e,t){if(B===e&&S&&R===(t||null))return;Be.style.display="none",ue.style.display="none",J.style.display="",J.classList.add("terminal-pending"),Qe(),S&&(at(),S.destroy(),S=null),B=e,R=t||null,window.__tmuxWebScopeAgent=R,window.__tmuxWebCurrentSession=B,es(e,t);let n=At(e,t);Tn.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 s=E.querySelector(t?'.session-item[data-agent="'+CSS.escape(t)+'"][data-session="'+CSS.escape(e)+'"]':'.session-item[data-session="'+CSS.escape(e)+'"]:not([data-agent])');s&&ut(s,n,i)}for(let s of E.querySelectorAll(".session-item"))s.classList.toggle("active",s.getAttribute("data-session")===e&&(s.getAttribute("data-agent")||null)===R);try{S=await oi(J,e,{terminal:Ie.terminal,scrollback:Ie.scrollback,theme:Ie.theme,wsBase:R?"/ws/a/"+encodeURIComponent(R):Ie.wsBase||"/ws"}),Cn()}catch(s){console.error("[shell] terminal init failed:",s);let r=s&&typeof s=="object"&&"message"in s?s.message:String(s);J.textContent="Failed to open terminal for "+e+": "+r,J.classList.remove("terminal-pending")}}var Ze=[],D=null,fn=!1;function Mi(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 Ai(e){fn=!0;try{let t=await fetch(N("/api/git/status?path="+encodeURIComponent(e)));t.ok?D=await t.json():D=null}catch{D=null}finally{fn=!1}}function Di(){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
- ${w(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>"}y.addEventListener("click",e=>{e.target.closest(".sidebar-git")&&ve&&T&&(e.stopPropagation(),kn())});var Ae=document.getElementById("header-git"),bn=document.getElementById("git-diff-view"),yn=document.getElementById("gd-path"),tt=document.getElementById("gd-status"),nt=document.getElementById("gd-content"),Pi=document.getElementById("gd-back"),ve=null;function Pe(e){if(!e||!e.branch){Ae.style.display="none",ve=null;return}ve=e.repoRoot;let{branch:t,linesAdded:n,linesRemoved:i}=e,a=`<span class="branch">${w(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=>{ve&&T&&(e.stopPropagation(),kn())});var j=document.getElementById("git-popover"),it=document.getElementById("git-popover-backdrop");function Tt(){let e=Ae.getBoundingClientRect();j.style.top=e.bottom+4+"px",j.style.left=Math.max(8,Math.min(e.left,window.innerWidth-400))+"px"}function wn(){let e=ve,t=document.getElementById("git-popover-browse");t&&t.addEventListener("click",()=>{if(st(),e){Lt="files",document.querySelectorAll(".mode-btn").forEach(i=>i.classList.remove("active"));let n=document.getElementById("mode-files");n&&n.classList.add("active"),ne(e)}})}var En="";function kn(){if(!T)return;let e=T.files||[];if(!e.length)j.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,l="";switch(i.status){case"M":l='<span class="git-file-status M">M</span>';break;case"A":l='<span class="git-file-status A">A</span>';break;case"D":l='<span class="git-file-status D">D</span>';break;case"?":l='<span class="git-file-status ?">?</span>';break;case"R":l='<span class="git-file-status R">R</span>';break}t+=`<div class="git-popover-item" data-idx="${n}">
24
- ${l}<span class="file-path">${w(i.path)}</span>
25
- <span class="file-add">${a>0?"+"+a:""}</span>
22
+ ${k(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>"}E.addEventListener("click",e=>{e.target.closest(".sidebar-git")&&ge&&D&&(e.stopPropagation(),yn())});var De=document.getElementById("header-git"),hn=document.getElementById("git-diff-view"),vn=document.getElementById("gd-path"),Ge=document.getElementById("gd-status"),et=document.getElementById("gd-content"),$i=document.getElementById("gd-back"),ge=null;function $e(e){if(!e||!e.branch){De.style.display="none",ge=null;return}ge=e.repoRoot;let{branch:t,linesAdded:n,linesRemoved:i}=e,s=`<span class="branch">${k(t)}</span>`;(n>0||i>0)&&(s+=`<span class="sep">\xB7</span>+<span class="diff-add">${n}</span> <span class="diff-del">-${i}</span>`),De.innerHTML=s,De.style.display="block"}De.addEventListener("click",e=>{ge&&D&&(e.stopPropagation(),yn())});var z=document.getElementById("git-popover"),tt=document.getElementById("git-popover-backdrop");function Lt(){let e=De.getBoundingClientRect();z.style.top=e.bottom+4+"px",z.style.left=Math.max(8,Math.min(e.left,window.innerWidth-400))+"px"}function gn(){let e=ge,t=document.getElementById("git-popover-browse");t&&t.addEventListener("click",()=>{if(it(),e){Ct="files",document.querySelectorAll(".mode-btn").forEach(i=>i.classList.remove("active"));let n=document.getElementById("mode-files");n&&n.classList.add("active"),ie(e)}})}var bn="";function yn(){if(!D)return;let e=D.files||[];if(!e.length)z.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],s=i.additions||0,r=i.deletions||0,a="";switch(i.status){case"M":a='<span class="git-file-status M">M</span>';break;case"A":a='<span class="git-file-status A">A</span>';break;case"D":a='<span class="git-file-status D">D</span>';break;case"?":a='<span class="git-file-status ?">?</span>';break;case"R":a='<span class="git-file-status R">R</span>';break}t+=`<div class="git-popover-item" data-idx="${n}">
24
+ ${a}<span class="file-path">${k(i.path)}</span>
25
+ <span class="file-add">${s>0?"+"+s:""}</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>',En=t,j.innerHTML=t,j.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",()=>xn(a.path)))})}Tt(),j.classList.add("open"),it.classList.add("open"),wn()}function Ni(){return window.innerWidth>=1024}function Cn(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>',bn=t,z.innerHTML=t,z.querySelectorAll(".git-popover-item").forEach(n=>{let i=parseInt(n.dataset.idx||"0",10),s=e[i];!s||s.status==="D"||(n.classList.add("clickable"),n.style.cursor="pointer",n.addEventListener("click",()=>En(s.path)))})}Lt(),z.classList.add("open"),tt.classList.add("open"),gn()}function Pi(){return window.innerWidth>=1024}function wn(e,t){let n=(e+(t&&e?`
28
28
  `:"")+t).split(`
29
- `),i="",a=0,r=0;for(let l of n){let s=l;if(s.startsWith("@@")){let p=s.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">${w(s)}</span></div>`;continue}if(s.startsWith("diff --git")||s.startsWith("index ")||s.startsWith("--- ")||s.startsWith("+++ ")||s.startsWith("new file")||s.startsWith("deleted file")){s.startsWith("diff --git")&&(i+=`<div class="diff-line header"><span class="ln-body">${w(s)}</span></div>`);continue}if(s.startsWith("+"))r++,i+=`<div class="diff-line add"><span class="ln-no">${r}</span><span class="ln-body">${w(s)}</span></div>`;else if(s.startsWith("-"))a++,i+=`<div class="diff-line del"><span class="ln-no">${a}</span><span class="ln-body">${w(s)}</span></div>`;else if(s.startsWith("\\"))i+=`<div class="diff-line"><span class="ln-body">${w(s)}</span></div>`;else{if(!s&&!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">${w(s)}</span></div>`}}return{html:i,lineCount:n.length}}var at=null;async function xn(e){let t=ve;if(t)if(st(),Ni()){_.style.display="none",k&&(ot(),k.destroy(),k=null,at=S,S=null),Pe(null),Me.style.display="none",ue.style.display="none",bn.style.display="flex",yn.textContent=e,tt.textContent="Loading\u2026",nt.innerHTML="";try{let n=await fetch(P("/api/git/diff?path="+encodeURIComponent(t)+"&file="+encodeURIComponent(e)));if(!n.ok)throw new Error(await n.text());let i=await n.json();Ri(e,i.diff,i.stagedDiff)}catch(n){let i=n instanceof Error?n.message:String(n);tt.textContent="Error",nt.innerHTML=`<div class="diff-empty" style="padding:24px;text-align:center;color:var(--panel-muted)">Error: ${w(i)}</div>`}}else{j.innerHTML=`<div class="git-diff-view"><div class="diff-header">
29
+ `),i="",s=0,r=0;for(let a of n){let o=a;if(o.startsWith("@@")){let p=o.match(/@@\s+-(\d+)[^+]*\+(\d+)/);p&&(s=parseInt(p[1],10)-1,r=parseInt(p[2],10)-1),i+=`<div class="diff-line hunk"><span class="ln-body">${k(o)}</span></div>`;continue}if(o.startsWith("diff --git")||o.startsWith("index ")||o.startsWith("--- ")||o.startsWith("+++ ")||o.startsWith("new file")||o.startsWith("deleted file")){o.startsWith("diff --git")&&(i+=`<div class="diff-line header"><span class="ln-body">${k(o)}</span></div>`);continue}if(o.startsWith("+"))r++,i+=`<div class="diff-line add"><span class="ln-no">${r}</span><span class="ln-body">${k(o)}</span></div>`;else if(o.startsWith("-"))s++,i+=`<div class="diff-line del"><span class="ln-no">${s}</span><span class="ln-body">${k(o)}</span></div>`;else if(o.startsWith("\\"))i+=`<div class="diff-line"><span class="ln-body">${k(o)}</span></div>`;else{if(!o&&!s&&!r)continue;s++,r++,i+=`<div class="diff-line"><span class="ln-no">${s}</span><span class="ln-no" style="margin-right:12px">${r}</span><span class="ln-body">${k(o)}</span></div>`}}return{html:i,lineCount:n.length}}var nt=null;async function En(e){let t=ge;if(t)if(it(),Pi()){J.style.display="none",S&&(at(),S.destroy(),S=null,nt=B,B=null),$e(null),Be.style.display="none",ue.style.display="none",hn.style.display="flex",vn.textContent=e,Ge.textContent="Loading\u2026",et.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();Fi(e,i.diff,i.stagedDiff)}catch(n){let i=n instanceof Error?n.message:String(n);Ge.textContent="Error",et.innerHTML=`<div class="diff-empty" style="padding:24px;text-align:center;color:var(--panel-muted)">Error: ${k(i)}</div>`}}else{z.innerHTML=`<div class="git-diff-view"><div class="diff-header">
30
30
  <button class="diff-back">\u2190 Back</button>
31
- <span class="diff-filename">${w(e)}</span>
31
+ <span class="diff-filename">${k(e)}</span>
32
32
  <span class="diff-loading">Loading\u2026</span>
33
- </div></div>`,Tt(),j.classList.add("open"),it.classList.add("open");try{let n=await fetch(P("/api/git/diff?path="+encodeURIComponent(t)+"&file="+encodeURIComponent(e)));if(!n.ok)throw new Error(await n.text());let i=await n.json();Fi(e,i.diff,i.stagedDiff)}catch(n){let i=n instanceof Error?n.message:String(n);j.innerHTML=`<div class="git-diff-view"><div class="diff-header">
33
+ </div></div>`,Lt(),z.classList.add("open"),tt.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();Ni(e,i.diff,i.stagedDiff)}catch(n){let i=n instanceof Error?n.message:String(n);z.innerHTML=`<div class="git-diff-view"><div class="diff-header">
34
34
  <button class="diff-back">\u2190 Back</button>
35
- <span class="diff-filename">${w(e)}</span>
36
- </div><div class="diff-empty">Error loading diff: ${w(i)}</div></div>`}}}function Fi(e,t,n){if(!t&&!n){j.innerHTML=`<div class="git-diff-view"><div class="diff-header">
35
+ <span class="diff-filename">${k(e)}</span>
36
+ </div><div class="diff-empty">Error loading diff: ${k(i)}</div></div>`}}}function Ni(e,t,n){if(!t&&!n){z.innerHTML=`<div class="git-diff-view"><div class="diff-header">
37
37
  <button class="diff-back">\u2190 Back</button>
38
- <span class="diff-filename">${w(e)}</span>
39
- </div><div class="diff-empty">No diff content available</div></div>`;return}let{html:i,lineCount:a}=Cn(t,n);j.innerHTML=`<div class="git-diff-view"><div class="diff-header">
38
+ <span class="diff-filename">${k(e)}</span>
39
+ </div><div class="diff-empty">No diff content available</div></div>`;return}let{html:i,lineCount:s}=wn(t,n);z.innerHTML=`<div class="git-diff-view"><div class="diff-header">
40
40
  <button class="diff-back">\u2190 Back</button>
41
- <span class="diff-filename">${w(e)}</span>
42
- <span class="diff-filesize">${a} lines</span>
43
- </div><div class="diff-content">${i}</div></div>`,j.querySelector(".diff-back")?.addEventListener("click",()=>{j.innerHTML=En,Tt(),T&&j.querySelectorAll(".git-popover-item").forEach(r=>{let l=parseInt(r.dataset.idx||"0",10),s=T.files[l];!s||s.status==="D"||(r.style.cursor="pointer",r.addEventListener("click",()=>xn(s.path)))}),wn()})}function Ri(e,t,n){if(!t&&!n){tt.textContent="No diff",nt.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}=Cn(t,n);yn.textContent=e,tt.textContent=a+" lines",nt.innerHTML=i}function ji(){bn.style.display="none",at?(_.style.display="",_.classList.add("terminal-pending"),$e(at),at=null):S?(_.style.display="",_.classList.add("terminal-pending"),Sn()):ue.style.display="flex"}Pi.addEventListener("click",ji);function st(){j.classList.remove("open"),it.classList.remove("open")}it.addEventListener("click",st),document.addEventListener("keydown",e=>{e.key==="Escape"&&(st(),mt())});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();T=i,Pe(i);return}}}catch{}T=null,Pe(null)}var lt=null;function Sn(){ot(),S&&(Ln(S),lt=setInterval(()=>{S&&Ln(S)},3e4))}function ot(){lt&&(clearInterval(lt),lt=null)}async function Bt(e){let t=e;if(t.startsWith("~"))try{let n=await(await fetch(P("/api/fs/list?path="+encodeURIComponent(t)))).json();typeof n.path=="string"&&n.path&&(t=n.path)}catch{}t=t.replace(/\/+$/,"")||"/",xt(t)}function In(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 Oi(){if(et=Te.fsRoots||[],et.length===0){if(S){Hi(S);return}ne("");return}y.innerHTML="";for(let e of et){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> ${w(e)}`,t.addEventListener("click",()=>ne(e)),In(t,e),y.appendChild(t)}}async function Hi(e){y.innerHTML='<div class="file-tree-empty">Loading...</div>';try{let t=await(await fetch(P("/api/fs/session-path?session="+encodeURIComponent(e)))).json();t.path?ne(t.path):y.innerHTML='<div class="file-tree-info">Could not determine session directory.</div>'}catch{y.innerHTML='<div class="file-tree-error">Failed to get session directory</div>'}}async function ne(e){ee=e,y.innerHTML='<div class="file-tree-empty">Loading...</div>';let t=$i(e);try{let n=await(await fetch(P("/api/fs/list?path="+encodeURIComponent(e)))).json(),i=typeof n.path=="string"&&n.path?n.path:e;if(i&&(ee=i),await t,y.innerHTML="",i){let l=document.createElement("div");l.className="file-tree-item file-tree-create-bot",l.innerHTML='<span class="file-tree-bot-plus">+</span> Create bot in this folder',l.title=`Create bot in ${i}`,l.addEventListener("click",()=>void Bt(i)),y.appendChild(l)}Pe(T),y.innerHTML+=Ai();let a=zi(i||e);if(a&&!et.some(l=>i===l)){let l=document.createElement("div");l.className="file-tree-item",l.innerHTML="..",l.addEventListener("click",()=>ne(a)),y.appendChild(l)}if(n.dirs)for(let l of n.dirs){let s=l.split("/").pop()||l.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> ${w(s)}`,p.addEventListener("click",()=>ne(l)),In(p,l),y.appendChild(p)}else y.innerHTML="";let r=n.files||[];for(let l of r){let s=l.split("/").pop()||l.split("\\").pop(),p=Di(l),u="",h="";if(p)switch(p){case"M":u="git-mod",h='<span class="git-file-status M">M</span>';break;case"A":u="git-add",h='<span class="git-file-status A">A</span>';break;case"D":u="git-del",h='<span class="git-file-status D">D</span>';break;case"?":u="git-untracked",h='<span class="git-file-status ?">?</span>';break;case"R":u="git-mod",h='<span class="git-file-status R">R</span>';break}let g=document.createElement("div");g.className="file-tree-item file"+(u?" "+u:""),g.innerHTML=`<span class="file-icon">\u{1F4C4}</span> ${h}${w(s)}`,g.addEventListener("click",()=>Ui(l)),y.appendChild(g)}}catch{y.innerHTML='<div class="file-tree-error">Failed to load directory</div>'}}function zi(e){let t=e.lastIndexOf("/");return t<=0?null:e.substring(0,t)}async function Ui(e){Xe=e,_.style.display="none",k&&(ot(),k.destroy(),k=null,S=null),Pe(null),Ge(),ue.style.display="none",Me.style.display="flex",ki.textContent=e,J.textContent="Loading...",me.style.display="none";try{let t=await fetch(P("/api/file?path="+encodeURIComponent(e)));if(!t.ok){let i=await t.json();J.textContent=i.error||"Failed to load",De.value="";return}let n=await t.json();De.value=n.content,Qe=n.content,sn=n.content,J.textContent=n.size+" bytes",me.style.display=""}catch{J.textContent="Failed to load",De.value=""}}De.addEventListener("input",()=>{Qe=De.value}),me.addEventListener("click",async()=>{me.textContent="Saving...",me.disabled=!0;try{let e=await fetch(P("/api/file"),{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:Xe,content:Qe})});if(!e.ok){let t=await e.json();J.textContent=t.error||"Save failed";return}sn=Qe,J.textContent="Saved"}catch{J.textContent="Save failed"}finally{me.disabled=!1,me.textContent="Save"}}),Ci.addEventListener("click",async()=>{if(confirm("Delete "+Xe+"?"))try{let e=await fetch(P("/api/file/delete"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:Xe})});if(!e.ok){let t=await e.json();J.textContent=t.error||"Delete failed";return}Me.style.display="none",ue.style.display="flex",ee&&ne(ee)}catch{J.textContent="Delete failed"}}),xi.addEventListener("click",()=>{Me.style.display="none",ue.style.display="flex",ee&&ne(ee)}),Li.addEventListener("click",async()=>{let e=ln.value.trim();if(!e)return;let t=ee+"/"+e;try{let n=await fetch(P("/api/file/touch"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:t})});if(!n.ok){let i=await n.json();J.textContent=i.error||"Create failed";return}ln.value="",ee&&ne(ee)}catch{J.textContent="Create failed"}});var rt=document.getElementById("force-narrow-toggle");rt&&(rt.checked=Ze(),rt.addEventListener("change",()=>{try{localStorage.setItem(dn,rt.checked?"1":"0")}catch{}cn(),te()})),cn(),document.getElementById("mode-settings").addEventListener("click",()=>{let e=on.classList.toggle("open");St.classList.toggle("open",e)}),St.addEventListener("click",()=>{on.classList.remove("open"),St.classList.remove("open")});var q="",Q=!1,Y,Ne=document.createElement("div");Ne.className="session-popover-backdrop",document.body.appendChild(Ne);var K=document.createElement("div");K.id="session-popover",K.className="session-popover",K.style.display="none",K.innerHTML=`<div class="sp-field">
41
+ <span class="diff-filename">${k(e)}</span>
42
+ <span class="diff-filesize">${s} lines</span>
43
+ </div><div class="diff-content">${i}</div></div>`,z.querySelector(".diff-back")?.addEventListener("click",()=>{z.innerHTML=bn,Lt(),D&&z.querySelectorAll(".git-popover-item").forEach(r=>{let a=parseInt(r.dataset.idx||"0",10),o=D.files[a];!o||o.status==="D"||(r.style.cursor="pointer",r.addEventListener("click",()=>En(o.path)))}),gn()})}function Fi(e,t,n){if(!t&&!n){Ge.textContent="No diff",et.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:s}=wn(t,n);vn.textContent=e,Ge.textContent=s+" lines",et.innerHTML=i}function Oi(){hn.style.display="none",nt?(J.style.display="",J.classList.add("terminal-pending"),Ae(nt),nt=null):B?(J.style.display="",J.classList.add("terminal-pending"),Cn()):ue.style.display="flex"}$i.addEventListener("click",Oi);function it(){z.classList.remove("open"),tt.classList.remove("open")}tt.addEventListener("click",it),document.addEventListener("keydown",e=>{e.key==="Escape"&&(it(),pt())});async function kn(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 st=null;function Cn(){at(),B&&(kn(B),st=setInterval(()=>{B&&kn(B)},3e4))}function at(){st&&(clearInterval(st),st=null)}async function It(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 xn(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(),It(t)}),e.appendChild(n)}function Hi(){if(Ze=Ie.fsRoots||[],Ze.length===0){if(B){ji(B);return}ie("");return}E.innerHTML="";for(let e of Ze){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> ${k(e)}`,t.addEventListener("click",()=>ie(e)),xn(t,e),E.appendChild(t)}}async function ji(e){E.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?ie(t.path):E.innerHTML='<div class="file-tree-info">Could not determine session directory.</div>'}catch{E.innerHTML='<div class="file-tree-error">Failed to get session directory</div>'}}async function ie(e){te=e,E.innerHTML='<div class="file-tree-empty">Loading...</div>';let t=Ai(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&&(te=i),await t,E.innerHTML="",i){let a=document.createElement("div");a.className="file-tree-item file-tree-create-bot",a.innerHTML='<span class="file-tree-bot-plus">+</span> Create bot in this folder',a.title=`Create bot in ${i}`,a.addEventListener("click",()=>void It(i)),E.appendChild(a)}$e(D),E.innerHTML+=Di();let s=Ri(i||e);if(s&&!Ze.some(a=>i===a)){let a=document.createElement("div");a.className="file-tree-item",a.innerHTML="..",a.addEventListener("click",()=>ie(s)),E.appendChild(a)}if(n.dirs)for(let a of n.dirs){let o=a.split("/").pop()||a.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> ${k(o)}`,p.addEventListener("click",()=>ie(a)),xn(p,a),E.appendChild(p)}else E.innerHTML="";let r=n.files||[];for(let a of r){let o=a.split("/").pop()||a.split("\\").pop(),p=Mi(a),u="",h="";if(p)switch(p){case"M":u="git-mod",h='<span class="git-file-status M">M</span>';break;case"A":u="git-add",h='<span class="git-file-status A">A</span>';break;case"D":u="git-del",h='<span class="git-file-status D">D</span>';break;case"?":u="git-untracked",h='<span class="git-file-status ?">?</span>';break;case"R":u="git-mod",h='<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> ${h}${k(o)}`,b.addEventListener("click",()=>zi(a)),E.appendChild(b)}}catch{E.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 zi(e){Ke=e,J.style.display="none",S&&(at(),S.destroy(),S=null,B=null),$e(null),Qe(),ue.style.display="none",Be.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,tn=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:Ke,content:Ve})});if(!e.ok){let t=await e.json();V.textContent=t.error||"Save failed";return}tn=Ve,V.textContent="Saved"}catch{V.textContent="Save failed"}finally{me.disabled=!1,me.textContent="Save"}}),Ei.addEventListener("click",async()=>{if(confirm("Delete "+Ke+"?"))try{let e=await fetch(N("/api/file/delete"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:Ke})});if(!e.ok){let t=await e.json();V.textContent=t.error||"Delete failed";return}Be.style.display="none",ue.style.display="flex",te&&ie(te)}catch{V.textContent="Delete failed"}}),ki.addEventListener("click",()=>{Be.style.display="none",ue.style.display="flex",te&&ie(te)}),Ci.addEventListener("click",async()=>{let e=nn.value.trim();if(!e)return;let t=te+"/"+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}nn.value="",te&&ie(te)}catch{V.textContent="Create failed"}});var ot=document.getElementById("force-narrow-toggle");ot&&(ot.checked=Xe(),ot.addEventListener("change",()=>{try{localStorage.setItem(on,ot.checked?"1":"0")}catch{}ln(),ne()})),ln(),document.getElementById("mode-settings").addEventListener("click",()=>{let e=sn.classList.toggle("open");xt.classList.toggle("open",e)}),xt.addEventListener("click",()=>{sn.classList.remove("open"),xt.classList.remove("open")});var Y="",se=!1,X,Pe=document.createElement("div");Pe.className="session-popover-backdrop",document.body.appendChild(Pe);var Q=document.createElement("div");Q.id="session-popover",Q.className="session-popover",Q.style.display="none",Q.innerHTML=`<div class="sp-field">
44
44
  <label>Rename session</label>
45
45
  <input type="text" id="sp-name" />
46
46
  </div>
@@ -50,6 +50,5 @@ ${i.model.id}`);let D=d("select","bv-input");for(let v of["","off","minimal","lo
50
50
  </div>
51
51
  <hr class="sp-divider" />
52
52
  <button class="btn primary" id="sp-rebuild" style="display:none">\u91CD\u5EFA\u540C\u540D\u540C\u8DEF\u5F84 session</button>
53
- <button class="btn" id="sp-create-bot" style="display:none">\uFF0B \u5728\u6B64\u76EE\u5F55\u521B\u5EFA Bot</button>
54
- <button class="btn danger" id="sp-delete">Delete session</button>`,document.body.appendChild(K);function Wi(e){let t=e.getBoundingClientRect(),n=window.innerHeight,i=K.offsetHeight||240,a=t.bottom+4;a+i>n-8&&(a=Math.max(8,t.top-i-4)),K.style.top=a+"px",K.style.left=Math.max(8,Math.min(t.left,window.innerWidth-240))+"px"}var ge="";function dt(e,t,n){q=e,Q=!!n?.tombstone,Y=n?.agentId,ge=n?.sessionPath||"";let i=document.getElementById("sp-name");i.value=e;let a=K.querySelector(".sp-field label");a.textContent=Q?"\u91CD\u547D\u540D (\u4EC5\u8BB0\u5F55\uFF0C\u4E0D\u91CD\u5EFA)":"Rename session";let r=document.getElementById("sp-rebuild");r.style.display=Q?"":"none";let l=document.getElementById("sp-delete");l.textContent=Q?"\u5220\u9664\u5931\u6548\u8BB0\u5F55 (\u5893\u7891\u6D88\u5931)":"Delete session";let s=document.getElementById("sp-save");s.textContent=Q?"\u91CD\u547D\u540D":"Save";let p=document.getElementById("sp-create-bot");p.style.display=!Q&&!Y&&ge?"":"none",p.title=ge?`Create bot in ${ge}`:"",Ne.classList.add("open"),K.style.display="block",Wi(t),setTimeout(()=>i.focus(),50)}function se(){Ne.classList.remove("open"),K.style.display="none"}Ne.addEventListener("click",se),document.getElementById("sp-create-bot").addEventListener("click",()=>{if(!ge)return;let e=ge;se(),Bt(e)}),document.getElementById("sp-save").addEventListener("click",async()=>{let e=document.getElementById("sp-name").value.trim();if(!e||e===q){se();return}try{let t=Q?{oldName:q,newName:e,agentId:Y}:{oldName:q,newName:e,...Y?{agentId:Y}:{}};if(!(await fetch(P(Q?"/api/sessions/rename-tombstone":"/api/sessions/rename"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})).ok)return;se(),te(),!Q&&S===q&&(Y??null)===R&&$e(e,Y)}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(P("/api/sessions/rebuild"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:q,agentId:Y})});if(!e.ok){let t=await e.json();alert(t.error||"\u91CD\u5EFA\u5931\u8D25");return}se(),te()}catch{}}),document.getElementById("sp-delete").addEventListener("click",async()=>{if(Q){if(!confirm('\u5220\u9664\u5931\u6548\u8BB0\u5F55 "'+q+'"\uFF1F'))return;try{if(!(await fetch(P("/api/sessions/dismiss"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:q,agentId:Y})})).ok)return;se(),te()}catch{}return}if(confirm('Delete session "'+q+'"?'))try{if(!(await fetch(P("/api/sessions/kill"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:q,...Y?{agentId:Y}:{}})})).ok)return;se(),S===q&&(Y??null)===R&&(k&&(k.destroy(),k=null),S=null,_.style.display="none",ue.style.display="flex"),te()}catch{}}),document.getElementById("sp-cancel").addEventListener("click",se);var Tn={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"},ct=document.getElementById("mobile-keys"),_i=new Set(["up","down","left","right","tab","s-tab","space"]),qi=400,Yi=80,Fe=0,pt=0,ut=!1;function Ji(){Fe&&(clearTimeout(Fe),Fe=0),pt&&(clearInterval(pt),pt=0)}ct.addEventListener("mousedown",e=>{e.target.closest("button[data-key]")&&e.preventDefault()}),ct.addEventListener("pointerdown",e=>{let t=e.target.closest("button[data-key]");if(!t)return;let n=t.dataset.key;_i.has(n)&&(ut=!1,Fe=setTimeout(()=>{Fe=0,ut=!0,pt=setInterval(()=>{let i=Tn[n];i&&k&&k.sendInput(i)},Yi)},qi))});for(let e of["pointerup","pointercancel","pointerleave"])ct.addEventListener(e,Ji);ct.addEventListener("click",e=>{let t=e.target.closest("button[data-key]");if(!t||!k)return;if(ut){ut=!1;return}let n=Tn[t.dataset.key];n&&(k.sendInput(n),k.focus())});var Z=document.getElementById("mk-input"),Bn=document.getElementById("mk-send");function Mn(){if(!Z||!k)return;let e=Z.value;e&&(k.sendInput(e+"\r"),Z.value="",Z.rows=1,k.focus())}if(Z&&(Z.addEventListener("input",()=>{Z.rows=1;let e=Z.value.split(`
55
- `).length;Z.rows=Math.min(e,4)}),Z.addEventListener("keydown",e=>{e.key==="Enter"&&!e.shiftKey&&(e.preventDefault(),Mn())})),Bn&&Bn.addEventListener("click",Mn),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 Mt=document.getElementById("process-panel"),Re=document.getElementById("proc-list"),Ki=document.getElementById("proc-close"),Dt=document.getElementById("proc-backdrop"),Vi=document.getElementById("header-ram");function Xi(){Re.innerHTML='<div class="proc-empty">Loading\u2026</div>',fetch(P("/api/system/processes")).then(e=>e.json()).then(e=>{if(!Array.isArray(e)||!e.length){Re.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="'+w(n.command)+'">'+w(n.command)+'</span><button class="proc-kill" title="Kill PID '+n.pid+'">&times;</button></div>'}Re.innerHTML=t;for(let n of Re.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(P("/api/system/kill"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({pid:parseInt(r.dataset.pid,10)})}).then(l=>l.json()).then(l=>{l.ok?r.style.opacity="0.3":alert("Failed: "+(l.error||"unknown"))}).catch(()=>alert("Network error"))})}}).catch(()=>{Re.innerHTML='<div class="proc-empty">Failed to load</div>'})}function Qi(){Mt.classList.add("open"),Dt.classList.add("open"),Xi()}function mt(){Mt.classList.remove("open"),Dt.classList.remove("open")}Vi.addEventListener("click",e=>{e.stopPropagation(),Mt.classList.contains("open")?mt():Qi()}),Ki.addEventListener("click",mt),Dt.addEventListener("click",mt);var Zi=2e3,je=null,$t=null,be=new Map,ye=new Map,Gi=5e3,Dn=new Map;function At(e,t){return(t?"a:"+t+":":"l:")+e}function ea(e,t,n){let i=At(e,t);if(n==="working"){let u=Dn.get(i);if(u&&Date.now()<u)return}let a=ye.get(i),r=e===S&&(t??null)===R,l=n==="idle"&&a?.state==="working";ye.set(i,{session:e,agentId:t,state:n,doneUntil:l?Date.now()+Zi:void 0,unread:l?!r:!1});let s=t?'.session-item[data-agent="'+CSS.escape(t)+'"][data-session="'+CSS.escape(e)+'"]':'.session-item[data-session="'+CSS.escape(e)+'"]:not([data-agent])',p=y.querySelector(s);p&&ft(p,i,ye.get(i))}function ft(e,t,n){let i=be.get(t);i&&(clearTimeout(i),be.delete(t)),e.classList.remove("working","just-done");let a=n.session===S&&(n.agentId??null)===R;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 Pt(){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=y.querySelector(n);i&&ft(i,e,t)}}function ta(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])',l=y.querySelector(r);l&&ft(l,n,i)}function $n(){if(je||$t)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);je=n,n.onmessage=i=>{try{let a=JSON.parse(String(i.data));a&&a.type==="session.activity"&&typeof a.session=="string"&&ea(a.session,a.agentId||void 0,a.state==="working"?"working":"idle")}catch{}},n.onclose=()=>{je===n&&(je=null,$t=setTimeout(()=>{$t=null,$n()},5e3))},n.onerror=()=>{try{n.close()}catch{}}}catch{je=null}}window.__openSession=$e,window.__refreshSidebar=te,te(),Ge(),Pt(),$n(),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&Pt()}),setInterval(()=>{document.visibilityState==="visible"&&te()},1e4),Ei();
53
+ <button class="btn danger" id="sp-delete">Delete session</button>`,document.body.appendChild(Q);function _i(e){let t=e.getBoundingClientRect(),n=window.innerHeight,i=Q.offsetHeight||240,s=t.bottom+4;s+i>n-8&&(s=Math.max(8,t.top-i-4)),Q.style.top=s+"px",Q.style.left=Math.max(8,Math.min(t.left,window.innerWidth-240))+"px"}function lt(e,t,n){Y=e,se=!!n?.tombstone,X=n?.agentId;let i=document.getElementById("sp-name");i.value=e;let s=Q.querySelector(".sp-field label");s.textContent=se?"\u91CD\u547D\u540D (\u4EC5\u8BB0\u5F55\uFF0C\u4E0D\u91CD\u5EFA)":"Rename session";let r=document.getElementById("sp-rebuild");r.style.display=se?"":"none";let a=document.getElementById("sp-delete");a.textContent=se?"\u5220\u9664\u5931\u6548\u8BB0\u5F55 (\u5893\u7891\u6D88\u5931)":"Delete session";let o=document.getElementById("sp-save");o.textContent=se?"\u91CD\u547D\u540D":"Save",Pe.classList.add("open"),Q.style.display="block",_i(t),setTimeout(()=>i.focus(),50)}function fe(){Pe.classList.remove("open"),Q.style.display="none"}Pe.addEventListener("click",fe),document.getElementById("sp-save").addEventListener("click",async()=>{let e=document.getElementById("sp-name").value.trim();if(!e||e===Y){fe();return}try{let t=se?{oldName:Y,newName:e,agentId:X}:{oldName:Y,newName:e,...X?{agentId:X}:{}};if(!(await fetch(N(se?"/api/sessions/rename-tombstone":"/api/sessions/rename"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})).ok)return;fe(),ne(),!se&&B===Y&&(X??null)===R&&Ae(e,X)}catch{}}),document.getElementById("sp-rebuild").addEventListener("click",async()=>{if(confirm('\u91CD\u5EFA\u4F1A\u8BDD "'+Y+'" (\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:Y,agentId:X})});if(!e.ok){let t=await e.json();alert(t.error||"\u91CD\u5EFA\u5931\u8D25");return}fe(),ne()}catch{}}),document.getElementById("sp-delete").addEventListener("click",async()=>{if(se){if(!confirm('\u5220\u9664\u5931\u6548\u8BB0\u5F55 "'+Y+'"\uFF1F'))return;try{if(!(await fetch(N("/api/sessions/dismiss"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:Y,agentId:X})})).ok)return;fe(),ne()}catch{}return}if(confirm('Delete session "'+Y+'"?'))try{if(!(await fetch(N("/api/sessions/kill"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:Y,...X?{agentId:X}:{}})})).ok)return;fe(),B===Y&&(X??null)===R&&(S&&(S.destroy(),S=null),B=null,J.style.display="none",ue.style.display="flex"),ne()}catch{}}),document.getElementById("sp-cancel").addEventListener("click",fe);var Sn={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"},rt=document.getElementById("mobile-keys"),Ui=new Set(["up","down","left","right","tab","s-tab","space"]),Wi=400,qi=80,Ne=0,dt=0,ct=!1;function Ji(){Ne&&(clearTimeout(Ne),Ne=0),dt&&(clearInterval(dt),dt=0)}rt.addEventListener("mousedown",e=>{e.target.closest("button[data-key]")&&e.preventDefault()}),rt.addEventListener("pointerdown",e=>{let t=e.target.closest("button[data-key]");if(!t)return;let n=t.dataset.key;Ui.has(n)&&(ct=!1,Ne=setTimeout(()=>{Ne=0,ct=!0,dt=setInterval(()=>{let i=Sn[n];i&&S&&S.sendInput(i)},qi)},Wi))});for(let e of["pointerup","pointercancel","pointerleave"])rt.addEventListener(e,Ji);rt.addEventListener("click",e=>{let t=e.target.closest("button[data-key]");if(!t||!S)return;if(ct){ct=!1;return}let n=Sn[t.dataset.key];n&&(S.sendInput(n),S.focus())});var G=document.getElementById("mk-input"),Ln=document.getElementById("mk-send");function In(){if(!G||!S)return;let e=G.value;e&&(S.sendInput(e+"\r"),G.value="",G.rows=1,S.focus())}if(G&&(G.addEventListener("input",()=>{G.rows=1;let e=G.value.split(`
54
+ `).length;G.rows=Math.min(e,4)}),G.addEventListener("keydown",e=>{e.key==="Enter"&&!e.shiftKey&&(e.preventDefault(),In())})),Ln&&Ln.addEventListener("click",In),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"),Fe=document.getElementById("proc-list"),Yi=document.getElementById("proc-close"),Bt=document.getElementById("proc-backdrop"),Ki=document.getElementById("header-ram");function Vi(){Fe.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){Fe.innerHTML='<div class="proc-empty">No processes</div>';return}let t="";for(let n of e){let i=n.rss,s=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">'+s+'</span><span class="proc-cmd" title="'+k(n.command)+'">'+k(n.command)+'</span><button class="proc-kill" title="Kill PID '+n.pid+'">&times;</button></div>'}Fe.innerHTML=t;for(let n of Fe.querySelectorAll(".proc-row")){let i=n.querySelector(".proc-kill");i&&i.addEventListener("click",s=>{let r=s.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(a=>a.json()).then(a=>{a.ok?r.style.opacity="0.3":alert("Failed: "+(a.error||"unknown"))}).catch(()=>alert("Network error"))})}}).catch(()=>{Fe.innerHTML='<div class="proc-empty">Failed to load</div>'})}function Xi(){Tt.classList.add("open"),Bt.classList.add("open"),Vi()}function pt(){Tt.classList.remove("open"),Bt.classList.remove("open")}Ki.addEventListener("click",e=>{e.stopPropagation(),Tt.classList.contains("open")?pt():Xi()}),Yi.addEventListener("click",pt),Bt.addEventListener("click",pt);var Qi=2e3,Oe=null,Mt=null,be=new Map,ye=new Map,Zi=5e3,Tn=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=Tn.get(i);if(u&&Date.now()<u)return}let s=ye.get(i),r=e===B&&(t??null)===R,a=n==="idle"&&s?.state==="working";ye.set(i,{session:e,agentId:t,state:n,doneUntil:a?Date.now()+Qi:void 0,unread:a?!r:!1});let o=t?'.session-item[data-agent="'+CSS.escape(t)+'"][data-session="'+CSS.escape(e)+'"]':'.session-item[data-session="'+CSS.escape(e)+'"]:not([data-agent])',p=E.querySelector(o);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 s=n.session===B&&(n.agentId??null)===R;n.state==="working"?e.classList.add("working"):s&&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())))):!s&&n.unread&&e.classList.add("just-done")}function Dt(){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=E.querySelector(n);i&&ut(i,e,t)}}function es(e,t){let n=At(e,t),i=ye.get(n);if(!i)return;let s=be.get(n);s&&(clearTimeout(s),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])',a=E.querySelector(r);a&&ut(a,n,i)}function Bn(){if(Oe||Mt)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 s=JSON.parse(String(i.data));s&&s.type==="session.activity"&&typeof s.session=="string"&&Gi(s.session,s.agentId||void 0,s.state==="working"?"working":"idle")}catch{}},n.onclose=()=>{Oe===n&&(Oe=null,Mt=setTimeout(()=>{Mt=null,Bn()},5e3))},n.onerror=()=>{try{n.close()}catch{}}}catch{Oe=null}}window.__openSession=Ae,window.__refreshSidebar=ne,ne(),Qe(),Dt(),Bn(),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&Dt()}),setInterval(()=>{document.visibilityState==="visible"&&ne()},1e4),yi();