tmux-weblink 2.2.40 → 2.2.41

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