tmux-weblink 2.2.42 → 2.2.44

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,46 +1,46 @@
1
- var ni=/\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(ni,"")}var _e;function ii(){return _e||(document.querySelector("link[data-tmux-web-xterm-css]")?_e=Promise.resolve():(_e=new Promise(e=>{let t=document.createElement("link");t.rel="stylesheet",t.href="/assets/xterm.css",t.setAttribute("data-tmux-web-xterm-css",""),t.addEventListener("load",()=>e(),{once:!0}),t.addEventListener("error",()=>e(),{once:!0}),document.head.appendChild(t)}),_e))}var si=class An{terminal;fitAddon;container;webglActive=!1;repaintTimer=0;webglAddon=null;constructor(t,n,i){this.container=t,this.terminal=n,this.fitAddon=i,this.terminal.loadAddon(this.fitAddon),this.terminal.open(t),this.enableWebglRenderer(),document.addEventListener("visibilitychange",()=>{document.hidden||this.refreshPaintedRows()})}enableWebglRenderer(){if(oi()==="webgl"){try{if(!document.createElement("canvas").getContext("webgl2",{failIfMajorPerformanceCaveat:!0}))return}catch{return}import("./addon-webgl-B45EJ6AW.js").then(({WebglAddon:t})=>{let n=new t;n.onContextLoss(()=>{this.webglActive=!1,this.webglAddon=null;try{n.dispose()}catch{}this.fit()});try{this.terminal.loadAddon(n)}catch{return}this.webglAddon=n,this.webglActive=!0,this.fit()}).catch(()=>{})}}refreshPaintedRows(){if(this.webglActive){try{this.webglAddon?.clearTextureAtlas?.()}catch{}try{this.terminal.refresh(0,Math.max(0,this.terminal.rows-1))}catch{}}}static async create(t,n,i){let[{Terminal:s},{FitAddon:r}]=await Promise.all([import("./xterm-BXEES47M.js"),import("./addon-fit-D5N335P2.js"),ii()]),o="'JetBrains Mono', 'SF Mono', 'Menlo', monospace",a=new s({fontSize:ai(14,o),fontFamily:o,cursorBlink:!0,cursorStyle:"bar",scrollback:n,convertEol:!1,smoothScrollDuration:120,theme:i});return new An(t,a,new r)}get cols(){return this.terminal.cols}get rows(){return this.terminal.rows}write(t){return new Promise(n=>this.terminal.write(t,n))}reset(){this.terminal.reset()}scrollToBottom(){this.terminal.scrollToBottom()}scrollToLine(t,n=!1){this.terminal.scrollToLine(Math.max(0,t),n),this.scheduleRepaintCheck()}scrollLines(t){this.terminal.scrollLines(t),this.scheduleRepaintCheck()}scheduleRepaintCheck(){this.webglActive&&(this.repaintTimer&&clearTimeout(this.repaintTimer),this.repaintTimer=setTimeout(()=>{this.repaintTimer=0,this.refreshPaintedRows()},150))}isNearScrollbackTop(){return this.terminal.buffer.active.viewportY<=1}viewportY(){return this.terminal.buffer.active.viewportY}baseY(){return this.terminal.buffer.active.baseY}cellHeight(){let t=this.terminal.element?.querySelector(".xterm-screen")?.getBoundingClientRect().height??0,n=this.terminal.rows;return t>0&&n>0?t/n:16}fit(){let t=li(this.container);if(t.width<=0||t.height<=0)return!1;let n=this.terminal.cols,i=this.terminal.rows,s=this.paintedCellWidth();s<=0&&(this.fitAddon.fit(),s=this.paintedCellWidth());let r=this.fitAddon.proposeDimensions?.();if(!r)return this.fitAddon.fit(),!0;let o=this.overlayScrollbarWidth(),a=o>0?o+2:0,p=s>0?Math.max(10,Math.min(r.cols,Math.floor((t.width-a)/s))):r.cols,u=r.rows;return(p!==this.terminal.cols||u!==this.terminal.rows)&&this.terminal.resize(p,u),this.webglActive&&(n!==this.terminal.cols||i!==this.terminal.rows)&&this.refreshPaintedRows(),!0}paintedCellWidth(){let t=this.terminal.element?.querySelector(".xterm-screen")?.getBoundingClientRect().width??0,n=this.terminal.cols;return t>0&&n>0?t/n:0}overlayScrollbarWidth(){let t=this.terminal.element?.querySelector(".vertical.scrollbar");if(!t)return 0;let n=t.getBoundingClientRect();return!(n.width>0)||!(n.height>0)?0:Math.round(n.width)}focus(){this.terminal.focus()}pasteText(t){this.terminal.paste(t)}input(t){this.terminal.input(t,!1)}onData(t){this.terminal.onData(t),this.terminal.onBinary(t)}onResize(t){this.terminal.onResize(t)}onScroll(t){this.terminal.onScroll(t)}attachCustomKeyEventHandler(t){this.terminal.attachCustomKeyEventHandler(t)}isFocused(){let t=document.activeElement;return t?t===this.container||t===this.terminal.textarea||this.container.contains(t)||!!t.closest?.(".xterm"):!1}getScreenText(){return this.getRowsText(0,this.terminal.rows-1)}getRowsText(t,n){let i=this.terminal.buffer.active,[s,r]=t<=n?[t,n]:[n,t],o=i.viewportY,a=[];for(let p=s;p<=r;p++){let u=i.getLine(o+p);a.push(u?u.translateToString(!0):"")}return a.join(`
2
- `)}selectRows(t,n){let i=this.terminal.buffer.active,[s,r]=t<=n?[t,n]:[n,t];this.terminal.selectLines(i.viewportY+s,i.viewportY+r)}selectCells(t,n,i,s){let r=this.terminal.buffer.active,o=Math.min(n,s),a=Math.max(n,s);if(o===a){let p=Math.min(t,i),u=Math.max(t,i);this.terminal.select(p,r.viewportY+o,u-p+1)}else this.terminal.selectLines(r.viewportY+o,r.viewportY+a)}getCellsText(t,n,i,s){let r=this.terminal.buffer.active,o=Math.min(n,s),a=Math.max(n,s),p=n<s?t:n>s?i:Math.min(t,i),u=n<s?i:n>s?t:Math.max(t,i),v=r.viewportY,b=[];for(let M=o;M<=a;M++){let T=r.getLine(v+M);if(!T){b.push("");continue}let E=M===o?p:0,S=M===a?u:this.terminal.cols-1,j="";for(let D=E;D<=S;D++){let _=T.getCell(D);_&&(j+=_.getChars())}b.push(j.replace(/\s+$/,""))}return b.join(`
3
- `)}getSelection(){return this.terminal.getSelection()}clearSelection(){this.terminal.clearSelection()}hasSelectionSupport(){return!0}};function ai(e,t){try{let n=document.createElement("canvas").getContext("2d");if(!n)return e;let i=100;n.font=`${i}px ${t}`;let s=n.measureText("M").width/i;if(!Number.isFinite(s)||s<=0)return e;let r=window.devicePixelRatio||1,o=e,a=Number.POSITIVE_INFINITY;for(let p=4;p<=40;p++){let u=p/(s*r);if(u<e-1.5||u>e+1.5)continue;let v=Math.abs(u-e);v<a&&(a=v,o=u)}return Math.round(o*100)/100}catch{return e}}function oi(){try{let e=new URLSearchParams(window.location.search).get("renderer");return e==="dom"||e==="webgl"?e:null}catch{return null}}function li(e){let t=e.getBoundingClientRect(),n=window.visualViewport;return n?{width:Math.min(t.width,n.width),height:Math.max(0,Math.min(t.height,n.height-Math.max(0,t.top)))}:t}function ri(e,t,n){return e.innerHTML="",e.classList.add("terminal-pending"),(async()=>{let i=await si.create(e,n.scrollback,n.theme),s,r=0,o,a=null,p=0,u=0,v=.2,b=10,M=.95,T=.04,E=null,S=null;function j(l){E||(E=document.createElement("div"),E.style.cssText=["position:absolute","left:0","width:40%","padding:10px 0","text-align:center","font:600 14px/1.4 system-ui, -apple-system, sans-serif","color:rgba(255,255,255,0.95)","background:rgba(20,30,50,0.55)","border:1px solid rgba(255,255,255,0.25)","border-radius:10px","pointer-events:none","opacity:0","transition:opacity 0.15s ease","z-index:6"].join(";"),e.appendChild(E)),E.textContent=l?"\u2191 \u4E0A\u7FFB\u4E00\u9875 (PgUp)":"\u2193 \u4E0B\u7FFB\u4E00\u9875 (PgDn)",E.style.top=l?"10%":"auto",E.style.bottom=l?"auto":"10%",E.style.opacity="1",S&&clearTimeout(S),S=setTimeout(()=>{E&&(E.style.opacity="0")},900)}function D(){S&&clearTimeout(S),E&&(E.style.opacity="0")}function _(){p&&(cancelAnimationFrame(p),p=0),u=0}function ae(l){if(_(),Math.abs(l)<v)return;u=Math.max(-b,Math.min(b,l));let c=()=>{if(x){p=0;return}let f=i.cellHeight(),g=f>0?Math.round(u*16/f):u>0?1:-1;g===0&&(g=u>0?1:-1);let k=i.viewportY()-g,V=i.baseY(),se=Math.max(0,Math.min(k,V));if(i.scrollToLine(se,!0),u*=M,se!==k){p=0;return}if(Math.abs(u)<T){p=0;return}p=requestAnimationFrame(c)};p=requestAnimationFrame(c)}let oe=0,O="connecting",N=0,ie=!1,h=[],z="",x=!1,le=1e3,B=location.protocol==="https:"?"wss:":"ws:",At=n.wsBase||"/ws",$n=B+"//"+location.host+At+"/"+encodeURIComponent(t),Pn=(At.replace(/^\/ws/,"")||"")+"/api/session/"+encodeURIComponent(t)+"/upload",Nn=/^((?!chrome|android|crios|fxios|edgios).)*safari/i.test(navigator.userAgent);function Fn(){return h.join("")+z}async function Hn(l,c=0){let f=l?i.viewportY():0,g=xe(Fn());if(i.reset(),!g){l||i.scrollToBottom();return}await i.write(g),l?i.scrollToLine(c+f):i.scrollToBottom()}function re(l){s?.readyState===WebSocket.OPEN&&s.send(JSON.stringify(l))}function Rn(l){let c;try{c=JSON.parse(l)}catch{O==="live"&&(z+=l,i.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",i.reset(),i.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:i.cols,rows:i.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="",N=typeof c.lines=="number"?c.lines:n.terminal.initialLines,O="live",i.reset(),de(),re({type:"resize",cols:i.cols,rows:i.rows}),i.write(f).then(()=>i.scrollToBottom());return}if(c.type==="window_changed"&&typeof c.activeIndex=="number"){let f=new URL(location.href);f.searchParams.get("window")!==String(c.activeIndex)&&(f.searchParams.set("window",String(c.activeIndex)),history.replaceState(history.state,"",f)),window.dispatchEvent(new CustomEvent("tmux:windows",{detail:c.windows}));return}if(c.type==="history"&&typeof c.data=="string"){c.lines>0&&c.data?(h.unshift(vt(c.data)),N+=c.lines,Hn(!0,c.lines).finally(()=>{ie=!1})):ie=!1;return}if(c.type==="data"&&typeof c.data=="string"){let f=vt(xe(c.data));if(O==="connecting"){O="live",z=f,i.write(f);return}O==="live"&&(z+=f,i.write(f))}}let Re=!1;function $t(){if(Re)return;let l=$n,c=localStorage.getItem("tmux-web-token");c&&(l+=(l.includes("?")?"&":"?")+"token="+encodeURIComponent(c)),l+=(l.includes("?")?"&":"?")+"cols="+i.cols+"&rows="+i.rows,s=new WebSocket(l),s.onopen=()=>{O="connecting",N=0,ie=!1,h=[],z="",i.reset(),le=1e3},s.onmessage=f=>{typeof f.data=="string"&&Rn(f.data)},s.onclose=()=>{x||(O="connecting",!Re&&setTimeout(()=>{le=Math.min(le*2,1e4),!x&&!Re&&$t()},le))},s.onerror=()=>s?.close()}function fe(l){re({type:"input",data:l})}function de(){return i.fit()}function je(){e.classList.remove("terminal-pending")}function W(){r&&cancelAnimationFrame(r),o&&clearTimeout(o),de(),r=requestAnimationFrame(()=>{r=0,de()&&je()}),o=setTimeout(()=>{de()&&je()},120)}function jn(){W(),setTimeout(W,50),setTimeout(W,150),setTimeout(W,300)}function Pt(l){return typeof l=="string"&&l.startsWith("image/")}function Nt(l){return l?.files?.length?l.files[0]??null:null}function On(l){if(!l?.items)return null;for(let c=0;c<l.items.length;c++){let f=l.items[c];if(f?.kind==="file"&&Pt(f.type))return f.getAsFile()}return null}async function zn(l){let c=new FormData,f=l instanceof File&&l.name?l.name:"upload";c.append("file",l,f);let g=localStorage.getItem("tmux-web-token"),k={};g&&(k.Authorization="Bearer "+g);let V=await fetch(Pn,{method:"POST",body:c,headers:k});if(!V.ok){let Wt="upload failed";try{let _t=await V.json();_t.error&&(Wt=_t.error)}catch{}throw new Error(Wt)}let se=await V.json();if(!se.path)throw new Error("no path in response");return se.path}async function mt(l){try{let c=await zn(l);fe(c)}catch{}}i.onData(l=>fe(l)),i.onResize(({cols:l,rows:c})=>re({type:"resize",cols:l,rows:c})),i.onScroll(()=>{O!=="live"||ie||!i.isNearScrollbackTop()||(ie=!0,re({type:"load_history",before:N}))});let be=!1,we=!1,A=null,F=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 Ft(l,c){let f=e.querySelector(".xterm-screen, canvas"),g=(f&&f.getBoundingClientRect().width>0?f:e).getBoundingClientRect(),k=g.height>0&&i.rows>0?g.height/i.rows:18,V=g.width>0&&i.cols>0?g.width/i.cols:9;return{row:Math.max(0,Math.min(i.rows-1,Math.floor((c-g.top)/k))),col:Math.max(0,Math.min(i.cols-1,Math.floor((l-g.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&&i.focus()}function Ht(){he(!be)}function Wn(l){x||l.button!==0||we||(be||l.shiftKey)&&(l.preventDefault(),l.stopPropagation(),we=!0,A=Ft(l.clientX,l.clientY),F=A,i.selectCells(A.col,A.row,F.col,F.row),document.addEventListener("mousemove",ft,!0),document.addEventListener("mouseup",ht,!0))}function ft(l){x||!we||!A||(l.preventDefault(),l.stopPropagation(),F=Ft(l.clientX,l.clientY),i.selectCells(A.col,A.row,F.col,F.row))}function ht(l){if(x||!we||!A||!F)return;l.preventDefault(),l.stopPropagation(),document.removeEventListener("mousemove",ft,!0),document.removeEventListener("mouseup",ht,!0),we=!1;let c=i.getCellsText(A.col,A.row,F.col,F.row);A=null,F=null,i.clearSelection(),he(!1),c&&(Z.textContent="\u5DF2\u590D\u5236",Oe(c).then(ze)),i.focus()}e.addEventListener("mousedown",Wn,!0),document.addEventListener("keydown",_n,!0);function _n(l){if(!(x||!i.isFocused()||l.defaultPrevented||l.isComposing)){if(be){if(l.key==="Escape"){l.preventDefault(),l.stopPropagation(),A=null,F=null,i.clearSelection(),he(!1);return}if(l.key==="Enter"||(l.ctrlKey||l.metaKey)&&l.code==="KeyC"){l.preventDefault(),l.stopPropagation(),Oe(i.getScreenText()).then(ze),he(!1);return}}if(l.altKey&&l.code==="KeyC"&&!l.ctrlKey&&!l.metaKey){if(l.preventDefault(),l.stopPropagation(),A&&F){let c=i.getCellsText(A.col,A.row,F.col,F.row);A=null,F=null,i.clearSelection(),he(!1),c&&(Z.textContent="Copied",Oe(c).then(ze))}else{let c=i.getSelection();c?(i.clearSelection(),Z.textContent="Copied",Oe(c).then(ze)):Ht()}return}if((l.ctrlKey||l.metaKey)&&l.code==="KeyV"){l.preventDefault(),l.stopPropagation(),(async()=>{try{if(navigator.clipboard?.read){let c=await navigator.clipboard.read();for(let f of c)for(let g of f.types)if(Pt(g)){let k=await f.getType(g);await mt(k);return}}}catch{}try{let c=await navigator.clipboard?.readText();c&&i.pasteText(Rt(c))}catch{}})();return}}}let We=0;function Rt(l){return l.split(`\r
1
+ var ii=/\x1b\](?:10|11|110|111|104)(?:;[^\x07\x1b]*)?\x1b?(?:\\|\x07)/g;function bt(e){return e.replace(/\x1b\[\?1049[hl]/g,"")}function Le(e){return e.replace(ii,"")}var _e;function ai(){return _e||(document.querySelector("link[data-tmux-web-xterm-css]")?_e=Promise.resolve():(_e=new Promise(e=>{let t=document.createElement("link");t.rel="stylesheet",t.href="/assets/xterm.css",t.setAttribute("data-tmux-web-xterm-css",""),t.addEventListener("load",()=>e(),{once:!0}),t.addEventListener("error",()=>e(),{once:!0}),document.head.appendChild(t)}),_e))}var si=class An{terminal;fitAddon;container;webglActive=!1;repaintTimer=0;webglAddon=null;constructor(t,n,i){this.container=t,this.terminal=n,this.fitAddon=i,this.terminal.loadAddon(this.fitAddon),this.terminal.open(t),this.enableWebglRenderer(),document.addEventListener("visibilitychange",()=>{document.hidden||this.refreshPaintedRows()})}enableWebglRenderer(){if(oi()==="webgl"){try{if(!document.createElement("canvas").getContext("webgl2",{failIfMajorPerformanceCaveat:!0}))return}catch{return}import("./addon-webgl-B45EJ6AW.js").then(({WebglAddon:t})=>{let n=new t;n.onContextLoss(()=>{this.webglActive=!1,this.webglAddon=null;try{n.dispose()}catch{}this.fit()});try{this.terminal.loadAddon(n)}catch{return}this.webglAddon=n,this.webglActive=!0,this.fit()}).catch(()=>{})}}refreshPaintedRows(){if(this.webglActive){try{this.webglAddon?.clearTextureAtlas?.()}catch{}try{this.terminal.refresh(0,Math.max(0,this.terminal.rows-1))}catch{}}}static async create(t,n,i){let[{Terminal:a},{FitAddon:r}]=await Promise.all([import("./xterm-BXEES47M.js"),import("./addon-fit-D5N335P2.js"),ai()]),l="'JetBrains Mono', 'SF Mono', 'Menlo', monospace",s=new a({fontSize:li(14,l),fontFamily:l,cursorBlink:!0,cursorStyle:"bar",scrollback:n,convertEol:!1,smoothScrollDuration:120,theme:i});return new An(t,s,new r)}get cols(){return this.terminal.cols}get rows(){return this.terminal.rows}write(t){return new Promise(n=>this.terminal.write(t,n))}reset(){this.terminal.reset()}scrollToBottom(){this.terminal.scrollToBottom()}scrollToLine(t,n=!1){this.terminal.scrollToLine(Math.max(0,t),n),this.scheduleRepaintCheck()}scrollLines(t){this.terminal.scrollLines(t),this.scheduleRepaintCheck()}scheduleRepaintCheck(){this.webglActive&&(this.repaintTimer&&clearTimeout(this.repaintTimer),this.repaintTimer=setTimeout(()=>{this.repaintTimer=0,this.refreshPaintedRows()},150))}isNearScrollbackTop(){return this.terminal.buffer.active.viewportY<=1}viewportY(){return this.terminal.buffer.active.viewportY}baseY(){return this.terminal.buffer.active.baseY}cellHeight(){let t=this.terminal.element?.querySelector(".xterm-screen")?.getBoundingClientRect().height??0,n=this.terminal.rows;return t>0&&n>0?t/n:16}fit(){let t=ri(this.container);if(t.width<=0||t.height<=0)return!1;let n=this.terminal.cols,i=this.terminal.rows,a=this.paintedCellWidth();a<=0&&(this.fitAddon.fit(),a=this.paintedCellWidth());let r=this.fitAddon.proposeDimensions?.();if(!r)return this.fitAddon.fit(),!0;let l=this.overlayScrollbarWidth(),s=l>0?l+2:0,p=a>0?Math.max(10,Math.min(r.cols,Math.floor((t.width-s)/a))):r.cols,u=r.rows;return(p!==this.terminal.cols||u!==this.terminal.rows)&&this.terminal.resize(p,u),this.webglActive&&(n!==this.terminal.cols||i!==this.terminal.rows)&&this.refreshPaintedRows(),!0}paintedCellWidth(){let t=this.terminal.element?.querySelector(".xterm-screen")?.getBoundingClientRect().width??0,n=this.terminal.cols;return t>0&&n>0?t/n:0}overlayScrollbarWidth(){let t=this.terminal.element?.querySelector(".vertical.scrollbar");if(!t)return 0;let n=t.getBoundingClientRect();return!(n.width>0)||!(n.height>0)?0:Math.round(n.width)}focus(){this.terminal.focus()}pasteText(t){this.terminal.paste(t)}input(t){this.terminal.input(t,!1)}onData(t){this.terminal.onData(t),this.terminal.onBinary(t)}onResize(t){this.terminal.onResize(t)}onScroll(t){this.terminal.onScroll(t)}attachCustomKeyEventHandler(t){this.terminal.attachCustomKeyEventHandler(t)}isFocused(){let t=document.activeElement;return t?t===this.container||t===this.terminal.textarea||this.container.contains(t)||!!t.closest?.(".xterm"):!1}getScreenText(){return this.getRowsText(0,this.terminal.rows-1)}getRowsText(t,n){let i=this.terminal.buffer.active,[a,r]=t<=n?[t,n]:[n,t],l=i.viewportY,s=[];for(let p=a;p<=r;p++){let u=i.getLine(l+p);s.push(u?u.translateToString(!0):"")}return s.join(`
2
+ `)}selectRows(t,n){let i=this.terminal.buffer.active,[a,r]=t<=n?[t,n]:[n,t];this.terminal.selectLines(i.viewportY+a,i.viewportY+r)}selectCells(t,n,i,a){let r=this.terminal.buffer.active,l=Math.min(n,a),s=Math.max(n,a);if(l===s){let p=Math.min(t,i),u=Math.max(t,i);this.terminal.select(p,r.viewportY+l,u-p+1)}else this.terminal.selectLines(r.viewportY+l,r.viewportY+s)}getCellsText(t,n,i,a){let r=this.terminal.buffer.active,l=Math.min(n,a),s=Math.max(n,a),p=n<a?t:n>a?i:Math.min(t,i),u=n<a?i:n>a?t:Math.max(t,i),h=r.viewportY,g=[];for(let x=l;x<=s;x++){let B=r.getLine(h+x);if(!B){g.push("");continue}let E=x===l?p:0,I=x===s?u:this.terminal.cols-1,O="";for(let D=E;D<=I;D++){let W=B.getCell(D);W&&(O+=W.getChars())}g.push(O.replace(/\s+$/,""))}return g.join(`
3
+ `)}getSelection(){return this.terminal.getSelection()}clearSelection(){this.terminal.clearSelection()}hasSelectionSupport(){return!0}};function li(e,t){try{let n=document.createElement("canvas").getContext("2d");if(!n)return e;let i=100;n.font=`${i}px ${t}`;let a=n.measureText("M").width/i;if(!Number.isFinite(a)||a<=0)return e;let r=window.devicePixelRatio||1,l=e,s=Number.POSITIVE_INFINITY;for(let p=4;p<=40;p++){let u=p/(a*r);if(u<e-1.5||u>e+1.5)continue;let h=Math.abs(u-e);h<s&&(s=h,l=u)}return Math.round(l*100)/100}catch{return e}}function oi(){try{let e=new URLSearchParams(window.location.search).get("renderer");return e==="dom"||e==="webgl"?e:null}catch{return null}}function ri(e){let t=e.getBoundingClientRect(),n=window.visualViewport;return n?{width:Math.min(t.width,n.width),height:Math.max(0,Math.min(t.height,n.height-Math.max(0,t.top)))}:t}function di(e,t,n){return e.innerHTML="",e.classList.add("terminal-pending"),(async()=>{let i=await si.create(e,n.scrollback,n.theme),a,r=0,l,s=null,p=0,u=0,h=.2,g=10,x=.95,B=.04,E=null,I=null;function O(o){E||(E=document.createElement("div"),E.style.cssText=["position:absolute","left:0","width:40%","padding:10px 0","text-align:center","font:600 14px/1.4 system-ui, -apple-system, sans-serif","color:rgba(255,255,255,0.95)","background:rgba(20,30,50,0.55)","border:1px solid rgba(255,255,255,0.25)","border-radius:10px","pointer-events:none","opacity:0","transition:opacity 0.15s ease","z-index:6"].join(";"),e.appendChild(E)),E.textContent=o?"\u2191 \u4E0A\u7FFB\u4E00\u9875 (PgUp)":"\u2193 \u4E0B\u7FFB\u4E00\u9875 (PgDn)",E.style.top=o?"10%":"auto",E.style.bottom=o?"auto":"10%",E.style.opacity="1",I&&clearTimeout(I),I=setTimeout(()=>{E&&(E.style.opacity="0")},900)}function D(){I&&clearTimeout(I),E&&(E.style.opacity="0")}function W(){p&&(cancelAnimationFrame(p),p=0),u=0}function le(o){if(W(),Math.abs(o)<h)return;u=Math.max(-g,Math.min(g,o));let c=()=>{if(L){p=0;return}let f=i.cellHeight(),b=f>0?Math.round(u*16/f):u>0?1:-1;b===0&&(b=u>0?1:-1);let C=i.viewportY()-b,V=i.baseY(),ae=Math.max(0,Math.min(C,V));if(i.scrollToLine(ae,!0),u*=x,ae!==C){p=0;return}if(Math.abs(u)<B){p=0;return}p=requestAnimationFrame(c)};p=requestAnimationFrame(c)}let oe=0,H="connecting",N=0,ie=!1,v=[],z="",L=!1,re=1e3,M=location.protocol==="https:"?"wss:":"ws:",Nt=n.wsBase||"/ws",Pn=M+"//"+location.host+Nt+"/"+encodeURIComponent(t),Nn=(Nt.replace(/^\/ws/,"")||"")+"/api/session/"+encodeURIComponent(t)+"/upload",Fn=/^((?!chrome|android|crios|fxios|edgios).)*safari/i.test(navigator.userAgent);function Rn(){return v.join("")+z}async function jn(o,c=0){let f=o?i.viewportY():0,b=Le(Rn());if(i.reset(),!b){o||i.scrollToBottom();return}await i.write(b),o?i.scrollToLine(c+f):i.scrollToBottom()}function de(o){a?.readyState===WebSocket.OPEN&&a.send(JSON.stringify(o))}function On(o){let c;try{c=JSON.parse(o)}catch{H==="live"&&(z+=o,i.write(Le(o)));return}if(c.type==="auth.required"){let f=localStorage.getItem("tmux-web-token");f?de({type:"auth.token",token:f}):location.href="/login?returnTo="+encodeURIComponent(location.pathname+location.search);return}if(c.type==="attach_failed"&&typeof c.message=="string"){Oe=!0,H="dead",i.reset(),i.write(`\r
4
+ \x1B[31m`+Le(c.message)+`\x1B[0m\r
5
+ `).then(()=>{He();try{a?.close()}catch{}});return}if(c.type==="auth.ok"){c.token&&localStorage.setItem("tmux-web-token",c.token),re=1e3,ce(),de({type:"resize",cols:i.cols,rows:i.rows}),U();return}if(c.type==="auth.failed"){if(c.permanentLock||c.retryAfterMs&&c.retryAfterMs>6e4){localStorage.removeItem("tmux-web-token"),location.href="/login?error="+encodeURIComponent(c.message);return}return}if(c.type==="snapshot"&&typeof c.data=="string"){let f=bt(Le(c.data));v=[f],z="",N=typeof c.lines=="number"?c.lines:n.terminal.initialLines,H="live",i.reset(),ce(),de({type:"resize",cols:i.cols,rows:i.rows}),i.write(f).then(()=>i.scrollToBottom());return}if(c.type==="window_changed"&&typeof c.activeIndex=="number"){let f=new URL(location.href);f.searchParams.get("window")!==String(c.activeIndex)&&(f.searchParams.set("window",String(c.activeIndex)),history.replaceState(history.state,"",f)),window.dispatchEvent(new CustomEvent("tmux:windows",{detail:c.windows}));return}if(c.type==="history"&&typeof c.data=="string"){c.lines>0&&c.data?(v.unshift(bt(c.data)),N+=c.lines,jn(!0,c.lines).finally(()=>{ie=!1})):ie=!1;return}if(c.type==="data"&&typeof c.data=="string"){let f=bt(Le(c.data));if(H==="connecting"){H="live",z=f,i.write(f);return}H==="live"&&(z+=f,i.write(f))}}let Oe=!1;function Ft(){if(Oe)return;let o=Pn,c=localStorage.getItem("tmux-web-token");c&&(o+=(o.includes("?")?"&":"?")+"token="+encodeURIComponent(c)),o+=(o.includes("?")?"&":"?")+"cols="+i.cols+"&rows="+i.rows,a=new WebSocket(o),a.onopen=()=>{H="connecting",N=0,ie=!1,v=[],z="",i.reset(),re=1e3},a.onmessage=f=>{typeof f.data=="string"&&On(f.data)},a.onclose=()=>{L||(H="connecting",!Oe&&setTimeout(()=>{re=Math.min(re*2,1e4),!L&&!Oe&&Ft()},re))},a.onerror=()=>a?.close()}function fe(o){de({type:"input",data:o})}function ce(){return i.fit()}function He(){e.classList.remove("terminal-pending")}function U(){r&&cancelAnimationFrame(r),l&&clearTimeout(l),ce(),r=requestAnimationFrame(()=>{r=0,ce()&&He()}),l=setTimeout(()=>{ce()&&He()},120)}function Hn(){U(),setTimeout(U,50),setTimeout(U,150),setTimeout(U,300)}function Rt(o){return typeof o=="string"&&o.startsWith("image/")}function jt(o){return o?.files?.length?o.files[0]??null:null}function zn(o){if(!o?.items)return null;for(let c=0;c<o.items.length;c++){let f=o.items[c];if(f?.kind==="file"&&Rt(f.type))return f.getAsFile()}return null}async function Un(o){let c=new FormData,f=o instanceof File&&o.name?o.name:"upload";c.append("file",o,f);let b=localStorage.getItem("tmux-web-token"),C={};b&&(C.Authorization="Bearer "+b);let V=await fetch(Nn,{method:"POST",body:c,headers:C});if(!V.ok){let qt="upload failed";try{let Yt=await V.json();Yt.error&&(qt=Yt.error)}catch{}throw new Error(qt)}let ae=await V.json();if(!ae.path)throw new Error("no path in response");return ae.path}async function ht(o){try{let c=await Un(o);fe(c)}catch{}}i.onData(o=>fe(o)),i.onResize(({cols:o,rows:c})=>de({type:"resize",cols:o,rows:c})),i.onScroll(()=>{H!=="live"||ie||!i.isNearScrollbackTop()||(ie=!0,de({type:"load_history",before:N}))});let we=!1,Ee=!1,A=null,F=null,ke=document.createElement("div");ke.className="terminal-copy-banner",ke.innerHTML='<strong>Copy mode</strong><span class="hint">drag to copy \xB7 Esc exits</span>',ke.hidden=!0,e.appendChild(ke);let G=document.createElement("div");G.className="terminal-copy-banner terminal-copy-toast",G.textContent="Copied",G.hidden=!0,e.appendChild(G);function Ot(o,c){let f=e.querySelector(".xterm-screen, canvas"),b=(f&&f.getBoundingClientRect().width>0?f:e).getBoundingClientRect(),C=b.height>0&&i.rows>0?b.height/i.rows:18,V=b.width>0&&i.cols>0?b.width/i.cols:9;return{row:Math.max(0,Math.min(i.rows-1,Math.floor((c-b.top)/C))),col:Math.max(0,Math.min(i.cols-1,Math.floor((o-b.left)/V)))}}async function ze(o){if(!o)return;try{if(navigator.clipboard?.writeText){await navigator.clipboard.writeText(o);return}}catch{}let c=document.createElement("textarea");c.value=o,c.style.position="fixed",c.style.opacity="0",c.style.pointerEvents="none",document.body.appendChild(c),c.focus(),c.select();try{document.execCommand("copy")}catch{}c.remove()}let Ce;function Ue(){G.hidden=!1,Ce&&clearTimeout(Ce),Ce=setTimeout(()=>{G.hidden=!0},1e3)}function he(o){we=o,ke.hidden=!o,e.classList.toggle("terminal-copy-mode-active",o),o&&i.focus()}function Ht(){he(!we)}function Wn(o){L||o.button!==0||Ee||(we||o.shiftKey)&&(o.preventDefault(),o.stopPropagation(),Ee=!0,A=Ot(o.clientX,o.clientY),F=A,i.selectCells(A.col,A.row,F.col,F.row),document.addEventListener("mousemove",vt,!0),document.addEventListener("mouseup",gt,!0))}function vt(o){L||!Ee||!A||(o.preventDefault(),o.stopPropagation(),F=Ot(o.clientX,o.clientY),i.selectCells(A.col,A.row,F.col,F.row))}function gt(o){if(L||!Ee||!A||!F)return;o.preventDefault(),o.stopPropagation(),document.removeEventListener("mousemove",vt,!0),document.removeEventListener("mouseup",gt,!0),Ee=!1;let c=i.getCellsText(A.col,A.row,F.col,F.row);A=null,F=null,i.clearSelection(),he(!1),c&&(G.textContent="\u5DF2\u590D\u5236",ze(c).then(Ue)),i.focus()}e.addEventListener("mousedown",Wn,!0),document.addEventListener("keydown",_n,!0);function _n(o){if(!(L||!i.isFocused()||o.defaultPrevented||o.isComposing)){if(we){if(o.key==="Escape"){o.preventDefault(),o.stopPropagation(),A=null,F=null,i.clearSelection(),he(!1);return}if(o.key==="Enter"||(o.ctrlKey||o.metaKey)&&o.code==="KeyC"){o.preventDefault(),o.stopPropagation(),ze(i.getScreenText()).then(Ue),he(!1);return}}if(o.altKey&&o.code==="KeyC"&&!o.ctrlKey&&!o.metaKey){if(o.preventDefault(),o.stopPropagation(),A&&F){let c=i.getCellsText(A.col,A.row,F.col,F.row);A=null,F=null,i.clearSelection(),he(!1),c&&(G.textContent="Copied",ze(c).then(Ue))}else{let c=i.getSelection();c?(i.clearSelection(),G.textContent="Copied",ze(c).then(Ue)):Ht()}return}if((o.ctrlKey||o.metaKey)&&o.code==="KeyV"){o.preventDefault(),o.stopPropagation(),(async()=>{try{if(navigator.clipboard?.read){let c=await navigator.clipboard.read();for(let f of c)for(let b of f.types)if(Rt(b)){let C=await f.getType(b);await ht(C);return}}}catch{}try{let c=await navigator.clipboard?.readText();c&&i.pasteText(zt(c))}catch{}})();return}}}let We=0;function zt(o){return o.split(`\r
6
6
  `).join(`
7
7
  `).split(`
8
- `).join("\r")}async function Un(l){let c=On(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 g=Date.now();g-We<50||(We=g,i.pasteText(Rt(f)))}let ke=0;function qn(l){l.preventDefault(),ke++,Nt(l.dataTransfer)&&e.classList.add("terminal-drag-over")}function Yn(l){l.preventDefault(),l.dataTransfer&&(l.dataTransfer.dropEffect="copy")}function Jn(l){l.preventDefault(),ke--,ke<=0&&(ke=0,e.classList.remove("terminal-drag-over"))}async function Kn(l){l.preventDefault(),ke=0,e.classList.remove("terminal-drag-over");let c=Nt(l.dataTransfer);c&&await mt(c)}function jt(l){!Nn||l.key!=="Escape"||be||l.defaultPrevented||l.repeat||l.metaKey||l.ctrlKey||l.altKey||i.isFocused()&&(l.preventDefault(),l.stopPropagation(),fe("\x1B"))}e.addEventListener("paste",Un),e.addEventListener("dragenter",qn),e.addEventListener("dragover",Yn),e.addEventListener("dragleave",Jn),e.addEventListener("drop",Kn),document.addEventListener("keydown",jt,!0);function Vn(l){if(l.touches.length!==1){a=null;return}let c=l.touches[0];if(!c)return;_();let f=e.getBoundingClientRect(),g=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:g,tuiUp:k,sent:!1},l.stopPropagation()}function Xn(l){if(!a||l.touches.length!==1)return;let c=l.touches[0];if(!c)return;let f=c.clientY-a.startY,g=c.clientX-a.startX;if(!a.scrolling){if(Math.abs(f)<8||Math.abs(f)<Math.abs(g))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 se=k-a.lastT;se>0&&(a.velocity=V/se),ei(-V),a.lastX=c.clientX,a.lastY=c.clientY,a.lastT=k}function Qn(l){if(!a)return;let c=a.scrolling,f=a.zone,g=a.tuiUp,k=a.velocity;if(a=null,l.stopPropagation(),f==="tui"){c||(fe(g?"\x1B[5~":"\x1B[6~"),j(g),oe=Date.now()+500,l.preventDefault());return}if(!c){i.focus();return}oe=Date.now()+500,l.preventDefault(),k&&ae(k)}function Zn(l){a=null,_(),l.stopPropagation()}function Gn(l){l.pointerType==="touch"&&Date.now()<oe&&(l.preventDefault(),l.stopPropagation())}function ei(l){let c=i.cellHeight(),f=c>0?Math.round(l/c):l>0?1:-1;f===0&&(f=l>0?1:-1),i.scrollLines(f)}e.addEventListener("touchstart",Vn,{passive:!0,capture:!0}),e.addEventListener("touchmove",Xn,{passive:!1,capture:!0}),e.addEventListener("touchend",Qn,{passive:!1,capture:!0}),e.addEventListener("touchcancel",Zn,{passive:!0,capture:!0}),e.addEventListener("pointerup",Gn,!0);function Ot(){W()}window.addEventListener("resize",Ot),window.visualViewport?.addEventListener("resize",W),window.visualViewport?.addEventListener("scroll",W);let zt=new ResizeObserver(()=>W());zt.observe(e),document.fonts?.ready.then(()=>{W(),setTimeout(W,50),setTimeout(W,200)}),e.addEventListener("focusin",jn,!0);async function ti(){if(document.fonts?.ready)try{await Promise.race([document.fonts.ready,new Promise(l=>setTimeout(l,1e3))])}catch{}}return requestAnimationFrame(()=>{de()&&je(),(async()=>(await ti(),de()&&re({type:"resize",cols:i.cols,rows:i.rows}),$t(),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",Ot),zt.disconnect(),document.removeEventListener("keydown",jt,!0)},focus(){i.focus()},sendInput(l){fe(l)},toggleCopyMode(){Ht()}}})()}var m={catalog:null,templates:[],bots:[],approvals:[],activeId:null,items:new Map,ws:null,pollTimer:0,renderQueued:!1};function Ut(){try{return localStorage.getItem("tmux-web-token")||""}catch{return""}}async function $(e,t){let n=await fetch(e,{...t,headers:{"content-type":"application/json",Authorization:`Bearer ${Ut()}`,...t?.headers||{}}}),i=await n.text(),s=i?JSON.parse(i):null;if(!n.ok)throw new Error(s&&s.error||`HTTP ${n.status}`);return s}function d(e,t,n){let i=document.createElement(e);return t&&(i.className=t),n!==void 0&&(i.textContent=n),i}function 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 di(){let e=d("div","bots-section");e.id="bots-section";let t=d("div","bots-head"),n=d("span","bots-title","Bots"),i=d("span","bots-badge");i.hidden=!0,n.appendChild(i);let s=d("span","bots-head-actions"),r=d("button","bots-icon-btn","\u2699");r.title="Bot templates",r.onclick=()=>void wt();let o=d("button","bots-icon-btn","+");o.title="New bot from template",o.onclick=()=>void bi(),s.append(r,o),t.append(n,s);let a=d("div","bots-list");a.id="bots-list",e.append(t,a);let p=document.querySelector(".sidebar"),u=document.querySelector(".sidebar-footer");return p&&p.insertBefore(e,u||null),{list:a,badge:i}}var Le=null,Ue=null;function qe(){if(!Le)return;Le.textContent="";let e=new Map;for(let i of m.bots){if(i.parentBotId)continue;let s=i.projectPath;e.has(s)||e.set(s,[]),e.get(s).push(i)}e.size===0&&Le.appendChild(d("div","bots-empty","No bots yet"));for(let[i,s]of e){let r=d("div","bots-group"),o=d("div","bots-group-label",i.replace(/^.*\//,"")||i);o.title=i;let a=d("button","bots-icon-btn bots-group-add","+");a.title=`New bot in ${i}`,a.onclick=p=>{p.stopPropagation(),Ct(i)},o.appendChild(a),r.appendChild(o);for(let p of s){r.appendChild(Yt(p));for(let u of m.bots.filter(v=>v.parentBotId===p.id)){let v=Yt(u);v.classList.add("bots-row-child"),r.appendChild(v)}}Le.appendChild(r)}let t=m.approvals.length;Ue&&(Ue.hidden=t===0,Ue.textContent=String(t));let n=document.getElementById("bv-inbox-count");n&&(n.textContent=t?`(${t})`:"")}function Yt(e){let t=d("div","bots-row");t.dataset.botId=e.id,e.id===m.activeId&&t.classList.add("active");let n=d("span","bots-dot");n.style.background=qt(e.status);let i=d("span","bots-name",e.title),s=d("span","bots-meta",e.status.replace(/_/g," "));return t.append(n,i,s),t.onclick=()=>void Vt(e.id),t}function ci(){let e=d("div","bots-view");e.id="bots-view",e.hidden=!0;let t=d("div","bots-view-head"),n=d("div","bv-title"),i=d("span","bots-dot");i.id="bv-dot";let s=d("span","bv-title-text");s.id="bv-title";let r=d("span","bv-status");r.id="bv-status",n.append(i,s,r);let o=d("div","bv-actions"),a=d("button","btn","Needs you "),p=d("span");p.id="bv-inbox-count",a.appendChild(p),a.onclick=()=>void tn();let u=d("button","btn","Resume");u.onclick=()=>void Kt(D=>$(`/api/bots/${D}/resume`,{method:"POST"}).then(()=>X(!0)));let v=d("button","btn danger","Stop");v.onclick=()=>void Kt(D=>$(`/api/bots/${D}/stop`,{method:"POST"}).then(()=>X(!0)));let b=d("button","btn","Delete");b.onclick=()=>{m.activeId&&confirm("Delete this bot and its session?")&&$(`/api/bots/${m.activeId}`,{method:"DELETE"}).then(()=>{gt(),X(!0)})};let M=d("button","btn","\u2715");M.onclick=()=>gt(),o.append(a,u,v,b,M),t.append(n,o);let T=d("div","bots-messages");T.id="bots-messages";let E=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(),Jt())};let j=d("button","btn primary","Send");j.onclick=()=>void Jt(),E.append(S,j),e.append(t,T,E),document.querySelector(".main-area")?.appendChild(e),document.getElementById("bots-modal")||gi()}async function Jt(){let e=document.getElementById("bots-input");if(!e||!m.activeId||!e.value.trim())return;let t=e.value;e.value="";try{await $(`/api/bots/${m.activeId}/input`,{method:"POST",body:JSON.stringify({text:t})})}catch(n){Se({kind:"notice",level:"error",text:n instanceof Error?n.message:String(n)})}}function Kt(e){m.activeId&&e(m.activeId).catch(t=>Se({kind:"notice",level:"error",text:t instanceof Error?t.message:String(t)}))}function gt(){m.activeId=null;let e=document.getElementById("bots-view");e&&(e.hidden=!0);try{m.ws?.close()}catch{}m.ws=null,qe();let t=document.getElementById("main-placeholder");t&&(t.style.display="")}async function Vt(e){m.activeId=e,m.items.set(e,[]);let t=document.getElementById("bots-view");t&&(t.hidden=!1);let n=document.getElementById("main-placeholder");n&&(n.style.display="none");let i=document.getElementById("terminal-container");i&&(i.style.display="none");let s=document.getElementById("file-editor");s&&(s.style.display="none"),qe(),yt();try{m.ws?.close()}catch{}let r=location.protocol==="https:"?"wss:":"ws:",o=new WebSocket(`${r}//${location.host}/ws/bots/${encodeURIComponent(e)}?token=${encodeURIComponent(Ut())}`);m.ws=o,o.onmessage=a=>{try{Zt(JSON.parse(String(a.data)))}catch{}},o.onclose=()=>{m.activeId===e&&setTimeout(()=>{m.activeId===e&&X(!0)},1500)},await X(!0)}function Xt(){return m.bots.find(e=>e.id===m.activeId)||null}function Qt(){let e=Xt();if(!e)return;let t=document.getElementById("bv-title"),n=document.getElementById("bv-status"),i=document.getElementById("bv-dot");t&&(t.textContent=e.title),n&&(n.textContent=`${e.status.replace(/_/g," ")} \xB7 ${e.templateId} \xB7 ${e.projectPath}`),i&&(i.style.background=qt(e.status))}function Se(e,t=m.activeId){if(!t)return;let n=m.items.get(t)||[];n.push(e),m.items.set(t,n),t===m.activeId&&ce()}function ce(){m.renderQueued||(m.renderQueued=!0,requestAnimationFrame(()=>{m.renderQueued=!1,yt()}))}function yt(){let e=document.getElementById("bots-messages");if(!e||!m.activeId)return;let t=m.items.get(m.activeId)||[];e.textContent="";let n=null;for(let i of t)if(i.kind==="user"){let s=d("div","bv-msg bv-user");s.textContent=i.text,e.appendChild(s),n=null}else if(i.kind==="assistant"){let s=d("div","bv-msg bv-assistant");if(i.thinking){let o=d("details","bv-thinking");o.appendChild(d("summary",void 0,"thinking")),o.appendChild(d("div",void 0,i.thinking)),s.appendChild(o)}let r=d("div","bv-text");r.textContent=i.text,s.appendChild(r),e.appendChild(s),n=r}else if(i.kind==="tool")e.appendChild(pi(i)),n=null;else if(i.kind==="approval")e.appendChild(ui(i)),n=null;else if(i.kind==="notice"){let s=d("div",`bv-notice bv-notice-${i.level}`,i.text);e.appendChild(s)}n&&(n.scrollTop=n.scrollHeight),e.scrollTop=e.scrollHeight}function pi(e){let t=d("details","bv-tool");t.open=e.phase!=="end"||!!e.isError;let n=d("summary"),i=d("span","bv-tool-name",e.name);if(n.appendChild(i),e.phase!=="end"&&n.appendChild(d("span","bv-tool-phase",e.phase)),e.isError&&n.appendChild(d("span","bv-tool-error","error")),typeof e.durationMs=="number"&&n.appendChild(d("span","bv-tool-meta",`${Math.round(e.durationMs)}ms`)),t.appendChild(n),e.args!==void 0){let s=d("pre","bv-pre");s.textContent=typeof e.args=="string"?e.args:JSON.stringify(e.args,null,2),t.appendChild(s)}if(e.output){let s=d("pre","bv-pre bv-output");s.textContent=e.output,t.appendChild(s)}return t}function ui(e){let t=d("div","bv-approval"),n=e.approval;if(t.appendChild(d("div","bv-approval-title",n.title)),n.message&&t.appendChild(d("pre","bv-pre",n.message)),e.decided)return t.appendChild(d("div","bv-approval-decided",e.decided==="allowed"?"Allowed":"Denied")),t;let i=d("input","bv-reason");i.placeholder="reason (optional)";let s=d("div","bv-approval-actions"),r=d("button","btn primary","Allow"),o=d("button","btn danger","Deny"),a=async p=>{try{await $(`/api/bots/${n.botId}/approve`,{method:"POST",body:JSON.stringify({requestId:n.id,allow:p,reason:i.value||void 0})}),e.decided=p?"allowed":"denied",ce(),X(!0)}catch(u){Se({kind:"notice",level:"error",text:u instanceof Error?u.message:String(u)})}};return r.onclick=()=>void a(!0),o.onclick=()=>void a(!1),s.append(i,r,o),t.appendChild(s),t}function Zt(e){let t=String(e.type||""),n=m.activeId;if(!n)return;let i=m.items.get(n)||[];if(t==="snapshot")m.items.set(n,[]);else if(t==="user")Se({kind:"user",text:String(e.text||"")});else if(t==="status"){let s=Xt();s&&(s.status=String(e.status||s.status)),Qt(),hi()}else if(t==="message"){let s=e.message;if(!s||String(s.role||"")!=="assistant")return;let r=mi(s),o=fi(s),a=i[i.length-1];a&&a.kind==="assistant"?(a.text=r||a.text,a.thinking=o||a.thinking):i.push({kind:"assistant",text:r,thinking:o}),m.items.set(n,i),ce()}else if(t==="delta"){let s=String(e.kind||""),r=String(e.delta||""),o=i[i.length-1];(!o||o.kind!=="assistant")&&(i.push({kind:"assistant",text:"",thinking:""}),o=i[i.length-1]),o.kind==="assistant"&&(s==="text"?o.text+=r:s==="thinking"&&(o.thinking+=r)),m.items.set(n,i),ce()}else if(t==="tool"){let s=String(e.callId||""),r=i.find(a=>a.kind==="tool"&&a.callId===s),o=String(e.phase||"start");r?(r.phase=o,o==="update"&&e.output&&(r.output=String(e.output)),o==="end"&&(e.output&&(r.output=String(e.output)),r.isError=e.isError===!0,typeof e.durationMs=="number"&&(r.durationMs=e.durationMs))):i.push({kind:"tool",callId: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:o}),m.items.set(n,i),ce()}else if(t==="approval"){let s=e.approval;if(!s)return;let r=i;for(let o=r.length-1;o>=0;o--){let a=r[o];if(a.kind==="approval"&&a.approval.id===s.id){a.approval=s,s.state!=="pending"&&(a.decided=s.state==="allowed"?"allowed":"denied"),m.items.set(n,r),ce();return}}r.push({kind:"approval",approval:s}),m.items.set(n,r),ce()}else t==="notice"&&Se({kind:"notice",level:String(e.level||"info"),text:String(e.text||"")})}function mi(e){let t=e.content;return Array.isArray(t)?t.map(n=>n&&typeof n=="object"&&n.type==="text"?String(n.text||""):"").join(""):String(e.text||"")}function fi(e){let t=e.content;return Array.isArray(t)?t.map(n=>n&&typeof n=="object"&&n.type==="thinking"?String(n.thinking||""):"").join(""):""}async function X(e=!1){try{let[t,n]=await Promise.all([$("/api/bots"),$("/api/bots/approvals")]);if(m.bots=t,m.approvals=n,qe(),Qt(),e&&m.activeId){let i=await $(`/api/bots/${m.activeId}/events?limit=300`);vi(i)}}catch{}}async function hi(){try{m.bots=await $("/api/bots"),qe()}catch{}}function vi(e){if(m.activeId){m.items.set(m.activeId,[]);for(let t of e)Zt(t);yt()}}function gi(){let e=d("div","bots-modal");e.id="bots-modal",e.hidden=!0;let t=d("div","bots-modal-card"),n=d("div","bots-modal-head"),i=d("span");i.id="bots-modal-title";let s=d("button","btn","\u2715");s.onclick=()=>Ye(),n.append(i,s);let r=d("div","bots-modal-body");r.id="bots-modal-body",t.append(n,r),e.appendChild(t),e.onclick=o=>{o.target===e&&Ye()},document.body.appendChild(e)}function bt(e){let t=document.getElementById("bots-modal"),n=document.getElementById("bots-modal-title"),i=document.getElementById("bots-modal-body");if(!t||!i)throw new Error("modal missing");return n&&(n.textContent=e),i.textContent="",t.hidden=!1,i}function Ye(){let e=document.getElementById("bots-modal");e&&(e.hidden=!0)}async function yi(){return m.catalog||(m.catalog=await $("/api/bots/catalog")),m.catalog}async function Gt(){return m.templates=await $("/api/bots/templates"),m.templates}async function wt(){let e=bt("Bot templates"),[t,n]=await Promise.all([yi(),Gt()]),i=d("div","bv-template-list");for(let r of n){let o=d("div","bv-template-row");o.appendChild(d("span","bv-template-name",r.manifest.name)),o.appendChild(d("span","bv-template-desc",r.manifest.description||""));let a=d("button","btn","Edit");a.onclick=()=>en(e,t,r);let p=d("button","btn danger","Delete");p.onclick=()=>{confirm(`Delete template ${r.manifest.name}?`)&&$(`/api/bots/templates/${r.id}`,{method:"DELETE"}).then(()=>wt())};let u=d("span","bv-template-actions");u.append(a,p),o.appendChild(u),i.appendChild(o)}n.length===0&&i.appendChild(d("div","bots-empty","No templates yet")),e.appendChild(i);let s=d("button","btn primary","New template");s.onclick=()=>en(e,t,null),e.appendChild(s)}function Et(e,t,n){let i=d("div","bv-field");i.appendChild(d("label","bv-label",e));let s=d("div","bv-check-grid"),r=[];for(let o of t){let a=d("label","bv-check"),p=document.createElement("input");p.type="checkbox",p.checked=n.includes(o.id),a.append(p,d("span",void 0,o.label)),o.hint&&(a.title=o.hint),s.appendChild(a),r.push({id:o.id,input:p})}return i.appendChild(s),{element:i,get:()=>r.filter(o=>o.input.checked).map(o=>o.id)}}function en(e,t,n){e.textContent="";let i=n?JSON.parse(JSON.stringify(n.manifest)):{name:"new-bot",description:""},s=d("input","bv-input");s.value=i.name,s.placeholder="Template name";let r=d("input","bv-input");r.value=i.description||"",r.placeholder="One line description";let o=d("textarea","bv-textarea");o.rows=6,o.value=i.system||"",o.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})),i.skills||[]),p=Et("Extensions (Pi builtins + library)",t.extensions.map(h=>({id:h.id,label:`${h.name}${h.kind==="builtin"?" (builtin)":""}`,hint:h.description})),(i.extensions||[]).map(h=>h.replace(/^.*\//,"").replace(/\.(js|ts)$/,""))),u=Et("Prompt templates",t.prompts.map(h=>({id:h.id,label:h.name})),i.prompts||[]),v=d("select","bv-input");v.appendChild(new Option("none",""));for(let h of t.mcp)v.appendChild(new Option(h.name,h.id));i.mcp&&(v.value=t.mcp.find(h=>JSON.stringify(h.servers)===JSON.stringify(i.mcp?.mcpServers))?.id||"");let b=d("div","bv-field");b.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=(i.tools?.allow||[]).includes(h.name)||!i.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})}b.appendChild(M);let E=d("input","bv-input");E.value=(i.tools?.deny||[]).join(", "),E.placeholder="Always deny (comma separated), e.g. bash, write";let S=d("textarea","bv-textarea");S.rows=2,S.value=(i.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}`));i.model?.provider&&i.model?.id&&(j.value=`${i.model.provider}
11
- ${i.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));i.model?.thinking&&(D.value=i.model.thinking);let _=d("select","bv-input");for(let h of["supervised","auto-accept-edits","full-access"])_.appendChild(new Option(h,h));_.value=i.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=i.projectResources||"ignore";let oe=d("label","bv-check"),O=document.createElement("input");O.type="checkbox",O.checked=!!i.orchestrator,oe.append(O,d("span",void 0,"Super bot: gets orchestration tools (create/stop/status child bots)"));let N=(h,z)=>{let x=d("div","bv-field");return x.appendChild(d("label","bv-label",h)),x.appendChild(z),x};e.append(N("Name",s),N("Description",r),N("System prompt",o),a.element,p.element,u.element,N("MCP preset",v),b,N("Always deny tools",E),N("Packages",S),N("Model",j),N("Thinking level",D),N("Approval mode",_),N("Project resources",ae),oe);let ie=d("button","btn primary",n?"Save template":"Create template");ie.onclick=async()=>{let[h,z]=j.value.split(`
12
- `),x=t.mcp.find(B=>B.id===v.value),le={name:s.value.trim()||"bot",description:r.value.trim()||void 0,system:o.value.trim()||void 0,skills:a.get(),extensions:p.get().map(B=>(B.startsWith("builtin:"),B)),prompts:u.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:E.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:n?.id,manifest:le})}),Ye(),await wt()}catch(B){alert(B instanceof Error?B.message:String(B))}},e.appendChild(ie)}async function bi(){return Ct("")}async function Ct(e){let t=bt("New bot"),n=await Gt();if(n.length===0){t.appendChild(d("div","bots-empty","Create a template first (\u2699)."));return}let i=d("select","bv-input");for(let u of n)i.appendChild(new Option(u.manifest.name,u.id));let s=d("input","bv-input");s.placeholder="Title (defaults to template name)";let r=d("input","bv-input");r.placeholder="/path/to/project";let o=e||m.bots[0]?.projectPath||"";r.value=o;let a=d("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(Je("Template",i),Je("Title",s),Je("Project path",r),Je("Workspace",a));let p=d("button","btn primary","Create bot");p.onclick=async()=>{try{let u=await $("/api/bots",{method:"POST",body:JSON.stringify({templateId:i.value,title:s.value.trim()||void 0,projectPath:r.value.trim()||void 0,isolation:a.value})});Ye(),await X(!0),await Vt(u.id)}catch(u){alert(u instanceof Error?u.message:String(u))}},t.appendChild(p)}function Je(e,t){let n=d("div","bv-field");return n.appendChild(d("label","bv-label",e)),n.appendChild(t),n}async function tn(){let e=bt("Needs you");if(m.approvals=await $("/api/bots/approvals"),m.approvals.length===0){e.appendChild(d("div","bots-empty","Nothing waiting."));return}for(let t of m.approvals){let n=d("div","bv-approval");n.appendChild(d("div","bv-approval-title",`${t.botTitle}: ${t.title}`)),t.message&&n.appendChild(d("pre","bv-pre",t.message));let i=d("input","bv-reason");i.placeholder="reason (optional)";let s=d("div","bv-approval-actions"),r=d("button","btn primary","Allow"),o=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:i.value||void 0})}),await X(!0),await tn()};r.onclick=()=>void a(!0),o.onclick=()=>void a(!1),s.append(i,r,o),n.appendChild(s),e.appendChild(n)}}function wi(){if(document.getElementById("bots-section"))return;let e=di();Le=e.list,Ue=e.badge,ci(),document.addEventListener("click",t=>{let n=t.target;n&&n.closest(".session-item")&&m.activeId&&gt()},!0),X(!0),m.pollTimer=window.setInterval(()=>{document.hidden||X()},6e3),window.addEventListener("beforeunload",()=>window.clearInterval(m.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,H=Te;window.__tmuxWebScopeAgent=Te;var kt="sessions",G="",Ke="",Ve="",nn="";function P(e){return H?"/a/"+encodeURIComponent(H)+e:e}var y=document.getElementById("sidebar-content"),pe=document.getElementById("main-placeholder"),U=document.getElementById("terminal-container"),Be=document.getElementById("file-editor"),Ei=document.getElementById("fe-path"),Y=document.getElementById("fe-status"),Me=document.getElementById("fe-content"),ue=document.getElementById("fe-save"),Ci=document.getElementById("fe-delete"),ki=document.getElementById("fe-back"),sn=document.getElementById("fe-new-name"),xi=document.getElementById("fe-new-btn"),xt=document.getElementById("settings-backdrop"),an=document.getElementById("settings-popover"),on=document.querySelector(".sidebar"),ln="tmux-web-force-narrow";function Xe(){try{return localStorage.getItem(ln)==="1"}catch{return!1}}function rn(){document.documentElement.classList.toggle("force-narrow",Xe()),Xe()&&dn()&&Qe()}function dn(){return Xe()?!0:window.matchMedia("(max-width: 640px)").matches}function Qe(){dn()&&on.classList.add("collapsed")}function cn(){on.classList.remove("collapsed")}document.getElementById("mode-sessions").addEventListener("click",()=>{cn(),pn("sessions")}),document.getElementById("mode-files").addEventListener("click",()=>{cn(),pn("files")});function pn(e){kt=e,document.querySelectorAll(".mode-btn").forEach(n=>n.classList.remove("active"));let t=document.getElementById(e==="sessions"?"mode-sessions":"mode-files");t&&t.classList.add("active"),e==="sessions"?(Lt="",ee()):Ri()}var Lt="";async function ee(){if(kt!=="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===Lt)return;Lt=n,Bi(t)}catch{y.innerHTML+='<div class="file-tree-empty">Failed to load sessions</div>'}let e=document.getElementById("ns-btn");e&&e.addEventListener("click",()=>{let t=window.__openNewSessionModal;typeof t=="function"?t():document.getElementById("new-session-modal")?.classList.add("open")}),Dt()}var un="tmux-web-sidebar-group-collapsed";function mn(){try{return new Set(JSON.parse(localStorage.getItem(un)||"[]"))}catch{return new Set}}function Li(e){try{localStorage.setItem(un,JSON.stringify([...e]))}catch{}}function Si(e,t,n){if(!e)return"\u2026";let i=n&&(e===n||e.startsWith(n+"/"))?"~"+e.slice(n.length):e,s=i.split("/").filter(Boolean);if(s.length===0)return e;for(let r=1;r<=s.length;r++){let o=s.slice(-r).join("/");if(!t.some(a=>!a||a===e?!1:(n&&(a===n||a.startsWith(n+"/"))?"~"+a.slice(n.length):a).split("/").filter(Boolean).slice(-r).join("/")===o))return o}return i}function fn(e,t,n,i=!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 r=[...s.keys()],o=mn();for(let[a,p]of s){let u=Si(a,r,t),v=o.has(a),b=document.createElement("div");b.className="session-group-header"+(v?" collapsed":""),b.title=a||"No working directory",b.innerHTML=`<span class="sg-folder">&#128193;</span><span class="sg-label">${w(u)}</span>`,b.addEventListener("click",()=>{let T=mn(),E=b.nextElementSibling;T.has(a)?(T.delete(a),b.classList.remove("collapsed"),E?.classList.remove("collapsed")):(T.add(a),b.classList.add("collapsed"),E?.classList.add("collapsed")),Li(T)});let M=document.createElement("div");M.className="session-group-body"+(v?" collapsed":"");for(let T of p)M.appendChild(n?Ii(T,n,i):Ti(T));y.appendChild(b),y.appendChild(M)}}function Ii(e,t,n){let i=document.createElement("div");i.className="session-item"+(e.name===L&&H===t?" active":"")+(n?"":" session-offline"),i.setAttribute("data-session",e.name),i.setAttribute("data-agent",t),i.innerHTML=`<svg viewBox="0 0 24 24" fill="currentColor"><path d="${e.attached?"M19 4H5a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6a2 2 0 0 0-2-2zm0 14H5V6h14v12z":"M4 6h16v2H4V6zm0 5h16v2H4v-2zm0 5h16v2H4v-2z"}"></svg>
8
+ `).join("\r")}async function qn(o){let c=zn(o.clipboardData);if(c){o.preventDefault(),o.stopPropagation();let C=Date.now();if(C-We<50)return;We=C,await ht(c);return}let f=o.clipboardData?.getData("text/plain");if(!f)return;o.preventDefault(),o.stopPropagation();let b=Date.now();b-We<50||(We=b,i.pasteText(zt(f)))}let xe=0;function Yn(o){o.preventDefault(),xe++,jt(o.dataTransfer)&&e.classList.add("terminal-drag-over")}function Jn(o){o.preventDefault(),o.dataTransfer&&(o.dataTransfer.dropEffect="copy")}function Kn(o){o.preventDefault(),xe--,xe<=0&&(xe=0,e.classList.remove("terminal-drag-over"))}async function Vn(o){o.preventDefault(),xe=0,e.classList.remove("terminal-drag-over");let c=jt(o.dataTransfer);c&&await ht(c)}function Ut(o){!Fn||o.key!=="Escape"||we||o.defaultPrevented||o.repeat||o.metaKey||o.ctrlKey||o.altKey||i.isFocused()&&(o.preventDefault(),o.stopPropagation(),fe("\x1B"))}e.addEventListener("paste",qn),e.addEventListener("dragenter",Yn),e.addEventListener("dragover",Jn),e.addEventListener("dragleave",Kn),e.addEventListener("drop",Vn),document.addEventListener("keydown",Ut,!0);function Xn(o){if(o.touches.length!==1){s=null;return}let c=o.touches[0];if(!c)return;W();let f=e.getBoundingClientRect(),b=c.clientX-f.left<f.width*.4?"tui":"history",C=c.clientY-f.top<f.height*.5;s={startX:c.clientX,startY:c.clientY,lastX:c.clientX,lastY:c.clientY,lastT:performance.now(),velocity:0,scrolling:!1,zone:b,tuiUp:C,sent:!1},o.stopPropagation()}function Qn(o){if(!s||o.touches.length!==1)return;let c=o.touches[0];if(!c)return;let f=c.clientY-s.startY,b=c.clientX-s.startX;if(!s.scrolling){if(Math.abs(f)<8||Math.abs(f)<Math.abs(b))return;s.scrolling=!0,oe=Date.now()+500}o.preventDefault(),o.stopPropagation();let C=performance.now(),V=c.clientY-s.lastY;if(s.zone==="tui"){s.sent||(s.sent=!0,fe(s.tuiUp?"\x1B[5~":"\x1B[6~"),O(s.tuiUp)),s.lastX=c.clientX,s.lastY=c.clientY,s.lastT=C;return}let ae=C-s.lastT;ae>0&&(s.velocity=V/ae),ti(-V),s.lastX=c.clientX,s.lastY=c.clientY,s.lastT=C}function Zn(o){if(!s)return;let c=s.scrolling,f=s.zone,b=s.tuiUp,C=s.velocity;if(s=null,o.stopPropagation(),f==="tui"){c||(fe(b?"\x1B[5~":"\x1B[6~"),O(b),oe=Date.now()+500,o.preventDefault());return}if(!c){i.focus();return}oe=Date.now()+500,o.preventDefault(),C&&le(C)}function Gn(o){s=null,W(),o.stopPropagation()}function ei(o){o.pointerType==="touch"&&Date.now()<oe&&(o.preventDefault(),o.stopPropagation())}function ti(o){let c=i.cellHeight(),f=c>0?Math.round(o/c):o>0?1:-1;f===0&&(f=o>0?1:-1),i.scrollLines(f)}e.addEventListener("touchstart",Xn,{passive:!0,capture:!0}),e.addEventListener("touchmove",Qn,{passive:!1,capture:!0}),e.addEventListener("touchend",Zn,{passive:!1,capture:!0}),e.addEventListener("touchcancel",Gn,{passive:!0,capture:!0}),e.addEventListener("pointerup",ei,!0);function Wt(){U()}window.addEventListener("resize",Wt),window.visualViewport?.addEventListener("resize",U),window.visualViewport?.addEventListener("scroll",U);let _t=new ResizeObserver(()=>U());_t.observe(e),document.fonts?.ready.then(()=>{U(),setTimeout(U,50),setTimeout(U,200)}),e.addEventListener("focusin",Hn,!0);async function ni(){if(document.fonts?.ready)try{await Promise.race([document.fonts.ready,new Promise(o=>setTimeout(o,1e3))])}catch{}}return requestAnimationFrame(()=>{ce()&&He(),(async()=>(await ni(),ce()&&de({type:"resize",cols:i.cols,rows:i.rows}),Ft(),U()))()}),{destroy(){if(L=!0,W(),he(!1),Ce&&clearTimeout(Ce),document.removeEventListener("mousemove",vt,!0),document.removeEventListener("mouseup",gt,!0),a){try{a.close(1e3,"session switch")}catch{}a=void 0}e.innerHTML="",e.classList.remove("terminal-pending"),window.removeEventListener("resize",Wt),_t.disconnect(),document.removeEventListener("keydown",Ut,!0)},focus(){i.focus()},sendInput(o){fe(o)},toggleCopyMode(){Ht()}}})()}var m={catalog:null,templates:[],bots:[],approvals:[],activeId:null,items:new Map,ws:null,pollTimer:0,renderQueued:!1};function yt(){try{return localStorage.getItem("tmux-web-token")||""}catch{return""}}async function $(e,t){let n=await fetch(e,{...t,headers:{"content-type":"application/json",Authorization:`Bearer ${yt()}`,...t?.headers||{}}}),i=await n.text(),a=i?JSON.parse(i):null;if(!n.ok)throw new Error(a&&a.error||`HTTP ${n.status}`);return a}function d(e,t,n){let i=document.createElement(e);return t&&(i.className=t),n!==void 0&&(i.textContent=n),i}function Jt(e){return e==="running"?"var(--panel-success)":e==="waiting_approval"||e==="waiting_input"?"#e0a23c":e==="failed"?"var(--panel-danger, #e5534b)":e==="completed"?"var(--panel-accent)":"var(--panel-muted)"}function ci(){let e=d("div","bots-section");e.id="bots-section";let t=d("div","bots-head"),n=d("span","bots-title","Bots"),i=d("span","bots-badge");i.hidden=!0,n.appendChild(i);let a=d("span","bots-head-actions"),r=d("button","bots-icon-btn","\u2699");r.title="Bot templates",r.onclick=()=>void Ke();let l=d("button","bots-icon-btn","+");l.title="New bot from template",l.onclick=()=>void wi(),a.append(r,l),t.append(n,a);let s=d("div","bots-list");s.id="bots-list",e.append(t,s);let p=document.querySelector(".sidebar"),u=document.querySelector(".sidebar-footer");return p&&p.insertBefore(e,u||null),{list:s,badge:i}}var Se=null,qe=null;function Ye(){if(!Se)return;Se.textContent="";let e=new Map;for(let i of m.bots){if(i.parentBotId)continue;let a=i.projectPath;e.has(a)||e.set(a,[]),e.get(a).push(i)}e.size===0&&Se.appendChild(d("div","bots-empty","No bots yet"));for(let[i,a]of e){let r=d("div","bots-group"),l=d("div","bots-group-label",i.replace(/^.*\//,"")||i);l.title=i;let s=d("button","bots-icon-btn bots-group-add","+");s.title=`New bot in ${i}`,s.onclick=p=>{p.stopPropagation(),xt(i)},l.appendChild(s),r.appendChild(l);for(let p of a){r.appendChild(Kt(p));for(let u of m.bots.filter(h=>h.parentBotId===p.id)){let h=Kt(u);h.classList.add("bots-row-child"),r.appendChild(h)}}Se.appendChild(r)}let t=m.approvals.length;qe&&(qe.hidden=t===0,qe.textContent=String(t));let n=document.getElementById("bv-inbox-count");n&&(n.textContent=t?`(${t})`:"")}function Kt(e){let t=d("div","bots-row");t.dataset.botId=e.id,e.id===m.activeId&&t.classList.add("active");let n=d("span","bots-dot");n.style.background=Jt(e.status);let i=d("span","bots-name",e.title),a=d("span","bots-meta",e.status.replace(/_/g," "));return t.append(n,i,a),t.onclick=()=>void Qt(e.id),t}function pi(){let e=d("div","bots-view");e.id="bots-view",e.hidden=!0;let t=d("div","bots-view-head"),n=d("div","bv-title"),i=d("span","bots-dot");i.id="bv-dot";let a=d("span","bv-title-text");a.id="bv-title";let r=d("span","bv-status");r.id="bv-status",n.append(i,a,r);let l=d("div","bv-actions"),s=d("button","btn","Needs you "),p=d("span");p.id="bv-inbox-count",s.appendChild(p),s.onclick=()=>void an();let u=d("button","btn","Resume");u.onclick=()=>void Xt(D=>$(`/api/bots/${D}/resume`,{method:"POST"}).then(()=>X(!0)));let h=d("button","btn danger","Stop");h.onclick=()=>void Xt(D=>$(`/api/bots/${D}/stop`,{method:"POST"}).then(()=>X(!0)));let g=d("button","btn","Delete");g.onclick=()=>{m.activeId&&confirm("Delete this bot and its session?")&&$(`/api/bots/${m.activeId}`,{method:"DELETE"}).then(()=>{wt(),X(!0)})};let x=d("button","btn","\u2715");x.onclick=()=>wt(),l.append(s,u,h,g,x),t.append(n,l);let B=d("div","bots-messages");B.id="bots-messages";let E=d("div","bots-composer"),I=d("textarea");I.id="bots-input",I.rows=1,I.placeholder="Message the bot\u2026 (Enter to send, Shift+Enter for newline)",I.onkeydown=D=>{D.key==="Enter"&&!D.shiftKey&&(D.preventDefault(),Vt())};let O=d("button","btn primary","Send");O.onclick=()=>void Vt(),E.append(I,O),e.append(t,B,E),document.querySelector(".main-area")?.appendChild(e),document.getElementById("bots-modal")||bi()}async function Vt(){let e=document.getElementById("bots-input");if(!e||!m.activeId||!e.value.trim())return;let t=e.value;e.value="";try{await $(`/api/bots/${m.activeId}/input`,{method:"POST",body:JSON.stringify({text:t})})}catch(n){Ie({kind:"notice",level:"error",text:n instanceof Error?n.message:String(n)})}}function Xt(e){m.activeId&&e(m.activeId).catch(t=>Ie({kind:"notice",level:"error",text:t instanceof Error?t.message:String(t)}))}function wt(){m.activeId=null;let e=document.getElementById("bots-view");e&&(e.hidden=!0);try{m.ws?.close()}catch{}m.ws=null,Ye();let t=document.getElementById("main-placeholder");t&&(t.style.display="")}async function Qt(e){m.activeId=e,m.items.set(e,[]);let t=document.getElementById("bots-view");t&&(t.hidden=!1);let n=document.getElementById("main-placeholder");n&&(n.style.display="none");let i=document.getElementById("terminal-container");i&&(i.style.display="none");let a=document.getElementById("file-editor");a&&(a.style.display="none"),Ye(),Et();try{m.ws?.close()}catch{}let r=location.protocol==="https:"?"wss:":"ws:",l=new WebSocket(`${r}//${location.host}/ws/bots/${encodeURIComponent(e)}?token=${encodeURIComponent(yt())}`);m.ws=l,l.onmessage=s=>{try{en(JSON.parse(String(s.data)))}catch{}},l.onclose=()=>{m.activeId===e&&setTimeout(()=>{m.activeId===e&&X(!0)},1500)},await X(!0)}function Zt(){return m.bots.find(e=>e.id===m.activeId)||null}function Gt(){let e=Zt();if(!e)return;let t=document.getElementById("bv-title"),n=document.getElementById("bv-status"),i=document.getElementById("bv-dot");t&&(t.textContent=e.title),n&&(n.textContent=`${e.status.replace(/_/g," ")} \xB7 ${e.templateId} \xB7 ${e.projectPath}`),i&&(i.style.background=Jt(e.status))}function Ie(e,t=m.activeId){if(!t)return;let n=m.items.get(t)||[];n.push(e),m.items.set(t,n),t===m.activeId&&pe()}function pe(){m.renderQueued||(m.renderQueued=!0,requestAnimationFrame(()=>{m.renderQueued=!1,Et()}))}function Et(){let e=document.getElementById("bots-messages");if(!e||!m.activeId)return;let t=m.items.get(m.activeId)||[];e.textContent="";let n=null;for(let i of t)if(i.kind==="user"){let a=d("div","bv-msg bv-user");a.textContent=i.text,e.appendChild(a),n=null}else if(i.kind==="assistant"){let a=d("div","bv-msg bv-assistant");if(i.thinking){let l=d("details","bv-thinking");l.appendChild(d("summary",void 0,"thinking")),l.appendChild(d("div",void 0,i.thinking)),a.appendChild(l)}let r=d("div","bv-text");r.textContent=i.text,a.appendChild(r),e.appendChild(a),n=r}else if(i.kind==="tool")e.appendChild(ui(i)),n=null;else if(i.kind==="approval")e.appendChild(mi(i)),n=null;else if(i.kind==="notice"){let a=d("div",`bv-notice bv-notice-${i.level}`,i.text);e.appendChild(a)}n&&(n.scrollTop=n.scrollHeight),e.scrollTop=e.scrollHeight}function ui(e){let t=d("details","bv-tool");t.open=e.phase!=="end"||!!e.isError;let n=d("summary"),i=d("span","bv-tool-name",e.name);if(n.appendChild(i),e.phase!=="end"&&n.appendChild(d("span","bv-tool-phase",e.phase)),e.isError&&n.appendChild(d("span","bv-tool-error","error")),typeof e.durationMs=="number"&&n.appendChild(d("span","bv-tool-meta",`${Math.round(e.durationMs)}ms`)),t.appendChild(n),e.args!==void 0){let a=d("pre","bv-pre");a.textContent=typeof e.args=="string"?e.args:JSON.stringify(e.args,null,2),t.appendChild(a)}if(e.output){let a=d("pre","bv-pre bv-output");a.textContent=e.output,t.appendChild(a)}return t}function mi(e){let t=d("div","bv-approval"),n=e.approval;if(t.appendChild(d("div","bv-approval-title",n.title)),n.message&&t.appendChild(d("pre","bv-pre",n.message)),e.decided)return t.appendChild(d("div","bv-approval-decided",e.decided==="allowed"?"Allowed":"Denied")),t;let i=d("input","bv-reason");i.placeholder="reason (optional)";let a=d("div","bv-approval-actions"),r=d("button","btn primary","Allow"),l=d("button","btn danger","Deny"),s=async p=>{try{await $(`/api/bots/${n.botId}/approve`,{method:"POST",body:JSON.stringify({requestId:n.id,allow:p,reason:i.value||void 0})}),e.decided=p?"allowed":"denied",pe(),X(!0)}catch(u){Ie({kind:"notice",level:"error",text:u instanceof Error?u.message:String(u)})}};return r.onclick=()=>void s(!0),l.onclick=()=>void s(!1),a.append(i,r,l),t.appendChild(a),t}function en(e){let t=String(e.type||""),n=m.activeId;if(!n)return;let i=m.items.get(n)||[];if(t==="snapshot")m.items.set(n,[]);else if(t==="user")Ie({kind:"user",text:String(e.text||"")});else if(t==="status"){let a=Zt();a&&(a.status=String(e.status||a.status)),Gt(),vi()}else if(t==="message"){let a=e.message;if(!a||String(a.role||"")!=="assistant")return;let r=fi(a),l=hi(a),s=i[i.length-1];s&&s.kind==="assistant"?(s.text=r||s.text,s.thinking=l||s.thinking):i.push({kind:"assistant",text:r,thinking:l}),m.items.set(n,i),pe()}else if(t==="delta"){let a=String(e.kind||""),r=String(e.delta||""),l=i[i.length-1];(!l||l.kind!=="assistant")&&(i.push({kind:"assistant",text:"",thinking:""}),l=i[i.length-1]),l.kind==="assistant"&&(a==="text"?l.text+=r:a==="thinking"&&(l.thinking+=r)),m.items.set(n,i),pe()}else if(t==="tool"){let a=String(e.callId||""),r=i.find(s=>s.kind==="tool"&&s.callId===a),l=String(e.phase||"start");r?(r.phase=l,l==="update"&&e.output&&(r.output=String(e.output)),l==="end"&&(e.output&&(r.output=String(e.output)),r.isError=e.isError===!0,typeof e.durationMs=="number"&&(r.durationMs=e.durationMs))):i.push({kind:"tool",callId:a,name:String(e.name||"tool"),args:e.args,output:e.output?String(e.output):void 0,isError:e.isError===!0,durationMs:typeof e.durationMs=="number"?e.durationMs:void 0,phase:l}),m.items.set(n,i),pe()}else if(t==="approval"){let a=e.approval;if(!a)return;let r=i;for(let l=r.length-1;l>=0;l--){let s=r[l];if(s.kind==="approval"&&s.approval.id===a.id){s.approval=a,a.state!=="pending"&&(s.decided=a.state==="allowed"?"allowed":"denied"),m.items.set(n,r),pe();return}}r.push({kind:"approval",approval:a}),m.items.set(n,r),pe()}else t==="notice"&&Ie({kind:"notice",level:String(e.level||"info"),text:String(e.text||"")})}function fi(e){let t=e.content;return Array.isArray(t)?t.map(n=>n&&typeof n=="object"&&n.type==="text"?String(n.text||""):"").join(""):String(e.text||"")}function hi(e){let t=e.content;return Array.isArray(t)?t.map(n=>n&&typeof n=="object"&&n.type==="thinking"?String(n.thinking||""):"").join(""):""}async function X(e=!1){try{let[t,n]=await Promise.all([$("/api/bots"),$("/api/bots/approvals")]);if(m.bots=t,m.approvals=n,Ye(),Gt(),e&&m.activeId){let i=await $(`/api/bots/${m.activeId}/events?limit=300`);gi(i)}}catch{}}async function vi(){try{m.bots=await $("/api/bots"),Ye()}catch{}}function gi(e){if(m.activeId){m.items.set(m.activeId,[]);for(let t of e)en(t);Et()}}function bi(){let e=d("div","bots-modal");e.id="bots-modal",e.hidden=!0;let t=d("div","bots-modal-card"),n=d("div","bots-modal-head"),i=d("span");i.id="bots-modal-title";let a=d("button","btn","\u2715");a.onclick=()=>Je(),n.append(i,a);let r=d("div","bots-modal-body");r.id="bots-modal-body",t.append(n,r),e.appendChild(t),e.onclick=l=>{l.target===e&&Je()},document.body.appendChild(e)}function kt(e){let t=document.getElementById("bots-modal"),n=document.getElementById("bots-modal-title"),i=document.getElementById("bots-modal-body");if(!t||!i)throw new Error("modal missing");return n&&(n.textContent=e),i.textContent="",t.hidden=!1,i}function Je(){let e=document.getElementById("bots-modal");e&&(e.hidden=!0)}async function yi(){return m.catalog||(m.catalog=await $("/api/bots/catalog")),m.catalog}async function tn(){return m.templates=await $("/api/bots/templates"),m.templates}async function Ke(){let e=kt("Bot templates"),[t,n]=await Promise.all([yi(),tn()]),i=d("div","bv-template-list");for(let p of n){let u=d("div","bv-template-row");u.appendChild(d("span","bv-template-name",p.manifest.name)),u.appendChild(d("span","bv-template-desc",p.manifest.description||""));let h=d("button","btn","Edit");h.onclick=()=>nn(e,t,p);let g=d("button","btn danger","Delete");g.onclick=()=>{confirm(`Delete template ${p.manifest.name}?`)&&$(`/api/bots/templates/${p.id}`,{method:"DELETE"}).then(()=>Ke())};let x=d("span","bv-template-actions");x.append(h,g),u.appendChild(x),i.appendChild(u)}n.length===0&&i.appendChild(d("div","bots-empty","No templates yet")),e.appendChild(i);let a=d("div","bv-template-actions"),r=d("button","btn primary","New template");r.onclick=()=>nn(e,t,null);let l=d("button","btn","Export");l.title="Download templates + library as JSON",l.onclick=()=>{(async()=>{try{let p=await fetch("/api/bots/export",{headers:{Authorization:`Bearer ${yt()}`}});if(!p.ok)throw new Error(`HTTP ${p.status}`);let u=await p.blob(),h=document.createElement("a");h.href=URL.createObjectURL(u),h.download=`tmux-weblink-bots-${new Date().toISOString().slice(0,10)}.json`,h.click(),setTimeout(()=>URL.revokeObjectURL(h.href),2e3)}catch(p){alert(p instanceof Error?p.message:String(p))}})()};let s=d("button","btn","Import");s.title="Restore templates from a JSON bundle",s.onclick=()=>{let p=document.createElement("input");p.type="file",p.accept="application/json,.json",p.onchange=()=>{let u=p.files?.[0];u&&(async()=>{try{let h=JSON.parse(await u.text()),g=await $("/api/bots/import",{method:"POST",body:JSON.stringify(h)});alert(`Imported ${g.templates} templates, ${g.files} library files (${g.skipped} kept)`),await Ke()}catch(h){alert(h instanceof Error?h.message:String(h))}})()},p.click()},a.append(r,l,s),e.appendChild(a)}function Ct(e,t,n){let i=d("div","bv-field");i.appendChild(d("label","bv-label",e));let a=d("div","bv-check-grid"),r=[];for(let l of t){let s=d("label","bv-check"),p=document.createElement("input");p.type="checkbox",p.checked=n.includes(l.id),s.append(p,d("span",void 0,l.label)),l.hint&&(s.title=l.hint),a.appendChild(s),r.push({id:l.id,input:p})}return i.appendChild(a),{element:i,get:()=>r.filter(l=>l.input.checked).map(l=>l.id)}}function nn(e,t,n){e.textContent="";let i=n?JSON.parse(JSON.stringify(n.manifest)):{name:"new-bot",description:""},a=d("input","bv-input");a.value=i.name,a.placeholder="Template name";let r=d("input","bv-input");r.value=i.description||"",r.placeholder="One line description";let l=d("textarea","bv-textarea");l.rows=6,l.value=i.system||"",l.placeholder="System prompt for this bot (written to SYSTEM.md)";let s=Ct("Skills",t.skills.map(v=>({id:v.id,label:v.name,hint:v.description})),i.skills||[]),p=Ct("Extensions (Pi builtins + library)",t.extensions.map(v=>({id:v.id,label:`${v.name}${v.kind==="builtin"?" (builtin)":""}`,hint:v.description})),(i.extensions||[]).map(v=>v.replace(/^.*\//,"").replace(/\.(js|ts)$/,""))),u=Ct("Prompt templates",t.prompts.map(v=>({id:v.id,label:v.name})),i.prompts||[]),h=d("select","bv-input");h.appendChild(new Option("none",""));for(let v of t.mcp)h.appendChild(new Option(v.name,v.id));i.mcp&&(h.value=t.mcp.find(v=>JSON.stringify(v.servers)===JSON.stringify(i.mcp?.mcpServers))?.id||"");let g=d("div","bv-field");g.appendChild(d("label","bv-label","Tools (allow list; deny always blocks)"));let x=d("div","bv-check-grid"),B=[];for(let v of t.tools){let z=d("label","bv-check"),L=document.createElement("input");L.type="checkbox",L.checked=(i.tools?.allow||[]).includes(v.name)||!i.tools?.allow?.length&&["read","grep","find","ls","edit","write","bash"].includes(v.name),z.append(L,d("span",void 0,v.name)),x.appendChild(z),B.push({name:v.name,input:L})}g.appendChild(x);let E=d("input","bv-input");E.value=(i.tools?.deny||[]).join(", "),E.placeholder="Always deny (comma separated), e.g. bash, write";let I=d("textarea","bv-textarea");I.rows=2,I.value=(i.packages||[]).join(`
9
+ `),I.placeholder="Pi packages, one per line (npm:@scope/pkg@1.2.3, git:..., ./path)";let O=d("select","bv-input");O.appendChild(new Option("default (Pi settings)",""));for(let v of t.models)O.appendChild(new Option(`${v.provider}/${v.model}`,`${v.provider}
10
+ ${v.model}`));i.model?.provider&&i.model?.id&&(O.value=`${i.model.provider}
11
+ ${i.model.id}`);let D=d("select","bv-input");for(let v of["","off","minimal","low","medium","high","xhigh","max"])D.appendChild(new Option(v||"default",v));i.model?.thinking&&(D.value=i.model.thinking);let W=d("select","bv-input");for(let v of["supervised","auto-accept-edits","full-access"])W.appendChild(new Option(v,v));W.value=i.permissions?.runtimeMode||"supervised";let le=d("select","bv-input");le.appendChild(new Option("ignore project .pi (recommended)","ignore")),le.appendChild(new Option("inherit project .pi (needs trust)","inherit")),le.value=i.projectResources||"ignore";let oe=d("label","bv-check"),H=document.createElement("input");H.type="checkbox",H.checked=!!i.orchestrator,oe.append(H,d("span",void 0,"Super bot: gets orchestration tools (create/stop/status child bots)"));let N=(v,z)=>{let L=d("div","bv-field");return L.appendChild(d("label","bv-label",v)),L.appendChild(z),L};e.append(N("Name",a),N("Description",r),N("System prompt",l),s.element,p.element,u.element,N("MCP preset",h),g,N("Always deny tools",E),N("Packages",I),N("Model",O),N("Thinking level",D),N("Approval mode",W),N("Project resources",le),oe);let ie=d("button","btn primary",n?"Save template":"Create template");ie.onclick=async()=>{let[v,z]=O.value.split(`
12
+ `),L=t.mcp.find(M=>M.id===h.value),re={name:a.value.trim()||"bot",description:r.value.trim()||void 0,system:l.value.trim()||void 0,skills:s.get(),extensions:p.get().map(M=>(M.startsWith("builtin:"),M)),prompts:u.get(),packages:I.value.split(`
13
+ `).map(M=>M.trim()).filter(Boolean),mcp:L?{mcpServers:L.servers}:void 0,tools:{allow:B.filter(M=>M.input.checked).map(M=>M.name),deny:E.value.split(",").map(M=>M.trim()).filter(Boolean)},model:v?{provider:v,id:z,thinking:D.value||void 0}:void 0,permissions:{runtimeMode:W.value},projectResources:le.value==="inherit"?"inherit":"ignore",orchestrator:H.checked||void 0};try{await $("/api/bots/templates",{method:"POST",body:JSON.stringify({id:n?.id,manifest:re})}),Je(),await Ke()}catch(M){alert(M instanceof Error?M.message:String(M))}},e.appendChild(ie)}async function wi(){return xt("")}async function xt(e){let t=kt("New bot"),n=await tn();if(n.length===0){t.appendChild(d("div","bots-empty","Create a template first (\u2699)."));return}let i=d("select","bv-input");for(let u of n)i.appendChild(new Option(u.manifest.name,u.id));let a=d("input","bv-input");a.placeholder="Title (defaults to template name)";let r=d("input","bv-input");r.placeholder="/path/to/project";let l=e||m.bots[0]?.projectPath||"";r.value=l;let s=d("select","bv-input");s.appendChild(new Option("shared \u2014 run in the project folder","shared")),s.appendChild(new Option("worktree \u2014 isolated git worktree","worktree")),t.append(Ve("Template",i),Ve("Title",a),Ve("Project path",r),Ve("Workspace",s));let p=d("button","btn primary","Create bot");p.onclick=async()=>{try{let u=await $("/api/bots",{method:"POST",body:JSON.stringify({templateId:i.value,title:a.value.trim()||void 0,projectPath:r.value.trim()||void 0,isolation:s.value})});Je(),await X(!0),await Qt(u.id)}catch(u){alert(u instanceof Error?u.message:String(u))}},t.appendChild(p)}function Ve(e,t){let n=d("div","bv-field");return n.appendChild(d("label","bv-label",e)),n.appendChild(t),n}async function an(){let e=kt("Needs you");if(m.approvals=await $("/api/bots/approvals"),m.approvals.length===0){e.appendChild(d("div","bots-empty","Nothing waiting."));return}for(let t of m.approvals){let n=d("div","bv-approval");n.appendChild(d("div","bv-approval-title",`${t.botTitle}: ${t.title}`)),t.message&&n.appendChild(d("pre","bv-pre",t.message));let i=d("input","bv-reason");i.placeholder="reason (optional)";let a=d("div","bv-approval-actions"),r=d("button","btn primary","Allow"),l=d("button","btn danger","Deny"),s=async p=>{await $(`/api/bots/${t.botId}/approve`,{method:"POST",body:JSON.stringify({requestId:t.id,allow:p,reason:i.value||void 0})}),await X(!0),await an()};r.onclick=()=>void s(!0),l.onclick=()=>void s(!1),a.append(i,r,l),n.appendChild(a),e.appendChild(n)}}function Ei(){if(document.getElementById("bots-section"))return;let e=ci();Se=e.list,qe=e.badge,pi(),document.addEventListener("click",t=>{let n=t.target;n&&n.closest(".session-item")&&m.activeId&&wt()},!0),X(!0),m.pollTimer=window.setInterval(()=>{document.hidden||X()},6e3),window.addEventListener("beforeunload",()=>window.clearInterval(m.pollTimer))}var Te=window.__TMUX_WEB_SHELL__,k=null,S=null,Be=typeof window.__TMUX_WEB_SCOPE__?.agentId=="string"?window.__TMUX_WEB_SCOPE__.agentId:null,R=Be;window.__tmuxWebScopeAgent=Be;var Lt="sessions",ee="",Xe="",Qe="",sn="";function P(e){return R?"/a/"+encodeURIComponent(R)+e:e}var y=document.getElementById("sidebar-content"),ue=document.getElementById("main-placeholder"),_=document.getElementById("terminal-container"),Me=document.getElementById("file-editor"),ki=document.getElementById("fe-path"),J=document.getElementById("fe-status"),De=document.getElementById("fe-content"),me=document.getElementById("fe-save"),Ci=document.getElementById("fe-delete"),xi=document.getElementById("fe-back"),ln=document.getElementById("fe-new-name"),Li=document.getElementById("fe-new-btn"),St=document.getElementById("settings-backdrop"),on=document.getElementById("settings-popover"),rn=document.querySelector(".sidebar"),dn="tmux-web-force-narrow";function Ze(){try{return localStorage.getItem(dn)==="1"}catch{return!1}}function cn(){document.documentElement.classList.toggle("force-narrow",Ze()),Ze()&&pn()&&Ge()}function pn(){return Ze()?!0:window.matchMedia("(max-width: 640px)").matches}function Ge(){pn()&&rn.classList.add("collapsed")}function un(){rn.classList.remove("collapsed")}document.getElementById("mode-sessions").addEventListener("click",()=>{un(),mn("sessions")}),document.getElementById("mode-files").addEventListener("click",()=>{un(),mn("files")});function mn(e){Lt=e,document.querySelectorAll(".mode-btn").forEach(n=>n.classList.remove("active"));let t=document.getElementById(e==="sessions"?"mode-sessions":"mode-files");t&&t.classList.add("active"),e==="sessions"?(It="",te()):Oi()}var It="";async function te(){if(Lt!=="sessions")return;try{let t=await(await fetch("/api/sidebar/sessions")).json(),n=JSON.stringify({recent:t.recent,agents:t.agents,tombstones:t.tombstones});if(n===It)return;It=n,Mi(t)}catch{y.innerHTML+='<div class="file-tree-empty">Failed to load sessions</div>'}let e=document.getElementById("ns-btn");e&&e.addEventListener("click",()=>{let t=window.__openNewSessionModal;typeof t=="function"?t():document.getElementById("new-session-modal")?.classList.add("open")}),Pt()}var fn="tmux-web-sidebar-group-collapsed";function hn(){try{return new Set(JSON.parse(localStorage.getItem(fn)||"[]"))}catch{return new Set}}function Si(e){try{localStorage.setItem(fn,JSON.stringify([...e]))}catch{}}function Ii(e,t,n){if(!e)return"\u2026";let i=n&&(e===n||e.startsWith(n+"/"))?"~"+e.slice(n.length):e,a=i.split("/").filter(Boolean);if(a.length===0)return e;for(let r=1;r<=a.length;r++){let l=a.slice(-r).join("/");if(!t.some(s=>!s||s===e?!1:(n&&(s===n||s.startsWith(n+"/"))?"~"+s.slice(n.length):s).split("/").filter(Boolean).slice(-r).join("/")===l))return l}return i}function vn(e,t,n,i=!0){let a=new Map;for(let s of e){let p=s.path||"";a.has(p)||a.set(p,[]),a.get(p).push(s)}let r=[...a.keys()],l=hn();for(let[s,p]of a){let u=Ii(s,r,t),h=l.has(s),g=document.createElement("div");g.className="session-group-header"+(h?" collapsed":""),g.title=s||"No working directory",g.innerHTML=`<span class="sg-folder">&#128193;</span><span class="sg-label">${w(u)}</span>`,g.addEventListener("click",()=>{let B=hn(),E=g.nextElementSibling;B.has(s)?(B.delete(s),g.classList.remove("collapsed"),E?.classList.remove("collapsed")):(B.add(s),g.classList.add("collapsed"),E?.classList.add("collapsed")),Si(B)});let x=document.createElement("div");x.className="session-group-body"+(h?" collapsed":"");for(let B of p)x.appendChild(n?Ti(B,n,i):Bi(B,s));y.appendChild(g),y.appendChild(x)}}function Ti(e,t,n){let i=document.createElement("div");i.className="session-item"+(e.name===S&&R===t?" active":"")+(n?"":" session-offline"),i.setAttribute("data-session",e.name),i.setAttribute("data-agent",t),i.innerHTML=`<svg viewBox="0 0 24 24" fill="currentColor"><path d="${e.attached?"M19 4H5a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6a2 2 0 0 0-2-2zm0 14H5V6h14v12z":"M4 6h16v2H4V6zm0 5h16v2H4v-2zm0 5h16v2H4v-2z"}"></svg>
14
14
  <span>${w(e.name)}</span>${n?"":'<span class="meta">offline</span>'}
15
- <button class="session-edit-btn" data-session="${w(e.name)}" title="Edit session"><svg viewBox="0 0 24 24" fill="currentColor" width="14" height="14"><path d="M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM20.71 7.04a1 1 0 000-1.41l-2.34-2.34a1 1 0 00-1.41 0l-1.83 1.83 3.75 3.75 1.83-1.83z"/></svg></button>`,n&&i.addEventListener("click",r=>{r.target.closest(".session-edit-btn")||De(e.name,t)});let s=i.querySelector(".session-edit-btn");return s&&s.addEventListener("click",r=>{r.stopPropagation(),lt(e.name,s,{agentId:t})}),i}function Ti(e){let t=document.createElement("div");t.className="session-item"+(e.name===L&&!H?" active":""),t.setAttribute("data-session",e.name),t.innerHTML=`<svg viewBox="0 0 24 24" fill="currentColor"><path d="${e.attached?"M19 4H5a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6a2 2 0 0 0-2-2zm0 14H5V6h14v12z":"M4 6h16v2H4V6zm0 5h16v2H4v-2zm0 5h16v2H4v-2z"}"></svg>
15
+ <button class="session-edit-btn" data-session="${w(e.name)}" title="Edit session"><svg viewBox="0 0 24 24" fill="currentColor" width="14" height="14"><path d="M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM20.71 7.04a1 1 0 000-1.41l-2.34-2.34a1 1 0 00-1.41 0l-1.83 1.83 3.75 3.75 1.83-1.83z"/></svg></button>`,n&&i.addEventListener("click",r=>{r.target.closest(".session-edit-btn")||$e(e.name,t)});let a=i.querySelector(".session-edit-btn");return a&&a.addEventListener("click",r=>{r.stopPropagation(),dt(e.name,a,{agentId:t})}),i}function Bi(e,t){let n=document.createElement("div");n.className="session-item"+(e.name===S&&!R?" active":""),n.setAttribute("data-session",e.name),n.innerHTML=`<svg viewBox="0 0 24 24" fill="currentColor"><path d="${e.attached?"M19 4H5a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6a2 2 0 0 0-2-2zm0 14H5V6h14v12z":"M4 6h16v2H4V6zm0 5h16v2H4v-2zm0 5h16v2H4v-2z"}"></svg>
16
16
  <span>${w(e.name)}</span>
17
17
  <button class="session-edit-btn" data-session="${w(e.name)}" title="Edit session"><svg viewBox="0 0 24 24" fill="currentColor" width="14" height="14"><path d="M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM20.71 7.04a1 1 0 000-1.41l-2.34-2.34a1 1 0 00-1.41 0l-1.83 1.83 3.75 3.75 1.83-1.83z"/></svg></button>
18
- `,t.addEventListener("click",i=>{i.target.closest(".session-edit-btn")||De(e.name)});let n=t.querySelector(".session-edit-btn");return n&&n.addEventListener("click",i=>{i.stopPropagation(),lt(e.name,n)}),t}function Bi(e){y.innerHTML='<button class="new-session-sidebar-btn" id="ns-btn">+ New Session</button>';let t=e.recent||[],n=document.createElement("div");n.className="sidebar-section-label"+(Te?" clickable":""),n.textContent=Te?"\u2190 \u8FD4\u56DE\u672C\u673A":"\u672C\u673A",Te&&(n.title="Back to hub",n.addEventListener("click",()=>{window.location.href="/"})),y.appendChild(n),fn(t,e.home);let i=e.agents||[];for(let r of i){if(!r.sessions||r.sessions.length===0)continue;let o=r.agentId===H,a=document.createElement("div");a.className="sidebar-section-label machine-label"+(r.online?"":" agent-offline-label")+(!o&&r.online?" clickable":""),a.textContent=r.agentName+(r.online?"":" (offline)"),!o&&r.online&&(a.title="\u6253\u5F00 "+r.agentName,a.addEventListener("click",()=>{window.location.href="/a/"+encodeURIComponent(r.agentId)+"/"})),y.appendChild(a),fn(r.sessions,e.home,r.agentId,r.online)}let s=e.tombstones||[];if(s.length>0){let r=document.createElement("div");r.className="sidebar-section-label tombstone-label",r.textContent="\u5931\u6548\u4F1A\u8BDD",y.appendChild(r);for(let o of s){let a=document.createElement("div");a.className="session-item session-tombstone",a.setAttribute("data-session",o.name),o.agentId&&a.setAttribute("data-agent",o.agentId);let p=o.agentId?o.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>${w(o.name)}</span><span class="meta">\u5931\u6548${p}</span>
20
- <button class="session-edit-btn" data-session="${w(o.name)}" title="\u6062\u590D\u4F1A\u8BDD"><svg viewBox="0 0 24 24" fill="currentColor" width="14" height="14"><path d="M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM20.71 7.04a1 1 0 000-1.41l-2.34-2.34a1 1 0 00-1.41 0l-1.83 1.83 3.75 3.75 1.83-1.83z"/></svg></button>`,a.title="\u5931\u6548\u4F1A\u8BDD\uFF1A\u70B9\u51FB\u7BA1\u7406\uFF08\u91CD\u5EFA/\u91CD\u547D\u540D/\u5220\u9664\uFF09",a.addEventListener("click",()=>{lt(o.name,a,{tombstone:!0,agentId:o.agentId})});let u=a.querySelector(".session-edit-btn");u&&u.addEventListener("click",v=>{v.stopPropagation(),lt(o.name,u,{tombstone:!0,agentId:o.agentId})}),y.appendChild(a)}}}function w(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}async function De(e,t){if(L===e&&C&&H===(t||null))return;Be.style.display="none",pe.style.display="none",U.style.display="",U.classList.add("terminal-pending"),Qe(),C&&(at(),C.destroy(),C=null),L=e,H=t||null,window.__tmuxWebScopeAgent=H,window.__tmuxWebCurrentSession=L,es(e,t);let n=Mt(e,t);Mn.set(n,Date.now()+Zi);let i=ye.get(n);if(i&&i.state==="working"){i.state="idle",i.doneUntil=void 0,i.unread=!1;let s=y.querySelector(t?'.session-item[data-agent="'+CSS.escape(t)+'"][data-session="'+CSS.escape(e)+'"]':'.session-item[data-session="'+CSS.escape(e)+'"]:not([data-agent])');s&&ut(s,n,i)}for(let s of y.querySelectorAll(".session-item"))s.classList.toggle("active",s.getAttribute("data-session")===e&&(s.getAttribute("data-agent")||null)===H);try{C=await ri(U,e,{terminal:Ie.terminal,scrollback:Ie.scrollback,theme:Ie.theme,wsBase:H?"/ws/a/"+encodeURIComponent(H):Ie.wsBase||"/ws"}),xn()}catch(s){console.error("[shell] terminal init failed:",s);let r=s&&typeof s=="object"&&"message"in s?s.message:String(s);U.textContent="Failed to open terminal for "+e+": "+r,U.classList.remove("terminal-pending")}}var Ze=[],I=null,hn=!1;function Mi(e){if(!I||!I.files.length)return null;let t=I.repoRoot;if(!t||!e.startsWith(t))return null;let n=e.slice(t.length+1);for(let i of I.files)if(i.path===n)return i.status;return null}async function Di(e){hn=!0;try{let t=await fetch(P("/api/git/status?path="+encodeURIComponent(e)));t.ok?I=await t.json():I=null}catch{I=null}finally{hn=!1}}function Ai(){if(!I||!I.branch)return"";let{branch:e,linesAdded:t,linesRemoved:n}=I,i=`<div class="sidebar-git"><div class="git-branch-badge">
18
+ `,n.addEventListener("click",a=>{a.target.closest(".session-edit-btn")||$e(e.name)});let i=n.querySelector(".session-edit-btn");return i&&i.addEventListener("click",a=>{a.stopPropagation(),dt(e.name,i,{sessionPath:t})}),n}function Mi(e){y.innerHTML='<button class="new-session-sidebar-btn" id="ns-btn">+ New Session</button>';let t=e.recent||[],n=document.createElement("div");n.className="sidebar-section-label"+(Be?" clickable":""),n.textContent=Be?"\u2190 \u8FD4\u56DE\u672C\u673A":"\u672C\u673A",Be&&(n.title="Back to hub",n.addEventListener("click",()=>{window.location.href="/"})),y.appendChild(n),vn(t,e.home);let i=e.agents||[];for(let r of i){if(!r.sessions||r.sessions.length===0)continue;let l=r.agentId===R,s=document.createElement("div");s.className="sidebar-section-label machine-label"+(r.online?"":" agent-offline-label")+(!l&&r.online?" clickable":""),s.textContent=r.agentName+(r.online?"":" (offline)"),!l&&r.online&&(s.title="\u6253\u5F00 "+r.agentName,s.addEventListener("click",()=>{window.location.href="/a/"+encodeURIComponent(r.agentId)+"/"})),y.appendChild(s),vn(r.sessions,e.home,r.agentId,r.online)}let a=e.tombstones||[];if(a.length>0){let r=document.createElement("div");r.className="sidebar-section-label tombstone-label",r.textContent="\u5931\u6548\u4F1A\u8BDD",y.appendChild(r);for(let l of a){let s=document.createElement("div");s.className="session-item session-tombstone",s.setAttribute("data-session",l.name),l.agentId&&s.setAttribute("data-agent",l.agentId);let p=l.agentId?l.agentOnline?" (agent)":" (agent \u79BB\u7EBF)":"";s.innerHTML=`<svg viewBox="0 0 24 24" fill="currentColor"><path d="M4 6h16v2H4V6zm0 5h16v2H4v-2zm0 5h16v2H4v-2z"></svg>
19
+ <span>${w(l.name)}</span><span class="meta">\u5931\u6548${p}</span>
20
+ <button class="session-edit-btn" data-session="${w(l.name)}" title="\u6062\u590D\u4F1A\u8BDD"><svg viewBox="0 0 24 24" fill="currentColor" width="14" height="14"><path d="M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM20.71 7.04a1 1 0 000-1.41l-2.34-2.34a1 1 0 00-1.41 0l-1.83 1.83 3.75 3.75 1.83-1.83z"/></svg></button>`,s.title="\u5931\u6548\u4F1A\u8BDD\uFF1A\u70B9\u51FB\u7BA1\u7406\uFF08\u91CD\u5EFA/\u91CD\u547D\u540D/\u5220\u9664\uFF09",s.addEventListener("click",()=>{dt(l.name,s,{tombstone:!0,agentId:l.agentId})});let u=s.querySelector(".session-edit-btn");u&&u.addEventListener("click",h=>{h.stopPropagation(),dt(l.name,u,{tombstone:!0,agentId:l.agentId})}),y.appendChild(s)}}}function w(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}async function $e(e,t){if(S===e&&k&&R===(t||null))return;Me.style.display="none",ue.style.display="none",_.style.display="",_.classList.add("terminal-pending"),Ge(),k&&(ot(),k.destroy(),k=null),S=e,R=t||null,window.__tmuxWebScopeAgent=R,window.__tmuxWebCurrentSession=S,ta(e,t);let n=At(e,t);Dn.set(n,Date.now()+Gi);let i=ye.get(n);if(i&&i.state==="working"){i.state="idle",i.doneUntil=void 0,i.unread=!1;let a=y.querySelector(t?'.session-item[data-agent="'+CSS.escape(t)+'"][data-session="'+CSS.escape(e)+'"]':'.session-item[data-session="'+CSS.escape(e)+'"]:not([data-agent])');a&&ft(a,n,i)}for(let a of y.querySelectorAll(".session-item"))a.classList.toggle("active",a.getAttribute("data-session")===e&&(a.getAttribute("data-agent")||null)===R);try{k=await di(_,e,{terminal:Te.terminal,scrollback:Te.scrollback,theme:Te.theme,wsBase:R?"/ws/a/"+encodeURIComponent(R):Te.wsBase||"/ws"}),Sn()}catch(a){console.error("[shell] terminal init failed:",a);let r=a&&typeof a=="object"&&"message"in a?a.message:String(a);_.textContent="Failed to open terminal for "+e+": "+r,_.classList.remove("terminal-pending")}}var et=[],T=null,gn=!1;function Di(e){if(!T||!T.files.length)return null;let t=T.repoRoot;if(!t||!e.startsWith(t))return null;let n=e.slice(t.length+1);for(let i of T.files)if(i.path===n)return i.status;return null}async function $i(e){gn=!0;try{let t=await fetch(P("/api/git/status?path="+encodeURIComponent(e)));t.ok?T=await t.json():T=null}catch{T=null}finally{gn=!1}}function Ai(){if(!T||!T.branch)return"";let{branch:e,linesAdded:t,linesRemoved:n}=T,i=`<div class="sidebar-git"><div class="git-branch-badge">
21
21
  <svg viewBox="0 0 16 16" fill="currentColor"><path d="M11.63 1.22a.75.75 0 00-1.06 0L5.99 5.8 4.12 3.93a.75.75 0 10-1.06 1.06L4.93 6.87A3.5 3.5 0 003 10.09v3.16a.75.75 0 001 0v-3.16a2.5 2.5 0 012.5-2.5h.27l-1.06 1.06a.75.75 0 001.06 1.06l2.37-2.38a.75.75 0 000-1.06L7.59 5.27l4.04-4.05a.75.75 0 000-1.06L11.63 1.22zM3.25 13.94a.75.75 0 01-.75-.75v-.69a.75.75 0 011.5 0v.69c0 .414-.336.75-.75.75z"/></svg>
22
- ${w(e)}</div>`;return(t>0||n>0)&&(i+=`<div class="git-diff-stats">+<span class="add">${t}</span> <span class="del">-${n}</span></div>`),i+"</div>"}y.addEventListener("click",e=>{e.target.closest(".sidebar-git")&&ve&&I&&(e.stopPropagation(),wn())});var Ae=document.getElementById("header-git"),vn=document.getElementById("git-diff-view"),gn=document.getElementById("gd-path"),Ge=document.getElementById("gd-status"),et=document.getElementById("gd-content"),$i=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:n,linesRemoved:i}=e,s=`<span class="branch">${w(t)}</span>`;(n>0||i>0)&&(s+=`<span class="sep">\xB7</span>+<span class="diff-add">${n}</span> <span class="diff-del">-${i}</span>`),Ae.innerHTML=s,Ae.style.display="block"}Ae.addEventListener("click",e=>{ve&&I&&(e.stopPropagation(),wn())});var R=document.getElementById("git-popover"),tt=document.getElementById("git-popover-backdrop");function St(){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 yn(){let e=ve,t=document.getElementById("git-popover-browse");t&&t.addEventListener("click",()=>{if(it(),e){kt="files",document.querySelectorAll(".mode-btn").forEach(i=>i.classList.remove("active"));let n=document.getElementById("mode-files");n&&n.classList.add("active"),te(e)}})}var bn="";function wn(){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 n=0;n<e.length;n++){let i=e[n],s=i.additions||0,r=i.deletions||0,o="";switch(i.status){case"M":o='<span class="git-file-status M">M</span>';break;case"A":o='<span class="git-file-status A">A</span>';break;case"D":o='<span class="git-file-status D">D</span>';break;case"?":o='<span class="git-file-status ?">?</span>';break;case"R":o='<span class="git-file-status R">R</span>';break}t+=`<div class="git-popover-item" data-idx="${n}">
24
- ${o}<span class="file-path">${w(i.path)}</span>
25
- <span class="file-add">${s>0?"+"+s:""}</span>
22
+ ${w(e)}</div>`;return(t>0||n>0)&&(i+=`<div class="git-diff-stats">+<span class="add">${t}</span> <span class="del">-${n}</span></div>`),i+"</div>"}y.addEventListener("click",e=>{e.target.closest(".sidebar-git")&&ve&&T&&(e.stopPropagation(),kn())});var Ae=document.getElementById("header-git"),bn=document.getElementById("git-diff-view"),yn=document.getElementById("gd-path"),tt=document.getElementById("gd-status"),nt=document.getElementById("gd-content"),Pi=document.getElementById("gd-back"),ve=null;function Pe(e){if(!e||!e.branch){Ae.style.display="none",ve=null;return}ve=e.repoRoot;let{branch:t,linesAdded:n,linesRemoved:i}=e,a=`<span class="branch">${w(t)}</span>`;(n>0||i>0)&&(a+=`<span class="sep">\xB7</span>+<span class="diff-add">${n}</span> <span class="diff-del">-${i}</span>`),Ae.innerHTML=a,Ae.style.display="block"}Ae.addEventListener("click",e=>{ve&&T&&(e.stopPropagation(),kn())});var j=document.getElementById("git-popover"),it=document.getElementById("git-popover-backdrop");function Tt(){let e=Ae.getBoundingClientRect();j.style.top=e.bottom+4+"px",j.style.left=Math.max(8,Math.min(e.left,window.innerWidth-400))+"px"}function wn(){let e=ve,t=document.getElementById("git-popover-browse");t&&t.addEventListener("click",()=>{if(st(),e){Lt="files",document.querySelectorAll(".mode-btn").forEach(i=>i.classList.remove("active"));let n=document.getElementById("mode-files");n&&n.classList.add("active"),ne(e)}})}var En="";function kn(){if(!T)return;let e=T.files||[];if(!e.length)j.innerHTML=`<div class="git-popover-header">No changes \u2014 clean working tree</div>
23
+ <div class="git-popover-footer"><button id="git-popover-browse">Browse repository \u2192</button></div>`;else{let t=`<div class="git-popover-header">${e.length} file${e.length>1?"s":""} changed</div>`;for(let n=0;n<e.length;n++){let i=e[n],a=i.additions||0,r=i.deletions||0,l="";switch(i.status){case"M":l='<span class="git-file-status M">M</span>';break;case"A":l='<span class="git-file-status A">A</span>';break;case"D":l='<span class="git-file-status D">D</span>';break;case"?":l='<span class="git-file-status ?">?</span>';break;case"R":l='<span class="git-file-status R">R</span>';break}t+=`<div class="git-popover-item" data-idx="${n}">
24
+ ${l}<span class="file-path">${w(i.path)}</span>
25
+ <span class="file-add">${a>0?"+"+a:""}</span>
26
26
  <span class="file-del">${r>0?"-"+r:""}</span>
27
- </div>`}t+='<div class="git-popover-footer"><button id="git-popover-browse">Browse repository \u2192</button></div>',bn=t,R.innerHTML=t,R.querySelectorAll(".git-popover-item").forEach(n=>{let i=parseInt(n.dataset.idx||"0",10),s=e[i];!s||s.status==="D"||(n.classList.add("clickable"),n.style.cursor="pointer",n.addEventListener("click",()=>Cn(s.path)))})}St(),R.classList.add("open"),tt.classList.add("open"),yn()}function Pi(){return window.innerWidth>=1024}function En(e,t){let n=(e+(t&&e?`
27
+ </div>`}t+='<div class="git-popover-footer"><button id="git-popover-browse">Browse repository \u2192</button></div>',En=t,j.innerHTML=t,j.querySelectorAll(".git-popover-item").forEach(n=>{let i=parseInt(n.dataset.idx||"0",10),a=e[i];!a||a.status==="D"||(n.classList.add("clickable"),n.style.cursor="pointer",n.addEventListener("click",()=>xn(a.path)))})}Tt(),j.classList.add("open"),it.classList.add("open"),wn()}function Ni(){return window.innerWidth>=1024}function Cn(e,t){let n=(e+(t&&e?`
28
28
  `:"")+t).split(`
29
- `),i="",s=0,r=0;for(let o of n){let a=o;if(a.startsWith("@@")){let p=a.match(/@@\s+-(\d+)[^+]*\+(\d+)/);p&&(s=parseInt(p[1],10)-1,r=parseInt(p[2],10)-1),i+=`<div class="diff-line hunk"><span class="ln-body">${w(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")&&(i+=`<div class="diff-line header"><span class="ln-body">${w(a)}</span></div>`);continue}if(a.startsWith("+"))r++,i+=`<div class="diff-line add"><span class="ln-no">${r}</span><span class="ln-body">${w(a)}</span></div>`;else if(a.startsWith("-"))s++,i+=`<div class="diff-line del"><span class="ln-no">${s}</span><span class="ln-body">${w(a)}</span></div>`;else if(a.startsWith("\\"))i+=`<div class="diff-line"><span class="ln-body">${w(a)}</span></div>`;else{if(!a&&!s&&!r)continue;s++,r++,i+=`<div class="diff-line"><span class="ln-no">${s}</span><span class="ln-no" style="margin-right:12px">${r}</span><span class="ln-body">${w(a)}</span></div>`}}return{html:i,lineCount:n.length}}var nt=null;async function Cn(e){let t=ve;if(t)if(it(),Pi()){U.style.display="none",C&&(at(),C.destroy(),C=null,nt=L,L=null),$e(null),Be.style.display="none",pe.style.display="none",vn.style.display="flex",gn.textContent=e,Ge.textContent="Loading\u2026",et.innerHTML="";try{let n=await fetch(P("/api/git/diff?path="+encodeURIComponent(t)+"&file="+encodeURIComponent(e)));if(!n.ok)throw new Error(await n.text());let i=await n.json();Fi(e,i.diff,i.stagedDiff)}catch(n){let i=n instanceof Error?n.message:String(n);Ge.textContent="Error",et.innerHTML=`<div class="diff-empty" style="padding:24px;text-align:center;color:var(--panel-muted)">Error: ${w(i)}</div>`}}else{R.innerHTML=`<div class="git-diff-view"><div class="diff-header">
29
+ `),i="",a=0,r=0;for(let l of n){let s=l;if(s.startsWith("@@")){let p=s.match(/@@\s+-(\d+)[^+]*\+(\d+)/);p&&(a=parseInt(p[1],10)-1,r=parseInt(p[2],10)-1),i+=`<div class="diff-line hunk"><span class="ln-body">${w(s)}</span></div>`;continue}if(s.startsWith("diff --git")||s.startsWith("index ")||s.startsWith("--- ")||s.startsWith("+++ ")||s.startsWith("new file")||s.startsWith("deleted file")){s.startsWith("diff --git")&&(i+=`<div class="diff-line header"><span class="ln-body">${w(s)}</span></div>`);continue}if(s.startsWith("+"))r++,i+=`<div class="diff-line add"><span class="ln-no">${r}</span><span class="ln-body">${w(s)}</span></div>`;else if(s.startsWith("-"))a++,i+=`<div class="diff-line del"><span class="ln-no">${a}</span><span class="ln-body">${w(s)}</span></div>`;else if(s.startsWith("\\"))i+=`<div class="diff-line"><span class="ln-body">${w(s)}</span></div>`;else{if(!s&&!a&&!r)continue;a++,r++,i+=`<div class="diff-line"><span class="ln-no">${a}</span><span class="ln-no" style="margin-right:12px">${r}</span><span class="ln-body">${w(s)}</span></div>`}}return{html:i,lineCount:n.length}}var at=null;async function xn(e){let t=ve;if(t)if(st(),Ni()){_.style.display="none",k&&(ot(),k.destroy(),k=null,at=S,S=null),Pe(null),Me.style.display="none",ue.style.display="none",bn.style.display="flex",yn.textContent=e,tt.textContent="Loading\u2026",nt.innerHTML="";try{let n=await fetch(P("/api/git/diff?path="+encodeURIComponent(t)+"&file="+encodeURIComponent(e)));if(!n.ok)throw new Error(await n.text());let i=await n.json();Ri(e,i.diff,i.stagedDiff)}catch(n){let i=n instanceof Error?n.message:String(n);tt.textContent="Error",nt.innerHTML=`<div class="diff-empty" style="padding:24px;text-align:center;color:var(--panel-muted)">Error: ${w(i)}</div>`}}else{j.innerHTML=`<div class="git-diff-view"><div class="diff-header">
30
30
  <button class="diff-back">\u2190 Back</button>
31
31
  <span class="diff-filename">${w(e)}</span>
32
32
  <span class="diff-loading">Loading\u2026</span>
33
- </div></div>`,St(),R.classList.add("open"),tt.classList.add("open");try{let n=await fetch(P("/api/git/diff?path="+encodeURIComponent(t)+"&file="+encodeURIComponent(e)));if(!n.ok)throw new Error(await n.text());let i=await n.json();Ni(e,i.diff,i.stagedDiff)}catch(n){let i=n instanceof Error?n.message:String(n);R.innerHTML=`<div class="git-diff-view"><div class="diff-header">
33
+ </div></div>`,Tt(),j.classList.add("open"),it.classList.add("open");try{let n=await fetch(P("/api/git/diff?path="+encodeURIComponent(t)+"&file="+encodeURIComponent(e)));if(!n.ok)throw new Error(await n.text());let i=await n.json();Fi(e,i.diff,i.stagedDiff)}catch(n){let i=n instanceof Error?n.message:String(n);j.innerHTML=`<div class="git-diff-view"><div class="diff-header">
34
34
  <button class="diff-back">\u2190 Back</button>
35
35
  <span class="diff-filename">${w(e)}</span>
36
- </div><div class="diff-empty">Error loading diff: ${w(i)}</div></div>`}}}function Ni(e,t,n){if(!t&&!n){R.innerHTML=`<div class="git-diff-view"><div class="diff-header">
36
+ </div><div class="diff-empty">Error loading diff: ${w(i)}</div></div>`}}}function Fi(e,t,n){if(!t&&!n){j.innerHTML=`<div class="git-diff-view"><div class="diff-header">
37
37
  <button class="diff-back">\u2190 Back</button>
38
38
  <span class="diff-filename">${w(e)}</span>
39
- </div><div class="diff-empty">No diff content available</div></div>`;return}let{html:i,lineCount:s}=En(t,n);R.innerHTML=`<div class="git-diff-view"><div class="diff-header">
39
+ </div><div class="diff-empty">No diff content available</div></div>`;return}let{html:i,lineCount:a}=Cn(t,n);j.innerHTML=`<div class="git-diff-view"><div class="diff-header">
40
40
  <button class="diff-back">\u2190 Back</button>
41
41
  <span class="diff-filename">${w(e)}</span>
42
- <span class="diff-filesize">${s} lines</span>
43
- </div><div class="diff-content">${i}</div></div>`,R.querySelector(".diff-back")?.addEventListener("click",()=>{R.innerHTML=bn,St(),I&&R.querySelectorAll(".git-popover-item").forEach(r=>{let o=parseInt(r.dataset.idx||"0",10),a=I.files[o];!a||a.status==="D"||(r.style.cursor="pointer",r.addEventListener("click",()=>Cn(a.path)))}),yn()})}function Fi(e,t,n){if(!t&&!n){Ge.textContent="No diff",et.innerHTML='<div class="diff-empty" style="padding:24px;text-align:center;color:var(--panel-muted)">No diff content available</div>';return}let{html:i,lineCount:s}=En(t,n);gn.textContent=e,Ge.textContent=s+" lines",et.innerHTML=i}function Hi(){vn.style.display="none",nt?(U.style.display="",U.classList.add("terminal-pending"),De(nt),nt=null):L?(U.style.display="",U.classList.add("terminal-pending"),xn()):pe.style.display="flex"}$i.addEventListener("click",Hi);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 kn(e){try{let t=await(await fetch("/api/fs/session-path?session="+encodeURIComponent(e))).json();if(t.path){let n=await fetch("/api/git/status?path="+encodeURIComponent(t.path));if(n.ok){let i=await n.json();I=i,$e(i);return}}}catch{}I=null,$e(null)}var st=null;function xn(){at(),L&&(kn(L),st=setInterval(()=>{L&&kn(L)},3e4))}function at(){st&&(clearInterval(st),st=null)}async function Ln(e){let t=e;if(t.startsWith("~"))try{let n=await(await fetch(P("/api/fs/list?path="+encodeURIComponent(t)))).json();typeof n.path=="string"&&n.path&&(t=n.path)}catch{}t=t.replace(/\/+$/,"")||"/",Ct(t)}function Sn(e,t){let n=document.createElement("button");n.className="file-tree-bot-btn",n.textContent="+",n.title=`Create bot in ${t}`,n.setAttribute("aria-label",`Create bot in ${t}`),n.addEventListener("click",i=>{i.preventDefault(),i.stopPropagation(),Ln(t)}),e.appendChild(n)}function Ri(){if(Ze=Ie.fsRoots||[],Ze.length===0){if(L){ji(L);return}te("");return}y.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> ${w(e)}`,t.addEventListener("click",()=>te(e)),Sn(t,e),y.appendChild(t)}}async function ji(e){y.innerHTML='<div class="file-tree-empty">Loading...</div>';try{let t=await(await fetch(P("/api/fs/session-path?session="+encodeURIComponent(e)))).json();t.path?te(t.path):y.innerHTML='<div class="file-tree-info">Could not determine session directory.</div>'}catch{y.innerHTML='<div class="file-tree-error">Failed to get session directory</div>'}}async function te(e){G=e,y.innerHTML='<div class="file-tree-empty">Loading...</div>';let t=Di(e);try{let n=await(await fetch(P("/api/fs/list?path="+encodeURIComponent(e)))).json(),i=typeof n.path=="string"&&n.path?n.path:e;if(i&&(G=i),await t,y.innerHTML="",i){let o=document.createElement("div");o.className="file-tree-item file-tree-create-bot",o.innerHTML='<span class="file-tree-bot-plus">+</span> Create bot in this folder',o.title=`Create bot in ${i}`,o.addEventListener("click",()=>void Ln(i)),y.appendChild(o)}$e(I),y.innerHTML+=Ai();let s=Oi(i||e);if(s&&!Ze.some(o=>i===o)){let o=document.createElement("div");o.className="file-tree-item",o.innerHTML="..",o.addEventListener("click",()=>te(s)),y.appendChild(o)}if(n.dirs)for(let o of n.dirs){let a=o.split("/").pop()||o.split("\\").pop(),p=document.createElement("div");p.className="file-tree-item",p.innerHTML=`<svg viewBox="0 0 24 24" fill="currentColor" class="file-icon"><path d="M10 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2h-8l-2-2z"/></svg> ${w(a)}`,p.addEventListener("click",()=>te(o)),Sn(p,o),y.appendChild(p)}else y.innerHTML="";let r=n.files||[];for(let o of r){let a=o.split("/").pop()||o.split("\\").pop(),p=Mi(o),u="",v="";if(p)switch(p){case"M":u="git-mod",v='<span class="git-file-status M">M</span>';break;case"A":u="git-add",v='<span class="git-file-status A">A</span>';break;case"D":u="git-del",v='<span class="git-file-status D">D</span>';break;case"?":u="git-untracked",v='<span class="git-file-status ?">?</span>';break;case"R":u="git-mod",v='<span class="git-file-status R">R</span>';break}let b=document.createElement("div");b.className="file-tree-item file"+(u?" "+u:""),b.innerHTML=`<span class="file-icon">\u{1F4C4}</span> ${v}${w(a)}`,b.addEventListener("click",()=>zi(o)),y.appendChild(b)}}catch{y.innerHTML='<div class="file-tree-error">Failed to load directory</div>'}}function Oi(e){let t=e.lastIndexOf("/");return t<=0?null:e.substring(0,t)}async function zi(e){Ke=e,U.style.display="none",C&&(at(),C.destroy(),C=null,L=null),$e(null),Qe(),pe.style.display="none",Be.style.display="flex",Ei.textContent=e,Y.textContent="Loading...",ue.style.display="none";try{let t=await fetch(P("/api/file?path="+encodeURIComponent(e)));if(!t.ok){let i=await t.json();Y.textContent=i.error||"Failed to load",Me.value="";return}let n=await t.json();Me.value=n.content,Ve=n.content,nn=n.content,Y.textContent=n.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(P("/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}nn=Ve,Y.textContent="Saved"}catch{Y.textContent="Save failed"}finally{ue.disabled=!1,ue.textContent="Save"}}),Ci.addEventListener("click",async()=>{if(confirm("Delete "+Ke+"?"))try{let e=await fetch(P("/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",G&&te(G)}catch{Y.textContent="Delete failed"}}),ki.addEventListener("click",()=>{Be.style.display="none",pe.style.display="flex",G&&te(G)}),xi.addEventListener("click",async()=>{let e=sn.value.trim();if(!e)return;let t=G+"/"+e;try{let n=await fetch(P("/api/file/touch"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:t})});if(!n.ok){let i=await n.json();Y.textContent=i.error||"Create failed";return}sn.value="",G&&te(G)}catch{Y.textContent="Create failed"}});var ot=document.getElementById("force-narrow-toggle");ot&&(ot.checked=Xe(),ot.addEventListener("change",()=>{try{localStorage.setItem(ln,ot.checked?"1":"0")}catch{}rn(),ee()})),rn(),document.getElementById("mode-settings").addEventListener("click",()=>{let e=an.classList.toggle("open");xt.classList.toggle("open",e)}),xt.addEventListener("click",()=>{an.classList.remove("open"),xt.classList.remove("open")});var q="",ne=!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">
42
+ <span class="diff-filesize">${a} lines</span>
43
+ </div><div class="diff-content">${i}</div></div>`,j.querySelector(".diff-back")?.addEventListener("click",()=>{j.innerHTML=En,Tt(),T&&j.querySelectorAll(".git-popover-item").forEach(r=>{let l=parseInt(r.dataset.idx||"0",10),s=T.files[l];!s||s.status==="D"||(r.style.cursor="pointer",r.addEventListener("click",()=>xn(s.path)))}),wn()})}function Ri(e,t,n){if(!t&&!n){tt.textContent="No diff",nt.innerHTML='<div class="diff-empty" style="padding:24px;text-align:center;color:var(--panel-muted)">No diff content available</div>';return}let{html:i,lineCount:a}=Cn(t,n);yn.textContent=e,tt.textContent=a+" lines",nt.innerHTML=i}function ji(){bn.style.display="none",at?(_.style.display="",_.classList.add("terminal-pending"),$e(at),at=null):S?(_.style.display="",_.classList.add("terminal-pending"),Sn()):ue.style.display="flex"}Pi.addEventListener("click",ji);function st(){j.classList.remove("open"),it.classList.remove("open")}it.addEventListener("click",st),document.addEventListener("keydown",e=>{e.key==="Escape"&&(st(),mt())});async function Ln(e){try{let t=await(await fetch("/api/fs/session-path?session="+encodeURIComponent(e))).json();if(t.path){let n=await fetch("/api/git/status?path="+encodeURIComponent(t.path));if(n.ok){let i=await n.json();T=i,Pe(i);return}}}catch{}T=null,Pe(null)}var lt=null;function Sn(){ot(),S&&(Ln(S),lt=setInterval(()=>{S&&Ln(S)},3e4))}function ot(){lt&&(clearInterval(lt),lt=null)}async function Bt(e){let t=e;if(t.startsWith("~"))try{let n=await(await fetch(P("/api/fs/list?path="+encodeURIComponent(t)))).json();typeof n.path=="string"&&n.path&&(t=n.path)}catch{}t=t.replace(/\/+$/,"")||"/",xt(t)}function In(e,t){let n=document.createElement("button");n.className="file-tree-bot-btn",n.textContent="+",n.title=`Create bot in ${t}`,n.setAttribute("aria-label",`Create bot in ${t}`),n.addEventListener("click",i=>{i.preventDefault(),i.stopPropagation(),Bt(t)}),e.appendChild(n)}function Oi(){if(et=Te.fsRoots||[],et.length===0){if(S){Hi(S);return}ne("");return}y.innerHTML="";for(let e of et){let t=document.createElement("div");t.className="file-tree-item",t.innerHTML=`<svg viewBox="0 0 24 24" fill="currentColor" class="file-icon"><path d="M10 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2h-8l-2-2z"/></svg> ${w(e)}`,t.addEventListener("click",()=>ne(e)),In(t,e),y.appendChild(t)}}async function Hi(e){y.innerHTML='<div class="file-tree-empty">Loading...</div>';try{let t=await(await fetch(P("/api/fs/session-path?session="+encodeURIComponent(e)))).json();t.path?ne(t.path):y.innerHTML='<div class="file-tree-info">Could not determine session directory.</div>'}catch{y.innerHTML='<div class="file-tree-error">Failed to get session directory</div>'}}async function ne(e){ee=e,y.innerHTML='<div class="file-tree-empty">Loading...</div>';let t=$i(e);try{let n=await(await fetch(P("/api/fs/list?path="+encodeURIComponent(e)))).json(),i=typeof n.path=="string"&&n.path?n.path:e;if(i&&(ee=i),await t,y.innerHTML="",i){let l=document.createElement("div");l.className="file-tree-item file-tree-create-bot",l.innerHTML='<span class="file-tree-bot-plus">+</span> Create bot in this folder',l.title=`Create bot in ${i}`,l.addEventListener("click",()=>void Bt(i)),y.appendChild(l)}Pe(T),y.innerHTML+=Ai();let a=zi(i||e);if(a&&!et.some(l=>i===l)){let l=document.createElement("div");l.className="file-tree-item",l.innerHTML="..",l.addEventListener("click",()=>ne(a)),y.appendChild(l)}if(n.dirs)for(let l of n.dirs){let s=l.split("/").pop()||l.split("\\").pop(),p=document.createElement("div");p.className="file-tree-item",p.innerHTML=`<svg viewBox="0 0 24 24" fill="currentColor" class="file-icon"><path d="M10 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2h-8l-2-2z"/></svg> ${w(s)}`,p.addEventListener("click",()=>ne(l)),In(p,l),y.appendChild(p)}else y.innerHTML="";let r=n.files||[];for(let l of r){let s=l.split("/").pop()||l.split("\\").pop(),p=Di(l),u="",h="";if(p)switch(p){case"M":u="git-mod",h='<span class="git-file-status M">M</span>';break;case"A":u="git-add",h='<span class="git-file-status A">A</span>';break;case"D":u="git-del",h='<span class="git-file-status D">D</span>';break;case"?":u="git-untracked",h='<span class="git-file-status ?">?</span>';break;case"R":u="git-mod",h='<span class="git-file-status R">R</span>';break}let g=document.createElement("div");g.className="file-tree-item file"+(u?" "+u:""),g.innerHTML=`<span class="file-icon">\u{1F4C4}</span> ${h}${w(s)}`,g.addEventListener("click",()=>Ui(l)),y.appendChild(g)}}catch{y.innerHTML='<div class="file-tree-error">Failed to load directory</div>'}}function zi(e){let t=e.lastIndexOf("/");return t<=0?null:e.substring(0,t)}async function Ui(e){Xe=e,_.style.display="none",k&&(ot(),k.destroy(),k=null,S=null),Pe(null),Ge(),ue.style.display="none",Me.style.display="flex",ki.textContent=e,J.textContent="Loading...",me.style.display="none";try{let t=await fetch(P("/api/file?path="+encodeURIComponent(e)));if(!t.ok){let i=await t.json();J.textContent=i.error||"Failed to load",De.value="";return}let n=await t.json();De.value=n.content,Qe=n.content,sn=n.content,J.textContent=n.size+" bytes",me.style.display=""}catch{J.textContent="Failed to load",De.value=""}}De.addEventListener("input",()=>{Qe=De.value}),me.addEventListener("click",async()=>{me.textContent="Saving...",me.disabled=!0;try{let e=await fetch(P("/api/file"),{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:Xe,content:Qe})});if(!e.ok){let t=await e.json();J.textContent=t.error||"Save failed";return}sn=Qe,J.textContent="Saved"}catch{J.textContent="Save failed"}finally{me.disabled=!1,me.textContent="Save"}}),Ci.addEventListener("click",async()=>{if(confirm("Delete "+Xe+"?"))try{let e=await fetch(P("/api/file/delete"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:Xe})});if(!e.ok){let t=await e.json();J.textContent=t.error||"Delete failed";return}Me.style.display="none",ue.style.display="flex",ee&&ne(ee)}catch{J.textContent="Delete failed"}}),xi.addEventListener("click",()=>{Me.style.display="none",ue.style.display="flex",ee&&ne(ee)}),Li.addEventListener("click",async()=>{let e=ln.value.trim();if(!e)return;let t=ee+"/"+e;try{let n=await fetch(P("/api/file/touch"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:t})});if(!n.ok){let i=await n.json();J.textContent=i.error||"Create failed";return}ln.value="",ee&&ne(ee)}catch{J.textContent="Create failed"}});var rt=document.getElementById("force-narrow-toggle");rt&&(rt.checked=Ze(),rt.addEventListener("change",()=>{try{localStorage.setItem(dn,rt.checked?"1":"0")}catch{}cn(),te()})),cn(),document.getElementById("mode-settings").addEventListener("click",()=>{let e=on.classList.toggle("open");St.classList.toggle("open",e)}),St.addEventListener("click",()=>{on.classList.remove("open"),St.classList.remove("open")});var q="",Q=!1,Y,Ne=document.createElement("div");Ne.className="session-popover-backdrop",document.body.appendChild(Ne);var K=document.createElement("div");K.id="session-popover",K.className="session-popover",K.style.display="none",K.innerHTML=`<div class="sp-field">
44
44
  <label>Rename session</label>
45
45
  <input type="text" id="sp-name" />
46
46
  </div>
@@ -50,5 +50,6 @@ ${i.model.id}`);let D=d("select","bv-input");for(let h of["","off","minimal","lo
50
50
  </div>
51
51
  <hr class="sp-divider" />
52
52
  <button class="btn primary" id="sp-rebuild" style="display:none">\u91CD\u5EFA\u540C\u540D\u540C\u8DEF\u5F84 session</button>
53
- <button class="btn danger" id="sp-delete">Delete session</button>`,document.body.appendChild(K);function Wi(e){let t=e.getBoundingClientRect(),n=window.innerHeight,i=K.offsetHeight||240,s=t.bottom+4;s+i>n-8&&(s=Math.max(8,t.top-i-4)),K.style.top=s+"px",K.style.left=Math.max(8,Math.min(t.left,window.innerWidth-240))+"px"}function lt(e,t,n){q=e,ne=!!n?.tombstone,J=n?.agentId;let i=document.getElementById("sp-name");i.value=e;let s=K.querySelector(".sp-field label");s.textContent=ne?"\u91CD\u547D\u540D (\u4EC5\u8BB0\u5F55\uFF0C\u4E0D\u91CD\u5EFA)":"Rename session";let r=document.getElementById("sp-rebuild");r.style.display=ne?"":"none";let o=document.getElementById("sp-delete");o.textContent=ne?"\u5220\u9664\u5931\u6548\u8BB0\u5F55 (\u5893\u7891\u6D88\u5931)":"Delete session";let a=document.getElementById("sp-save");a.textContent=ne?"\u91CD\u547D\u540D":"Save",Pe.classList.add("open"),K.style.display="block",Wi(t),setTimeout(()=>i.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===q){me();return}try{let t=ne?{oldName:q,newName:e,agentId:J}:{oldName:q,newName:e,...J?{agentId:J}:{}};if(!(await fetch(P(ne?"/api/sessions/rename-tombstone":"/api/sessions/rename"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})).ok)return;me(),ee(),!ne&&L===q&&(J??null)===H&&De(e,J)}catch{}}),document.getElementById("sp-rebuild").addEventListener("click",async()=>{if(confirm('\u91CD\u5EFA\u4F1A\u8BDD "'+q+'" (\u540C\u540D\u540C\u8DEF\u5F84\uFF0C\u5185\u5BB9\u4E3A\u7A7A)\uFF1F'))try{let e=await fetch(P("/api/sessions/rebuild"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:q,agentId:J})});if(!e.ok){let t=await e.json();alert(t.error||"\u91CD\u5EFA\u5931\u8D25");return}me(),ee()}catch{}}),document.getElementById("sp-delete").addEventListener("click",async()=>{if(ne){if(!confirm('\u5220\u9664\u5931\u6548\u8BB0\u5F55 "'+q+'"\uFF1F'))return;try{if(!(await fetch(P("/api/sessions/dismiss"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:q,agentId:J})})).ok)return;me(),ee()}catch{}return}if(confirm('Delete session "'+q+'"?'))try{if(!(await fetch(P("/api/sessions/kill"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:q,...J?{agentId:J}:{}})})).ok)return;me(),L===q&&(J??null)===H&&(C&&(C.destroy(),C=null),L=null,U.style.display="none",pe.style.display="flex"),ee()}catch{}}),document.getElementById("sp-cancel").addEventListener("click",me);var In={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"),_i=new Set(["up","down","left","right","tab","s-tab","space"]),Ui=400,qi=80,Ne=0,dt=0,ct=!1;function Yi(){Ne&&(clearTimeout(Ne),Ne=0),dt&&(clearInterval(dt),dt=0)}rt.addEventListener("mousedown",e=>{e.target.closest("button[data-key]")&&e.preventDefault()}),rt.addEventListener("pointerdown",e=>{let t=e.target.closest("button[data-key]");if(!t)return;let n=t.dataset.key;_i.has(n)&&(ct=!1,Ne=setTimeout(()=>{Ne=0,ct=!0,dt=setInterval(()=>{let i=In[n];i&&C&&C.sendInput(i)},qi)},Ui))});for(let e of["pointerup","pointercancel","pointerleave"])rt.addEventListener(e,Yi);rt.addEventListener("click",e=>{let t=e.target.closest("button[data-key]");if(!t||!C)return;if(ct){ct=!1;return}let n=In[t.dataset.key];n&&(C.sendInput(n),C.focus())});var Q=document.getElementById("mk-input"),Tn=document.getElementById("mk-send");function Bn(){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(),Bn())})),Tn&&Tn.addEventListener("click",Bn),window.visualViewport){let e=document.querySelector(".app-layout"),t=()=>{e&&(e.style.height=window.visualViewport.height+"px"),window.scrollTo(0,0),document.documentElement.scrollTop=0,document.body.scrollTop=0};window.visualViewport.addEventListener("resize",t),window.addEventListener("orientationchange",()=>setTimeout(t,100)),document.addEventListener("touchstart",()=>{(window.scrollY>0||document.documentElement.scrollTop>0)&&window.scrollTo(0,0)},{passive:!0})}var It=document.getElementById("process-panel"),Fe=document.getElementById("proc-list"),Ji=document.getElementById("proc-close"),Tt=document.getElementById("proc-backdrop"),Ki=document.getElementById("header-ram");function Vi(){Fe.innerHTML='<div class="proc-empty">Loading\u2026</div>',fetch(P("/api/system/processes")).then(e=>e.json()).then(e=>{if(!Array.isArray(e)||!e.length){Fe.innerHTML='<div class="proc-empty">No processes</div>';return}let t="";for(let n of e){let i=n.rss,s=i<1048576?(i/1024).toFixed(0)+"K":(i/1048576).toFixed(1)+"M";t+='<div class="proc-row" data-pid="'+n.pid+'"><span class="proc-mem">'+n.mem+'%</span><span class="proc-rss">'+s+'</span><span class="proc-cmd" title="'+w(n.command)+'">'+w(n.command)+'</span><button class="proc-kill" title="Kill PID '+n.pid+'">&times;</button></div>'}Fe.innerHTML=t;for(let n of Fe.querySelectorAll(".proc-row")){let i=n.querySelector(".proc-kill");i&&i.addEventListener("click",s=>{let r=s.target.closest(".proc-row");!r||!confirm("Kill PID "+r.dataset.pid+"?")||fetch(P("/api/system/kill"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({pid:parseInt(r.dataset.pid,10)})}).then(o=>o.json()).then(o=>{o.ok?r.style.opacity="0.3":alert("Failed: "+(o.error||"unknown"))}).catch(()=>alert("Network error"))})}}).catch(()=>{Fe.innerHTML='<div class="proc-empty">Failed to load</div>'})}function Xi(){It.classList.add("open"),Tt.classList.add("open"),Vi()}function pt(){It.classList.remove("open"),Tt.classList.remove("open")}Ki.addEventListener("click",e=>{e.stopPropagation(),It.classList.contains("open")?pt():Xi()}),Ji.addEventListener("click",pt),Tt.addEventListener("click",pt);var Qi=2e3,He=null,Bt=null,ge=new Map,ye=new Map,Zi=5e3,Mn=new Map;function Mt(e,t){return(t?"a:"+t+":":"l:")+e}function Gi(e,t,n){let i=Mt(e,t);if(n==="working"){let u=Mn.get(i);if(u&&Date.now()<u)return}let s=ye.get(i),r=e===L&&(t??null)===H,o=n==="idle"&&s?.state==="working";ye.set(i,{session:e,agentId:t,state:n,doneUntil:o?Date.now()+Qi:void 0,unread:o?!r:!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=y.querySelector(a);p&&ut(p,i,ye.get(i))}function ut(e,t,n){let i=ge.get(t);i&&(clearTimeout(i),ge.delete(t)),e.classList.remove("working","just-done");let s=n.session===L&&(n.agentId??null)===H;n.state==="working"?e.classList.add("working"):s&&n.doneUntil&&Date.now()<n.doneUntil?(e.classList.add("just-done"),ge.set(t,setTimeout(()=>{e.classList.remove("just-done"),ge.delete(t)},Math.max(0,n.doneUntil-Date.now())))):!s&&n.unread&&e.classList.add("just-done")}function Dt(){for(let[e,t]of ye){let n=t.agentId?'.session-item[data-agent="'+CSS.escape(t.agentId)+'"][data-session="'+CSS.escape(t.session)+'"]':'.session-item[data-session="'+CSS.escape(t.session)+'"]:not([data-agent])',i=y.querySelector(n);i&&ut(i,e,t)}}function es(e,t){let n=Mt(e,t),i=ye.get(n);if(!i)return;let s=ge.get(n);s&&(clearTimeout(s),ge.delete(n)),i.doneUntil=void 0,i.unread=!1;let r=t?'.session-item[data-agent="'+CSS.escape(t)+'"][data-session="'+CSS.escape(e)+'"]':'.session-item[data-session="'+CSS.escape(e)+'"]:not([data-agent])',o=y.querySelector(r);o&&ut(o,n,i)}function Dn(){if(He||Bt)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);He=n,n.onmessage=i=>{try{let s=JSON.parse(String(i.data));s&&s.type==="session.activity"&&typeof s.session=="string"&&Gi(s.session,s.agentId||void 0,s.state==="working"?"working":"idle")}catch{}},n.onclose=()=>{He===n&&(He=null,Bt=setTimeout(()=>{Bt=null,Dn()},5e3))},n.onerror=()=>{try{n.close()}catch{}}}catch{He=null}}window.__openSession=De,window.__refreshSidebar=ee,ee(),Qe(),Dt(),Dn(),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&Dt()}),setInterval(()=>{document.visibilityState==="visible"&&ee()},1e4),wi();
53
+ <button class="btn" id="sp-create-bot" style="display:none">\uFF0B \u5728\u6B64\u76EE\u5F55\u521B\u5EFA Bot</button>
54
+ <button class="btn danger" id="sp-delete">Delete session</button>`,document.body.appendChild(K);function Wi(e){let t=e.getBoundingClientRect(),n=window.innerHeight,i=K.offsetHeight||240,a=t.bottom+4;a+i>n-8&&(a=Math.max(8,t.top-i-4)),K.style.top=a+"px",K.style.left=Math.max(8,Math.min(t.left,window.innerWidth-240))+"px"}var ge="";function dt(e,t,n){q=e,Q=!!n?.tombstone,Y=n?.agentId,ge=n?.sessionPath||"";let i=document.getElementById("sp-name");i.value=e;let a=K.querySelector(".sp-field label");a.textContent=Q?"\u91CD\u547D\u540D (\u4EC5\u8BB0\u5F55\uFF0C\u4E0D\u91CD\u5EFA)":"Rename session";let r=document.getElementById("sp-rebuild");r.style.display=Q?"":"none";let l=document.getElementById("sp-delete");l.textContent=Q?"\u5220\u9664\u5931\u6548\u8BB0\u5F55 (\u5893\u7891\u6D88\u5931)":"Delete session";let s=document.getElementById("sp-save");s.textContent=Q?"\u91CD\u547D\u540D":"Save";let p=document.getElementById("sp-create-bot");p.style.display=!Q&&!Y&&ge?"":"none",p.title=ge?`Create bot in ${ge}`:"",Ne.classList.add("open"),K.style.display="block",Wi(t),setTimeout(()=>i.focus(),50)}function se(){Ne.classList.remove("open"),K.style.display="none"}Ne.addEventListener("click",se),document.getElementById("sp-create-bot").addEventListener("click",()=>{if(!ge)return;let e=ge;se(),Bt(e)}),document.getElementById("sp-save").addEventListener("click",async()=>{let e=document.getElementById("sp-name").value.trim();if(!e||e===q){se();return}try{let t=Q?{oldName:q,newName:e,agentId:Y}:{oldName:q,newName:e,...Y?{agentId:Y}:{}};if(!(await fetch(P(Q?"/api/sessions/rename-tombstone":"/api/sessions/rename"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})).ok)return;se(),te(),!Q&&S===q&&(Y??null)===R&&$e(e,Y)}catch{}}),document.getElementById("sp-rebuild").addEventListener("click",async()=>{if(confirm('\u91CD\u5EFA\u4F1A\u8BDD "'+q+'" (\u540C\u540D\u540C\u8DEF\u5F84\uFF0C\u5185\u5BB9\u4E3A\u7A7A)\uFF1F'))try{let e=await fetch(P("/api/sessions/rebuild"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:q,agentId:Y})});if(!e.ok){let t=await e.json();alert(t.error||"\u91CD\u5EFA\u5931\u8D25");return}se(),te()}catch{}}),document.getElementById("sp-delete").addEventListener("click",async()=>{if(Q){if(!confirm('\u5220\u9664\u5931\u6548\u8BB0\u5F55 "'+q+'"\uFF1F'))return;try{if(!(await fetch(P("/api/sessions/dismiss"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:q,agentId:Y})})).ok)return;se(),te()}catch{}return}if(confirm('Delete session "'+q+'"?'))try{if(!(await fetch(P("/api/sessions/kill"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:q,...Y?{agentId:Y}:{}})})).ok)return;se(),S===q&&(Y??null)===R&&(k&&(k.destroy(),k=null),S=null,_.style.display="none",ue.style.display="flex"),te()}catch{}}),document.getElementById("sp-cancel").addEventListener("click",se);var Tn={esc:"\x1B",tab:" ","s-tab":"\x1B[Z",up:"\x1B[A",down:"\x1B[B",left:"\x1B[D",right:"\x1B[C",space:" ",enter:"\r","ctrl-r":"","ctrl-c":"",btw:"/btw ",yes:"yes\r"},ct=document.getElementById("mobile-keys"),_i=new Set(["up","down","left","right","tab","s-tab","space"]),qi=400,Yi=80,Fe=0,pt=0,ut=!1;function Ji(){Fe&&(clearTimeout(Fe),Fe=0),pt&&(clearInterval(pt),pt=0)}ct.addEventListener("mousedown",e=>{e.target.closest("button[data-key]")&&e.preventDefault()}),ct.addEventListener("pointerdown",e=>{let t=e.target.closest("button[data-key]");if(!t)return;let n=t.dataset.key;_i.has(n)&&(ut=!1,Fe=setTimeout(()=>{Fe=0,ut=!0,pt=setInterval(()=>{let i=Tn[n];i&&k&&k.sendInput(i)},Yi)},qi))});for(let e of["pointerup","pointercancel","pointerleave"])ct.addEventListener(e,Ji);ct.addEventListener("click",e=>{let t=e.target.closest("button[data-key]");if(!t||!k)return;if(ut){ut=!1;return}let n=Tn[t.dataset.key];n&&(k.sendInput(n),k.focus())});var Z=document.getElementById("mk-input"),Bn=document.getElementById("mk-send");function Mn(){if(!Z||!k)return;let e=Z.value;e&&(k.sendInput(e+"\r"),Z.value="",Z.rows=1,k.focus())}if(Z&&(Z.addEventListener("input",()=>{Z.rows=1;let e=Z.value.split(`
55
+ `).length;Z.rows=Math.min(e,4)}),Z.addEventListener("keydown",e=>{e.key==="Enter"&&!e.shiftKey&&(e.preventDefault(),Mn())})),Bn&&Bn.addEventListener("click",Mn),window.visualViewport){let e=document.querySelector(".app-layout"),t=()=>{e&&(e.style.height=window.visualViewport.height+"px"),window.scrollTo(0,0),document.documentElement.scrollTop=0,document.body.scrollTop=0};window.visualViewport.addEventListener("resize",t),window.addEventListener("orientationchange",()=>setTimeout(t,100)),document.addEventListener("touchstart",()=>{(window.scrollY>0||document.documentElement.scrollTop>0)&&window.scrollTo(0,0)},{passive:!0})}var Mt=document.getElementById("process-panel"),Re=document.getElementById("proc-list"),Ki=document.getElementById("proc-close"),Dt=document.getElementById("proc-backdrop"),Vi=document.getElementById("header-ram");function Xi(){Re.innerHTML='<div class="proc-empty">Loading\u2026</div>',fetch(P("/api/system/processes")).then(e=>e.json()).then(e=>{if(!Array.isArray(e)||!e.length){Re.innerHTML='<div class="proc-empty">No processes</div>';return}let t="";for(let n of e){let i=n.rss,a=i<1048576?(i/1024).toFixed(0)+"K":(i/1048576).toFixed(1)+"M";t+='<div class="proc-row" data-pid="'+n.pid+'"><span class="proc-mem">'+n.mem+'%</span><span class="proc-rss">'+a+'</span><span class="proc-cmd" title="'+w(n.command)+'">'+w(n.command)+'</span><button class="proc-kill" title="Kill PID '+n.pid+'">&times;</button></div>'}Re.innerHTML=t;for(let n of Re.querySelectorAll(".proc-row")){let i=n.querySelector(".proc-kill");i&&i.addEventListener("click",a=>{let r=a.target.closest(".proc-row");!r||!confirm("Kill PID "+r.dataset.pid+"?")||fetch(P("/api/system/kill"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({pid:parseInt(r.dataset.pid,10)})}).then(l=>l.json()).then(l=>{l.ok?r.style.opacity="0.3":alert("Failed: "+(l.error||"unknown"))}).catch(()=>alert("Network error"))})}}).catch(()=>{Re.innerHTML='<div class="proc-empty">Failed to load</div>'})}function Qi(){Mt.classList.add("open"),Dt.classList.add("open"),Xi()}function mt(){Mt.classList.remove("open"),Dt.classList.remove("open")}Vi.addEventListener("click",e=>{e.stopPropagation(),Mt.classList.contains("open")?mt():Qi()}),Ki.addEventListener("click",mt),Dt.addEventListener("click",mt);var Zi=2e3,je=null,$t=null,be=new Map,ye=new Map,Gi=5e3,Dn=new Map;function At(e,t){return(t?"a:"+t+":":"l:")+e}function ea(e,t,n){let i=At(e,t);if(n==="working"){let u=Dn.get(i);if(u&&Date.now()<u)return}let a=ye.get(i),r=e===S&&(t??null)===R,l=n==="idle"&&a?.state==="working";ye.set(i,{session:e,agentId:t,state:n,doneUntil:l?Date.now()+Zi:void 0,unread:l?!r:!1});let s=t?'.session-item[data-agent="'+CSS.escape(t)+'"][data-session="'+CSS.escape(e)+'"]':'.session-item[data-session="'+CSS.escape(e)+'"]:not([data-agent])',p=y.querySelector(s);p&&ft(p,i,ye.get(i))}function ft(e,t,n){let i=be.get(t);i&&(clearTimeout(i),be.delete(t)),e.classList.remove("working","just-done");let a=n.session===S&&(n.agentId??null)===R;n.state==="working"?e.classList.add("working"):a&&n.doneUntil&&Date.now()<n.doneUntil?(e.classList.add("just-done"),be.set(t,setTimeout(()=>{e.classList.remove("just-done"),be.delete(t)},Math.max(0,n.doneUntil-Date.now())))):!a&&n.unread&&e.classList.add("just-done")}function Pt(){for(let[e,t]of ye){let n=t.agentId?'.session-item[data-agent="'+CSS.escape(t.agentId)+'"][data-session="'+CSS.escape(t.session)+'"]':'.session-item[data-session="'+CSS.escape(t.session)+'"]:not([data-agent])',i=y.querySelector(n);i&&ft(i,e,t)}}function ta(e,t){let n=At(e,t),i=ye.get(n);if(!i)return;let a=be.get(n);a&&(clearTimeout(a),be.delete(n)),i.doneUntil=void 0,i.unread=!1;let r=t?'.session-item[data-agent="'+CSS.escape(t)+'"][data-session="'+CSS.escape(e)+'"]':'.session-item[data-session="'+CSS.escape(e)+'"]:not([data-agent])',l=y.querySelector(r);l&&ft(l,n,i)}function $n(){if(je||$t)return;let e=localStorage.getItem("tmux-web-token"),t=(location.protocol==="https:"?"wss:":"ws:")+"//"+location.host+"/ws/activity";e&&(t+="?token="+encodeURIComponent(e));try{let n=new WebSocket(t);je=n,n.onmessage=i=>{try{let a=JSON.parse(String(i.data));a&&a.type==="session.activity"&&typeof a.session=="string"&&ea(a.session,a.agentId||void 0,a.state==="working"?"working":"idle")}catch{}},n.onclose=()=>{je===n&&(je=null,$t=setTimeout(()=>{$t=null,$n()},5e3))},n.onerror=()=>{try{n.close()}catch{}}}catch{je=null}}window.__openSession=$e,window.__refreshSidebar=te,te(),Ge(),Pt(),$n(),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&Pt()}),setInterval(()=>{document.visibilityState==="visible"&&te()},1e4),Ei();
@@ -1,6 +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,n){const i=await fetch(t,{...n,headers:{"content-type":"application/json",Authorization:`Bearer ${_()}`,...n?.headers||{}}}),e=await i.text(),s=e?JSON.parse(e):null;if(!i.ok)throw new Error(s&&s.error||`HTTP ${i.status}`);return s}function o(t,n,i){const e=document.createElement(t);return n&&(e.className=n),i!==void 0&&(e.textContent=i),e}function F(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 it(){const t=o("div","bots-section");t.id="bots-section";const n=o("div","bots-head"),i=o("span","bots-title","Bots"),e=o("span","bots-badge");e.hidden=!0,i.appendChild(e);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 bt(),s.append(d,a),n.append(i,s);const r=o("div","bots-list");r.id="bots-list",t.append(n,r);const c=document.querySelector(".sidebar"),u=document.querySelector(".sidebar-footer");return c&&c.insertBefore(t,u||null),{list:r,badge:e}}let O=null,j=null;function M(){if(!O)return;O.textContent="";const t=new Map;for(const e of l.bots){if(e.parentBotId)continue;const s=e.projectPath;t.has(s)||t.set(s,[]),t.get(s).push(e)}t.size===0&&O.appendChild(o("div","bots-empty","No bots yet"));for(const[e,s]of t){const d=o("div","bots-group"),a=o("div","bots-group-label",e.replace(/^.*\//,"")||e);a.title=e;const r=o("button","bots-icon-btn bots-group-add","+");r.title=`New bot in ${e}`,r.onclick=c=>{c.stopPropagation(),et(e)},a.appendChild(r),d.appendChild(a);for(const c of s){d.appendChild(z(c));for(const u of l.bots.filter(f=>f.parentBotId===c.id)){const f=z(u);f.classList.add("bots-row-child"),d.appendChild(f)}}O.appendChild(d)}const n=l.approvals.length;j&&(j.hidden=n===0,j.textContent=String(n));const i=document.getElementById("bv-inbox-count");i&&(i.textContent=n?`(${n})`:"")}function z(t){const n=o("div","bots-row");n.dataset.botId=t.id,t.id===l.activeId&&n.classList.add("active");const i=o("span","bots-dot");i.style.background=F(t.status);const e=o("span","bots-name",t.title),s=o("span","bots-meta",t.status.replace(/_/g," "));return n.append(i,e,s),n.onclick=()=>void K(t.id),n}function st(){const t=o("div","bots-view");t.id="bots-view",t.hidden=!0;const n=o("div","bots-view-head"),i=o("div","bv-title"),e=o("span","bots-dot");e.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(e,s,d);const a=o("div","bv-actions"),r=o("button","btn","Needs you "),c=o("span");c.id="bv-inbox-count",r.appendChild(c),r.onclick=()=>void nt();const u=o("button","btn","Resume");u.onclick=()=>void G(h=>b(`/api/bots/${h}/resume`,{method:"POST"}).then(()=>w(!0)));const f=o("button","btn danger","Stop");f.onclick=()=>void G(h=>b(`/api/bots/${h}/stop`,{method:"POST"}).then(()=>w(!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(),w(!0)})};const E=o("button","btn","\u2715");E.onclick=()=>D(),a.append(r,u,f,x,E),n.append(i,a);const B=o("div","bots-messages");B.id="bots-messages";const C=o("div","bots-composer"),v=o("textarea");v.id="bots-input",v.rows=1,v.placeholder="Message the bot\u2026 (Enter to send, Shift+Enter for newline)",v.onkeydown=h=>{h.key==="Enter"&&!h.shiftKey&&(h.preventDefault(),U())};const k=o("button","btn primary","Send");k.onclick=()=>void U(),C.append(v,k),t.append(n,B,C),document.querySelector(".main-area")?.appendChild(t),document.getElementById("bots-modal")||ut()}async function U(){const t=document.getElementById("bots-input");if(!t||!l.activeId||!t.value.trim())return;const n=t.value;t.value="";try{await b(`/api/bots/${l.activeId}/input`,{method:"POST",body:JSON.stringify({text:n})})}catch(i){T({kind:"notice",level:"error",text:i instanceof Error?i.message:String(i)})}}function G(t){l.activeId&&t(l.activeId).catch(n=>T({kind:"notice",level:"error",text:n instanceof Error?n.message:String(n)}))}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 n=document.getElementById("main-placeholder");n&&(n.style.display="")}async function K(t){l.activeId=t,l.items.set(t,[]);const n=document.getElementById("bots-view");n&&(n.hidden=!1);const i=document.getElementById("main-placeholder");i&&(i.style.display="none");const e=document.getElementById("terminal-container");e&&(e.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&&w(!0)},1500)},await w(!0)}function V(){return l.bots.find(t=>t.id===l.activeId)||null}function Y(){const t=V();if(!t)return;const n=document.getElementById("bv-title"),i=document.getElementById("bv-status"),e=document.getElementById("bv-dot");n&&(n.textContent=t.title),i&&(i.textContent=`${t.status.replace(/_/g," ")} \xB7 ${t.templateId} \xB7 ${t.projectPath}`),e&&(e.style.background=F(t.status))}function T(t,n=l.activeId){if(!n)return;const i=l.items.get(n)||[];i.push(t),l.items.set(n,i),n===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 n=l.items.get(l.activeId)||[];t.textContent="";let i=null;for(const e of n)if(e.kind==="user"){const s=o("div","bv-msg bv-user");s.textContent=e.text,t.appendChild(s),i=null}else if(e.kind==="assistant"){const s=o("div","bv-msg bv-assistant");if(e.thinking){const a=o("details","bv-thinking");a.appendChild(o("summary",void 0,"thinking")),a.appendChild(o("div",void 0,e.thinking)),s.appendChild(a)}const d=o("div","bv-text");d.textContent=e.text,s.appendChild(d),t.appendChild(s),i=d}else if(e.kind==="tool")t.appendChild(at(e)),i=null;else if(e.kind==="approval")t.appendChild(dt(e)),i=null;else if(e.kind==="notice"){const s=o("div",`bv-notice bv-notice-${e.level}`,e.text);t.appendChild(s)}i&&(i.scrollTop=i.scrollHeight),t.scrollTop=t.scrollHeight}function at(t){const n=o("details","bv-tool");n.open=t.phase!=="end"||!!t.isError;const i=o("summary"),e=o("span","bv-tool-name",t.name);if(i.appendChild(e),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`)),n.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),n.appendChild(s)}if(t.output){const s=o("pre","bv-pre bv-output");s.textContent=t.output,n.appendChild(s)}return n}function dt(t){const n=o("div","bv-approval"),i=t.approval;if(n.appendChild(o("div","bv-approval-title",i.title)),i.message&&n.appendChild(o("pre","bv-pre",i.message)),t.decided)return n.appendChild(o("div","bv-approval-decided",t.decided==="allowed"?"Allowed":"Denied")),n;const e=o("input","bv-reason");e.placeholder="reason (optional)";const s=o("div","bv-approval-actions"),d=o("button","btn primary","Allow"),a=o("button","btn danger","Deny"),r=async c=>{try{await b(`/api/bots/${i.botId}/approve`,{method:"POST",body:JSON.stringify({requestId:i.id,allow:c,reason:e.value||void 0})}),t.decided=c?"allowed":"denied",S(),w(!0)}catch(u){T({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(e,d,a),n.appendChild(s),n}function X(t){const n=String(t.type||""),i=l.activeId;if(!i)return;const e=l.items.get(i)||[];if(n==="snapshot")l.items.set(i,[]);else if(n==="user")T({kind:"user",text:String(t.text||"")});else if(n==="status"){const s=V();s&&(s.status=String(t.status||s.status)),Y(),pt()}else if(n==="message"){const s=t.message;if(!s||String(s.role||"")!=="assistant")return;const a=lt(s),r=rt(s),c=e[e.length-1];c&&c.kind==="assistant"?(c.text=a||c.text,c.thinking=r||c.thinking):e.push({kind:"assistant",text:a,thinking:r}),l.items.set(i,e),S()}else if(n==="delta"){const s=String(t.kind||""),d=String(t.delta||"");let a=e[e.length-1];(!a||a.kind!=="assistant")&&(e.push({kind:"assistant",text:"",thinking:""}),a=e[e.length-1]),a.kind==="assistant"&&(s==="text"?a.text+=d:s==="thinking"&&(a.thinking+=d)),l.items.set(i,e),S()}else if(n==="tool"){const s=String(t.callId||""),d=e.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))):e.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,e),S()}else if(n==="approval"){const s=t.approval;if(!s)return;const d=e;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 n==="notice"&&T({kind:"notice",level:String(t.level||"info"),text:String(t.text||"")})}function lt(t){const n=t.content;return Array.isArray(n)?n.map(i=>i&&typeof i=="object"&&i.type==="text"?String(i.text||""):"").join(""):String(t.text||"")}function rt(t){const n=t.content;return Array.isArray(n)?n.map(i=>i&&typeof i=="object"&&i.type==="thinking"?String(i.thinking||""):"").join(""):""}async function w(t=!1){try{const[n,i]=await Promise.all([b("/api/bots"),b("/api/bots/approvals")]);if(l.bots=n,l.approvals=i,M(),Y(),t&&l.activeId){const e=await b(`/api/bots/${l.activeId}/events?limit=300`);ct(e)}}catch{}}async function pt(){try{l.bots=await b("/api/bots"),M()}catch{}}function ct(t){if(l.activeId){l.items.set(l.activeId,[]);for(const n of t)X(n);L()}}function ut(){const t=o("div","bots-modal");t.id="bots-modal",t.hidden=!0;const n=o("div","bots-modal-card"),i=o("div","bots-modal-head"),e=o("span");e.id="bots-modal-title";const s=o("button","btn","\u2715");s.onclick=()=>A(),i.append(e,s);const d=o("div","bots-modal-body");d.id="bots-modal-body",n.append(i,d),t.appendChild(n),t.onclick=a=>{a.target===t&&A()},document.body.appendChild(t)}function R(t){const n=document.getElementById("bots-modal"),i=document.getElementById("bots-modal-title"),e=document.getElementById("bots-modal-body");if(!n||!e)throw new Error("modal missing");return i&&(i.textContent=t),e.textContent="",n.hidden=!1,e}function A(){const t=document.getElementById("bots-modal");t&&(t.hidden=!0)}async function mt(){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"),[n,i]=await Promise.all([mt(),Z()]),e=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,n,d);const c=o("button","btn danger","Delete");c.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,c),a.appendChild(u),e.appendChild(a)}i.length===0&&e.appendChild(o("div","bots-empty","No templates yet")),t.appendChild(e);const s=o("button","btn primary","New template");s.onclick=()=>tt(t,n,null),t.appendChild(s)}function W(t,n,i){const e=o("div","bv-field");e.appendChild(o("label","bv-label",t));const s=o("div","bv-check-grid"),d=[];for(const a of n){const r=o("label","bv-check"),c=document.createElement("input");c.type="checkbox",c.checked=i.includes(a.id),r.append(c,o("span",void 0,a.label)),a.hint&&(r.title=a.hint),s.appendChild(r),d.push({id:a.id,input:c})}return e.appendChild(s),{element:e,get:()=>d.filter(a=>a.input.checked).map(a=>a.id)}}function tt(t,n,i){t.textContent="";const e=i?JSON.parse(JSON.stringify(i.manifest)):{name:"new-bot",description:""},s=o("input","bv-input");s.value=e.name,s.placeholder="Template name";const d=o("input","bv-input");d.value=e.description||"",d.placeholder="One line description";const a=o("textarea","bv-textarea");a.rows=6,a.value=e.system||"",a.placeholder="System prompt for this bot (written to SYSTEM.md)";const r=W("Skills",n.skills.map(p=>({id:p.id,label:p.name,hint:p.description})),e.skills||[]),c=W("Extensions (Pi builtins + library)",n.extensions.map(p=>({id:p.id,label:`${p.name}${p.kind==="builtin"?" (builtin)":""}`,hint:p.description})),(e.extensions||[]).map(p=>p.replace(/^.*\//,"").replace(/\.(js|ts)$/,""))),u=W("Prompt templates",n.prompts.map(p=>({id:p.id,label:p.name})),e.prompts||[]),f=o("select","bv-input");f.appendChild(new Option("none",""));for(const p of n.mcp)f.appendChild(new Option(p.name,p.id));e.mcp&&(f.value=n.mcp.find(p=>JSON.stringify(p.servers)===JSON.stringify(e.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 p of n.tools){const I=o("label","bv-check"),g=document.createElement("input");g.type="checkbox",g.checked=(e.tools?.allow||[]).includes(p.name)||!e.tools?.allow?.length&&["read","grep","find","ls","edit","write","bash"].includes(p.name),I.append(g,o("span",void 0,p.name)),E.appendChild(I),B.push({name:p.name,input:g})}x.appendChild(E);const C=o("input","bv-input");C.value=(e.tools?.deny||[]).join(", "),C.placeholder="Always deny (comma separated), e.g. bash, write";const v=o("textarea","bv-textarea");v.rows=2,v.value=(e.packages||[]).join(`
2
- `),v.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 p of n.models)k.appendChild(new Option(`${p.provider}/${p.model}`,`${p.provider}
3
- ${p.model}`));e.model?.provider&&e.model?.id&&(k.value=`${e.model.provider}
4
- ${e.model.id}`);const h=o("select","bv-input");for(const p of["","off","minimal","low","medium","high","xhigh","max"])h.appendChild(new Option(p||"default",p));e.model?.thinking&&(h.value=e.model.thinking);const N=o("select","bv-input");for(const p of["supervised","auto-accept-edits","full-access"])N.appendChild(new Option(p,p));N.value=e.permissions?.runtimeMode||"supervised";const $=o("select","bv-input");$.appendChild(new Option("ignore project .pi (recommended)","ignore")),$.appendChild(new Option("inherit project .pi (needs trust)","inherit")),$.value=e.projectResources||"ignore";const H=o("label","bv-check"),P=document.createElement("input");P.type="checkbox",P.checked=!!e.orchestrator,H.append(P,o("span",void 0,"Super bot: gets orchestration tools (create/stop/status child bots)"));const y=(p,I)=>{const g=o("div","bv-field");return g.appendChild(o("label","bv-label",p)),g.appendChild(I),g};t.append(y("Name",s),y("Description",d),y("System prompt",a),r.element,c.element,u.element,y("MCP preset",f),x,y("Always deny tools",C),y("Packages",v),y("Model",k),y("Thinking level",h),y("Approval mode",N),y("Project resources",$),H);const Q=o("button","btn primary",i?"Save template":"Create template");Q.onclick=async()=>{const[p,I]=k.value.split(`
5
- `),g=n.mcp.find(m=>m.id===f.value),ot={name:s.value.trim()||"bot",description:d.value.trim()||void 0,system:a.value.trim()||void 0,skills:r.get(),extensions:c.get().map(m=>(m.startsWith("builtin:"),m)),prompts:u.get(),packages:v.value.split(`
6
- `).map(m=>m.trim()).filter(Boolean),mcp:g?{mcpServers:g.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:p?{provider:p,id:I,thinking:h.value||void 0}:void 0,permissions:{runtimeMode:N.value},projectResources:$.value==="inherit"?"inherit":"ignore",orchestrator:P.checked||void 0};try{await b("/api/bots/templates",{method:"POST",body:JSON.stringify({id:i?.id,manifest:ot})}),A(),await q()}catch(m){alert(m instanceof Error?m.message:String(m))}},t.appendChild(Q)}async function bt(){return et("")}async function et(t){const n=R("New bot"),i=await Z();if(i.length===0){n.appendChild(o("div","bots-empty","Create a template first (\u2699)."));return}const e=o("select","bv-input");for(const u of i)e.appendChild(new Option(u.manifest.name,u.id));const s=o("input","bv-input");s.placeholder="Title (defaults to template name)";const d=o("input","bv-input");d.placeholder="/path/to/project";const a=t||l.bots[0]?.projectPath||"";d.value=a;const r=o("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")),n.append(J("Template",e),J("Title",s),J("Project path",d),J("Workspace",r));const c=o("button","btn primary","Create bot");c.onclick=async()=>{try{const u=await b("/api/bots",{method:"POST",body:JSON.stringify({templateId:e.value,title:s.value.trim()||void 0,projectPath:d.value.trim()||void 0,isolation:r.value})});A(),await w(!0),await K(u.id)}catch(u){alert(u instanceof Error?u.message:String(u))}},n.appendChild(c)}function J(t,n){const i=o("div","bv-field");return i.appendChild(o("label","bv-label",t)),i.appendChild(n),i}async function nt(){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 n of l.approvals){const i=o("div","bv-approval");i.appendChild(o("div","bv-approval-title",`${n.botTitle}: ${n.title}`)),n.message&&i.appendChild(o("pre","bv-pre",n.message));const e=o("input","bv-reason");e.placeholder="reason (optional)";const s=o("div","bv-approval-actions"),d=o("button","btn primary","Allow"),a=o("button","btn danger","Deny"),r=async c=>{await b(`/api/bots/${n.botId}/approve`,{method:"POST",body:JSON.stringify({requestId:n.id,allow:c,reason:e.value||void 0})}),await w(!0),await nt()};d.onclick=()=>void r(!0),a.onclick=()=>void r(!1),s.append(e,d,a),i.appendChild(s),t.appendChild(i)}}function ft(){if(document.getElementById("bots-section"))return;const t=it();O=t.list,j=t.badge,st(),document.addEventListener("click",n=>{const i=n.target;i&&i.closest(".session-item")&&l.activeId&&D()},!0),w(!0),l.pollTimer=window.setInterval(()=>{document.hidden||w()},6e3),window.addEventListener("beforeunload",()=>window.clearInterval(l.pollTimer))}export{ft as initBots,et as openNewBotForPath};
1
+ const r={catalog:null,templates:[],bots:[],approvals:[],activeId:null,items:new Map,ws:null,pollTimer:0,renderQueued:!1};function L(){try{return localStorage.getItem("tmux-web-token")||""}catch{return""}}async function f(t,o){const i=await fetch(t,{...o,headers:{"content-type":"application/json",Authorization:`Bearer ${L()}`,...o?.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 e(t,o,i){const n=document.createElement(t);return o&&(n.className=o),i!==void 0&&(n.textContent=i),n}function _(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 it(){const t=e("div","bots-section");t.id="bots-section";const o=e("div","bots-head"),i=e("span","bots-title","Bots"),n=e("span","bots-badge");n.hidden=!0,i.appendChild(n);const s=e("span","bots-head-actions"),d=e("button","bots-icon-btn","\u2699");d.title="Bot templates",d.onclick=()=>void J();const a=e("button","bots-icon-btn","+");a.title="New bot from template",a.onclick=()=>void bt(),s.append(d,a),o.append(i,s);const c=e("div","bots-list");c.id="bots-list",t.append(o,c);const l=document.querySelector(".sidebar"),u=document.querySelector(".sidebar-footer");return l&&l.insertBefore(t,u||null),{list:c,badge:n}}let $=null,P=null;function M(){if(!$)return;$.textContent="";const t=new Map;for(const n of r.bots){if(n.parentBotId)continue;const s=n.projectPath;t.has(s)||t.set(s,[]),t.get(s).push(n)}t.size===0&&$.appendChild(e("div","bots-empty","No bots yet"));for(const[n,s]of t){const d=e("div","bots-group"),a=e("div","bots-group-label",n.replace(/^.*\//,"")||n);a.title=n;const c=e("button","bots-icon-btn bots-group-add","+");c.title=`New bot in ${n}`,c.onclick=l=>{l.stopPropagation(),et(n)},a.appendChild(c),d.appendChild(a);for(const l of s){d.appendChild(z(l));for(const u of r.bots.filter(m=>m.parentBotId===l.id)){const m=z(u);m.classList.add("bots-row-child"),d.appendChild(m)}}$.appendChild(d)}const o=r.approvals.length;P&&(P.hidden=o===0,P.textContent=String(o));const i=document.getElementById("bv-inbox-count");i&&(i.textContent=o?`(${o})`:"")}function z(t){const o=e("div","bots-row");o.dataset.botId=t.id,t.id===r.activeId&&o.classList.add("active");const i=e("span","bots-dot");i.style.background=_(t.status);const n=e("span","bots-name",t.title),s=e("span","bots-meta",t.status.replace(/_/g," "));return o.append(i,n,s),o.onclick=()=>void K(t.id),o}function st(){const t=e("div","bots-view");t.id="bots-view",t.hidden=!0;const o=e("div","bots-view-head"),i=e("div","bv-title"),n=e("span","bots-dot");n.id="bv-dot";const s=e("span","bv-title-text");s.id="bv-title";const d=e("span","bv-status");d.id="bv-status",i.append(n,s,d);const a=e("div","bv-actions"),c=e("button","btn","Needs you "),l=e("span");l.id="bv-inbox-count",c.appendChild(l),c.onclick=()=>void nt();const u=e("button","btn","Resume");u.onclick=()=>void G(v=>f(`/api/bots/${v}/resume`,{method:"POST"}).then(()=>k(!0)));const m=e("button","btn danger","Stop");m.onclick=()=>void G(v=>f(`/api/bots/${v}/stop`,{method:"POST"}).then(()=>k(!0)));const h=e("button","btn","Delete");h.onclick=()=>{r.activeId&&confirm("Delete this bot and its session?")&&f(`/api/bots/${r.activeId}`,{method:"DELETE"}).then(()=>{R(),k(!0)})};const C=e("button","btn","\u2715");C.onclick=()=>R(),a.append(c,u,m,h,C),o.append(i,a);const B=e("div","bots-messages");B.id="bots-messages";const x=e("div","bots-composer"),g=e("textarea");g.id="bots-input",g.rows=1,g.placeholder="Message the bot\u2026 (Enter to send, Shift+Enter for newline)",g.onkeydown=v=>{v.key==="Enter"&&!v.shiftKey&&(v.preventDefault(),F())};const S=e("button","btn primary","Send");S.onclick=()=>void F(),x.append(g,S),t.append(o,B,x),document.querySelector(".main-area")?.appendChild(t),document.getElementById("bots-modal")||ut()}async function F(){const t=document.getElementById("bots-input");if(!t||!r.activeId||!t.value.trim())return;const o=t.value;t.value="";try{await f(`/api/bots/${r.activeId}/input`,{method:"POST",body:JSON.stringify({text:o})})}catch(i){T({kind:"notice",level:"error",text:i instanceof Error?i.message:String(i)})}}function G(t){r.activeId&&t(r.activeId).catch(o=>T({kind:"notice",level:"error",text:o instanceof Error?o.message:String(o)}))}function R(){r.activeId=null;const t=document.getElementById("bots-view");t&&(t.hidden=!0);try{r.ws?.close()}catch{}r.ws=null,M();const o=document.getElementById("main-placeholder");o&&(o.style.display="")}async function K(t){r.activeId=t,r.items.set(t,[]);const o=document.getElementById("bots-view");o&&(o.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(),q();try{r.ws?.close()}catch{}const d=location.protocol==="https:"?"wss:":"ws:",a=new WebSocket(`${d}//${location.host}/ws/bots/${encodeURIComponent(t)}?token=${encodeURIComponent(L())}`);r.ws=a,a.onmessage=c=>{try{X(JSON.parse(String(c.data)))}catch{}},a.onclose=()=>{r.activeId===t&&setTimeout(()=>{r.activeId===t&&k(!0)},1500)},await k(!0)}function V(){return r.bots.find(t=>t.id===r.activeId)||null}function Y(){const t=V();if(!t)return;const o=document.getElementById("bv-title"),i=document.getElementById("bv-status"),n=document.getElementById("bv-dot");o&&(o.textContent=t.title),i&&(i.textContent=`${t.status.replace(/_/g," ")} \xB7 ${t.templateId} \xB7 ${t.projectPath}`),n&&(n.style.background=_(t.status))}function T(t,o=r.activeId){if(!o)return;const i=r.items.get(o)||[];i.push(t),r.items.set(o,i),o===r.activeId&&I()}function I(){r.renderQueued||(r.renderQueued=!0,requestAnimationFrame(()=>{r.renderQueued=!1,q()}))}function q(){const t=document.getElementById("bots-messages");if(!t||!r.activeId)return;const o=r.items.get(r.activeId)||[];t.textContent="";let i=null;for(const n of o)if(n.kind==="user"){const s=e("div","bv-msg bv-user");s.textContent=n.text,t.appendChild(s),i=null}else if(n.kind==="assistant"){const s=e("div","bv-msg bv-assistant");if(n.thinking){const a=e("details","bv-thinking");a.appendChild(e("summary",void 0,"thinking")),a.appendChild(e("div",void 0,n.thinking)),s.appendChild(a)}const d=e("div","bv-text");d.textContent=n.text,s.appendChild(d),t.appendChild(s),i=d}else if(n.kind==="tool")t.appendChild(at(n)),i=null;else if(n.kind==="approval")t.appendChild(dt(n)),i=null;else if(n.kind==="notice"){const s=e("div",`bv-notice bv-notice-${n.level}`,n.text);t.appendChild(s)}i&&(i.scrollTop=i.scrollHeight),t.scrollTop=t.scrollHeight}function at(t){const o=e("details","bv-tool");o.open=t.phase!=="end"||!!t.isError;const i=e("summary"),n=e("span","bv-tool-name",t.name);if(i.appendChild(n),t.phase!=="end"&&i.appendChild(e("span","bv-tool-phase",t.phase)),t.isError&&i.appendChild(e("span","bv-tool-error","error")),typeof t.durationMs=="number"&&i.appendChild(e("span","bv-tool-meta",`${Math.round(t.durationMs)}ms`)),o.appendChild(i),t.args!==void 0){const s=e("pre","bv-pre");s.textContent=typeof t.args=="string"?t.args:JSON.stringify(t.args,null,2),o.appendChild(s)}if(t.output){const s=e("pre","bv-pre bv-output");s.textContent=t.output,o.appendChild(s)}return o}function dt(t){const o=e("div","bv-approval"),i=t.approval;if(o.appendChild(e("div","bv-approval-title",i.title)),i.message&&o.appendChild(e("pre","bv-pre",i.message)),t.decided)return o.appendChild(e("div","bv-approval-decided",t.decided==="allowed"?"Allowed":"Denied")),o;const n=e("input","bv-reason");n.placeholder="reason (optional)";const s=e("div","bv-approval-actions"),d=e("button","btn primary","Allow"),a=e("button","btn danger","Deny"),c=async l=>{try{await f(`/api/bots/${i.botId}/approve`,{method:"POST",body:JSON.stringify({requestId:i.id,allow:l,reason:n.value||void 0})}),t.decided=l?"allowed":"denied",I(),k(!0)}catch(u){T({kind:"notice",level:"error",text:u instanceof Error?u.message:String(u)})}};return d.onclick=()=>void c(!0),a.onclick=()=>void c(!1),s.append(n,d,a),o.appendChild(s),o}function X(t){const o=String(t.type||""),i=r.activeId;if(!i)return;const n=r.items.get(i)||[];if(o==="snapshot")r.items.set(i,[]);else if(o==="user")T({kind:"user",text:String(t.text||"")});else if(o==="status"){const s=V();s&&(s.status=String(t.status||s.status)),Y(),ct()}else if(o==="message"){const s=t.message;if(!s||String(s.role||"")!=="assistant")return;const a=rt(s),c=lt(s),l=n[n.length-1];l&&l.kind==="assistant"?(l.text=a||l.text,l.thinking=c||l.thinking):n.push({kind:"assistant",text:a,thinking:c}),r.items.set(i,n),I()}else if(o==="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)),r.items.set(i,n),I()}else if(o==="tool"){const s=String(t.callId||""),d=n.find(c=>c.kind==="tool"&&c.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}),r.items.set(i,n),I()}else if(o==="approval"){const s=t.approval;if(!s)return;const d=n;for(let a=d.length-1;a>=0;a--){const c=d[a];if(c.kind==="approval"&&c.approval.id===s.id){c.approval=s,s.state!=="pending"&&(c.decided=s.state==="allowed"?"allowed":"denied"),r.items.set(i,d),I();return}}d.push({kind:"approval",approval:s}),r.items.set(i,d),I()}else o==="notice"&&T({kind:"notice",level:String(t.level||"info"),text:String(t.text||"")})}function rt(t){const o=t.content;return Array.isArray(o)?o.map(i=>i&&typeof i=="object"&&i.type==="text"?String(i.text||""):"").join(""):String(t.text||"")}function lt(t){const o=t.content;return Array.isArray(o)?o.map(i=>i&&typeof i=="object"&&i.type==="thinking"?String(i.thinking||""):"").join(""):""}async function k(t=!1){try{const[o,i]=await Promise.all([f("/api/bots"),f("/api/bots/approvals")]);if(r.bots=o,r.approvals=i,M(),Y(),t&&r.activeId){const n=await f(`/api/bots/${r.activeId}/events?limit=300`);pt(n)}}catch{}}async function ct(){try{r.bots=await f("/api/bots"),M()}catch{}}function pt(t){if(r.activeId){r.items.set(r.activeId,[]);for(const o of t)X(o);q()}}function ut(){const t=e("div","bots-modal");t.id="bots-modal",t.hidden=!0;const o=e("div","bots-modal-card"),i=e("div","bots-modal-head"),n=e("span");n.id="bots-modal-title";const s=e("button","btn","\u2715");s.onclick=()=>A(),i.append(n,s);const d=e("div","bots-modal-body");d.id="bots-modal-body",o.append(i,d),t.appendChild(o),t.onclick=a=>{a.target===t&&A()},document.body.appendChild(t)}function H(t){const o=document.getElementById("bots-modal"),i=document.getElementById("bots-modal-title"),n=document.getElementById("bots-modal-body");if(!o||!n)throw new Error("modal missing");return i&&(i.textContent=t),n.textContent="",o.hidden=!1,n}function A(){const t=document.getElementById("bots-modal");t&&(t.hidden=!0)}async function mt(){return r.catalog||(r.catalog=await f("/api/bots/catalog")),r.catalog}async function Z(){return r.templates=await f("/api/bots/templates"),r.templates}async function J(){const t=H("Bot templates"),[o,i]=await Promise.all([mt(),Z()]),n=e("div","bv-template-list");for(const l of i){const u=e("div","bv-template-row");u.appendChild(e("span","bv-template-name",l.manifest.name)),u.appendChild(e("span","bv-template-desc",l.manifest.description||""));const m=e("button","btn","Edit");m.onclick=()=>tt(t,o,l);const h=e("button","btn danger","Delete");h.onclick=()=>{confirm(`Delete template ${l.manifest.name}?`)&&f(`/api/bots/templates/${l.id}`,{method:"DELETE"}).then(()=>J())};const C=e("span","bv-template-actions");C.append(m,h),u.appendChild(C),n.appendChild(u)}i.length===0&&n.appendChild(e("div","bots-empty","No templates yet")),t.appendChild(n);const s=e("div","bv-template-actions"),d=e("button","btn primary","New template");d.onclick=()=>tt(t,o,null);const a=e("button","btn","Export");a.title="Download templates + library as JSON",a.onclick=()=>{(async()=>{try{const l=await fetch("/api/bots/export",{headers:{Authorization:`Bearer ${L()}`}});if(!l.ok)throw new Error(`HTTP ${l.status}`);const u=await l.blob(),m=document.createElement("a");m.href=URL.createObjectURL(u),m.download=`tmux-weblink-bots-${new Date().toISOString().slice(0,10)}.json`,m.click(),setTimeout(()=>URL.revokeObjectURL(m.href),2e3)}catch(l){alert(l instanceof Error?l.message:String(l))}})()};const c=e("button","btn","Import");c.title="Restore templates from a JSON bundle",c.onclick=()=>{const l=document.createElement("input");l.type="file",l.accept="application/json,.json",l.onchange=()=>{const u=l.files?.[0];u&&(async()=>{try{const m=JSON.parse(await u.text()),h=await f("/api/bots/import",{method:"POST",body:JSON.stringify(m)});alert(`Imported ${h.templates} templates, ${h.files} library files (${h.skipped} kept)`),await J()}catch(m){alert(m instanceof Error?m.message:String(m))}})()},l.click()},s.append(d,a,c),t.appendChild(s)}function U(t,o,i){const n=e("div","bv-field");n.appendChild(e("label","bv-label",t));const s=e("div","bv-check-grid"),d=[];for(const a of o){const c=e("label","bv-check"),l=document.createElement("input");l.type="checkbox",l.checked=i.includes(a.id),c.append(l,e("span",void 0,a.label)),a.hint&&(c.title=a.hint),s.appendChild(c),d.push({id:a.id,input:l})}return n.appendChild(s),{element:n,get:()=>d.filter(a=>a.input.checked).map(a=>a.id)}}function tt(t,o,i){t.textContent="";const n=i?JSON.parse(JSON.stringify(i.manifest)):{name:"new-bot",description:""},s=e("input","bv-input");s.value=n.name,s.placeholder="Template name";const d=e("input","bv-input");d.value=n.description||"",d.placeholder="One line description";const a=e("textarea","bv-textarea");a.rows=6,a.value=n.system||"",a.placeholder="System prompt for this bot (written to SYSTEM.md)";const c=U("Skills",o.skills.map(p=>({id:p.id,label:p.name,hint:p.description})),n.skills||[]),l=U("Extensions (Pi builtins + library)",o.extensions.map(p=>({id:p.id,label:`${p.name}${p.kind==="builtin"?" (builtin)":""}`,hint:p.description})),(n.extensions||[]).map(p=>p.replace(/^.*\//,"").replace(/\.(js|ts)$/,""))),u=U("Prompt templates",o.prompts.map(p=>({id:p.id,label:p.name})),n.prompts||[]),m=e("select","bv-input");m.appendChild(new Option("none",""));for(const p of o.mcp)m.appendChild(new Option(p.name,p.id));n.mcp&&(m.value=o.mcp.find(p=>JSON.stringify(p.servers)===JSON.stringify(n.mcp?.mcpServers))?.id||"");const h=e("div","bv-field");h.appendChild(e("label","bv-label","Tools (allow list; deny always blocks)"));const C=e("div","bv-check-grid"),B=[];for(const p of o.tools){const E=e("label","bv-check"),y=document.createElement("input");y.type="checkbox",y.checked=(n.tools?.allow||[]).includes(p.name)||!n.tools?.allow?.length&&["read","grep","find","ls","edit","write","bash"].includes(p.name),E.append(y,e("span",void 0,p.name)),C.appendChild(E),B.push({name:p.name,input:y})}h.appendChild(C);const x=e("input","bv-input");x.value=(n.tools?.deny||[]).join(", "),x.placeholder="Always deny (comma separated), e.g. bash, write";const g=e("textarea","bv-textarea");g.rows=2,g.value=(n.packages||[]).join(`
2
+ `),g.placeholder="Pi packages, one per line (npm:@scope/pkg@1.2.3, git:..., ./path)";const S=e("select","bv-input");S.appendChild(new Option("default (Pi settings)",""));for(const p of o.models)S.appendChild(new Option(`${p.provider}/${p.model}`,`${p.provider}
3
+ ${p.model}`));n.model?.provider&&n.model?.id&&(S.value=`${n.model.provider}
4
+ ${n.model.id}`);const v=e("select","bv-input");for(const p of["","off","minimal","low","medium","high","xhigh","max"])v.appendChild(new Option(p||"default",p));n.model?.thinking&&(v.value=n.model.thinking);const N=e("select","bv-input");for(const p of["supervised","auto-accept-edits","full-access"])N.appendChild(new Option(p,p));N.value=n.permissions?.runtimeMode||"supervised";const O=e("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 W=e("label","bv-check"),j=document.createElement("input");j.type="checkbox",j.checked=!!n.orchestrator,W.append(j,e("span",void 0,"Super bot: gets orchestration tools (create/stop/status child bots)"));const w=(p,E)=>{const y=e("div","bv-field");return y.appendChild(e("label","bv-label",p)),y.appendChild(E),y};t.append(w("Name",s),w("Description",d),w("System prompt",a),c.element,l.element,u.element,w("MCP preset",m),h,w("Always deny tools",x),w("Packages",g),w("Model",S),w("Thinking level",v),w("Approval mode",N),w("Project resources",O),W);const Q=e("button","btn primary",i?"Save template":"Create template");Q.onclick=async()=>{const[p,E]=S.value.split(`
5
+ `),y=o.mcp.find(b=>b.id===m.value),ot={name:s.value.trim()||"bot",description:d.value.trim()||void 0,system:a.value.trim()||void 0,skills:c.get(),extensions:l.get().map(b=>(b.startsWith("builtin:"),b)),prompts:u.get(),packages:g.value.split(`
6
+ `).map(b=>b.trim()).filter(Boolean),mcp:y?{mcpServers:y.servers}:void 0,tools:{allow:B.filter(b=>b.input.checked).map(b=>b.name),deny:x.value.split(",").map(b=>b.trim()).filter(Boolean)},model:p?{provider:p,id:E,thinking:v.value||void 0}:void 0,permissions:{runtimeMode:N.value},projectResources:O.value==="inherit"?"inherit":"ignore",orchestrator:j.checked||void 0};try{await f("/api/bots/templates",{method:"POST",body:JSON.stringify({id:i?.id,manifest:ot})}),A(),await J()}catch(b){alert(b instanceof Error?b.message:String(b))}},t.appendChild(Q)}async function bt(){return et("")}async function et(t){const o=H("New bot"),i=await Z();if(i.length===0){o.appendChild(e("div","bots-empty","Create a template first (\u2699)."));return}const n=e("select","bv-input");for(const u of i)n.appendChild(new Option(u.manifest.name,u.id));const s=e("input","bv-input");s.placeholder="Title (defaults to template name)";const d=e("input","bv-input");d.placeholder="/path/to/project";const a=t||r.bots[0]?.projectPath||"";d.value=a;const c=e("select","bv-input");c.appendChild(new Option("shared \u2014 run in the project folder","shared")),c.appendChild(new Option("worktree \u2014 isolated git worktree","worktree")),o.append(D("Template",n),D("Title",s),D("Project path",d),D("Workspace",c));const l=e("button","btn primary","Create bot");l.onclick=async()=>{try{const u=await f("/api/bots",{method:"POST",body:JSON.stringify({templateId:n.value,title:s.value.trim()||void 0,projectPath:d.value.trim()||void 0,isolation:c.value})});A(),await k(!0),await K(u.id)}catch(u){alert(u instanceof Error?u.message:String(u))}},o.appendChild(l)}function D(t,o){const i=e("div","bv-field");return i.appendChild(e("label","bv-label",t)),i.appendChild(o),i}async function nt(){const t=H("Needs you");if(r.approvals=await f("/api/bots/approvals"),r.approvals.length===0){t.appendChild(e("div","bots-empty","Nothing waiting."));return}for(const o of r.approvals){const i=e("div","bv-approval");i.appendChild(e("div","bv-approval-title",`${o.botTitle}: ${o.title}`)),o.message&&i.appendChild(e("pre","bv-pre",o.message));const n=e("input","bv-reason");n.placeholder="reason (optional)";const s=e("div","bv-approval-actions"),d=e("button","btn primary","Allow"),a=e("button","btn danger","Deny"),c=async l=>{await f(`/api/bots/${o.botId}/approve`,{method:"POST",body:JSON.stringify({requestId:o.id,allow:l,reason:n.value||void 0})}),await k(!0),await nt()};d.onclick=()=>void c(!0),a.onclick=()=>void c(!1),s.append(n,d,a),i.appendChild(s),t.appendChild(i)}}function ft(){if(document.getElementById("bots-section"))return;const t=it();$=t.list,P=t.badge,st(),document.addEventListener("click",o=>{const i=o.target;i&&i.closest(".session-item")&&r.activeId&&R()},!0),k(!0),r.pollTimer=window.setInterval(()=>{document.hidden||k()},6e3),window.addEventListener("beforeunload",()=>window.clearInterval(r.pollTimer))}export{ft as initBots,et as openNewBotForPath};
@@ -1,34 +1,34 @@
1
- import{initTerminal as Qe}from"./terminal-core.js";import{initBots as et,openNewBotForPath as tt}from"./bots-client.js";const P=window.__TMUX_WEB_SHELL__;let f=null,u=null;const j=typeof window.__TMUX_WEB_SCOPE__?.agentId=="string"?window.__TMUX_WEB_SCOPE__.agentId:null;let y=j;window.__tmuxWebScopeAgent=j;let me="sessions",I="",K="",Y="",Ce="";function g(e){return y?"/a/"+encodeURIComponent(y)+e:e}const r=document.getElementById("sidebar-content"),R=document.getElementById("main-placeholder"),w=document.getElementById("terminal-container"),O=document.getElementById("file-editor"),nt=document.getElementById("fe-path"),E=document.getElementById("fe-status"),U=document.getElementById("fe-content"),N=document.getElementById("fe-save"),st=document.getElementById("fe-delete"),it=document.getElementById("fe-back"),Se=document.getElementById("fe-new-name"),ot=document.getElementById("fe-new-btn"),ge=document.getElementById("settings-backdrop"),Ie=document.getElementById("settings-popover"),Be=document.querySelector(".sidebar"),xe="tmux-web-force-narrow";function X(){try{return localStorage.getItem(xe)==="1"}catch{return!1}}function Te(){document.documentElement.classList.toggle("force-narrow",X()),X()&&Me()&&Z()}function Me(){return X()?!0:window.matchMedia("(max-width: 640px)").matches}function Z(){Me()&&Be.classList.add("collapsed")}function He(){Be.classList.remove("collapsed")}document.getElementById("mode-sessions").addEventListener("click",()=>{He(),Re("sessions")}),document.getElementById("mode-files").addEventListener("click",()=>{He(),Re("files")});function Re(e){me=e,document.querySelectorAll(".mode-btn").forEach(n=>n.classList.remove("active"));const t=document.getElementById(e==="sessions"?"mode-sessions":"mode-files");t&&t.classList.add("active"),e==="sessions"?(ve="",B()):bt()}let ve="";async function B(){if(me!=="sessions")return;try{const n=await(await fetch("/api/sidebar/sessions")).json(),s=JSON.stringify({recent:n.recent,agents:n.agents,tombstones:n.tombstones});if(s===ve)return;ve=s,dt(n)}catch{r.innerHTML+='<div class="file-tree-empty">Failed to load sessions</div>'}const e=document.getElementById("ns-btn");e&&e.addEventListener("click",()=>{const t=window.__openNewSessionModal;typeof t=="function"?t():document.getElementById("new-session-modal")?.classList.add("open")}),Ee()}const Ne="tmux-web-sidebar-group-collapsed";function Ae(){try{return new Set(JSON.parse(localStorage.getItem(Ne)||"[]"))}catch{return new Set}}function at(e){try{localStorage.setItem(Ne,JSON.stringify([...e]))}catch{}}function lt(e,t,n){if(!e)return"\u2026";const s=n&&(e===n||e.startsWith(n+"/"))?"~"+e.slice(n.length):e,i=s.split("/").filter(Boolean);if(i.length===0)return e;for(let o=1;o<=i.length;o++){const l=i.slice(-o).join("/");if(!t.some(c=>!c||c===e?!1:(n&&(c===n||c.startsWith(n+"/"))?"~"+c.slice(n.length):c).split("/").filter(Boolean).slice(-o).join("/")===l))return l}return s}function $e(e,t,n,s=!0){const i=new Map;for(const a of e){const c=a.path||"";i.has(c)||i.set(c,[]),i.get(c).push(a)}const o=[...i.keys()],l=Ae();for(const[a,c]of i){const p=lt(a,o,t),b=l.has(a),v=document.createElement("div");v.className="session-group-header"+(b?" collapsed":""),v.title=a||"No working directory",v.innerHTML=`<span class="sg-folder">&#128193;</span><span class="sg-label">${d(p)}</span>`,v.addEventListener("click",()=>{const H=Ae(),ke=v.nextElementSibling;H.has(a)?(H.delete(a),v.classList.remove("collapsed"),ke?.classList.remove("collapsed")):(H.add(a),v.classList.add("collapsed"),ke?.classList.add("collapsed")),at(H)});const M=document.createElement("div");M.className="session-group-body"+(b?" collapsed":"");for(const H of c)M.appendChild(n?ct(H,n,s):rt(H));r.appendChild(v),r.appendChild(M)}}function ct(e,t,n){const s=document.createElement("div");s.className="session-item"+(e.name===u&&y===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>
2
- <span>${d(e.name)}</span>${n?"":'<span class="meta">offline</span>'}
3
- <button class="session-edit-btn" data-session="${d(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",o=>{o.target.closest(".session-edit-btn")||W(e.name,t)});const i=s.querySelector(".session-edit-btn");return i&&i.addEventListener("click",o=>{o.stopPropagation(),ce(e.name,i,{agentId:t})}),s}function rt(e){const t=document.createElement("div");t.className="session-item"+(e.name===u&&!y?" 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>
1
+ import{initTerminal as et}from"./terminal-core.js";import{initBots as tt,openNewBotForPath as nt}from"./bots-client.js";const j=window.__TMUX_WEB_SHELL__;let f=null,u=null;const O=typeof window.__TMUX_WEB_SCOPE__?.agentId=="string"?window.__TMUX_WEB_SCOPE__.agentId:null;let y=O;window.__tmuxWebScopeAgent=O;let ge="sessions",B="",Y="",X="",Ie="";function g(e){return y?"/a/"+encodeURIComponent(y)+e:e}const r=document.getElementById("sidebar-content"),N=document.getElementById("main-placeholder"),w=document.getElementById("terminal-container"),U=document.getElementById("file-editor"),st=document.getElementById("fe-path"),k=document.getElementById("fe-status"),W=document.getElementById("fe-content"),$=document.getElementById("fe-save"),it=document.getElementById("fe-delete"),ot=document.getElementById("fe-back"),Be=document.getElementById("fe-new-name"),at=document.getElementById("fe-new-btn"),ve=document.getElementById("settings-backdrop"),xe=document.getElementById("settings-popover"),Te=document.querySelector(".sidebar"),Me="tmux-web-force-narrow";function Z(){try{return localStorage.getItem(Me)==="1"}catch{return!1}}function He(){document.documentElement.classList.toggle("force-narrow",Z()),Z()&&Re()&&Q()}function Re(){return Z()?!0:window.matchMedia("(max-width: 640px)").matches}function Q(){Re()&&Te.classList.add("collapsed")}function Ne(){Te.classList.remove("collapsed")}document.getElementById("mode-sessions").addEventListener("click",()=>{Ne(),$e("sessions")}),document.getElementById("mode-files").addEventListener("click",()=>{Ne(),$e("files")});function $e(e){ge=e,document.querySelectorAll(".mode-btn").forEach(t=>t.classList.remove("active"));const n=document.getElementById(e==="sessions"?"mode-sessions":"mode-files");n&&n.classList.add("active"),e==="sessions"?(ye="",x()):wt()}let ye="";async function x(){if(ge!=="sessions")return;try{const t=await(await fetch("/api/sidebar/sessions")).json(),s=JSON.stringify({recent:t.recent,agents:t.agents,tombstones:t.tombstones});if(s===ye)return;ye=s,pt(t)}catch{r.innerHTML+='<div class="file-tree-empty">Failed to load sessions</div>'}const e=document.getElementById("ns-btn");e&&e.addEventListener("click",()=>{const n=window.__openNewSessionModal;typeof n=="function"?n():document.getElementById("new-session-modal")?.classList.add("open")}),Ce()}const Ae="tmux-web-sidebar-group-collapsed";function _e(){try{return new Set(JSON.parse(localStorage.getItem(Ae)||"[]"))}catch{return new Set}}function lt(e){try{localStorage.setItem(Ae,JSON.stringify([...e]))}catch{}}function ct(e,n,t){if(!e)return"\u2026";const s=t&&(e===t||e.startsWith(t+"/"))?"~"+e.slice(t.length):e,i=s.split("/").filter(Boolean);if(i.length===0)return e;for(let o=1;o<=i.length;o++){const c=i.slice(-o).join("/");if(!n.some(l=>!l||l===e?!1:(t&&(l===t||l.startsWith(t+"/"))?"~"+l.slice(t.length):l).split("/").filter(Boolean).slice(-o).join("/")===c))return c}return s}function De(e,n,t,s=!0){const i=new Map;for(const a of e){const l=a.path||"";i.has(l)||i.set(l,[]),i.get(l).push(a)}const o=[...i.keys()],c=_e();for(const[a,l]of i){const p=ct(a,o,n),b=c.has(a),v=document.createElement("div");v.className="session-group-header"+(b?" collapsed":""),v.title=a||"No working directory",v.innerHTML=`<span class="sg-folder">&#128193;</span><span class="sg-label">${d(p)}</span>`,v.addEventListener("click",()=>{const R=_e(),Se=v.nextElementSibling;R.has(a)?(R.delete(a),v.classList.remove("collapsed"),Se?.classList.remove("collapsed")):(R.add(a),v.classList.add("collapsed"),Se?.classList.add("collapsed")),lt(R)});const M=document.createElement("div");M.className="session-group-body"+(b?" collapsed":"");for(const R of l)M.appendChild(t?rt(R,t,s):dt(R,a));r.appendChild(v),r.appendChild(M)}}function rt(e,n,t){const s=document.createElement("div");s.className="session-item"+(e.name===u&&y===n?" active":"")+(t?"":" session-offline"),s.setAttribute("data-session",e.name),s.setAttribute("data-agent",n),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>
2
+ <span>${d(e.name)}</span>${t?"":'<span class="meta">offline</span>'}
3
+ <button class="session-edit-btn" data-session="${d(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>`,t&&s.addEventListener("click",o=>{o.target.closest(".session-edit-btn")||z(e.name,n)});const i=s.querySelector(".session-edit-btn");return i&&i.addEventListener("click",o=>{o.stopPropagation(),re(e.name,i,{agentId:n})}),s}function dt(e,n){const t=document.createElement("div");t.className="session-item"+(e.name===u&&!y?" 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>
4
4
  <span>${d(e.name)}</span>
5
5
  <button class="session-edit-btn" data-session="${d(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>
6
- `,t.addEventListener("click",s=>{s.target.closest(".session-edit-btn")||W(e.name)});const n=t.querySelector(".session-edit-btn");return n&&n.addEventListener("click",s=>{s.stopPropagation(),ce(e.name,n)}),t}function dt(e){r.innerHTML='<button class="new-session-sidebar-btn" id="ns-btn">+ New Session</button>';const t=e.recent||[],n=document.createElement("div");n.className="sidebar-section-label"+(j?" clickable":""),n.textContent=j?"\u2190 \u8FD4\u56DE\u672C\u673A":"\u672C\u673A",j&&(n.title="Back to hub",n.addEventListener("click",()=>{window.location.href="/"})),r.appendChild(n),$e(t,e.home);const s=e.agents||[];for(const o of s){if(!o.sessions||o.sessions.length===0)continue;const l=o.agentId===y,a=document.createElement("div");a.className="sidebar-section-label machine-label"+(o.online?"":" agent-offline-label")+(!l&&o.online?" clickable":""),a.textContent=o.agentName+(o.online?"":" (offline)"),!l&&o.online&&(a.title="\u6253\u5F00 "+o.agentName,a.addEventListener("click",()=>{window.location.href="/a/"+encodeURIComponent(o.agentId)+"/"})),r.appendChild(a),$e(o.sessions,e.home,o.agentId,o.online)}const i=e.tombstones||[];if(i.length>0){const o=document.createElement("div");o.className="sidebar-section-label tombstone-label",o.textContent="\u5931\u6548\u4F1A\u8BDD",r.appendChild(o);for(const l of i){const a=document.createElement("div");a.className="session-item session-tombstone",a.setAttribute("data-session",l.name),l.agentId&&a.setAttribute("data-agent",l.agentId);const c=l.agentId?l.agentOnline?" (agent)":" (agent \u79BB\u7EBF)":"";a.innerHTML=`<svg viewBox="0 0 24 24" fill="currentColor"><path d="M4 6h16v2H4V6zm0 5h16v2H4v-2zm0 5h16v2H4v-2z"></svg>
7
- <span>${d(l.name)}</span><span class="meta">\u5931\u6548${c}</span>
8
- <button class="session-edit-btn" data-session="${d(l.name)}" title="\u6062\u590D\u4F1A\u8BDD"><svg viewBox="0 0 24 24" fill="currentColor" width="14" height="14"><path d="M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM20.71 7.04a1 1 0 000-1.41l-2.34-2.34a1 1 0 00-1.41 0l-1.83 1.83 3.75 3.75 1.83-1.83z"/></svg></button>`,a.title="\u5931\u6548\u4F1A\u8BDD\uFF1A\u70B9\u51FB\u7BA1\u7406\uFF08\u91CD\u5EFA/\u91CD\u547D\u540D/\u5220\u9664\uFF09",a.addEventListener("click",()=>{ce(l.name,a,{tombstone:!0,agentId:l.agentId})});const p=a.querySelector(".session-edit-btn");p&&p.addEventListener("click",b=>{b.stopPropagation(),ce(l.name,p,{tombstone:!0,agentId:l.agentId})}),r.appendChild(a)}}}function d(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}async function W(e,t){if(u===e&&f&&y===(t||null))return;O.style.display="none",R.style.display="none",w.style.display="",w.classList.add("terminal-pending"),Z(),f&&(ae(),f.destroy(),f=null),u=e,y=t||null,window.__tmuxWebScopeAgent=y,window.__tmuxWebCurrentSession=u,$t(e,t);const n=Le(e,t);Xe.set(n,Date.now()+Nt);const s=D.get(n);if(s&&s.state==="working"){s.state="idle",s.doneUntil=void 0,s.unread=!1;const i=r.querySelector(t?'.session-item[data-agent="'+CSS.escape(t)+'"][data-session="'+CSS.escape(e)+'"]':'.session-item[data-session="'+CSS.escape(e)+'"]:not([data-agent])');i&&ue(i,n,s)}for(const i of r.querySelectorAll(".session-item"))i.classList.toggle("active",i.getAttribute("data-session")===e&&(i.getAttribute("data-agent")||null)===y);try{f=await Qe(w,e,{terminal:P.terminal,scrollback:P.scrollback,theme:P.theme,wsBase:y?"/ws/a/"+encodeURIComponent(y):P.wsBase||"/ws"}),Ge()}catch(i){console.error("[shell] terminal init failed:",i);const o=i&&typeof i=="object"&&"message"in i?i.message:String(i);w.textContent="Failed to open terminal for "+e+": "+o,w.classList.remove("terminal-pending")}}let Q=[],m=null,_e=!1;function pt(e){if(!m||!m.files.length)return null;const t=m.repoRoot;if(!t||!e.startsWith(t))return null;const n=e.slice(t.length+1);for(const s of m.files)if(s.path===n)return s.status;return null}async function ft(e){_e=!0;try{const t=await fetch(g("/api/git/status?path="+encodeURIComponent(e)));t.ok?m=await t.json():m=null}catch{m=null}finally{_e=!1}}function ut(){if(!m||!m.branch)return"";const{branch:e,linesAdded:t,linesRemoved:n}=m;let s=`<div class="sidebar-git"><div class="git-branch-badge">
6
+ `,t.addEventListener("click",i=>{i.target.closest(".session-edit-btn")||z(e.name)});const s=t.querySelector(".session-edit-btn");return s&&s.addEventListener("click",i=>{i.stopPropagation(),re(e.name,s,{sessionPath:n})}),t}function pt(e){r.innerHTML='<button class="new-session-sidebar-btn" id="ns-btn">+ New Session</button>';const n=e.recent||[],t=document.createElement("div");t.className="sidebar-section-label"+(O?" clickable":""),t.textContent=O?"\u2190 \u8FD4\u56DE\u672C\u673A":"\u672C\u673A",O&&(t.title="Back to hub",t.addEventListener("click",()=>{window.location.href="/"})),r.appendChild(t),De(n,e.home);const s=e.agents||[];for(const o of s){if(!o.sessions||o.sessions.length===0)continue;const c=o.agentId===y,a=document.createElement("div");a.className="sidebar-section-label machine-label"+(o.online?"":" agent-offline-label")+(!c&&o.online?" clickable":""),a.textContent=o.agentName+(o.online?"":" (offline)"),!c&&o.online&&(a.title="\u6253\u5F00 "+o.agentName,a.addEventListener("click",()=>{window.location.href="/a/"+encodeURIComponent(o.agentId)+"/"})),r.appendChild(a),De(o.sessions,e.home,o.agentId,o.online)}const i=e.tombstones||[];if(i.length>0){const o=document.createElement("div");o.className="sidebar-section-label tombstone-label",o.textContent="\u5931\u6548\u4F1A\u8BDD",r.appendChild(o);for(const c of i){const a=document.createElement("div");a.className="session-item session-tombstone",a.setAttribute("data-session",c.name),c.agentId&&a.setAttribute("data-agent",c.agentId);const l=c.agentId?c.agentOnline?" (agent)":" (agent \u79BB\u7EBF)":"";a.innerHTML=`<svg viewBox="0 0 24 24" fill="currentColor"><path d="M4 6h16v2H4V6zm0 5h16v2H4v-2zm0 5h16v2H4v-2z"></svg>
7
+ <span>${d(c.name)}</span><span class="meta">\u5931\u6548${l}</span>
8
+ <button class="session-edit-btn" data-session="${d(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>`,a.title="\u5931\u6548\u4F1A\u8BDD\uFF1A\u70B9\u51FB\u7BA1\u7406\uFF08\u91CD\u5EFA/\u91CD\u547D\u540D/\u5220\u9664\uFF09",a.addEventListener("click",()=>{re(c.name,a,{tombstone:!0,agentId:c.agentId})});const p=a.querySelector(".session-edit-btn");p&&p.addEventListener("click",b=>{b.stopPropagation(),re(c.name,p,{tombstone:!0,agentId:c.agentId})}),r.appendChild(a)}}}function d(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}async function z(e,n){if(u===e&&f&&y===(n||null))return;U.style.display="none",N.style.display="none",w.style.display="",w.classList.add("terminal-pending"),Q(),f&&(le(),f.destroy(),f=null),u=e,y=n||null,window.__tmuxWebScopeAgent=y,window.__tmuxWebCurrentSession=u,_t(e,n);const t=ke(e,n);Ze.set(t,Date.now()+$t);const s=P.get(t);if(s&&s.state==="working"){s.state="idle",s.doneUntil=void 0,s.unread=!1;const i=r.querySelector(n?'.session-item[data-agent="'+CSS.escape(n)+'"][data-session="'+CSS.escape(e)+'"]':'.session-item[data-session="'+CSS.escape(e)+'"]:not([data-agent])');i&&me(i,t,s)}for(const i of r.querySelectorAll(".session-item"))i.classList.toggle("active",i.getAttribute("data-session")===e&&(i.getAttribute("data-agent")||null)===y);try{f=await et(w,e,{terminal:j.terminal,scrollback:j.scrollback,theme:j.theme,wsBase:y?"/ws/a/"+encodeURIComponent(y):j.wsBase||"/ws"}),Ve()}catch(i){console.error("[shell] terminal init failed:",i);const o=i&&typeof i=="object"&&"message"in i?i.message:String(i);w.textContent="Failed to open terminal for "+e+": "+o,w.classList.remove("terminal-pending")}}let ee=[],m=null,Pe=!1;function ft(e){if(!m||!m.files.length)return null;const n=m.repoRoot;if(!n||!e.startsWith(n))return null;const t=e.slice(n.length+1);for(const s of m.files)if(s.path===t)return s.status;return null}async function ut(e){Pe=!0;try{const n=await fetch(g("/api/git/status?path="+encodeURIComponent(e)));n.ok?m=await n.json():m=null}catch{m=null}finally{Pe=!1}}function mt(){if(!m||!m.branch)return"";const{branch:e,linesAdded:n,linesRemoved:t}=m;let s=`<div class="sidebar-git"><div class="git-branch-badge">
9
9
  <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>
10
- ${d(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>"}r.addEventListener("click",e=>{e.target.closest(".sidebar-git")&&$&&m&&(e.stopPropagation(),Ue())});const z=document.getElementById("header-git"),De=document.getElementById("git-diff-view"),Pe=document.getElementById("gd-path"),ee=document.getElementById("gd-status"),te=document.getElementById("gd-content"),mt=document.getElementById("gd-back");let $=null;function F(e){if(!e||!e.branch){z.style.display="none",$=null;return}$=e.repoRoot;const{branch:t,linesAdded:n,linesRemoved:s}=e;let i=`<span class="branch">${d(t)}</span>`;(n>0||s>0)&&(i+=`<span class="sep">\xB7</span>+<span class="diff-add">${n}</span> <span class="diff-del">-${s}</span>`),z.innerHTML=i,z.style.display="block"}z.addEventListener("click",e=>{$&&m&&(e.stopPropagation(),Ue())});const h=document.getElementById("git-popover"),ne=document.getElementById("git-popover-backdrop");function ye(){const e=z.getBoundingClientRect();h.style.top=e.bottom+4+"px",h.style.left=Math.max(8,Math.min(e.left,window.innerWidth-400))+"px"}function je(){const e=$,t=document.getElementById("git-popover-browse");t&&t.addEventListener("click",()=>{if(ie(),e){me="files",document.querySelectorAll(".mode-btn").forEach(s=>s.classList.remove("active"));const n=document.getElementById("mode-files");n&&n.classList.add("active"),x(e)}})}let Oe="";function Ue(){if(!m)return;const e=m.files||[];if(!e.length)h.innerHTML=`<div class="git-popover-header">No changes \u2014 clean working tree</div>
11
- <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++){const s=e[n],i=s.additions||0,o=s.deletions||0;let l="";switch(s.status){case"M":l='<span class="git-file-status M">M</span>';break;case"A":l='<span class="git-file-status A">A</span>';break;case"D":l='<span class="git-file-status D">D</span>';break;case"?":l='<span class="git-file-status ?">?</span>';break;case"R":l='<span class="git-file-status R">R</span>';break}t+=`<div class="git-popover-item" data-idx="${n}">
12
- ${l}<span class="file-path">${d(s.path)}</span>
10
+ ${d(e)}</div>`;return(n>0||t>0)&&(s+=`<div class="git-diff-stats">+<span class="add">${n}</span> <span class="del">-${t}</span></div>`),s+"</div>"}r.addEventListener("click",e=>{e.target.closest(".sidebar-git")&&A&&m&&(e.stopPropagation(),ze())});const F=document.getElementById("header-git"),je=document.getElementById("git-diff-view"),Oe=document.getElementById("gd-path"),te=document.getElementById("gd-status"),ne=document.getElementById("gd-content"),gt=document.getElementById("gd-back");let A=null;function G(e){if(!e||!e.branch){F.style.display="none",A=null;return}A=e.repoRoot;const{branch:n,linesAdded:t,linesRemoved:s}=e;let i=`<span class="branch">${d(n)}</span>`;(t>0||s>0)&&(i+=`<span class="sep">\xB7</span>+<span class="diff-add">${t}</span> <span class="diff-del">-${s}</span>`),F.innerHTML=i,F.style.display="block"}F.addEventListener("click",e=>{A&&m&&(e.stopPropagation(),ze())});const h=document.getElementById("git-popover"),se=document.getElementById("git-popover-backdrop");function he(){const e=F.getBoundingClientRect();h.style.top=e.bottom+4+"px",h.style.left=Math.max(8,Math.min(e.left,window.innerWidth-400))+"px"}function Ue(){const e=A,n=document.getElementById("git-popover-browse");n&&n.addEventListener("click",()=>{if(oe(),e){ge="files",document.querySelectorAll(".mode-btn").forEach(s=>s.classList.remove("active"));const t=document.getElementById("mode-files");t&&t.classList.add("active"),T(e)}})}let We="";function ze(){if(!m)return;const e=m.files||[];if(!e.length)h.innerHTML=`<div class="git-popover-header">No changes \u2014 clean working tree</div>
11
+ <div class="git-popover-footer"><button id="git-popover-browse">Browse repository \u2192</button></div>`;else{let n=`<div class="git-popover-header">${e.length} file${e.length>1?"s":""} changed</div>`;for(let t=0;t<e.length;t++){const s=e[t],i=s.additions||0,o=s.deletions||0;let 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}n+=`<div class="git-popover-item" data-idx="${t}">
12
+ ${c}<span class="file-path">${d(s.path)}</span>
13
13
  <span class="file-add">${i>0?"+"+i:""}</span>
14
14
  <span class="file-del">${o>0?"-"+o:""}</span>
15
- </div>`}t+='<div class="git-popover-footer"><button id="git-popover-browse">Browse repository \u2192</button></div>',Oe=t,h.innerHTML=t,h.querySelectorAll(".git-popover-item").forEach(n=>{const s=parseInt(n.dataset.idx||"0",10),i=e[s];!i||i.status==="D"||(n.classList.add("clickable"),n.style.cursor="pointer",n.addEventListener("click",()=>ze(i.path)))})}ye(),h.classList.add("open"),ne.classList.add("open"),je()}function gt(){return window.innerWidth>=1024}function We(e,t){const s=(e+(t&&e?`
16
- `:"")+t).split(`
17
- `);let i="",o=0,l=0;for(const a of s){const c=a;if(c.startsWith("@@")){const p=c.match(/@@\s+-(\d+)[^+]*\+(\d+)/);p&&(o=parseInt(p[1],10)-1,l=parseInt(p[2],10)-1),i+=`<div class="diff-line hunk"><span class="ln-body">${d(c)}</span></div>`;continue}if(c.startsWith("diff --git")||c.startsWith("index ")||c.startsWith("--- ")||c.startsWith("+++ ")||c.startsWith("new file")||c.startsWith("deleted file")){c.startsWith("diff --git")&&(i+=`<div class="diff-line header"><span class="ln-body">${d(c)}</span></div>`);continue}if(c.startsWith("+"))l++,i+=`<div class="diff-line add"><span class="ln-no">${l}</span><span class="ln-body">${d(c)}</span></div>`;else if(c.startsWith("-"))o++,i+=`<div class="diff-line del"><span class="ln-no">${o}</span><span class="ln-body">${d(c)}</span></div>`;else if(c.startsWith("\\"))i+=`<div class="diff-line"><span class="ln-body">${d(c)}</span></div>`;else{if(!c&&!o&&!l)continue;o++,l++,i+=`<div class="diff-line"><span class="ln-no">${o}</span><span class="ln-no" style="margin-right:12px">${l}</span><span class="ln-body">${d(c)}</span></div>`}}return{html:i,lineCount:s.length}}let se=null;async function ze(e){const t=$;if(t)if(ie(),gt()){w.style.display="none",f&&(ae(),f.destroy(),f=null,se=u,u=null),F(null),O.style.display="none",R.style.display="none",De.style.display="flex",Pe.textContent=e,ee.textContent="Loading\u2026",te.innerHTML="";try{const n=await fetch(g("/api/git/diff?path="+encodeURIComponent(t)+"&file="+encodeURIComponent(e)));if(!n.ok)throw new Error(await n.text());const s=await n.json();yt(e,s.diff,s.stagedDiff)}catch(n){const s=n instanceof Error?n.message:String(n);ee.textContent="Error",te.innerHTML=`<div class="diff-empty" style="padding:24px;text-align:center;color:var(--panel-muted)">Error: ${d(s)}</div>`}}else{h.innerHTML=`<div class="git-diff-view"><div class="diff-header">
15
+ </div>`}n+='<div class="git-popover-footer"><button id="git-popover-browse">Browse repository \u2192</button></div>',We=n,h.innerHTML=n,h.querySelectorAll(".git-popover-item").forEach(t=>{const s=parseInt(t.dataset.idx||"0",10),i=e[s];!i||i.status==="D"||(t.classList.add("clickable"),t.style.cursor="pointer",t.addEventListener("click",()=>Ge(i.path)))})}he(),h.classList.add("open"),se.classList.add("open"),Ue()}function vt(){return window.innerWidth>=1024}function Fe(e,n){const s=(e+(n&&e?`
16
+ `:"")+n).split(`
17
+ `);let i="",o=0,c=0;for(const a of s){const l=a;if(l.startsWith("@@")){const p=l.match(/@@\s+-(\d+)[^+]*\+(\d+)/);p&&(o=parseInt(p[1],10)-1,c=parseInt(p[2],10)-1),i+=`<div class="diff-line hunk"><span class="ln-body">${d(l)}</span></div>`;continue}if(l.startsWith("diff --git")||l.startsWith("index ")||l.startsWith("--- ")||l.startsWith("+++ ")||l.startsWith("new file")||l.startsWith("deleted file")){l.startsWith("diff --git")&&(i+=`<div class="diff-line header"><span class="ln-body">${d(l)}</span></div>`);continue}if(l.startsWith("+"))c++,i+=`<div class="diff-line add"><span class="ln-no">${c}</span><span class="ln-body">${d(l)}</span></div>`;else if(l.startsWith("-"))o++,i+=`<div class="diff-line del"><span class="ln-no">${o}</span><span class="ln-body">${d(l)}</span></div>`;else if(l.startsWith("\\"))i+=`<div class="diff-line"><span class="ln-body">${d(l)}</span></div>`;else{if(!l&&!o&&!c)continue;o++,c++,i+=`<div class="diff-line"><span class="ln-no">${o}</span><span class="ln-no" style="margin-right:12px">${c}</span><span class="ln-body">${d(l)}</span></div>`}}return{html:i,lineCount:s.length}}let ie=null;async function Ge(e){const n=A;if(n)if(oe(),vt()){w.style.display="none",f&&(le(),f.destroy(),f=null,ie=u,u=null),G(null),U.style.display="none",N.style.display="none",je.style.display="flex",Oe.textContent=e,te.textContent="Loading\u2026",ne.innerHTML="";try{const t=await fetch(g("/api/git/diff?path="+encodeURIComponent(n)+"&file="+encodeURIComponent(e)));if(!t.ok)throw new Error(await t.text());const s=await t.json();ht(e,s.diff,s.stagedDiff)}catch(t){const s=t instanceof Error?t.message:String(t);te.textContent="Error",ne.innerHTML=`<div class="diff-empty" style="padding:24px;text-align:center;color:var(--panel-muted)">Error: ${d(s)}</div>`}}else{h.innerHTML=`<div class="git-diff-view"><div class="diff-header">
18
18
  <button class="diff-back">\u2190 Back</button>
19
19
  <span class="diff-filename">${d(e)}</span>
20
20
  <span class="diff-loading">Loading\u2026</span>
21
- </div></div>`,ye(),h.classList.add("open"),ne.classList.add("open");try{const n=await fetch(g("/api/git/diff?path="+encodeURIComponent(t)+"&file="+encodeURIComponent(e)));if(!n.ok)throw new Error(await n.text());const s=await n.json();vt(e,s.diff,s.stagedDiff)}catch(n){const s=n instanceof Error?n.message:String(n);h.innerHTML=`<div class="git-diff-view"><div class="diff-header">
21
+ </div></div>`,he(),h.classList.add("open"),se.classList.add("open");try{const t=await fetch(g("/api/git/diff?path="+encodeURIComponent(n)+"&file="+encodeURIComponent(e)));if(!t.ok)throw new Error(await t.text());const s=await t.json();yt(e,s.diff,s.stagedDiff)}catch(t){const s=t instanceof Error?t.message:String(t);h.innerHTML=`<div class="git-diff-view"><div class="diff-header">
22
22
  <button class="diff-back">\u2190 Back</button>
23
23
  <span class="diff-filename">${d(e)}</span>
24
- </div><div class="diff-empty">Error loading diff: ${d(s)}</div></div>`}}}function vt(e,t,n){if(!t&&!n){h.innerHTML=`<div class="git-diff-view"><div class="diff-header">
24
+ </div><div class="diff-empty">Error loading diff: ${d(s)}</div></div>`}}}function yt(e,n,t){if(!n&&!t){h.innerHTML=`<div class="git-diff-view"><div class="diff-header">
25
25
  <button class="diff-back">\u2190 Back</button>
26
26
  <span class="diff-filename">${d(e)}</span>
27
- </div><div class="diff-empty">No diff content available</div></div>`;return}const{html:s,lineCount:i}=We(t,n);h.innerHTML=`<div class="git-diff-view"><div class="diff-header">
27
+ </div><div class="diff-empty">No diff content available</div></div>`;return}const{html:s,lineCount:i}=Fe(n,t);h.innerHTML=`<div class="git-diff-view"><div class="diff-header">
28
28
  <button class="diff-back">\u2190 Back</button>
29
29
  <span class="diff-filename">${d(e)}</span>
30
30
  <span class="diff-filesize">${i} lines</span>
31
- </div><div class="diff-content">${s}</div></div>`,h.querySelector(".diff-back")?.addEventListener("click",()=>{h.innerHTML=Oe,ye(),m&&h.querySelectorAll(".git-popover-item").forEach(o=>{const l=parseInt(o.dataset.idx||"0",10),a=m.files[l];!a||a.status==="D"||(o.style.cursor="pointer",o.addEventListener("click",()=>ze(a.path)))}),je()})}function yt(e,t,n){if(!t&&!n){ee.textContent="No diff",te.innerHTML='<div class="diff-empty" style="padding:24px;text-align:center;color:var(--panel-muted)">No diff content available</div>';return}const{html:s,lineCount:i}=We(t,n);Pe.textContent=e,ee.textContent=i+" lines",te.innerHTML=s}function ht(){De.style.display="none",se?(w.style.display="",w.classList.add("terminal-pending"),W(se),se=null):u?(w.style.display="",w.classList.add("terminal-pending"),Ge()):R.style.display="flex"}mt.addEventListener("click",ht);function ie(){h.classList.remove("open"),ne.classList.remove("open")}ne.addEventListener("click",ie),document.addEventListener("keydown",e=>{e.key==="Escape"&&(ie(),fe())});async function Fe(e){try{const n=await(await fetch("/api/fs/session-path?session="+encodeURIComponent(e))).json();if(n.path){const s=await fetch("/api/git/status?path="+encodeURIComponent(n.path));if(s.ok){const i=await s.json();m=i,F(i);return}}}catch{}m=null,F(null)}let oe=null;function Ge(){ae(),u&&(Fe(u),oe=setInterval(()=>{u&&Fe(u)},3e4))}function ae(){oe&&(clearInterval(oe),oe=null)}async function qe(e){let t=e;if(t.startsWith("~"))try{const s=await(await fetch(g("/api/fs/list?path="+encodeURIComponent(t)))).json();typeof s.path=="string"&&s.path&&(t=s.path)}catch{}t=t.replace(/\/+$/,"")||"/",tt(t)}function Ve(e,t){const n=document.createElement("button");n.className="file-tree-bot-btn",n.textContent="+",n.title=`Create bot in ${t}`,n.setAttribute("aria-label",`Create bot in ${t}`),n.addEventListener("click",s=>{s.preventDefault(),s.stopPropagation(),qe(t)}),e.appendChild(n)}function bt(){if(Q=P.fsRoots||[],Q.length===0){if(u){wt(u);return}x("");return}r.innerHTML="";for(const e of Q){const 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> ${d(e)}`,t.addEventListener("click",()=>x(e)),Ve(t,e),r.appendChild(t)}}async function wt(e){r.innerHTML='<div class="file-tree-empty">Loading...</div>';try{const n=await(await fetch(g("/api/fs/session-path?session="+encodeURIComponent(e)))).json();n.path?x(n.path):r.innerHTML='<div class="file-tree-info">Could not determine session directory.</div>'}catch{r.innerHTML='<div class="file-tree-error">Failed to get session directory</div>'}}async function x(e){I=e,r.innerHTML='<div class="file-tree-empty">Loading...</div>';const t=ft(e);try{const s=await(await fetch(g("/api/fs/list?path="+encodeURIComponent(e)))).json(),i=typeof s.path=="string"&&s.path?s.path:e;if(i&&(I=i),await t,r.innerHTML="",i){const a=document.createElement("div");a.className="file-tree-item file-tree-create-bot",a.innerHTML='<span class="file-tree-bot-plus">+</span> Create bot in this folder',a.title=`Create bot in ${i}`,a.addEventListener("click",()=>void qe(i)),r.appendChild(a)}F(m),r.innerHTML+=ut();const o=Lt(i||e);if(o&&!Q.some(c=>i===c)){const c=document.createElement("div");c.className="file-tree-item",c.innerHTML="..",c.addEventListener("click",()=>x(o)),r.appendChild(c)}if(s.dirs)for(const a of s.dirs){const c=a.split("/").pop()||a.split("\\").pop(),p=document.createElement("div");p.className="file-tree-item",p.innerHTML=`<svg viewBox="0 0 24 24" fill="currentColor" class="file-icon"><path d="M10 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2h-8l-2-2z"/></svg> ${d(c)}`,p.addEventListener("click",()=>x(a)),Ve(p,a),r.appendChild(p)}else r.innerHTML="";const l=s.files||[];for(const a of l){const c=a.split("/").pop()||a.split("\\").pop(),p=pt(a);let b="",v="";if(p)switch(p){case"M":b="git-mod",v='<span class="git-file-status M">M</span>';break;case"A":b="git-add",v='<span class="git-file-status A">A</span>';break;case"D":b="git-del",v='<span class="git-file-status D">D</span>';break;case"?":b="git-untracked",v='<span class="git-file-status ?">?</span>';break;case"R":b="git-mod",v='<span class="git-file-status R">R</span>';break}const M=document.createElement("div");M.className="file-tree-item file"+(b?" "+b:""),M.innerHTML=`<span class="file-icon">\u{1F4C4}</span> ${v}${d(c)}`,M.addEventListener("click",()=>Et(a)),r.appendChild(M)}}catch{r.innerHTML='<div class="file-tree-error">Failed to load directory</div>'}}function Lt(e){const t=e.lastIndexOf("/");return t<=0?null:e.substring(0,t)}async function Et(e){K=e,w.style.display="none",f&&(ae(),f.destroy(),f=null,u=null),F(null),Z(),R.style.display="none",O.style.display="flex",nt.textContent=e,E.textContent="Loading...",N.style.display="none";try{const t=await fetch(g("/api/file?path="+encodeURIComponent(e)));if(!t.ok){const s=await t.json();E.textContent=s.error||"Failed to load",U.value="";return}const n=await t.json();U.value=n.content,Y=n.content,Ce=n.content,E.textContent=n.size+" bytes",N.style.display=""}catch{E.textContent="Failed to load",U.value=""}}U.addEventListener("input",()=>{Y=U.value}),N.addEventListener("click",async()=>{N.textContent="Saving...",N.disabled=!0;try{const e=await fetch(g("/api/file"),{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:K,content:Y})});if(!e.ok){const t=await e.json();E.textContent=t.error||"Save failed";return}Ce=Y,E.textContent="Saved"}catch{E.textContent="Save failed"}finally{N.disabled=!1,N.textContent="Save"}}),st.addEventListener("click",async()=>{if(confirm("Delete "+K+"?"))try{const e=await fetch(g("/api/file/delete"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:K})});if(!e.ok){const t=await e.json();E.textContent=t.error||"Delete failed";return}O.style.display="none",R.style.display="flex",I&&x(I)}catch{E.textContent="Delete failed"}}),it.addEventListener("click",()=>{O.style.display="none",R.style.display="flex",I&&x(I)}),ot.addEventListener("click",async()=>{const e=Se.value.trim();if(!e)return;const t=I+"/"+e;try{const n=await fetch(g("/api/file/touch"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:t})});if(!n.ok){const s=await n.json();E.textContent=s.error||"Create failed";return}Se.value="",I&&x(I)}catch{E.textContent="Create failed"}});const le=document.getElementById("force-narrow-toggle");le&&(le.checked=X(),le.addEventListener("change",()=>{try{localStorage.setItem(xe,le.checked?"1":"0")}catch{}Te(),B()})),Te(),document.getElementById("mode-settings").addEventListener("click",()=>{const e=Ie.classList.toggle("open");ge.classList.toggle("open",e)}),ge.addEventListener("click",()=>{Ie.classList.remove("open"),ge.classList.remove("open")});let L="",T=!1,k;const G=document.createElement("div");G.className="session-popover-backdrop",document.body.appendChild(G);const C=document.createElement("div");C.id="session-popover",C.className="session-popover",C.style.display="none",C.innerHTML=`<div class="sp-field">
31
+ </div><div class="diff-content">${s}</div></div>`,h.querySelector(".diff-back")?.addEventListener("click",()=>{h.innerHTML=We,he(),m&&h.querySelectorAll(".git-popover-item").forEach(o=>{const c=parseInt(o.dataset.idx||"0",10),a=m.files[c];!a||a.status==="D"||(o.style.cursor="pointer",o.addEventListener("click",()=>Ge(a.path)))}),Ue()})}function ht(e,n,t){if(!n&&!t){te.textContent="No diff",ne.innerHTML='<div class="diff-empty" style="padding:24px;text-align:center;color:var(--panel-muted)">No diff content available</div>';return}const{html:s,lineCount:i}=Fe(n,t);Oe.textContent=e,te.textContent=i+" lines",ne.innerHTML=s}function bt(){je.style.display="none",ie?(w.style.display="",w.classList.add("terminal-pending"),z(ie),ie=null):u?(w.style.display="",w.classList.add("terminal-pending"),Ve()):N.style.display="flex"}gt.addEventListener("click",bt);function oe(){h.classList.remove("open"),se.classList.remove("open")}se.addEventListener("click",oe),document.addEventListener("keydown",e=>{e.key==="Escape"&&(oe(),ue())});async function qe(e){try{const t=await(await fetch("/api/fs/session-path?session="+encodeURIComponent(e))).json();if(t.path){const s=await fetch("/api/git/status?path="+encodeURIComponent(t.path));if(s.ok){const i=await s.json();m=i,G(i);return}}}catch{}m=null,G(null)}let ae=null;function Ve(){le(),u&&(qe(u),ae=setInterval(()=>{u&&qe(u)},3e4))}function le(){ae&&(clearInterval(ae),ae=null)}async function be(e){let n=e;if(n.startsWith("~"))try{const s=await(await fetch(g("/api/fs/list?path="+encodeURIComponent(n)))).json();typeof s.path=="string"&&s.path&&(n=s.path)}catch{}n=n.replace(/\/+$/,"")||"/",nt(n)}function Je(e,n){const t=document.createElement("button");t.className="file-tree-bot-btn",t.textContent="+",t.title=`Create bot in ${n}`,t.setAttribute("aria-label",`Create bot in ${n}`),t.addEventListener("click",s=>{s.preventDefault(),s.stopPropagation(),be(n)}),e.appendChild(t)}function wt(){if(ee=j.fsRoots||[],ee.length===0){if(u){Lt(u);return}T("");return}r.innerHTML="";for(const e of ee){const n=document.createElement("div");n.className="file-tree-item",n.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> ${d(e)}`,n.addEventListener("click",()=>T(e)),Je(n,e),r.appendChild(n)}}async function Lt(e){r.innerHTML='<div class="file-tree-empty">Loading...</div>';try{const t=await(await fetch(g("/api/fs/session-path?session="+encodeURIComponent(e)))).json();t.path?T(t.path):r.innerHTML='<div class="file-tree-info">Could not determine session directory.</div>'}catch{r.innerHTML='<div class="file-tree-error">Failed to get session directory</div>'}}async function T(e){B=e,r.innerHTML='<div class="file-tree-empty">Loading...</div>';const n=ut(e);try{const s=await(await fetch(g("/api/fs/list?path="+encodeURIComponent(e)))).json(),i=typeof s.path=="string"&&s.path?s.path:e;if(i&&(B=i),await n,r.innerHTML="",i){const a=document.createElement("div");a.className="file-tree-item file-tree-create-bot",a.innerHTML='<span class="file-tree-bot-plus">+</span> Create bot in this folder',a.title=`Create bot in ${i}`,a.addEventListener("click",()=>void be(i)),r.appendChild(a)}G(m),r.innerHTML+=mt();const o=Et(i||e);if(o&&!ee.some(l=>i===l)){const l=document.createElement("div");l.className="file-tree-item",l.innerHTML="..",l.addEventListener("click",()=>T(o)),r.appendChild(l)}if(s.dirs)for(const a of s.dirs){const l=a.split("/").pop()||a.split("\\").pop(),p=document.createElement("div");p.className="file-tree-item",p.innerHTML=`<svg viewBox="0 0 24 24" fill="currentColor" class="file-icon"><path d="M10 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2h-8l-2-2z"/></svg> ${d(l)}`,p.addEventListener("click",()=>T(a)),Je(p,a),r.appendChild(p)}else r.innerHTML="";const c=s.files||[];for(const a of c){const l=a.split("/").pop()||a.split("\\").pop(),p=ft(a);let b="",v="";if(p)switch(p){case"M":b="git-mod",v='<span class="git-file-status M">M</span>';break;case"A":b="git-add",v='<span class="git-file-status A">A</span>';break;case"D":b="git-del",v='<span class="git-file-status D">D</span>';break;case"?":b="git-untracked",v='<span class="git-file-status ?">?</span>';break;case"R":b="git-mod",v='<span class="git-file-status R">R</span>';break}const M=document.createElement("div");M.className="file-tree-item file"+(b?" "+b:""),M.innerHTML=`<span class="file-icon">\u{1F4C4}</span> ${v}${d(l)}`,M.addEventListener("click",()=>kt(a)),r.appendChild(M)}}catch{r.innerHTML='<div class="file-tree-error">Failed to load directory</div>'}}function Et(e){const n=e.lastIndexOf("/");return n<=0?null:e.substring(0,n)}async function kt(e){Y=e,w.style.display="none",f&&(le(),f.destroy(),f=null,u=null),G(null),Q(),N.style.display="none",U.style.display="flex",st.textContent=e,k.textContent="Loading...",$.style.display="none";try{const n=await fetch(g("/api/file?path="+encodeURIComponent(e)));if(!n.ok){const s=await n.json();k.textContent=s.error||"Failed to load",W.value="";return}const t=await n.json();W.value=t.content,X=t.content,Ie=t.content,k.textContent=t.size+" bytes",$.style.display=""}catch{k.textContent="Failed to load",W.value=""}}W.addEventListener("input",()=>{X=W.value}),$.addEventListener("click",async()=>{$.textContent="Saving...",$.disabled=!0;try{const e=await fetch(g("/api/file"),{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:Y,content:X})});if(!e.ok){const n=await e.json();k.textContent=n.error||"Save failed";return}Ie=X,k.textContent="Saved"}catch{k.textContent="Save failed"}finally{$.disabled=!1,$.textContent="Save"}}),it.addEventListener("click",async()=>{if(confirm("Delete "+Y+"?"))try{const e=await fetch(g("/api/file/delete"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:Y})});if(!e.ok){const n=await e.json();k.textContent=n.error||"Delete failed";return}U.style.display="none",N.style.display="flex",B&&T(B)}catch{k.textContent="Delete failed"}}),ot.addEventListener("click",()=>{U.style.display="none",N.style.display="flex",B&&T(B)}),at.addEventListener("click",async()=>{const e=Be.value.trim();if(!e)return;const n=B+"/"+e;try{const t=await fetch(g("/api/file/touch"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:n})});if(!t.ok){const s=await t.json();k.textContent=s.error||"Create failed";return}Be.value="",B&&T(B)}catch{k.textContent="Create failed"}});const ce=document.getElementById("force-narrow-toggle");ce&&(ce.checked=Z(),ce.addEventListener("change",()=>{try{localStorage.setItem(Me,ce.checked?"1":"0")}catch{}He(),x()})),He(),document.getElementById("mode-settings").addEventListener("click",()=>{const e=xe.classList.toggle("open");ve.classList.toggle("open",e)}),ve.addEventListener("click",()=>{xe.classList.remove("open"),ve.classList.remove("open")});let L="",S=!1,E;const q=document.createElement("div");q.className="session-popover-backdrop",document.body.appendChild(q);const C=document.createElement("div");C.id="session-popover",C.className="session-popover",C.style.display="none",C.innerHTML=`<div class="sp-field">
32
32
  <label>Rename session</label>
33
33
  <input type="text" id="sp-name" />
34
34
  </div>
@@ -38,5 +38,6 @@ import{initTerminal as Qe}from"./terminal-core.js";import{initBots as et,openNew
38
38
  </div>
39
39
  <hr class="sp-divider" />
40
40
  <button class="btn primary" id="sp-rebuild" style="display:none">\u91CD\u5EFA\u540C\u540D\u540C\u8DEF\u5F84 session</button>
41
- <button class="btn danger" id="sp-delete">Delete session</button>`,document.body.appendChild(C);function kt(e){const t=e.getBoundingClientRect(),n=window.innerHeight,s=C.offsetHeight||240;let i=t.bottom+4;i+s>n-8&&(i=Math.max(8,t.top-s-4)),C.style.top=i+"px",C.style.left=Math.max(8,Math.min(t.left,window.innerWidth-240))+"px"}function ce(e,t,n){L=e,T=!!n?.tombstone,k=n?.agentId;const s=document.getElementById("sp-name");s.value=e;const i=C.querySelector(".sp-field label");i.textContent=T?"\u91CD\u547D\u540D (\u4EC5\u8BB0\u5F55\uFF0C\u4E0D\u91CD\u5EFA)":"Rename session";const o=document.getElementById("sp-rebuild");o.style.display=T?"":"none";const l=document.getElementById("sp-delete");l.textContent=T?"\u5220\u9664\u5931\u6548\u8BB0\u5F55 (\u5893\u7891\u6D88\u5931)":"Delete session";const a=document.getElementById("sp-save");a.textContent=T?"\u91CD\u547D\u540D":"Save",G.classList.add("open"),C.style.display="block",kt(t),setTimeout(()=>s.focus(),50)}function A(){G.classList.remove("open"),C.style.display="none"}G.addEventListener("click",A),document.getElementById("sp-save").addEventListener("click",async()=>{const e=document.getElementById("sp-name").value.trim();if(!e||e===L){A();return}try{const t=T?{oldName:L,newName:e,agentId:k}:{oldName:L,newName:e,...k?{agentId:k}:{}};if(!(await fetch(g(T?"/api/sessions/rename-tombstone":"/api/sessions/rename"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})).ok)return;A(),B(),!T&&u===L&&(k??null)===y&&W(e,k)}catch{}}),document.getElementById("sp-rebuild").addEventListener("click",async()=>{if(confirm('\u91CD\u5EFA\u4F1A\u8BDD "'+L+'" (\u540C\u540D\u540C\u8DEF\u5F84\uFF0C\u5185\u5BB9\u4E3A\u7A7A)\uFF1F'))try{const e=await fetch(g("/api/sessions/rebuild"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:L,agentId:k})});if(!e.ok){const t=await e.json();alert(t.error||"\u91CD\u5EFA\u5931\u8D25");return}A(),B()}catch{}}),document.getElementById("sp-delete").addEventListener("click",async()=>{if(T){if(!confirm('\u5220\u9664\u5931\u6548\u8BB0\u5F55 "'+L+'"\uFF1F'))return;try{if(!(await fetch(g("/api/sessions/dismiss"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:L,agentId:k})})).ok)return;A(),B()}catch{}return}if(confirm('Delete session "'+L+'"?'))try{if(!(await fetch(g("/api/sessions/kill"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:L,...k?{agentId:k}:{}})})).ok)return;A(),u===L&&(k??null)===y&&(f&&(f.destroy(),f=null),u=null,w.style.display="none",R.style.display="flex"),B()}catch{}}),document.getElementById("sp-cancel").addEventListener("click",A);const Je={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"},re=document.getElementById("mobile-keys"),Ct=new Set(["up","down","left","right","tab","s-tab","space"]),St=400,It=80;let q=0,de=0,pe=!1;function Bt(){q&&(clearTimeout(q),q=0),de&&(clearInterval(de),de=0)}re.addEventListener("mousedown",e=>{e.target.closest("button[data-key]")&&e.preventDefault()}),re.addEventListener("pointerdown",e=>{const t=e.target.closest("button[data-key]");if(!t)return;const n=t.dataset.key;Ct.has(n)&&(pe=!1,q=setTimeout(()=>{q=0,pe=!0,de=setInterval(()=>{const s=Je[n];s&&f&&f.sendInput(s)},It)},St))});for(const e of["pointerup","pointercancel","pointerleave"])re.addEventListener(e,Bt);re.addEventListener("click",e=>{const t=e.target.closest("button[data-key]");if(!t||!f)return;if(pe){pe=!1;return}const n=Je[t.dataset.key];n&&(f.sendInput(n),f.focus())});const S=document.getElementById("mk-input"),Ke=document.getElementById("mk-send");function Ye(){if(!S||!f)return;const e=S.value;e&&(f.sendInput(e+"\r"),S.value="",S.rows=1,f.focus())}if(S&&(S.addEventListener("input",()=>{S.rows=1;const e=S.value.split(`
42
- `).length;S.rows=Math.min(e,4)}),S.addEventListener("keydown",e=>{e.key==="Enter"&&!e.shiftKey&&(e.preventDefault(),Ye())})),Ke&&Ke.addEventListener("click",Ye),window.visualViewport){const 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})}const he=document.getElementById("process-panel"),V=document.getElementById("proc-list"),xt=document.getElementById("proc-close"),be=document.getElementById("proc-backdrop"),Tt=document.getElementById("header-ram");function Mt(){V.innerHTML='<div class="proc-empty">Loading\u2026</div>',fetch(g("/api/system/processes")).then(e=>e.json()).then(e=>{if(!Array.isArray(e)||!e.length){V.innerHTML='<div class="proc-empty">No processes</div>';return}let t="";for(const n of e){const s=n.rss,i=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">'+i+'</span><span class="proc-cmd" title="'+d(n.command)+'">'+d(n.command)+'</span><button class="proc-kill" title="Kill PID '+n.pid+'">&times;</button></div>'}V.innerHTML=t;for(const n of V.querySelectorAll(".proc-row")){const s=n.querySelector(".proc-kill");s&&s.addEventListener("click",i=>{const o=i.target.closest(".proc-row");!o||!confirm("Kill PID "+o.dataset.pid+"?")||fetch(g("/api/system/kill"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({pid:parseInt(o.dataset.pid,10)})}).then(l=>l.json()).then(l=>{l.ok?o.style.opacity="0.3":alert("Failed: "+(l.error||"unknown"))}).catch(()=>alert("Network error"))})}}).catch(()=>{V.innerHTML='<div class="proc-empty">Failed to load</div>'})}function Ht(){he.classList.add("open"),be.classList.add("open"),Mt()}function fe(){he.classList.remove("open"),be.classList.remove("open")}Tt.addEventListener("click",e=>{e.stopPropagation(),he.classList.contains("open")?fe():Ht()}),xt.addEventListener("click",fe),be.addEventListener("click",fe);const Rt=2e3;let J=null,we=null;const _=new Map,D=new Map,Nt=5e3,Xe=new Map;function Le(e,t){return(t?"a:"+t+":":"l:")+e}function At(e,t,n){const s=Le(e,t);if(n==="working"){const p=Xe.get(s);if(p&&Date.now()<p)return}const i=D.get(s),o=e===u&&(t??null)===y,l=n==="idle"&&i?.state==="working";D.set(s,{session:e,agentId:t,state:n,doneUntil:l?Date.now()+Rt:void 0,unread:l?!o:!1});const a=t?'.session-item[data-agent="'+CSS.escape(t)+'"][data-session="'+CSS.escape(e)+'"]':'.session-item[data-session="'+CSS.escape(e)+'"]:not([data-agent])',c=r.querySelector(a);c&&ue(c,s,D.get(s))}function ue(e,t,n){const s=_.get(t);s&&(clearTimeout(s),_.delete(t)),e.classList.remove("working","just-done");const i=n.session===u&&(n.agentId??null)===y;n.state==="working"?e.classList.add("working"):i&&n.doneUntil&&Date.now()<n.doneUntil?(e.classList.add("just-done"),_.set(t,setTimeout(()=>{e.classList.remove("just-done"),_.delete(t)},Math.max(0,n.doneUntil-Date.now())))):!i&&n.unread&&e.classList.add("just-done")}function Ee(){for(const[e,t]of D){const 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=r.querySelector(n);s&&ue(s,e,t)}}function $t(e,t){const n=Le(e,t),s=D.get(n);if(!s)return;const i=_.get(n);i&&(clearTimeout(i),_.delete(n)),s.doneUntil=void 0,s.unread=!1;const o=t?'.session-item[data-agent="'+CSS.escape(t)+'"][data-session="'+CSS.escape(e)+'"]':'.session-item[data-session="'+CSS.escape(e)+'"]:not([data-agent])',l=r.querySelector(o);l&&ue(l,n,s)}function Ze(){if(J||we)return;const e=localStorage.getItem("tmux-web-token");let n=(location.protocol==="https:"?"wss:":"ws:")+"//"+location.host+"/ws/activity";e&&(n+="?token="+encodeURIComponent(e));try{const s=new WebSocket(n);J=s,s.onmessage=i=>{try{const o=JSON.parse(String(i.data));o&&o.type==="session.activity"&&typeof o.session=="string"&&At(o.session,o.agentId||void 0,o.state==="working"?"working":"idle")}catch{}},s.onclose=()=>{J===s&&(J=null,we=setTimeout(()=>{we=null,Ze()},5e3))},s.onerror=()=>{try{s.close()}catch{}}}catch{J=null}}window.__openSession=W,window.__refreshSidebar=B,B(),Z(),Ee(),Ze(),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&Ee()}),setInterval(()=>{document.visibilityState==="visible"&&B()},1e4),et();
41
+ <button class="btn" id="sp-create-bot" style="display:none">\uFF0B \u5728\u6B64\u76EE\u5F55\u521B\u5EFA Bot</button>
42
+ <button class="btn danger" id="sp-delete">Delete session</button>`,document.body.appendChild(C);function Ct(e){const n=e.getBoundingClientRect(),t=window.innerHeight,s=C.offsetHeight||240;let i=n.bottom+4;i+s>t-8&&(i=Math.max(8,n.top-s-4)),C.style.top=i+"px",C.style.left=Math.max(8,Math.min(n.left,window.innerWidth-240))+"px"}let _="";function re(e,n,t){L=e,S=!!t?.tombstone,E=t?.agentId,_=t?.sessionPath||"";const s=document.getElementById("sp-name");s.value=e;const i=C.querySelector(".sp-field label");i.textContent=S?"\u91CD\u547D\u540D (\u4EC5\u8BB0\u5F55\uFF0C\u4E0D\u91CD\u5EFA)":"Rename session";const o=document.getElementById("sp-rebuild");o.style.display=S?"":"none";const c=document.getElementById("sp-delete");c.textContent=S?"\u5220\u9664\u5931\u6548\u8BB0\u5F55 (\u5893\u7891\u6D88\u5931)":"Delete session";const a=document.getElementById("sp-save");a.textContent=S?"\u91CD\u547D\u540D":"Save";const l=document.getElementById("sp-create-bot");l.style.display=!S&&!E&&_?"":"none",l.title=_?`Create bot in ${_}`:"",q.classList.add("open"),C.style.display="block",Ct(n),setTimeout(()=>s.focus(),50)}function H(){q.classList.remove("open"),C.style.display="none"}q.addEventListener("click",H),document.getElementById("sp-create-bot").addEventListener("click",()=>{if(!_)return;const e=_;H(),be(e)}),document.getElementById("sp-save").addEventListener("click",async()=>{const e=document.getElementById("sp-name").value.trim();if(!e||e===L){H();return}try{const n=S?{oldName:L,newName:e,agentId:E}:{oldName:L,newName:e,...E?{agentId:E}:{}};if(!(await fetch(g(S?"/api/sessions/rename-tombstone":"/api/sessions/rename"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)})).ok)return;H(),x(),!S&&u===L&&(E??null)===y&&z(e,E)}catch{}}),document.getElementById("sp-rebuild").addEventListener("click",async()=>{if(confirm('\u91CD\u5EFA\u4F1A\u8BDD "'+L+'" (\u540C\u540D\u540C\u8DEF\u5F84\uFF0C\u5185\u5BB9\u4E3A\u7A7A)\uFF1F'))try{const e=await fetch(g("/api/sessions/rebuild"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:L,agentId:E})});if(!e.ok){const n=await e.json();alert(n.error||"\u91CD\u5EFA\u5931\u8D25");return}H(),x()}catch{}}),document.getElementById("sp-delete").addEventListener("click",async()=>{if(S){if(!confirm('\u5220\u9664\u5931\u6548\u8BB0\u5F55 "'+L+'"\uFF1F'))return;try{if(!(await fetch(g("/api/sessions/dismiss"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:L,agentId:E})})).ok)return;H(),x()}catch{}return}if(confirm('Delete session "'+L+'"?'))try{if(!(await fetch(g("/api/sessions/kill"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:L,...E?{agentId:E}:{}})})).ok)return;H(),u===L&&(E??null)===y&&(f&&(f.destroy(),f=null),u=null,w.style.display="none",N.style.display="flex"),x()}catch{}}),document.getElementById("sp-cancel").addEventListener("click",H);const Ke={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"},de=document.getElementById("mobile-keys"),St=new Set(["up","down","left","right","tab","s-tab","space"]),It=400,Bt=80;let V=0,pe=0,fe=!1;function xt(){V&&(clearTimeout(V),V=0),pe&&(clearInterval(pe),pe=0)}de.addEventListener("mousedown",e=>{e.target.closest("button[data-key]")&&e.preventDefault()}),de.addEventListener("pointerdown",e=>{const n=e.target.closest("button[data-key]");if(!n)return;const t=n.dataset.key;St.has(t)&&(fe=!1,V=setTimeout(()=>{V=0,fe=!0,pe=setInterval(()=>{const s=Ke[t];s&&f&&f.sendInput(s)},Bt)},It))});for(const e of["pointerup","pointercancel","pointerleave"])de.addEventListener(e,xt);de.addEventListener("click",e=>{const n=e.target.closest("button[data-key]");if(!n||!f)return;if(fe){fe=!1;return}const t=Ke[n.dataset.key];t&&(f.sendInput(t),f.focus())});const I=document.getElementById("mk-input"),Ye=document.getElementById("mk-send");function Xe(){if(!I||!f)return;const e=I.value;e&&(f.sendInput(e+"\r"),I.value="",I.rows=1,f.focus())}if(I&&(I.addEventListener("input",()=>{I.rows=1;const e=I.value.split(`
43
+ `).length;I.rows=Math.min(e,4)}),I.addEventListener("keydown",e=>{e.key==="Enter"&&!e.shiftKey&&(e.preventDefault(),Xe())})),Ye&&Ye.addEventListener("click",Xe),window.visualViewport){const e=document.querySelector(".app-layout"),n=()=>{e&&(e.style.height=window.visualViewport.height+"px"),window.scrollTo(0,0),document.documentElement.scrollTop=0,document.body.scrollTop=0};window.visualViewport.addEventListener("resize",n),window.addEventListener("orientationchange",()=>setTimeout(n,100)),document.addEventListener("touchstart",()=>{(window.scrollY>0||document.documentElement.scrollTop>0)&&window.scrollTo(0,0)},{passive:!0})}const we=document.getElementById("process-panel"),J=document.getElementById("proc-list"),Tt=document.getElementById("proc-close"),Le=document.getElementById("proc-backdrop"),Mt=document.getElementById("header-ram");function Ht(){J.innerHTML='<div class="proc-empty">Loading\u2026</div>',fetch(g("/api/system/processes")).then(e=>e.json()).then(e=>{if(!Array.isArray(e)||!e.length){J.innerHTML='<div class="proc-empty">No processes</div>';return}let n="";for(const t of e){const s=t.rss,i=s<1048576?(s/1024).toFixed(0)+"K":(s/1048576).toFixed(1)+"M";n+='<div class="proc-row" data-pid="'+t.pid+'"><span class="proc-mem">'+t.mem+'%</span><span class="proc-rss">'+i+'</span><span class="proc-cmd" title="'+d(t.command)+'">'+d(t.command)+'</span><button class="proc-kill" title="Kill PID '+t.pid+'">&times;</button></div>'}J.innerHTML=n;for(const t of J.querySelectorAll(".proc-row")){const s=t.querySelector(".proc-kill");s&&s.addEventListener("click",i=>{const o=i.target.closest(".proc-row");!o||!confirm("Kill PID "+o.dataset.pid+"?")||fetch(g("/api/system/kill"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({pid:parseInt(o.dataset.pid,10)})}).then(c=>c.json()).then(c=>{c.ok?o.style.opacity="0.3":alert("Failed: "+(c.error||"unknown"))}).catch(()=>alert("Network error"))})}}).catch(()=>{J.innerHTML='<div class="proc-empty">Failed to load</div>'})}function Rt(){we.classList.add("open"),Le.classList.add("open"),Ht()}function ue(){we.classList.remove("open"),Le.classList.remove("open")}Mt.addEventListener("click",e=>{e.stopPropagation(),we.classList.contains("open")?ue():Rt()}),Tt.addEventListener("click",ue),Le.addEventListener("click",ue);const Nt=2e3;let K=null,Ee=null;const D=new Map,P=new Map,$t=5e3,Ze=new Map;function ke(e,n){return(n?"a:"+n+":":"l:")+e}function At(e,n,t){const s=ke(e,n);if(t==="working"){const p=Ze.get(s);if(p&&Date.now()<p)return}const i=P.get(s),o=e===u&&(n??null)===y,c=t==="idle"&&i?.state==="working";P.set(s,{session:e,agentId:n,state:t,doneUntil:c?Date.now()+Nt:void 0,unread:c?!o:!1});const a=n?'.session-item[data-agent="'+CSS.escape(n)+'"][data-session="'+CSS.escape(e)+'"]':'.session-item[data-session="'+CSS.escape(e)+'"]:not([data-agent])',l=r.querySelector(a);l&&me(l,s,P.get(s))}function me(e,n,t){const s=D.get(n);s&&(clearTimeout(s),D.delete(n)),e.classList.remove("working","just-done");const i=t.session===u&&(t.agentId??null)===y;t.state==="working"?e.classList.add("working"):i&&t.doneUntil&&Date.now()<t.doneUntil?(e.classList.add("just-done"),D.set(n,setTimeout(()=>{e.classList.remove("just-done"),D.delete(n)},Math.max(0,t.doneUntil-Date.now())))):!i&&t.unread&&e.classList.add("just-done")}function Ce(){for(const[e,n]of P){const t=n.agentId?'.session-item[data-agent="'+CSS.escape(n.agentId)+'"][data-session="'+CSS.escape(n.session)+'"]':'.session-item[data-session="'+CSS.escape(n.session)+'"]:not([data-agent])',s=r.querySelector(t);s&&me(s,e,n)}}function _t(e,n){const t=ke(e,n),s=P.get(t);if(!s)return;const i=D.get(t);i&&(clearTimeout(i),D.delete(t)),s.doneUntil=void 0,s.unread=!1;const o=n?'.session-item[data-agent="'+CSS.escape(n)+'"][data-session="'+CSS.escape(e)+'"]':'.session-item[data-session="'+CSS.escape(e)+'"]:not([data-agent])',c=r.querySelector(o);c&&me(c,t,s)}function Qe(){if(K||Ee)return;const e=localStorage.getItem("tmux-web-token");let t=(location.protocol==="https:"?"wss:":"ws:")+"//"+location.host+"/ws/activity";e&&(t+="?token="+encodeURIComponent(e));try{const s=new WebSocket(t);K=s,s.onmessage=i=>{try{const o=JSON.parse(String(i.data));o&&o.type==="session.activity"&&typeof o.session=="string"&&At(o.session,o.agentId||void 0,o.state==="working"?"working":"idle")}catch{}},s.onclose=()=>{K===s&&(K=null,Ee=setTimeout(()=>{Ee=null,Qe()},5e3))},s.onerror=()=>{try{s.close()}catch{}}}catch{K=null}}window.__openSession=z,window.__refreshSidebar=x,x(),Q(),Ce(),Qe(),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&Ce()}),setInterval(()=>{document.visibilityState==="visible"&&x()},1e4),tt();
@@ -1 +1 @@
1
- function m(s,c){const{manager:o,userAuth:u}=c,a=async(t,r)=>{const e=t.req.header("x-bots-token");return e&&e===o.token?r():u()(t,r)},l=()=>a,n=()=>u();s.get("/api/bots/catalog",n(),async t=>t.json(await o.catalog())),s.get("/api/bots/templates",n(),t=>t.json(o.listTemplates())),s.post("/api/bots/templates",n(),async t=>{const r=await t.req.json().catch(()=>null);if(!r||!r.manifest||typeof r.manifest.name!="string")return t.json({error:"manifest.name is required"},400);try{const e=o.saveTemplate({id:typeof r.id=="string"?r.id:void 0,manifest:r.manifest});return t.json(e,200)}catch(e){return t.json({error:e instanceof Error?e.message:String(e)},400)}}),s.delete("/api/bots/templates/:id",n(),t=>o.deleteTemplate(t.req.param("id"))?t.json({ok:!0}):t.json({error:"not found"},404)),s.get("/api/bots",a,t=>{const r=t.req.query("project")||void 0,e=t.req.query("parent")||void 0,d=t.req.query("status")||void 0;return t.json(o.listBots({project:r,parentBotId:e,parentOnly:!!e,status:d}))});const p=async t=>{const r=await t.req.json().catch(()=>null);if(!r||typeof r.templateId!="string")return t.json({error:"templateId is required"},400);try{const e=o.createInstance({templateId:r.templateId,title:typeof r.title=="string"?r.title:void 0,projectPath:typeof r.projectPath=="string"?r.projectPath:void 0,isolation:r.isolation==="worktree"?"worktree":"shared",parentBotId:typeof r.parentBotId=="string"?r.parentBotId:void 0,runtimeMode:r.runtimeMode});return t.json(e,201)}catch(e){return t.json({error:e instanceof Error?e.message:String(e)},400)}};s.post("/api/bots",n(),p),s.post("/api/bots/create",l(),p),s.post("/api/bots/list_templates",a,t=>t.json(o.listTemplates().map(r=>({id:r.id,name:r.manifest.name,description:r.manifest.description,orchestrator:!!r.manifest.orchestrator})))),s.post("/api/bots/list",a,async t=>{const r=await t.req.json().catch(()=>({})),e=r.parentBotId,d=o.listBots({parentBotId:r.parentOnly&&e?e:void 0,status:r.status});return t.json(d.map(i=>({id:i.id,title:i.title,status:i.status,projectPath:i.projectPath,parentBotId:i.parentBotId,depth:i.depth,lastText:i.lastText?.slice(0,400),updatedAt:i.updatedAt})))}),s.post("/api/bots/status",a,async t=>{const r=await t.req.json().catch(()=>({}));if(!r.botId)return t.json({error:"botId is required"},400);try{return t.json(o.status(r.botId))}catch(e){return t.json({error:e instanceof Error?e.message:String(e)},404)}}),s.post("/api/bots/message",a,async t=>{const r=await t.req.json().catch(()=>({}));if(!r.botId||typeof r.text!="string")return t.json({error:"botId and text are required"},400);try{return await o.input(r.botId,r.text,r.mode==="follow_up"?"follow_up":r.mode==="steer"?"steer":void 0),t.json({ok:!0})}catch(e){return t.json({error:e instanceof Error?e.message:String(e)},400)}}),s.post("/api/bots/wait",a,async t=>{const r=await t.req.json().catch(()=>({}));return!Array.isArray(r.botIds)||r.botIds.length===0?t.json({error:"botIds is required"},400):t.json(await o.waitFor(r.botIds,typeof r.timeoutMs=="number"?r.timeoutMs:void 0))}),s.post("/api/bots/result",a,async t=>{const r=await t.req.json().catch(()=>({}));if(!r.botId)return t.json({error:"botId is required"},400);try{return t.json(o.result(r.botId))}catch(e){return t.json({error:e instanceof Error?e.message:String(e)},404)}}),s.post("/api/bots/stop",a,async t=>{const r=await t.req.json().catch(()=>({}));if(!r.botId)return t.json({error:"botId is required"},400);try{return o.stop(r.botId,r.cascade!==!1),t.json({ok:!0})}catch(e){return t.json({error:e instanceof Error?e.message:String(e)},400)}}),s.post("/api/bots/approvals",a,t=>t.json(o.listApprovals())),s.post("/api/bots/approve",a,async t=>{const r=await t.req.json().catch(()=>({}));if(!r.botId||!r.requestId)return t.json({error:"botId and requestId are required"},400);const e=t.req.header("x-bots-token")===o.token?"parent-bot":"human";if(e==="parent-bot"&&!r.reason)return t.json({error:"a reason is required when a bot approves"},400);try{return t.json(o.respondApproval(r.botId,r.requestId,r.allow===!0,r.reason,e))}catch(d){return t.json({error:d instanceof Error?d.message:String(d)},400)}}),s.get("/api/bots/approvals",n(),t=>t.json(o.listApprovals())),s.get("/api/bots/:id",n(),t=>{const r=o.getBot(t.req.param("id"));return r?t.json(r):t.json({error:"not found"},404)}),s.get("/api/bots/:id/events",n(),t=>{const r=Number(t.req.query("limit"))||400;return t.json(o.store.readEvents(t.req.param("id"),r))}),s.post("/api/bots/:id/input",n(),async t=>{const r=await t.req.json().catch(()=>({}));if(typeof r.text!="string"||!r.text.trim())return t.json({error:"text is required"},400);try{return await o.input(t.req.param("id"),r.text,r.mode==="follow_up"?"follow_up":r.mode==="steer"?"steer":void 0),t.json({ok:!0})}catch(e){return t.json({error:e instanceof Error?e.message:String(e)},400)}}),s.post("/api/bots/:id/stop",n(),t=>{try{return o.stop(t.req.param("id"),!0),t.json({ok:!0})}catch(r){return t.json({error:r instanceof Error?r.message:String(r)},400)}}),s.post("/api/bots/:id/resume",n(),t=>{try{return o.resume(t.req.param("id")),t.json({ok:!0})}catch(r){return t.json({error:r instanceof Error?r.message:String(r)},400)}}),s.post("/api/bots/:id/approve",n(),async t=>{const r=await t.req.json().catch(()=>({}));if(!r.requestId)return t.json({error:"requestId is required"},400);try{return t.json(o.respondApproval(t.req.param("id"),r.requestId,r.allow===!0,r.reason,"human"))}catch(e){return t.json({error:e instanceof Error?e.message:String(e)},400)}}),s.delete("/api/bots/:id",n(),t=>{try{return o.deleteBot(t.req.param("id"),!0),t.json({ok:!0})}catch(r){return t.json({error:r instanceof Error?r.message:String(r)},400)}})}export{m as registerBotRoutes};
1
+ import{exportBots as m,importBots as b}from"./transfer.js";function f(s,c){const{manager:o,userAuth:u}=c,a=async(r,t)=>{const e=r.req.header("x-bots-token");return e&&e===o.token?t():u()(r,t)},l=()=>a,n=()=>u();s.get("/api/bots/catalog",n(),async r=>r.json(await o.catalog())),s.get("/api/bots/templates",n(),r=>r.json(o.listTemplates())),s.post("/api/bots/templates",n(),async r=>{const t=await r.req.json().catch(()=>null);if(!t||!t.manifest||typeof t.manifest.name!="string")return r.json({error:"manifest.name is required"},400);try{const e=o.saveTemplate({id:typeof t.id=="string"?t.id:void 0,manifest:t.manifest});return r.json(e,200)}catch(e){return r.json({error:e instanceof Error?e.message:String(e)},400)}}),s.get("/api/bots/export",n(),r=>{const t=m(o.store);return r.json(t,200,{"content-disposition":`attachment; filename="tmux-weblink-bots-${t.exportedAt.slice(0,10)}.json"`})}),s.post("/api/bots/import",n(),async r=>{const t=await r.req.json().catch(()=>null);if(!t)return r.json({error:"invalid bundle"},400);try{return r.json(b(o.store,t,{overwriteLibrary:t.overwriteLibrary===!0}))}catch(e){return r.json({error:e instanceof Error?e.message:String(e)},400)}}),s.delete("/api/bots/templates/:id",n(),r=>o.deleteTemplate(r.req.param("id"))?r.json({ok:!0}):r.json({error:"not found"},404)),s.get("/api/bots",a,r=>{const t=r.req.query("project")||void 0,e=r.req.query("parent")||void 0,d=r.req.query("status")||void 0;return r.json(o.listBots({project:t,parentBotId:e,parentOnly:!!e,status:d}))});const p=async r=>{const t=await r.req.json().catch(()=>null);if(!t||typeof t.templateId!="string")return r.json({error:"templateId is required"},400);try{const e=o.createInstance({templateId:t.templateId,title:typeof t.title=="string"?t.title:void 0,projectPath:typeof t.projectPath=="string"?t.projectPath:void 0,isolation:t.isolation==="worktree"?"worktree":"shared",parentBotId:typeof t.parentBotId=="string"?t.parentBotId:void 0,runtimeMode:t.runtimeMode});return r.json(e,201)}catch(e){return r.json({error:e instanceof Error?e.message:String(e)},400)}};s.post("/api/bots",n(),p),s.post("/api/bots/create",l(),p),s.post("/api/bots/list_templates",a,r=>r.json(o.listTemplates().map(t=>({id:t.id,name:t.manifest.name,description:t.manifest.description,orchestrator:!!t.manifest.orchestrator})))),s.post("/api/bots/list",a,async r=>{const t=await r.req.json().catch(()=>({})),e=t.parentBotId,d=o.listBots({parentBotId:t.parentOnly&&e?e:void 0,status:t.status});return r.json(d.map(i=>({id:i.id,title:i.title,status:i.status,projectPath:i.projectPath,parentBotId:i.parentBotId,depth:i.depth,lastText:i.lastText?.slice(0,400),updatedAt:i.updatedAt})))}),s.post("/api/bots/status",a,async r=>{const t=await r.req.json().catch(()=>({}));if(!t.botId)return r.json({error:"botId is required"},400);try{return r.json(o.status(t.botId))}catch(e){return r.json({error:e instanceof Error?e.message:String(e)},404)}}),s.post("/api/bots/message",a,async r=>{const t=await r.req.json().catch(()=>({}));if(!t.botId||typeof t.text!="string")return r.json({error:"botId and text are required"},400);try{return await o.input(t.botId,t.text,t.mode==="follow_up"?"follow_up":t.mode==="steer"?"steer":void 0),r.json({ok:!0})}catch(e){return r.json({error:e instanceof Error?e.message:String(e)},400)}}),s.post("/api/bots/wait",a,async r=>{const t=await r.req.json().catch(()=>({}));return!Array.isArray(t.botIds)||t.botIds.length===0?r.json({error:"botIds is required"},400):r.json(await o.waitFor(t.botIds,typeof t.timeoutMs=="number"?t.timeoutMs:void 0))}),s.post("/api/bots/result",a,async r=>{const t=await r.req.json().catch(()=>({}));if(!t.botId)return r.json({error:"botId is required"},400);try{return r.json(o.result(t.botId))}catch(e){return r.json({error:e instanceof Error?e.message:String(e)},404)}}),s.post("/api/bots/stop",a,async r=>{const t=await r.req.json().catch(()=>({}));if(!t.botId)return r.json({error:"botId is required"},400);try{return o.stop(t.botId,t.cascade!==!1),r.json({ok:!0})}catch(e){return r.json({error:e instanceof Error?e.message:String(e)},400)}}),s.post("/api/bots/approvals",a,r=>r.json(o.listApprovals())),s.post("/api/bots/approve",a,async r=>{const t=await r.req.json().catch(()=>({}));if(!t.botId||!t.requestId)return r.json({error:"botId and requestId are required"},400);const e=r.req.header("x-bots-token")===o.token?"parent-bot":"human";if(e==="parent-bot"&&!t.reason)return r.json({error:"a reason is required when a bot approves"},400);try{return r.json(o.respondApproval(t.botId,t.requestId,t.allow===!0,t.reason,e))}catch(d){return r.json({error:d instanceof Error?d.message:String(d)},400)}}),s.get("/api/bots/approvals",n(),r=>r.json(o.listApprovals())),s.get("/api/bots/:id",n(),r=>{const t=o.getBot(r.req.param("id"));return t?r.json(t):r.json({error:"not found"},404)}),s.get("/api/bots/:id/events",n(),r=>{const t=Number(r.req.query("limit"))||400;return r.json(o.store.readEvents(r.req.param("id"),t))}),s.post("/api/bots/:id/input",n(),async r=>{const t=await r.req.json().catch(()=>({}));if(typeof t.text!="string"||!t.text.trim())return r.json({error:"text is required"},400);try{return await o.input(r.req.param("id"),t.text,t.mode==="follow_up"?"follow_up":t.mode==="steer"?"steer":void 0),r.json({ok:!0})}catch(e){return r.json({error:e instanceof Error?e.message:String(e)},400)}}),s.post("/api/bots/:id/stop",n(),r=>{try{return o.stop(r.req.param("id"),!0),r.json({ok:!0})}catch(t){return r.json({error:t instanceof Error?t.message:String(t)},400)}}),s.post("/api/bots/:id/resume",n(),r=>{try{return o.resume(r.req.param("id")),r.json({ok:!0})}catch(t){return r.json({error:t instanceof Error?t.message:String(t)},400)}}),s.post("/api/bots/:id/approve",n(),async r=>{const t=await r.req.json().catch(()=>({}));if(!t.requestId)return r.json({error:"requestId is required"},400);try{return r.json(o.respondApproval(r.req.param("id"),t.requestId,t.allow===!0,t.reason,"human"))}catch(e){return r.json({error:e instanceof Error?e.message:String(e)},400)}}),s.delete("/api/bots/:id",n(),r=>{try{return o.deleteBot(r.req.param("id"),!0),r.json({ok:!0})}catch(t){return r.json({error:t instanceof Error?t.message:String(t)},400)}})}export{f as registerBotRoutes};
@@ -1,3 +1,3 @@
1
- import{existsSync as r,mkdirSync as c,readFileSync as o,writeFileSync as l,readdirSync as d,rmSync as m,appendFileSync as S}from"node:fs";import n from"node:path";import{randomBytes as f,randomUUID as j}from"node:crypto";import{getDataRoot as D}from"../state-paths.js";class g{root;instancesFile;instances=new Map;token;constructor(t){this.root=t||n.join(D(),"bots"),c(this.root,{recursive:!0,mode:448}),c(n.join(this.root,"templates"),{recursive:!0,mode:448}),c(n.join(this.root,"instances"),{recursive:!0,mode:448}),this.instancesFile=n.join(this.root,"instances.json"),this.loadInstances(),this.token=this.loadOrCreateToken()}loadOrCreateToken(){const t=n.join(this.root,"api-token");if(r(t)){const s=o(t,"utf8").trim();if(s)return s}const e=f(24).toString("hex");return l(t,e,{mode:384}),e}templatesDir=()=>n.join(this.root,"templates");listTemplates(){const t=this.templatesDir();if(!r(t))return[];const e=[];for(const s of d(t))if(s.endsWith(".json"))try{const i=JSON.parse(o(n.join(t,s),"utf8"));i&&i.id&&i.manifest&&e.push(i)}catch{}return e.sort((s,i)=>s.manifest.name.localeCompare(i.manifest.name))}getTemplate(t){const e=n.join(this.templatesDir(),`${t}.json`);if(!r(e))return null;try{return JSON.parse(o(e,"utf8"))}catch{return null}}saveTemplate(t){const e=new Date().toISOString(),s=t.id||`${Date.now().toString(36)}-${f(3).toString("hex")}`,i=this.getTemplate(s),a={id:s,manifest:{...t.manifest,schema:1},createdAt:i?.createdAt||e,updatedAt:e};return l(n.join(this.templatesDir(),`${s}.json`),JSON.stringify(a,null,2),{mode:384}),a}deleteTemplate(t){const e=n.join(this.templatesDir(),`${t}.json`);return r(e)?(m(e),!0):!1}loadInstances(){if(r(this.instancesFile))try{const t=JSON.parse(o(this.instancesFile,"utf8"));for(const e of t)this.instances.set(e.id,e)}catch{}}persistInstances(){l(this.instancesFile,JSON.stringify([...this.instances.values()],null,2),{mode:384})}listInstances(){return[...this.instances.values()].sort((t,e)=>t.createdAt.localeCompare(e.createdAt))}getInstance(t){return this.instances.get(t)||null}saveInstance(t){t.updatedAt=new Date().toISOString(),this.instances.set(t.id,t),this.persistInstances()}deleteInstance(t){this.instances.delete(t),this.persistInstances(),m(this.instanceDir(t),{recursive:!0,force:!0})}instanceDir(t){return n.join(this.root,"instances",t)}agentDir(t){return n.join(this.instanceDir(t),"agent")}sessionsDir(t){return n.join(this.instanceDir(t),"sessions")}appendEvent(t,e){try{c(this.instanceDir(t),{recursive:!0,mode:448}),S(n.join(this.instanceDir(t),"events.jsonl"),`${JSON.stringify(e)}
2
- `,{mode:384})}catch{}}readEvents(t,e=2e3){const s=n.join(this.instanceDir(t),"events.jsonl");if(!r(s))return[];const a=o(s,"utf8").split(`
3
- `).filter(Boolean).slice(-e),h=[];for(const p of a)try{h.push(JSON.parse(p))}catch{}return h}newId(){return j()}}let u=null;function F(){return u||(u=new g),u}export{g as BotStore,F as getBotStore};
1
+ import{existsSync as o,mkdirSync as a,readFileSync as c,writeFileSync as h,readdirSync as u,rmSync as m,appendFileSync as j,copyFileSync as S}from"node:fs";import n from"node:path";import{randomBytes as f,randomUUID as D}from"node:crypto";import{getDataRoot as y}from"../state-paths.js";class g{root;instancesFile;instances=new Map;token;constructor(t){this.root=t||process.env.TMUX_WEB_BOTS_DIR||n.join(y(),"bots"),a(this.root,{recursive:!0,mode:448}),a(n.join(this.root,"templates"),{recursive:!0,mode:448}),a(n.join(this.root,"templates",".history"),{recursive:!0,mode:448}),a(n.join(this.root,"instances"),{recursive:!0,mode:448}),this.instancesFile=n.join(this.root,"instances.json"),this.loadInstances(),this.token=this.loadOrCreateToken()}loadOrCreateToken(){const t=n.join(this.root,"api-token");if(o(t)){const s=c(t,"utf8").trim();if(s)return s}const e=f(24).toString("hex");return h(t,e,{mode:384}),e}templatesDir=()=>n.join(this.root,"templates");listTemplates(){const t=this.templatesDir();if(!o(t))return[];const e=[];for(const s of u(t))if(s.endsWith(".json"))try{const i=JSON.parse(c(n.join(t,s),"utf8"));i&&i.id&&i.manifest&&e.push(i)}catch{}return e.sort((s,i)=>s.manifest.name.localeCompare(i.manifest.name))}getTemplate(t){const e=n.join(this.templatesDir(),`${t}.json`);if(!o(e))return null;try{return JSON.parse(c(e,"utf8"))}catch{return null}}saveTemplate(t){const e=new Date().toISOString(),s=t.id||`${Date.now().toString(36)}-${f(3).toString("hex")}`,i=this.getTemplate(s);i&&this.snapshotTemplate(n.join(this.templatesDir(),`${s}.json`),s);const r={id:s,manifest:{...t.manifest,schema:1},createdAt:i?.createdAt||e,updatedAt:e};return h(n.join(this.templatesDir(),`${s}.json`),JSON.stringify(r,null,2),{mode:384}),r}deleteTemplate(t){const e=n.join(this.templatesDir(),`${t}.json`);return o(e)?(this.snapshotTemplate(e,t),m(e),!0):!1}snapshotTemplate(t,e){try{const s=n.join(this.templatesDir(),".history",e);a(s,{recursive:!0,mode:448});const i=new Date().toISOString().replace(/[:.]/g,"-");S(t,n.join(s,`${i}.json`));const r=u(s).sort();for(const l of r.slice(0,Math.max(0,r.length-10)))m(n.join(s,l),{force:!0})}catch{}}listTemplateHistory(t){const e=n.join(this.templatesDir(),".history",t);return o(e)?u(e).sort():[]}loadInstances(){if(o(this.instancesFile))try{const t=JSON.parse(c(this.instancesFile,"utf8"));for(const e of t)this.instances.set(e.id,e)}catch{}}persistInstances(){h(this.instancesFile,JSON.stringify([...this.instances.values()],null,2),{mode:384})}listInstances(){return[...this.instances.values()].sort((t,e)=>t.createdAt.localeCompare(e.createdAt))}getInstance(t){return this.instances.get(t)||null}saveInstance(t){t.updatedAt=new Date().toISOString(),this.instances.set(t.id,t),this.persistInstances()}deleteInstance(t){this.instances.delete(t),this.persistInstances(),m(this.instanceDir(t),{recursive:!0,force:!0})}instanceDir(t){return n.join(this.root,"instances",t)}agentDir(t){return n.join(this.instanceDir(t),"agent")}sessionsDir(t){return n.join(this.instanceDir(t),"sessions")}appendEvent(t,e){try{a(this.instanceDir(t),{recursive:!0,mode:448}),j(n.join(this.instanceDir(t),"events.jsonl"),`${JSON.stringify(e)}
2
+ `,{mode:384})}catch{}}readEvents(t,e=2e3){const s=n.join(this.instanceDir(t),"events.jsonl");if(!o(s))return[];const r=c(s,"utf8").split(`
3
+ `).filter(Boolean).slice(-e),l=[];for(const d of r)try{l.push(JSON.parse(d))}catch{}return l}newId(){return D()}}let p=null;function F(){return p||(p=new g),p}export{g as BotStore,F as getBotStore};
@@ -0,0 +1 @@
1
+ import{existsSync as l,mkdirSync as u,readFileSync as y,readdirSync as h,statSync as S,writeFileSync as d}from"node:fs";import n from"node:path";const b=512*1024;function m(e,t=""){if(!l(e))return[];const o=[];for(const r of h(e)){if(r.startsWith("."))continue;const s=n.join(e,r),a=t?`${t}/${r}`:r,c=S(s);c.isDirectory()?o.push(...m(s,a)):c.size<=b&&o.push(a)}return o}function x(e){const t=n.join(e.root,"library"),o={};for(const r of m(t))try{o[r]=y(n.join(t,r),"utf8")}catch{}return{schema:1,exportedAt:new Date().toISOString(),templates:e.listTemplates(),library:o}}function D(e,t,o={}){if(!t||t.schema!==1)throw new Error("unsupported bundle");const r=n.join(e.root,"library");let s=0,a=0;for(const[i,p]of Object.entries(t.library||{})){const f=n.join(r,i);if(l(f)&&!o.overwriteLibrary){a+=1;continue}u(n.dirname(f),{recursive:!0,mode:448}),d(f,p,{mode:384}),s+=1}let c=0;for(const i of t.templates||[])!i||!i.manifest||typeof i.manifest.name!="string"||(e.saveTemplate({id:i.id,manifest:i.manifest}),c+=1);return{templates:c,files:s,skipped:a}}export{x as exportBots,D as importBots};
@@ -1,4 +1,4 @@
1
- import{cssVarsStyle as c}from"../theme.js";import{newSessionModalCSS as f,newSessionModalHTML as b,newSessionModalScript as x,reducedMotion as g}from"../shared-layout.js";import{icon as a}from"../icons.js";function m(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function o(e="var(--panel-accent)"){return`box-shadow: 0 0 0 2px ${e}; outline: none;`}function w(e){const{theme:t,fsRoots:n,terminalCfg:i,scrollback:l,wsBase:p}=e,r=e.version?m(e.version):"",s=`
1
+ import{cssVarsStyle as c}from"../theme.js";import{newSessionModalCSS as b,newSessionModalHTML as f,newSessionModalScript as x,reducedMotion as g}from"../shared-layout.js";import{icon as a}from"../icons.js";function m(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function o(e="var(--panel-accent)"){return`box-shadow: 0 0 0 2px ${e}; outline: none;`}function w(e){const{theme:t,fsRoots:n,terminalCfg:i,scrollback:l,wsBase:p}=e,r=e.version?m(e.version):"",s=`
2
2
  *, *::before, *::after { box-sizing: border-box; }
3
3
  html, body {
4
4
  background: var(--page-bg); color: var(--page-fg);
@@ -111,6 +111,11 @@ import{cssVarsStyle as c}from"../theme.js";import{newSessionModalCSS as f,newSes
111
111
  }
112
112
  .session-item:hover .session-edit-btn { display: flex; align-items: center; }
113
113
  .session-edit-btn:hover { color: var(--panel-accent); background: color-mix(in srgb, var(--panel-accent) 8%, transparent); }
114
+ /* No hover on touch devices: keep the session menu (and "create bot here") reachable. */
115
+ @media (hover: none) {
116
+ .session-edit-btn { display: flex; align-items: center; opacity: 0.7; }
117
+ .session-item.active .session-edit-btn { opacity: 1; color: var(--panel-accent); }
118
+ }
114
119
  .session-edit-btn:focus-visible { ${o()} }
115
120
 
116
121
  .sidebar-section-label {
@@ -751,7 +756,7 @@ import{cssVarsStyle as c}from"../theme.js";import{newSessionModalCSS as f,newSes
751
756
  .file-roots-list li svg { width: 20px; height: 20px; flex-shrink: 0; fill: var(--panel-accent); }
752
757
 
753
758
  ${g()}
754
- ${f()}
759
+ ${b()}
755
760
  @media (max-width: 640px) {
756
761
  .app-layout { flex-direction: column; }
757
762
  .sidebar { flex: 0 0 auto; border-right: none; border-bottom: 1px solid var(--panel-border); transition: max-height 0.2s; }
@@ -945,7 +950,7 @@ import{cssVarsStyle as c}from"../theme.js";import{newSessionModalCSS as f,newSes
945
950
  })();
946
951
  </script>
947
952
 
948
- ${b()}
953
+ ${f()}
949
954
 
950
955
  <script>
951
956
  window.__TMUX_WEB_SHELL__ = ${d};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tmux-weblink",
3
- "version": "2.2.42",
3
+ "version": "2.2.44",
4
4
  "description": "Access your tmux sessions from the browser. A continuation of tmux-web and persalink.",
5
5
  "type": "module",
6
6
  "bin": {