tmux-weblink 2.2.41 → 2.2.42
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
|
|
2
|
-
`)}selectRows(t,
|
|
3
|
-
`)}getSelection(){return this.terminal.getSelection()}clearSelection(){this.terminal.clearSelection()}hasSelectionSupport(){return!0}};function
|
|
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
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:
|
|
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
|
|
6
6
|
`).join(`
|
|
7
7
|
`).split(`
|
|
8
|
-
`).join("\r")}async function zn(l){let c=Hn(l.clipboardData);if(c){l.preventDefault(),l.stopPropagation();let k=Date.now();if(k-We<50)return;We=k,await mt(c);return}let f=l.clipboardData?.getData("text/plain");if(!f)return;l.preventDefault(),l.stopPropagation();let v=Date.now();v-We<50||(We=v,n.pasteText(Ht(f)))}let ke=0;function Wn(l){l.preventDefault(),ke++,Pt(l.dataTransfer)&&e.classList.add("terminal-drag-over")}function _n(l){l.preventDefault(),l.dataTransfer&&(l.dataTransfer.dropEffect="copy")}function qn(l){l.preventDefault(),ke--,ke<=0&&(ke=0,e.classList.remove("terminal-drag-over"))}async function Un(l){l.preventDefault(),ke=0,e.classList.remove("terminal-drag-over");let c=Pt(l.dataTransfer);c&&await mt(c)}function Rt(l){!An||l.key!=="Escape"||be||l.defaultPrevented||l.repeat||l.metaKey||l.ctrlKey||l.altKey||n.isFocused()&&(l.preventDefault(),l.stopPropagation(),fe("\x1B"))}e.addEventListener("paste",zn),e.addEventListener("dragenter",Wn),e.addEventListener("dragover",_n),e.addEventListener("dragleave",qn),e.addEventListener("drop",Un),document.addEventListener("keydown",Rt,!0);function Yn(l){if(l.touches.length!==1){a=null;return}let c=l.touches[0];if(!c)return;_();let f=e.getBoundingClientRect(),v=c.clientX-f.left<f.width*.4?"tui":"history",k=c.clientY-f.top<f.height*.5;a={startX:c.clientX,startY:c.clientY,lastX:c.clientX,lastY:c.clientY,lastT:performance.now(),velocity:0,scrolling:!1,zone:v,tuiUp:k,sent:!1},l.stopPropagation()}function Jn(l){if(!a||l.touches.length!==1)return;let c=l.touches[0];if(!c)return;let f=c.clientY-a.startY,v=c.clientX-a.startX;if(!a.scrolling){if(Math.abs(f)<8||Math.abs(f)<Math.abs(v))return;a.scrolling=!0,oe=Date.now()+500}l.preventDefault(),l.stopPropagation();let k=performance.now(),V=c.clientY-a.lastY;if(a.zone==="tui"){a.sent||(a.sent=!0,fe(a.tuiUp?"\x1B[5~":"\x1B[6~"),j(a.tuiUp)),a.lastX=c.clientX,a.lastY=c.clientY,a.lastT=k;return}let ne=k-a.lastT;ne>0&&(a.velocity=V/ne),Qn(-V),a.lastX=c.clientX,a.lastY=c.clientY,a.lastT=k}function Kn(l){if(!a)return;let c=a.scrolling,f=a.zone,v=a.tuiUp,k=a.velocity;if(a=null,l.stopPropagation(),f==="tui"){c||(fe(v?"\x1B[5~":"\x1B[6~"),j(v),oe=Date.now()+500,l.preventDefault());return}if(!c){n.focus();return}oe=Date.now()+500,l.preventDefault(),k&&ae(k)}function Vn(l){a=null,_(),l.stopPropagation()}function Xn(l){l.pointerType==="touch"&&Date.now()<oe&&(l.preventDefault(),l.stopPropagation())}function Qn(l){let c=n.cellHeight(),f=c>0?Math.round(l/c):l>0?1:-1;f===0&&(f=l>0?1:-1),n.scrollLines(f)}e.addEventListener("touchstart",Yn,{passive:!0,capture:!0}),e.addEventListener("touchmove",Jn,{passive:!1,capture:!0}),e.addEventListener("touchend",Kn,{passive:!1,capture:!0}),e.addEventListener("touchcancel",Vn,{passive:!0,capture:!0}),e.addEventListener("pointerup",Xn,!0);function jt(){W()}window.addEventListener("resize",jt),window.visualViewport?.addEventListener("resize",W),window.visualViewport?.addEventListener("scroll",W);let Ot=new ResizeObserver(()=>W());Ot.observe(e),document.fonts?.ready.then(()=>{W(),setTimeout(W,50),setTimeout(W,200)}),e.addEventListener("focusin",Fn,!0);async function Zn(){if(document.fonts?.ready)try{await Promise.race([document.fonts.ready,new Promise(l=>setTimeout(l,1e3))])}catch{}}return requestAnimationFrame(()=>{de()&&je(),(async()=>(await Zn(),de()&&re({type:"resize",cols:n.cols,rows:n.rows}),At(),W()))()}),{destroy(){if(x=!0,_(),he(!1),Ce&&clearTimeout(Ce),document.removeEventListener("mousemove",ft,!0),document.removeEventListener("mouseup",ht,!0),s){try{s.close(1e3,"session switch")}catch{}s=void 0}e.innerHTML="",e.classList.remove("terminal-pending"),window.removeEventListener("resize",jt),Ot.disconnect(),document.removeEventListener("keydown",Rt,!0)},focus(){n.focus()},sendInput(l){fe(l)},toggleCopyMode(){Ft()}}})()}var u={catalog:null,templates:[],bots:[],approvals:[],activeId:null,items:new Map,ws:null,pollTimer:0,renderQueued:!1};function _t(){try{return localStorage.getItem("tmux-web-token")||""}catch{return""}}async function $(e,t){let i=await fetch(e,{...t,headers:{"content-type":"application/json",Authorization:`Bearer ${_t()}`,...t?.headers||{}}}),n=await i.text(),s=n?JSON.parse(n):null;if(!i.ok)throw new Error(s&&s.error||`HTTP ${i.status}`);return s}function d(e,t,i){let n=document.createElement(e);return t&&(n.className=t),i!==void 0&&(n.textContent=i),n}function qt(e){return e==="running"?"var(--panel-success)":e==="waiting_approval"||e==="waiting_input"?"#e0a23c":e==="failed"?"var(--panel-danger, #e5534b)":e==="completed"?"var(--panel-accent)":"var(--panel-muted)"}function oi(){let e=d("div","bots-section");e.id="bots-section";let t=d("div","bots-head"),i=d("span","bots-title","Bots"),n=d("span","bots-badge");n.hidden=!0,i.appendChild(n);let s=d("span","bots-head-actions"),o=d("button","bots-icon-btn","\u2699");o.title="Bot templates",o.onclick=()=>void wt();let r=d("button","bots-icon-btn","+");r.title="New bot from template",r.onclick=()=>void vi(),s.append(o,r),t.append(i,s);let a=d("div","bots-list");a.id="bots-list",e.append(t,a);let p=document.querySelector(".sidebar"),m=document.querySelector(".sidebar-footer");return p&&p.insertBefore(e,m||null),{list:a,badge:n}}var Le=null,qe=null;function Ue(){if(!Le)return;Le.textContent="";let e=new Map;for(let n of u.bots){if(n.parentBotId)continue;let s=n.projectPath;e.has(s)||e.set(s,[]),e.get(s).push(n)}e.size===0&&Le.appendChild(d("div","bots-empty","No bots yet"));for(let[n,s]of e){let o=d("div","bots-group"),r=d("div","bots-group-label",n.replace(/^.*\//,"")||n);r.title=n,o.appendChild(r);for(let a of s){o.appendChild(Ut(a));for(let p of u.bots.filter(m=>m.parentBotId===a.id)){let m=Ut(p);m.classList.add("bots-row-child"),o.appendChild(m)}}Le.appendChild(o)}let t=u.approvals.length;qe&&(qe.hidden=t===0,qe.textContent=String(t));let i=document.getElementById("bv-inbox-count");i&&(i.textContent=t?`(${t})`:"")}function Ut(e){let t=d("div","bots-row");t.dataset.botId=e.id,e.id===u.activeId&&t.classList.add("active");let i=d("span","bots-dot");i.style.background=qt(e.status);let n=d("span","bots-name",e.title),s=d("span","bots-meta",e.status.replace(/_/g," "));return t.append(i,n,s),t.onclick=()=>void Kt(e.id),t}function li(){let e=d("div","bots-view");e.id="bots-view",e.hidden=!0;let t=d("div","bots-view-head"),i=d("div","bv-title"),n=d("span","bots-dot");n.id="bv-dot";let s=d("span","bv-title-text");s.id="bv-title";let o=d("span","bv-status");o.id="bv-status",i.append(n,s,o);let r=d("div","bv-actions"),a=d("button","btn","Needs you "),p=d("span");p.id="bv-inbox-count",a.appendChild(p),a.onclick=()=>void en();let m=d("button","btn","Resume");m.onclick=()=>void Jt(D=>$(`/api/bots/${D}/resume`,{method:"POST"}).then(()=>X(!0)));let b=d("button","btn danger","Stop");b.onclick=()=>void Jt(D=>$(`/api/bots/${D}/stop`,{method:"POST"}).then(()=>X(!0)));let E=d("button","btn","Delete");E.onclick=()=>{u.activeId&&confirm("Delete this bot and its session?")&&$(`/api/bots/${u.activeId}`,{method:"DELETE"}).then(()=>{gt(),X(!0)})};let M=d("button","btn","\u2715");M.onclick=()=>gt(),r.append(a,m,b,E,M),t.append(i,r);let T=d("div","bots-messages");T.id="bots-messages";let w=d("div","bots-composer"),S=d("textarea");S.id="bots-input",S.rows=1,S.placeholder="Message the bot\u2026 (Enter to send, Shift+Enter for newline)",S.onkeydown=D=>{D.key==="Enter"&&!D.shiftKey&&(D.preventDefault(),Yt())};let j=d("button","btn primary","Send");j.onclick=()=>void Yt(),w.append(S,j),e.append(t,T,w),document.querySelector(".main-area")?.appendChild(e),document.getElementById("bots-modal")||fi()}async function Yt(){let e=document.getElementById("bots-input");if(!e||!u.activeId||!e.value.trim())return;let t=e.value;e.value="";try{await $(`/api/bots/${u.activeId}/input`,{method:"POST",body:JSON.stringify({text:t})})}catch(i){Se({kind:"notice",level:"error",text:i instanceof Error?i.message:String(i)})}}function Jt(e){u.activeId&&e(u.activeId).catch(t=>Se({kind:"notice",level:"error",text:t instanceof Error?t.message:String(t)}))}function gt(){u.activeId=null;let e=document.getElementById("bots-view");e&&(e.hidden=!0);try{u.ws?.close()}catch{}u.ws=null,Ue();let t=document.getElementById("main-placeholder");t&&(t.style.display="")}async function Kt(e){u.activeId=e,u.items.set(e,[]);let t=document.getElementById("bots-view");t&&(t.hidden=!1);let i=document.getElementById("main-placeholder");i&&(i.style.display="none");let n=document.getElementById("terminal-container");n&&(n.style.display="none");let s=document.getElementById("file-editor");s&&(s.style.display="none"),Ue(),yt();try{u.ws?.close()}catch{}let o=location.protocol==="https:"?"wss:":"ws:",r=new WebSocket(`${o}//${location.host}/ws/bots/${encodeURIComponent(e)}?token=${encodeURIComponent(_t())}`);u.ws=r,r.onmessage=a=>{try{Qt(JSON.parse(String(a.data)))}catch{}},r.onclose=()=>{u.activeId===e&&setTimeout(()=>{u.activeId===e&&X(!0)},1500)},await X(!0)}function Vt(){return u.bots.find(e=>e.id===u.activeId)||null}function Xt(){let e=Vt();if(!e)return;let t=document.getElementById("bv-title"),i=document.getElementById("bv-status"),n=document.getElementById("bv-dot");t&&(t.textContent=e.title),i&&(i.textContent=`${e.status.replace(/_/g," ")} \xB7 ${e.templateId} \xB7 ${e.projectPath}`),n&&(n.style.background=qt(e.status))}function Se(e,t=u.activeId){if(!t)return;let i=u.items.get(t)||[];i.push(e),u.items.set(t,i),t===u.activeId&&ce()}function ce(){u.renderQueued||(u.renderQueued=!0,requestAnimationFrame(()=>{u.renderQueued=!1,yt()}))}function yt(){let e=document.getElementById("bots-messages");if(!e||!u.activeId)return;let t=u.items.get(u.activeId)||[];e.textContent="";let i=null;for(let n of t)if(n.kind==="user"){let s=d("div","bv-msg bv-user");s.textContent=n.text,e.appendChild(s),i=null}else if(n.kind==="assistant"){let s=d("div","bv-msg bv-assistant");if(n.thinking){let r=d("details","bv-thinking");r.appendChild(d("summary",void 0,"thinking")),r.appendChild(d("div",void 0,n.thinking)),s.appendChild(r)}let o=d("div","bv-text");o.textContent=n.text,s.appendChild(o),e.appendChild(s),i=o}else if(n.kind==="tool")e.appendChild(ri(n)),i=null;else if(n.kind==="approval")e.appendChild(di(n)),i=null;else if(n.kind==="notice"){let s=d("div",`bv-notice bv-notice-${n.level}`,n.text);e.appendChild(s)}i&&(i.scrollTop=i.scrollHeight),e.scrollTop=e.scrollHeight}function ri(e){let t=d("details","bv-tool");t.open=e.phase!=="end"||!!e.isError;let i=d("summary"),n=d("span","bv-tool-name",e.name);if(i.appendChild(n),e.phase!=="end"&&i.appendChild(d("span","bv-tool-phase",e.phase)),e.isError&&i.appendChild(d("span","bv-tool-error","error")),typeof e.durationMs=="number"&&i.appendChild(d("span","bv-tool-meta",`${Math.round(e.durationMs)}ms`)),t.appendChild(i),e.args!==void 0){let s=d("pre","bv-pre");s.textContent=typeof e.args=="string"?e.args:JSON.stringify(e.args,null,2),t.appendChild(s)}if(e.output){let s=d("pre","bv-pre bv-output");s.textContent=e.output,t.appendChild(s)}return t}function di(e){let t=d("div","bv-approval"),i=e.approval;if(t.appendChild(d("div","bv-approval-title",i.title)),i.message&&t.appendChild(d("pre","bv-pre",i.message)),e.decided)return t.appendChild(d("div","bv-approval-decided",e.decided==="allowed"?"Allowed":"Denied")),t;let n=d("input","bv-reason");n.placeholder="reason (optional)";let s=d("div","bv-approval-actions"),o=d("button","btn primary","Allow"),r=d("button","btn danger","Deny"),a=async p=>{try{await $(`/api/bots/${i.botId}/approve`,{method:"POST",body:JSON.stringify({requestId:i.id,allow:p,reason:n.value||void 0})}),e.decided=p?"allowed":"denied",ce(),X(!0)}catch(m){Se({kind:"notice",level:"error",text:m instanceof Error?m.message:String(m)})}};return o.onclick=()=>void a(!0),r.onclick=()=>void a(!1),s.append(n,o,r),t.appendChild(s),t}function Qt(e){let t=String(e.type||""),i=u.activeId;if(!i)return;let n=u.items.get(i)||[];if(t==="snapshot")u.items.set(i,[]);else if(t==="user")Se({kind:"user",text:String(e.text||"")});else if(t==="status"){let s=Vt();s&&(s.status=String(e.status||s.status)),Xt(),ui()}else if(t==="message"){let s=e.message;if(!s||String(s.role||"")!=="assistant")return;let o=ci(s),r=pi(s),a=n[n.length-1];a&&a.kind==="assistant"?(a.text=o||a.text,a.thinking=r||a.thinking):n.push({kind:"assistant",text:o,thinking:r}),u.items.set(i,n),ce()}else if(t==="delta"){let s=String(e.kind||""),o=String(e.delta||""),r=n[n.length-1];(!r||r.kind!=="assistant")&&(n.push({kind:"assistant",text:"",thinking:""}),r=n[n.length-1]),r.kind==="assistant"&&(s==="text"?r.text+=o:s==="thinking"&&(r.thinking+=o)),u.items.set(i,n),ce()}else if(t==="tool"){let s=String(e.callId||""),o=n.find(a=>a.kind==="tool"&&a.callId===s),r=String(e.phase||"start");o?(o.phase=r,r==="update"&&e.output&&(o.output=String(e.output)),r==="end"&&(e.output&&(o.output=String(e.output)),o.isError=e.isError===!0,typeof e.durationMs=="number"&&(o.durationMs=e.durationMs))):n.push({kind:"tool",callId:s,name:String(e.name||"tool"),args:e.args,output:e.output?String(e.output):void 0,isError:e.isError===!0,durationMs:typeof e.durationMs=="number"?e.durationMs:void 0,phase:r}),u.items.set(i,n),ce()}else if(t==="approval"){let s=e.approval;if(!s)return;let o=n;for(let r=o.length-1;r>=0;r--){let a=o[r];if(a.kind==="approval"&&a.approval.id===s.id){a.approval=s,s.state!=="pending"&&(a.decided=s.state==="allowed"?"allowed":"denied"),u.items.set(i,o),ce();return}}o.push({kind:"approval",approval:s}),u.items.set(i,o),ce()}else t==="notice"&&Se({kind:"notice",level:String(e.level||"info"),text:String(e.text||"")})}function ci(e){let t=e.content;return Array.isArray(t)?t.map(i=>i&&typeof i=="object"&&i.type==="text"?String(i.text||""):"").join(""):String(e.text||"")}function pi(e){let t=e.content;return Array.isArray(t)?t.map(i=>i&&typeof i=="object"&&i.type==="thinking"?String(i.thinking||""):"").join(""):""}async function X(e=!1){try{let[t,i]=await Promise.all([$("/api/bots"),$("/api/bots/approvals")]);if(u.bots=t,u.approvals=i,Ue(),Xt(),e&&u.activeId){let n=await $(`/api/bots/${u.activeId}/events?limit=300`);mi(n)}}catch{}}async function ui(){try{u.bots=await $("/api/bots"),Ue()}catch{}}function mi(e){if(u.activeId){u.items.set(u.activeId,[]);for(let t of e)Qt(t);yt()}}function fi(){let e=d("div","bots-modal");e.id="bots-modal",e.hidden=!0;let t=d("div","bots-modal-card"),i=d("div","bots-modal-head"),n=d("span");n.id="bots-modal-title";let s=d("button","btn","\u2715");s.onclick=()=>Ye(),i.append(n,s);let o=d("div","bots-modal-body");o.id="bots-modal-body",t.append(i,o),e.appendChild(t),e.onclick=r=>{r.target===e&&Ye()},document.body.appendChild(e)}function bt(e){let t=document.getElementById("bots-modal"),i=document.getElementById("bots-modal-title"),n=document.getElementById("bots-modal-body");if(!t||!n)throw new Error("modal missing");return i&&(i.textContent=e),n.textContent="",t.hidden=!1,n}function Ye(){let e=document.getElementById("bots-modal");e&&(e.hidden=!0)}async function hi(){return u.catalog||(u.catalog=await $("/api/bots/catalog")),u.catalog}async function Zt(){return u.templates=await $("/api/bots/templates"),u.templates}async function wt(){let e=bt("Bot templates"),[t,i]=await Promise.all([hi(),Zt()]),n=d("div","bv-template-list");for(let o of i){let r=d("div","bv-template-row");r.appendChild(d("span","bv-template-name",o.manifest.name)),r.appendChild(d("span","bv-template-desc",o.manifest.description||""));let a=d("button","btn","Edit");a.onclick=()=>Gt(e,t,o);let p=d("button","btn danger","Delete");p.onclick=()=>{confirm(`Delete template ${o.manifest.name}?`)&&$(`/api/bots/templates/${o.id}`,{method:"DELETE"}).then(()=>wt())};let m=d("span","bv-template-actions");m.append(a,p),r.appendChild(m),n.appendChild(r)}i.length===0&&n.appendChild(d("div","bots-empty","No templates yet")),e.appendChild(n);let s=d("button","btn primary","New template");s.onclick=()=>Gt(e,t,null),e.appendChild(s)}function Et(e,t,i){let n=d("div","bv-field");n.appendChild(d("label","bv-label",e));let s=d("div","bv-check-grid"),o=[];for(let r of t){let a=d("label","bv-check"),p=document.createElement("input");p.type="checkbox",p.checked=i.includes(r.id),a.append(p,d("span",void 0,r.label)),r.hint&&(a.title=r.hint),s.appendChild(a),o.push({id:r.id,input:p})}return n.appendChild(s),{element:n,get:()=>o.filter(r=>r.input.checked).map(r=>r.id)}}function Gt(e,t,i){e.textContent="";let n=i?JSON.parse(JSON.stringify(i.manifest)):{name:"new-bot",description:""},s=d("input","bv-input");s.value=n.name,s.placeholder="Template name";let o=d("input","bv-input");o.value=n.description||"",o.placeholder="One line description";let r=d("textarea","bv-textarea");r.rows=6,r.value=n.system||"",r.placeholder="System prompt for this bot (written to SYSTEM.md)";let a=Et("Skills",t.skills.map(h=>({id:h.id,label:h.name,hint:h.description})),n.skills||[]),p=Et("Extensions (Pi builtins + library)",t.extensions.map(h=>({id:h.id,label:`${h.name}${h.kind==="builtin"?" (builtin)":""}`,hint:h.description})),(n.extensions||[]).map(h=>h.replace(/^.*\//,"").replace(/\.(js|ts)$/,""))),m=Et("Prompt templates",t.prompts.map(h=>({id:h.id,label:h.name})),n.prompts||[]),b=d("select","bv-input");b.appendChild(new Option("none",""));for(let h of t.mcp)b.appendChild(new Option(h.name,h.id));n.mcp&&(b.value=t.mcp.find(h=>JSON.stringify(h.servers)===JSON.stringify(n.mcp?.mcpServers))?.id||"");let E=d("div","bv-field");E.appendChild(d("label","bv-label","Tools (allow list; deny always blocks)"));let M=d("div","bv-check-grid"),T=[];for(let h of t.tools){let z=d("label","bv-check"),x=document.createElement("input");x.type="checkbox",x.checked=(n.tools?.allow||[]).includes(h.name)||!n.tools?.allow?.length&&["read","grep","find","ls","edit","write","bash"].includes(h.name),z.append(x,d("span",void 0,h.name)),M.appendChild(z),T.push({name:h.name,input:x})}E.appendChild(M);let w=d("input","bv-input");w.value=(n.tools?.deny||[]).join(", "),w.placeholder="Always deny (comma separated), e.g. bash, write";let S=d("textarea","bv-textarea");S.rows=2,S.value=(n.packages||[]).join(`
|
|
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
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}`));
|
|
11
|
-
${
|
|
12
|
-
`),x=t.mcp.find(B=>B.id===
|
|
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:
|
|
14
|
-
<span>${
|
|
15
|
-
<button class="session-edit-btn" data-session="${
|
|
16
|
-
<span>${
|
|
17
|
-
<button class="session-edit-btn" data-session="${
|
|
18
|
-
`,t.addEventListener("click",
|
|
19
|
-
<span>${
|
|
20
|
-
<button class="session-edit-btn" data-session="${
|
|
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&>()},!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">📁</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>
|
|
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>
|
|
16
|
+
<span>${w(e.name)}</span>
|
|
17
|
+
<button class="session-edit-btn" data-session="${w(e.name)}" title="Edit session"><svg viewBox="0 0 24 24" fill="currentColor" width="14" height="14"><path d="M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM20.71 7.04a1 1 0 000-1.41l-2.34-2.34a1 1 0 00-1.41 0l-1.83 1.83 3.75 3.75 1.83-1.83z"/></svg></button>
|
|
18
|
+
`,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,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}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">
|
|
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
|
-
${
|
|
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
|
|
24
|
-
${
|
|
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
25
|
<span class="file-add">${s>0?"+"+s:""}</span>
|
|
26
|
-
<span class="file-del">${
|
|
27
|
-
</div>`}t+='<div class="git-popover-footer"><button id="git-popover-browse">Browse repository \u2192</button></div>',
|
|
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?`
|
|
28
28
|
`:"")+t).split(`
|
|
29
|
-
`),
|
|
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">
|
|
30
30
|
<button class="diff-back">\u2190 Back</button>
|
|
31
|
-
<span class="diff-filename">${
|
|
31
|
+
<span class="diff-filename">${w(e)}</span>
|
|
32
32
|
<span class="diff-loading">Loading\u2026</span>
|
|
33
|
-
</div></div>`,
|
|
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">
|
|
34
34
|
<button class="diff-back">\u2190 Back</button>
|
|
35
|
-
<span class="diff-filename">${
|
|
36
|
-
</div><div class="diff-empty">Error loading diff: ${
|
|
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">
|
|
37
37
|
<button class="diff-back">\u2190 Back</button>
|
|
38
|
-
<span class="diff-filename">${
|
|
39
|
-
</div><div class="diff-empty">No diff content available</div></div>`;return}let{html:
|
|
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">
|
|
40
40
|
<button class="diff-back">\u2190 Back</button>
|
|
41
|
-
<span class="diff-filename">${
|
|
41
|
+
<span class="diff-filename">${w(e)}</span>
|
|
42
42
|
<span class="diff-filesize">${s} lines</span>
|
|
43
|
-
</div><div class="diff-content">${
|
|
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">
|
|
44
44
|
<label>Rename session</label>
|
|
45
45
|
<input type="text" id="sp-name" />
|
|
46
46
|
</div>
|
|
@@ -50,5 +50,5 @@ ${n.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
|
|
54
|
-
`).length;Q.rows=Math.min(e,4)}),Q.addEventListener("keydown",e=>{e.key==="Enter"&&!e.shiftKey&&(e.preventDefault(),
|
|
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+'">×</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();
|